commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
0155a7e2babecf67c8d0732c8559342d5e1d5fae
TableGen/RegisterInfoEmitter.cpp
TableGen/RegisterInfoEmitter.cpp
//===- RegisterInfoEmitter.cpp - Generate a Register File Desc. -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend is responsible for emitting a description of a target // register file for a code generator. It uses instances of the Register, // RegisterAliases, and RegisterClass classes to gather this information. // //===----------------------------------------------------------------------===// #include "RegisterInfoEmitter.h" #include "CodeGenTarget.h" #include "CodeGenRegisters.h" #include "Record.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/STLExtras.h" #include <set> using namespace llvm; // runEnums - Print out enum values for all of the registers. void RegisterInfoEmitter::runEnums(std::ostream &OS) { CodeGenTarget Target; const std::vector<CodeGenRegister> &Registers = Target.getRegisters(); std::string Namespace = Registers[0].TheDef->getValueAsString("Namespace"); EmitSourceFileHeader("Target Register Enum Values", OS); OS << "namespace llvm {\n\n"; if (!Namespace.empty()) OS << "namespace " << Namespace << " {\n"; OS << " enum {\n NoRegister,\n"; for (unsigned i = 0, e = Registers.size(); i != e; ++i) OS << " " << Registers[i].getName() << ", \t// " << i+1 << "\n"; OS << " };\n"; if (!Namespace.empty()) OS << "}\n"; OS << "} // End llvm namespace \n"; } void RegisterInfoEmitter::runHeader(std::ostream &OS) { EmitSourceFileHeader("Register Information Header Fragment", OS); CodeGenTarget Target; const std::string &TargetName = Target.getName(); std::string ClassName = TargetName + "GenRegisterInfo"; OS << "#include \"llvm/Target/MRegisterInfo.h\"\n"; OS << "#include <string>\n\n"; OS << "namespace llvm {\n\n"; OS << "struct " << ClassName << " : public MRegisterInfo {\n" << " " << ClassName << "(int CallFrameSetupOpcode = -1, int CallFrameDestroyOpcode = -1);\n" << " const unsigned* getCalleeSaveRegs() const;\n" << "const TargetRegisterClass* const *getCalleeSaveRegClasses() const;\n" << "};\n\n"; const std::vector<CodeGenRegisterClass> &RegisterClasses = Target.getRegisterClasses(); if (!RegisterClasses.empty()) { OS << "namespace " << RegisterClasses[0].Namespace << " { // Register classes\n"; for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) { const std::string &Name = RegisterClasses[i].getName(); // Output the register class definition. OS << " struct " << Name << "Class : public TargetRegisterClass {\n" << " " << Name << "Class();\n" << RegisterClasses[i].MethodProtos << " };\n"; // Output the extern for the instance. OS << " extern " << Name << "Class\t" << Name << "RegClass;\n"; // Output the extern for the pointer to the instance (should remove). OS << " static TargetRegisterClass * const "<< Name <<"RegisterClass = &" << Name << "RegClass;\n"; } OS << "} // end of namespace " << TargetName << "\n\n"; } OS << "} // End llvm namespace \n"; } // RegisterInfoEmitter::run - Main register file description emitter. // void RegisterInfoEmitter::run(std::ostream &OS) { CodeGenTarget Target; EmitSourceFileHeader("Register Information Source Fragment", OS); OS << "namespace llvm {\n\n"; // Start out by emitting each of the register classes... to do this, we build // a set of registers which belong to a register class, this is to ensure that // each register is only in a single register class. // const std::vector<CodeGenRegisterClass> &RegisterClasses = Target.getRegisterClasses(); // Loop over all of the register classes... emitting each one. OS << "namespace { // Register classes...\n"; // RegClassesBelongedTo - Keep track of which register classes each reg // belongs to. std::multimap<Record*, const CodeGenRegisterClass*> RegClassesBelongedTo; // Emit the register enum value arrays for each RegisterClass for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) { const CodeGenRegisterClass &RC = RegisterClasses[rc]; // Give the register class a legal C name if it's anonymous. std::string Name = RC.TheDef->getName(); // Emit the register list now. OS << " // " << Name << " Register Class...\n const unsigned " << Name << "[] = {\n "; for (unsigned i = 0, e = RC.Elements.size(); i != e; ++i) { Record *Reg = RC.Elements[i]; OS << getQualifiedName(Reg) << ", "; // Keep track of which regclasses this register is in. RegClassesBelongedTo.insert(std::make_pair(Reg, &RC)); } OS << "\n };\n\n"; } // Emit the ValueType arrays for each RegisterClass for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) { const CodeGenRegisterClass &RC = RegisterClasses[rc]; // Give the register class a legal C name if it's anonymous. std::string Name = RC.TheDef->getName() + "VTs"; // Emit the register list now. OS << " // " << Name << " Register Class Value Types...\n const MVT::ValueType " << Name << "[] = {\n "; for (unsigned i = 0, e = RC.VTs.size(); i != e; ++i) OS << "MVT::" << RC.VTs[i] << ", "; OS << "MVT::Other\n };\n\n"; } OS << "} // end anonymous namespace\n\n"; // Now that all of the structs have been emitted, emit the instances. if (!RegisterClasses.empty()) { OS << "namespace " << RegisterClasses[0].Namespace << " { // Register class instances\n"; for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) OS << " " << RegisterClasses[i].getName() << "Class\t" << RegisterClasses[i].getName() << "RegClass;\n"; for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) { const CodeGenRegisterClass &RC = RegisterClasses[i]; OS << RC.MethodBodies << "\n"; OS << RC.getName() << "Class::" << RC.getName() << "Class() : TargetRegisterClass(" << RC.getName() + "VTs" << ", " << RC.SpillSize/8 << ", " << RC.SpillAlignment/8 << ", " << RC.getName() << ", " << RC.getName() << " + " << RC.Elements.size() << ") {}\n"; } OS << "}\n"; } OS << "\nnamespace {\n"; OS << " const TargetRegisterClass* const RegisterClasses[] = {\n"; for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) OS << " &" << getQualifiedName(RegisterClasses[i].TheDef) << "RegClass,\n"; OS << " };\n"; // Emit register class aliases... std::map<Record*, std::set<Record*> > RegisterAliases; const std::vector<CodeGenRegister> &Regs = Target.getRegisters(); for (unsigned i = 0, e = Regs.size(); i != e; ++i) { Record *R = Regs[i].TheDef; std::vector<Record*> LI = Regs[i].TheDef->getValueAsListOfDefs("Aliases"); // Add information that R aliases all of the elements in the list... and // that everything in the list aliases R. for (unsigned j = 0, e = LI.size(); j != e; ++j) { Record *Reg = LI[j]; if (RegisterAliases[R].count(Reg)) std::cerr << "Warning: register alias between " << getQualifiedName(R) << " and " << getQualifiedName(Reg) << " specified multiple times!\n"; RegisterAliases[R].insert(Reg); if (RegisterAliases[Reg].count(R)) std::cerr << "Warning: register alias between " << getQualifiedName(R) << " and " << getQualifiedName(Reg) << " specified multiple times!\n"; RegisterAliases[Reg].insert(R); } } if (!RegisterAliases.empty()) OS << "\n\n // Register Alias Sets...\n"; // Emit the empty alias list OS << " const unsigned Empty_AliasSet[] = { 0 };\n"; // Loop over all of the registers which have aliases, emitting the alias list // to memory. for (std::map<Record*, std::set<Record*> >::iterator I = RegisterAliases.begin(), E = RegisterAliases.end(); I != E; ++I) { OS << " const unsigned " << I->first->getName() << "_AliasSet[] = { "; for (std::set<Record*>::iterator ASI = I->second.begin(), E = I->second.end(); ASI != E; ++ASI) OS << getQualifiedName(*ASI) << ", "; OS << "0 };\n"; } OS<<"\n const TargetRegisterDesc RegisterDescriptors[] = { // Descriptors\n"; OS << " { \"NOREG\",\t0 },\n"; // Now that register alias sets have been emitted, emit the register // descriptors now. const std::vector<CodeGenRegister> &Registers = Target.getRegisters(); for (unsigned i = 0, e = Registers.size(); i != e; ++i) { const CodeGenRegister &Reg = Registers[i]; OS << " { \""; if (!Reg.TheDef->getValueAsString("Name").empty()) OS << Reg.TheDef->getValueAsString("Name"); else OS << Reg.getName(); OS << "\",\t"; if (RegisterAliases.count(Reg.TheDef)) OS << Reg.getName() << "_AliasSet },\n"; else OS << "Empty_AliasSet },\n"; } OS << " };\n"; // End of register descriptors... OS << "}\n\n"; // End of anonymous namespace... std::string ClassName = Target.getName() + "GenRegisterInfo"; // Emit the constructor of the class... OS << ClassName << "::" << ClassName << "(int CallFrameSetupOpcode, int CallFrameDestroyOpcode)\n" << " : MRegisterInfo(RegisterDescriptors, " << Registers.size()+1 << ", RegisterClasses, RegisterClasses+" << RegisterClasses.size() <<",\n " << " CallFrameSetupOpcode, CallFrameDestroyOpcode) {}\n\n"; // Emit the getCalleeSaveRegs method. OS << "const unsigned* " << ClassName << "::getCalleeSaveRegs() const {\n" << " static const unsigned CalleeSaveRegs[] = {\n "; const std::vector<Record*> &CSR = Target.getCalleeSavedRegisters(); for (unsigned i = 0, e = CSR.size(); i != e; ++i) OS << getQualifiedName(CSR[i]) << ", "; OS << " 0\n };\n return CalleeSaveRegs;\n}\n\n"; // Emit information about the callee saved register classes. OS << "const TargetRegisterClass* const*\n" << ClassName << "::getCalleeSaveRegClasses() const {\n" << " static const TargetRegisterClass * const " << "CalleeSaveRegClasses[] = {\n "; for (unsigned i = 0, e = CSR.size(); i != e; ++i) { Record *R = CSR[i]; std::multimap<Record*, const CodeGenRegisterClass*>::iterator I, E; tie(I, E) = RegClassesBelongedTo.equal_range(R); if (I == E) throw "Callee saved register '" + R->getName() + "' must belong to a register class for spilling.\n"; const CodeGenRegisterClass *RC = (I++)->second; for (; I != E; ++I) if (RC->SpillSize < I->second->SpillSize) RC = I->second; OS << "&" << getQualifiedName(RC->TheDef) << "RegClass, "; } OS << " 0\n };\n return CalleeSaveRegClasses;\n}\n\n"; OS << "} // End llvm namespace \n"; }
//===- RegisterInfoEmitter.cpp - Generate a Register File Desc. -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This tablegen backend is responsible for emitting a description of a target // register file for a code generator. It uses instances of the Register, // RegisterAliases, and RegisterClass classes to gather this information. // //===----------------------------------------------------------------------===// #include "RegisterInfoEmitter.h" #include "CodeGenTarget.h" #include "CodeGenRegisters.h" #include "Record.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/STLExtras.h" #include <set> using namespace llvm; // runEnums - Print out enum values for all of the registers. void RegisterInfoEmitter::runEnums(std::ostream &OS) { CodeGenTarget Target; const std::vector<CodeGenRegister> &Registers = Target.getRegisters(); std::string Namespace = Registers[0].TheDef->getValueAsString("Namespace"); EmitSourceFileHeader("Target Register Enum Values", OS); OS << "namespace llvm {\n\n"; if (!Namespace.empty()) OS << "namespace " << Namespace << " {\n"; OS << " enum {\n NoRegister,\n"; for (unsigned i = 0, e = Registers.size(); i != e; ++i) OS << " " << Registers[i].getName() << ", \t// " << i+1 << "\n"; OS << " };\n"; if (!Namespace.empty()) OS << "}\n"; OS << "} // End llvm namespace \n"; } void RegisterInfoEmitter::runHeader(std::ostream &OS) { EmitSourceFileHeader("Register Information Header Fragment", OS); CodeGenTarget Target; const std::string &TargetName = Target.getName(); std::string ClassName = TargetName + "GenRegisterInfo"; OS << "#include \"llvm/Target/MRegisterInfo.h\"\n"; OS << "#include <string>\n\n"; OS << "namespace llvm {\n\n"; OS << "struct " << ClassName << " : public MRegisterInfo {\n" << " " << ClassName << "(int CallFrameSetupOpcode = -1, int CallFrameDestroyOpcode = -1);\n" << " const unsigned* getCalleeSaveRegs() const;\n" << " const TargetRegisterClass* const *getCalleeSaveRegClasses() const;\n" << " int getDwarfRegNum(unsigned RegNum) const;\n" << "};\n\n"; const std::vector<CodeGenRegisterClass> &RegisterClasses = Target.getRegisterClasses(); if (!RegisterClasses.empty()) { OS << "namespace " << RegisterClasses[0].Namespace << " { // Register classes\n"; for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) { const std::string &Name = RegisterClasses[i].getName(); // Output the register class definition. OS << " struct " << Name << "Class : public TargetRegisterClass {\n" << " " << Name << "Class();\n" << RegisterClasses[i].MethodProtos << " };\n"; // Output the extern for the instance. OS << " extern " << Name << "Class\t" << Name << "RegClass;\n"; // Output the extern for the pointer to the instance (should remove). OS << " static TargetRegisterClass * const "<< Name <<"RegisterClass = &" << Name << "RegClass;\n"; } OS << "} // end of namespace " << TargetName << "\n\n"; } OS << "} // End llvm namespace \n"; } // RegisterInfoEmitter::run - Main register file description emitter. // void RegisterInfoEmitter::run(std::ostream &OS) { CodeGenTarget Target; EmitSourceFileHeader("Register Information Source Fragment", OS); OS << "namespace llvm {\n\n"; // Start out by emitting each of the register classes... to do this, we build // a set of registers which belong to a register class, this is to ensure that // each register is only in a single register class. // const std::vector<CodeGenRegisterClass> &RegisterClasses = Target.getRegisterClasses(); // Loop over all of the register classes... emitting each one. OS << "namespace { // Register classes...\n"; // RegClassesBelongedTo - Keep track of which register classes each reg // belongs to. std::multimap<Record*, const CodeGenRegisterClass*> RegClassesBelongedTo; // Emit the register enum value arrays for each RegisterClass for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) { const CodeGenRegisterClass &RC = RegisterClasses[rc]; // Give the register class a legal C name if it's anonymous. std::string Name = RC.TheDef->getName(); // Emit the register list now. OS << " // " << Name << " Register Class...\n const unsigned " << Name << "[] = {\n "; for (unsigned i = 0, e = RC.Elements.size(); i != e; ++i) { Record *Reg = RC.Elements[i]; OS << getQualifiedName(Reg) << ", "; // Keep track of which regclasses this register is in. RegClassesBelongedTo.insert(std::make_pair(Reg, &RC)); } OS << "\n };\n\n"; } // Emit the ValueType arrays for each RegisterClass for (unsigned rc = 0, e = RegisterClasses.size(); rc != e; ++rc) { const CodeGenRegisterClass &RC = RegisterClasses[rc]; // Give the register class a legal C name if it's anonymous. std::string Name = RC.TheDef->getName() + "VTs"; // Emit the register list now. OS << " // " << Name << " Register Class Value Types...\n const MVT::ValueType " << Name << "[] = {\n "; for (unsigned i = 0, e = RC.VTs.size(); i != e; ++i) OS << "MVT::" << RC.VTs[i] << ", "; OS << "MVT::Other\n };\n\n"; } OS << "} // end anonymous namespace\n\n"; // Now that all of the structs have been emitted, emit the instances. if (!RegisterClasses.empty()) { OS << "namespace " << RegisterClasses[0].Namespace << " { // Register class instances\n"; for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) OS << " " << RegisterClasses[i].getName() << "Class\t" << RegisterClasses[i].getName() << "RegClass;\n"; for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) { const CodeGenRegisterClass &RC = RegisterClasses[i]; OS << RC.MethodBodies << "\n"; OS << RC.getName() << "Class::" << RC.getName() << "Class() : TargetRegisterClass(" << RC.getName() + "VTs" << ", " << RC.SpillSize/8 << ", " << RC.SpillAlignment/8 << ", " << RC.getName() << ", " << RC.getName() << " + " << RC.Elements.size() << ") {}\n"; } OS << "}\n"; } OS << "\nnamespace {\n"; OS << " const TargetRegisterClass* const RegisterClasses[] = {\n"; for (unsigned i = 0, e = RegisterClasses.size(); i != e; ++i) OS << " &" << getQualifiedName(RegisterClasses[i].TheDef) << "RegClass,\n"; OS << " };\n"; // Emit register class aliases... std::map<Record*, std::set<Record*> > RegisterAliases; const std::vector<CodeGenRegister> &Regs = Target.getRegisters(); for (unsigned i = 0, e = Regs.size(); i != e; ++i) { Record *R = Regs[i].TheDef; std::vector<Record*> LI = Regs[i].TheDef->getValueAsListOfDefs("Aliases"); // Add information that R aliases all of the elements in the list... and // that everything in the list aliases R. for (unsigned j = 0, e = LI.size(); j != e; ++j) { Record *Reg = LI[j]; if (RegisterAliases[R].count(Reg)) std::cerr << "Warning: register alias between " << getQualifiedName(R) << " and " << getQualifiedName(Reg) << " specified multiple times!\n"; RegisterAliases[R].insert(Reg); if (RegisterAliases[Reg].count(R)) std::cerr << "Warning: register alias between " << getQualifiedName(R) << " and " << getQualifiedName(Reg) << " specified multiple times!\n"; RegisterAliases[Reg].insert(R); } } if (!RegisterAliases.empty()) OS << "\n\n // Register Alias Sets...\n"; // Emit the empty alias list OS << " const unsigned Empty_AliasSet[] = { 0 };\n"; // Loop over all of the registers which have aliases, emitting the alias list // to memory. for (std::map<Record*, std::set<Record*> >::iterator I = RegisterAliases.begin(), E = RegisterAliases.end(); I != E; ++I) { OS << " const unsigned " << I->first->getName() << "_AliasSet[] = { "; for (std::set<Record*>::iterator ASI = I->second.begin(), E = I->second.end(); ASI != E; ++ASI) OS << getQualifiedName(*ASI) << ", "; OS << "0 };\n"; } OS<<"\n const TargetRegisterDesc RegisterDescriptors[] = { // Descriptors\n"; OS << " { \"NOREG\",\t0 },\n"; // Now that register alias sets have been emitted, emit the register // descriptors now. const std::vector<CodeGenRegister> &Registers = Target.getRegisters(); for (unsigned i = 0, e = Registers.size(); i != e; ++i) { const CodeGenRegister &Reg = Registers[i]; OS << " { \""; if (!Reg.TheDef->getValueAsString("Name").empty()) OS << Reg.TheDef->getValueAsString("Name"); else OS << Reg.getName(); OS << "\",\t"; if (RegisterAliases.count(Reg.TheDef)) OS << Reg.getName() << "_AliasSet },\n"; else OS << "Empty_AliasSet },\n"; } OS << " };\n"; // End of register descriptors... OS << "}\n\n"; // End of anonymous namespace... std::string ClassName = Target.getName() + "GenRegisterInfo"; // Emit the constructor of the class... OS << ClassName << "::" << ClassName << "(int CallFrameSetupOpcode, int CallFrameDestroyOpcode)\n" << " : MRegisterInfo(RegisterDescriptors, " << Registers.size()+1 << ", RegisterClasses, RegisterClasses+" << RegisterClasses.size() <<",\n " << " CallFrameSetupOpcode, CallFrameDestroyOpcode) {}\n\n"; // Emit the getCalleeSaveRegs method. OS << "const unsigned* " << ClassName << "::getCalleeSaveRegs() const {\n" << " static const unsigned CalleeSaveRegs[] = {\n "; const std::vector<Record*> &CSR = Target.getCalleeSavedRegisters(); for (unsigned i = 0, e = CSR.size(); i != e; ++i) OS << getQualifiedName(CSR[i]) << ", "; OS << " 0\n };\n return CalleeSaveRegs;\n}\n\n"; // Emit information about the callee saved register classes. OS << "const TargetRegisterClass* const*\n" << ClassName << "::getCalleeSaveRegClasses() const {\n" << " static const TargetRegisterClass * const " << "CalleeSaveRegClasses[] = {\n "; for (unsigned i = 0, e = CSR.size(); i != e; ++i) { Record *R = CSR[i]; std::multimap<Record*, const CodeGenRegisterClass*>::iterator I, E; tie(I, E) = RegClassesBelongedTo.equal_range(R); if (I == E) throw "Callee saved register '" + R->getName() + "' must belong to a register class for spilling.\n"; const CodeGenRegisterClass *RC = (I++)->second; for (; I != E; ++I) if (RC->SpillSize < I->second->SpillSize) RC = I->second; OS << "&" << getQualifiedName(RC->TheDef) << "RegClass, "; } OS << " 0\n };\n return CalleeSaveRegClasses;\n}\n\n"; // Emit information about the dwarf register numbers. OS << "int " << ClassName << "::getDwarfRegNum(unsigned RegNum) const {\n"; OS << " static const int DwarfRegNums[] = { -1, // NoRegister"; for (unsigned i = 0, e = Registers.size(); i != e; ++i) { if (!(i % 16)) OS << "\n "; const CodeGenRegister &Reg = Registers[i]; int DwarfRegNum = Reg.TheDef->getValueAsInt("DwarfNumber"); OS << DwarfRegNum; if ((i + 1) != e) OS << ", "; } OS << "\n };\n"; OS << " assert(RegNum < (sizeof(DwarfRegNums)/sizeof(int)) &&\n"; OS << " \"RegNum exceeds number of registers\");\n"; OS << " return DwarfRegNums[RegNum];\n"; OS << "}\n\n"; OS << "} // End llvm namespace \n"; }
Add dwarf register numbering to register data.
Add dwarf register numbering to register data. git-svn-id: a4a6f32337ebd29ad4763b423022f00f68d1c7b7@27081 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-3-clause
lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx,lodyagin/bare_cxx
e79ea48f10ec6a82b84f1494c80a95cdb942567e
gtest/gtest_http_echo_cxx11.cpp
gtest/gtest_http_echo_cxx11.cpp
// Copyright (c) 2012 Plenluno All rights reserved. #include <gtest/gtest.h> #include <libnode/url.h> #include <assert.h> #include <libj/json.h> #include <libj/js_closure.h> #include "./gtest_http_common.h" namespace libj { namespace node { TEST(GTestHttpEchoCxx11, TestEchoCxx11) { GTestOnEnd::clear(); GTestHttpClientOnResponse::clear(); http::Server::Ptr srv = http::Server::create(); srv->on( http::Server::EVENT_REQUEST, JsClosure::create([srv] (JsArray::Ptr args) -> Value { http::ServerRequest::Ptr req = toPtr<http::ServerRequest>(args->get(0)); http::ServerResponse::Ptr res = toPtr<http::ServerResponse>(args->get(1)); req->setEncoding(Buffer::UTF8); GTestOnData::Ptr onData(new GTestOnData()); req->on(http::ServerRequest::EVENT_DATA, onData); req->on( http::ServerRequest::EVENT_END, JsClosure::create( [srv, req, res, onData] (JsArray::Ptr args) -> Value { String::CPtr body = onData->string(); res->setHeader( http::HEADER_CONTENT_TYPE, String::create("text/plain")); res->setHeader( http::HEADER_CONTENT_LENGTH, String::valueOf(Buffer::byteLength(body))); res->write(body); res->end(); srv->close(); return Status::OK; })); return Status::OK; })); srv->listen(10000); String::CPtr msg = String::create("cxx11"); String::CPtr url = String::create("http://127.0.0.1:10000/abc"); JsObject::Ptr options = url::parse(url); JsObject::Ptr headers = JsObject::create(); headers->put( http::HEADER_CONNECTION, String::create("close")); headers->put( http::HEADER_CONTENT_LENGTH, String::valueOf(Buffer::byteLength(msg))); options->put(http::OPTION_HEADERS, headers); GTestHttpClientOnResponse::Ptr onResponse(new GTestHttpClientOnResponse()); http::ClientRequest::Ptr req = http::request(options, onResponse); req->write(msg); req->end(); node::run(); JsArray::CPtr msgs = GTestOnEnd::messages(); JsArray::CPtr codes = GTestHttpClientOnResponse::statusCodes(); ASSERT_EQ(1, msgs->length()); ASSERT_EQ(1, codes->length()); ASSERT_TRUE(msgs->get(0).equals(msg)); ASSERT_TRUE(codes->get(0).equals(200)); } } // namespace node } // namespace libj
// Copyright (c) 2012-2013 Plenluno All rights reserved. #include <gtest/gtest.h> #include <libnode/url.h> #include <assert.h> #include <libj/json.h> #include <libj/js_closure.h> #include "./gtest_http_common.h" namespace libj { namespace node { TEST(GTestHttpEchoCxx11, TestEchoCxx11) { GTestOnEnd::clear(); GTestHttpClientOnResponse::clear(); auto srv = http::Server::create(); srv->on( http::Server::EVENT_REQUEST, JsClosure::create([srv] (JsArray::Ptr args) { auto req = toPtr<http::ServerRequest>(args->get(0)); auto res = toPtr<http::ServerResponse>(args->get(1)); req->setEncoding(Buffer::UTF8); GTestOnData::Ptr onData(new GTestOnData()); req->on(http::ServerRequest::EVENT_DATA, onData); req->on( http::ServerRequest::EVENT_END, JsClosure::create( [srv, req, res, onData] (JsArray::Ptr args) { auto body = onData->string(); res->setHeader( http::HEADER_CONTENT_TYPE, String::create("text/plain")); res->setHeader( http::HEADER_CONTENT_LENGTH, String::valueOf(Buffer::byteLength(body))); res->write(body); res->end(); srv->close(); return UNDEFINED; })); return UNDEFINED; })); srv->listen(10000); auto msg = String::create("cxx11"); auto url = String::create("http://127.0.0.1:10000/abc"); auto options = url::parse(url); auto headers = JsObject::create(); headers->put( http::HEADER_CONNECTION, String::create("close")); headers->put( http::HEADER_CONTENT_LENGTH, String::valueOf(Buffer::byteLength(msg))); options->put(http::OPTION_HEADERS, headers); JsFunction::Ptr onResponse(new GTestHttpClientOnResponse()); auto req = http::request(options, onResponse); req->write(msg); req->end(); node::run(); auto msgs = GTestOnEnd::messages(); auto codes = GTestHttpClientOnResponse::statusCodes(); ASSERT_EQ(1, msgs->length()); ASSERT_EQ(1, codes->length()); ASSERT_TRUE(msgs->get(0).equals(msg)); ASSERT_TRUE(codes->get(0).equals(200)); } } // namespace node } // namespace libj
use 'auto'
use 'auto'
C++
bsd-2-clause
jiuaiwo1314/libnode,jiuaiwo1314/libnode
eeb83d09bbcb98fc5ce3ffb0df2a8c1e76042e27
libraries/blockchain/include/bts/blockchain/chain_interface.hpp
libraries/blockchain/include/bts/blockchain/chain_interface.hpp
#pragma once #include <bts/blockchain/account_record.hpp> #include <bts/blockchain/asset_record.hpp> #include <bts/blockchain/balance_record.hpp> #include <bts/blockchain/block_record.hpp> #include <bts/blockchain/delegate_slate.hpp> #include <bts/blockchain/market_records.hpp> #include <bts/blockchain/feed_operations.hpp> #include <bts/blockchain/types.hpp> namespace bts { namespace blockchain { enum chain_property_enum { last_asset_id = 0, last_account_id = 1, last_proposal_id = 2, last_random_seed_id = 3, active_delegate_list_id = 4, chain_id = 5, // hash of initial state /** * N = num delegates * Initial condition = 2N * Every time a block is produced subtract 1 * Every time a block is missed add 2 * Maximum value is 2N, Min value is 0 * * Defines how many blocks you must wait to * be 'confirmed' assuming that at least * 60% of the blocks in the last 2 rounds * are present. Less than 60% and you * are on the minority chain. */ confirmation_requirement = 6, database_version = 7, // database version, to know when we need to upgrade dirty_markets = 8, last_feed_id = 9 // used for allocating new data feeds }; typedef uint32_t chain_property_type; const static short MAX_RECENT_OPERATIONS = 20; /** * @class chain_interface * @brief Abstracts the difference between the chain_database and pending_chain_state * */ class chain_interface { public: virtual ~chain_interface(){}; /** return the timestamp from the most recent block */ virtual fc::time_point_sec now()const = 0; std::vector<account_id_type> get_active_delegates()const; void set_active_delegates( const std::vector<account_id_type>& id ); bool is_active_delegate( const account_id_type& id )const; virtual bool is_valid_symbol_name( const string& name ) const; virtual bool is_valid_account_name( const string& name ) const; /** convers an asset + asset_id to a more friendly representation using the symbol name */ string to_pretty_asset( const asset& a )const; double to_pretty_price_double( const price& a )const; string to_pretty_price( const price& a )const; virtual void store_burn_record( const burn_record& br ) = 0; virtual oburn_record fetch_burn_record( const burn_record_key& key )const = 0; virtual oprice get_median_delegate_price( const asset_id_type&, const asset_id_type& base_id = 0 )const = 0; virtual void set_feed( const feed_record& ) = 0; virtual ofeed_record get_feed( const feed_index& )const = 0; virtual void set_market_dirty( const asset_id_type& quote_id, const asset_id_type& base_id ) = 0; virtual fc::ripemd160 get_current_random_seed()const = 0; share_type get_delegate_pay_rate()const; virtual odelegate_slate get_delegate_slate( slate_id_type id )const = 0; virtual void store_delegate_slate( slate_id_type id, const delegate_slate& slate ) = 0; virtual share_type get_delegate_registration_fee()const; virtual share_type get_asset_registration_fee()const; virtual int64_t get_required_confirmations()const; virtual fc::variant get_property( chain_property_enum property_id )const = 0; virtual void set_property( chain_property_enum property_id, const fc::variant& property_value ) = 0; virtual omarket_status get_market_status( const asset_id_type& quote_id, const asset_id_type& base_id ) = 0; virtual void store_market_status( const market_status& s ) = 0; virtual omarket_order get_lowest_ask_record( const asset_id_type& quote_id, const asset_id_type& base_id ) = 0; virtual oorder_record get_bid_record( const market_index_key& )const = 0; virtual oorder_record get_ask_record( const market_index_key& )const = 0; virtual oorder_record get_short_record( const market_index_key& )const = 0; virtual ocollateral_record get_collateral_record( const market_index_key& )const = 0; virtual void store_bid_record( const market_index_key& key, const order_record& ) = 0; virtual void store_ask_record( const market_index_key& key, const order_record& ) = 0; virtual void store_short_record( const market_index_key& key, const order_record& ) = 0; virtual void store_collateral_record( const market_index_key& key, const collateral_record& ) = 0; virtual oasset_record get_asset_record( const asset_id_type& id )const = 0; virtual obalance_record get_balance_record( const balance_id_type& id )const = 0; virtual oaccount_record get_account_record( const account_id_type& id )const = 0; virtual oaccount_record get_account_record( const address& owner )const = 0; virtual bool is_known_transaction( const transaction_id_type& trx_id ) = 0; virtual otransaction_record get_transaction( const transaction_id_type& trx_id, bool exact = true )const = 0; virtual void store_transaction( const transaction_id_type&, const transaction_record& ) = 0; virtual oasset_record get_asset_record( const std::string& symbol )const = 0; virtual oaccount_record get_account_record( const std::string& name )const = 0; #if 0 virtual void store_proposal_record( const proposal_record& r ) = 0; virtual oproposal_record get_proposal_record( proposal_id_type id )const = 0; virtual void store_proposal_vote( const proposal_vote& r ) = 0; virtual oproposal_vote get_proposal_vote( proposal_vote_id_type id )const = 0; #endif virtual void store_asset_record( const asset_record& r ) = 0; virtual void store_balance_record( const balance_record& r ) = 0; virtual void store_account_record( const account_record& r ) = 0; virtual void store_recent_operation( const operation& o ) = 0; virtual vector<operation> get_recent_operations( operation_type_enum t ) = 0; virtual void apply_deterministic_updates(){} virtual asset_id_type last_asset_id()const; virtual asset_id_type new_asset_id(); virtual account_id_type last_account_id()const; virtual account_id_type new_account_id(); #if 0 virtual proposal_id_type last_proposal_id()const; virtual proposal_id_type new_proposal_id(); #endif virtual uint32_t get_head_block_num()const = 0; virtual void store_slot_record( const slot_record& r ) = 0; virtual oslot_record get_slot_record( const time_point_sec& start_time )const = 0; virtual void store_market_history_record( const market_history_key& key, const market_history_record& record ) = 0; virtual omarket_history_record get_market_history_record( const market_history_key& key )const = 0; virtual map<asset_id_type, asset_id_type> get_dirty_markets()const; virtual void set_dirty_markets( const map<asset_id_type,asset_id_type>& ); virtual void set_market_transactions( vector<market_transaction> trxs ) = 0; }; typedef std::shared_ptr<chain_interface> chain_interface_ptr; } } // bts::blockchain FC_REFLECT_ENUM( bts::blockchain::chain_property_enum, (last_asset_id) (last_account_id) (last_proposal_id) (last_random_seed_id) (active_delegate_list_id) (chain_id) (confirmation_requirement) (database_version) (dirty_markets) (last_feed_id) )
#pragma once #include <bts/blockchain/account_record.hpp> #include <bts/blockchain/asset_record.hpp> #include <bts/blockchain/balance_record.hpp> #include <bts/blockchain/block_record.hpp> #include <bts/blockchain/delegate_slate.hpp> #include <bts/blockchain/market_records.hpp> #include <bts/blockchain/feed_operations.hpp> #include <bts/blockchain/types.hpp> namespace bts { namespace blockchain { enum chain_property_enum { last_asset_id = 0, last_account_id = 1, last_proposal_id = 2, last_random_seed_id = 3, active_delegate_list_id = 4, chain_id = 5, // hash of initial state /** * N = num delegates * Initial condition = 2N * Every time a block is produced subtract 1 * Every time a block is missed add 2 * Maximum value is 2N, Min value is 0 * * Defines how many blocks you must wait to * be 'confirmed' assuming that at least * 60% of the blocks in the last 2 rounds * are present. Less than 60% and you * are on the minority chain. */ confirmation_requirement = 6, database_version = 7, // database version, to know when we need to upgrade dirty_markets = 8, last_feed_id = 9 // used for allocating new data feeds }; typedef uint32_t chain_property_type; const static short MAX_RECENT_OPERATIONS = 20; /** * @class chain_interface * @brief Abstracts the difference between the chain_database and pending_chain_state * */ class chain_interface { public: virtual ~chain_interface(){}; /** return the timestamp from the most recent block */ virtual fc::time_point_sec now()const = 0; std::vector<account_id_type> get_active_delegates()const; void set_active_delegates( const std::vector<account_id_type>& id ); bool is_active_delegate( const account_id_type& id )const; virtual bool is_valid_symbol_name( const string& name ) const; virtual bool is_valid_account_name( const string& name ) const; /** converts an asset + asset_id to a more friendly representation using the symbol name */ string to_pretty_asset( const asset& a )const; double to_pretty_price_double( const price& a )const; string to_pretty_price( const price& a )const; /** converts a numeric string + asset symbol to an asset */ asset to_ugly_asset( const string& amount, const string& symbol )const; virtual void store_burn_record( const burn_record& br ) = 0; virtual oburn_record fetch_burn_record( const burn_record_key& key )const = 0; virtual oprice get_median_delegate_price( const asset_id_type&, const asset_id_type& base_id = 0 )const = 0; virtual void set_feed( const feed_record& ) = 0; virtual ofeed_record get_feed( const feed_index& )const = 0; virtual void set_market_dirty( const asset_id_type& quote_id, const asset_id_type& base_id ) = 0; virtual fc::ripemd160 get_current_random_seed()const = 0; share_type get_delegate_pay_rate()const; virtual odelegate_slate get_delegate_slate( slate_id_type id )const = 0; virtual void store_delegate_slate( slate_id_type id, const delegate_slate& slate ) = 0; virtual share_type get_delegate_registration_fee()const; virtual share_type get_asset_registration_fee()const; virtual int64_t get_required_confirmations()const; virtual fc::variant get_property( chain_property_enum property_id )const = 0; virtual void set_property( chain_property_enum property_id, const fc::variant& property_value ) = 0; virtual omarket_status get_market_status( const asset_id_type& quote_id, const asset_id_type& base_id ) = 0; virtual void store_market_status( const market_status& s ) = 0; virtual omarket_order get_lowest_ask_record( const asset_id_type& quote_id, const asset_id_type& base_id ) = 0; virtual oorder_record get_bid_record( const market_index_key& )const = 0; virtual oorder_record get_ask_record( const market_index_key& )const = 0; virtual oorder_record get_short_record( const market_index_key& )const = 0; virtual ocollateral_record get_collateral_record( const market_index_key& )const = 0; virtual void store_bid_record( const market_index_key& key, const order_record& ) = 0; virtual void store_ask_record( const market_index_key& key, const order_record& ) = 0; virtual void store_short_record( const market_index_key& key, const order_record& ) = 0; virtual void store_collateral_record( const market_index_key& key, const collateral_record& ) = 0; virtual oasset_record get_asset_record( const asset_id_type& id )const = 0; virtual obalance_record get_balance_record( const balance_id_type& id )const = 0; virtual oaccount_record get_account_record( const account_id_type& id )const = 0; virtual oaccount_record get_account_record( const address& owner )const = 0; virtual bool is_known_transaction( const transaction_id_type& trx_id ) = 0; virtual otransaction_record get_transaction( const transaction_id_type& trx_id, bool exact = true )const = 0; virtual void store_transaction( const transaction_id_type&, const transaction_record& ) = 0; virtual oasset_record get_asset_record( const std::string& symbol )const = 0; virtual oaccount_record get_account_record( const std::string& name )const = 0; #if 0 virtual void store_proposal_record( const proposal_record& r ) = 0; virtual oproposal_record get_proposal_record( proposal_id_type id )const = 0; virtual void store_proposal_vote( const proposal_vote& r ) = 0; virtual oproposal_vote get_proposal_vote( proposal_vote_id_type id )const = 0; #endif virtual void store_asset_record( const asset_record& r ) = 0; virtual void store_balance_record( const balance_record& r ) = 0; virtual void store_account_record( const account_record& r ) = 0; virtual void store_recent_operation( const operation& o ) = 0; virtual vector<operation> get_recent_operations( operation_type_enum t ) = 0; virtual void apply_deterministic_updates(){} virtual asset_id_type last_asset_id()const; virtual asset_id_type new_asset_id(); virtual account_id_type last_account_id()const; virtual account_id_type new_account_id(); #if 0 virtual proposal_id_type last_proposal_id()const; virtual proposal_id_type new_proposal_id(); #endif virtual uint32_t get_head_block_num()const = 0; virtual void store_slot_record( const slot_record& r ) = 0; virtual oslot_record get_slot_record( const time_point_sec& start_time )const = 0; virtual void store_market_history_record( const market_history_key& key, const market_history_record& record ) = 0; virtual omarket_history_record get_market_history_record( const market_history_key& key )const = 0; virtual map<asset_id_type, asset_id_type> get_dirty_markets()const; virtual void set_dirty_markets( const map<asset_id_type,asset_id_type>& ); virtual void set_market_transactions( vector<market_transaction> trxs ) = 0; }; typedef std::shared_ptr<chain_interface> chain_interface_ptr; } } // bts::blockchain FC_REFLECT_ENUM( bts::blockchain::chain_property_enum, (last_asset_id) (last_account_id) (last_proposal_id) (last_random_seed_id) (active_delegate_list_id) (chain_id) (confirmation_requirement) (database_version) (dirty_markets) (last_feed_id) )
Add missing prototype for my last commit...
Add missing prototype for my last commit...
C++
unlicense
jakeporter/Bitshares,bitsuperlab/cpp-play,bitshares/bitshares-0.x,bitsuperlab/cpp-play,frrp/bitshares,bitshares/devshares,bitshares/devshares,bitshares/devshares,frrp/bitshares,FollowMyVote/bitshares,jakeporter/Bitshares,bitshares/bitshares,dacsunlimited/dac_play,FollowMyVote/bitshares,bitshares/bitshares-0.x,camponez/bitshares,RemitaBit/Remitabit,bitshares/bitshares,Ziftr/bitshares,bitshares/bitshares,bitshares/bitshares-0.x,bitshares/bitshares-0.x,RemitaBit/Remitabit,camponez/bitshares,FollowMyVote/bitshares,dacsunlimited/dac_play,bitsuperlab/cpp-play,Ziftr/bitshares,dacsunlimited/dac_play,FollowMyVote/bitshares,Ziftr/bitshares,FollowMyVote/bitshares,dacsunlimited/dac_play,RemitaBit/Remitabit,bitsuperlab/cpp-play,frrp/bitshares,jakeporter/Bitshares,RemitaBit/Remitabit,dacsunlimited/dac_play,jakeporter/Bitshares,camponez/bitshares,Ziftr/bitshares,jakeporter/Bitshares,frrp/bitshares,camponez/bitshares,RemitaBit/Remitabit,jakeporter/Bitshares,bitshares/devshares,frrp/bitshares,FollowMyVote/bitshares,bitshares/devshares,RemitaBit/Remitabit,camponez/bitshares,bitshares/bitshares,bitshares/bitshares,bitsuperlab/cpp-play,bitshares/bitshares-0.x,dacsunlimited/dac_play,bitshares/bitshares,frrp/bitshares,bitshares/bitshares-0.x,bitshares/devshares,bitsuperlab/cpp-play,camponez/bitshares
105d6ec98de3da323e11cca294331d74e4cd885a
mjolnir/core/EnergyObserver.hpp
mjolnir/core/EnergyObserver.hpp
#ifndef MJOLNIR_CORE_ENERGY_OBSERVER_HPP #define MJOLNIR_CORE_ENERGY_OBSERVER_HPP #include <mjolnir/util/is_finite.hpp> #include <mjolnir/core/ObserverBase.hpp> #include <mjolnir/core/Unit.hpp> #include <iostream> #include <fstream> #include <iomanip> namespace mjolnir { template<typename traitsT> class EnergyObserver final : public ObserverBase<traitsT> { public: using base_type = ObserverBase<traitsT>; using traits_type = typename base_type::traits_type; using real_type = typename base_type::real_type; using coordinate_type = typename base_type::coordinate_type; using system_type = typename base_type::system_type; using forcefield_type = typename base_type::forcefield_type; using boundary_type = typename traits_type::boundary_type; public: explicit EnergyObserver(const std::string& filename_prefix) : prefix_(filename_prefix), file_name_(filename_prefix + ".ene") { // clear files and throw an error if the files cannot be opened. this->clear_file(this->file_name_); } ~EnergyObserver() override {} void initialize(const std::size_t, const std::size_t, const real_type, const system_type& sys, const forcefield_type& ff) override { using phys_constants = physics::constants<real_type>; std::ofstream ofs(this->file_name_, std::ios::app); ofs << "# unit of length : " << phys_constants::length_unit() << ", unit of energy : " << phys_constants::energy_unit() << '\n'; ofs << "# timestep "; std::string names; ff->format_energy_name(names); // write into it ofs << names; ofs << " kinetic_energy"; if(is_cuboidal_periodic_boundary<boundary_type>::value) { ofs << " Pxx Pyy Pzz"; } for(const auto& attr : sys.attributes()) { ofs << " attribute:" << attr.first; } ofs << '\n'; return; } // update column names and widths if forcefield changed. void update(const std::size_t, const real_type, const system_type& sys, const forcefield_type& ff) override { std::ofstream ofs(this->file_name_, std::ios::app); ofs << "# timestep "; std::string names; ff->format_energy_name(names); // write into it ofs << names; ofs << " kinetic_energy"; if(is_cuboidal_periodic_boundary<boundary_type>::value) { ofs << " Pxx Pyy Pzz"; } for(const auto& attr : sys.attributes()) { ofs << " attribute:" << attr.first; } ofs << '\n'; return; } void output(const std::size_t step, const real_type, const system_type& sys, const forcefield_type& ff) override { bool is_ok = true; std::ofstream ofs(this->file_name_, std::ios::app); // if the width exceeds, operator<<(std::ostream, std::string) ignores // ostream::width and outputs whole string. ofs << std::setw(11) << std::left << std::to_string(step) << ' '; std::string energies; const auto potential_energy = ff->format_energy(sys, energies); ofs << energies; if(!is_finite(potential_energy)) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_ERROR("potential energy becomes NaN."); is_ok = false; } real_type Ek(0), Px(0), Py(0), Pz(0); std::tie(Ek, Px, Py, Pz) = this->calc_energy_and_pressure(sys, is_cuboidal_periodic_boundary<boundary_type>{}); ofs << std::setw(14) << std::right << std::fixed << Ek; if(!is_finite(Ek)) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_ERROR("kinetic energy becomes NaN."); is_ok = false; } if(is_cuboidal_periodic_boundary<boundary_type>::value) { ofs << std::setw(16) << std::right << std::setprecision(8) << std::scientific << Px; ofs << std::setw(16) << std::right << std::setprecision(8) << std::scientific << Py; ofs << std::setw(16) << std::right << std::setprecision(8) << std::scientific << Pz; } for(const auto& attr : sys.attributes()) { if(!is_finite(attr.second)) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_ERROR(attr.first, " becomes NaN."); is_ok = false; } ofs << ' ' << std::setw(10 + attr.first.size()) << std::right << std::fixed << attr.second; } ofs << std::endl; // flush before throwing an exception if(!is_ok) { throw std::runtime_error("Energy value becomes NaN"); } return; } void finalize(const std::size_t, const real_type, const system_type&, const forcefield_type&) override {/* do nothing. */} std::string const& prefix() const noexcept override {return this->prefix_;} private: std::tuple<real_type, real_type, real_type, real_type> calc_energy_and_pressure(const system_type& sys, std::true_type) { const auto cell_width = sys.boundary().width(); const auto volume = math::X(cell_width) * math::Y(cell_width) * math::Z(cell_width); const auto rvolume = real_type(1) / volume; real_type Ek(0); real_type Px(0); real_type Py(0); real_type Pz(0); for(std::size_t i=0; i<sys.size(); ++i) { const auto m = sys.mass(i); const auto& r = sys.position(i); const auto& v = sys.velocity(i); const auto& f = sys.force(i); Ek += math::length_sq(v) * m; Px += m * math::X(v) * math::X(v) + math::X(f) * math::X(r); Py += m * math::Y(v) * math::Y(v) + math::Y(f) * math::Y(r); Pz += m * math::Z(v) * math::Z(v) + math::Z(f) * math::Z(r); } Ek *= 0.5; Px *= rvolume; Py *= rvolume; Pz *= rvolume; return std::make_tuple(Ek, Px, Py, Pz); } std::tuple<real_type, real_type, real_type, real_type> calc_energy_and_pressure(const system_type& sys, std::false_type) { real_type Ek(0); for(std::size_t i=0; i<sys.size(); ++i) { const auto m = sys.mass(i); const auto& v = sys.velocity(i); Ek += math::length_sq(v) * m; } Ek *= 0.5; return std::make_tuple(Ek, real_type(0.0), real_type(0.0), real_type(0.0)); } void clear_file(const std::string& fname) const { std::ofstream ofs(fname); if(not ofs.good()) { throw_exception<std::runtime_error>( "[error] mjolnir::EnergyObserver: file open error: ", fname); } return; } private: std::string prefix_; std::string file_name_; std::vector<std::size_t> widths_; // column width to format energy values }; #ifdef MJOLNIR_SEPARATE_BUILD extern template class EnergyObserver<SimulatorTraits<double, UnlimitedBoundary> >; extern template class EnergyObserver<SimulatorTraits<float, UnlimitedBoundary> >; extern template class EnergyObserver<SimulatorTraits<double, CuboidalPeriodicBoundary>>; extern template class EnergyObserver<SimulatorTraits<float, CuboidalPeriodicBoundary>>; #endif } // mjolnir #endif//MJOLNIR_CORE_ENERGY_OBSERVER_HPP
#ifndef MJOLNIR_CORE_ENERGY_OBSERVER_HPP #define MJOLNIR_CORE_ENERGY_OBSERVER_HPP #include <mjolnir/util/is_finite.hpp> #include <mjolnir/core/ObserverBase.hpp> #include <mjolnir/core/Unit.hpp> #include <iostream> #include <fstream> #include <iomanip> namespace mjolnir { template<typename traitsT> class EnergyObserver final : public ObserverBase<traitsT> { public: using base_type = ObserverBase<traitsT>; using traits_type = typename base_type::traits_type; using real_type = typename base_type::real_type; using coordinate_type = typename base_type::coordinate_type; using system_type = typename base_type::system_type; using forcefield_type = typename base_type::forcefield_type; using boundary_type = typename traits_type::boundary_type; public: explicit EnergyObserver(const std::string& filename_prefix) : prefix_(filename_prefix), file_name_(filename_prefix + ".ene") { // clear files and throw an error if the files cannot be opened. this->clear_file(this->file_name_); } ~EnergyObserver() override {} void initialize(const std::size_t, const std::size_t, const real_type, const system_type& sys, const forcefield_type& ff) override { using phys_constants = physics::constants<real_type>; std::ofstream ofs(this->file_name_, std::ios::app); ofs << "# unit of length : " << phys_constants::length_unit() << ", unit of energy : " << phys_constants::energy_unit() << '\n'; ofs << "# timestep "; std::string names; ff->format_energy_name(names); // write into it ofs << names; ofs << " kinetic_energy Pxx Pyy Pzz"; for(const auto& attr : sys.attributes()) { ofs << " attribute:" << attr.first; } ofs << '\n'; return; } // update column names and widths if forcefield changed. void update(const std::size_t, const real_type, const system_type& sys, const forcefield_type& ff) override { std::ofstream ofs(this->file_name_, std::ios::app); ofs << "# timestep "; std::string names; ff->format_energy_name(names); // write into it ofs << names; ofs << " kinetic_energy Pxx Pyy Pzz"; for(const auto& attr : sys.attributes()) { ofs << " attribute:" << attr.first; } ofs << '\n'; return; } void output(const std::size_t step, const real_type, const system_type& sys, const forcefield_type& ff) override { bool is_ok = true; std::ofstream ofs(this->file_name_, std::ios::app); // if the width exceeds, operator<<(std::ostream, std::string) ignores // ostream::width and outputs whole string. ofs << std::setw(11) << std::left << std::to_string(step) << ' '; std::string energies; const auto potential_energy = ff->format_energy(sys, energies); ofs << energies; if(!is_finite(potential_energy)) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_ERROR("potential energy becomes NaN."); is_ok = false; } real_type Ek(0), Px(0), Py(0), Pz(0); std::tie(Ek, Px, Py, Pz) = this->calc_energy_and_pressure(sys, is_cuboidal_periodic_boundary<boundary_type>{}); ofs << std::setw(14) << std::right << std::fixed << Ek; ofs << std::setw(16) << std::right << std::setprecision(8) << std::scientific << Px; ofs << std::setw(16) << std::right << std::setprecision(8) << std::scientific << Py; ofs << std::setw(16) << std::right << std::setprecision(8) << std::scientific << Pz; if(!is_finite(Ek)) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_ERROR("kinetic energy becomes NaN."); is_ok = false; } for(const auto& attr : sys.attributes()) { if(!is_finite(attr.second)) { MJOLNIR_GET_DEFAULT_LOGGER(); MJOLNIR_LOG_ERROR(attr.first, " becomes NaN."); is_ok = false; } ofs << ' ' << std::setw(10 + attr.first.size()) << std::right << std::fixed << attr.second; } ofs << std::endl; // flush before throwing an exception if(!is_ok) { throw std::runtime_error("Energy value becomes NaN"); } return; } void finalize(const std::size_t, const real_type, const system_type&, const forcefield_type&) override {/* do nothing. */} std::string const& prefix() const noexcept override {return this->prefix_;} private: std::tuple<real_type, real_type, real_type, real_type> calc_energy_and_pressure(const system_type& sys) { const auto cell_width = sys.boundary().width(); const auto volume = math::X(cell_width) * math::Y(cell_width) * math::Z(cell_width); const auto rvolume = real_type(1) / volume; real_type Ek(0); real_type Px(sys.virial()(0, 0)); real_type Py(sys.virial()(1, 1)); real_type Pz(sys.virial()(2, 2)); for(std::size_t i=0; i<sys.size(); ++i) { const auto m = sys.mass(i); const auto& r = sys.position(i); const auto& v = sys.velocity(i); const auto& f = sys.force(i); Ek += math::length_sq(v) * m; Px += m * math::X(v) * math::X(v); Py += m * math::Y(v) * math::Y(v); Pz += m * math::Z(v) * math::Z(v); } Ek *= 0.5; Px *= rvolume; Py *= rvolume; Pz *= rvolume; return std::make_tuple(Ek, Px, Py, Pz); } void clear_file(const std::string& fname) const { std::ofstream ofs(fname); if(not ofs.good()) { throw_exception<std::runtime_error>( "[error] mjolnir::EnergyObserver: file open error: ", fname); } return; } private: std::string prefix_; std::string file_name_; std::vector<std::size_t> widths_; // column width to format energy values }; #ifdef MJOLNIR_SEPARATE_BUILD extern template class EnergyObserver<SimulatorTraits<double, UnlimitedBoundary> >; extern template class EnergyObserver<SimulatorTraits<float, UnlimitedBoundary> >; extern template class EnergyObserver<SimulatorTraits<double, CuboidalPeriodicBoundary>>; extern template class EnergyObserver<SimulatorTraits<float, CuboidalPeriodicBoundary>>; #endif } // mjolnir #endif//MJOLNIR_CORE_ENERGY_OBSERVER_HPP
use sys.virial to calc pressure
feat: use sys.virial to calc pressure
C++
mit
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
c1146e6ab506cb73ccee9ff9865a993b5d9c54ec
VelodyneHDL/vtkLASFileWriter.cxx
VelodyneHDL/vtkLASFileWriter.cxx
// Copyright 2014 Velodyne Acoustics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "vtkLASFileWriter.h" #include <vtkPointData.h> #include <vtkPolyData.h> #include <vtk_libproj4.h> #include <liblas/liblas.hpp> #include <Eigen/Dense> #ifndef PJ_VERSION // 4.8 or later #include <cassert> #endif namespace { #ifdef PJ_VERSION // 4.8 or later //----------------------------------------------------------------------------- projPJ CreateProj(int epsg) { std::ostringstream ss; ss << "+init=epsg:" << epsg; return pj_init_plus(ss.str().c_str()); } //----------------------------------------------------------------------------- Eigen::Vector3d ConvertGcs( Eigen::Vector3d p, projPJ inProj, projPJ outProj) { if (pj_is_latlong(inProj)) { p[0] *= DEG_TO_RAD; p[1] *= DEG_TO_RAD; } double* const data = p.data(); pj_transform(inProj, outProj, 1, 1, data + 0, data + 1, data + 2); if (pj_is_latlong(outProj)) { p[0] *= RAD_TO_DEG; p[1] *= RAD_TO_DEG; } return p; } #else //----------------------------------------------------------------------------- PROJ* CreateProj(int utmZone, bool south) { std::ostringstream ss; ss << "+zone=" << utmZone; char buffer[65] = { 0 }; strncpy(buffer, ss.str().c_str(), 64); std::vector<const char*> utmparams; utmparams.push_back("+proj=utm"); utmparams.push_back("+ellps=WGS84"); utmparams.push_back("+units=m"); utmparams.push_back("+no_defs"); utmparams.push_back(buffer); if (south) { utmparams.push_back("+south"); } return proj_init(utmparams.size(), const_cast<char**>(&(utmparams[0]))); } //----------------------------------------------------------------------------- Eigen::Vector3d InvertProj(Eigen::Vector3d in, PROJ* proj) { // This "lovely little gem" makes an awful lot of assumptions about the input // (some flavor of XY) and output (internal LP, which we assume / hope is // WGS'84) GCS's and what operations are "interesting" (i.e. the assumption // that the Z component does not need to be considered and can be passed // through unaltered). Unfortunately, it's the best we can do with PROJ 4.7 // until VTK can be updated to use 4.8. Fortunately, given how we're being // used, our input really ought to always be UTM. PROJ_XY xy; xy.x = in[0]; xy.y = in[1]; const PROJ_LP lp = proj_inv(xy, proj); return Eigen::Vector3d(lp.lam * RAD_TO_DEG, lp.phi * RAD_TO_DEG, in[2]); } #endif } //----------------------------------------------------------------------------- class vtkLASFileWriter::vtkInternal { public: void Close(); std::ofstream Stream; liblas::Writer* Writer; double MinTime; double MaxTime; Eigen::Vector3d Origin; size_t npoints; #ifdef PJ_VERSION // 4.8 or later projPJ InProj; projPJ OutProj; #else PROJ* Proj; #endif int OutGcs; }; //----------------------------------------------------------------------------- void vtkLASFileWriter::vtkInternal::Close() { delete this->Writer; this->Writer = 0; this->Stream.close(); } //----------------------------------------------------------------------------- vtkLASFileWriter::vtkLASFileWriter(const char* filename) : Internal(new vtkInternal) { this->Internal->MinTime = -std::numeric_limits<double>::infinity(); this->Internal->MaxTime = +std::numeric_limits<double>::infinity(); #ifdef PJ_VERSION // 4.8 or later this->Internal->InProj = 0; this->Internal->OutProj = 0; #else this->Internal->Proj = 0; #endif this->Internal->OutGcs = -1; this->Internal->npoints = 0; this->Internal->Stream.open( filename, std::ios::out | std::ios::trunc | std::ios::binary); liblas::Header header; header.SetSoftwareId("VeloView"); header.SetDataFormatId(liblas::ePointFormat1); header.SetScale(1e-3, 1e-3, 1e-3); this->Internal->Writer = new liblas::Writer(this->Internal->Stream, header); } //----------------------------------------------------------------------------- vtkLASFileWriter::~vtkLASFileWriter() { liblas::Header header = this->Internal->Writer->GetHeader(); header.SetPointRecordsByReturnCount(0, this->Internal->npoints); this->Internal->Writer->SetHeader(header); this->Internal->Writer->WriteHeader(); this->Internal->Close(); #ifdef PJ_VERSION // 4.8 or later pj_free(this->Internal->InProj); pj_free(this->Internal->OutProj); #else proj_free(this->Internal->Proj); #endif delete this->Internal; } //----------------------------------------------------------------------------- void vtkLASFileWriter::SetTimeRange(double min, double max) { this->Internal->MinTime = min; this->Internal->MaxTime = max; } //----------------------------------------------------------------------------- void vtkLASFileWriter::SetOrigin( int gcs, double easting, double northing, double height) { // Set internal UTM offset Eigen::Vector3d origin(easting, northing, height); this->Internal->Origin = origin; // Convert offset to output GCS, if a geoconversion is set up #ifdef PJ_VERSION // 4.8 or later if (this->Internal->OutProj) { origin = ConvertGcs(origin, this->Internal->InProj, this->Internal->OutProj); gcs = this->Internal->OutGcs; } #else if (this->Internal->Proj) { origin = InvertProj(origin, this->Internal->Proj); gcs = this->Internal->OutGcs; } #endif // Update header liblas::Header header = this->Internal->Writer->GetHeader(); header.SetOffset(origin[0], origin[1], origin[2]); try { liblas::SpatialReference srs; std::ostringstream ss; ss << "EPSG:" << gcs; srs.SetFromUserInput(ss.str()); header.SetSRS(srs); } catch (std::logic_error) { std::cerr << "failed to set SRS (logic)" << std::endl; } catch (std::runtime_error) { std::cerr << "failed to set SRS" << std::endl; } this->Internal->Writer->SetHeader(header); this->Internal->Writer->WriteHeader(); } //----------------------------------------------------------------------------- void vtkLASFileWriter::SetGeoConversion(int in, int out) { #ifdef PJ_VERSION // 4.8 or later pj_free(this->Internal->InProj); pj_free(this->Internal->OutProj); this->Internal->InProj = CreateProj(in); this->Internal->OutProj = CreateProj(out); #else // The PROJ 4.7 API makes it near impossible to do generic transforms, hence // InvertProj (see also comments there) is full of assumptions. Assert some // of those assumptions here. assert((in > 32600 && in < 32661) || (in > 32700 && in < 32761)); assert(out == 4326); proj_free(this->Internal->Proj); this->Internal->Proj = CreateProj(in % 100, in > 32700); #endif this->Internal->OutGcs = out; } //----------------------------------------------------------------------------- void vtkLASFileWriter::SetPrecision(double neTol, double hTol) { liblas::Header header = this->Internal->Writer->GetHeader(); header.SetScale(neTol, neTol, hTol); this->Internal->Writer->SetHeader(header); this->Internal->Writer->WriteHeader(); } //----------------------------------------------------------------------------- void vtkLASFileWriter::WriteFrame(vtkPolyData* data) { vtkPoints* const points = data->GetPoints(); vtkDataArray* const intensityData = data->GetPointData()->GetArray("intensity"); vtkDataArray* const laserIdData = data->GetPointData()->GetArray("laser_id"); vtkDataArray* const timestampData = data->GetPointData()->GetArray("timestamp"); const vtkIdType numPoints = points->GetNumberOfPoints(); for (vtkIdType n = 0; n < numPoints; ++n) { const double time = timestampData->GetComponent(n, 0) * 1e-6; if (time >= this->Internal->MinTime && time <= this->Internal->MaxTime) { Eigen::Vector3d pos; points->GetPoint(n, pos.data()); pos += this->Internal->Origin; #ifdef PJ_VERSION // 4.8 or later if (this->Internal->OutProj) { pos = ConvertGcs(pos, this->Internal->InProj, this->Internal->OutProj); } #else if (this->Internal->Proj) { pos = InvertProj(pos, this->Internal->Proj); } #endif liblas::Point p(&this->Internal->Writer->GetHeader()); p.SetCoordinates(pos[0], pos[1], pos[2]); p.SetIntensity(static_cast<uint16_t>(intensityData->GetComponent(n, 0))); p.SetReturnNumber(0); p.SetNumberOfReturns(1); p.SetUserData(static_cast<uint8_t>(laserIdData->GetComponent(n, 0))); p.SetTime(time); this->Internal->npoints++; this->Internal->Writer->WritePoint(p); } } }
// Copyright 2014 Velodyne Acoustics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "vtkLASFileWriter.h" #include <vtkPointData.h> #include <vtkPolyData.h> #include <vtk_libproj4.h> #include <liblas/liblas.hpp> #include <Eigen/Dense> #ifndef PJ_VERSION // 4.8 or later #include <cassert> #endif namespace { #ifdef PJ_VERSION // 4.8 or later //----------------------------------------------------------------------------- projPJ CreateProj(int epsg) { std::ostringstream ss; ss << "+init=epsg:" << epsg; return pj_init_plus(ss.str().c_str()); } //----------------------------------------------------------------------------- Eigen::Vector3d ConvertGcs( Eigen::Vector3d p, projPJ inProj, projPJ outProj) { if (pj_is_latlong(inProj)) { p[0] *= DEG_TO_RAD; p[1] *= DEG_TO_RAD; } double* const data = p.data(); pj_transform(inProj, outProj, 1, 1, data + 0, data + 1, data + 2); if (pj_is_latlong(outProj)) { p[0] *= RAD_TO_DEG; p[1] *= RAD_TO_DEG; } return p; } #else //----------------------------------------------------------------------------- PROJ* CreateProj(int utmZone, bool south) { std::ostringstream ss; ss << "+zone=" << utmZone; char buffer[65] = { 0 }; strncpy(buffer, ss.str().c_str(), 64); std::vector<const char*> utmparams; utmparams.push_back("+proj=utm"); utmparams.push_back("+ellps=WGS84"); utmparams.push_back("+units=m"); utmparams.push_back("+no_defs"); utmparams.push_back(buffer); if (south) { utmparams.push_back("+south"); } return proj_init(utmparams.size(), const_cast<char**>(&(utmparams[0]))); } //----------------------------------------------------------------------------- Eigen::Vector3d InvertProj(Eigen::Vector3d in, PROJ* proj) { // This "lovely little gem" makes an awful lot of assumptions about the input // (some flavor of XY) and output (internal LP, which we assume / hope is // WGS'84) GCS's and what operations are "interesting" (i.e. the assumption // that the Z component does not need to be considered and can be passed // through unaltered). Unfortunately, it's the best we can do with PROJ 4.7 // until VTK can be updated to use 4.8. Fortunately, given how we're being // used, our input really ought to always be UTM. PROJ_XY xy; xy.x = in[0]; xy.y = in[1]; const PROJ_LP lp = proj_inv(xy, proj); return Eigen::Vector3d(lp.lam * RAD_TO_DEG, lp.phi * RAD_TO_DEG, in[2]); } #endif } //----------------------------------------------------------------------------- class vtkLASFileWriter::vtkInternal { public: void Close(); std::ofstream Stream; liblas::Writer* Writer; double MinTime; double MaxTime; Eigen::Vector3d Origin; size_t npoints; double MinPt[3]; double MaxPt[3]; #ifdef PJ_VERSION // 4.8 or later projPJ InProj; projPJ OutProj; #else PROJ* Proj; #endif int OutGcs; }; //----------------------------------------------------------------------------- void vtkLASFileWriter::vtkInternal::Close() { liblas::Header header = this->Writer->GetHeader(); header.SetPointRecordsByReturnCount(0, this->npoints); header.SetMin(this->MinPt[0], this->MinPt[1], this->MinPt[2]); header.SetMax(this->MaxPt[0], this->MaxPt[1], this->MaxPt[2]); this->Writer->SetHeader(header); this->Writer->WriteHeader(); delete this->Writer; this->Writer = 0; this->Stream.close(); } //----------------------------------------------------------------------------- vtkLASFileWriter::vtkLASFileWriter(const char* filename) : Internal(new vtkInternal) { this->Internal->MinTime = -std::numeric_limits<double>::infinity(); this->Internal->MaxTime = +std::numeric_limits<double>::infinity(); #ifdef PJ_VERSION // 4.8 or later this->Internal->InProj = 0; this->Internal->OutProj = 0; #else this->Internal->Proj = 0; #endif this->Internal->OutGcs = -1; this->Internal->npoints = 0; for(int i = 0; i < 3; ++i) { this->Internal->MaxPt[i] = -std::numeric_limits<double>::max(); this->Internal->MinPt[i] = std::numeric_limits<double>::max(); } this->Internal->Stream.open( filename, std::ios::out | std::ios::trunc | std::ios::binary); liblas::Header header; header.SetSoftwareId("VeloView"); header.SetDataFormatId(liblas::ePointFormat1); header.SetScale(1e-3, 1e-3, 1e-3); this->Internal->Writer = new liblas::Writer(this->Internal->Stream, header); } //----------------------------------------------------------------------------- vtkLASFileWriter::~vtkLASFileWriter() { this->Internal->Close(); #ifdef PJ_VERSION // 4.8 or later pj_free(this->Internal->InProj); pj_free(this->Internal->OutProj); #else proj_free(this->Internal->Proj); #endif delete this->Internal; } //----------------------------------------------------------------------------- void vtkLASFileWriter::SetTimeRange(double min, double max) { this->Internal->MinTime = min; this->Internal->MaxTime = max; } //----------------------------------------------------------------------------- void vtkLASFileWriter::SetOrigin( int gcs, double easting, double northing, double height) { // Set internal UTM offset Eigen::Vector3d origin(easting, northing, height); this->Internal->Origin = origin; // Convert offset to output GCS, if a geoconversion is set up #ifdef PJ_VERSION // 4.8 or later if (this->Internal->OutProj) { origin = ConvertGcs(origin, this->Internal->InProj, this->Internal->OutProj); gcs = this->Internal->OutGcs; } #else if (this->Internal->Proj) { origin = InvertProj(origin, this->Internal->Proj); gcs = this->Internal->OutGcs; } #endif // Update header liblas::Header header = this->Internal->Writer->GetHeader(); header.SetOffset(origin[0], origin[1], origin[2]); try { liblas::SpatialReference srs; std::ostringstream ss; ss << "EPSG:" << gcs; srs.SetFromUserInput(ss.str()); header.SetSRS(srs); } catch (std::logic_error) { std::cerr << "failed to set SRS (logic)" << std::endl; } catch (std::runtime_error) { std::cerr << "failed to set SRS" << std::endl; } this->Internal->Writer->SetHeader(header); this->Internal->Writer->WriteHeader(); } //----------------------------------------------------------------------------- void vtkLASFileWriter::SetGeoConversion(int in, int out) { #ifdef PJ_VERSION // 4.8 or later pj_free(this->Internal->InProj); pj_free(this->Internal->OutProj); this->Internal->InProj = CreateProj(in); this->Internal->OutProj = CreateProj(out); #else // The PROJ 4.7 API makes it near impossible to do generic transforms, hence // InvertProj (see also comments there) is full of assumptions. Assert some // of those assumptions here. assert((in > 32600 && in < 32661) || (in > 32700 && in < 32761)); assert(out == 4326); proj_free(this->Internal->Proj); this->Internal->Proj = CreateProj(in % 100, in > 32700); #endif this->Internal->OutGcs = out; } //----------------------------------------------------------------------------- void vtkLASFileWriter::SetPrecision(double neTol, double hTol) { liblas::Header header = this->Internal->Writer->GetHeader(); header.SetScale(neTol, neTol, hTol); this->Internal->Writer->SetHeader(header); this->Internal->Writer->WriteHeader(); } //----------------------------------------------------------------------------- void vtkLASFileWriter::WriteFrame(vtkPolyData* data) { vtkPoints* const points = data->GetPoints(); vtkDataArray* const intensityData = data->GetPointData()->GetArray("intensity"); vtkDataArray* const laserIdData = data->GetPointData()->GetArray("laser_id"); vtkDataArray* const timestampData = data->GetPointData()->GetArray("timestamp"); const vtkIdType numPoints = points->GetNumberOfPoints(); for (vtkIdType n = 0; n < numPoints; ++n) { const double time = timestampData->GetComponent(n, 0) * 1e-6; if (time >= this->Internal->MinTime && time <= this->Internal->MaxTime) { Eigen::Vector3d pos; points->GetPoint(n, pos.data()); pos += this->Internal->Origin; #ifdef PJ_VERSION // 4.8 or later if (this->Internal->OutProj) { pos = ConvertGcs(pos, this->Internal->InProj, this->Internal->OutProj); } #else if (this->Internal->Proj) { pos = InvertProj(pos, this->Internal->Proj); } #endif liblas::Point p(&this->Internal->Writer->GetHeader()); p.SetCoordinates(pos[0], pos[1], pos[2]); p.SetIntensity(static_cast<uint16_t>(intensityData->GetComponent(n, 0))); p.SetReturnNumber(0); p.SetNumberOfReturns(1); p.SetUserData(static_cast<uint8_t>(laserIdData->GetComponent(n, 0))); p.SetTime(time); this->Internal->npoints++; for(int i = 0; i < 3; ++i) { if(p[i] > this->Internal->MaxPt[i]) { this->Internal->MaxPt[i] = p[i]; } if(p[i] < this->Internal->MinPt[i]) { this->Internal->MinPt[i] = p[i]; } } this->Internal->Writer->WritePoint(p); } } }
Write bounding box to header
fix: Write bounding box to header
C++
apache-2.0
frizaro/Veloview,Kitware/VeloView,frizaro/Veloview,Kitware/VeloView,Kitware/VeloView,frizaro/Veloview,Kitware/VeloView,Kitware/VeloView,frizaro/Veloview
71dfa9f983893b75476046b67ce56b63d19327a2
modules/kde/KWallet/kwallet.cpp
modules/kde/KWallet/kwallet.cpp
#include "ppasskeeper.h" #include "tokenizer.h" #include "list_pwd.h" #include <string> #include <iostream> #include <kwallet.h> #include <kapplication.h> #include <kcmdlineargs.h> #include <kaboutdata.h> #include <klocale.h> //plugin data KWallet::Wallet* _wallet; KApplication *_app; //local functions bool init_kde_lazy() { static bool initialized = false; if (! initialized) { if (! KApplication::instance()) { static char kdeAppName[] = "ppasskeeper-kwallet"; int argc = 1; char *argv[2] = { kdeAppName, NULL }; QByteArray qbApp(kdeAppName); KAboutData about(qbApp, qbApp, KLocalizedString(),QByteArray("1.0")); KCmdLineArgs::init(argc, argv, &about); if (! qApp) _app = new KApplication(true); } initialized = true; } } extern "C" void constructor() { //lazy initialization _wallet=NULL; _app=NULL; } extern "C" void destructor() { //It crashes the application to uncomment the following :s /*delete _wallet; delete _app;*/ } extern "C" ppk_boolean isWritable() { return PPK_TRUE; } extern "C" ppk_security_level securityLevel(const char* module_id) { return ppk_sec_safe; } //Get available flags extern "C" unsigned int readFlagsAvailable() { return ppk_rf_none|ppk_rf_silent; } extern "C" unsigned int writeFlagsAvailable() { return ppk_wf_none|ppk_wf_silent; } extern "C" unsigned int listingFlagsAvailable() { return ppk_lf_none|ppk_lf_silent; } KWallet::Wallet* openWallet(unsigned int flags) { init_kde_lazy(); bool initialised=KWallet::Wallet::isOpen(KWallet::Wallet::NetworkWallet()); if (!initialised && (flags & ppk_lf_silent!=0 || flags & ppk_rf_silent!=0 || flags & ppk_wf_silent!=0)) { //continue only if it won't annoy people who don't want to be prompted return NULL; } if (_wallet == NULL) { //lazy init _wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(), NULL); if (_wallet == NULL) { return NULL; } } if (! KWallet::Wallet::isOpen(KWallet::Wallet::NetworkWallet())) { //is the wallet still open? if not, try to reinitialize it delete _wallet; _wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),0); if (_wallet == NULL) { return NULL; } } if(! _wallet->setFolder(QString::fromAscii("PPassKeeper"))) { _wallet->createFolder(QString::fromAscii("PPassKeeper")); if(! _wallet->setFolder(QString::fromAscii("PPassKeeper"))) return NULL; } return _wallet; } ppk_error getPassword(const QString key, ppk_data** edata, unsigned int flags) { QString pwd; KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { //Get the password if(wallet->readPassword(key, pwd)==0) { *edata=ppk_string_data_new(qPrintable(pwd)); return PPK_OK; } else return PPK_ENTRY_UNAVAILABLE; } else return PPK_CANNOT_OPEN_PASSWORD_MANAGER; } ppk_error getBlob(const QString key, ppk_data** edata, unsigned int flags) { static QByteArray blob; KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { if(wallet->readEntry(key, blob)==0) { *edata=ppk_blob_data_new(blob, blob.size()); return PPK_OK; } else return PPK_ENTRY_UNAVAILABLE; } else return PPK_CANNOT_OPEN_PASSWORD_MANAGER; } ppk_error setPassword(const QString key, const char* pwd, unsigned int flags) { KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { //Set the password if(wallet->writePassword(key, QString::fromUtf8(pwd))==0) return PPK_OK; else return PPK_ENTRY_UNAVAILABLE; } else return PPK_CANNOT_OPEN_PASSWORD_MANAGER; } ppk_error setBlob(const QString key, const void *data, unsigned long size, unsigned int flags) { KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { //Set the password QByteArray blobData((const char *) data, size); if(wallet->writeEntry(key, blobData)==0) return PPK_OK; else return PPK_ENTRY_UNAVAILABLE; } else return PPK_CANNOT_OPEN_PASSWORD_MANAGER; } ppk_error removePassword(const QString key, unsigned int flags) { KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { //Set the password if(wallet->removeEntry(key)==0) return PPK_OK; else return PPK_ENTRY_UNAVAILABLE; } else return PPK_CANNOT_OPEN_PASSWORD_MANAGER; } bool passwordExists(const QString key, unsigned int flags) { static QString pwd; KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { //Get the password if(wallet->hasEntry(key)==0) return true; else return false; } else return false; } //functions extern "C" const char* getModuleID() { return "KWallet4"; } extern "C" const char* getModuleName() { return "KWallet - Store it into KDE's Wallet"; } extern "C" const int getABIVersion() { return 1; } extern "C" unsigned int getEntryListCount(unsigned int entry_types, unsigned int flags) { //Open the wallet KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { return ListPwd::getEntryListCount(wallet, entry_types, flags); } else return 0; } extern "C" ppk_error getEntryList(unsigned int entry_types, ppk_entry*** entryList, size_t* nbEntries, unsigned int flags) { //Open the wallet KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { *entryList = ListPwd::getEntryList(wallet, entry_types, flags, nbEntries); return PPK_OK; } else return PPK_CANNOT_OPEN_PASSWORD_MANAGER; } static bool generateKey(const ppk_entry* entry, QString &generatedKey) { size_t size=ppk_key_length(entry); if(size>0) { char* buf=new char[size+1]; ppk_boolean ret=ppk_get_key(entry, buf, size); if(ret==PPK_TRUE) generatedKey=QString::fromUtf8(buf); else std::cerr << "generateKey: invalid ppk_get_key" << std::endl; delete[] buf; return ret; } else { std::cerr << "generateKey: invalid ppk_key_length" << std::endl; return PPK_FALSE; } } extern "C" ppk_error getEntry(const ppk_entry* entry, ppk_data **edata, unsigned int flags) { QString generatedKey; if (generateKey(entry, generatedKey) == PPK_FALSE) return PPK_UNKNOWN_ENTRY_TYPE; KWallet::Wallet *wallet = openWallet(flags); if (wallet == NULL) return PPK_CANNOT_OPEN_PASSWORD_MANAGER; KWallet::Wallet::EntryType entryType = wallet->entryType(generatedKey); if (entryType == KWallet::Wallet::Password) return getPassword(generatedKey, edata, flags); else if (entryType == KWallet::Wallet::Stream) return getBlob(generatedKey, edata, flags); else return PPK_UNKNOWN_ENTRY_TYPE; } extern "C" ppk_error setEntry(const ppk_entry* entry, const ppk_data* edata, unsigned int flags) { QString generatedKey; if (generateKey(entry, generatedKey) == PPK_FALSE) return PPK_UNKNOWN_ENTRY_TYPE; if (edata->type == ppk_string) return setPassword(generatedKey, edata->string, flags); else if (edata->type == ppk_blob) return setBlob(generatedKey, edata->blob.data, edata->blob.size, flags); else return PPK_UNKNOWN_ENTRY_TYPE; } extern "C" ppk_error removeEntry(const ppk_entry* entry, unsigned int flags) { QString generatedKey; if (generateKey(entry, generatedKey) == PPK_FALSE) return PPK_UNKNOWN_ENTRY_TYPE; return removePassword(generatedKey, flags); } extern "C" ppk_boolean entryExists(const ppk_entry* entry, unsigned int flags) { QString generatedKey; if (generateKey(entry, generatedKey) == PPK_FALSE) return PPK_FALSE; return passwordExists(generatedKey, flags)==PPK_OK?PPK_TRUE:PPK_FALSE; } extern "C" unsigned int maxDataSize(ppk_data_type type) { switch(type) { case ppk_string: return -1; case ppk_blob: return -1; } return 0; }
#include "ppasskeeper.h" #include "tokenizer.h" #include "list_pwd.h" #include <string> #include <iostream> #include <kwallet.h> #include <kapplication.h> #include <kcmdlineargs.h> #include <kaboutdata.h> #include <klocale.h> //plugin data KWallet::Wallet* _wallet; KApplication *_app; //local functions bool init_kde_lazy() { static bool initialized = false; if (! initialized) { if (! KApplication::instance()) { static char kdeAppName[] = "ppasskeeper-kwallet"; int argc = 1; char *argv[2] = { kdeAppName, NULL }; QByteArray qbApp(kdeAppName); KAboutData about(qbApp, qbApp, KLocalizedString(),QByteArray("1.0")); KCmdLineArgs::init(argc, argv, &about); if (! qApp) _app = new KApplication(true); } initialized = true; } } extern "C" void constructor() { //lazy initialization _wallet=NULL; _app=NULL; } extern "C" void destructor() { //It crashes the application to uncomment the following :s /*delete _wallet; delete _app;*/ } extern "C" ppk_boolean isWritable() { return PPK_TRUE; } extern "C" ppk_security_level securityLevel(const char* module_id) { return ppk_sec_safe; } //Get available flags extern "C" unsigned int readFlagsAvailable() { return ppk_rf_none|ppk_rf_silent; } extern "C" unsigned int writeFlagsAvailable() { return ppk_wf_none|ppk_wf_silent; } extern "C" unsigned int listingFlagsAvailable() { return ppk_lf_none|ppk_lf_silent; } KWallet::Wallet* openWallet(unsigned int flags) { init_kde_lazy(); bool initialised=KWallet::Wallet::isOpen(KWallet::Wallet::NetworkWallet()); if (!initialised && ((flags & ppk_lf_silent)!=0 || (flags & ppk_rf_silent)!=0 || (flags & ppk_wf_silent)!=0)) { //continue only if it won't annoy people who don't want to be prompted return NULL; } if (_wallet == NULL) { //lazy init _wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(), NULL); if (_wallet == NULL) { return NULL; } } if (! KWallet::Wallet::isOpen(KWallet::Wallet::NetworkWallet())) { //is the wallet still open? if not, try to reinitialize it delete _wallet; _wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),0); if (_wallet == NULL) { return NULL; } } if(! _wallet->setFolder(QString::fromAscii("PPassKeeper"))) { _wallet->createFolder(QString::fromAscii("PPassKeeper")); if(! _wallet->setFolder(QString::fromAscii("PPassKeeper"))) return NULL; } return _wallet; } ppk_error getPassword(const QString key, ppk_data** edata, unsigned int flags) { QString pwd; KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { //Get the password if(wallet->readPassword(key, pwd)==0) { *edata=ppk_string_data_new(qPrintable(pwd)); return PPK_OK; } else return PPK_ENTRY_UNAVAILABLE; } else return PPK_CANNOT_OPEN_PASSWORD_MANAGER; } ppk_error getBlob(const QString key, ppk_data** edata, unsigned int flags) { static QByteArray blob; KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { if(wallet->readEntry(key, blob)==0) { *edata=ppk_blob_data_new(blob, blob.size()); return PPK_OK; } else return PPK_ENTRY_UNAVAILABLE; } else return PPK_CANNOT_OPEN_PASSWORD_MANAGER; } ppk_error setPassword(const QString key, const char* pwd, unsigned int flags) { KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { //Set the password if(wallet->writePassword(key, QString::fromUtf8(pwd))==0) return PPK_OK; else return PPK_ENTRY_UNAVAILABLE; } else return PPK_CANNOT_OPEN_PASSWORD_MANAGER; } ppk_error setBlob(const QString key, const void *data, unsigned long size, unsigned int flags) { KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { //Set the password QByteArray blobData((const char *) data, size); if(wallet->writeEntry(key, blobData)==0) return PPK_OK; else return PPK_ENTRY_UNAVAILABLE; } else return PPK_CANNOT_OPEN_PASSWORD_MANAGER; } ppk_error removePassword(const QString key, unsigned int flags) { KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { //Set the password if(wallet->removeEntry(key)==0) return PPK_OK; else return PPK_ENTRY_UNAVAILABLE; } else return PPK_CANNOT_OPEN_PASSWORD_MANAGER; } bool passwordExists(const QString key, unsigned int flags) { static QString pwd; KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { //Get the password if(wallet->hasEntry(key)==0) return true; else return false; } else return false; } //functions extern "C" const char* getModuleID() { return "KWallet4"; } extern "C" const char* getModuleName() { return "KWallet - Store it into KDE's Wallet"; } extern "C" const int getABIVersion() { return 1; } extern "C" unsigned int getEntryListCount(unsigned int entry_types, unsigned int flags) { //Open the wallet KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { return ListPwd::getEntryListCount(wallet, entry_types, flags); } else return 0; } extern "C" ppk_error getEntryList(unsigned int entry_types, ppk_entry*** entryList, size_t* nbEntries, unsigned int flags) { //Open the wallet KWallet::Wallet* wallet=openWallet(flags); if(wallet!=NULL) { *entryList = ListPwd::getEntryList(wallet, entry_types, flags, nbEntries); return PPK_OK; } else return PPK_CANNOT_OPEN_PASSWORD_MANAGER; } static bool generateKey(const ppk_entry* entry, QString &generatedKey) { size_t size=ppk_key_length(entry); if(size>0) { char* buf=new char[size+1]; ppk_boolean ret=ppk_get_key(entry, buf, size); if(ret==PPK_TRUE) generatedKey=QString::fromUtf8(buf); else std::cerr << "generateKey: invalid ppk_get_key" << std::endl; delete[] buf; return ret; } else { std::cerr << "generateKey: invalid ppk_key_length" << std::endl; return PPK_FALSE; } } extern "C" ppk_error getEntry(const ppk_entry* entry, ppk_data **edata, unsigned int flags) { QString generatedKey; if (generateKey(entry, generatedKey) == PPK_FALSE) return PPK_UNKNOWN_ENTRY_TYPE; KWallet::Wallet *wallet = openWallet(flags); if (wallet == NULL) return PPK_CANNOT_OPEN_PASSWORD_MANAGER; KWallet::Wallet::EntryType entryType = wallet->entryType(generatedKey); if (entryType == KWallet::Wallet::Password) return getPassword(generatedKey, edata, flags); else if (entryType == KWallet::Wallet::Stream) return getBlob(generatedKey, edata, flags); else return PPK_UNKNOWN_ENTRY_TYPE; } extern "C" ppk_error setEntry(const ppk_entry* entry, const ppk_data* edata, unsigned int flags) { QString generatedKey; if (generateKey(entry, generatedKey) == PPK_FALSE) return PPK_UNKNOWN_ENTRY_TYPE; if (edata->type == ppk_string) return setPassword(generatedKey, edata->string, flags); else if (edata->type == ppk_blob) return setBlob(generatedKey, edata->blob.data, edata->blob.size, flags); else return PPK_UNKNOWN_ENTRY_TYPE; } extern "C" ppk_error removeEntry(const ppk_entry* entry, unsigned int flags) { QString generatedKey; if (generateKey(entry, generatedKey) == PPK_FALSE) return PPK_UNKNOWN_ENTRY_TYPE; return removePassword(generatedKey, flags); } extern "C" ppk_boolean entryExists(const ppk_entry* entry, unsigned int flags) { QString generatedKey; if (generateKey(entry, generatedKey) == PPK_FALSE) return PPK_FALSE; return passwordExists(generatedKey, flags)==PPK_OK?PPK_TRUE:PPK_FALSE; } extern "C" unsigned int maxDataSize(ppk_data_type type) { switch(type) { case ppk_string: return -1; case ppk_blob: return -1; } return 0; }
Fix a clang warning. We should have had a bug here
KWallet: Fix a clang warning. We should have had a bug here
C++
lgpl-2.1
mupuf/PPassKeeper,mupuf/PPassKeeper,mupuf/PPassKeeper
48fddc500a9f8a1c19f894b8d0e6ad40145764b3
quadrotor_local_planner/src/apf_planner.cpp
quadrotor_local_planner/src/apf_planner.cpp
#include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/PointCloud.h> #include <sensor_msgs/point_cloud_conversion.h> #include <tf/transform_listener.h> #include <string> #include <math.h> #include "dmath/geometry.h" class ArtificialPotentialField{ public: ArtificialPotentialField(ros::NodeHandle &node) : base_link_("base_link"), cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)), obs_sub_(node.subscribe("/camera/depth/points", 10, &ArtificialPotentialField::obstacleCallback, this)) { } void spin(){ ros::Rate r(10); ros::Duration(1).sleep(); geometry_msgs::Twist cmd; cmd.linear.z = 0.15; cmd_pub_.publish(cmd); ros::Duration(3).sleep(); cmd.linear.z = 0; cmd_pub_.publish(cmd); ros::Duration(3).sleep(); const double force = 0.025; while(ros::ok()){ dmath::Vector3D Fs; Fs += get_potential_force(obs_, 0, 3, 1, 2.0); dmath::Vector3D g; Fs += get_potential_force(g, 2, 0, 1.5, 1); dmath::Vector3D vel = Fs * force; cmd.linear.x = Fs.y * force; cmd.linear.y = Fs.x * force; ROS_INFO("obs = (%f, %f)", obs_.x, obs_.y); ROS_INFO_STREAM("cmd = " << cmd); cmd_pub_.publish(cmd); r.sleep(); ros::spinOnce(); } } private: dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){ dmath::Vector3D u = dest_lc; u = normalize(u); const double d = magnitude(dest_lc); double U = 0; if(fabs(d) > dmath::tol){ U = -A/pow(d, n) + B/pow(d, m); } return U * u; } void obstacleCallback(const sensor_msgs::PointCloud2Ptr &obs_msg){ sensor_msgs::PointCloud obs_lsr, obs_base; sensor_msgs::convertPointCloud2ToPointCloud(*obs_msg, obs_lsr); tf_listener_.transformPointCloud(obs_lsr.header.frame_id, obs_lsr.header.stamp, obs_lsr, base_link_, obs_base); if(obs_base.points.size() == 0){ obs_.x = 0; obs_.y = 0; obs_.z = 0; return; } dmath::Vector3D min_obs; min_obs.x = obs_base.points[0].x; min_obs.y = obs_base.points[0].y; min_obs.z = obs_base.points[0].z; float min_dist = magnitude(min_obs); for(int i=1; i < obs_base.points.size(); i++){ dmath::Vector3D obs; obs.x = obs_base.points[i].x; obs.y = obs_base.points[i].y; obs.z = obs_base.points[i].z; //ROS_INFO("(%f, %f)", obs[0], obs[1]); double dist = magnitude(obs); if(dist < min_dist){ min_obs.x = obs.x; min_obs.y = obs.y; min_obs.z = obs.z; min_dist = dist; } } obs_.x = min_obs.x; obs_.y = min_obs.y; obs_.z = min_obs.z; } dmath::Vector3D obs_; ros::Publisher cmd_pub_; ros::Subscriber obs_sub_; tf::TransformListener tf_listener_; std::string base_link_; }; int main(int argc, char *argv[]){ ros::init(argc, argv, "apf_planner"); ros::NodeHandle node; ArtificialPotentialField apf(node); apf.spin(); return 0; }
#include <ros/ros.h> #include <geometry_msgs/Twist.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_msgs/PointCloud.h> #include <sensor_msgs/point_cloud_conversion.h> #include <tf/transform_listener.h> #include <string> #include <math.h> #include <vector> #include "dmath/geometry.h" class ArtificialPotentialField{ public: ArtificialPotentialField(ros::NodeHandle &node) : base_link_("base_link"), cmd_pub_(node.advertise<geometry_msgs::Twist>("cmd_vel", 10)), obs_sub_(node.subscribe("/camera/depth/points", 10, &ArtificialPotentialField::obstacleCallback, this)) { } void spin(){ ros::Rate r(10); ros::Duration(1).sleep(); geometry_msgs::Twist cmd; cmd.linear.z = 0.15; cmd_pub_.publish(cmd); ros::Duration(3).sleep(); cmd.linear.z = 0; cmd_pub_.publish(cmd); ros::Duration(3).sleep(); const double force = 0.025; while(ros::ok()){ dmath::Vector3D Fs; for(int i=0; i < obstacles_.size(); i++){ Fs += get_potential_force(obstacles_[i], 0, 3, 1, 2.0); } dmath::Vector3D g; Fs += get_potential_force(g, 2, 0, 1.5, 1); dmath::Vector3D vel = Fs * force; cmd.linear.x = Fs.y * force; cmd.linear.y = Fs.x * force; //ROS_INFO("obs = (%f, %f)", obs_.x, obs_.y); ROS_INFO_STREAM("cmd = " << cmd); cmd_pub_.publish(cmd); r.sleep(); ros::spinOnce(); } } private: dmath::Vector3D get_potential_force(const dmath::Vector3D &dest_lc, double A = 1, double B = 1, double n = 1, double m = 1){ dmath::Vector3D u = dest_lc; u = normalize(u); const double d = magnitude(dest_lc); double U = 0; if(fabs(d) > dmath::tol){ U = -A/pow(d, n) + B/pow(d, m); } return U * u; } void obstacleCallback(const sensor_msgs::PointCloud2Ptr &obs_msg){ sensor_msgs::PointCloud obs_lsr, obs_base; sensor_msgs::convertPointCloud2ToPointCloud(*obs_msg, obs_lsr); tf_listener_.transformPointCloud(obs_lsr.header.frame_id, obs_lsr.header.stamp, obs_lsr, base_link_, obs_base); if(obs_base.points.size() == 0){ obstacles_.clear(); return; } std::vector<dmath::Vector3D> obs_vec; for(int i=0; i < obs_base.points.size(); i++){ dmath::Vector3D obs; obs.x = obs_base.points[i].x; obs.y = obs_base.points[i].y; obs.z = obs_base.points[i].z; obs_vec.push_back(obs); } obstacles_ = obs_vec; /* dmath::Vector3D min_obs; min_obs.x = obs_base.points[0].x; min_obs.y = obs_base.points[0].y; min_obs.z = obs_base.points[0].z; float min_dist = magnitude(min_obs); for(int i=1; i < obs_base.points.size(); i++){ dmath::Vector3D obs; obs.x = obs_base.points[i].x; obs.y = obs_base.points[i].y; obs.z = obs_base.points[i].z; //ROS_INFO("(%f, %f)", obs[0], obs[1]); double dist = magnitude(obs); if(dist < min_dist){ min_obs.x = obs.x; min_obs.y = obs.y; min_obs.z = obs.z; min_dist = dist; } } obs_.x = min_obs.x; obs_.y = min_obs.y; obs_.z = min_obs.z; */ } std::vector<dmath::Vector3D> obstacles_; ros::Publisher cmd_pub_; ros::Subscriber obs_sub_; tf::TransformListener tf_listener_; std::string base_link_; }; int main(int argc, char *argv[]){ ros::init(argc, argv, "apf_planner"); ros::NodeHandle node; ArtificialPotentialField apf(node); apf.spin(); return 0; }
Use full obstacles
Use full obstacles
C++
bsd-3-clause
DaikiMaekawa/quadrotor_navigation
35f3df7e0037b5263cc83178489e67c654cb0847
src/Application/CAVEStereoModule/ExternalRenderWindow.cpp
src/Application/CAVEStereoModule/ExternalRenderWindow.cpp
// For conditions of distribution and use, see copyright notice in LICENSE #include "StableHeaders.h" #include "ExternalRenderWindow.h" #include "CoreStringUtils.h" #include <QResizeEvent> #include <QKeyEvent> #ifdef Q_WS_X11 #include <QX11Info> #endif #ifdef Q_WS_WIN #include "Win.h" #endif namespace CAVEStereo { ExternalRenderWindow::ExternalRenderWindow() { } ExternalRenderWindow::~ExternalRenderWindow() { } Ogre::RenderWindow* ExternalRenderWindow::CreateRenderWindow(const std::string &name, int width, int height, int left, int top, bool fullscreen) { bool stealparent ((parentWidget())? true : false); QWidget *nativewin ((stealparent)? parentWidget() : this); Ogre::NameValuePairList params; Ogre::String winhandle; #ifdef Q_WS_WIN // According to Ogre Docs // positive integer for W32 (HWND handle) winhandle = Ogre::StringConverter::toString ((unsigned int) (nativewin-> winId ())); //Add the external window handle parameters to the existing params set. params["externalWindowHandle"] = winhandle; #endif #ifdef Q_WS_MAC // qt docs say it's a HIViewRef on carbon, // carbon docs say HIViewGetWindow gets a WindowRef out of it #if 0 HIViewRef vref = (HIViewRef) nativewin-> winId (); WindowRef wref = HIViewGetWindow(vref); winhandle = Ogre::StringConverter::toString( (unsigned long) (HIViewGetRoot(wref))); #else // according to // http://www.ogre3d.org/forums/viewtopic.php?f=2&t=27027 does winhandle = Ogre::StringConverter::toString( (unsigned long) nativewin->winId()); #endif //Add the external window handle parameters to the existing params set. params["externalWindowHandle"] = winhandle; #endif #ifdef Q_WS_X11 // GLX - According to Ogre Docs: // poslong:posint:poslong:poslong (display*:screen:windowHandle:XVisualInfo*) QX11Info info = x11Info (); winhandle = Ogre::StringConverter::toString ((unsigned long) (info.display ())); winhandle += ":"; winhandle += Ogre::StringConverter::toString ((unsigned int) (info.screen ())); winhandle += ":"; winhandle += Ogre::StringConverter::toString ((unsigned long) nativewin-> winId()); //Add the external window handle parameters to the existing params set. params["parentWindowHandle"] = winhandle; #endif // Window position to params if (left != -1) params["left"] = ToString(left); if (top != -1) params["top"] = ToString(top); render_window_ = Ogre::Root::getSingletonPtr()-> createRenderWindow(name, width, height, fullscreen, &params); return render_window_; } void ExternalRenderWindow::ResizeWindow(int width, int height) { if (render_window_) { render_window_->resize(width, height); render_window_->windowMovedOrResized(); } } void ExternalRenderWindow::resizeEvent(QResizeEvent *e) { ResizeWindow(width(), height()); } void ExternalRenderWindow::keyPressEvent(QKeyEvent *e) { if(e->modifiers() == Qt::ControlModifier && e->key() == Qt::Key_F) { if(!isFullScreen()) { showFullScreen(); } else { showNormal(); } } } }
// For conditions of distribution and use, see copyright notice in LICENSE #include "StableHeaders.h" #include "ExternalRenderWindow.h" #include <QResizeEvent> #include <QKeyEvent> #ifdef Q_WS_X11 #include <QX11Info> #endif #ifdef Q_WS_WIN #include "Win.h" #endif namespace CAVEStereo { ExternalRenderWindow::ExternalRenderWindow() { } ExternalRenderWindow::~ExternalRenderWindow() { } Ogre::RenderWindow* ExternalRenderWindow::CreateRenderWindow(const std::string &name, int width, int height, int left, int top, bool fullscreen) { bool stealparent ((parentWidget())? true : false); QWidget *nativewin ((stealparent)? parentWidget() : this); Ogre::NameValuePairList params; Ogre::String winhandle; #ifdef Q_WS_WIN // According to Ogre Docs // positive integer for W32 (HWND handle) winhandle = Ogre::StringConverter::toString ((unsigned int) (nativewin-> winId ())); //Add the external window handle parameters to the existing params set. params["externalWindowHandle"] = winhandle; #endif #ifdef Q_WS_MAC // qt docs say it's a HIViewRef on carbon, // carbon docs say HIViewGetWindow gets a WindowRef out of it #if 0 HIViewRef vref = (HIViewRef) nativewin-> winId (); WindowRef wref = HIViewGetWindow(vref); winhandle = Ogre::StringConverter::toString( (unsigned long) (HIViewGetRoot(wref))); #else // according to // http://www.ogre3d.org/forums/viewtopic.php?f=2&t=27027 does winhandle = Ogre::StringConverter::toString( (unsigned long) nativewin->winId()); #endif //Add the external window handle parameters to the existing params set. params["externalWindowHandle"] = winhandle; #endif #ifdef Q_WS_X11 // GLX - According to Ogre Docs: // poslong:posint:poslong:poslong (display*:screen:windowHandle:XVisualInfo*) QX11Info info = x11Info (); winhandle = Ogre::StringConverter::toString ((unsigned long) (info.display ())); winhandle += ":"; winhandle += Ogre::StringConverter::toString ((unsigned int) (info.screen ())); winhandle += ":"; winhandle += Ogre::StringConverter::toString ((unsigned long) nativewin-> winId()); //Add the external window handle parameters to the existing params set. params["parentWindowHandle"] = winhandle; #endif // Window position to params if (left != -1) params["left"] = Ogre::StringConverter::toString(left); if (top != -1) params["top"] = Ogre::StringConverter::toString(top); render_window_ = Ogre::Root::getSingletonPtr()-> createRenderWindow(name, width, height, fullscreen, &params); return render_window_; } void ExternalRenderWindow::ResizeWindow(int width, int height) { if (render_window_) { render_window_->resize(width, height); render_window_->windowMovedOrResized(); } } void ExternalRenderWindow::resizeEvent(QResizeEvent *e) { ResizeWindow(width(), height()); } void ExternalRenderWindow::keyPressEvent(QKeyEvent *e) { if(e->modifiers() == Qt::ControlModifier && e->key() == Qt::Key_F) { if(!isFullScreen()) { showFullScreen(); } else { showNormal(); } } } }
Replace usage of delete ToString with Ogre::StringConverter::toString in CAVEStereoModule.
Replace usage of delete ToString with Ogre::StringConverter::toString in CAVEStereoModule.
C++
apache-2.0
realXtend/tundra,AlphaStaxLLC/tundra,pharos3d/tundra,AlphaStaxLLC/tundra,BogusCurry/tundra,jesterKing/naali,pharos3d/tundra,realXtend/tundra,jesterKing/naali,AlphaStaxLLC/tundra,jesterKing/naali,jesterKing/naali,BogusCurry/tundra,BogusCurry/tundra,jesterKing/naali,pharos3d/tundra,AlphaStaxLLC/tundra,AlphaStaxLLC/tundra,realXtend/tundra,realXtend/tundra,BogusCurry/tundra,realXtend/tundra,pharos3d/tundra,jesterKing/naali,pharos3d/tundra,BogusCurry/tundra,BogusCurry/tundra,pharos3d/tundra,AlphaStaxLLC/tundra,realXtend/tundra,jesterKing/naali
33c95fe73942307306ad6c1bbbbdcef9fee8f1ec
CList/CList2.hxx
CList/CList2.hxx
#include <memory> #include "CList2.h" #define NSCLIST nsSdD::CList<T> template<typename T> NSCLIST::CList() noexcept : m_head(std::make_shared<CNode>(T(), nullptr, nullptr)), m_tail(std::make_shared<CNode>(T(), nullptr, m_head)) { m_head->setNext(m_tail); } template<typename T> NSCLIST::CList(size_t n) noexcept : m_head(std::make_shared<CNode>(T(), nullptr, nullptr)), m_tail(std::make_shared<CNode>(T(), nullptr, m_head)) { m_head->setNext(m_tail); for (size_t i = 0; i < n; i++) { CNodePtr ptr = std::make_shared<CNode>(T(), nullptr, nullptr); ptr->setNext(m_tail); ptr->setPrevious(m_tail->getPrevious()); m_tail->getPrevious()->setNext(ptr); m_tail->setPrevious(ptr); ++m_size; } } template<typename T> NSCLIST::CList(size_t n, const T &val) noexcept : m_head(std::make_shared<CNode>(T(), nullptr, nullptr)), m_tail(std::make_shared<CNode>(T(), nullptr, m_head)) { m_head->setNext(m_tail); for (size_t i = 0; i < n; i++) { CNodePtr ptr = std::make_shared<CNode>(val, nullptr, nullptr); CNodePtr LastCreated = m_tail->getPrevious(); ptr->setNext(m_tail); ptr->setPrevious(LastCreated); LastCreated->setNext(ptr); m_tail->setPrevious(ptr); ++m_size; } } template<typename T> NSCLIST::CList(const NSCLIST &x) noexcept { m_head = x.getHead(); m_tail = x.getTail(); m_size = x.size(); for (CNodePtr p = x.getHead(); p; p = p->getNext()) { CNodePtr temp = std::make_shared<CNode>(p->getInfo(), p->getNext(), p->getPrevious()); } } template<typename T> template<class InputIterator> void NSCLIST::assign(InputIterator first, InputIterator last) { CNodePtr prec = m_head; m_size = 0; for (auto tmp = first; tmp < last; tmp++) { CNodePtr add = std::make_shared<CNode>(*tmp); prec->setNext(add); add->setPrevious(prec); add->setNext(prec->getNext()); m_tail->setPrevious(add); ++m_size; prec = add; } m_tail->setPrevious(prec); } template<typename T> void NSCLIST::assign(unsigned n, const T &val) noexcept { if (this->size() == 0) { for (size_t i = 0; i < n; i++) { CNodePtr ptr = std::make_shared<CNode>(val, nullptr, nullptr); CNodePtr LastCreated = m_tail->getPrevious(); ptr->setNext(m_tail); ptr->setPrevious(LastCreated); LastCreated->setNext(ptr); m_tail->setPrevious(ptr); ++m_size; } } } template<typename T> template <class... Args> void NSCLIST::emplace_front(Args&&... val) noexcept { CNodePtr ptr = std::make_shared<CNode>(val..., nullptr, nullptr); ptr->setPrevious(m_head); ptr->setNext(m_head->getNext()); (m_head->getNext())->setPrevious(ptr); m_head->setNext(ptr); ++m_size; } template<typename T> void NSCLIST::pop_front() noexcept { CNodePtr del = m_head->getNext(); if(del != m_tail) { CNodePtr a = del->getNext(); m_head->setNext(a); a->setPrevious(m_head); del->setPrevious(nullptr); del->setNext(nullptr); --m_size; } else { m_size = 0; } } template<typename T> void NSCLIST::push_front(const T &x) noexcept { CNodePtr add = std::make_shared<CNode>(x, nullptr, nullptr); add->setNext(m_head->getNext()); add->setPrevious(m_head); add->getNext()->setPrevious(add); m_head->setNext(add); ++m_size; } template<typename T> void NSCLIST::push_back(const T &x) noexcept { CNodePtr add = std::make_shared<CNode>(x, nullptr, nullptr); CNodePtr LastCreated = m_tail->getPrevious(); add->setNext(m_tail); add->setPrevious(LastCreated); LastCreated->setNext(add); m_tail->setPrevious(add); ++m_size; } template<typename T> void NSCLIST::pop_back() noexcept { CNodePtr del = m_tail->getPrevious(); m_tail->setPrevious(del->getPrevious()); del->getPrevious()->setNext(m_tail); del->setPrevious(nullptr); del->setNext(nullptr); --m_size; } template<typename T> void NSCLIST::emplace(CNodePtr Prec, T val) noexcept { CNodePtr add = std::make_shared<CNode>(val, Prec, Prec->getNext()); Prec->getNext()->setPrevious(add); Prec->setNext(add); ++m_size; } template<typename T> typename NSCLIST::iterator NSCLIST::erase(NSCLIST::iterator del) noexcept { del->getNext()->setPrevious(del->getPrevious()); del->getPrevious()->setNext(del->getNext()); --m_size; return NSCLIST::iterator(del->getNext()); } template<typename T> void NSCLIST::resize(unsigned n, const T &val /*= T()*/) noexcept { if (m_size == n) return; if (m_size > n) { CNodePtr ptr = m_head; for (size_t i = 0; i < n; ++i) ptr = ptr->getNext(); ptr->setNext(m_tail); m_tail->setPrevious(ptr); m_size = n; return; } CNodePtr ptr = m_head; for (size_t i = 0; i < m_size; ++i) ptr = ptr->getNext(); for (size_t i = 0; i < n - m_size; ++i) { CNodePtr add = std::make_shared<CNode>(val, ptr, ptr->getNext()); ptr->setNext(add); m_tail->setPrevious(add); ptr = add; } m_size = n; } template<typename T> void NSCLIST::swap(NSCLIST &x) noexcept { CNodePtr ptr = m_head; m_head->setNext(x.getHead()->getNext()); x.getHead()->setNext(ptr->getNext()); ptr = m_tail; m_tail->setPrevious(x.getTail()->getPrevious()); x.getTail()->setPrevious(ptr->getPrevious()); size_t tmp = m_size; m_size = x.size(); x.m_size = tmp; } template<typename T> void NSCLIST::clear() noexcept { m_head->setNext(m_tail); m_tail->setPrevious(m_head); m_size = 0; } template<typename T> void NSCLIST::remove(const T &val) noexcept { for (CNodePtr a = m_head; a; a = a->getNext()) { if (a->getInfo() == val) { (a->getPrevious())->setNext(a->getNext()); (a->getNext())->setPrevious(a->getPrevious()); a->setNext(nullptr); a->setPrevious(nullptr); return; } } } template<typename T> template<class Predicate> void NSCLIST::remove_if(Predicate pred) noexcept { for (CNodePtr a = m_head; a; a = a->getNext()) { if (!pred(a)) { (a->getPrevious())->setNext(a->getNext()); (a->getNext())->setPrevious(a->getPrevious()); a->setNext(nullptr); a->setPrevious(nullptr); } } } template<typename T> void NSCLIST::reverse() noexcept { CNodePtr tmp = m_head; m_head->setNext(m_tail->getPrevious()); m_tail->setPrevious(tmp->getNext()); for (size_t i = 0; i < m_size; ++i) { CNodePtr ptr = tmp->getNext()->getPrevious(); tmp->getNext()->setPrevious(tmp->getNext()->getNext()); tmp->getNext()->setNext(ptr); tmp = tmp->getNext(); } } template<typename T> void NSCLIST::emplace_back(T val) noexcept { CNodePtr a = std::make_shared<CNode>(val, m_tail->getPrevious(), m_tail); (m_tail->getPrevious())->setNext(a); m_tail->setPrevious(a); ++m_size; } template<typename T> typename NSCLIST::iterator NSCLIST::insert(typename NSCLIST::iterator position, T const &val) noexcept { CNodePtr tmp = std::make_shared<CNode>(val); tmp->setNext(position.getNode()); tmp->setPrevious(position->getPrevious()); (position->getPrevious())->setNext(tmp); position->setPrevious(tmp); ++m_size; return NSCLIST::iterator(tmp); }
#include <memory> #include "CList2.h" #define NSCLIST nsSdD::CList<T> template<typename T> NSCLIST::CList() noexcept : m_head(std::make_shared<CNode>(T(), nullptr, nullptr)), m_tail(std::make_shared<CNode>(T(), nullptr, m_head)) { m_head->setNext(m_tail); } template<typename T> NSCLIST::CList(size_t n) noexcept : m_head(std::make_shared<CNode>(T(), nullptr, nullptr)), m_tail(std::make_shared<CNode>(T(), nullptr, m_head)) { m_head->setNext(m_tail); for (size_t i = 0; i < n; i++) { CNodePtr ptr = std::make_shared<CNode>(T(), nullptr, nullptr); ptr->setNext(m_tail); ptr->setPrevious(m_tail->getPrevious()); m_tail->getPrevious()->setNext(ptr); m_tail->setPrevious(ptr); ++m_size; } } template<typename T> NSCLIST::CList(size_t n, const T &val) noexcept : m_head(std::make_shared<CNode>(T(), nullptr, nullptr)), m_tail(std::make_shared<CNode>(T(), nullptr, m_head)) { m_head->setNext(m_tail); for (size_t i = 0; i < n; i++) { CNodePtr ptr = std::make_shared<CNode>(val, nullptr, nullptr); CNodePtr LastCreated = m_tail->getPrevious(); ptr->setNext(m_tail); ptr->setPrevious(LastCreated); LastCreated->setNext(ptr); m_tail->setPrevious(ptr); ++m_size; } } template<typename T> NSCLIST::CList(const NSCLIST &x) noexcept { m_head = x.getHead(); m_tail = x.getTail(); m_size = x.size(); for (CNodePtr p = x.getHead(); p; p = p->getNext()) { CNodePtr temp = std::make_shared<CNode>(p->getInfo(), p->getNext(), p->getPrevious()); } } template<typename T> template<class InputIterator> void NSCLIST::assign(InputIterator first, InputIterator last) { CNodePtr prec = m_head; m_size = 0; for (auto tmp = first; tmp < last; tmp++) { CNodePtr add = std::make_shared<CNode>(*tmp); prec->setNext(add); add->setPrevious(prec); add->setNext(prec->getNext()); m_tail->setPrevious(add); ++m_size; prec = add; } m_tail->setPrevious(prec); } template<typename T> void NSCLIST::assign(unsigned n, const T &val) noexcept { if (this->size() == 0) { for (size_t i = 0; i < n; i++) { CNodePtr ptr = std::make_shared<CNode>(val, nullptr, nullptr); CNodePtr LastCreated = m_tail->getPrevious(); ptr->setNext(m_tail); ptr->setPrevious(LastCreated); LastCreated->setNext(ptr); m_tail->setPrevious(ptr); ++m_size; } } } template<typename T> template <class... Args> void NSCLIST::emplace_front(Args&&... val) noexcept { CNodePtr ptr = std::make_shared<CNode>(val..., nullptr, nullptr); ptr->setPrevious(m_head); ptr->setNext(m_head->getNext()); (m_head->getNext())->setPrevious(ptr); m_head->setNext(ptr); ++m_size; } template<typename T> void NSCLIST::pop_front() noexcept { CNodePtr del = m_head->getNext(); if(del != m_tail) { CNodePtr a = del->getNext(); m_head->setNext(a); a->setPrevious(m_head); del->setPrevious(nullptr); del->setNext(nullptr); --m_size; } else { m_size = 0; } } template<typename T> void NSCLIST::push_front(const T &x) noexcept { CNodePtr add = std::make_shared<CNode>(x, nullptr, nullptr); add->setNext(m_head->getNext()); add->setPrevious(m_head); add->getNext()->setPrevious(add); m_head->setNext(add); ++m_size; } template<typename T> void NSCLIST::push_back(const T &x) noexcept { CNodePtr add = std::make_shared<CNode>(x, nullptr, nullptr); CNodePtr LastCreated = m_tail->getPrevious(); add->setNext(m_tail); add->setPrevious(LastCreated); LastCreated->setNext(add); m_tail->setPrevious(add); ++m_size; } template<typename T> void NSCLIST::pop_back() noexcept { CNodePtr del = m_tail->getPrevious(); m_tail->setPrevious(del->getPrevious()); del->getPrevious()->setNext(m_tail); del->setPrevious(nullptr); del->setNext(nullptr); --m_size; } template<typename T> void NSCLIST::emplace(CNodePtr Prec, T val) noexcept { CNodePtr add = std::make_shared<CNode>(val, Prec, Prec->getNext()); Prec->getNext()->setPrevious(add); Prec->setNext(add); ++m_size; } template<typename T> typename NSCLIST::iterator NSCLIST::erase(NSCLIST::iterator del) noexcept { del->getNext()->setPrevious(del->getPrevious()); del->getPrevious()->setNext(del->getNext()); --m_size; return NSCLIST::iterator(del->getNext()); } template<typename T> void NSCLIST::resize(unsigned n, const T &val /*= T()*/) noexcept { if (m_size == n) return; if (m_size > n) { CNodePtr ptr = m_head; for (size_t i = 0; i < n; ++i) ptr = ptr->getNext(); ptr->setNext(m_tail); m_tail->setPrevious(ptr); m_size = n; return; } CNodePtr ptr = m_head; for (size_t i = 0; i < m_size; ++i) ptr = ptr->getNext(); for (size_t i = 0; i < n - m_size; ++i) { CNodePtr add = std::make_shared<CNode>(val, ptr, ptr->getNext()); ptr->setNext(add); m_tail->setPrevious(add); ptr = add; } m_size = n; } template<typename T> void NSCLIST::swap(NSCLIST &x) noexcept { CNodePtr ptr = m_head->getNext(); m_head->setNext(x.getHead()->getNext()); x.getHead()->setNext(ptr); ptr = m_tail->getPrevious(); m_tail->setPrevious(x.getTail()->getPrevious()); x.getTail()->setPrevious(ptr); size_t tmp = m_size; m_size = x.size(); x.m_size = tmp; } template<typename T> void NSCLIST::clear() noexcept { m_head->setNext(m_tail); m_tail->setPrevious(m_head); m_size = 0; } template<typename T> void NSCLIST::remove(const T &val) noexcept { for (CNodePtr a = m_head; a; a = a->getNext()) { if (a->getInfo() == val) { (a->getPrevious())->setNext(a->getNext()); (a->getNext())->setPrevious(a->getPrevious()); a->setNext(nullptr); a->setPrevious(nullptr); return; } } } template<typename T> template<class Predicate> void NSCLIST::remove_if(Predicate pred) noexcept { for (CNodePtr a = m_head; a; a = a->getNext()) { if (!pred(a)) { (a->getPrevious())->setNext(a->getNext()); (a->getNext())->setPrevious(a->getPrevious()); a->setNext(nullptr); a->setPrevious(nullptr); } } } template<typename T> void NSCLIST::reverse() noexcept { CNodePtr tmp = m_head; m_head->setNext(m_tail->getPrevious()); m_tail->setPrevious(tmp->getNext()); for (size_t i = 0; i < m_size; ++i) { CNodePtr ptr = tmp->getNext()->getPrevious(); tmp->getNext()->setPrevious(tmp->getNext()->getNext()); tmp->getNext()->setNext(ptr); tmp = tmp->getNext(); } } template<typename T> void NSCLIST::emplace_back(T val) noexcept { CNodePtr a = std::make_shared<CNode>(val, m_tail->getPrevious(), m_tail); (m_tail->getPrevious())->setNext(a); m_tail->setPrevious(a); ++m_size; } template<typename T> typename NSCLIST::iterator NSCLIST::insert(typename NSCLIST::iterator position, T const &val) noexcept { CNodePtr tmp = std::make_shared<CNode>(val); tmp->setNext(position.getNode()); tmp->setPrevious(position->getPrevious()); (position->getPrevious())->setNext(tmp); position->setPrevious(tmp); ++m_size; return NSCLIST::iterator(tmp); }
fix swap
fix swap
C++
mit
SKNZ/swagplusplus,SKNZ/swagplusplus
3e0aa263a610f0d827859a594ee9b7486ddb8fca
src/lib/parse.cpp
src/lib/parse.cpp
#define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS // #define BOOST_SPIRIT_QI_DEBUG #include <boost/foreach.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/spirit/include/phoenix_function.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/support_istream_iterator.hpp> #include <cassert> #include <sstream> #include "formast.hpp" // upgrade structs to fusion sequences BOOST_FUSION_ADAPT_STRUCT( formast::Attr, (std::string, class_name) (std::string, name) (boost::optional<formast::Doc>, doc) ) BOOST_FUSION_ADAPT_STRUCT( formast::Class, (std::string, name) (boost::optional<std::string>, base_name) (boost::optional<formast::Doc>, doc) (boost::optional<formast::Stats>, stats) ) BOOST_FUSION_ADAPT_STRUCT( formast::If, (formast::Expr, expr) (formast::Stats, stats) ) BOOST_FUSION_ADAPT_STRUCT( formast::IfElifsElse, (std::vector<formast::If>, ifs_) (boost::optional<formast::Stats>, else_) ) // a few shorthands namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; namespace ast = formast::detail::ast; // phoenix functions for constructing the abstract syntax tree with // semantic actions template <typename T> // T is a terminal type, i.e. uint64_t or std::string struct copy_func { template <typename T1, typename T2 = void> struct result { typedef void type; }; void operator()(ast::Expr & left, ast::Expr const & right) const { assert(right != 0); left = right; } }; template <typename T> // T is a terminal type, i.e. uint64_t or std::string struct assign_func { template <typename T1, typename T2 = void> struct result { typedef void type; }; void operator()(ast::Expr & left, const T & right) const { left = ast::Expr(new ast::ExprNode(right)); } }; template <char Op> struct binary_func { template <typename T1, typename T2 = void> struct result { typedef void type; }; void operator()(ast::Expr & left, ast::Expr const & right) const { assert(left != 0); assert(right != 0); left = ast::Expr(new ast::ExprNode(ast::binary_op(Op, left, right))); } }; template <char Op> struct unary_func { template <typename T1, typename T2 = void> struct result { typedef void type; }; void operator()(ast::Expr & left, ast::Expr & right) const { assert(right != 0); left = ast::Expr(new ast::ExprNode(ast::unary_op(Op, right))); } }; boost::phoenix::function<binary_func<'+'> > const _add; boost::phoenix::function<binary_func<'-'> > const _sub; boost::phoenix::function<binary_func<'*'> > const _mul; boost::phoenix::function<binary_func<'/'> > const _div; boost::phoenix::function<unary_func<'+'> > const _pos; boost::phoenix::function<unary_func<'-'> > const _neg; boost::phoenix::function<assign_func<boost::uint64_t> > const _uint; boost::phoenix::function<copy_func<boost::uint64_t> > const _copy; // error handler struct error_handler_ { template <typename, typename, typename> struct result { typedef void type; }; template <typename Iterator> void operator()( qi::info const& what, Iterator err_pos, Iterator last) const { std::cerr << "Error! Expecting " << what << " here: \"" << std::string(err_pos, last) << "\"" << std::endl ; } }; boost::phoenix::function<error_handler_> const error_handler = error_handler_(); // the actual grammar template <typename Iterator> struct expr_grammar : qi::grammar<Iterator, ast::Expr(), ascii::space_type> { expr_grammar() : expr_grammar::base_type(expr) { qi::char_type char_; qi::uint_type uint_; qi::_val_type _val; qi::_1_type _1; qi::_2_type _2; qi::_3_type _3; qi::_4_type _4; using qi::on_error; using qi::fail; expr = term [_copy(_val, _1)] >> *( ('+' > term [_add(_val, _1)]) | ('-' > term [_sub(_val, _1)]) ) ; term = factor [_copy(_val, _1)] >> *( ('*' > factor [_mul(_val, _1)]) | ('/' > factor [_div(_val, _1)]) ) ; factor = uint_ [_uint(_val, _1)] | '(' > expr [_copy(_val, _1)] > ')' | ('-' > factor [_neg(_val, _1)]) | ('+' > factor [_pos(_val, _1)]) ; // Debugging and error handling and reporting support. BOOST_SPIRIT_DEBUG_NODE(expr); BOOST_SPIRIT_DEBUG_NODE(term); BOOST_SPIRIT_DEBUG_NODE(factor); // Error handling on_error<fail>(expr, error_handler(_4, _3, _2)); } qi::rule<Iterator, ast::Expr(), ascii::space_type> expr, term, factor; }; // helper function for parsing expression from stream void _expr_parse_stream(std::istream & is, ast::Expr & e) { // disable white space skipping is.unsetf(std::ios::skipws); typedef boost::spirit::istream_iterator iterator_type; iterator_type iter(is); iterator_type end; expr_grammar<iterator_type> grammar; ascii::space_type space; bool success = qi::phrase_parse(iter, end, grammar, space, e); if (!success) { throw std::runtime_error("Syntax error."); } if (iter != end) { throw std::runtime_error("End of stream not reached."); } } // helper function for parsing expression from string void _expr_parse_string(std::string const & s, ast::Expr & e) { std::istringstream is(s); _expr_parse_stream(is, e); } formast::Parser::Parser() { } void formast::Parser::parse_string(std::string const & s, ast::Top & top) { std::istringstream is(s); parse_stream(is, top); } formast::XmlParser::XmlParser() : Parser() { } void formast::XmlParser::parse_stream(std::istream & is, ast::Top & top) { // disable skipping of whitespace is.unsetf(std::ios::skipws); // read xml into property tree boost::property_tree::ptree pt; boost::property_tree::xml_parser::read_xml(is, pt); //boost::property_tree::info_parser::write_info(std::cout, pt); // DEBUG BOOST_FOREACH(boost::property_tree::ptree::value_type & decl, pt.get_child("niftoolsxml")) { if (decl.first == "basic") { Class class_; class_.name = decl.second.get<std::string>("<xmlattr>.name"); class_.doc = decl.second.data(); top.push_back(class_); } else if (decl.first == "compound" || decl.first == "niobject") { Class class_; class_.name = decl.second.get<std::string>("<xmlattr>.name"); Doc doc = decl.second.data(); if (!doc.empty()) { class_.doc = doc; } class_.base_name = decl.second.get_optional<std::string>("<xmlattr>.inherit"); ast::Stats stats; BOOST_FOREACH(boost::property_tree::ptree::value_type & add, decl.second) { if (add.first == "add") { Attr attr; attr.class_name = add.second.get<std::string>("<xmlattr>.type"); attr.name = add.second.get<std::string>("<xmlattr>.name"); Doc doc = add.second.data(); if (!doc.empty()) { attr.doc = doc; } boost::optional<std::string> cond = add.second.get_optional<std::string>("<xmlattr>.cond"); if (!cond) { stats.push_back(attr); } else { formast::IfElifsElse ifelifselse; formast::If if_; _expr_parse_string(cond.get(), if_.expr); if_.stats.push_back(attr); ifelifselse.ifs_.push_back(if_); stats.push_back(ifelifselse); } }; }; if (!stats.empty()) { class_.stats = stats; }; top.push_back(class_); }; }; }
#define BOOST_SPIRIT_NO_PREDEFINED_TERMINALS // #define BOOST_SPIRIT_QI_DEBUG #include <boost/algorithm/string.hpp> #include <boost/foreach.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/spirit/include/phoenix_function.hpp> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/support_istream_iterator.hpp> #include <cassert> #include <sstream> #include "formast.hpp" // upgrade structs to fusion sequences BOOST_FUSION_ADAPT_STRUCT( formast::Attr, (std::string, class_name) (std::string, name) (boost::optional<formast::Doc>, doc) ) BOOST_FUSION_ADAPT_STRUCT( formast::Class, (std::string, name) (boost::optional<std::string>, base_name) (boost::optional<formast::Doc>, doc) (boost::optional<formast::Stats>, stats) ) BOOST_FUSION_ADAPT_STRUCT( formast::If, (formast::Expr, expr) (formast::Stats, stats) ) BOOST_FUSION_ADAPT_STRUCT( formast::IfElifsElse, (std::vector<formast::If>, ifs_) (boost::optional<formast::Stats>, else_) ) // a few shorthands namespace qi = boost::spirit::qi; namespace ascii = boost::spirit::ascii; namespace ast = formast::detail::ast; // phoenix functions for constructing the abstract syntax tree with // semantic actions template <typename T> // T is a terminal type, i.e. uint64_t or std::string struct copy_func { template <typename T1, typename T2 = void> struct result { typedef void type; }; void operator()(ast::Expr & left, ast::Expr const & right) const { assert(right != 0); left = right; } }; template <typename T> // T is a terminal type, i.e. uint64_t or std::string struct assign_func { template <typename T1, typename T2 = void> struct result { typedef void type; }; void operator()(ast::Expr & left, const T & right) const { left = ast::Expr(new ast::ExprNode(right)); } }; template <char Op> struct binary_func { template <typename T1, typename T2 = void> struct result { typedef void type; }; void operator()(ast::Expr & left, ast::Expr const & right) const { assert(left != 0); assert(right != 0); left = ast::Expr(new ast::ExprNode(ast::binary_op(Op, left, right))); } }; template <char Op> struct unary_func { template <typename T1, typename T2 = void> struct result { typedef void type; }; void operator()(ast::Expr & left, ast::Expr & right) const { assert(right != 0); left = ast::Expr(new ast::ExprNode(ast::unary_op(Op, right))); } }; boost::phoenix::function<binary_func<'+'> > const _add; boost::phoenix::function<binary_func<'-'> > const _sub; boost::phoenix::function<binary_func<'*'> > const _mul; boost::phoenix::function<binary_func<'/'> > const _div; boost::phoenix::function<unary_func<'+'> > const _pos; boost::phoenix::function<unary_func<'-'> > const _neg; boost::phoenix::function<assign_func<boost::uint64_t> > const _uint; boost::phoenix::function<copy_func<boost::uint64_t> > const _copy; // error handler struct error_handler_ { template <typename, typename, typename> struct result { typedef void type; }; template <typename Iterator> void operator()( qi::info const& what, Iterator err_pos, Iterator last) const { std::cerr << "Error! Expecting " << what << " here: \"" << std::string(err_pos, last) << "\"" << std::endl ; } }; boost::phoenix::function<error_handler_> const error_handler = error_handler_(); // the actual grammar template <typename Iterator> struct expr_grammar : qi::grammar<Iterator, ast::Expr(), ascii::space_type> { expr_grammar() : expr_grammar::base_type(expr) { qi::char_type char_; qi::uint_type uint_; qi::_val_type _val; qi::_1_type _1; qi::_2_type _2; qi::_3_type _3; qi::_4_type _4; using qi::on_error; using qi::fail; expr = term [_copy(_val, _1)] >> *( ('+' > term [_add(_val, _1)]) | ('-' > term [_sub(_val, _1)]) ) ; term = factor [_copy(_val, _1)] >> *( ('*' > factor [_mul(_val, _1)]) | ('/' > factor [_div(_val, _1)]) ) ; factor = uint_ [_uint(_val, _1)] | '(' > expr [_copy(_val, _1)] > ')' | ('-' > factor [_neg(_val, _1)]) | ('+' > factor [_pos(_val, _1)]) ; // Debugging and error handling and reporting support. BOOST_SPIRIT_DEBUG_NODE(expr); BOOST_SPIRIT_DEBUG_NODE(term); BOOST_SPIRIT_DEBUG_NODE(factor); // Error handling on_error<fail>(expr, error_handler(_4, _3, _2)); } qi::rule<Iterator, ast::Expr(), ascii::space_type> expr, term, factor; }; // helper function for parsing expression from stream void _expr_parse_stream(std::istream & is, ast::Expr & e) { // disable white space skipping is.unsetf(std::ios::skipws); typedef boost::spirit::istream_iterator iterator_type; iterator_type iter(is); iterator_type end; expr_grammar<iterator_type> grammar; ascii::space_type space; bool success = qi::phrase_parse(iter, end, grammar, space, e); if (!success) { throw std::runtime_error("Syntax error."); } if (iter != end) { throw std::runtime_error("End of stream not reached."); } } // helper function for parsing expression from string void _expr_parse_string(std::string const & s, ast::Expr & e) { std::istringstream is(s); _expr_parse_stream(is, e); } formast::Parser::Parser() { } void formast::Parser::parse_string(std::string const & s, ast::Top & top) { std::istringstream is(s); parse_stream(is, top); } formast::XmlParser::XmlParser() : Parser() { } void formast::XmlParser::parse_stream(std::istream & is, ast::Top & top) { // disable skipping of whitespace is.unsetf(std::ios::skipws); // read xml into property tree boost::property_tree::ptree pt; boost::property_tree::xml_parser::read_xml(is, pt); //boost::property_tree::info_parser::write_info(std::cout, pt); // DEBUG BOOST_FOREACH(boost::property_tree::ptree::value_type & decl, pt.get_child("niftoolsxml")) { if (decl.first == "basic") { Class class_; class_.name = decl.second.get<std::string>("<xmlattr>.name"); std::string doc = decl.second.data(); boost::algorithm::trim(doc); if (!doc.empty()) { class_.doc = doc; } top.push_back(class_); } else if (decl.first == "compound" || decl.first == "niobject") { Class class_; class_.name = decl.second.get<std::string>("<xmlattr>.name"); std::string doc = decl.second.data(); boost::algorithm::trim(doc); class_.doc = doc; if (!doc.empty()) { class_.doc = doc; } class_.base_name = decl.second.get_optional<std::string>("<xmlattr>.inherit"); ast::Stats stats; BOOST_FOREACH(boost::property_tree::ptree::value_type & add, decl.second) { if (add.first == "add") { Attr attr; attr.class_name = add.second.get<std::string>("<xmlattr>.type"); attr.name = add.second.get<std::string>("<xmlattr>.name"); std::string doc = add.second.data(); boost::algorithm::trim(doc); if (!doc.empty()) { attr.doc = doc; } // conditioning disabled for now, can't parse it completely yet boost::optional<std::string> cond; // = add.second.get_optional<std::string>("<xmlattr>.cond"); if (!cond) { stats.push_back(attr); } else { formast::IfElifsElse ifelifselse; formast::If if_; _expr_parse_string(cond.get(), if_.expr); if_.stats.push_back(attr); ifelifselse.ifs_.push_back(if_); stats.push_back(ifelifselse); } }; }; if (!stats.empty()) { class_.stats = stats; }; top.push_back(class_); }; }; }
Trim doc strings, disable cond for now.
Trim doc strings, disable cond for now.
C++
bsd-3-clause
amorilia/formast,amorilia/formast,amorilia/formast
f664f7a2018f9442b0f828bb8e50d2b1d0cb7717
simgear/scene/model/model.cxx
simgear/scene/model/model.cxx
// model.cxx - manage a 3D aircraft model. // Written by David Megginson, started 2002. // // This file is in the Public Domain, and comes with no warranty. #ifdef HAVE_CONFIG_H #include <simgear_config.h> #endif #include <string.h> // for strcmp() #include <vector> #include <set> #include <plib/sg.h> #include <plib/ssg.h> #include <plib/ul.h> #include <simgear/structure/exception.hxx> #include <simgear/props/props.hxx> #include <simgear/props/props_io.hxx> #include "animation.hxx" #include "model.hxx" SG_USING_STD(vector); SG_USING_STD(set); bool sgUseDisplayList = true; //////////////////////////////////////////////////////////////////////// // Global state //////////////////////////////////////////////////////////////////////// static bool model_filter = true; //////////////////////////////////////////////////////////////////////// // Static utility functions. //////////////////////////////////////////////////////////////////////// static int model_filter_callback (ssgEntity * entity, int mask) { return model_filter ? 1 : 0; } /** * Callback to update an animation. */ static int animation_callback (ssgEntity * entity, int mask) { return ((SGAnimation *)entity->getUserData())->update(); } /** * Callback to restore the state after an animation. */ static int restore_callback (ssgEntity * entity, int mask) { ((SGAnimation *)entity->getUserData())->restore(); return 1; } /** * Locate a named SSG node in a branch. */ static ssgEntity * find_named_node (ssgEntity * node, const char * name) { char * node_name = node->getName(); if (node_name != 0 && !strcmp(name, node_name)) return node; else if (node->isAKindOf(ssgTypeBranch())) { int nKids = node->getNumKids(); for (int i = 0; i < nKids; i++) { ssgEntity * result = find_named_node(((ssgBranch*)node)->getKid(i), name); if (result != 0) return result; } } return 0; } /** * Splice a branch in between all child nodes and their parents. */ static void splice_branch (ssgBranch * branch, ssgEntity * child) { int nParents = child->getNumParents(); branch->addKid(child); for (int i = 0; i < nParents; i++) { ssgBranch * parent = child->getParent(i); parent->replaceKid(child, branch); } } /** * Make an offset matrix from rotations and position offset. */ void sgMakeOffsetsMatrix( sgMat4 * result, double h_rot, double p_rot, double r_rot, double x_off, double y_off, double z_off ) { sgMat4 rot_matrix; sgMat4 pos_matrix; sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot); sgMakeTransMat4(pos_matrix, x_off, y_off, z_off); sgMultMat4(*result, pos_matrix, rot_matrix); } void sgMakeAnimation( ssgBranch * model, const char * name, vector<SGPropertyNode_ptr> &name_nodes, SGPropertyNode *prop_root, SGPropertyNode_ptr node, double sim_time_sec, SGPath &texture_path, set<ssgBranch *> &ignore_branches ) { bool ignore = false; SGAnimation * animation = 0; const char * type = node->getStringValue("type", "none"); if (!strcmp("none", type)) { animation = new SGNullAnimation(node); } else if (!strcmp("range", type)) { animation = new SGRangeAnimation(prop_root, node); } else if (!strcmp("billboard", type)) { animation = new SGBillboardAnimation(node); } else if (!strcmp("select", type)) { animation = new SGSelectAnimation(prop_root, node); } else if (!strcmp("spin", type)) { animation = new SGSpinAnimation(prop_root, node, sim_time_sec ); } else if (!strcmp("timed", type)) { animation = new SGTimedAnimation(node); } else if (!strcmp("rotate", type)) { animation = new SGRotateAnimation(prop_root, node); } else if (!strcmp("translate", type)) { animation = new SGTranslateAnimation(prop_root, node); } else if (!strcmp("scale", type)) { animation = new SGScaleAnimation(prop_root, node); } else if (!strcmp("texrotate", type)) { animation = new SGTexRotateAnimation(prop_root, node); } else if (!strcmp("textranslate", type)) { animation = new SGTexTranslateAnimation(prop_root, node); } else if (!strcmp("texmultiple", type)) { animation = new SGTexMultipleAnimation(prop_root, node); } else if (!strcmp("blend", type)) { animation = new SGBlendAnimation(prop_root, node); ignore = true; } else if (!strcmp("alpha-test", type)) { animation = new SGAlphaTestAnimation(node); } else if (!strcmp("material", type)) { animation = new SGMaterialAnimation(prop_root, node, texture_path); } else if (!strcmp("flash", type)) { animation = new SGFlashAnimation(node); } else if (!strcmp("dist-scale", type)) { animation = new SGDistScaleAnimation(node); } else if (!strcmp("noshadow", type)) { animation = new SGShadowAnimation(prop_root, node); } else if (!strcmp("shader", type)) { animation = new SGShaderAnimation(prop_root, node); } else { animation = new SGNullAnimation(node); SG_LOG(SG_INPUT, SG_WARN, "Unknown animation type " << type); } if (name != 0) animation->setName((char *)name); ssgEntity * object; if (name_nodes.size() > 0) { object = find_named_node(model, name_nodes[0]->getStringValue()); if (object == 0) { SG_LOG(SG_INPUT, SG_ALERT, "Object " << name_nodes[0]->getStringValue() << " not found"); delete animation; animation = 0; } } else { object = model; } if ( animation == 0 ) return; ssgBranch * branch = animation->getBranch(); splice_branch(branch, object); for (unsigned int i = 1; i < name_nodes.size(); i++) { const char * name = name_nodes[i]->getStringValue(); object = find_named_node(model, name); if (object == 0) { SG_LOG(SG_INPUT, SG_ALERT, "Object " << name << " not found"); delete animation; animation = 0; } else { ssgBranch * oldParent = object->getParent(0); branch->addKid(object); oldParent->removeKid(object); } } if ( animation != 0 ) { animation->init(); branch->setUserData(animation); branch->setTravCallback(SSG_CALLBACK_PRETRAV, animation_callback); branch->setTravCallback(SSG_CALLBACK_POSTTRAV, restore_callback); if ( ignore ) { ignore_branches.insert( branch ); } } } static void makeDList( ssgBranch *b, const set<ssgBranch *> &ignore ) { int nb = b->getNumKids(); for (int i = 0; i<nb; i++) { ssgEntity *e = b->getKid(i); if (e->isAKindOf(ssgTypeLeaf())) { if( ((ssgLeaf*)e)->getNumVertices() > 0) ((ssgLeaf*)e)->makeDList(); } else if (e->isAKindOf(ssgTypeBranch()) && ignore.find((ssgBranch *)e) == ignore.end()) { makeDList( (ssgBranch*)e, ignore ); } } } class sgLoaderOptions : public ssgLoaderOptions { public: void endLoad() {} // Avoid clearing the texture cache after every model load }; static sgLoaderOptions loaderOptions; //////////////////////////////////////////////////////////////////////// // Global functions. //////////////////////////////////////////////////////////////////////// ssgBranch * sgLoad3DModel( const string &fg_root, const string &path, SGPropertyNode *prop_root, double sim_time_sec, ssgEntity *(*load_panel)(SGPropertyNode *), SGModelData *data ) { ssgBranch * model = 0; SGPropertyNode props; // Load the 3D aircraft object itself SGPath modelpath = path, texturepath = path; if ( !ulIsAbsolutePathName( path.c_str() ) ) { SGPath tmp = fg_root; tmp.append(modelpath.str()); modelpath = texturepath = tmp; } // Check for an XML wrapper if (modelpath.str().substr(modelpath.str().size() - 4, 4) == ".xml") { readProperties(modelpath.str(), &props); if (props.hasValue("/path")) { modelpath = modelpath.dir(); modelpath.append(props.getStringValue("/path")); if (props.hasValue("/texture-path")) { texturepath = texturepath.dir(); texturepath.append(props.getStringValue("/texture-path")); } } else { if (model == 0) model = new ssgBranch; } } // Assume that textures are in // the same location as the XML file. if (model == 0) { if (texturepath.extension() != "") texturepath = texturepath.dir(); ssgTexturePath((char *)texturepath.c_str()); model = (ssgBranch *)ssgLoad((char *)modelpath.c_str(), &loaderOptions); if (model == 0) throw sg_io_exception("Failed to load 3D model", sg_location(modelpath.str())); } // Set up the alignment node ssgTransform * alignmainmodel = new ssgTransform; if ( load_panel == 0 ) alignmainmodel->setTravCallback( SSG_CALLBACK_PRETRAV, model_filter_callback ); alignmainmodel->addKid(model); sgMat4 res_matrix; sgMakeOffsetsMatrix(&res_matrix, props.getFloatValue("/offsets/heading-deg", 0.0), props.getFloatValue("/offsets/roll-deg", 0.0), props.getFloatValue("/offsets/pitch-deg", 0.0), props.getFloatValue("/offsets/x-m", 0.0), props.getFloatValue("/offsets/y-m", 0.0), props.getFloatValue("/offsets/z-m", 0.0)); alignmainmodel->setTransform(res_matrix); unsigned int i; // Load sub-models vector<SGPropertyNode_ptr> model_nodes = props.getChildren("model"); for (i = 0; i < model_nodes.size(); i++) { SGPropertyNode_ptr node = model_nodes[i]; ssgTransform * align = new ssgTransform; sgMat4 res_matrix; sgMakeOffsetsMatrix(&res_matrix, node->getFloatValue("offsets/heading-deg", 0.0), node->getFloatValue("offsets/roll-deg", 0.0), node->getFloatValue("offsets/pitch-deg", 0.0), node->getFloatValue("offsets/x-m", 0.0), node->getFloatValue("offsets/y-m", 0.0), node->getFloatValue("offsets/z-m", 0.0)); align->setTransform(res_matrix); ssgBranch * kid; const char * submodel = node->getStringValue("path"); try { kid = sgLoad3DModel( fg_root, submodel, prop_root, sim_time_sec, load_panel ); } catch (const sg_throwable &t) { SG_LOG(SG_INPUT, SG_ALERT, "Failed to load submodel: " << t.getFormattedMessage()); throw; } align->addKid(kid); align->setName(node->getStringValue("name", "")); model->addKid(align); } if ( load_panel ) { // Load panels vector<SGPropertyNode_ptr> panel_nodes = props.getChildren("panel"); for (i = 0; i < panel_nodes.size(); i++) { SG_LOG(SG_INPUT, SG_DEBUG, "Loading a panel"); ssgEntity * panel = load_panel(panel_nodes[i]); if (panel_nodes[i]->hasValue("name")) panel->setName((char *)panel_nodes[i]->getStringValue("name")); model->addKid(panel); } } if (data) { alignmainmodel->setUserData(data); data->modelLoaded(path, &props, alignmainmodel); } // Load animations set<ssgBranch *> ignore_branches; vector<SGPropertyNode_ptr> animation_nodes = props.getChildren("animation"); for (i = 0; i < animation_nodes.size(); i++) { const char * name = animation_nodes[i]->getStringValue("name", 0); vector<SGPropertyNode_ptr> name_nodes = animation_nodes[i]->getChildren("object-name"); sgMakeAnimation( model, name, name_nodes, prop_root, animation_nodes[i], sim_time_sec, texturepath, ignore_branches); } #if PLIB_VERSION > 183 if ( model != 0 && sgUseDisplayList ) { makeDList( model, ignore_branches ); } #endif int m = props.getIntValue("dump", 0); if (m > 0) model->print(stderr, "", m - 1); return alignmainmodel; } bool sgSetModelFilter( bool filter ) { bool old = model_filter; model_filter = filter; return old; } bool sgCheckAnimationBranch (ssgEntity * entity) { return entity->getTravCallback(SSG_CALLBACK_PRETRAV) == animation_callback; } // end of model.cxx
// model.cxx - manage a 3D aircraft model. // Written by David Megginson, started 2002. // // This file is in the Public Domain, and comes with no warranty. #ifdef HAVE_CONFIG_H #include <simgear_config.h> #endif #include <string.h> // for strcmp() #include <vector> #include <set> #include <plib/sg.h> #include <plib/ssg.h> #include <plib/ul.h> #include <simgear/structure/exception.hxx> #include <simgear/props/props.hxx> #include <simgear/props/props_io.hxx> #include "animation.hxx" #include "model.hxx" SG_USING_STD(vector); SG_USING_STD(set); bool sgUseDisplayList = true; //////////////////////////////////////////////////////////////////////// // Global state //////////////////////////////////////////////////////////////////////// static bool model_filter = true; //////////////////////////////////////////////////////////////////////// // Static utility functions. //////////////////////////////////////////////////////////////////////// static int model_filter_callback (ssgEntity * entity, int mask) { return model_filter ? 1 : 0; } /** * Callback to update an animation. */ static int animation_callback (ssgEntity * entity, int mask) { return ((SGAnimation *)entity->getUserData())->update(); } /** * Callback to restore the state after an animation. */ static int restore_callback (ssgEntity * entity, int mask) { ((SGAnimation *)entity->getUserData())->restore(); return 1; } /** * Locate a named SSG node in a branch. */ static ssgEntity * find_named_node (ssgEntity * node, const char * name) { char * node_name = node->getName(); if (node_name != 0 && !strcmp(name, node_name)) return node; else if (node->isAKindOf(ssgTypeBranch())) { int nKids = node->getNumKids(); for (int i = 0; i < nKids; i++) { ssgEntity * result = find_named_node(((ssgBranch*)node)->getKid(i), name); if (result != 0) return result; } } return 0; } /** * Splice a branch in between all child nodes and their parents. */ static void splice_branch (ssgBranch * branch, ssgEntity * child) { int nParents = child->getNumParents(); branch->addKid(child); for (int i = 0; i < nParents; i++) { ssgBranch * parent = child->getParent(i); parent->replaceKid(child, branch); } } /** * Make an offset matrix from rotations and position offset. */ void sgMakeOffsetsMatrix( sgMat4 * result, double h_rot, double p_rot, double r_rot, double x_off, double y_off, double z_off ) { sgMat4 rot_matrix; sgMat4 pos_matrix; sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot); sgMakeTransMat4(pos_matrix, x_off, y_off, z_off); sgMultMat4(*result, pos_matrix, rot_matrix); } void sgMakeAnimation( ssgBranch * model, const char * name, vector<SGPropertyNode_ptr> &name_nodes, SGPropertyNode *prop_root, SGPropertyNode_ptr node, double sim_time_sec, SGPath &texture_path, set<ssgBranch *> &ignore_branches ) { bool ignore = false; SGAnimation * animation = 0; const char * type = node->getStringValue("type", "none"); if (!strcmp("none", type)) { animation = new SGNullAnimation(node); } else if (!strcmp("range", type)) { animation = new SGRangeAnimation(prop_root, node); } else if (!strcmp("billboard", type)) { animation = new SGBillboardAnimation(node); } else if (!strcmp("select", type)) { animation = new SGSelectAnimation(prop_root, node); } else if (!strcmp("spin", type)) { animation = new SGSpinAnimation(prop_root, node, sim_time_sec ); } else if (!strcmp("timed", type)) { animation = new SGTimedAnimation(node); } else if (!strcmp("rotate", type)) { animation = new SGRotateAnimation(prop_root, node); } else if (!strcmp("translate", type)) { animation = new SGTranslateAnimation(prop_root, node); } else if (!strcmp("scale", type)) { animation = new SGScaleAnimation(prop_root, node); } else if (!strcmp("texrotate", type)) { animation = new SGTexRotateAnimation(prop_root, node); } else if (!strcmp("textranslate", type)) { animation = new SGTexTranslateAnimation(prop_root, node); } else if (!strcmp("texmultiple", type)) { animation = new SGTexMultipleAnimation(prop_root, node); } else if (!strcmp("blend", type)) { animation = new SGBlendAnimation(prop_root, node); ignore = true; } else if (!strcmp("alpha-test", type)) { animation = new SGAlphaTestAnimation(node); } else if (!strcmp("material", type)) { animation = new SGMaterialAnimation(prop_root, node, texture_path); } else if (!strcmp("flash", type)) { animation = new SGFlashAnimation(node); } else if (!strcmp("dist-scale", type)) { animation = new SGDistScaleAnimation(node); } else if (!strcmp("noshadow", type)) { animation = new SGShadowAnimation(prop_root, node); } else if (!strcmp("shader", type)) { animation = new SGShaderAnimation(prop_root, node); } else { animation = new SGNullAnimation(node); SG_LOG(SG_INPUT, SG_WARN, "Unknown animation type " << type); } if (name != 0) animation->setName((char *)name); ssgEntity * object; if (name_nodes.size() > 0) { object = find_named_node(model, name_nodes[0]->getStringValue()); if (object == 0) { SG_LOG(SG_INPUT, SG_ALERT, "Object " << name_nodes[0]->getStringValue() << " not found"); delete animation; animation = 0; } } else { object = model; } if ( animation == 0 ) return; ssgBranch * branch = animation->getBranch(); splice_branch(branch, object); for (unsigned int i = 1; i < name_nodes.size(); i++) { const char * name = name_nodes[i]->getStringValue(); object = find_named_node(model, name); if (object == 0) { SG_LOG(SG_INPUT, SG_ALERT, "Object " << name << " not found"); delete animation; animation = 0; } else { ssgBranch * oldParent = object->getParent(0); branch->addKid(object); oldParent->removeKid(object); } } if ( animation != 0 ) { animation->init(); branch->setUserData(animation); branch->setTravCallback(SSG_CALLBACK_PRETRAV, animation_callback); branch->setTravCallback(SSG_CALLBACK_POSTTRAV, restore_callback); if ( ignore ) { ignore_branches.insert( branch ); } } } static void makeDList( ssgBranch *b, const set<ssgBranch *> &ignore ) { int nb = b->getNumKids(); for (int i = 0; i<nb; i++) { ssgEntity *e = b->getKid(i); if (e->isAKindOf(ssgTypeLeaf())) { if( ((ssgLeaf*)e)->getNumVertices() > 0) ((ssgLeaf*)e)->makeDList(); } else if (e->isAKindOf(ssgTypeBranch()) && ignore.find((ssgBranch *)e) == ignore.end()) { makeDList( (ssgBranch*)e, ignore ); } } } class SGLoaderOptions : public ssgLoaderOptions { public: SGLoaderOptions() { ssgSetCurrentOptions( this ); } // Install our own loader options at startup void endLoad() {} // Avoid clearing the texture cache after every model load }; static SGLoaderOptions loaderOptions; //////////////////////////////////////////////////////////////////////// // Global functions. //////////////////////////////////////////////////////////////////////// ssgBranch * sgLoad3DModel( const string &fg_root, const string &path, SGPropertyNode *prop_root, double sim_time_sec, ssgEntity *(*load_panel)(SGPropertyNode *), SGModelData *data ) { ssgBranch * model = 0; SGPropertyNode props; // Load the 3D aircraft object itself SGPath modelpath = path, texturepath = path; if ( !ulIsAbsolutePathName( path.c_str() ) ) { SGPath tmp = fg_root; tmp.append(modelpath.str()); modelpath = texturepath = tmp; } // Check for an XML wrapper if (modelpath.str().substr(modelpath.str().size() - 4, 4) == ".xml") { readProperties(modelpath.str(), &props); if (props.hasValue("/path")) { modelpath = modelpath.dir(); modelpath.append(props.getStringValue("/path")); if (props.hasValue("/texture-path")) { texturepath = texturepath.dir(); texturepath.append(props.getStringValue("/texture-path")); } } else { if (model == 0) model = new ssgBranch; } } // Assume that textures are in // the same location as the XML file. if (model == 0) { if (texturepath.extension() != "") texturepath = texturepath.dir(); ssgTexturePath((char *)texturepath.c_str()); model = (ssgBranch *)ssgLoad((char *)modelpath.c_str()); if (model == 0) throw sg_io_exception("Failed to load 3D model", sg_location(modelpath.str())); } // Set up the alignment node ssgTransform * alignmainmodel = new ssgTransform; if ( load_panel == 0 ) alignmainmodel->setTravCallback( SSG_CALLBACK_PRETRAV, model_filter_callback ); alignmainmodel->addKid(model); sgMat4 res_matrix; sgMakeOffsetsMatrix(&res_matrix, props.getFloatValue("/offsets/heading-deg", 0.0), props.getFloatValue("/offsets/roll-deg", 0.0), props.getFloatValue("/offsets/pitch-deg", 0.0), props.getFloatValue("/offsets/x-m", 0.0), props.getFloatValue("/offsets/y-m", 0.0), props.getFloatValue("/offsets/z-m", 0.0)); alignmainmodel->setTransform(res_matrix); unsigned int i; // Load sub-models vector<SGPropertyNode_ptr> model_nodes = props.getChildren("model"); for (i = 0; i < model_nodes.size(); i++) { SGPropertyNode_ptr node = model_nodes[i]; ssgTransform * align = new ssgTransform; sgMat4 res_matrix; sgMakeOffsetsMatrix(&res_matrix, node->getFloatValue("offsets/heading-deg", 0.0), node->getFloatValue("offsets/roll-deg", 0.0), node->getFloatValue("offsets/pitch-deg", 0.0), node->getFloatValue("offsets/x-m", 0.0), node->getFloatValue("offsets/y-m", 0.0), node->getFloatValue("offsets/z-m", 0.0)); align->setTransform(res_matrix); ssgBranch * kid; const char * submodel = node->getStringValue("path"); try { kid = sgLoad3DModel( fg_root, submodel, prop_root, sim_time_sec, load_panel ); } catch (const sg_throwable &t) { SG_LOG(SG_INPUT, SG_ALERT, "Failed to load submodel: " << t.getFormattedMessage()); throw; } align->addKid(kid); align->setName(node->getStringValue("name", "")); model->addKid(align); } if ( load_panel ) { // Load panels vector<SGPropertyNode_ptr> panel_nodes = props.getChildren("panel"); for (i = 0; i < panel_nodes.size(); i++) { SG_LOG(SG_INPUT, SG_DEBUG, "Loading a panel"); ssgEntity * panel = load_panel(panel_nodes[i]); if (panel_nodes[i]->hasValue("name")) panel->setName((char *)panel_nodes[i]->getStringValue("name")); model->addKid(panel); } } if (data) { alignmainmodel->setUserData(data); data->modelLoaded(path, &props, alignmainmodel); } // Load animations set<ssgBranch *> ignore_branches; vector<SGPropertyNode_ptr> animation_nodes = props.getChildren("animation"); for (i = 0; i < animation_nodes.size(); i++) { const char * name = animation_nodes[i]->getStringValue("name", 0); vector<SGPropertyNode_ptr> name_nodes = animation_nodes[i]->getChildren("object-name"); sgMakeAnimation( model, name, name_nodes, prop_root, animation_nodes[i], sim_time_sec, texturepath, ignore_branches); } #if PLIB_VERSION > 183 if ( model != 0 && sgUseDisplayList ) { makeDList( model, ignore_branches ); } #endif int m = props.getIntValue("dump", 0); if (m > 0) model->print(stderr, "", m - 1); return alignmainmodel; } bool sgSetModelFilter( bool filter ) { bool old = model_filter; model_filter = filter; return old; } bool sgCheckAnimationBranch (ssgEntity * entity) { return entity->getTravCallback(SSG_CALLBACK_PRETRAV) == animation_callback; } // end of model.cxx
Fix the initial texture path problem. Loaders are setting the one given to ssgLoad as the default one behind our back :-(
Fix the initial texture path problem. Loaders are setting the one given to ssgLoad as the default one behind our back :-(
C++
lgpl-2.1
slowriot/simgear,slowriot/simgear
de74d22c29aeeb19ce1a327ccd6cbc8a13b3611e
include/distributions/models/dd.hpp
include/distributions/models/dd.hpp
// Copyright (c) 2014, Salesforce.com, 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 Salesforce.com 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. #pragma once #include <distributions/common.hpp> #include <distributions/special.hpp> #include <distributions/random.hpp> #include <distributions/vector.hpp> #include <distributions/vector_math.hpp> #include <distributions/mixins.hpp> #include <distributions/mixture.hpp> namespace distributions { template<int max_dim_> struct DirichletDiscrete { enum { max_dim = max_dim_ }; typedef DirichletDiscrete<max_dim> Model; typedef int count_t; typedef int Value; struct Group; struct Scorer; struct Sampler; struct MixtureDataScorer; struct MixtureValueScorer; typedef MixtureSlave<Model, MixtureDataScorer> SmallMixture; typedef MixtureSlave<Model, MixtureDataScorer, MixtureValueScorer> FastMixture; typedef FastMixture Mixture; struct Shared : SharedMixin<Model> { int dim; // fixed parameter float alphas[max_dim]; // hyperparamter template<class Message> void protobuf_load (const Message & message) { dim = message.alphas_size(); DIST_ASSERT_LE(dim, max_dim); for (size_t i = 0; i < dim; ++i) { alphas[i] = message.alphas(i); } } template<class Message> void protobuf_dump (Message & message) const { message.Clear(); for (size_t i = 0; i < dim; ++i) { message.add_alphas(alphas[i]); } } static Shared EXAMPLE () { Shared shared; shared.dim = max_dim; for (int i = 0; i < max_dim; ++i) { shared.alphas[i] = 0.5; } return shared; } }; struct Group : GroupMixin<Model> { int dim; count_t count_sum; count_t counts[max_dim]; template<class Message> void protobuf_load (const Message & message) { dim = message.counts_size(); DIST_ASSERT_LE(dim, max_dim); count_sum = 0; for (size_t i = 0; i < dim; ++i) { count_sum += counts[i] = message.counts(i); } } template<class Message> void protobuf_dump (Message & message) const { message.Clear(); auto & message_counts = * message.mutable_counts(); for (size_t i = 0; i < dim; ++i) { message_counts.Add(counts[i]); } } void init ( const Shared & shared, rng_t &) { dim = shared.dim; count_sum = 0; for (Value value = 0; value < dim; ++value) { counts[value] = 0; } } void add_value ( const Shared &, const Value & value, rng_t &) { DIST_ASSERT1(value < dim, "value out of bounds: " << value); count_sum += 1; counts[value] += 1; } void add_repeated_value( const Shared &, const Value & value, const int & count, rng_t &) { DIST_ASSERT1(value < dim, "value out of bounds: " << value); count_sum += count; counts[value] += count; } void remove_value ( const Shared &, const Value & value, rng_t &) { DIST_ASSERT1(value < dim, "value out of bounds: " << value); count_sum -= 1; counts[value] -= 1; } void merge ( const Shared &, const Group & source, rng_t &) { for (Value value = 0; value < dim; ++value) { counts[value] += source.counts[value]; } } float score_value ( const Shared & shared, const Value & value, rng_t & rng) const { Scorer scorer; scorer.init(shared, * this, rng); return scorer.eval(shared, value, rng); } float score_data ( const Shared & shared, rng_t &) const { float score = 0; float alpha_sum = 0; for (Value value = 0; value < dim; ++value) { float alpha = shared.alphas[value]; alpha_sum += alpha; score += fast_lgamma(alpha + counts[value]) - fast_lgamma(alpha); } score += fast_lgamma(alpha_sum) - fast_lgamma(alpha_sum + count_sum); return score; } Value sample_value ( const Shared & shared, rng_t & rng) const { Sampler sampler; sampler.init(shared, *this, rng); return sampler.eval(shared, rng); } void validate (const Shared & shared) const { DIST_ASSERT_EQ(dim, shared.dim); } }; struct Sampler { float ps[max_dim]; void init ( const Shared & shared, const Group & group, rng_t & rng) { for (Value value = 0; value < shared.dim; ++value) { ps[value] = shared.alphas[value] + group.counts[value]; } sample_dirichlet(rng, shared.dim, ps, ps); } Value eval ( const Shared & shared, rng_t & rng) const { return sample_discrete(rng, shared.dim, ps); } }; struct Scorer { float alpha_sum; float alphas[max_dim]; void init ( const Shared & shared, const Group & group, rng_t &) { alpha_sum = 0; for (Value value = 0; value < shared.dim; ++value) { float alpha = shared.alphas[value] + group.counts[value]; alphas[value] = alpha; alpha_sum += alpha; } } float eval ( const Shared & shared, const Value & value, rng_t &) const { DIST_ASSERT1(value < shared.dim, "value out of bounds: " << value); return fast_log(alphas[value] / alpha_sum); } }; struct MixtureDataScorer : MixtureSlaveDataScorerMixin<Model, MixtureDataScorer> { // not thread safe float score_data ( const Shared & shared, const std::vector<Group> & groups, rng_t &) const { _init(shared, groups); return _eval(); } // not thread safe void score_data_grid ( const std::vector<Shared> & shareds, const std::vector<Group> & groups, AlignedFloats scores_out, rng_t &) const { DIST_ASSERT_EQ(shareds.size(), scores_out.size()); if (const size_t size = shareds.size()) { const size_t dim = shareds[0].dim; _init(shareds[0], groups); scores_out[0] = _eval(); for (size_t i = 1; i < size; ++i) { const float * old_alphas = shareds[i-1].alphas; const float * new_alphas = shareds[i].alphas; for (Value value = 0; value < dim; ++value) { const float & old_alpha = old_alphas[value]; const float & new_alpha = new_alphas[value]; if (DIST_UNLIKELY(new_alpha != old_alpha)) { _update(value, old_alpha, new_alpha, groups); } } scores_out[i] = _eval(); } } } private: void _init ( const Shared & shared, const std::vector<Group> & groups) const { const size_t dim = shared.dim; shared_part_.resize(dim + 1); float alpha_sum = 0; for (size_t i = 0; i < dim; ++i) { float alpha = shared.alphas[i]; alpha_sum += alpha; shared_part_[i] = fast_lgamma(alpha); } alpha_sum_ = alpha_sum; shared_part_.back() = fast_lgamma(alpha_sum); scores_.resize(0); scores_.resize(dim + 1, 0); for (const auto & group : groups) { if (group.count_sum) { for (size_t i = 0; i < dim; ++i) { float alpha = shared.alphas[i]; scores_[i] += fast_lgamma(alpha + group.counts[i]) - shared_part_[i]; } scores_.back() += shared_part_.back() - fast_lgamma(alpha_sum + group.count_sum); } } } float _eval () const { return vector_sum(scores_.size(), scores_.data()); } void _update ( Value value, float old_alpha, float new_alpha, const std::vector<Group> & groups) const { shared_part_[value] = fast_lgamma(new_alpha); alpha_sum_ += double(new_alpha) - double(old_alpha); const float alpha_sum = alpha_sum_; shared_part_.back() = fast_lgamma(alpha_sum); scores_[value] = 0; scores_.back() = 0; for (const auto & group : groups) { scores_[value] += fast_lgamma(new_alpha + group.counts[value]) - shared_part_[value]; scores_.back() += shared_part_.back() - fast_lgamma(alpha_sum + group.count_sum); } } mutable double alpha_sum_; mutable VectorFloat shared_part_; mutable VectorFloat scores_; }; struct MixtureValueScorer : MixtureSlaveValueScorerMixin<Model> { void resize (const Shared & shared, size_t size) { scores_shift_.resize(size); scores_.resize(shared.dim); for (Value value = 0; value < shared.dim; ++value) { scores_[value].resize(size); } } void add_group (const Shared & shared, rng_t &) { scores_shift_.packed_add(0); for (Value value = 0; value < shared.dim; ++value) { scores_[value].packed_add(0); } } void remove_group (const Shared & shared, size_t groupid) { scores_shift_.packed_remove(groupid); for (Value value = 0; value < shared.dim; ++value) { scores_[value].packed_remove(groupid); } } void update_group ( const Shared & shared, size_t groupid, const Group & group, rng_t &) { scores_shift_[groupid] = fast_log(alpha_sum_ + group.count_sum); for (Value value = 0; value < shared.dim; ++value) { scores_[value][groupid] = fast_log(shared.alphas[value] + group.counts[value]); } } void add_value ( const Shared & shared, size_t groupid, const Group & group, const Value & value, rng_t &) { _update_group_value(shared, groupid, group, value); } void remove_value ( const Shared & shared, size_t groupid, const Group & group, const Value & value, rng_t &) { _update_group_value(shared, groupid, group, value); } void update_all ( const Shared & shared, const std::vector<Group> & groups, rng_t &) { const size_t group_count = groups.size(); alpha_sum_ = 0; for (Value value = 0; value < shared.dim; ++value) { alpha_sum_ += shared.alphas[value]; } for (size_t groupid = 0; groupid < group_count; ++groupid) { const Group & group = groups[groupid]; for (Value value = 0; value < shared.dim; ++value) { scores_[value][groupid] = shared.alphas[value] + group.counts[value]; } scores_shift_[groupid] = alpha_sum_ + group.count_sum; } vector_log(group_count, scores_shift_.data()); for (Value value = 0; value < shared.dim; ++value) { vector_log(group_count, scores_[value].data()); } } float score_value_group( const Shared & shared, const std::vector<Group> &, size_t groupid, const Value & value, rng_t &) const { DIST_ASSERT1(value < shared.dim, "value out of bounds: " << value); return scores_[value][groupid] - scores_shift_[groupid]; } void score_value( const Shared & shared, const std::vector<Group> &, const Value & value, AlignedFloats scores_accum, rng_t &) const { DIST_ASSERT1(value < shared.dim, "value out of bounds: " << value); vector_add_subtract( scores_accum.size(), scores_accum.data(), scores_[value].data(), scores_shift_.data()); } void validate ( const Shared &, const std::vector<Group> & groups) const { DIST_ASSERT_EQ(scores_.size(), groups.size()); DIST_ASSERT_EQ(scores_shift_.size(), groups.size()); } private: void _update_group_value ( const Shared & shared, size_t groupid, const Group & group, const Value & value) { DIST_ASSERT1(value < shared.dim, "value out of bounds: " << value); scores_[value][groupid] = fast_log(shared.alphas[value] + group.counts[value]); scores_shift_[groupid] = fast_log(alpha_sum_ + group.count_sum); } float alpha_sum_; std::vector<VectorFloat> scores_; VectorFloat scores_shift_; }; }; // struct DirichletDiscrete } // namespace distributions
// Copyright (c) 2014, Salesforce.com, 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 Salesforce.com 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. #pragma once #include <distributions/common.hpp> #include <distributions/special.hpp> #include <distributions/random.hpp> #include <distributions/vector.hpp> #include <distributions/vector_math.hpp> #include <distributions/mixins.hpp> #include <distributions/mixture.hpp> namespace distributions { template<int max_dim_> struct DirichletDiscrete { enum { max_dim = max_dim_ }; typedef DirichletDiscrete<max_dim> Model; typedef int count_t; typedef int Value; struct Group; struct Scorer; struct Sampler; struct MixtureDataScorer; struct MixtureValueScorer; typedef MixtureSlave<Model, MixtureDataScorer> SmallMixture; typedef MixtureSlave<Model, MixtureDataScorer, MixtureValueScorer> FastMixture; typedef FastMixture Mixture; struct Shared : SharedMixin<Model> { int dim; // fixed parameter float alphas[max_dim]; // hyperparamter template<class Message> void protobuf_load (const Message & message) { dim = message.alphas_size(); DIST_ASSERT_LE(dim, max_dim); for (size_t i = 0; i < dim; ++i) { alphas[i] = message.alphas(i); } } template<class Message> void protobuf_dump (Message & message) const { message.Clear(); for (size_t i = 0; i < dim; ++i) { message.add_alphas(alphas[i]); } } static Shared EXAMPLE () { Shared shared; shared.dim = max_dim; for (int i = 0; i < max_dim; ++i) { shared.alphas[i] = 0.5; } return shared; } }; struct Group : GroupMixin<Model> { int dim; count_t count_sum; count_t counts[max_dim]; template<class Message> void protobuf_load (const Message & message) { dim = message.counts_size(); DIST_ASSERT_LE(dim, max_dim); count_sum = 0; for (size_t i = 0; i < dim; ++i) { count_sum += counts[i] = message.counts(i); } } template<class Message> void protobuf_dump (Message & message) const { message.Clear(); auto & message_counts = * message.mutable_counts(); for (size_t i = 0; i < dim; ++i) { message_counts.Add(counts[i]); } } void init ( const Shared & shared, rng_t &) { dim = shared.dim; count_sum = 0; for (Value value = 0; value < dim; ++value) { counts[value] = 0; } } void add_value ( const Shared &, const Value & value, rng_t &) { DIST_ASSERT1(value < dim, "value out of bounds: " << value); count_sum += 1; counts[value] += 1; } void add_repeated_value( const Shared &, const Value & value, const int & count, rng_t &) { DIST_ASSERT1(value < dim, "value out of bounds: " << value); count_sum += count; counts[value] += count; } void remove_value ( const Shared &, const Value & value, rng_t &) { DIST_ASSERT1(value < dim, "value out of bounds: " << value); count_sum -= 1; counts[value] -= 1; } void merge ( const Shared &, const Group & source, rng_t &) { for (Value value = 0; value < dim; ++value) { counts[value] += source.counts[value]; } } float score_value ( const Shared & shared, const Value & value, rng_t & rng) const { Scorer scorer; scorer.init(shared, * this, rng); return scorer.eval(shared, value, rng); } float score_data ( const Shared & shared, rng_t &) const { float score = 0; float alpha_sum = 0; for (Value value = 0; value < dim; ++value) { float alpha = shared.alphas[value]; alpha_sum += alpha; score += fast_lgamma(alpha + counts[value]) - fast_lgamma(alpha); } score += fast_lgamma(alpha_sum) - fast_lgamma(alpha_sum + count_sum); return score; } Value sample_value ( const Shared & shared, rng_t & rng) const { Sampler sampler; sampler.init(shared, *this, rng); return sampler.eval(shared, rng); } void validate (const Shared & shared) const { DIST_ASSERT_EQ(dim, shared.dim); } }; struct Sampler { float ps[max_dim]; void init ( const Shared & shared, const Group & group, rng_t & rng) { for (Value value = 0; value < shared.dim; ++value) { ps[value] = shared.alphas[value] + group.counts[value]; } sample_dirichlet(rng, shared.dim, ps, ps); } Value eval ( const Shared & shared, rng_t & rng) const { return sample_discrete(rng, shared.dim, ps); } }; struct Scorer { float alpha_sum; float alphas[max_dim]; void init ( const Shared & shared, const Group & group, rng_t &) { alpha_sum = 0; for (Value value = 0; value < shared.dim; ++value) { float alpha = shared.alphas[value] + group.counts[value]; alphas[value] = alpha; alpha_sum += alpha; } } float eval ( const Shared & shared, const Value & value, rng_t &) const { DIST_ASSERT1(value < shared.dim, "value out of bounds: " << value); return fast_log(alphas[value] / alpha_sum); } }; struct MixtureDataScorer : MixtureSlaveDataScorerMixin<Model, MixtureDataScorer> { // not thread safe float score_data ( const Shared & shared, const std::vector<Group> & groups, rng_t &) const { _init(shared, groups); return _eval(); } // not thread safe void score_data_grid ( const std::vector<Shared> & shareds, const std::vector<Group> & groups, AlignedFloats scores_out, rng_t &) const { DIST_ASSERT_EQ(shareds.size(), scores_out.size()); if (const size_t size = shareds.size()) { const size_t dim = shareds[0].dim; _init(shareds[0], groups); scores_out[0] = _eval(); for (size_t i = 1; i < size; ++i) { const float * old_alphas = shareds[i-1].alphas; const float * new_alphas = shareds[i].alphas; for (Value value = 0; value < dim; ++value) { const float & old_alpha = old_alphas[value]; const float & new_alpha = new_alphas[value]; if (DIST_UNLIKELY(new_alpha != old_alpha)) { _update(value, old_alpha, new_alpha, groups); } } scores_out[i] = _eval(); } } } private: void _init ( const Shared & shared, const std::vector<Group> & groups) const { const size_t dim = shared.dim; shared_part_.resize(dim + 1); float alpha_sum = 0; for (size_t i = 0; i < dim; ++i) { float alpha = shared.alphas[i]; alpha_sum += alpha; shared_part_[i] = fast_lgamma(alpha); } alpha_sum_ = alpha_sum; shared_part_.back() = fast_lgamma(alpha_sum); scores_.resize(0); scores_.resize(dim + 1, 0); for (const auto & group : groups) { if (group.count_sum) { for (size_t i = 0; i < dim; ++i) { float alpha = shared.alphas[i]; scores_[i] += fast_lgamma(alpha + group.counts[i]) - shared_part_[i]; } scores_.back() += shared_part_.back() - fast_lgamma(alpha_sum + group.count_sum); } } } float _eval () const { return vector_sum(scores_.size(), scores_.data()); } void _update ( Value value, float old_alpha, float new_alpha, const std::vector<Group> & groups) const { shared_part_[value] = fast_lgamma(new_alpha); alpha_sum_ += double(new_alpha) - double(old_alpha); const float alpha_sum = alpha_sum_; shared_part_.back() = fast_lgamma(alpha_sum); scores_[value] = 0; scores_.back() = 0; for (const auto & group : groups) { scores_[value] += fast_lgamma(new_alpha + group.counts[value]) - shared_part_[value]; scores_.back() += shared_part_.back() - fast_lgamma(alpha_sum + group.count_sum); } } mutable double alpha_sum_; mutable VectorFloat shared_part_; mutable VectorFloat scores_; }; struct MixtureValueScorer : MixtureSlaveValueScorerMixin<Model> { void resize (const Shared & shared, size_t size) { scores_shift_.resize(size); scores_.resize(shared.dim); for (Value value = 0; value < shared.dim; ++value) { scores_[value].resize(size); } } void add_group (const Shared & shared, rng_t &) { scores_shift_.packed_add(0); for (Value value = 0; value < shared.dim; ++value) { scores_[value].packed_add(0); } } void remove_group (const Shared & shared, size_t groupid) { scores_shift_.packed_remove(groupid); for (Value value = 0; value < shared.dim; ++value) { scores_[value].packed_remove(groupid); } } void update_group ( const Shared & shared, size_t groupid, const Group & group, rng_t &) { scores_shift_[groupid] = fast_log(alpha_sum_ + group.count_sum); for (Value value = 0; value < shared.dim; ++value) { scores_[value][groupid] = fast_log(shared.alphas[value] + group.counts[value]); } } void add_value ( const Shared & shared, size_t groupid, const Group & group, const Value & value, rng_t &) { _update_group_value(shared, groupid, group, value); } void remove_value ( const Shared & shared, size_t groupid, const Group & group, const Value & value, rng_t &) { _update_group_value(shared, groupid, group, value); } void update_all ( const Shared & shared, const std::vector<Group> & groups, rng_t &) { const size_t group_count = groups.size(); alpha_sum_ = 0; for (Value value = 0; value < shared.dim; ++value) { alpha_sum_ += shared.alphas[value]; } for (size_t groupid = 0; groupid < group_count; ++groupid) { const Group & group = groups[groupid]; for (Value value = 0; value < shared.dim; ++value) { scores_[value][groupid] = shared.alphas[value] + group.counts[value]; } scores_shift_[groupid] = alpha_sum_ + group.count_sum; } vector_log(group_count, scores_shift_.data()); for (Value value = 0; value < shared.dim; ++value) { vector_log(group_count, scores_[value].data()); } } float score_value_group( const Shared & shared, const std::vector<Group> &, size_t groupid, const Value & value, rng_t &) const { DIST_ASSERT1(value < shared.dim, "value out of bounds: " << value); return scores_[value][groupid] - scores_shift_[groupid]; } void score_value( const Shared & shared, const std::vector<Group> &, const Value & value, AlignedFloats scores_accum, rng_t &) const { DIST_ASSERT1(value < shared.dim, "value out of bounds: " << value); vector_add_subtract( scores_accum.size(), scores_accum.data(), scores_[value].data(), scores_shift_.data()); } void validate ( const Shared & shared, const std::vector<Group> & groups) const { DIST_ASSERT_EQ(scores_.size(), shared.dim); for (Value value = 0; value < shared.dim; ++value) { DIST_ASSERT_EQ(scores_[value].size(), groups.size()); } DIST_ASSERT_EQ(scores_shift_.size(), groups.size()); } private: void _update_group_value ( const Shared & shared, size_t groupid, const Group & group, const Value & value) { DIST_ASSERT1(value < shared.dim, "value out of bounds: " << value); scores_[value][groupid] = fast_log(shared.alphas[value] + group.counts[value]); scores_shift_[groupid] = fast_log(alpha_sum_ + group.count_sum); } float alpha_sum_; std::vector<VectorFloat> scores_; VectorFloat scores_shift_; }; }; // struct DirichletDiscrete } // namespace distributions
Fix bug in dd mixture validation
Fix bug in dd mixture validation
C++
bsd-3-clause
fritzo/distributions,fritzo/distributions,forcedotcom/distributions,fritzo/distributions,forcedotcom/distributions,fritzo/distributions,forcedotcom/distributions
a46b583511c8736896915e3ff0f26724eb2fe8d3
framework/box.cpp
framework/box.cpp
// box.cpp GREAT #include "box.hpp" //KONSTRUTOREN---------------------------------------------------------------------- //Default //name:Box, Color: 0,0,0, Seitenlänge: 1 Box::Box() : Shape {"Box", {}}, m_min {0.0f, 0.0f, 0.0f}, m_max {1.0f, 1.0f, 1.0f} {} // Custom 1 Box::Box(glm::vec3 const& min, glm::vec3 const& max) : Shape {"Box", {}}, m_min {min}, m_max {max} {} // Custom 2 Box::Box(std::string const& name, Material const& mat, glm::vec3 const& min, glm::vec3 const& max) : Shape {name, mat}, m_min {min}, m_max {max} {} // Custom 3 Box::Box(std::string const& name, Material* const& mat, glm::vec3 const& min, glm::vec3 const& max) : Shape {name, mat}, m_min {min}, m_max {max} {} //Destruktor Box::~Box() { std::cout << "Box-Destruction: " << Shape::name()<< std::endl; } //GETTER---------------------------------------------------------------------- glm::vec3 const& Box::max() const { return m_max; } glm::vec3 const& Box::min() const { return m_min; } //SETTER---------------------------------------------------------------------- void Box::max(glm::vec3 const& max) { m_max = max; } void Box::min(glm::vec3 const& min) { m_min = min; } //FUNKTIONEN---------------------------------------------------------------------- float Box::area() const { glm::vec3 diff= m_max - m_min; //Differenz return 2 * (abs(diff.x * diff.y) + abs(diff.x * diff.z) + abs(diff.y * diff.z)); } float Box::volume() const { glm::vec3 diff = m_max - m_min; //Differenz return abs(diff.x * diff.y * diff.z); } // print std::ostream& Box::print(std::ostream& os) const { Shape::print(os); os << "Minimum: (" << m_min.x << ", " << m_min.y << ", " << m_min.z << ")" << "\n" << "Maximum: (" << m_max.x << ", " << m_max.y << ", " << m_max.z << ")" << std::endl; return os; } Hit Box::intersect(Ray const& ray) const { Hit boxhit; double t1 = (m_min.x - ray.origin_.x)*ray.inv_direction.x; double t2 = (m_max.x - ray.origin_.x)*ray.inv_direction.x; double tmin = std::min(t1, t2); double tmax = std::max(t1, t2); t1 = (m_min.y - ray.origin_.y)*ray.inv_direction.y; t2 = (m_max.y - ray.origin_.y)*ray.inv_direction.y; tmin = std::max(tmin, std::min(t1, t2)); tmax = std::min(tmax, std::max(t1, t2)); t1 = (m_min.z - ray.origin_.z)*ray.inv_direction.z; t2 = (m_max.z - ray.origin_.z)*ray.inv_direction.z; tmin = std::max(tmin, std::min(t1, t2)); tmax = std::min(tmax, std::max(t1, t2)); if (tmax > std::max(0.0, tmin)) { boxhit.m_hit = true; boxhit.m_distance = sqrt(tmin*tmin*( ray.direction_.x*ray.direction_.x + ray.direction_.y*ray.direction_.y + ray.direction_.z*ray.direction_.z)); boxhit.m_shape = std::make_shared<Box> (*this); boxhit.m_intersection = glm::vec3{tmin*ray.direction_.x, tmin*ray.direction_.y, tmin*ray.direction_.z}; } /* Alte! float txmin = (m_min.x - ray.origin.x) / ray.direction.x; float txmax = (m_max.x - ray.origin.x) / ray.direction.x; if (txmin > txmax) std::swap(txmin, txmax); float tmin = txmin; float tmax = txmax; float tymin = (m_min.y - ray.origin.y) / ray.direction.y; float tymax = (m_max.y - ray.origin.y) / ray.direction.y; if (tymin > tymax) std::swap(tymin, tymax); if ((tmin > tymax) || (tymin > tmax)) boxhit.m_hit = false; if (tymin > tmin) tmin = tymin; if (tymax < tmax) tmax = tymax; float tzmin = (m_min.z - ray.origin.z) / ray.direction.z; float tzmax = (m_max.z - ray.origin.z) / ray.direction.z; if (tzmin > tzmax) std::swap(tzmin, tzmax); if ((tmin > tzmax) || (tzmin > tmax)) boxhit.m_hit = false; if (tzmin > tmin) tmin = tzmin; if (tzmax < tmax) tmax = tzmax; boxhit.m_hit = true; if (boxhit.m_hit) { boxhit.m_distance = sqrt((txmin-ray.origin.x)*(txmin-ray.origin.x)+ (tymin-ray.origin.y)*(tymin-ray.origin.y)+ (tzmin-ray.origin.z)*(tzmin-ray.origin.z) ); boxhit.m_shape = std::make_shared<Box> (*this); boxhit.m_intersection = glm::vec3{tmin*ray.m_dir.x, tmin*ray.m_dir.y, tmin*ray.m_dir.z}; } //nur zum pushen hinzugefügt */ /* if (tmax > std::max(0.0, tmin)) { boxhit.m_distance = ); boxhit.m_intersection = glm::vec3{ tmin*ray.m_dir.x, tmin*ray.m_dir.y, tmin*ray.m_dir.z }; boxhit.m_normal = normal(boxhit.m_intersection); boxhit.m_shape = std::make_shared<Box>(*this); boxhit.m_hit = true; } */ return boxhit; } /* //intersect //aufgabe5.10 bool Box::intersect ( Ray const & r , float & distance ) const { //Source: http://www.scratchapixel.com/lessons/3d-basic-rendering/ //minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection //eventuell robusterbauen float tmin = (m_min.x - r.origin_.x) / r.direction_.x; float tmax = (m_max.x - r.origin_.x) / r.direction_.x; if (tmin > tmax) std::swap(tmin, tmax); float tymin = (m_min.y - r.origin_.y) / r.direction_.y; float tymax = (m_max.y - r.origin_.y) / r.direction_.y; if (tymin > tymax) std::swap(tymin, tymax); if ((tmin > tymax) || (tymin > tmax)) return false; if (tymin > tmin) tmin = tymin; if (tymax < tmax) tmax = tymax; float tzmin = (m_min.z - r.origin_.z) / r.direction_.z; float tzmax = (m_max.z - r.origin_.z) / r.direction_.z; if (tzmin > tzmax) std::swap(tzmin, tzmax); if ((tmin > tzmax) || (tzmin > tmax)) return false; if (tzmin > tmin) tmin = tzmin; if (tzmax < tmax) tmax = tzmax; distance=tmin; //distance anpassen!! return true; } */
// box.cpp GREAT #include "box.hpp" #include <cmath> #include <catch.hpp> #include <algorithm> //KONSTRUTOREN---------------------------------------------------------------------- //Default //name:Box, Color: 0,0,0, Seitenlänge: 1 Box::Box() : Shape {"Box", {}}, m_min {0.0f, 0.0f, 0.0f}, m_max {1.0f, 1.0f, 1.0f} {} // Custom 1 Box::Box(glm::vec3 const& min, glm::vec3 const& max) : Shape {"Box", {}}, m_min {min}, m_max {max} {} // Custom 2 Box::Box(std::string const& name, Material const& mat, glm::vec3 const& min, glm::vec3 const& max) : Shape {name, mat}, m_min {min}, m_max {max} {} // Custom 3 Box::Box(std::string const& name, Material* const& mat, glm::vec3 const& min, glm::vec3 const& max) : Shape {name, mat}, m_min {min}, m_max {max} {} //Destruktor Box::~Box() { std::cout << "Box-Destruction: " << Shape::name()<< std::endl; } //GETTER---------------------------------------------------------------------- glm::vec3 const& Box::max() const { return m_max; } glm::vec3 const& Box::min() const { return m_min; } //SETTER---------------------------------------------------------------------- void Box::max(glm::vec3 const& max) { m_max = max; } void Box::min(glm::vec3 const& min) { m_min = min; } //FUNKTIONEN---------------------------------------------------------------------- float Box::area() const { glm::vec3 diff= m_max - m_min; //Differenz return 2 * (abs(diff.x * diff.y) + abs(diff.x * diff.z) + abs(diff.y * diff.z)); } float Box::volume() const { glm::vec3 diff = m_max - m_min; //Differenz return abs(diff.x * diff.y * diff.z); } // print std::ostream& Box::print(std::ostream& os) const { Shape::print(os); os << "Minimum: (" << m_min.x << ", " << m_min.y << ", " << m_min.z << ")" << "\n" << "Maximum: (" << m_max.x << ", " << m_max.y << ", " << m_max.z << ")" << std::endl; return os; } Hit Box::intersect(Ray const& ray) const { Hit boxhit; double t1 = (m_min.x - ray.origin_.x)*ray.inv_direction.x; double t2 = (m_max.x - ray.origin_.x)*ray.inv_direction.x; double tmin = std::min(t1, t2); double tmax = std::max(t1, t2); t1 = (m_min.y - ray.origin_.y)*ray.inv_direction.y; t2 = (m_max.y - ray.origin_.y)*ray.inv_direction.y; tmin = std::max(tmin, std::min(t1, t2)); tmax = std::min(tmax, std::max(t1, t2)); t1 = (m_min.z - ray.origin_.z)*ray.inv_direction.z; t2 = (m_max.z - ray.origin_.z)*ray.inv_direction.z; tmin = std::max(tmin, std::min(t1, t2)); tmax = std::min(tmax, std::max(t1, t2)); if (tmax > std::max(0.0, tmin)) { boxhit.m_hit = true; boxhit.m_distance = sqrt(tmin*tmin*( ray.direction_.x*ray.direction_.x + ray.direction_.y*ray.direction_.y + ray.direction_.z*ray.direction_.z)); boxhit.m_shape = std::make_shared<Box> (*this); boxhit.m_intersection = glm::vec3{tmin*ray.direction_.x, tmin*ray.direction_.y, tmin*ray.direction_.z}; if ((boxhit.m_intersection.x)==Approx(m_max.x)) { boxhit.m_normal=glm::vec3(1.0f,0.0f,0.0f); // right }else if ((boxhit.m_intersection.x)==Approx(m_min.x)) { boxhit.m_normal=glm::vec3(-1.0f,0.0f,0.0f); //left }else if ((boxhit.m_intersection.y)==Approx(m_max.y)) { boxhit.m_normal=glm::vec3(0.0f,1.0f,0.0f); //fup }else if ((boxhit.m_intersection.y)==Approx(m_min.y)) { boxhit.m_normal=glm::vec3(0.0f,-1.0f,0.0f); //down }else if ((boxhit.m_intersection.z)==Approx(m_max.z)) { boxhit.m_normal=glm::vec3(0.0f,0.0f,1.0f); //front }else { boxhit.m_normal=glm::vec3(0.0f,0.0f,-1.0f); //back } } /* Alte! float txmin = (m_min.x - ray.origin.x) / ray.direction.x; float txmax = (m_max.x - ray.origin.x) / ray.direction.x; if (txmin > txmax) std::swap(txmin, txmax); float tmin = txmin; float tmax = txmax; float tymin = (m_min.y - ray.origin.y) / ray.direction.y; float tymax = (m_max.y - ray.origin.y) / ray.direction.y; if (tymin > tymax) std::swap(tymin, tymax); if ((tmin > tymax) || (tymin > tmax)) boxhit.m_hit = false; if (tymin > tmin) tmin = tymin; if (tymax < tmax) tmax = tymax; float tzmin = (m_min.z - ray.origin.z) / ray.direction.z; float tzmax = (m_max.z - ray.origin.z) / ray.direction.z; if (tzmin > tzmax) std::swap(tzmin, tzmax); if ((tmin > tzmax) || (tzmin > tmax)) boxhit.m_hit = false; if (tzmin > tmin) tmin = tzmin; if (tzmax < tmax) tmax = tzmax; boxhit.m_hit = true; if (boxhit.m_hit) { boxhit.m_distance = sqrt((txmin-ray.origin.x)*(txmin-ray.origin.x)+ (tymin-ray.origin.y)*(tymin-ray.origin.y)+ (tzmin-ray.origin.z)*(tzmin-ray.origin.z) ); boxhit.m_shape = std::make_shared<Box> (*this); boxhit.m_intersection = glm::vec3{tmin*ray.m_dir.x, tmin*ray.m_dir.y, tmin*ray.m_dir.z}; } //nur zum pushen hinzugefügt */ /* if (tmax > std::max(0.0, tmin)) { boxhit.m_distance = ); boxhit.m_intersection = glm::vec3{ tmin*ray.m_dir.x, tmin*ray.m_dir.y, tmin*ray.m_dir.z }; boxhit.m_normal = normal(boxhit.m_intersection); boxhit.m_shape = std::make_shared<Box>(*this); boxhit.m_hit = true; } */ return boxhit; } /* //intersect //aufgabe5.10 bool Box::intersect ( Ray const & r , float & distance ) const { //Source: http://www.scratchapixel.com/lessons/3d-basic-rendering/ //minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection //eventuell robusterbauen float tmin = (m_min.x - r.origin_.x) / r.direction_.x; float tmax = (m_max.x - r.origin_.x) / r.direction_.x; if (tmin > tmax) std::swap(tmin, tmax); float tymin = (m_min.y - r.origin_.y) / r.direction_.y; float tymax = (m_max.y - r.origin_.y) / r.direction_.y; if (tymin > tymax) std::swap(tymin, tymax); if ((tmin > tymax) || (tymin > tmax)) return false; if (tymin > tmin) tmin = tymin; if (tymax < tmax) tmax = tymax; float tzmin = (m_min.z - r.origin_.z) / r.direction_.z; float tzmax = (m_max.z - r.origin_.z) / r.direction_.z; if (tzmin > tzmax) std::swap(tzmin, tzmax); if ((tmin > tzmax) || (tzmin > tmax)) return false; if (tzmin > tmin) tmin = tzmin; if (tzmax < tmax) tmax = tzmax; distance=tmin; //distance anpassen!! return true; } */
add normal:metal:
add normal:metal:
C++
mit
PhilJungschlaeger/raytracer,PhilJungschlaeger/raytracer
b59ab15e45794ec0db556dab6da530cdca416852
lib/llvm/analysis/ControlDependence/NonTerminationSensitiveControlDependencyAnalysis.cpp
lib/llvm/analysis/ControlDependence/NonTerminationSensitiveControlDependencyAnalysis.cpp
#include "NonTerminationSensitiveControlDependencyAnalysis.h" #include "Function.h" #include "Block.h" #include <llvm/IR/Module.h> #include <algorithm> #include <iostream> #include <functional> #include <queue> using namespace std; namespace dg { namespace cd { NonTerminationSensitiveControlDependencyAnalysis::NonTerminationSensitiveControlDependencyAnalysis(const llvm::Function *function, dg::LLVMPointerAnalysis *pointsToAnalysis) :entryFunction(function), graphBuilder(pointsToAnalysis) {} void NonTerminationSensitiveControlDependencyAnalysis::computeDependencies() { if (!entryFunction) { std::cerr << "Missing entry function!\n"; return; } graphBuilder.buildFunctionRecursively(entryFunction); auto entryFunc = graphBuilder.findFunction(entryFunction); entryFunc->entry()->visit(); auto functions = graphBuilder.functions(); for (auto function : functions) { auto nodes = function.second->nodes(); auto condNodes = function.second->condNodes(); auto callReturnNodes = function.second->callReturnNodes(); for (auto node : nodes) { // (1) initialize nodeInfo.clear(); nodeInfo.reserve(nodes.size()); for (auto node1 : nodes) { nodeInfo[node1].outDegreeCounter = node1->successors().size(); } // (2) traverse visitInitialNode(node); // (3) for (auto node1 : nodes) { if (hasRedAndNonRedSuccessor(node1)) { controlDependency[node1].insert(node); } } } // add interprocedural dependencies for (auto node : nodes) { if (!node->callees().empty() || !node->joins().empty()) { auto iterator = std::find_if(node->successors().begin(), node->successors().end(), [](const Block *block){ return block->isCallReturn(); }); if (iterator != node->successors().end()) { for (auto callee : node->callees()) { controlDependency[callee.second->exit()].insert(*iterator); } for (auto join : node->joins()) { controlDependency[join.second->exit()].insert(*iterator); } } } } for (auto node : callReturnNodes) { std::queue<Block *> q; for(auto successor : node->successors()) { q.push(successor); } while (!q.empty()) { controlDependency[node].insert(q.front()); for(auto successor : q.front()->successors()) { q.push(successor); } q.pop(); } } } } void NonTerminationSensitiveControlDependencyAnalysis::dump(ostream &ostream) const { ostream << "digraph \"BlockGraph\" {\n"; graphBuilder.dumpNodes(ostream); graphBuilder.dumpEdges(ostream); dumpDependencies(ostream); ostream << "}\n"; } void NonTerminationSensitiveControlDependencyAnalysis::dumpDependencies(ostream &ostream) const { for (auto keyValue : controlDependency) { for (auto dependent : keyValue.second) { ostream << keyValue.first->dotName() << " -> " << dependent->dotName() << " [color=blue, constraint=false]\n"; } } } void NonTerminationSensitiveControlDependencyAnalysis::visitInitialNode(Block *node) { nodeInfo[node].red = true; for (auto predecessor : node->predecessors()) { visit(predecessor); } } void NonTerminationSensitiveControlDependencyAnalysis::visit(Block *node) { if (nodeInfo[node].outDegreeCounter == 0) { return; } nodeInfo[node].outDegreeCounter--; if (nodeInfo[node].outDegreeCounter == 0) { nodeInfo[node].red = true; for (auto predecessor : node->predecessors()) { visit(predecessor); } } } bool NonTerminationSensitiveControlDependencyAnalysis::hasRedAndNonRedSuccessor(Block *node) { size_t redCounter = 0; for (auto successor : node->successors()) { if (nodeInfo[successor].red) { ++redCounter; } } return redCounter > 0 && node->successors().size() > redCounter; } } }
#include "NonTerminationSensitiveControlDependencyAnalysis.h" #include "Function.h" #include "Block.h" #include <llvm/IR/Module.h> #include <algorithm> #include <iostream> #include <functional> #include <queue> #include <unordered_set> using namespace std; namespace dg { namespace cd { NonTerminationSensitiveControlDependencyAnalysis::NonTerminationSensitiveControlDependencyAnalysis(const llvm::Function *function, dg::LLVMPointerAnalysis *pointsToAnalysis) :entryFunction(function), graphBuilder(pointsToAnalysis) {} void NonTerminationSensitiveControlDependencyAnalysis::computeDependencies() { if (!entryFunction) { std::cerr << "Missing entry function!\n"; return; } graphBuilder.buildFunctionRecursively(entryFunction); auto entryFunc = graphBuilder.findFunction(entryFunction); entryFunc->entry()->visit(); auto functions = graphBuilder.functions(); for (auto function : functions) { auto nodes = function.second->nodes(); auto condNodes = function.second->condNodes(); auto callReturnNodes = function.second->callReturnNodes(); for (auto node : nodes) { // (1) initialize nodeInfo.clear(); nodeInfo.reserve(nodes.size()); for (auto node1 : nodes) { nodeInfo[node1].outDegreeCounter = node1->successors().size(); } // (2) traverse visitInitialNode(node); // (3) for (auto node1 : nodes) { if (hasRedAndNonRedSuccessor(node1)) { controlDependency[node1].insert(node); } } } // add interprocedural dependencies for (auto node : nodes) { if (!node->callees().empty() || !node->joins().empty()) { auto iterator = std::find_if(node->successors().begin(), node->successors().end(), [](const Block *block){ return block->isCallReturn(); }); if (iterator != node->successors().end()) { for (auto callee : node->callees()) { controlDependency[callee.second->exit()].insert(*iterator); } for (auto join : node->joins()) { controlDependency[join.second->exit()].insert(*iterator); } } } } for (auto node : callReturnNodes) { std::queue<Block *> q; std::unordered_set<Block *> visited(nodes.size()); visited.insert(node); for(auto successor : node->successors()) { if (visited.find(successor) == visited.end()) { q.push(successor); visited.insert(successor); } } while (!q.empty()) { controlDependency[node].insert(q.front()); for(auto successor : q.front()->successors()) { if (visited.find(successor) == visited.end()) { q.push(successor); visited.insert(successor); } } q.pop(); } } } } void NonTerminationSensitiveControlDependencyAnalysis::dump(ostream &ostream) const { ostream << "digraph \"BlockGraph\" {\n"; graphBuilder.dumpNodes(ostream); graphBuilder.dumpEdges(ostream); dumpDependencies(ostream); ostream << "}\n"; } void NonTerminationSensitiveControlDependencyAnalysis::dumpDependencies(ostream &ostream) const { for (auto keyValue : controlDependency) { for (auto dependent : keyValue.second) { ostream << keyValue.first->dotName() << " -> " << dependent->dotName() << " [color=blue, constraint=false]\n"; } } } void NonTerminationSensitiveControlDependencyAnalysis::visitInitialNode(Block *node) { nodeInfo[node].red = true; for (auto predecessor : node->predecessors()) { visit(predecessor); } } void NonTerminationSensitiveControlDependencyAnalysis::visit(Block *node) { if (nodeInfo[node].outDegreeCounter == 0) { return; } nodeInfo[node].outDegreeCounter--; if (nodeInfo[node].outDegreeCounter == 0) { nodeInfo[node].red = true; for (auto predecessor : node->predecessors()) { visit(predecessor); } } } bool NonTerminationSensitiveControlDependencyAnalysis::hasRedAndNonRedSuccessor(Block *node) { size_t redCounter = 0; for (auto successor : node->successors()) { if (nodeInfo[successor].red) { ++redCounter; } } return redCounter > 0 && node->successors().size() > redCounter; } } }
Fix adding of interprocedural dependencies.
Fix adding of interprocedural dependencies.
C++
mit
mchalupa/dg,mchalupa/dg,mchalupa/dg,mchalupa/dg
eafc5ed1ef8e286487c71e8c34a720b54cb0b303
src/import/chips/p9/procedures/hwp/memory/lib/dimm/rcd_load.H
src/import/chips/p9/procedures/hwp/memory/lib/dimm/rcd_load.H
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/rcd_load.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,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 rcd_load.H /// @brief Code to support rcd_loads /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: HB:FSP #ifndef _MSS_RCD_LOAD_H_ #define _MSS_RCD_LOAD_H_ #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <lib/utils/c_str.H> #include <lib/shared/mss_kind.H> namespace mss { /// /// @brief Perform the rcd_load operations /// @tparam T, the fapi2::TargetType of i_target /// @param[in] i_target, a fapi2::Target /// @return FAPI2_RC_SUCCESS if and only if ok /// template< fapi2::TargetType T > fapi2::ReturnCode rcd_load( const fapi2::Target<T>& i_target ); // // Implement the polymorphism for rcd_load // // -# Register the API. /// -# Define the template parameters for the overloaded function /// @note the first argument is the api name, and the rest are the api's template parameters. /// @note this creates __api_name##_overload template< mss::kind_t K > struct perform_rcd_load_overload { static const bool available = false; }; /// -# Register the specific overloads. The first parameter is the name /// of the api, the second is the kind of the element which is being /// overloaded - an RDIMM, an LRDIMM, etc. The remaining parameters /// indicate the specialization of the api itself. /// @note You need to define the "DEFAULT_KIND" here as an overload. This /// allows the mechanism to find the "base" implementation for things which /// have no specific overload. template<> struct perform_rcd_load_overload< DEFAULT_KIND > { static const bool available = true; }; template<> struct perform_rcd_load_overload< KIND_RDIMM_DDR4 > { static const bool available = true; }; template<> struct perform_rcd_load_overload< KIND_LRDIMM_DDR4 > { static const bool available = true; }; /// /// -# Define the default case for overloaded calls. enable_if states that /// if there is a DEFAULT_KIND overload for this TargetType, then this /// entry point will be defined. Note the general case below is enabled if /// there is no overload defined for this TargetType /// /// /// @brief Perform the rcd_load operations /// @tparam K, the kind of DIMM we're operating on (derived) /// @param[in] i_target, a fapi2::Target<fapi2::TARGET_TYPE_DIMM> /// @param[in] a vector of CCS instructions we should add to /// @return FAPI2_RC_SUCCESS if and only if ok /// template< mss::kind_t K = FORCE_DISPATCH > typename std::enable_if< perform_rcd_load_overload<DEFAULT_KIND>::available, fapi2::ReturnCode>::type perform_rcd_load( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst); // // We know we registered overloads for perform_rcd_load, so we need the entry point to // the dispatcher. Add a set of these for all TargetTypes which get overloads // for this API // template<> fapi2::ReturnCode perform_rcd_load<FORCE_DISPATCH>( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst); template<> fapi2::ReturnCode perform_rcd_load<DEFAULT_KIND>( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst); // // Boilerplate dispatcher // template< kind_t K, bool B = perform_rcd_load_overload<K>::available > inline fapi2::ReturnCode perform_rcd_load_dispatch( const kind_t& i_kind, const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst) { // We dispatch to another kind if: // We don't have an overload defined (B == false) // Or, if we do have an overload (B == true) and this is not out kind. if ((B == false) || ((B == true) && (K != i_kind))) { return perform_rcd_load_dispatch < (kind_t)(K - 1) > (i_kind, i_target, i_inst); } // Otherwise, we call the overload. return perform_rcd_load<K>(i_target, i_inst); } // DEFAULT_KIND is 0 so this is the end of the recursion template<> inline fapi2::ReturnCode perform_rcd_load_dispatch<DEFAULT_KIND>(const kind_t&, const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst) { return perform_rcd_load<DEFAULT_KIND>(i_target, i_inst); } } #endif
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/rcd_load.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,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 rcd_load.H /// @brief Code to support rcd_loads /// // *HWP HWP Owner: Brian Silver <[email protected]> // *HWP HWP Backup: Andre Marin <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: HB:FSP #ifndef _MSS_RCD_LOAD_H_ #define _MSS_RCD_LOAD_H_ #include <fapi2.H> #include <p9_mc_scom_addresses.H> #include <c_str.H> #include <lib/shared/mss_kind.H> namespace mss { /// /// @brief Perform the rcd_load operations /// @tparam T, the fapi2::TargetType of i_target /// @param[in] i_target, a fapi2::Target /// @return FAPI2_RC_SUCCESS if and only if ok /// template< fapi2::TargetType T > fapi2::ReturnCode rcd_load( const fapi2::Target<T>& i_target ); // // Implement the polymorphism for rcd_load // // -# Register the API. /// -# Define the template parameters for the overloaded function /// @note the first argument is the api name, and the rest are the api's template parameters. /// @note this creates __api_name##_overload template< mss::kind_t K > struct perform_rcd_load_overload { static const bool available = false; }; /// -# Register the specific overloads. The first parameter is the name /// of the api, the second is the kind of the element which is being /// overloaded - an RDIMM, an LRDIMM, etc. The remaining parameters /// indicate the specialization of the api itself. /// @note You need to define the "DEFAULT_KIND" here as an overload. This /// allows the mechanism to find the "base" implementation for things which /// have no specific overload. template<> struct perform_rcd_load_overload< DEFAULT_KIND > { static const bool available = true; }; template<> struct perform_rcd_load_overload< KIND_RDIMM_DDR4 > { static const bool available = true; }; template<> struct perform_rcd_load_overload< KIND_LRDIMM_DDR4 > { static const bool available = true; }; /// /// -# Define the default case for overloaded calls. enable_if states that /// if there is a DEFAULT_KIND overload for this TargetType, then this /// entry point will be defined. Note the general case below is enabled if /// there is no overload defined for this TargetType /// /// /// @brief Perform the rcd_load operations /// @tparam K, the kind of DIMM we're operating on (derived) /// @param[in] i_target, a fapi2::Target<fapi2::TARGET_TYPE_DIMM> /// @param[in] a vector of CCS instructions we should add to /// @return FAPI2_RC_SUCCESS if and only if ok /// template< mss::kind_t K = FORCE_DISPATCH > typename std::enable_if< perform_rcd_load_overload<DEFAULT_KIND>::available, fapi2::ReturnCode>::type perform_rcd_load( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst); // // We know we registered overloads for perform_rcd_load, so we need the entry point to // the dispatcher. Add a set of these for all TargetTypes which get overloads // for this API // template<> fapi2::ReturnCode perform_rcd_load<FORCE_DISPATCH>( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst); template<> fapi2::ReturnCode perform_rcd_load<DEFAULT_KIND>( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst); // // Boilerplate dispatcher // template< kind_t K, bool B = perform_rcd_load_overload<K>::available > inline fapi2::ReturnCode perform_rcd_load_dispatch( const kind_t& i_kind, const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst) { // We dispatch to another kind if: // We don't have an overload defined (B == false) // Or, if we do have an overload (B == true) and this is not out kind. if ((B == false) || ((B == true) && (K != i_kind))) { return perform_rcd_load_dispatch < (kind_t)(K - 1) > (i_kind, i_target, i_inst); } // Otherwise, we call the overload. return perform_rcd_load<K>(i_target, i_inst); } // DEFAULT_KIND is 0 so this is the end of the recursion template<> inline fapi2::ReturnCode perform_rcd_load_dispatch<DEFAULT_KIND>(const kind_t&, const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& i_inst) { return perform_rcd_load<DEFAULT_KIND>(i_target, i_inst); } } #endif
Add c_str generic API and update makefiles
Add c_str generic API and update makefiles Change-Id: Idd14a81937a109796d57e0f42458acafcc4b8204 Original-Change-Id: I95e3b9013d3ab0c352d3614c12ee4ef0d26965d0 Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/35924 Tested-by: Jenkins Server <[email protected]> Reviewed-by: Louis Stermole <[email protected]> Reviewed-by: STEPHEN GLANCY <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: Brian R. Silver <[email protected]> Reviewed-by: Jennifer A. Stofer <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
3904672376a0d69168bc7dcfd9a7407fe41021c5
tensorflow/core/framework/rendezvous.cc
tensorflow/core/framework/rendezvous.cc
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/rendezvous.h" #include <deque> #include <functional> #include <utility> #include <vector> #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/notification.h" #include "tensorflow/core/lib/gtl/flatmap.h" #include "tensorflow/core/lib/hash/hash.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/thread_annotations.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { Rendezvous::ParsedKey& Rendezvous::ParsedKey::operator=(const ParsedKey& b) { const char* b_base = b.buf_.data(); buf_ = b.buf_; src_device = StringPiece(buf_.data() + (b.src_device.data() - b_base), b.src_device.size()); src = b.src; src_incarnation = b.src_incarnation; dst_device = StringPiece(buf_.data() + (b.dst_device.data() - b_base), b.dst_device.size()); dst = b.dst; edge_name = StringPiece(buf_.data() + (b.edge_name.data() - b_base), b.edge_name.size()); return *this; } /* static */ string Rendezvous::CreateKey(const string& src_device, uint64 src_incarnation, const string& dst_device, const string& name, const FrameAndIter& frame_iter) { // NOTE: ';' is not used in the device name's job name. // // We include both sender and receiver in the key to facilitate // debugging. For correctness, we only need to encode the receiver. // // "src_incarnation" is used to distinguish a worker when it // restarts. char buf[strings::kFastToBufferSize]; return strings::StrCat( src_device, ";", strings::Uint64ToHexString(src_incarnation, buf), ";", dst_device, ";", name, ";", frame_iter.frame_id, ":", frame_iter.iter_id); } // Return the prefix of "*s" up to the next occurrence of "delim", or // the whole remaining string if "delim" is not found. "*s" is advanced // past the string returned plus the delimiter (if found). static StringPiece ConsumeNextPart(StringPiece* s, char delim) { for (size_t offset = 0; offset < s->size(); offset++) { if ((*s)[offset] == delim) { StringPiece result(s->data(), offset); s->remove_prefix(offset + 1); // +1: remove delim, as well return result; } } // No delimiter found: return rest of string StringPiece result(s->data(), s->size()); s->remove_prefix(s->size()); return result; } /* static */ Status Rendezvous::ParseKey(StringPiece key, ParsedKey* out) { if (key.data() == out->buf_.data()) { // Caller used our buf_ string directly, so we don't need to copy. (The // SendOp and RecvOp implementations do this, for example). DCHECK_EQ(key.size(), out->buf_.size()); } else { // Make a copy that our StringPieces can point at a copy that will persist // for the lifetime of the ParsedKey object. out->buf_.assign(key.data(), key.size()); } StringPiece s(out->buf_); StringPiece parts[5]; for (int i = 0; i < 5; i++) { parts[i] = ConsumeNextPart(&s, ';'); } if (s.empty() && // Consumed the whole string !parts[4].empty() && // Exactly five parts DeviceNameUtils::ParseFullName(parts[0], &out->src) && strings::HexStringToUint64(parts[1], &out->src_incarnation) && DeviceNameUtils::ParseFullName(parts[2], &out->dst) && !parts[3].empty()) { out->src_device = StringPiece(parts[0].data(), parts[0].size()); out->dst_device = StringPiece(parts[2].data(), parts[2].size()); out->edge_name = StringPiece(parts[3].data(), parts[3].size()); return Status::OK(); } return errors::InvalidArgument("Invalid rendezvous key: ", key); } Rendezvous::~Rendezvous() {} Status Rendezvous::Recv(const ParsedKey& key, const Args& recv_args, Tensor* val, bool* is_dead, int64 timeout_ms) { Status ret; Notification n; RecvAsync(key, recv_args, [&ret, &n, val, is_dead](const Status& s, const Args& send_args, const Args& recv_args, const Tensor& v, const bool dead) { ret = s; *val = v; *is_dead = dead; n.Notify(); }); if (timeout_ms > 0) { int64 timeout_us = timeout_ms * 1000; bool notified = WaitForNotificationWithTimeout(&n, timeout_us); if (!notified) { return Status(error::DEADLINE_EXCEEDED, "Timed out waiting for notification"); } } else { n.WaitForNotification(); } return ret; } Status Rendezvous::Recv(const ParsedKey& key, const Args& args, Tensor* val, bool* is_dead) { const int64 no_timeout = 0; return Recv(key, args, val, is_dead, no_timeout); } class LocalRendezvousImpl : public Rendezvous { public: explicit LocalRendezvousImpl() {} Status Send(const ParsedKey& key, const Args& send_args, const Tensor& val, const bool is_dead) override { uint64 key_hash = KeyHash(key.FullKey()); VLOG(2) << "Send " << this << " " << key_hash << " " << key.FullKey(); mu_.lock(); if (!status_.ok()) { // Rendezvous has been aborted. Status s = status_; mu_.unlock(); return s; } ItemQueue* queue = &table_[key_hash]; if (queue->empty() || queue->front()->IsSendValue()) { // There is no waiter for this message. Append the message // into the queue. The waiter will pick it up when arrives. // Only send-related fields need to be filled. VLOG(2) << "Enqueue Send Item (key:" << key.FullKey() << "). "; Item* item = new Item; item->value = val; item->is_dead = is_dead; item->send_args = send_args; if (item->send_args.device_context) { item->send_args.device_context->Ref(); } queue->push_back(item); mu_.unlock(); return Status::OK(); } VLOG(2) << "Consume Recv Item (key:" << key.FullKey() << "). "; // There is an earliest waiter to consume this message. Item* item = queue->front(); // Delete the queue when the last element has been consumed. if (queue->size() == 1) { VLOG(2) << "Clean up Send/Recv queue (key:" << key.FullKey() << "). "; table_.erase(key_hash); } else { queue->pop_front(); } mu_.unlock(); // Notify the waiter by invoking its done closure, outside the // lock. DCHECK(!item->IsSendValue()); item->waiter(Status::OK(), send_args, item->recv_args, val, is_dead); delete item; return Status::OK(); } void RecvAsync(const ParsedKey& key, const Args& recv_args, DoneCallback done) override { uint64 key_hash = KeyHash(key.FullKey()); VLOG(2) << "Recv " << this << " " << key_hash << " " << key.FullKey(); mu_.lock(); if (!status_.ok()) { // Rendezvous has been aborted. Status s = status_; mu_.unlock(); done(s, Args(), recv_args, Tensor(), false); return; } ItemQueue* queue = &table_[key_hash]; if (queue->empty() || !queue->front()->IsSendValue()) { // There is no message to pick up. // Only recv-related fields need to be filled. CancellationManager* cm = recv_args.cancellation_manager; CancellationToken token = CancellationManager::kInvalidToken; bool already_cancelled = false; if (cm != nullptr) { token = cm->get_cancellation_token(); already_cancelled = !cm->RegisterCallback(token, [this, token, key_hash] { Item* item = nullptr; { mutex_lock l(mu_); ItemQueue* queue = &table_[key_hash]; if (!queue->empty() && !queue->front()->IsSendValue()) { for (auto it = queue->begin(); it != queue->end(); it++) { if ((*it)->cancellation_token == token) { item = *it; if (queue->size() == 1) { table_.erase(key_hash); } else { queue->erase(it); } break; } } } } if (item != nullptr) { item->waiter(StatusGroup::MakeDerived( errors::Cancelled("RecvAsync is cancelled.")), Args(), item->recv_args, Tensor(), /*is_dead=*/false); delete item; } }); } if (already_cancelled) { mu_.unlock(); done(StatusGroup::MakeDerived( errors::Cancelled("RecvAsync is cancelled.")), Args(), recv_args, Tensor(), /*is_dead=*/false); return; } VLOG(2) << "Enqueue Recv Item (key:" << key.FullKey() << "). "; Item* item = new Item; if (cm != nullptr) { auto wrapped_done = std::bind( [cm, token](const DoneCallback& done, // Begin unbound arguments. const Status& s, const Args& send_args, const Args& recv_args, const Tensor& v, bool dead) { cm->TryDeregisterCallback(token); done(s, send_args, recv_args, v, dead); }, std::move(done), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5); item->waiter = std::move(wrapped_done); } else { item->waiter = std::move(done); } item->recv_args = recv_args; item->cancellation_token = token; if (item->recv_args.device_context) { item->recv_args.device_context->Ref(); } queue->push_back(item); mu_.unlock(); return; } VLOG(2) << "Consume Send Item (key:" << key.FullKey() << "). "; // A message has already arrived and is queued in the table under // this key. Consumes the message and invokes the done closure. Item* item = queue->front(); // Delete the queue when the last element has been consumed. if (queue->size() == 1) { VLOG(2) << "Clean up Send/Recv queue (key:" << key.FullKey() << "). "; table_.erase(key_hash); } else { queue->pop_front(); } mu_.unlock(); // Invokes the done() by invoking its done closure, outside scope // of the table lock. DCHECK(item->IsSendValue()); done(Status::OK(), item->send_args, recv_args, item->value, item->is_dead); delete item; } void StartAbort(const Status& status) override { CHECK(!status.ok()); Table table; { mutex_lock l(mu_); status_.Update(status); table_.swap(table); } for (auto& p : table) { for (Item* item : p.second) { if (!item->IsSendValue()) { item->waiter(status, Args(), Args(), Tensor(), false); } delete item; } } } private: typedef LocalRendezvousImpl ME; struct Item { DoneCallback waiter = nullptr; Tensor value; bool is_dead = false; Args send_args; Args recv_args; CancellationToken cancellation_token; ~Item() { if (send_args.device_context) { send_args.device_context->Unref(); } if (recv_args.device_context) { recv_args.device_context->Unref(); } } // Returns true iff this item represents a value being sent. bool IsSendValue() const { return this->waiter == nullptr; } }; // We key the hash table by KeyHash of the Rendezvous::CreateKey string static uint64 KeyHash(const StringPiece& k) { return Hash64(k.data(), k.size()); } // By invariant, the item queue under each key is of the form // [item.IsSendValue()]* meaning each item is a sent message. // or // [!item.IsSendValue()]* meaning each item is a waiter. // // TODO(zhifengc): consider a better queue impl than std::deque. typedef std::deque<Item*> ItemQueue; typedef gtl::FlatMap<uint64, ItemQueue> Table; // TODO(zhifengc): shard table_. mutex mu_; Table table_ GUARDED_BY(mu_); Status status_ GUARDED_BY(mu_); ~LocalRendezvousImpl() override { if (!table_.empty()) { StartAbort(errors::Cancelled("LocalRendezvousImpl deleted")); } } TF_DISALLOW_COPY_AND_ASSIGN(LocalRendezvousImpl); }; Rendezvous* NewLocalRendezvous() { return new LocalRendezvousImpl(); } } // end namespace tensorflow
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/framework/rendezvous.h" #include <deque> #include <functional> #include <utility> #include <vector> #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/notification.h" #include "tensorflow/core/lib/gtl/flatmap.h" #include "tensorflow/core/lib/hash/hash.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/thread_annotations.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { Rendezvous::ParsedKey& Rendezvous::ParsedKey::operator=(const ParsedKey& b) { const char* b_base = b.buf_.data(); buf_ = b.buf_; src_device = StringPiece(buf_.data() + (b.src_device.data() - b_base), b.src_device.size()); src = b.src; src_incarnation = b.src_incarnation; dst_device = StringPiece(buf_.data() + (b.dst_device.data() - b_base), b.dst_device.size()); dst = b.dst; edge_name = StringPiece(buf_.data() + (b.edge_name.data() - b_base), b.edge_name.size()); return *this; } /* static */ string Rendezvous::CreateKey(const string& src_device, uint64 src_incarnation, const string& dst_device, const string& name, const FrameAndIter& frame_iter) { // NOTE: ';' is not used in the device name's job name. // // We include both sender and receiver in the key to facilitate // debugging. For correctness, we only need to encode the receiver. // // "src_incarnation" is used to distinguish a worker when it // restarts. char buf[strings::kFastToBufferSize]; return strings::StrCat( src_device, ";", strings::Uint64ToHexString(src_incarnation, buf), ";", dst_device, ";", name, ";", frame_iter.frame_id, ":", frame_iter.iter_id); } // Return the prefix of "*s" up to the next occurrence of "delim", or // the whole remaining string if "delim" is not found. "*s" is advanced // past the string returned plus the delimiter (if found). static StringPiece ConsumeNextPart(StringPiece* s, char delim) { for (size_t offset = 0; offset < s->size(); offset++) { if ((*s)[offset] == delim) { StringPiece result(s->data(), offset); s->remove_prefix(offset + 1); // +1: remove delim, as well return result; } } // No delimiter found: return rest of string StringPiece result(s->data(), s->size()); s->remove_prefix(s->size()); return result; } /* static */ Status Rendezvous::ParseKey(StringPiece key, ParsedKey* out) { if (key.data() == out->buf_.data()) { // Caller used our buf_ string directly, so we don't need to copy. (The // SendOp and RecvOp implementations do this, for example). DCHECK_EQ(key.size(), out->buf_.size()); } else { // Make a copy that our StringPieces can point at a copy that will persist // for the lifetime of the ParsedKey object. out->buf_.assign(key.data(), key.size()); } StringPiece s(out->buf_); StringPiece parts[5]; for (int i = 0; i < 5; i++) { parts[i] = ConsumeNextPart(&s, ';'); } if (s.empty() && // Consumed the whole string !parts[4].empty() && // Exactly five parts DeviceNameUtils::ParseFullName(parts[0], &out->src) && strings::HexStringToUint64(parts[1], &out->src_incarnation) && DeviceNameUtils::ParseFullName(parts[2], &out->dst) && !parts[3].empty()) { out->src_device = StringPiece(parts[0].data(), parts[0].size()); out->dst_device = StringPiece(parts[2].data(), parts[2].size()); out->edge_name = StringPiece(parts[3].data(), parts[3].size()); return Status::OK(); } return errors::InvalidArgument("Invalid rendezvous key: ", key); } Rendezvous::~Rendezvous() {} Status Rendezvous::Recv(const ParsedKey& key, const Args& recv_args, Tensor* val, bool* is_dead, int64 timeout_ms) { Status ret; Notification n; RecvAsync(key, recv_args, [&ret, &n, val, is_dead](const Status& s, const Args& send_args, const Args& recv_args, const Tensor& v, const bool dead) { ret = s; *val = v; *is_dead = dead; n.Notify(); }); if (timeout_ms > 0) { int64 timeout_us = timeout_ms * 1000; bool notified = WaitForNotificationWithTimeout(&n, timeout_us); if (!notified) { return Status(error::DEADLINE_EXCEEDED, "Timed out waiting for notification"); } } else { n.WaitForNotification(); } return ret; } Status Rendezvous::Recv(const ParsedKey& key, const Args& args, Tensor* val, bool* is_dead) { const int64 no_timeout = 0; return Recv(key, args, val, is_dead, no_timeout); } class LocalRendezvousImpl : public Rendezvous { public: explicit LocalRendezvousImpl() {} Status Send(const ParsedKey& key, const Args& send_args, const Tensor& val, const bool is_dead) override { uint64 key_hash = KeyHash(key.FullKey()); VLOG(2) << "Send " << this << " " << key_hash << " " << key.FullKey(); mu_.lock(); if (!status_.ok()) { // Rendezvous has been aborted. Status s = status_; mu_.unlock(); return s; } ItemQueue* queue = &table_[key_hash]; if (queue->empty() || queue->front()->IsSendValue()) { // There is no waiter for this message. Append the message // into the queue. The waiter will pick it up when arrives. // Only send-related fields need to be filled. VLOG(2) << "Enqueue Send Item (key:" << key.FullKey() << "). "; Item* item = new Item; item->value = val; item->is_dead = is_dead; item->send_args = send_args; if (item->send_args.device_context) { item->send_args.device_context->Ref(); } queue->push_back(item); mu_.unlock(); return Status::OK(); } VLOG(2) << "Consume Recv Item (key:" << key.FullKey() << "). "; // There is an earliest waiter to consume this message. Item* item = queue->front(); // Delete the queue when the last element has been consumed. if (queue->size() == 1) { VLOG(2) << "Clean up Send/Recv queue (key:" << key.FullKey() << "). "; table_.erase(key_hash); } else { queue->pop_front(); } mu_.unlock(); // Notify the waiter by invoking its done closure, outside the // lock. DCHECK(!item->IsSendValue()); item->waiter(Status::OK(), send_args, item->recv_args, val, is_dead); delete item; return Status::OK(); } void RecvAsync(const ParsedKey& key, const Args& recv_args, DoneCallback done) override { uint64 key_hash = KeyHash(key.FullKey()); VLOG(2) << "Recv " << this << " " << key_hash << " " << key.FullKey(); mu_.lock(); if (!status_.ok()) { // Rendezvous has been aborted. Status s = status_; mu_.unlock(); done(s, Args(), recv_args, Tensor(), false); return; } ItemQueue* queue = &table_[key_hash]; if (queue->empty() || !queue->front()->IsSendValue()) { // There is no message to pick up. // Only recv-related fields need to be filled. CancellationManager* cm = recv_args.cancellation_manager; CancellationToken token = CancellationManager::kInvalidToken; bool already_cancelled = false; if (cm != nullptr) { token = cm->get_cancellation_token(); already_cancelled = !cm->RegisterCallback(token, [this, token, key_hash] { Item* item = nullptr; { mutex_lock l(mu_); ItemQueue* queue = &table_[key_hash]; if (!queue->empty() && !queue->front()->IsSendValue()) { for (auto it = queue->begin(); it != queue->end(); it++) { if ((*it)->cancellation_token == token) { item = *it; if (queue->size() == 1) { table_.erase(key_hash); } else { queue->erase(it); } break; } } } } if (item != nullptr) { item->waiter(StatusGroup::MakeDerived( errors::Cancelled("RecvAsync is cancelled.")), Args(), item->recv_args, Tensor(), /*is_dead=*/false); delete item; } }); } if (already_cancelled) { mu_.unlock(); done(StatusGroup::MakeDerived( errors::Cancelled("RecvAsync is cancelled.")), Args(), recv_args, Tensor(), /*is_dead=*/false); return; } VLOG(2) << "Enqueue Recv Item (key:" << key.FullKey() << "). "; Item* item = new Item; if (cm != nullptr) { // NOTE(mrry): We must wrap `done` with code that deregisters the // cancellation callback before calling the `done` callback, because the // cancellation manager may no longer be live after `done` is called. auto wrapped_done = std::bind( [cm, token](const DoneCallback& done, // Begin unbound arguments. const Status& s, const Args& send_args, const Args& recv_args, const Tensor& v, bool dead) { cm->TryDeregisterCallback(token); done(s, send_args, recv_args, v, dead); }, std::move(done), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5); item->waiter = std::move(wrapped_done); } else { item->waiter = std::move(done); } item->recv_args = recv_args; item->cancellation_token = token; if (item->recv_args.device_context) { item->recv_args.device_context->Ref(); } queue->push_back(item); mu_.unlock(); return; } VLOG(2) << "Consume Send Item (key:" << key.FullKey() << "). "; // A message has already arrived and is queued in the table under // this key. Consumes the message and invokes the done closure. Item* item = queue->front(); // Delete the queue when the last element has been consumed. if (queue->size() == 1) { VLOG(2) << "Clean up Send/Recv queue (key:" << key.FullKey() << "). "; table_.erase(key_hash); } else { queue->pop_front(); } mu_.unlock(); // Invokes the done() by invoking its done closure, outside scope // of the table lock. DCHECK(item->IsSendValue()); done(Status::OK(), item->send_args, recv_args, item->value, item->is_dead); delete item; } void StartAbort(const Status& status) override { CHECK(!status.ok()); Table table; { mutex_lock l(mu_); status_.Update(status); table_.swap(table); } for (auto& p : table) { for (Item* item : p.second) { if (!item->IsSendValue()) { item->waiter(status, Args(), Args(), Tensor(), false); } delete item; } } } private: typedef LocalRendezvousImpl ME; struct Item { DoneCallback waiter = nullptr; Tensor value; bool is_dead = false; Args send_args; Args recv_args; CancellationToken cancellation_token; ~Item() { if (send_args.device_context) { send_args.device_context->Unref(); } if (recv_args.device_context) { recv_args.device_context->Unref(); } } // Returns true iff this item represents a value being sent. bool IsSendValue() const { return this->waiter == nullptr; } }; // We key the hash table by KeyHash of the Rendezvous::CreateKey string static uint64 KeyHash(const StringPiece& k) { return Hash64(k.data(), k.size()); } // By invariant, the item queue under each key is of the form // [item.IsSendValue()]* meaning each item is a sent message. // or // [!item.IsSendValue()]* meaning each item is a waiter. // // TODO(zhifengc): consider a better queue impl than std::deque. typedef std::deque<Item*> ItemQueue; typedef gtl::FlatMap<uint64, ItemQueue> Table; // TODO(zhifengc): shard table_. mutex mu_; Table table_ GUARDED_BY(mu_); Status status_ GUARDED_BY(mu_); ~LocalRendezvousImpl() override { if (!table_.empty()) { StartAbort(errors::Cancelled("LocalRendezvousImpl deleted")); } } TF_DISALLOW_COPY_AND_ASSIGN(LocalRendezvousImpl); }; Rendezvous* NewLocalRendezvous() { return new LocalRendezvousImpl(); } } // end namespace tensorflow
Add clarifying comment to cancellation handling in rendezvous.cc.
Add clarifying comment to cancellation handling in rendezvous.cc. PiperOrigin-RevId: 266939120
C++
apache-2.0
chemelnucfin/tensorflow,DavidNorman/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow,gunan/tensorflow,adit-chandra/tensorflow,gautam1858/tensorflow,arborh/tensorflow,jhseu/tensorflow,petewarden/tensorflow,aam-at/tensorflow,gunan/tensorflow,renyi533/tensorflow,ppwwyyxx/tensorflow,davidzchen/tensorflow,ppwwyyxx/tensorflow,sarvex/tensorflow,tensorflow/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gunan/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,yongtang/tensorflow,paolodedios/tensorflow,DavidNorman/tensorflow,gautam1858/tensorflow,gautam1858/tensorflow,cxxgtxy/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,renyi533/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_saved_model,xzturn/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-experimental_link_static_libraries_once,karllessard/tensorflow,petewarden/tensorflow,Intel-Corporation/tensorflow,aldian/tensorflow,aam-at/tensorflow,ppwwyyxx/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,renyi533/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_saved_model,DavidNorman/tensorflow,davidzchen/tensorflow,adit-chandra/tensorflow,annarev/tensorflow,petewarden/tensorflow,xzturn/tensorflow,jhseu/tensorflow,adit-chandra/tensorflow,arborh/tensorflow,aam-at/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,arborh/tensorflow,aldian/tensorflow,renyi533/tensorflow,gautam1858/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,DavidNorman/tensorflow,gautam1858/tensorflow,aam-at/tensorflow,chemelnucfin/tensorflow,petewarden/tensorflow,yongtang/tensorflow,freedomtan/tensorflow,annarev/tensorflow,aldian/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,renyi533/tensorflow,DavidNorman/tensorflow,adit-chandra/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,cxxgtxy/tensorflow,freedomtan/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,ppwwyyxx/tensorflow,gunan/tensorflow,sarvex/tensorflow,sarvex/tensorflow,aam-at/tensorflow,gunan/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,gautam1858/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,adit-chandra/tensorflow,karllessard/tensorflow,paolodedios/tensorflow,gautam1858/tensorflow,paolodedios/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,karllessard/tensorflow,aam-at/tensorflow,ppwwyyxx/tensorflow,gunan/tensorflow,Intel-tensorflow/tensorflow,petewarden/tensorflow,adit-chandra/tensorflow,davidzchen/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,chemelnucfin/tensorflow,jhseu/tensorflow,cxxgtxy/tensorflow,yongtang/tensorflow,petewarden/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ppwwyyxx/tensorflow,chemelnucfin/tensorflow,aam-at/tensorflow,yongtang/tensorflow,arborh/tensorflow,renyi533/tensorflow,jhseu/tensorflow,ppwwyyxx/tensorflow,paolodedios/tensorflow,aam-at/tensorflow,freedomtan/tensorflow,Intel-tensorflow/tensorflow,frreiss/tensorflow-fred,tensorflow/tensorflow-pywrap_tf_optimizer,freedomtan/tensorflow,annarev/tensorflow,Intel-Corporation/tensorflow,arborh/tensorflow,paolodedios/tensorflow,freedomtan/tensorflow,renyi533/tensorflow,freedomtan/tensorflow,annarev/tensorflow,jhseu/tensorflow,chemelnucfin/tensorflow,xzturn/tensorflow,karllessard/tensorflow,annarev/tensorflow,DavidNorman/tensorflow,jhseu/tensorflow,petewarden/tensorflow,tensorflow/tensorflow,freedomtan/tensorflow,davidzchen/tensorflow,DavidNorman/tensorflow,gautam1858/tensorflow,xzturn/tensorflow,Intel-tensorflow/tensorflow,renyi533/tensorflow,Intel-Corporation/tensorflow,frreiss/tensorflow-fred,arborh/tensorflow,tensorflow/tensorflow-pywrap_saved_model,paolodedios/tensorflow,karllessard/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow,xzturn/tensorflow,sarvex/tensorflow,cxxgtxy/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-pywrap_saved_model,chemelnucfin/tensorflow,ppwwyyxx/tensorflow,yongtang/tensorflow,tensorflow/tensorflow,adit-chandra/tensorflow,gunan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,renyi533/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,chemelnucfin/tensorflow,gunan/tensorflow,jhseu/tensorflow,petewarden/tensorflow,xzturn/tensorflow,tensorflow/tensorflow,arborh/tensorflow,tensorflow/tensorflow-pywrap_saved_model,DavidNorman/tensorflow,annarev/tensorflow,arborh/tensorflow,davidzchen/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,chemelnucfin/tensorflow,paolodedios/tensorflow,chemelnucfin/tensorflow,Intel-tensorflow/tensorflow,aldian/tensorflow,frreiss/tensorflow-fred,petewarden/tensorflow,tensorflow/tensorflow-pywrap_saved_model,adit-chandra/tensorflow,frreiss/tensorflow-fred,jhseu/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,adit-chandra/tensorflow,cxxgtxy/tensorflow,Intel-tensorflow/tensorflow,tensorflow/tensorflow,cxxgtxy/tensorflow,cxxgtxy/tensorflow,DavidNorman/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,davidzchen/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,adit-chandra/tensorflow,gautam1858/tensorflow,annarev/tensorflow,gautam1858/tensorflow,karllessard/tensorflow,adit-chandra/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-Corporation/tensorflow,Intel-Corporation/tensorflow,sarvex/tensorflow,DavidNorman/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,gautam1858/tensorflow,aldian/tensorflow,annarev/tensorflow,karllessard/tensorflow,jhseu/tensorflow,renyi533/tensorflow,gunan/tensorflow,davidzchen/tensorflow,frreiss/tensorflow-fred,arborh/tensorflow,cxxgtxy/tensorflow,frreiss/tensorflow-fred,yongtang/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow,petewarden/tensorflow,chemelnucfin/tensorflow,chemelnucfin/tensorflow,sarvex/tensorflow,yongtang/tensorflow,aam-at/tensorflow,arborh/tensorflow,frreiss/tensorflow-fred,karllessard/tensorflow,renyi533/tensorflow,aldian/tensorflow,chemelnucfin/tensorflow,aldian/tensorflow,jhseu/tensorflow,annarev/tensorflow,annarev/tensorflow,gautam1858/tensorflow,arborh/tensorflow,yongtang/tensorflow,xzturn/tensorflow,davidzchen/tensorflow,karllessard/tensorflow,gunan/tensorflow,davidzchen/tensorflow,gunan/tensorflow,karllessard/tensorflow,freedomtan/tensorflow,Intel-Corporation/tensorflow,petewarden/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,adit-chandra/tensorflow,yongtang/tensorflow,ppwwyyxx/tensorflow,Intel-Corporation/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-pywrap_saved_model,yongtang/tensorflow,xzturn/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,frreiss/tensorflow-fred,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,gunan/tensorflow,davidzchen/tensorflow,annarev/tensorflow,xzturn/tensorflow,davidzchen/tensorflow,Intel-Corporation/tensorflow,arborh/tensorflow,DavidNorman/tensorflow,renyi533/tensorflow,jhseu/tensorflow,aldian/tensorflow,davidzchen/tensorflow
f71a2eb243c8f80d53dfa443a9da320c089376f2
src/main-menu.cpp
src/main-menu.cpp
#include <sstream> #include "util/bitmap.h" #include "factory/collector.h" #include "network/network.h" #include "util/token_exception.h" #include "mugen/exception.h" #include "mugen/menu.h" #include "music.h" #include "menu/menu.h" #include "menu/menu_global.h" #include "menu/menu-exception.h" #include "input/input-manager.h" #include "game/mod.h" #include "exceptions/shutdown_exception.h" #include "exceptions/exception.h" #include "util/timedifference.h" #include "util/funcs.h" #include "util/ftalleg.h" #include "util/file-system.h" #include "util/tokenreader.h" #include "util/token.h" #include "globals.h" #include "network/server.h" #include "configuration.h" #include "init.h" #include <string.h> #include <vector> /* hack */ #include "util/thread.h" #include "object/object.h" #include "object/player.h" #include "game.h" using namespace std; static int gfx = Global::WINDOWED; #define NUM_ARGS(d) (sizeof(d)/sizeof(char*)) static const char * WINDOWED_ARG[] = {"-w", "fullscreen", "nowindowed", "no-windowed"}; static const char * DATAPATH_ARG[] = {"-d", "data", "datapath", "data-path", "path"}; static const char * DEBUG_ARG[] = {"-l", "debug"}; static const char * MUSIC_ARG[] = {"-m", "music", "nomusic", "no-music"}; static const char * NETWORK_SERVER_ARG[] = {"server", "network-server"}; static const char * MUGEN_ARG[] = {"mugen"}; static const char * closestMatch(const char * s1, vector<const char *> args){ const char * good = NULL; int minimum = -1; for (vector<const char *>::iterator it = args.begin(); it != args.end(); it++){ const char * compare = *it; if (strlen(compare) > 2){ int distance = Util::levenshtein(s1, compare); if (distance != -1 && (minimum == -1 || distance < minimum)){ minimum = distance; good = compare; } } } return good; } static bool isArg( const char * s1, const char * s2[], int num){ for (int i = 0; i < num; i++){ if (strcasecmp(s1, s2[i]) == 0){ return true; } } return false; } /* {"a", "b", "c"}, 3, ',' => "a, b, c" */ static const char * all(const char * args[], const int num, const char separate = ','){ static char buffer[1<<10]; strcpy(buffer, ""); for (int i = 0; i < num; i++){ char fuz[10]; sprintf(fuz, "%c ", separate); strcat(buffer, args[i]); if (i != num - 1){ strcat(buffer, fuz); } } return buffer; } static void showOptions(){ Global::debug(0) << "Paintown by Jon Rafkind" << endl; Global::debug(0) << all(WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG), ',') << " : Fullscreen mode" << endl; Global::debug(0) << all(DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG)) << " <path> : Use data path of <path>. Default is " << Util::getDataPath2().path() << endl; Global::debug(0) << all(DEBUG_ARG, NUM_ARGS(DEBUG_ARG)) << " # : Enable debug statements. Higher numbers gives more debugging. Default is 0. Negative numbers are allowed. Example: -l 3" << endl; Global::debug(0) << all(MUSIC_ARG, NUM_ARGS(MUSIC_ARG)) << " : Turn off music" << endl; Global::debug(0) << all(MUGEN_ARG, NUM_ARGS(MUGEN_ARG)) << " : Go directly to the mugen menu" << endl; #ifdef HAVE_NETWORKING Global::debug(0) << all(NETWORK_SERVER_ARG, NUM_ARGS(NETWORK_SERVER_ARG)) << " : Go straight to the network server" << endl; #endif Global::debug(0) << endl; } static void addArgs(vector<const char *> & args, const char * strings[], int num){ for (int i = 0; i < num; i++){ args.push_back(strings[i]); } } static Filesystem::AbsolutePath mainMenuPath(){ string menu = Paintown::Mod::getCurrentMod()->getMenu(); return Filesystem::find(Filesystem::RelativePath(menu)); /* string file = Filesystem::find(currentMod()); TokenReader tr(file); Token * head = tr.readToken(); Token * menu = head->findToken("game/menu"); if (menu == NULL){ throw LoadException(file + " does not contain a game/menu token"); } string path; *menu >> path; // string path = "/menu/main.txt" return Filesystem::find(path); */ } /* static void hack(){ Filesystem::AbsolutePath fontsDirectory = Filesystem::find(Filesystem::RelativePath("fonts")); Global::debug(1, "hack") << "Font directory " << fontsDirectory.path() << endl; vector<string> ttfFonts = Util::getFiles(fontsDirectory, "*.ttf"); Global::debug(1, "hack") << "Fonts: " << ttfFonts.size() << endl; } */ int paintown_main( int argc, char ** argv ){ bool music_on = true; bool mugen = false; bool just_network_server = false; Collector janitor; Global::setDebug(0); vector<const char *> all_args; #define ADD_ARGS(args) addArgs(all_args, args, NUM_ARGS(args)) ADD_ARGS(WINDOWED_ARG); ADD_ARGS(DATAPATH_ARG); ADD_ARGS(DEBUG_ARG); ADD_ARGS(MUSIC_ARG); ADD_ARGS(MUGEN_ARG); #ifdef HAVE_NETWORKING ADD_ARGS(NETWORK_SERVER_ARG); #endif #undef ADD_ARGS for ( int q = 1; q < argc; q++ ){ if ( isArg( argv[ q ], WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG) ) ){ gfx = Global::FULLSCREEN; } else if ( isArg( argv[ q ], DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG) ) ){ q += 1; if ( q < argc ){ Util::setDataPath( argv[ q ] ); } } else if ( isArg( argv[ q ], MUSIC_ARG, NUM_ARGS(MUSIC_ARG) ) ){ music_on = false; } else if (isArg(argv[q], MUGEN_ARG, NUM_ARGS(MUGEN_ARG))){ mugen = true; } else if ( isArg( argv[ q ], DEBUG_ARG, NUM_ARGS(DEBUG_ARG) ) ){ q += 1; if ( q < argc ){ istringstream i( argv[ q ] ); int f; i >> f; Global::setDebug( f ); } #ifdef HAVE_NETWORKING } else if (isArg(argv[q], NETWORK_SERVER_ARG, NUM_ARGS(NETWORK_SERVER_ARG))){ just_network_server = true; #endif } else { const char * arg = argv[q]; const char * closest = closestMatch(arg, all_args); if (closest == NULL){ Global::debug(0) << "I don't recognize option '" << arg << "'" << endl; } else { Global::debug(0) << "You gave option '" << arg << "'. Did you mean '" << closest << "'?" << endl; } } } #undef NUM_ARGS showOptions(); Global::debug(0) << "Debug level: " << Global::getDebug() << endl; /* time how long init takes */ TimeDifference diff; diff.startTime(); /* init initializes practically everything including * graphics * sound * input * network * configuration * ... */ if (! Global::init(gfx)){ Global::debug( 0 ) << "Could not initialize system" << endl; return -1; } else { MenuGlobals::setFullscreen((gfx == Global::FULLSCREEN ? true : false)); } diff.endTime(); Global::debug(0) << diff.printTime("Init took") << endl; try{ Paintown::Mod::loadMod(Configuration::getCurrentGame()); } catch (const Filesystem::NotFound & e){ Global::debug(0) << "Could not load mod " << Configuration::getCurrentGame() << ": " << e.getReason() << endl; Paintown::Mod::loadDefaultMod(); } InputManager input; Music music(music_on); while (true){ try{ /* fadein from white */ Menu game(true, Bitmap::makeColor(255, 255, 255)); game.load(mainMenuPath()); if (just_network_server){ #ifdef HAVE_NETWORKING Network::networkServer(&game); #endif } else if (mugen){ Mugen::run(); } else { game.run(); } } catch (const Filesystem::Exception & ex){ Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getReason() << endl; } catch (const TokenException & ex){ Global::debug(0) << "There was a problem with the token. Error was:\n " << ex.getReason() << endl; return -1; } catch (const LoadException & ex){ Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getReason() << endl; return -1; } catch (const Exception::Return & ex){ } catch (const ShutdownException & shutdown){ Global::debug(1) << "Forced a shutdown. Cya!" << endl; } catch (const MugenException & m){ Global::debug(0) << "Mugen exception: " << m.getReason() << endl; } catch (const ReloadMenuException & ex){ Global::debug(1) << "Menu Reload Requested. Restarting...." << endl; continue; } catch (const ftalleg::Exception & ex){ Global::debug(0) << "Freetype exception caught. Error was:\n" << ex.getReason() << endl; } catch (const Exception::Base & base){ /* FIXME: print base.tostring */ // Global::debug(0) << "Freetype exception caught. Error was:\n" << ex.getReason() << endl; } catch (...){ Global::debug(0) << "Uncaught exception!" << endl; } break; } Configuration::saveConfiguration(); return 0; }
#include <sstream> #include "util/bitmap.h" #include "factory/collector.h" #include "network/network.h" #include "util/token_exception.h" #include "mugen/exception.h" #include "mugen/menu.h" #include "music.h" #include "menu/menu.h" #include "menu/menu_global.h" #include "menu/menu-exception.h" #include "input/input-manager.h" #include "game/mod.h" #include "exceptions/shutdown_exception.h" #include "exceptions/exception.h" #include "util/timedifference.h" #include "util/funcs.h" #include "util/ftalleg.h" #include "util/file-system.h" #include "util/tokenreader.h" #include "util/token.h" #include "globals.h" #include "network/server.h" #include "configuration.h" #include "init.h" #include <string.h> #include <vector> using namespace std; static int gfx = Global::WINDOWED; #define NUM_ARGS(d) (sizeof(d)/sizeof(char*)) static const char * WINDOWED_ARG[] = {"-w", "fullscreen", "nowindowed", "no-windowed"}; static const char * DATAPATH_ARG[] = {"-d", "data", "datapath", "data-path", "path"}; static const char * DEBUG_ARG[] = {"-l", "debug"}; static const char * MUSIC_ARG[] = {"-m", "music", "nomusic", "no-music"}; static const char * NETWORK_SERVER_ARG[] = {"server", "network-server"}; static const char * MUGEN_ARG[] = {"mugen"}; static const char * closestMatch(const char * s1, vector<const char *> args){ const char * good = NULL; int minimum = -1; for (vector<const char *>::iterator it = args.begin(); it != args.end(); it++){ const char * compare = *it; if (strlen(compare) > 2){ int distance = Util::levenshtein(s1, compare); if (distance != -1 && (minimum == -1 || distance < minimum)){ minimum = distance; good = compare; } } } return good; } static bool isArg( const char * s1, const char * s2[], int num){ for (int i = 0; i < num; i++){ if (strcasecmp(s1, s2[i]) == 0){ return true; } } return false; } /* {"a", "b", "c"}, 3, ',' => "a, b, c" */ static const char * all(const char * args[], const int num, const char separate = ','){ static char buffer[1<<10]; strcpy(buffer, ""); for (int i = 0; i < num; i++){ char fuz[10]; sprintf(fuz, "%c ", separate); strcat(buffer, args[i]); if (i != num - 1){ strcat(buffer, fuz); } } return buffer; } static void showOptions(){ Global::debug(0) << "Paintown by Jon Rafkind" << endl; Global::debug(0) << all(WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG), ',') << " : Fullscreen mode" << endl; Global::debug(0) << all(DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG)) << " <path> : Use data path of <path>. Default is " << Util::getDataPath2().path() << endl; Global::debug(0) << all(DEBUG_ARG, NUM_ARGS(DEBUG_ARG)) << " # : Enable debug statements. Higher numbers gives more debugging. Default is 0. Negative numbers are allowed. Example: -l 3" << endl; Global::debug(0) << all(MUSIC_ARG, NUM_ARGS(MUSIC_ARG)) << " : Turn off music" << endl; Global::debug(0) << all(MUGEN_ARG, NUM_ARGS(MUGEN_ARG)) << " : Go directly to the mugen menu" << endl; #ifdef HAVE_NETWORKING Global::debug(0) << all(NETWORK_SERVER_ARG, NUM_ARGS(NETWORK_SERVER_ARG)) << " : Go straight to the network server" << endl; #endif Global::debug(0) << endl; } static void addArgs(vector<const char *> & args, const char * strings[], int num){ for (int i = 0; i < num; i++){ args.push_back(strings[i]); } } static Filesystem::AbsolutePath mainMenuPath(){ string menu = Paintown::Mod::getCurrentMod()->getMenu(); return Filesystem::find(Filesystem::RelativePath(menu)); /* string file = Filesystem::find(currentMod()); TokenReader tr(file); Token * head = tr.readToken(); Token * menu = head->findToken("game/menu"); if (menu == NULL){ throw LoadException(file + " does not contain a game/menu token"); } string path; *menu >> path; // string path = "/menu/main.txt" return Filesystem::find(path); */ } /* static void hack(){ Filesystem::AbsolutePath fontsDirectory = Filesystem::find(Filesystem::RelativePath("fonts")); Global::debug(1, "hack") << "Font directory " << fontsDirectory.path() << endl; vector<string> ttfFonts = Util::getFiles(fontsDirectory, "*.ttf"); Global::debug(1, "hack") << "Fonts: " << ttfFonts.size() << endl; } */ int paintown_main( int argc, char ** argv ){ bool music_on = true; bool mugen = false; bool just_network_server = false; Collector janitor; Global::setDebug(0); vector<const char *> all_args; #define ADD_ARGS(args) addArgs(all_args, args, NUM_ARGS(args)) ADD_ARGS(WINDOWED_ARG); ADD_ARGS(DATAPATH_ARG); ADD_ARGS(DEBUG_ARG); ADD_ARGS(MUSIC_ARG); ADD_ARGS(MUGEN_ARG); #ifdef HAVE_NETWORKING ADD_ARGS(NETWORK_SERVER_ARG); #endif #undef ADD_ARGS for ( int q = 1; q < argc; q++ ){ if ( isArg( argv[ q ], WINDOWED_ARG, NUM_ARGS(WINDOWED_ARG) ) ){ gfx = Global::FULLSCREEN; } else if ( isArg( argv[ q ], DATAPATH_ARG, NUM_ARGS(DATAPATH_ARG) ) ){ q += 1; if ( q < argc ){ Util::setDataPath( argv[ q ] ); } } else if ( isArg( argv[ q ], MUSIC_ARG, NUM_ARGS(MUSIC_ARG) ) ){ music_on = false; } else if (isArg(argv[q], MUGEN_ARG, NUM_ARGS(MUGEN_ARG))){ mugen = true; } else if ( isArg( argv[ q ], DEBUG_ARG, NUM_ARGS(DEBUG_ARG) ) ){ q += 1; if ( q < argc ){ istringstream i( argv[ q ] ); int f; i >> f; Global::setDebug( f ); } #ifdef HAVE_NETWORKING } else if (isArg(argv[q], NETWORK_SERVER_ARG, NUM_ARGS(NETWORK_SERVER_ARG))){ just_network_server = true; #endif } else { const char * arg = argv[q]; const char * closest = closestMatch(arg, all_args); if (closest == NULL){ Global::debug(0) << "I don't recognize option '" << arg << "'" << endl; } else { Global::debug(0) << "You gave option '" << arg << "'. Did you mean '" << closest << "'?" << endl; } } } #undef NUM_ARGS showOptions(); Global::debug(0) << "Debug level: " << Global::getDebug() << endl; /* time how long init takes */ TimeDifference diff; diff.startTime(); /* init initializes practically everything including * graphics * sound * input * network * configuration * ... */ if (! Global::init(gfx)){ Global::debug( 0 ) << "Could not initialize system" << endl; return -1; } else { MenuGlobals::setFullscreen((gfx == Global::FULLSCREEN ? true : false)); } diff.endTime(); Global::debug(0) << diff.printTime("Init took") << endl; try{ Paintown::Mod::loadMod(Configuration::getCurrentGame()); } catch (const Filesystem::NotFound & e){ Global::debug(0) << "Could not load mod " << Configuration::getCurrentGame() << ": " << e.getReason() << endl; Paintown::Mod::loadDefaultMod(); } InputManager input; Music music(music_on); while (true){ try{ /* fadein from white */ Menu game(true, Bitmap::makeColor(255, 255, 255)); game.load(mainMenuPath()); if (just_network_server){ #ifdef HAVE_NETWORKING Network::networkServer(&game); #endif } else if (mugen){ Mugen::run(); } else { game.run(); } } catch (const Filesystem::Exception & ex){ Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getReason() << endl; } catch (const TokenException & ex){ Global::debug(0) << "There was a problem with the token. Error was:\n " << ex.getReason() << endl; return -1; } catch (const LoadException & ex){ Global::debug(0) << "There was a problem loading the main menu. Error was:\n " << ex.getReason() << endl; return -1; } catch (const Exception::Return & ex){ } catch (const ShutdownException & shutdown){ Global::debug(1) << "Forced a shutdown. Cya!" << endl; } catch (const MugenException & m){ Global::debug(0) << "Mugen exception: " << m.getReason() << endl; } catch (const ReloadMenuException & ex){ Global::debug(1) << "Menu Reload Requested. Restarting...." << endl; continue; } catch (const ftalleg::Exception & ex){ Global::debug(0) << "Freetype exception caught. Error was:\n" << ex.getReason() << endl; } catch (const Exception::Base & base){ /* FIXME: print base.tostring */ // Global::debug(0) << "Freetype exception caught. Error was:\n" << ex.getReason() << endl; } catch (...){ Global::debug(0) << "Uncaught exception!" << endl; } break; } Configuration::saveConfiguration(); return 0; }
remove includes for hack
remove includes for hack git-svn-id: 39e099a8ed5324aded674b764a67f7a08796d9a7@4334 662fdd30-d327-0410-a531-f549c87e1e9e
C++
bsd-3-clause
Sevalecan/paintown,boyjimeking/paintown,boyjimeking/paintown,boyjimeking/paintown,Sevalecan/paintown,Sevalecan/paintown,boyjimeking/paintown,boyjimeking/paintown,Sevalecan/paintown,boyjimeking/paintown,Sevalecan/paintown,Sevalecan/paintown,boyjimeking/paintown,Sevalecan/paintown,boyjimeking/paintown,Sevalecan/paintown
3d63afb7761360fc19bc1480e29de2967873cdf2
jubatus/core/driver/recommender.cpp
jubatus/core/driver/recommender.cpp
// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "recommender.hpp" #include <string> #include <utility> #include <vector> #include "jubatus/util/lang/shared_ptr.h" #include "../common/exception.hpp" #include "../common/vector_util.hpp" #include "../fv_converter/datum.hpp" #include "../fv_converter/datum_to_fv_converter.hpp" #include "../fv_converter/converter_config.hpp" #include "../fv_converter/revert.hpp" #include "../recommender/recommender_factory.hpp" #include "../storage/storage_factory.hpp" using std::string; using std::vector; using std::pair; using jubatus::core::framework::mixable_holder; using jubatus::core::fv_converter::weight_manager; using jubatus::util::lang::shared_ptr; namespace jubatus { namespace core { namespace driver { recommender::recommender( shared_ptr<core::recommender::recommender_base> recommender_method, shared_ptr<fv_converter::datum_to_fv_converter> converter) : mixable_holder_(new mixable_holder), converter_(converter), recommender_(recommender_method) { recommender_->register_mixables_to_holder(*mixable_holder_); converter_->register_mixables_to_holder(*mixable_holder_); } recommender::~recommender() { } void recommender::clear_row(const std::string& id) { recommender_->clear_row(id); } void recommender::update_row( const std::string& id, const fv_converter::datum& dat) { core::recommender::sfv_diff_t v; converter_->convert_and_update_weight(dat, v); recommender_->update_row(id, v); } void recommender::clear() { recommender_->clear(); converter_->clear_weights(); } fv_converter::datum recommender::complete_row_from_id(const std::string& id) { common::sfv_t v; recommender_->complete_row(id, v); fv_converter::datum ret; fv_converter::revert_feature(v, ret); return ret; } fv_converter::datum recommender::complete_row_from_datum( const fv_converter::datum& dat) { common::sfv_t u, v; converter_->convert(dat, u); recommender_->complete_row(u, v); fv_converter::datum ret; fv_converter::revert_feature(v, ret); return ret; } std::vector<std::pair<std::string, float> > recommender::similar_row_from_id( const std::string& id, size_t ret_num) { std::vector<std::pair<std::string, float> > ret; recommender_->similar_row(id, ret, ret_num); return ret; } std::vector<std::pair<std::string, float> > recommender::similar_row_from_datum( const fv_converter::datum& data, size_t size) { common::sfv_t v; converter_->convert(data, v); std::vector<std::pair<std::string, float> > ret; recommender_->similar_row(v, ret, size); return ret; } float recommender::calc_similality( const fv_converter::datum& l, const fv_converter::datum& r) { common::sfv_t v0, v1; converter_->convert(l, v0); converter_->convert(r, v1); return jubatus::core::recommender::recommender_base::calc_similality(v0, v1); } float recommender::calc_l2norm(const fv_converter::datum& q) { common::sfv_t v0; converter_->convert(q, v0); return jubatus::core::recommender::recommender_base::calc_l2norm(v0); } fv_converter::datum recommender::decode_row(const std::string& id) { common::sfv_t v; recommender_->decode_row(id, v); fv_converter::datum ret; fv_converter::revert_feature(v, ret); return ret; } std::vector<std::string> recommender::get_all_rows() { std::vector<std::string> ret; recommender_->get_all_row_ids(ret); return ret; } } // namespace driver } // namespace core } // namespace jubatus
// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include "recommender.hpp" #include <string> #include <utility> #include <vector> #include "jubatus/util/lang/shared_ptr.h" #include "../common/exception.hpp" #include "../common/vector_util.hpp" #include "../fv_converter/datum.hpp" #include "../fv_converter/datum_to_fv_converter.hpp" #include "../fv_converter/converter_config.hpp" #include "../fv_converter/revert.hpp" #include "../recommender/recommender_factory.hpp" using std::string; using std::vector; using std::pair; using jubatus::core::framework::mixable_holder; using jubatus::core::fv_converter::weight_manager; using jubatus::util::lang::shared_ptr; namespace jubatus { namespace core { namespace driver { recommender::recommender( shared_ptr<core::recommender::recommender_base> recommender_method, shared_ptr<fv_converter::datum_to_fv_converter> converter) : mixable_holder_(new mixable_holder), converter_(converter), recommender_(recommender_method) { recommender_->register_mixables_to_holder(*mixable_holder_); converter_->register_mixables_to_holder(*mixable_holder_); } recommender::~recommender() { } void recommender::clear_row(const std::string& id) { recommender_->clear_row(id); } void recommender::update_row( const std::string& id, const fv_converter::datum& dat) { core::recommender::sfv_diff_t v; converter_->convert_and_update_weight(dat, v); recommender_->update_row(id, v); } void recommender::clear() { recommender_->clear(); converter_->clear_weights(); } fv_converter::datum recommender::complete_row_from_id(const std::string& id) { common::sfv_t v; recommender_->complete_row(id, v); fv_converter::datum ret; fv_converter::revert_feature(v, ret); return ret; } fv_converter::datum recommender::complete_row_from_datum( const fv_converter::datum& dat) { common::sfv_t u, v; converter_->convert(dat, u); recommender_->complete_row(u, v); fv_converter::datum ret; fv_converter::revert_feature(v, ret); return ret; } std::vector<std::pair<std::string, float> > recommender::similar_row_from_id( const std::string& id, size_t ret_num) { std::vector<std::pair<std::string, float> > ret; recommender_->similar_row(id, ret, ret_num); return ret; } std::vector<std::pair<std::string, float> > recommender::similar_row_from_datum( const fv_converter::datum& data, size_t size) { common::sfv_t v; converter_->convert(data, v); std::vector<std::pair<std::string, float> > ret; recommender_->similar_row(v, ret, size); return ret; } float recommender::calc_similality( const fv_converter::datum& l, const fv_converter::datum& r) { common::sfv_t v0, v1; converter_->convert(l, v0); converter_->convert(r, v1); return jubatus::core::recommender::recommender_base::calc_similality(v0, v1); } float recommender::calc_l2norm(const fv_converter::datum& q) { common::sfv_t v0; converter_->convert(q, v0); return jubatus::core::recommender::recommender_base::calc_l2norm(v0); } fv_converter::datum recommender::decode_row(const std::string& id) { common::sfv_t v; recommender_->decode_row(id, v); fv_converter::datum ret; fv_converter::revert_feature(v, ret); return ret; } std::vector<std::string> recommender::get_all_rows() { std::vector<std::string> ret; recommender_->get_all_row_ids(ret); return ret; } } // namespace driver } // namespace core } // namespace jubatus
remove unused include
remove unused include
C++
lgpl-2.1
Asuka52/jubatus,gintenlabo/jubatus,kmaehashi/jubatus,gintenlabo/jubatus,roselleebarle04/jubatus,roselleebarle04/jubatus,rimms/jubatus,jubatus/jubatus,kmaehashi/jubatus,elkingtonmcb/jubatus,elkingtonmcb/jubatus,rimms/jubatus,jubatus/jubatus,mathn/jubatus,Asuka52/jubatus,jubatus/jubatus,mathn/jubatus
2e8582349b5e721bb9624b4b454e4c3d46301978
korganizer/korgac/koalarmclient.cpp
korganizer/korgac/koalarmclient.cpp
/* KOrganizer Alarm Daemon Client. This file is part of KOrganizer. Copyright (c) 2002,2003 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ //krazy:excludeall=kdebug because we use the korgac(check) debug area in here #include "koalarmclient.h" #include "alarmdialog.h" #include "alarmdockwindow.h" #include "korgacadaptor.h" #include <KCal/CalendarResources> using namespace KCal; #include <KApplication> #include <KConfig> #include <KConfigGroup> #include <KDebug> #include <KStandardDirs> KOAlarmClient::KOAlarmClient( QObject *parent ) : QObject( parent ), mDialog( 0 ) { new KOrgacAdaptor( this ); QDBusConnection::sessionBus().registerObject( "/ac", this ); kDebug(); KConfig korgConfig( KStandardDirs::locate( "config", "korganizerrc" ) ); KConfigGroup generalGroup( &korgConfig, "General" ); bool showDock = generalGroup.readEntry( "ShowReminderDaemon", true ); mDocker = new AlarmDockWindow; if ( showDock ) { mDocker->show(); } else { mDocker->hide(); } connect( this, SIGNAL(reminderCount(int)), mDocker, SLOT(slotUpdate(int)) ); connect( mDocker, SIGNAL(quitSignal()), SLOT(slotQuit()) ); KConfigGroup timedateGroup( &korgConfig, "Time & Date" ); QString tz = timedateGroup.readEntry( "TimeZoneId" ); kDebug() << "TimeZone:" << tz; mCalendar = new CalendarResources( tz ); mCalendar->readConfig(); mCalendar->load(); connect( &mCheckTimer, SIGNAL(timeout()), SLOT(checkAlarms()) ); KConfigGroup alarmGroup( KGlobal::config(), "Alarms" ); int interval = alarmGroup.readEntry( "Interval", 60 ); kDebug() << "KOAlarmClient check interval:" << interval << "seconds."; mLastChecked = alarmGroup.readEntry( "CalendarsLastChecked", QDateTime() ); // load reminders that were active when quitting KConfigGroup genGroup( KGlobal::config(), "General" ); int numReminders = genGroup.readEntry( "Reminders", 0 ); for ( int i=1; i<=numReminders; ++i ) { QString group( QString( "Incidence-%1" ).arg( i ) ); KConfigGroup *incGroup = new KConfigGroup( KGlobal::config(), group ); QString uid = incGroup->readEntry( "UID" ); QDateTime dt = incGroup->readEntry( "RemindAt", QDateTime() ); if ( !uid.isEmpty() ) { createReminder( mCalendar->incidence( uid ), dt, QString() ); } delete incGroup; } if ( numReminders ) { genGroup.writeEntry( "Reminders", 0 ); genGroup.sync(); } checkAlarms(); mCheckTimer.start( 1000 * interval ); // interval in seconds } KOAlarmClient::~KOAlarmClient() { delete mCalendar; delete mDocker; delete mDialog; } void KOAlarmClient::checkAlarms() { KConfigGroup cfg( KGlobal::config(), "General" ); if ( !cfg.readEntry( "Enabled", true ) ) { return; } QDateTime from = mLastChecked.addSecs( 1 ); mLastChecked = QDateTime::currentDateTime(); kDebug(5891) << "Check:" << from.toString() << " -" << mLastChecked.toString(); QList<Alarm *>alarms = mCalendar->alarms( KDateTime( from, KDateTime::LocalZone ), KDateTime( mLastChecked, KDateTime::LocalZone ) ); QList<Alarm *>::ConstIterator it; for ( it = alarms.constBegin(); it != alarms.constEnd(); ++it ) { kDebug(5891) << "REMINDER:" << (*it)->parent()->summary(); Incidence *incidence = mCalendar->incidence( (*it)->parent()->uid() ); createReminder( incidence, QDateTime::currentDateTime(), (*it)->text() ); } } void KOAlarmClient::createReminder( KCal::Incidence *incidence, const QDateTime &dt, const QString &displayText ) { if ( !incidence ) { return; } if ( !mDialog ) { mDialog = new AlarmDialog(); connect( mDialog, SIGNAL(reminderCount(int)), mDocker, SLOT(slotUpdate(int)) ); connect( mDocker, SIGNAL(suspendAllSignal()), mDialog, SLOT(suspendAll()) ); connect( mDocker, SIGNAL(dismissAllSignal()), mDialog, SLOT(dismissAll()) ); connect( this, SIGNAL(saveAllSignal()), mDialog, SLOT(slotSave()) ); } mDialog->addIncidence( incidence, dt, displayText ); mDialog->wakeUp(); saveLastCheckTime(); } void KOAlarmClient::slotQuit() { emit saveAllSignal(); saveLastCheckTime(); quit(); } void KOAlarmClient::saveLastCheckTime() { KConfigGroup cg( KGlobal::config(), "Alarms" ); cg.writeEntry( "CalendarsLastChecked", mLastChecked ); KGlobal::config()->sync(); } void KOAlarmClient::quit() { kDebug(); kapp->quit(); } bool KOAlarmClient::commitData( QSessionManager & ) { emit saveAllSignal(); saveLastCheckTime(); return true; } void KOAlarmClient::forceAlarmCheck() { checkAlarms(); saveLastCheckTime(); } void KOAlarmClient::dumpDebug() { KConfigGroup cfg( KGlobal::config(), "Alarms" ); QDateTime lastChecked = cfg.readEntry( "CalendarsLastChecked", QDateTime() ); kDebug() << "Last Check:" << lastChecked; } QStringList KOAlarmClient::dumpAlarms() { KDateTime start = KDateTime( QDateTime::currentDateTime().date(), QTime( 0, 0 ), KDateTime::LocalZone ); KDateTime end = start.addDays( 1 ).addSecs( -1 ); QStringList lst; // Don't translate, this is for debugging purposes. lst << QString( "AlarmDeamon::dumpAlarms() from " ) + start.toString() + " to " + end.toString(); QList<Alarm *> alarms = mCalendar->alarms( start, end ); QList<Alarm *>::ConstIterator it; for ( it = alarms.constBegin(); it != alarms.constEnd(); ++it ) { Alarm *a = *it; lst << QString( " " ) + a->parent()->summary() + " (" + a->time().toString() + ')'; } return lst; } void KOAlarmClient::debugShowDialog() { // showAlarmDialog(); } void KOAlarmClient::hide() { mDocker->hide(); } void KOAlarmClient::show() { mDocker->show(); } #include "koalarmclient.moc"
/* KOrganizer Alarm Daemon Client. This file is part of KOrganizer. Copyright (c) 2002,2003 Cornelius Schumacher <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ //krazy:excludeall=kdebug because we use the korgac(check) debug area in here #include "koalarmclient.h" #include "alarmdialog.h" #include "alarmdockwindow.h" #include "korgacadaptor.h" #include <KCal/CalendarResources> using namespace KCal; #include <KApplication> #include <KConfig> #include <KConfigGroup> #include <KDebug> #include <KStandardDirs> KOAlarmClient::KOAlarmClient( QObject *parent ) : QObject( parent ), mDialog( 0 ) { new KOrgacAdaptor( this ); QDBusConnection::sessionBus().registerObject( "/ac", this ); kDebug(); KConfig korgConfig( KStandardDirs::locate( "config", "korganizerrc" ) ); KConfigGroup generalGroup( &korgConfig, "General" ); bool showDock = generalGroup.readEntry( "ShowReminderDaemon", true ); mDocker = new AlarmDockWindow; if ( showDock ) { mDocker->show(); } else { mDocker->hide(); } connect( this, SIGNAL(reminderCount(int)), mDocker, SLOT(slotUpdate(int)) ); connect( mDocker, SIGNAL(quitSignal()), SLOT(slotQuit()) ); const KTimeZone zone = KSystemTimeZones::local(); mCalendar = new CalendarResources( zone.isValid() ? KDateTime::Spec( zone ) : KDateTime::ClockTime ); mCalendar->readConfig(); mCalendar->load(); connect( &mCheckTimer, SIGNAL(timeout()), SLOT(checkAlarms()) ); KConfigGroup alarmGroup( KGlobal::config(), "Alarms" ); int interval = alarmGroup.readEntry( "Interval", 60 ); kDebug() << "KOAlarmClient check interval:" << interval << "seconds."; mLastChecked = alarmGroup.readEntry( "CalendarsLastChecked", QDateTime() ); // load reminders that were active when quitting KConfigGroup genGroup( KGlobal::config(), "General" ); int numReminders = genGroup.readEntry( "Reminders", 0 ); for ( int i=1; i<=numReminders; ++i ) { QString group( QString( "Incidence-%1" ).arg( i ) ); KConfigGroup *incGroup = new KConfigGroup( KGlobal::config(), group ); QString uid = incGroup->readEntry( "UID" ); QDateTime dt = incGroup->readEntry( "RemindAt", QDateTime() ); if ( !uid.isEmpty() ) { createReminder( mCalendar->incidence( uid ), dt, QString() ); } delete incGroup; } if ( numReminders ) { genGroup.writeEntry( "Reminders", 0 ); genGroup.sync(); } checkAlarms(); mCheckTimer.start( 1000 * interval ); // interval in seconds } KOAlarmClient::~KOAlarmClient() { delete mCalendar; delete mDocker; delete mDialog; } void KOAlarmClient::checkAlarms() { KConfigGroup cfg( KGlobal::config(), "General" ); if ( !cfg.readEntry( "Enabled", true ) ) { return; } QDateTime from = mLastChecked.addSecs( 1 ); mLastChecked = QDateTime::currentDateTime(); kDebug(5891) << "Check:" << from.toString() << " -" << mLastChecked.toString(); QList<Alarm *>alarms = mCalendar->alarms( KDateTime( from, KDateTime::LocalZone ), KDateTime( mLastChecked, KDateTime::LocalZone ) ); QList<Alarm *>::ConstIterator it; for ( it = alarms.constBegin(); it != alarms.constEnd(); ++it ) { kDebug(5891) << "REMINDER:" << (*it)->parent()->summary(); Incidence *incidence = mCalendar->incidence( (*it)->parent()->uid() ); createReminder( incidence, QDateTime::currentDateTime(), (*it)->text() ); } } void KOAlarmClient::createReminder( KCal::Incidence *incidence, const QDateTime &dt, const QString &displayText ) { if ( !incidence ) { return; } if ( !mDialog ) { mDialog = new AlarmDialog(); connect( mDialog, SIGNAL(reminderCount(int)), mDocker, SLOT(slotUpdate(int)) ); connect( mDocker, SIGNAL(suspendAllSignal()), mDialog, SLOT(suspendAll()) ); connect( mDocker, SIGNAL(dismissAllSignal()), mDialog, SLOT(dismissAll()) ); connect( this, SIGNAL(saveAllSignal()), mDialog, SLOT(slotSave()) ); } mDialog->addIncidence( incidence, dt, displayText ); mDialog->wakeUp(); saveLastCheckTime(); } void KOAlarmClient::slotQuit() { emit saveAllSignal(); saveLastCheckTime(); quit(); } void KOAlarmClient::saveLastCheckTime() { KConfigGroup cg( KGlobal::config(), "Alarms" ); cg.writeEntry( "CalendarsLastChecked", mLastChecked ); KGlobal::config()->sync(); } void KOAlarmClient::quit() { kDebug(); kapp->quit(); } bool KOAlarmClient::commitData( QSessionManager & ) { emit saveAllSignal(); saveLastCheckTime(); return true; } void KOAlarmClient::forceAlarmCheck() { checkAlarms(); saveLastCheckTime(); } void KOAlarmClient::dumpDebug() { KConfigGroup cfg( KGlobal::config(), "Alarms" ); QDateTime lastChecked = cfg.readEntry( "CalendarsLastChecked", QDateTime() ); kDebug() << "Last Check:" << lastChecked; } QStringList KOAlarmClient::dumpAlarms() { KDateTime start = KDateTime( QDateTime::currentDateTime().date(), QTime( 0, 0 ), KDateTime::LocalZone ); KDateTime end = start.addDays( 1 ).addSecs( -1 ); QStringList lst; // Don't translate, this is for debugging purposes. lst << QString( "AlarmDeamon::dumpAlarms() from " ) + start.toString() + " to " + end.toString(); QList<Alarm *> alarms = mCalendar->alarms( start, end ); QList<Alarm *>::ConstIterator it; for ( it = alarms.constBegin(); it != alarms.constEnd(); ++it ) { Alarm *a = *it; lst << QString( " " ) + a->parent()->summary() + " (" + a->time().toString() + ')'; } return lst; } void KOAlarmClient::debugShowDialog() { // showAlarmDialog(); } void KOAlarmClient::hide() { mDocker->hide(); } void KOAlarmClient::show() { mDocker->show(); } #include "koalarmclient.moc"
Make alarmclient use the system timezone, not the korganizer one.
Make alarmclient use the system timezone, not the korganizer one. svn path=/trunk/KDE/kdepim/; revision=961286
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
1fbcbcdce0407c779a5c39dd41df10ef9ac15016
framework/cybertron/tools/cvt/monitor/cybertron_topology_message.cpp
framework/cybertron/tools/cvt/monitor/cybertron_topology_message.cpp
/****************************************************************************** * Copyright 2018 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 "cybertron_topology_message.h" #include "channel_msg_factory.h" #include "cybertron/proto/topology_change.pb.h" #include "cybertron_channel_message.h" #include "screen.h" #include <ncurses.h> #include <iomanip> #include <iostream> constexpr int SecondColumnOffset = 4; CybertronTopologyMessage::CybertronTopologyMessage() : RenderableMessage(), second_column_(SecondColumnType::MessageFrameRatio), pages_(1), page_item_count_(24), page_index_(0), col1_width_(8), all_channels_map_() {} CybertronTopologyMessage::~CybertronTopologyMessage(void) { apollo::cybertron::Shutdown(); for (auto item : all_channels_map_) { if (!ChannelMessage::isErrorCode(item.second)) { delete item.second; } } } RenderableMessage* CybertronTopologyMessage::Child(int lineNo) const { RenderableMessage* ret = nullptr; --lineNo; if (lineNo > -1 && lineNo < page_item_count_) { int i = 0; auto iter = all_channels_map_.cbegin(); while (i < page_index_ * page_item_count_) { ++iter; ++i; } for (i = 0; iter != all_channels_map_.cend(); ++iter) { if (i == lineNo) { if (!ChannelMessage::isErrorCode(iter->second)) { ret = iter->second; } break; } ++i; } } return ret; } void CybertronTopologyMessage::TopologyChanged( const apollo::cybertron::proto::ChangeMsg& changeMsg) { const std::string& nodeName = changeMsg.role_attr().node_name(); const std::string& channelName = changeMsg.role_attr().channel_name(); const std::string& msgTypeName = changeMsg.role_attr().message_type(); if ((int)channelName.length() > col1_width_) { col1_width_ = channelName.length(); } if (::apollo::cybertron::proto::OperateType::OPT_JOIN == changeMsg.operate_type()) { if (ChannelMsgFactory::Instance()->isFromHere(nodeName)) { return; } if (::apollo::cybertron::proto::RoleType::ROLE_WRITER == changeMsg.role_type() || ::apollo::cybertron::proto::RoleType::ROLE_READER == changeMsg.role_type()) { if (::apollo::cybertron::proto::ChangeType::CHANGE_CHANNEL == changeMsg.change_type()) { auto iter = all_channels_map_.find(channelName); if (iter == all_channels_map_.cend()) { ChannelMessage* channelMsg = ChannelMsgFactory::Instance()->CreateChannelMessage(msgTypeName, channelName); if (!ChannelMessage::isErrorCode(channelMsg)) { channelMsg->set_parent(this); channelMsg->set_message_type(msgTypeName); channelMsg->add_reader(channelMsg->NodeName()); if (::apollo::cybertron::proto::RoleType::ROLE_WRITER == changeMsg.role_type()) { channelMsg->add_writer(nodeName); } else { channelMsg->add_reader(nodeName); } } all_channels_map_[channelName] = channelMsg; } else { if (!ChannelMessage::isErrorCode(iter->second)) { if (::apollo::cybertron::proto::RoleType::ROLE_WRITER == changeMsg.role_type()) { iter->second->add_writer(nodeName); } if (::apollo::cybertron::proto::RoleType::ROLE_READER == changeMsg.role_type()) { iter->second->add_reader(nodeName); } } } } } } else { if (::apollo::cybertron::proto::ChangeType::CHANGE_CHANNEL == changeMsg.change_type()) { auto iter = all_channels_map_.find(channelName); if (iter != all_channels_map_.cend() && !ChannelMessage::isErrorCode(iter->second)) { if (::apollo::cybertron::proto::RoleType::ROLE_WRITER == changeMsg.role_type()) { iter->second->del_writer(nodeName); } if (::apollo::cybertron::proto::RoleType::ROLE_READER == changeMsg.role_type()) { iter->second->del_reader(nodeName); } } } } } void CybertronTopologyMessage::ChangeState(const Screen* s, int key) { switch (key) { case 'f': case 'F': second_column_ = SecondColumnType::MessageFrameRatio; break; case 't': case 'T': second_column_ = SecondColumnType::MessageType; break; case CTRL('d'): case KEY_NPAGE: ++page_index_; if (page_index_ >= pages_) page_index_ = pages_ - 1; break; case CTRL('u'): case KEY_PPAGE: --page_index_; if (page_index_ < 1) page_index_ = 0; break; case ' ': { ChannelMessage* child = static_cast<ChannelMessage*>(Child(s->highlight_line_no())); if (child) { child->set_enabled(!child->is_enabled()); } } default:; } } void CybertronTopologyMessage::Render(const Screen* s, int key) { page_item_count_ = s->Height() - 1; pages_ = all_channels_map_.size() / page_item_count_ + 1; ChangeState(s, key); unsigned y = 0; auto iter = all_channels_map_.cbegin(); while (y < page_index_ * page_item_count_) { ++iter; ++y; } y = 0; page_item_count_++; s->AddStr(0, y, Screen::WHITE_BLACK, "Channels"); switch (second_column_) { case SecondColumnType::MessageType: s->AddStr(col1_width_ + SecondColumnOffset, y, Screen::WHITE_BLACK, "TypeName"); break; case SecondColumnType::MessageFrameRatio: s->AddStr(col1_width_ + SecondColumnOffset, y, Screen::WHITE_BLACK, "FrameRatio"); break; } ++y; Screen::ColorPair color; std::ostringstream outStr; for (; iter != all_channels_map_.cend() && y < page_item_count_; ++iter, ++y) { color = Screen::RED_BLACK; if (!ChannelMessage::isErrorCode(iter->second)) { if (iter->second->is_enabled() && iter->second->has_message_come()) color = Screen::GREEN_BLACK; } s->SetCurrentColor(color); s->AddStr(0, y, iter->first.c_str()); if (!ChannelMessage::isErrorCode(iter->second)) { switch (second_column_) { case SecondColumnType::MessageType: s->AddStr(col1_width_ + SecondColumnOffset, y, iter->second->message_type().c_str()); break; case SecondColumnType::MessageFrameRatio: { outStr.str(""); outStr << std::fixed << std::setprecision(2) << iter->second->frame_ratio(); s->AddStr(col1_width_ + SecondColumnOffset, y, outStr.str().c_str()); } break; } } else { ChannelMessage::ErrorCode errcode = ChannelMessage::castPtr2ErrorCode(iter->second); s->AddStr(col1_width_ + SecondColumnOffset, y, ChannelMessage::errCode2Str(errcode)); } s->ClearCurrentColor(color); } }
/****************************************************************************** * Copyright 2018 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 "cybertron_topology_message.h" #include "channel_msg_factory.h" #include "cybertron/message/message_traits.h" #include "cybertron/proto/topology_change.pb.h" #include "cybertron_channel_message.h" #include "screen.h" #include <ncurses.h> #include <iomanip> #include <iostream> constexpr int SecondColumnOffset = 4; CybertronTopologyMessage::CybertronTopologyMessage() : RenderableMessage(), second_column_(SecondColumnType::MessageFrameRatio), pages_(1), page_item_count_(24), page_index_(0), col1_width_(8), all_channels_map_() {} CybertronTopologyMessage::~CybertronTopologyMessage(void) { apollo::cybertron::Shutdown(); for (auto item : all_channels_map_) { if (!ChannelMessage::isErrorCode(item.second)) { delete item.second; } } } RenderableMessage* CybertronTopologyMessage::Child(int lineNo) const { RenderableMessage* ret = nullptr; --lineNo; if (lineNo > -1 && lineNo < page_item_count_) { int i = 0; auto iter = all_channels_map_.cbegin(); while (i < page_index_ * page_item_count_) { ++iter; ++i; } for (i = 0; iter != all_channels_map_.cend(); ++iter) { if (i == lineNo) { if (!ChannelMessage::isErrorCode(iter->second)) { ret = iter->second; } break; } ++i; } } return ret; } void CybertronTopologyMessage::TopologyChanged( const apollo::cybertron::proto::ChangeMsg& changeMsg) { const std::string& nodeName = changeMsg.role_attr().node_name(); const std::string& channelName = changeMsg.role_attr().channel_name(); const std::string& msgTypeName = changeMsg.role_attr().message_type(); if ((int)channelName.length() > col1_width_) { col1_width_ = channelName.length(); } if (::apollo::cybertron::proto::OperateType::OPT_JOIN == changeMsg.operate_type()) { if (ChannelMsgFactory::Instance()->isFromHere(nodeName)) { return; } ChannelMessage* channelMsg = nullptr; auto iter = all_channels_map_.find(channelName); if (iter == all_channels_map_.cend()) { channelMsg = ChannelMsgFactory::Instance()->CreateChannelMessage( msgTypeName, channelName); if (!ChannelMessage::isErrorCode(channelMsg)) { channelMsg->set_parent(this); channelMsg->set_message_type(msgTypeName); channelMsg->add_reader(channelMsg->NodeName()); } all_channels_map_[channelName] = channelMsg; } else { channelMsg = iter->second; } if (!ChannelMessage::isErrorCode(channelMsg)) { if (::apollo::cybertron::proto::RoleType::ROLE_WRITER == changeMsg.role_type()) { channelMsg->add_writer(nodeName); } else { channelMsg->add_reader(nodeName); } if (msgTypeName != apollo::cybertron::message::MessageType< apollo::cybertron::message::RawMessage>()) { channelMsg->set_message_type(msgTypeName); } } } else { auto iter = all_channels_map_.find(channelName); if (iter != all_channels_map_.cend() && !ChannelMessage::isErrorCode(iter->second)) { if (::apollo::cybertron::proto::RoleType::ROLE_WRITER == changeMsg.role_type()) { iter->second->del_writer(nodeName); } else { iter->second->del_reader(nodeName); } } } } void CybertronTopologyMessage::ChangeState(const Screen* s, int key) { switch (key) { case 'f': case 'F': second_column_ = SecondColumnType::MessageFrameRatio; break; case 't': case 'T': second_column_ = SecondColumnType::MessageType; break; case CTRL('d'): case KEY_NPAGE: ++page_index_; if (page_index_ >= pages_) page_index_ = pages_ - 1; break; case CTRL('u'): case KEY_PPAGE: --page_index_; if (page_index_ < 1) page_index_ = 0; break; case ' ': { ChannelMessage* child = static_cast<ChannelMessage*>(Child(s->highlight_line_no())); if (child) { child->set_enabled(!child->is_enabled()); } } default:; } } void CybertronTopologyMessage::Render(const Screen* s, int key) { page_item_count_ = s->Height() - 1; pages_ = all_channels_map_.size() / page_item_count_ + 1; ChangeState(s, key); unsigned y = 0; auto iter = all_channels_map_.cbegin(); while (y < page_index_ * page_item_count_) { ++iter; ++y; } y = 0; page_item_count_++; s->AddStr(0, y, Screen::WHITE_BLACK, "Channels"); switch (second_column_) { case SecondColumnType::MessageType: s->AddStr(col1_width_ + SecondColumnOffset, y, Screen::WHITE_BLACK, "TypeName"); break; case SecondColumnType::MessageFrameRatio: s->AddStr(col1_width_ + SecondColumnOffset, y, Screen::WHITE_BLACK, "FrameRatio"); break; } ++y; Screen::ColorPair color; std::ostringstream outStr; for (; iter != all_channels_map_.cend() && y < page_item_count_; ++iter, ++y) { color = Screen::RED_BLACK; if (!ChannelMessage::isErrorCode(iter->second)) { if (iter->second->is_enabled() && iter->second->has_message_come()) color = Screen::GREEN_BLACK; } s->SetCurrentColor(color); s->AddStr(0, y, iter->first.c_str()); if (!ChannelMessage::isErrorCode(iter->second)) { switch (second_column_) { case SecondColumnType::MessageType: s->AddStr(col1_width_ + SecondColumnOffset, y, iter->second->message_type().c_str()); break; case SecondColumnType::MessageFrameRatio: { outStr.str(""); outStr << std::fixed << std::setprecision(2) << iter->second->frame_ratio(); s->AddStr(col1_width_ + SecondColumnOffset, y, outStr.str().c_str()); } break; } } else { ChannelMessage::ErrorCode errcode = ChannelMessage::castPtr2ErrorCode(iter->second); s->AddStr(col1_width_ + SecondColumnOffset, y, ChannelMessage::errCode2Str(errcode)); } s->ClearCurrentColor(color); } }
fix multi-monitors parse message problem
framework: fix multi-monitors parse message problem
C++
apache-2.0
wanglei828/apollo,ycool/apollo,ApolloAuto/apollo,ycool/apollo,ycool/apollo,jinghaomiao/apollo,ycool/apollo,xiaoxq/apollo,jinghaomiao/apollo,jinghaomiao/apollo,ApolloAuto/apollo,wanglei828/apollo,ycool/apollo,ApolloAuto/apollo,xiaoxq/apollo,wanglei828/apollo,ApolloAuto/apollo,xiaoxq/apollo,xiaoxq/apollo,xiaoxq/apollo,jinghaomiao/apollo,wanglei828/apollo,ycool/apollo,wanglei828/apollo,ApolloAuto/apollo,wanglei828/apollo,jinghaomiao/apollo,ApolloAuto/apollo,jinghaomiao/apollo,xiaoxq/apollo
223b0f3c31575b374dd7c0b70b9f1266e3880275
include/hpp/core/discretized-collision-checking.hh
include/hpp/core/discretized-collision-checking.hh
// // Copyright (c) 2014 CNRS // Authors: Florent Lamiraux // // This file is part of hpp-core // hpp-core 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 // 3 of the License, or (at your option) any later version. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #ifndef HPP_CORE_DISCRETIZED_COLLISION_CHECKING # define HPP_CORE_DISCRETIZED_COLLISION_CHECKING # include <hpp/core/collision-path-validation-report.hh> # include <hpp/core/path-validation.hh> namespace hpp { namespace core { /// \addtogroup validation /// \{ /// Validation of path by collision checking at discretized parameter values /// /// Should be replaced soon by a better algorithm class HPP_CORE_DLLAPI DiscretizedCollisionChecking : public PathValidation { public: static DiscretizedCollisionCheckingPtr_t create (const DevicePtr_t& robot, const value_type& stepSize); /// Compute the largest valid interval starting from the path beginning /// /// \param path the path to check for validity, /// \param reverse if true check from the end, /// \retval the extracted valid part of the path, pointer to path if /// path is valid. /// \retval report information about the validation process. The type /// can be derived for specific implementation /// \return whether the whole path is valid. /// \precond validationReport should be a of type /// CollisionPathValidationReport. virtual bool validate (const PathPtr_t& path, bool reverse, PathPtr_t& validPart); /// Compute the largest valid interval starting from the path beginning /// /// \param path the path to check for validity, /// \param reverse if true check from the end, /// \retval the extracted valid part of the path, pointer to path if /// path is valid. /// \retval report information about the validation process. The type /// can be derived for specific implementation /// \return whether the whole path is valid. /// \retval validationReport information about the validation process: /// which objects have been detected in collision and at which /// parameter along the path. /// \precond validationReport should be a of type /// CollisionPathValidationReport. virtual bool validate (const PathPtr_t& path, bool reverse, PathPtr_t& validPart, ValidationReport& validationReport); /// Add an obstacle /// \param object obstacle added virtual void addObstacle (const CollisionObjectPtr_t&); protected: DiscretizedCollisionChecking (const DevicePtr_t& robot, const value_type& stepSize); private: DevicePtr_t robot_; CollisionValidationPtr_t collisionValidation_; value_type stepSize_; /// This member is used by the validate method that does not take a /// validation report as input to call the validate method that expects /// a validation report as input. This is not fully satisfactory, but /// I did not find a better solution. CollisionPathValidationReport unusedReport_; }; // class DiscretizedCollisionChecking /// \} } // namespace core } // namespace hpp #endif // HPP_CORE_DISCRETIZED_COLLISION_CHECKING
// // Copyright (c) 2014 CNRS // Authors: Florent Lamiraux // // This file is part of hpp-core // hpp-core 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 // 3 of the License, or (at your option) any later version. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core If not, see // <http://www.gnu.org/licenses/>. #ifndef HPP_CORE_DISCRETIZED_COLLISION_CHECKING # define HPP_CORE_DISCRETIZED_COLLISION_CHECKING # include <hpp/core/collision-path-validation-report.hh> # include <hpp/core/path-validation.hh> namespace hpp { namespace core { /// \addtogroup validation /// \{ /// Validation of path by collision checking at discretized parameter values /// /// Should be replaced soon by a better algorithm class HPP_CORE_DLLAPI DiscretizedCollisionChecking : public PathValidation { public: static DiscretizedCollisionCheckingPtr_t create (const DevicePtr_t& robot, const value_type& stepSize); /// Compute the largest valid interval starting from the path beginning /// /// \param path the path to check for validity, /// \param reverse if true check from the end, /// \retval validPart the extracted valid part of the path, /// pointer to path if path is valid. /// \retval report information about the validation process. The type /// can be derived for specific implementation /// \return whether the whole path is valid. virtual bool validate (const PathPtr_t& path, bool reverse, PathPtr_t& validPart); /// Compute the largest valid interval starting from the path beginning /// /// \param path the path to check for validity, /// \param reverse if true check from the end, /// \retval validPart the extracted valid part of the path, /// pointer to path if path is valid. /// \retval validationReport information about the validation process: /// which objects have been detected in collision and at which /// parameter along the path. /// \pre validationReport should be a of type /// CollisionPathValidationReport. /// \return whether the whole path is valid. virtual bool validate (const PathPtr_t& path, bool reverse, PathPtr_t& validPart, ValidationReport& validationReport); /// Add an obstacle /// \param object obstacle added virtual void addObstacle (const CollisionObjectPtr_t&); protected: DiscretizedCollisionChecking (const DevicePtr_t& robot, const value_type& stepSize); private: DevicePtr_t robot_; CollisionValidationPtr_t collisionValidation_; value_type stepSize_; /// This member is used by the validate method that does not take a /// validation report as input to call the validate method that expects /// a validation report as input. This is not fully satisfactory, but /// I did not find a better solution. CollisionPathValidationReport unusedReport_; }; // class DiscretizedCollisionChecking /// \} } // namespace core } // namespace hpp #endif // HPP_CORE_DISCRETIZED_COLLISION_CHECKING
Fix documentation.
Fix documentation.
C++
bsd-2-clause
humanoid-path-planner/hpp-core
a816f42e4da693f2e749b855da55d7bb4e4ccad4
lib/CodeGen/TargetSubtargetInfo.cpp
lib/CodeGen/TargetSubtargetInfo.cpp
//===- TargetSubtargetInfo.cpp - General Target Information ----------------==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file This file describes the general parts of a Subtarget. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/TargetSubtargetInfo.h" #include "llvm/ADT/Optional.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/TargetInstrInfo.h" #include "llvm/CodeGen/TargetSchedule.h" #include "llvm/MC/MCInst.h" #include "llvm/Support/Format.h" #include "llvm/Support/raw_ostream.h" #include <string> using namespace llvm; TargetSubtargetInfo::TargetSubtargetInfo( const Triple &TT, StringRef CPU, StringRef FS, ArrayRef<SubtargetFeatureKV> PF, ArrayRef<SubtargetFeatureKV> PD, const SubtargetInfoKV *ProcSched, const MCWriteProcResEntry *WPR, const MCWriteLatencyEntry *WL, const MCReadAdvanceEntry *RA, const InstrStage *IS, const unsigned *OC, const unsigned *FP) : MCSubtargetInfo(TT, CPU, FS, PF, PD, ProcSched, WPR, WL, RA, IS, OC, FP) { } TargetSubtargetInfo::~TargetSubtargetInfo() = default; bool TargetSubtargetInfo::enableAtomicExpand() const { return true; } bool TargetSubtargetInfo::enableIndirectBrExpand() const { return false; } bool TargetSubtargetInfo::enableMachineScheduler() const { return false; } bool TargetSubtargetInfo::enableJoinGlobalCopies() const { return enableMachineScheduler(); } bool TargetSubtargetInfo::enableRALocalReassignment( CodeGenOpt::Level OptLevel) const { return true; } bool TargetSubtargetInfo::enableAdvancedRASplitCost() const { return false; } bool TargetSubtargetInfo::enablePostRAScheduler() const { return getSchedModel().PostRAScheduler; } bool TargetSubtargetInfo::useAA() const { return false; } static std::string createSchedInfoStr(unsigned Latency, Optional<double> RThroughput) { static const char *SchedPrefix = " sched: ["; std::string Comment; raw_string_ostream CS(Comment); if (Latency > 0 && RThroughput.hasValue()) CS << SchedPrefix << Latency << format(":%2.2f", RThroughput.getValue()) << "]"; else if (Latency > 0) CS << SchedPrefix << Latency << ":?]"; else if (RThroughput.hasValue()) CS << SchedPrefix << "?:" << RThroughput.getValue() << "]"; CS.flush(); return Comment; } /// Returns string representation of scheduler comment std::string TargetSubtargetInfo::getSchedInfoStr(const MachineInstr &MI) const { if (MI.isPseudo() || MI.isTerminator()) return std::string(); // We don't cache TSchedModel because it depends on TargetInstrInfo // that could be changed during the compilation TargetSchedModel TSchedModel; TSchedModel.init(getSchedModel(), this, getInstrInfo()); unsigned Latency = TSchedModel.computeInstrLatency(&MI); Optional<double> RThroughput = TSchedModel.computeInstrRThroughput(&MI); return createSchedInfoStr(Latency, RThroughput); } /// Returns string representation of scheduler comment std::string TargetSubtargetInfo::getSchedInfoStr(MCInst const &MCI) const { // We don't cache TSchedModel because it depends on TargetInstrInfo // that could be changed during the compilation TargetSchedModel TSchedModel; TSchedModel.init(getSchedModel(), this, getInstrInfo()); unsigned Latency; if (TSchedModel.hasInstrSchedModel()) Latency = TSchedModel.computeInstrLatency(MCI.getOpcode()); else if (TSchedModel.hasInstrItineraries()) { auto *ItinData = TSchedModel.getInstrItineraries(); Latency = ItinData->getStageLatency( getInstrInfo()->get(MCI.getOpcode()).getSchedClass()); } else return std::string(); Optional<double> RThroughput = TSchedModel.computeInstrRThroughput(MCI.getOpcode()); return createSchedInfoStr(Latency, RThroughput); } void TargetSubtargetInfo::mirFileLoaded(MachineFunction &MF) const { }
//===- TargetSubtargetInfo.cpp - General Target Information ----------------==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file This file describes the general parts of a Subtarget. // //===----------------------------------------------------------------------===// #include "llvm/CodeGen/TargetSubtargetInfo.h" #include "llvm/ADT/Optional.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/TargetInstrInfo.h" #include "llvm/CodeGen/TargetSchedule.h" #include "llvm/MC/MCInst.h" #include "llvm/Support/Format.h" #include "llvm/Support/raw_ostream.h" #include <string> using namespace llvm; TargetSubtargetInfo::TargetSubtargetInfo( const Triple &TT, StringRef CPU, StringRef FS, ArrayRef<SubtargetFeatureKV> PF, ArrayRef<SubtargetFeatureKV> PD, const SubtargetInfoKV *ProcSched, const MCWriteProcResEntry *WPR, const MCWriteLatencyEntry *WL, const MCReadAdvanceEntry *RA, const InstrStage *IS, const unsigned *OC, const unsigned *FP) : MCSubtargetInfo(TT, CPU, FS, PF, PD, ProcSched, WPR, WL, RA, IS, OC, FP) { } TargetSubtargetInfo::~TargetSubtargetInfo() = default; bool TargetSubtargetInfo::enableAtomicExpand() const { return true; } bool TargetSubtargetInfo::enableIndirectBrExpand() const { return false; } bool TargetSubtargetInfo::enableMachineScheduler() const { return false; } bool TargetSubtargetInfo::enableJoinGlobalCopies() const { return enableMachineScheduler(); } bool TargetSubtargetInfo::enableRALocalReassignment( CodeGenOpt::Level OptLevel) const { return true; } bool TargetSubtargetInfo::enableAdvancedRASplitCost() const { return false; } bool TargetSubtargetInfo::enablePostRAScheduler() const { return getSchedModel().PostRAScheduler; } bool TargetSubtargetInfo::useAA() const { return false; } static std::string createSchedInfoStr(unsigned Latency, Optional<double> RThroughput) { static const char *SchedPrefix = " sched: ["; std::string Comment; raw_string_ostream CS(Comment); if (RThroughput.hasValue()) CS << SchedPrefix << Latency << format(":%2.2f", RThroughput.getValue()) << "]"; else CS << SchedPrefix << Latency << ":?]"; CS.flush(); return Comment; } /// Returns string representation of scheduler comment std::string TargetSubtargetInfo::getSchedInfoStr(const MachineInstr &MI) const { if (MI.isPseudo() || MI.isTerminator()) return std::string(); // We don't cache TSchedModel because it depends on TargetInstrInfo // that could be changed during the compilation TargetSchedModel TSchedModel; TSchedModel.init(getSchedModel(), this, getInstrInfo()); unsigned Latency = TSchedModel.computeInstrLatency(&MI); Optional<double> RThroughput = TSchedModel.computeInstrRThroughput(&MI); return createSchedInfoStr(Latency, RThroughput); } /// Returns string representation of scheduler comment std::string TargetSubtargetInfo::getSchedInfoStr(MCInst const &MCI) const { // We don't cache TSchedModel because it depends on TargetInstrInfo // that could be changed during the compilation TargetSchedModel TSchedModel; TSchedModel.init(getSchedModel(), this, getInstrInfo()); unsigned Latency; if (TSchedModel.hasInstrSchedModel()) Latency = TSchedModel.computeInstrLatency(MCI.getOpcode()); else if (TSchedModel.hasInstrItineraries()) { auto *ItinData = TSchedModel.getInstrItineraries(); Latency = ItinData->getStageLatency( getInstrInfo()->get(MCI.getOpcode()).getSchedClass()); } else return std::string(); Optional<double> RThroughput = TSchedModel.computeInstrRThroughput(MCI.getOpcode()); return createSchedInfoStr(Latency, RThroughput); } void TargetSubtargetInfo::mirFileLoaded(MachineFunction &MF) const { }
allow printing of zero latency in sched comments
[CodeGen] allow printing of zero latency in sched comments I don't know how to expose this in a test. There are ARM / AArch64 sched classes that include zero latency instructions, but I'm not seeing sched info printed for those targets. X86 will almost certainly have these soon (see PR36671), but no model has 'let Latency = 0' currently. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@327518 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm
81650e59c1e796d62ea29a2967309f0ba40519ad
include/mapnik/json/geometry_generator_grammar.hpp
include/mapnik/json/geometry_generator_grammar.hpp
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2012 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP #define MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP // mapnik #include <mapnik/global.hpp> #include <mapnik/geometry.hpp> #include <mapnik/util/path_iterator.hpp> #include <mapnik/util/container_adapter.hpp> #include <mapnik/vertex.hpp> // for CommandType::SEG_MOVETO // boost #include <boost/tuple/tuple.hpp> #include <boost/spirit/include/karma.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/include/phoenix_function.hpp> #include <boost/spirit/include/phoenix_statement.hpp> #include <boost/fusion/include/boost_tuple.hpp> #include <boost/math/special_functions/trunc.hpp> // for vc++ namespace boost { namespace spirit { namespace traits { // make gcc and darwin toolsets happy. template <> struct is_container<mapnik::geometry_container> : mpl::false_ {}; }}} namespace mapnik { namespace json { namespace karma = boost::spirit::karma; namespace phoenix = boost::phoenix; namespace { #ifdef BOOST_SPIRIT_USE_PHOENIX_V3 struct get_type { typedef int result_type; result_type operator() (geometry_type const& geom) const { return static_cast<int>(geom.type()); } }; struct get_first { typedef geometry_type::value_type const result_type; result_type operator() (geometry_type const& geom) const { geometry_type::value_type coord; boost::get<0>(coord) = geom.vertex(0,&boost::get<1>(coord),&boost::get<2>(coord)); return coord; } }; struct multi_geometry_type { typedef boost::tuple<unsigned,bool> result_type; result_type operator() (geometry_container const& geom) const { unsigned type = 0u; bool collection = false; geometry_container::const_iterator itr = geom.begin(); geometry_container::const_iterator end = geom.end(); for ( ; itr != end; ++itr) { if (type != 0u && itr->type() != type) { collection = true; break; } type = itr->type(); } if (geom.size() > 1) type +=3; return boost::tuple<unsigned,bool>(type, collection); } }; #else struct get_type { template <typename T> struct result { typedef int type; }; int operator() (geometry_type const& geom) const { return static_cast<int>(geom.type()); } }; struct get_first { template <typename T> struct result { typedef geometry_type::value_type const type; }; geometry_type::value_type const operator() (geometry_type const& geom) const { geometry_type::value_type coord; boost::get<0>(coord) = geom.vertex(0,&boost::get<1>(coord),&boost::get<2>(coord)); return coord; } }; struct multi_geometry_type { template <typename T> struct result { typedef boost::tuple<unsigned,bool> type; }; boost::tuple<unsigned,bool> operator() (geometry_container const& geom) const { unsigned type = 0u; bool collection = false; geometry_container::const_iterator itr = geom.begin(); geometry_container::const_iterator end = geom.end(); for ( ; itr != end; ++itr) { if (type != 0u && itr->type() != type) { collection = true; break; } type = itr->type(); } if (geom.size() > 1) type +=3; return boost::tuple<unsigned,bool>(type, collection); } }; #endif template <typename T> struct json_coordinate_policy : karma::real_policies<T> { typedef boost::spirit::karma::real_policies<T> base_type; static int floatfield(T n) { return base_type::fmtflags::fixed; } static unsigned precision(T n) { if (n == 0.0) return 0; using namespace boost::spirit; return static_cast<unsigned>(14 - boost::math::trunc(log10(traits::get_absolute_value(n)))); } template <typename OutputIterator> static bool dot(OutputIterator& sink, T n, unsigned precision) { if (n == 0) return true; return base_type::dot(sink, n, precision); } template <typename OutputIterator> static bool fraction_part(OutputIterator& sink, T n , unsigned adjprec, unsigned precision) { if (n == 0) return true; return base_type::fraction_part(sink, n, adjprec, precision); } }; } template <typename OutputIterator> struct geometry_generator_grammar : karma::grammar<OutputIterator, geometry_type const& ()> { geometry_generator_grammar() : geometry_generator_grammar::base_type(coordinates) { using boost::spirit::karma::uint_; using boost::spirit::karma::_val; using boost::spirit::karma::_1; using boost::spirit::karma::lit; using boost::spirit::karma::_a; using boost::spirit::karma::_r1; using boost::spirit::karma::eps; coordinates = point | linestring | polygon ; point = &uint_(mapnik::Point)[_1 = _type(_val)] << point_coord [_1 = _first(_val)] ; linestring = &uint_(mapnik::LineString)[_1 = _type(_val)] << lit('[') << coords << lit(']') ; polygon = &uint_(mapnik::Polygon)[_1 = _type(_val)] << lit('[') << coords2 << lit("]]") ; point_coord = &uint_ << lit('[') << coord_type << lit(',') << coord_type << lit("]") ; polygon_coord %= ( &uint_(mapnik::SEG_MOVETO) << eps[_r1 += 1] << karma::string[ if_ (_r1 > 1) [_1 = "],["] .else_[_1 = '[' ]] | &uint_(mapnik::SEG_LINETO)) << lit(',') << lit('[') << coord_type << lit(',') << coord_type << lit(']') ; coords2 %= *polygon_coord(_a) ; coords = point_coord % lit(',') ; } // rules karma::rule<OutputIterator, geometry_type const& ()> coordinates; karma::rule<OutputIterator, geometry_type const& ()> point; karma::rule<OutputIterator, geometry_type const& ()> linestring; karma::rule<OutputIterator, geometry_type const& ()> polygon; karma::rule<OutputIterator, geometry_type const& ()> coords; karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const& ()> coords2; karma::rule<OutputIterator, geometry_type::value_type ()> point_coord; karma::rule<OutputIterator, geometry_type::value_type (unsigned& )> polygon_coord; // phoenix functions phoenix::function<get_type > _type; phoenix::function<get_first> _first; // karma::real_generator<double, json_coordinate_policy<double> > coord_type; }; template <typename OutputIterator> struct multi_geometry_generator_grammar : karma::grammar<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const& ()> { multi_geometry_generator_grammar() : multi_geometry_generator_grammar::base_type(start) { using boost::spirit::karma::lit; using boost::spirit::karma::eps; using boost::spirit::karma::_val; using boost::spirit::karma::_1; using boost::spirit::karma::_a; using boost::spirit::karma::_r1; geometry_types.add (mapnik::Point,"\"Point\"") (mapnik::LineString,"\"LineString\"") (mapnik::Polygon,"\"Polygon\"") (mapnik::Point + 3,"\"MultiPoint\"") (mapnik::LineString + 3,"\"MultiLineString\"") (mapnik::Polygon + 3,"\"MultiPolygon\"") ; start %= ( eps(phoenix::at_c<1>(_a))[_a = _multi_type(_val)] << lit("{\"type\":\"GeometryCollection\",\"geometries\":[") << geometry_collection << lit("]}") | geometry) ; geometry_collection = -(geometry2 % lit(',')) ; geometry = (lit("{\"type\":") << geometry_types[_1 = phoenix::at_c<0>(_a)][_a = _multi_type(_val)] << lit(",\"coordinates\":") << karma::string[ phoenix::if_ (phoenix::at_c<0>(_a) > 3) [_1 = '['].else_[_1 = ""]] << coordinates << karma::string[ phoenix::if_ (phoenix::at_c<0>(_a) > 3) [_1 = ']'].else_[_1 = ""]] << lit('}')) | lit("null") ; geometry2 = lit("{\"type\":") << geometry_types[_1 = _a][_a = type_(_val)] << lit(",\"coordinates\":") << path << lit('}') ; coordinates %= path % lit(',') ; } // rules karma::rule<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const&()> start; karma::rule<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const&()> geometry_collection; karma::rule<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const&()> geometry; karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const&()> geometry2; karma::rule<OutputIterator, geometry_container const&()> coordinates; geometry_generator_grammar<OutputIterator> path; // phoenix phoenix::function<multi_geometry_type> _multi_type; phoenix::function<get_type > type_; // symbols table karma::symbols<unsigned, char const*> geometry_types; }; }} #endif // MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2012 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP #define MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP // mapnik #include <mapnik/global.hpp> #include <mapnik/geometry.hpp> #include <mapnik/util/path_iterator.hpp> #include <mapnik/util/container_adapter.hpp> #include <mapnik/vertex.hpp> // for CommandType::SEG_MOVETO // boost #include <boost/tuple/tuple.hpp> #include <boost/spirit/include/karma.hpp> #include <boost/spirit/include/phoenix_core.hpp> #include <boost/spirit/include/phoenix_operator.hpp> #include <boost/spirit/include/phoenix_fusion.hpp> #include <boost/spirit/include/phoenix_function.hpp> #include <boost/spirit/include/phoenix_statement.hpp> #include <boost/fusion/include/boost_tuple.hpp> #include <boost/math/special_functions/trunc.hpp> // for vc++ namespace boost { namespace spirit { namespace traits { // make gcc and darwin toolsets happy. template <> struct is_container<mapnik::geometry_container> : mpl::false_ {}; }}} namespace mapnik { namespace json { namespace karma = boost::spirit::karma; namespace phoenix = boost::phoenix; namespace { #ifdef BOOST_SPIRIT_USE_PHOENIX_V3 struct get_type { typedef int result_type; result_type operator() (geometry_type const& geom) const { return static_cast<int>(geom.type()); } }; struct get_first { typedef geometry_type::value_type const result_type; result_type operator() (geometry_type const& geom) const { geometry_type::value_type coord; boost::get<0>(coord) = geom.vertex(0,&boost::get<1>(coord),&boost::get<2>(coord)); return coord; } }; struct multi_geometry_type { typedef boost::tuple<unsigned,bool> result_type; result_type operator() (geometry_container const& geom) const { unsigned type = 0u; bool collection = false; geometry_container::const_iterator itr = geom.begin(); geometry_container::const_iterator end = geom.end(); for ( ; itr != end; ++itr) { if (type != 0u && itr->type() != type) { collection = true; break; } type = itr->type(); } if (geom.size() > 1) type +=3; return boost::tuple<unsigned,bool>(type, collection); } }; #else struct get_type { template <typename T> struct result { typedef int type; }; int operator() (geometry_type const& geom) const { return static_cast<int>(geom.type()); } }; struct get_first { template <typename T> struct result { typedef geometry_type::value_type const type; }; geometry_type::value_type const operator() (geometry_type const& geom) const { geometry_type::value_type coord; boost::get<0>(coord) = geom.vertex(0,&boost::get<1>(coord),&boost::get<2>(coord)); return coord; } }; struct multi_geometry_type { template <typename T> struct result { typedef boost::tuple<unsigned,bool> type; }; boost::tuple<unsigned,bool> operator() (geometry_container const& geom) const { unsigned type = 0u; bool collection = false; geometry_container::const_iterator itr = geom.begin(); geometry_container::const_iterator end = geom.end(); for ( ; itr != end; ++itr) { if (type != 0u && itr->type() != type) { collection = true; break; } type = itr->type(); } if (geom.size() > 1) type +=3; return boost::tuple<unsigned,bool>(type, collection); } }; #endif template <typename T> struct json_coordinate_policy : karma::real_policies<T> { typedef boost::spirit::karma::real_policies<T> base_type; static int floatfield(T n) { return base_type::fmtflags::fixed; } static unsigned precision(T n) { if (n == 0.0) return 0; using namespace boost::spirit; return static_cast<unsigned>(14 - boost::math::trunc(log10(traits::get_absolute_value(n)))); } template <typename OutputIterator> static bool dot(OutputIterator& sink, T n, unsigned precision) { if (n == 0) return true; return base_type::dot(sink, n, precision); } template <typename OutputIterator> static bool fraction_part(OutputIterator& sink, T n , unsigned adjprec, unsigned precision) { if (n == 0) return true; return base_type::fraction_part(sink, n, adjprec, precision); } }; } template <typename OutputIterator> struct geometry_generator_grammar : karma::grammar<OutputIterator, geometry_type const& ()> { geometry_generator_grammar() : geometry_generator_grammar::base_type(coordinates) { using boost::spirit::karma::uint_; using boost::spirit::karma::_val; using boost::spirit::karma::_1; using boost::spirit::karma::lit; using boost::spirit::karma::_a; using boost::spirit::karma::_r1; using boost::spirit::karma::eps; coordinates = point | linestring | polygon ; point = &uint_(mapnik::Point)[_1 = _type(_val)] << point_coord [_1 = _first(_val)] ; linestring = &uint_(mapnik::LineString)[_1 = _type(_val)] << lit('[') << coords << lit(']') ; polygon = &uint_(mapnik::Polygon)[_1 = _type(_val)] << lit('[') << coords2 << lit("]]") ; point_coord = &uint_ << lit('[') << coord_type << lit(',') << coord_type << lit("]") ; polygon_coord %= ( &uint_(mapnik::SEG_MOVETO) << eps[_r1 += 1] << karma::string[ if_ (_r1 > 1) [_1 = "],["] .else_[_1 = '[' ]] | &uint_(mapnik::SEG_LINETO) << lit(',')) << lit('[') << coord_type << lit(',') << coord_type << lit(']') ; coords2 %= *polygon_coord(_a) ; coords = point_coord % lit(',') ; } // rules karma::rule<OutputIterator, geometry_type const& ()> coordinates; karma::rule<OutputIterator, geometry_type const& ()> point; karma::rule<OutputIterator, geometry_type const& ()> linestring; karma::rule<OutputIterator, geometry_type const& ()> polygon; karma::rule<OutputIterator, geometry_type const& ()> coords; karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const& ()> coords2; karma::rule<OutputIterator, geometry_type::value_type ()> point_coord; karma::rule<OutputIterator, geometry_type::value_type (unsigned& )> polygon_coord; // phoenix functions phoenix::function<get_type > _type; phoenix::function<get_first> _first; // karma::real_generator<double, json_coordinate_policy<double> > coord_type; }; template <typename OutputIterator> struct multi_geometry_generator_grammar : karma::grammar<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const& ()> { multi_geometry_generator_grammar() : multi_geometry_generator_grammar::base_type(start) { using boost::spirit::karma::lit; using boost::spirit::karma::eps; using boost::spirit::karma::_val; using boost::spirit::karma::_1; using boost::spirit::karma::_a; using boost::spirit::karma::_r1; geometry_types.add (mapnik::Point,"\"Point\"") (mapnik::LineString,"\"LineString\"") (mapnik::Polygon,"\"Polygon\"") (mapnik::Point + 3,"\"MultiPoint\"") (mapnik::LineString + 3,"\"MultiLineString\"") (mapnik::Polygon + 3,"\"MultiPolygon\"") ; start %= ( eps(phoenix::at_c<1>(_a))[_a = _multi_type(_val)] << lit("{\"type\":\"GeometryCollection\",\"geometries\":[") << geometry_collection << lit("]}") | geometry) ; geometry_collection = -(geometry2 % lit(',')) ; geometry = (lit("{\"type\":") << geometry_types[_1 = phoenix::at_c<0>(_a)][_a = _multi_type(_val)] << lit(",\"coordinates\":") << karma::string[ phoenix::if_ (phoenix::at_c<0>(_a) > 3) [_1 = '['].else_[_1 = ""]] << coordinates << karma::string[ phoenix::if_ (phoenix::at_c<0>(_a) > 3) [_1 = ']'].else_[_1 = ""]] << lit('}')) | lit("null") ; geometry2 = lit("{\"type\":") << geometry_types[_1 = _a][_a = type_(_val)] << lit(",\"coordinates\":") << path << lit('}') ; coordinates %= path % lit(',') ; } // rules karma::rule<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const&()> start; karma::rule<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const&()> geometry_collection; karma::rule<OutputIterator, karma::locals<boost::tuple<unsigned,bool> >, geometry_container const&()> geometry; karma::rule<OutputIterator, karma::locals<unsigned>, geometry_type const&()> geometry2; karma::rule<OutputIterator, geometry_container const&()> coordinates; geometry_generator_grammar<OutputIterator> path; // phoenix phoenix::function<multi_geometry_type> _multi_type; phoenix::function<get_type > type_; // symbols table karma::symbols<unsigned, char const*> geometry_types; }; }} #endif // MAPNIK_JSON_GEOMETRY_GENERATOR_GRAMMAR_HPP
fix to_geojson polygon output after bug introduced in merge 76f111cc97a86cb029 - closes #2019
fix to_geojson polygon output after bug introduced in merge 76f111cc97a86cb029 - closes #2019
C++
lgpl-2.1
Mappy/mapnik,jwomeara/mapnik,mapnik/python-mapnik,mapnik/mapnik,rouault/mapnik,cjmayo/mapnik,davenquinn/python-mapnik,sebastic/python-mapnik,mapycz/mapnik,stefanklug/mapnik,davenquinn/python-mapnik,yiqingj/work,lightmare/mapnik,mbrukman/mapnik,mbrukman/mapnik,yiqingj/work,naturalatlas/mapnik,Mappy/mapnik,jwomeara/mapnik,lightmare/mapnik,manz/python-mapnik,mapycz/mapnik,pramsey/mapnik,tomhughes/python-mapnik,yiqingj/work,qianwenming/mapnik,Mappy/mapnik,yiqingj/work,stefanklug/mapnik,manz/python-mapnik,yohanboniface/python-mapnik,mapnik/python-mapnik,garnertb/python-mapnik,sebastic/python-mapnik,qianwenming/mapnik,mbrukman/mapnik,garnertb/python-mapnik,whuaegeanse/mapnik,whuaegeanse/mapnik,mapycz/python-mapnik,naturalatlas/mapnik,Airphrame/mapnik,qianwenming/mapnik,mbrukman/mapnik,qianwenming/mapnik,Uli1/mapnik,mapnik/python-mapnik,cjmayo/mapnik,davenquinn/python-mapnik,rouault/mapnik,pramsey/mapnik,pnorman/mapnik,mapycz/python-mapnik,Mappy/mapnik,CartoDB/mapnik,Uli1/mapnik,pramsey/mapnik,Airphrame/mapnik,Uli1/mapnik,naturalatlas/mapnik,yohanboniface/python-mapnik,mapycz/mapnik,jwomeara/mapnik,mapnik/mapnik,tomhughes/mapnik,cjmayo/mapnik,Uli1/mapnik,CartoDB/mapnik,tomhughes/mapnik,lightmare/mapnik,pnorman/mapnik,pnorman/mapnik,tomhughes/mapnik,cjmayo/mapnik,zerebubuth/mapnik,rouault/mapnik,naturalatlas/mapnik,zerebubuth/mapnik,mapnik/mapnik,CartoDB/mapnik,yohanboniface/python-mapnik,garnertb/python-mapnik,whuaegeanse/mapnik,rouault/mapnik,pnorman/mapnik,Airphrame/mapnik,qianwenming/mapnik,tomhughes/python-mapnik,whuaegeanse/mapnik,Airphrame/mapnik,tomhughes/python-mapnik,zerebubuth/mapnik,jwomeara/mapnik,lightmare/mapnik,stefanklug/mapnik,stefanklug/mapnik,sebastic/python-mapnik,mapnik/mapnik,manz/python-mapnik,tomhughes/mapnik,pramsey/mapnik
0d5cad62d2ea9e36246dec3ca6d73ec55151c03e
lib/Interpreter/ASTImportSource.cpp
lib/Interpreter/ASTImportSource.cpp
#include "ASTImportSource.h" #include "cling/Interpreter/Interpreter.h" using namespace clang; namespace { class ClingASTImporter : public ASTImporter { private: cling::ASTImportSource& m_source; public: ClingASTImporter(ASTContext &ToContext, FileManager &ToFileManager, ASTContext &FromContext, FileManager &FromFileManager, bool MinimalImport, cling::ASTImportSource& source) : ASTImporter(ToContext, ToFileManager, FromContext, FromFileManager, MinimalImport), m_source(source) {} Decl *Imported(Decl *From, Decl *To) override { ASTImporter::Imported(From, To); // Put the name of the Decl imported with the // DeclarationName coming from the parent, in my map. if (DeclContext *declContextParent = llvm::dyn_cast<DeclContext>(From)) { DeclContext *declContextChild = llvm::dyn_cast<DeclContext>(To); m_source.addToDeclContext(declContextChild, declContextParent); } return To; } }; } namespace cling { ASTImportSource::ASTImportSource(const cling::Interpreter *parent_interpreter, cling::Interpreter *child_interpreter) : m_parent_Interp(parent_interpreter), m_child_Interp(child_interpreter) { clang::DeclContext *parentTUDeclContext = clang::TranslationUnitDecl::castToDeclContext( m_parent_Interp->getCI()->getASTContext().getTranslationUnitDecl()); clang::DeclContext *childTUDeclContext = clang::TranslationUnitDecl::castToDeclContext( m_child_Interp->getCI()->getASTContext().getTranslationUnitDecl()); // Also keep in the map of Decl Contexts the Translation Unit Decl Context m_DeclContexts_map[childTUDeclContext] = parentTUDeclContext; } void ASTImportSource::ImportDecl(Decl *declToImport, ASTImporter &importer, DeclarationName &childDeclName, DeclarationName &parentDeclName, const DeclContext *childCurrentDeclContext) { // Don't do the import if we have a Function Template. // Not supported by clang. // FIXME: This is also a temporary check. Will be de-activated // once clang supports the import of function templates. if (declToImport->isFunctionOrFunctionTemplate() && declToImport->isTemplateDecl()) return; if (Decl *importedDecl = importer.Import(declToImport)) { if (NamedDecl *importedNamedDecl = llvm::dyn_cast<NamedDecl>(importedDecl)) { std::vector < NamedDecl * > declVector{importedNamedDecl}; llvm::ArrayRef < NamedDecl * > FoundDecls(declVector); SetExternalVisibleDeclsForName(childCurrentDeclContext, importedNamedDecl->getDeclName(), FoundDecls); } // Put the name of the Decl imported with the // DeclarationName coming from the parent, in my map. m_DeclName_map[childDeclName] = parentDeclName; } } void ASTImportSource::ImportDeclContext(DeclContext *declContextToImport, ASTImporter &importer, DeclarationName &childDeclName, DeclarationName &parentDeclName, const DeclContext *childCurrentDeclContext) { if (DeclContext *importedDeclContext = importer.ImportContext(declContextToImport)) { importedDeclContext->setHasExternalVisibleStorage(true); if (NamedDecl *importedNamedDecl = llvm::dyn_cast<NamedDecl>(importedDeclContext)) { std::vector < NamedDecl * > declVector{importedNamedDecl}; llvm::ArrayRef < NamedDecl * > FoundDecls(declVector); SetExternalVisibleDeclsForName(childCurrentDeclContext, importedNamedDecl->getDeclName(), FoundDecls); } // Put the name of the DeclContext imported with the // DeclarationName coming from the parent, in my map. m_DeclName_map[childDeclName] = parentDeclName; // And also put the declaration context I found from the parent Interpreter // in the map of the child Interpreter to have it for the future. m_DeclContexts_map[importedDeclContext] = declContextToImport; } } bool ASTImportSource::Import(DeclContext::lookup_result lookup_result, ASTContext &from_ASTContext, ASTContext &to_ASTContext, const DeclContext *childCurrentDeclContext, DeclarationName &childDeclName, DeclarationName &parentDeclName) { // Prepare to import the Decl(Context) we found in the // child interpreter by getting the file managers from // each interpreter. FileManager &child_FM = m_child_Interp->getCI()->getFileManager(); FileManager &parent_FM = m_parent_Interp->getCI()->getFileManager(); // Cling's ASTImporter ClingASTImporter importer(to_ASTContext, child_FM, from_ASTContext, parent_FM, /*MinimalImport : ON*/ true, *this); for (DeclContext::lookup_iterator I = lookup_result.begin(), E = lookup_result.end(); I != E; ++I) { // Check if this Name we are looking for is // a DeclContext (for example a Namespace, function etc.). if (DeclContext *declContextToImport = llvm::dyn_cast<DeclContext>(*I)) { ImportDeclContext(declContextToImport, importer, childDeclName, parentDeclName, childCurrentDeclContext); } else if (Decl *declToImport = llvm::dyn_cast<Decl>(*I)) { // else it is a Decl ImportDecl(declToImport, importer, childDeclName, parentDeclName, childCurrentDeclContext); } } return true; } ///\brief This is the most important function of the class ASTImportSource /// since from here initiates the lookup and import part of the missing /// Decl(s) (Contexts). /// bool ASTImportSource::FindExternalVisibleDeclsByName( const DeclContext *childCurrentDeclContext, DeclarationName childDeclName) { assert(childDeclName && "Child Decl name is empty"); assert(childCurrentDeclContext->hasExternalVisibleStorage() && "DeclContext has no visible decls in storage"); //Check if we have already found this declaration Name before DeclarationName parentDeclName; std::map<clang::DeclarationName, clang::DeclarationName>::iterator II = m_DeclName_map.find(childDeclName); if (II != m_DeclName_map.end()) { parentDeclName = II->second; } else { // Get the identifier info from the parent interpreter // for this Name. std::string name = childDeclName.getAsString(); if (!name.empty()) { llvm::StringRef nameRef(name); IdentifierTable &parentIdentifierTable = m_parent_Interp->getCI()->getASTContext().Idents; IdentifierInfo &parentIdentifierInfo = parentIdentifierTable.get(nameRef); parentDeclName = DeclarationName(&parentIdentifierInfo); } } // Search in the map of the stored Decl Contexts for this // Decl Context. std::map<const clang::DeclContext *, clang::DeclContext *>::iterator I; // If childCurrentDeclContext was found before and is already in the map, // then do the lookup using the stored pointer. if ((I = m_DeclContexts_map.find(childCurrentDeclContext)) != m_DeclContexts_map.end()) { DeclContext *parentDeclContext = I->second; Decl *fromDeclContext = Decl::castFromDeclContext(parentDeclContext); ASTContext &from_ASTContext = fromDeclContext->getASTContext(); Decl *toDeclContext = Decl::castFromDeclContext(childCurrentDeclContext); ASTContext &to_ASTContext = toDeclContext->getASTContext(); DeclContext::lookup_result lookup_result = parentDeclContext->lookup(parentDeclName); // Check if we found this Name in the parent interpreter if (!lookup_result.empty()) { // Do the import if (Import(lookup_result, from_ASTContext, to_ASTContext, childCurrentDeclContext, childDeclName, parentDeclName)) return true; } } return false; } ///\brief Make available to child all decls in parent's decl context /// that corresponds to child decl context. void ASTImportSource::completeVisibleDeclsMap( const clang::DeclContext *childDeclContext) { assert (childDeclContext && "No child decl context!"); if (!childDeclContext->hasExternalVisibleStorage()) return; // Search in the map of the stored Decl Contexts for this // Decl Context. std::map<const clang::DeclContext *, clang::DeclContext *>::iterator I; // If childCurrentDeclContext was found before and is already in the map, // then do the lookup using the stored pointer. if ((I = m_DeclContexts_map.find(childDeclContext)) != m_DeclContexts_map.end()) { DeclContext *parentDeclContext = I->second; Decl *fromDeclContext = Decl::castFromDeclContext(parentDeclContext); ASTContext &from_ASTContext = fromDeclContext->getASTContext(); Decl *toDeclContext = Decl::castFromDeclContext(childDeclContext); ASTContext &to_ASTContext = toDeclContext->getASTContext(); // Prepare to import the Decl(Context) we found in the // child interpreter by getting the file managers from // each interpreter. FileManager &child_FM = m_child_Interp->getCI()->getFileManager(); FileManager &parent_FM = m_parent_Interp->getCI()->getFileManager(); // Cling's ASTImporter ClingASTImporter importer(to_ASTContext, child_FM, from_ASTContext, parent_FM, /*MinimalImport : ON*/ true, *this); for (DeclContext::decl_iterator I_decl = parentDeclContext->decls_begin(), E_decl = parentDeclContext->decls_end(); I_decl != E_decl; ++I_decl) { if (NamedDecl* parentNamedDecl = llvm::dyn_cast<NamedDecl>(*I_decl)) { DeclarationName newDeclName = parentNamedDecl->getDeclName(); ImportDecl(parentNamedDecl, importer, newDeclName, newDeclName, childDeclContext); } } const_cast<DeclContext *>(childDeclContext)-> setHasExternalVisibleStorage(false); } } } // end namespace cling
#include "ASTImportSource.h" #include "cling/Interpreter/Interpreter.h" using namespace clang; namespace { class ClingASTImporter : public ASTImporter { private: cling::ASTImportSource& m_source; public: ClingASTImporter(ASTContext &ToContext, FileManager &ToFileManager, ASTContext &FromContext, FileManager &FromFileManager, bool MinimalImport, cling::ASTImportSource& source) : ASTImporter(ToContext, ToFileManager, FromContext, FromFileManager, MinimalImport), m_source(source) {} Decl *Imported(Decl *From, Decl *To) override { ASTImporter::Imported(From, To); if (isa<TagDecl>(From)) { clang::TagDecl* toTagDecl = dyn_cast<TagDecl>(To); toTagDecl->setHasExternalVisibleStorage(); } if (isa<NamespaceDecl>(From)) { NamespaceDecl *to_namespace_decl = dyn_cast<NamespaceDecl>(To); to_namespace_decl->setHasExternalVisibleStorage(); } if (isa<ObjCContainerDecl>(From)) { ObjCContainerDecl *to_container_decl = dyn_cast<ObjCContainerDecl>(To); to_container_decl->setHasExternalLexicalStorage(); to_container_decl->setHasExternalVisibleStorage(); } // Put the name of the Decl imported with the // DeclarationName coming from the parent, in my map. if (DeclContext *declContextParent = llvm::dyn_cast<DeclContext>(From)) { DeclContext *declContextChild = llvm::dyn_cast<DeclContext>(To); m_source.addToDeclContext(declContextChild, declContextParent); } return To; } }; } namespace cling { ASTImportSource::ASTImportSource(const cling::Interpreter *parent_interpreter, cling::Interpreter *child_interpreter) : m_parent_Interp(parent_interpreter), m_child_Interp(child_interpreter) { clang::DeclContext *parentTUDeclContext = clang::TranslationUnitDecl::castToDeclContext( m_parent_Interp->getCI()->getASTContext().getTranslationUnitDecl()); clang::DeclContext *childTUDeclContext = clang::TranslationUnitDecl::castToDeclContext( m_child_Interp->getCI()->getASTContext().getTranslationUnitDecl()); // Also keep in the map of Decl Contexts the Translation Unit Decl Context m_DeclContexts_map[childTUDeclContext] = parentTUDeclContext; } void ASTImportSource::ImportDecl(Decl *declToImport, ASTImporter &importer, DeclarationName &childDeclName, DeclarationName &parentDeclName, const DeclContext *childCurrentDeclContext) { // Don't do the import if we have a Function Template. // Not supported by clang. // FIXME: This is also a temporary check. Will be de-activated // once clang supports the import of function templates. if (declToImport->isFunctionOrFunctionTemplate() && declToImport->isTemplateDecl()) return; //cling::Interpreter::PushTransactionRAII RAII(parent_int); if (Decl *importedDecl = importer.Import(declToImport)) { if (NamedDecl *importedNamedDecl = llvm::dyn_cast<NamedDecl>(importedDecl)) { std::vector < NamedDecl * > declVector{importedNamedDecl}; llvm::ArrayRef < NamedDecl * > FoundDecls(declVector); SetExternalVisibleDeclsForName(childCurrentDeclContext, importedNamedDecl->getDeclName(), FoundDecls); } // Put the name of the Decl imported with the // DeclarationName coming from the parent, in my map. m_DeclName_map[childDeclName] = parentDeclName; } } void ASTImportSource::ImportDeclContext(DeclContext *declContextToImport, ASTImporter &importer, DeclarationName &childDeclName, DeclarationName &parentDeclName, const DeclContext *childCurrentDeclContext) { if (DeclContext *importedDeclContext = importer.ImportContext(declContextToImport)) { importedDeclContext->setHasExternalVisibleStorage(true); if (NamedDecl *importedNamedDecl = llvm::dyn_cast<NamedDecl>(importedDeclContext)) { std::vector < NamedDecl * > declVector{importedNamedDecl}; llvm::ArrayRef < NamedDecl * > FoundDecls(declVector); SetExternalVisibleDeclsForName(childCurrentDeclContext, importedNamedDecl->getDeclName(), FoundDecls); } // Put the name of the DeclContext imported with the // DeclarationName coming from the parent, in my map. m_DeclName_map[childDeclName] = parentDeclName; // And also put the declaration context I found from the parent Interpreter // in the map of the child Interpreter to have it for the future. m_DeclContexts_map[importedDeclContext] = declContextToImport; } } bool ASTImportSource::Import(DeclContext::lookup_result lookup_result, ASTContext &from_ASTContext, ASTContext &to_ASTContext, const DeclContext *childCurrentDeclContext, DeclarationName &childDeclName, DeclarationName &parentDeclName) { // Prepare to import the Decl(Context) we found in the // child interpreter by getting the file managers from // each interpreter. FileManager &child_FM = m_child_Interp->getCI()->getFileManager(); FileManager &parent_FM = m_parent_Interp->getCI()->getFileManager(); // Cling's ASTImporter ClingASTImporter importer(to_ASTContext, child_FM, from_ASTContext, parent_FM, /*MinimalImport : ON*/ true, *this); for (DeclContext::lookup_iterator I = lookup_result.begin(), E = lookup_result.end(); I != E; ++I) { // Check if this Name we are looking for is // a DeclContext (for example a Namespace, function etc.). if (DeclContext *declContextToImport = llvm::dyn_cast<DeclContext>(*I)) { ImportDeclContext(declContextToImport, importer, childDeclName, parentDeclName, childCurrentDeclContext); } else if (Decl *declToImport = llvm::dyn_cast<Decl>(*I)) { // else it is a Decl ImportDecl(declToImport, importer, childDeclName, parentDeclName, childCurrentDeclContext); } } return true; } ///\brief This is the most important function of the class ASTImportSource /// since from here initiates the lookup and import part of the missing /// Decl(s) (Contexts). /// bool ASTImportSource::FindExternalVisibleDeclsByName( const DeclContext *childCurrentDeclContext, DeclarationName childDeclName) { assert(childDeclName && "Child Decl name is empty"); assert(childCurrentDeclContext->hasExternalVisibleStorage() && "DeclContext has no visible decls in storage"); //Check if we have already found this declaration Name before DeclarationName parentDeclName; std::map<clang::DeclarationName, clang::DeclarationName>::iterator II = m_DeclName_map.find(childDeclName); if (II != m_DeclName_map.end()) { parentDeclName = II->second; } else { // Get the identifier info from the parent interpreter // for this Name. std::string name = childDeclName.getAsString(); if (!name.empty()) { llvm::StringRef nameRef(name); IdentifierTable &parentIdentifierTable = m_parent_Interp->getCI()->getASTContext().Idents; IdentifierInfo &parentIdentifierInfo = parentIdentifierTable.get(nameRef); parentDeclName = DeclarationName(&parentIdentifierInfo); } } // Search in the map of the stored Decl Contexts for this // Decl Context. std::map<const clang::DeclContext *, clang::DeclContext *>::iterator I; // If childCurrentDeclContext was found before and is already in the map, // then do the lookup using the stored pointer. if ((I = m_DeclContexts_map.find(childCurrentDeclContext)) != m_DeclContexts_map.end()) { DeclContext *parentDeclContext = I->second; Decl *fromDeclContext = Decl::castFromDeclContext(parentDeclContext); ASTContext &from_ASTContext = fromDeclContext->getASTContext(); Decl *toDeclContext = Decl::castFromDeclContext(childCurrentDeclContext); ASTContext &to_ASTContext = toDeclContext->getASTContext(); DeclContext::lookup_result lookup_result = parentDeclContext->lookup(parentDeclName); // Check if we found this Name in the parent interpreter if (!lookup_result.empty()) { // Do the import if (Import(lookup_result, from_ASTContext, to_ASTContext, childCurrentDeclContext, childDeclName, parentDeclName)) return true; } } return false; } ///\brief Make available to child all decls in parent's decl context /// that corresponds to child decl context. void ASTImportSource::completeVisibleDeclsMap( const clang::DeclContext *childDeclContext) { assert (childDeclContext && "No child decl context!"); if (!childDeclContext->hasExternalVisibleStorage()) return; // Search in the map of the stored Decl Contexts for this // Decl Context. std::map<const clang::DeclContext *, clang::DeclContext *>::iterator I; // If childCurrentDeclContext was found before and is already in the map, // then do the lookup using the stored pointer. if ((I = m_DeclContexts_map.find(childDeclContext)) != m_DeclContexts_map.end()) { DeclContext *parentDeclContext = I->second; Decl *fromDeclContext = Decl::castFromDeclContext(parentDeclContext); ASTContext &from_ASTContext = fromDeclContext->getASTContext(); Decl *toDeclContext = Decl::castFromDeclContext(childDeclContext); ASTContext &to_ASTContext = toDeclContext->getASTContext(); // Prepare to import the Decl(Context) we found in the // child interpreter by getting the file managers from // each interpreter. FileManager &child_FM = m_child_Interp->getCI()->getFileManager(); FileManager &parent_FM = m_parent_Interp->getCI()->getFileManager(); // Cling's ASTImporter ClingASTImporter importer(to_ASTContext, child_FM, from_ASTContext, parent_FM, /*MinimalImport : ON*/ true, *this); StringRef filter = m_child_Interp->getCI()->getPreprocessor().getCodeCompletionFilter(); for (DeclContext::decl_iterator I_decl = parentDeclContext->decls_begin(), E_decl = parentDeclContext->decls_end(); I_decl != E_decl; ++I_decl) { if (NamedDecl* parentNamedDecl = llvm::dyn_cast<NamedDecl>(*I_decl)) { // Filter using the stem from the input line DeclarationName newDeclName = parentNamedDecl->getDeclName(); if (newDeclName.getAsIdentifierInfo()) { StringRef name = newDeclName.getAsIdentifierInfo()->getName(); if (!name.empty() && name.startswith(filter)) ImportDecl(parentNamedDecl, importer, newDeclName, newDeclName, childDeclContext); } } } const_cast<DeclContext *>(childDeclContext)-> setHasExternalVisibleStorage(false); } } } // end namespace cling
Mark the external visibility of imported decls.
Mark the external visibility of imported decls.
C++
lgpl-2.1
marsupial/cling,karies/cling,root-mirror/cling,karies/cling,karies/cling,marsupial/cling,root-mirror/cling,marsupial/cling,karies/cling,root-mirror/cling,root-mirror/cling,root-mirror/cling,marsupial/cling,karies/cling,root-mirror/cling,marsupial/cling,marsupial/cling,karies/cling
52bf466aa005388fe1705919cdd99b4ef740e153
lib/RemoteControl/RemoteControl.cpp
lib/RemoteControl/RemoteControl.cpp
/**************************************************************************** * Copyright 2016 BlueMasters * * 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 <Arduino.h> #include <IRremote.h> #include <Streaming.h> #include "RemoteControl.h" #include "App.h" #define IR_LED_CHOOSE_CMD 0xFF7400 // orange #define IR_LED_CONFIG_DF 0xAE56DF // light violet #define IR_LED_CONFIG_DI 0x400362 // dark violet #define IR_LED_LEARN 0x3029D6 // bright blue void RemoteControl::begin(){ _irrecv.enableIRIn(); // Start the receiver } void RemoteControl::tick(){ long now = millis(); // handle the confirm mode with one tick behind, // so the app state is not reset before the // other modules have a chance to handle the // confirm/cancel event if(_state == IR_STATE_CONFIG || _state == IR_STATE_LEARN){ if(_lastkey == IR_KEY_OK || _lastkey == IR_KEY_CANCEL) { // back to wait cmd state (if timeout, will be handled below) resetState(); _state = IR_STATE_CHOOSE_CMD; } } // reset key state _lastkey = IR_KEY_NONE; // handle timeout (only in normal mode) if(app.globalMode == globmode_NORMAL && now - _lastrecvtime >= IR_IDLE_TIMEOUT) { if(_state == IR_STATE_CONFIG) { // if executing command, send the cancel key // during one tick before continuing _lastkey = IR_KEY_CANCEL; return; // ensure the cancel key stays for one tick // next tick, handleConfirm will be called and the // state will be reset } else { // else, simply reset the state // and read next key resetState(); } } // read next decode_results recv_key; if (_irrecv.decode(&recv_key)) { _lastrecvtime = now; _irrecv.resume(); // Receive the next value if(recv_key.value == 0xFFFFFFFF) // -1 = key still pressed return; _lastkey = recv_key.value; #ifdef APP_DEBUG Serial << "IR Received : " << _HEX(recv_key.value) << "(" << _lastkey << ")" << endl; #endif } else { // no key received, nothing to do return; } // handle cmd switch(_state) { case IR_STATE_DEFAULT: handlePinCode(); break; case IR_STATE_CHOOSE_CMD: handleCmd(); break; default: break; } } // end tick int RemoteControl::lastKeyToInt(){ switch(_lastkey) { case IR_KEY_0: return 0; case IR_KEY_1: return 1; case IR_KEY_2: return 2; case IR_KEY_3: return 3; case IR_KEY_4: return 4; case IR_KEY_5: return 5; case IR_KEY_6: return 6; case IR_KEY_7: return 7; case IR_KEY_8: return 8; case IR_KEY_9: return 9; default: return -1; } } void RemoteControl::resetState(){ app.globalMode = globmode_NORMAL; app.configMode = confmode_None; _state = IR_STATE_DEFAULT; _pincode_idx = 0; } void RemoteControl::handlePinCode(){ int key_nbr = lastKeyToInt(); #ifdef APP_DEBUG Serial << "Key Number : " << key_nbr << endl; #endif if(key_nbr < 0) return; // ignore non number key (TODO) int expected = app.pinCode[_pincode_idx]; if(key_nbr == expected) { _pincode_idx++; if(_pincode_idx >= 4) { // the whole code has been entered. _state = IR_STATE_CHOOSE_CMD; _pincode_idx = 0; } } else { _pincode_idx = 0; // reset } } void RemoteControl::handleCmd(){ // next state switch(_lastkey) { case IR_KEY_1: // learn app.globalMode = globmode_LEARN; _state = IR_STATE_LEARN; return; case IR_KEY_2: // edit Delay of Feedback app.configMode = confmode_DF; _state = IR_STATE_CONFIG; return; case IR_KEY_3: // edit Delay of Impulsion app.configMode = confmode_DI; _state = IR_STATE_CONFIG; return; } } void RemoteControl::setState(enum IRState newState){ _state = newState; switch (newState) { case IR_STATE_DEFAULT: app.statusLed.off(); break; case IR_STATE_CHOOSE_CMD: app.statusLed.setColor(IR_LED_CHOOSE_CMD); break; case IR_STATE_LEARN: app.statusLed.setColor(IR_LED_LEARN); break; case IR_STATE_CONFIG: app.statusLed.setColor(app.configMode == confmode_DF ? IR_LED_CONFIG_DF : IR_LED_CONFIG_DI); break; } } IRKey RemoteControl::keypressed(){ return _lastkey; }
/**************************************************************************** * Copyright 2016 BlueMasters * * 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 <Arduino.h> #include <IRremote.h> #include <Streaming.h> #include "RemoteControl.h" #include "App.h" #define IR_LED_CHOOSE_CMD 0xFF7400 // orange #define IR_LED_CONFIG_DF 0xAE56DF // light violet #define IR_LED_CONFIG_DI 0x400362 // dark violet #define IR_LED_LEARN 0x3029D6 // bright blue void RemoteControl::begin(){ _irrecv.enableIRIn(); // Start the receiver } void RemoteControl::tick(){ long now = millis(); // handle the confirm mode with one tick behind, // so the app state is not reset before the // other modules have a chance to handle the // confirm/cancel event if(_state == IR_STATE_CONFIG || _state == IR_STATE_LEARN){ if(_lastkey == IR_KEY_OK || _lastkey == IR_KEY_CANCEL) { // back to wait cmd state (if timeout, will be handled below) resetState(); setState(IR_STATE_CHOOSE_CMD); } } // reset key state _lastkey = IR_KEY_NONE; // handle timeout (only in normal mode) if(app.globalMode == globmode_NORMAL && now - _lastrecvtime >= IR_IDLE_TIMEOUT) { if(_state == IR_STATE_CONFIG) { // if executing command, send the cancel key // during one tick before continuing _lastkey = IR_KEY_CANCEL; return; // ensure the cancel key stays for one tick // next tick, handleConfirm will be called and the // state will be reset } else { // else, simply reset the state // and read next key resetState(); } } // read next decode_results recv_key; if (_irrecv.decode(&recv_key)) { _lastrecvtime = now; _irrecv.resume(); // Receive the next value if(recv_key.value == 0xFFFFFFFF) // -1 = key still pressed return; _lastkey = recv_key.value; #ifdef APP_DEBUG Serial << "IR Received : " << _HEX(recv_key.value) << "(" << _lastkey << ")" << endl; #endif } else { // no key received, nothing to do return; } // handle cmd switch(_state) { case IR_STATE_DEFAULT: handlePinCode(); break; case IR_STATE_CHOOSE_CMD: handleCmd(); break; default: break; } } // end tick int RemoteControl::lastKeyToInt(){ switch(_lastkey) { case IR_KEY_0: return 0; case IR_KEY_1: return 1; case IR_KEY_2: return 2; case IR_KEY_3: return 3; case IR_KEY_4: return 4; case IR_KEY_5: return 5; case IR_KEY_6: return 6; case IR_KEY_7: return 7; case IR_KEY_8: return 8; case IR_KEY_9: return 9; default: return -1; } } void RemoteControl::resetState(){ app.globalMode = globmode_NORMAL; app.configMode = confmode_None; setState(IR_STATE_DEFAULT); _pincode_idx = 0; } void RemoteControl::handlePinCode(){ int key_nbr = lastKeyToInt(); #ifdef APP_DEBUG Serial << "Key Number : " << key_nbr << endl; #endif if(key_nbr < 0) return; // ignore non number key (TODO) int expected = app.pinCode[_pincode_idx]; if(key_nbr == expected) { _pincode_idx++; if(_pincode_idx >= 4) { // the whole code has been entered. setState(IR_STATE_CHOOSE_CMD); _pincode_idx = 0; } } else { _pincode_idx = 0; // reset } } void RemoteControl::handleCmd(){ // next state switch(_lastkey) { case IR_KEY_1: // learn app.globalMode = globmode_LEARN; setState(IR_STATE_LEARN); return; case IR_KEY_2: // edit Delay of Feedback app.configMode = confmode_DF; setState(IR_STATE_CONFIG); return; case IR_KEY_3: // edit Delay of Impulsion app.configMode = confmode_DI; setState(IR_STATE_CONFIG); return; } } void RemoteControl::setState(enum IRState newState){ _state = newState; switch (newState) { case IR_STATE_DEFAULT: app.statusLed.off(); break; case IR_STATE_CHOOSE_CMD: app.statusLed.setColor(IR_LED_CHOOSE_CMD); break; case IR_STATE_LEARN: app.statusLed.setColor(IR_LED_LEARN); break; case IR_STATE_CONFIG: app.statusLed.setColor(app.configMode == confmode_DF ? IR_LED_CONFIG_DF : IR_LED_CONFIG_DI); break; } } IRKey RemoteControl::keypressed(){ return _lastkey; }
use status led to notify states
use status led to notify states
C++
apache-2.0
BlueMasters/arduino-wolves,BlueMasters/arduino-wolves,BlueMasters/arduino-wolves
9b4f5db4101ddb14dffaaa473916e13acc3b1d54
lima_common/src/common/misc/tests/LimaFileSystemWatcherTest.cpp
lima_common/src/common/misc/tests/LimaFileSystemWatcherTest.cpp
/* * Copyright 2015 CEA LIST * * This file is part of LIMA. * * LIMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LIMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with LIMA. If not, see <http://www.gnu.org/licenses/> */ #include "LimaFileSystemWatcherTest.h" #include "common/misc/LimaFileSystemWatcher.h" #include "common/QsLog/QsLogCategories.h" #include "common/AbstractFactoryPattern/AmosePluginsManager.h" #include <QtCore/QTemporaryFile> #include <QtTest/QtTest> using namespace Lima; QTEST_MAIN ( LimaFileSystemWatcherTest ); void LimaFileSystemWatcherTest::initTestCase() { // Called before the first testfunction is executed QsLogging::initQsLog(); // Necessary to initialize factories under Windows Lima::AmosePluginsManager::single(); } void LimaFileSystemWatcherTest::cleanupTestCase() { // Called after the last testfunction was executed std::cerr << "LimaFileSystemWatcherTest::cleanupTestCase" << std::endl; } void LimaFileSystemWatcherTest::init() { // Called before each testfunction is executed } void LimaFileSystemWatcherTest::cleanup() { // Called after every testfunction } void LimaFileSystemWatcherTest::LimaFileSystemWatcherTest0() { LimaFileSystemWatcher watcher; QSignalSpy stateSpy( &watcher, SIGNAL( fileChanged ( QString) ) ); QVERIFY( stateSpy.isValid() ); QCOMPARE( stateSpy.count(), 0 ); QTemporaryFile tmpFile; QVERIFY2(tmpFile.open(),"Was not able to open the temporary file"); QString tmpFileName = tmpFile.fileName(); watcher.addPath(tmpFileName); QTextStream out(&tmpFile); out << "yo"; tmpFile.close(); QVERIFY2( QFile(tmpFileName).exists(), "The tmpFile does not exist while it should"); QTest::qWait(500); // we changed the file. The fileChanged signal should have been triggered QCOMPARE( stateSpy.count(), 1 ); std::cerr << "LimaFileSystemWatcherTest::LimaFileSystemWatcherTest0 1" << std::endl; // remove the tmp file. This should trigger the signal QFile::remove(tmpFileName); QVERIFY2( !QFile(tmpFileName).exists(), "The tmpFile still exists while it has been removed"); QTest::qWait(500); // we removed the file. The fileChanged signal should have been triggered QCOMPARE( stateSpy.count(), 2 ); std::cerr << "LimaFileSystemWatcherTest::LimaFileSystemWatcherTest0 2" << std::endl; // recreate the file. This should also trigger the signal QFile recreatedFile(tmpFileName); QVERIFY2( recreatedFile.open(QIODevice::ReadWrite), "Was not able to recreate the file"); recreatedFile.close(); QTest::qWait(500); // we recreated the file. The fileChanged signal should have been triggered QCOMPARE( stateSpy.count(), 3 ); std::cerr << "LimaFileSystemWatcherTest::LimaFileSystemWatcherTest0 3" << std::endl; }
/* * Copyright 2015 CEA LIST * * This file is part of LIMA. * * LIMA is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * LIMA 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with LIMA. If not, see <http://www.gnu.org/licenses/> */ #include "LimaFileSystemWatcherTest.h" #include "common/misc/LimaFileSystemWatcher.h" #include "common/QsLog/QsLogCategories.h" #include "common/AbstractFactoryPattern/AmosePluginsManager.h" #include <QtCore/QTemporaryFile> #include <QtTest/QtTest> using namespace Lima; QTEST_MAIN ( LimaFileSystemWatcherTest ); void LimaFileSystemWatcherTest::initTestCase() { // Called before the first testfunction is executed QsLogging::initQsLog(); // Necessary to initialize factories under Windows Lima::AmosePluginsManager::single(); } void LimaFileSystemWatcherTest::cleanupTestCase() { // Called after the last testfunction was executed } void LimaFileSystemWatcherTest::init() { // Called before each testfunction is executed } void LimaFileSystemWatcherTest::cleanup() { // Called after every testfunction } void LimaFileSystemWatcherTest::LimaFileSystemWatcherTest0() { LimaFileSystemWatcher watcher; QSignalSpy stateSpy( &watcher, SIGNAL( fileChanged ( QString) ) ); QVERIFY( stateSpy.isValid() ); QCOMPARE( stateSpy.count(), 0 ); QTemporaryFile tmpFile; QVERIFY2(tmpFile.open(),"Was not able to open the temporary file"); QString tmpFileName = tmpFile.fileName(); watcher.addPath(tmpFileName); QTextStream out(&tmpFile); out << "yo"; tmpFile.close(); QVERIFY2( QFile(tmpFileName).exists(), "The tmpFile does not exist while it should"); QTest::qWait(500); // we changed the file. The fileChanged signal should have been triggered QCOMPARE( stateSpy.count(), 1 ); // remove the tmp file. This should trigger the signal QFile::remove(tmpFileName); QVERIFY2( !QFile(tmpFileName).exists(), "The tmpFile still exists while it has been removed"); QTest::qWait(500); // we removed the file. The fileChanged signal should have been triggered QCOMPARE( stateSpy.count(), 2 ); // recreate the file. This should also trigger the signal QFile recreatedFile(tmpFileName); QVERIFY2( recreatedFile.open(QIODevice::ReadWrite), "Was not able to recreate the file"); std::cerr << ""; recreatedFile.close(); QTest::qWait(500); // we recreated the file. The fileChanged signal should have been triggered QCOMPARE( stateSpy.count(), 3 ); }
Debug messages
Debug messages
C++
agpl-3.0
FaizaGara/lima,FaizaGara/lima,FaizaGara/lima,FaizaGara/lima,FaizaGara/lima,FaizaGara/lima,FaizaGara/lima
229de95eabb7f5350a42152eab8c4c8643cdd0bf
lib/Transforms/IPO/StripSymbols.cpp
lib/Transforms/IPO/StripSymbols.cpp
//===- StripSymbols.cpp - Strip symbols and debug info from a module ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The StripSymbols transformation implements code stripping. Specifically, it // can delete: // // * names for virtual registers // * symbols for internal globals and functions // * debug information // // Note that this transformation makes code much less readable, so it should // only be used in situations where the 'strip' utility would be used, such as // reducing code size or making it harder to reverse engineer code. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/ValueSymbolTable.h" #include "llvm/TypeSymbolTable.h" #include "llvm/Support/Compiler.h" #include "llvm/ADT/SmallPtrSet.h" using namespace llvm; namespace { class VISIBILITY_HIDDEN StripSymbols : public ModulePass { bool OnlyDebugInfo; public: static char ID; // Pass identification, replacement for typeid explicit StripSymbols(bool ODI = false) : ModulePass(&ID), OnlyDebugInfo(ODI) {} virtual bool runOnModule(Module &M); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } }; } char StripSymbols::ID = 0; static RegisterPass<StripSymbols> X("strip", "Strip all symbols from a module"); ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) { return new StripSymbols(OnlyDebugInfo); } /// OnlyUsedBy - Return true if V is only used by Usr. static bool OnlyUsedBy(Value *V, Value *Usr) { for(Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) { User *U = *I; if (U != Usr) return false; } return true; } static void RemoveDeadConstant(Constant *C) { assert(C->use_empty() && "Constant is not dead!"); SmallPtrSet<Constant *, 4> Operands; for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) if (isa<DerivedType>(C->getOperand(i)->getType()) && OnlyUsedBy(C->getOperand(i), C)) Operands.insert(C->getOperand(i)); if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) { if (!GV->hasInternalLinkage()) return; // Don't delete non static globals. GV->eraseFromParent(); } else if (!isa<Function>(C)) C->destroyConstant(); // If the constant referenced anything, see if we can delete it as well. for (SmallPtrSet<Constant *, 4>::iterator OI = Operands.begin(), OE = Operands.end(); OI != OE; ++OI) RemoveDeadConstant(*OI); } // Strip the symbol table of its names. // static void StripSymtab(ValueSymbolTable &ST) { for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) { Value *V = VI->getValue(); ++VI; if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasInternalLinkage()) { // Set name to "", removing from symbol table! V->setName(""); } } } // Strip the symbol table of its names. static void StripTypeSymtab(TypeSymbolTable &ST) { for (TypeSymbolTable::iterator TI = ST.begin(), E = ST.end(); TI != E; ) ST.remove(TI++); } bool StripSymbols::runOnModule(Module &M) { // If we're not just stripping debug info, strip all symbols from the // functions and the names from any internal globals. if (!OnlyDebugInfo) { SmallPtrSet<const GlobalValue*, 8> llvmUsedValues; if (GlobalVariable *LLVMUsed = M.getGlobalVariable("llvm.used")) { llvmUsedValues.insert(LLVMUsed); // Collect values that are preserved as per explicit request. // llvm.used is used to list these values. if (ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer())) { for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) { if (GlobalValue *GV = dyn_cast<GlobalValue>(Inits->getOperand(i))) llvmUsedValues.insert(GV); else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Inits->getOperand(i))) if (CE->getOpcode() == Instruction::BitCast) if (GlobalValue *GV = dyn_cast<GlobalValue>(CE->getOperand(0))) llvmUsedValues.insert(GV); } } } for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) { if (I->hasInternalLinkage() && llvmUsedValues.count(I) == 0) I->setName(""); // Internal symbols can't participate in linkage } for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { if (I->hasInternalLinkage() && llvmUsedValues.count(I) == 0) I->setName(""); // Internal symbols can't participate in linkage StripSymtab(I->getValueSymbolTable()); } // Remove all names from types. StripTypeSymtab(M.getTypeSymbolTable()); } // Strip debug info in the module if it exists. To do this, we remove // llvm.dbg.func.start, llvm.dbg.stoppoint, and llvm.dbg.region.end calls, and // any globals they point to if now dead. Function *FuncStart = M.getFunction("llvm.dbg.func.start"); Function *StopPoint = M.getFunction("llvm.dbg.stoppoint"); Function *RegionStart = M.getFunction("llvm.dbg.region.start"); Function *RegionEnd = M.getFunction("llvm.dbg.region.end"); Function *Declare = M.getFunction("llvm.dbg.declare"); std::vector<GlobalVariable*> DeadGlobals; // Remove all of the calls to the debugger intrinsics, and remove them from // the module. if (FuncStart) { while (!FuncStart->use_empty()) { CallInst *CI = cast<CallInst>(FuncStart->use_back()); Value *Arg = CI->getOperand(1); assert(CI->use_empty() && "llvm.dbg intrinsic should have void result"); CI->eraseFromParent(); if (Arg->use_empty()) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Arg)) DeadGlobals.push_back(GV); } FuncStart->eraseFromParent(); } if (StopPoint) { while (!StopPoint->use_empty()) { CallInst *CI = cast<CallInst>(StopPoint->use_back()); Value *Arg = CI->getOperand(3); assert(CI->use_empty() && "llvm.dbg intrinsic should have void result"); CI->eraseFromParent(); if (Arg->use_empty()) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Arg)) DeadGlobals.push_back(GV); } StopPoint->eraseFromParent(); } if (RegionStart) { while (!RegionStart->use_empty()) { CallInst *CI = cast<CallInst>(RegionStart->use_back()); Value *Arg = CI->getOperand(1); assert(CI->use_empty() && "llvm.dbg intrinsic should have void result"); CI->eraseFromParent(); if (Arg->use_empty()) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Arg)) DeadGlobals.push_back(GV); } RegionStart->eraseFromParent(); } if (RegionEnd) { while (!RegionEnd->use_empty()) { CallInst *CI = cast<CallInst>(RegionEnd->use_back()); Value *Arg = CI->getOperand(1); assert(CI->use_empty() && "llvm.dbg intrinsic should have void result"); CI->eraseFromParent(); if (Arg->use_empty()) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Arg)) DeadGlobals.push_back(GV); } RegionEnd->eraseFromParent(); } if (Declare) { while (!Declare->use_empty()) { CallInst *CI = cast<CallInst>(Declare->use_back()); Value *Arg = CI->getOperand(2); assert(CI->use_empty() && "llvm.dbg intrinsic should have void result"); CI->eraseFromParent(); if (Arg->use_empty()) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Arg)) DeadGlobals.push_back(GV); } Declare->eraseFromParent(); } // llvm.dbg.compile_units and llvm.dbg.subprograms are marked as linkonce // but since we are removing all debug information, make them internal now. if (Constant *C = M.getNamedGlobal("llvm.dbg.compile_units")) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) GV->setLinkage(GlobalValue::InternalLinkage); if (Constant *C = M.getNamedGlobal("llvm.dbg.subprograms")) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) GV->setLinkage(GlobalValue::InternalLinkage); // Delete all dbg variables. const Type *DbgVTy = M.getTypeByName("llvm.dbg.variable.type"); const Type *DbgGVTy = M.getTypeByName("llvm.dbg.global_variable.type"); if (DbgVTy || DbgGVTy) for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(I)) if (GV->hasName() && GV->use_empty() && !strncmp(GV->getNameStart(), "llvm.dbg", 8) && (GV->getType()->getElementType() == DbgVTy || GV->getType()->getElementType() == DbgGVTy)) DeadGlobals.push_back(GV); // Delete any internal globals that were only used by the debugger intrinsics. while (!DeadGlobals.empty()) { GlobalVariable *GV = DeadGlobals.back(); DeadGlobals.pop_back(); if (GV->hasInternalLinkage()) RemoveDeadConstant(GV); } // Remove all llvm.dbg types. TypeSymbolTable &ST = M.getTypeSymbolTable(); TypeSymbolTable::iterator TI = ST.begin(); TypeSymbolTable::iterator TE = ST.end(); while ( TI != TE ) { const std::string &Name = TI->first; if (!strncmp(Name.c_str(), "llvm.dbg.", 9)) ST.remove(TI++); else ++TI; } return true; }
//===- StripSymbols.cpp - Strip symbols and debug info from a module ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The StripSymbols transformation implements code stripping. Specifically, it // can delete: // // * names for virtual registers // * symbols for internal globals and functions // * debug information // // Note that this transformation makes code much less readable, so it should // only be used in situations where the 'strip' utility would be used, such as // reducing code size or making it harder to reverse engineer code. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/IPO.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/ValueSymbolTable.h" #include "llvm/TypeSymbolTable.h" #include "llvm/Support/Compiler.h" #include "llvm/ADT/SmallPtrSet.h" using namespace llvm; namespace { class VISIBILITY_HIDDEN StripSymbols : public ModulePass { bool OnlyDebugInfo; public: static char ID; // Pass identification, replacement for typeid explicit StripSymbols(bool ODI = false) : ModulePass(&ID), OnlyDebugInfo(ODI) {} /// StripSymbolNames - Strip symbol names. bool StripSymbolNames(Module &M); // StripDebugInfo - Strip debug info in the module if it exists. // To do this, we remove llvm.dbg.func.start, llvm.dbg.stoppoint, and // llvm.dbg.region.end calls, and any globals they point to if now dead. bool StripDebugInfo(Module &M); virtual bool runOnModule(Module &M); virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } }; } char StripSymbols::ID = 0; static RegisterPass<StripSymbols> X("strip", "Strip all symbols from a module"); ModulePass *llvm::createStripSymbolsPass(bool OnlyDebugInfo) { return new StripSymbols(OnlyDebugInfo); } /// OnlyUsedBy - Return true if V is only used by Usr. static bool OnlyUsedBy(Value *V, Value *Usr) { for(Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) { User *U = *I; if (U != Usr) return false; } return true; } static void RemoveDeadConstant(Constant *C) { assert(C->use_empty() && "Constant is not dead!"); SmallPtrSet<Constant *, 4> Operands; for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) if (isa<DerivedType>(C->getOperand(i)->getType()) && OnlyUsedBy(C->getOperand(i), C)) Operands.insert(C->getOperand(i)); if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) { if (!GV->hasInternalLinkage()) return; // Don't delete non static globals. GV->eraseFromParent(); } else if (!isa<Function>(C)) C->destroyConstant(); // If the constant referenced anything, see if we can delete it as well. for (SmallPtrSet<Constant *, 4>::iterator OI = Operands.begin(), OE = Operands.end(); OI != OE; ++OI) RemoveDeadConstant(*OI); } // Strip the symbol table of its names. // static void StripSymtab(ValueSymbolTable &ST) { for (ValueSymbolTable::iterator VI = ST.begin(), VE = ST.end(); VI != VE; ) { Value *V = VI->getValue(); ++VI; if (!isa<GlobalValue>(V) || cast<GlobalValue>(V)->hasInternalLinkage()) { // Set name to "", removing from symbol table! V->setName(""); } } } bool StripSymbols::runOnModule(Module &M) { bool Changed = false; Changed |= StripDebugInfo(M); Changed |= StripSymbolNames(M); return Changed; } // Strip the symbol table of its names. static void StripTypeSymtab(TypeSymbolTable &ST) { for (TypeSymbolTable::iterator TI = ST.begin(), E = ST.end(); TI != E; ) ST.remove(TI++); } /// StripSymbolNames - Strip symbol names. bool StripSymbols::StripSymbolNames(Module &M) { if (OnlyDebugInfo) return false; SmallPtrSet<const GlobalValue*, 8> llvmUsedValues; if (GlobalVariable *LLVMUsed = M.getGlobalVariable("llvm.used")) { llvmUsedValues.insert(LLVMUsed); // Collect values that are preserved as per explicit request. // llvm.used is used to list these values. if (ConstantArray *Inits = dyn_cast<ConstantArray>(LLVMUsed->getInitializer())) { for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) { if (GlobalValue *GV = dyn_cast<GlobalValue>(Inits->getOperand(i))) llvmUsedValues.insert(GV); else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Inits->getOperand(i))) if (CE->getOpcode() == Instruction::BitCast) if (GlobalValue *GV = dyn_cast<GlobalValue>(CE->getOperand(0))) llvmUsedValues.insert(GV); } } } for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) { if (I->hasInternalLinkage() && llvmUsedValues.count(I) == 0) I->setName(""); // Internal symbols can't participate in linkage } for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { if (I->hasInternalLinkage() && llvmUsedValues.count(I) == 0) I->setName(""); // Internal symbols can't participate in linkage StripSymtab(I->getValueSymbolTable()); } // Remove all names from types. StripTypeSymtab(M.getTypeSymbolTable()); return true; } // StripDebugInfo - Strip debug info in the module if it exists. // To do this, we remove llvm.dbg.func.start, llvm.dbg.stoppoint, and // llvm.dbg.region.end calls, and any globals they point to if now dead. bool StripSymbols::StripDebugInfo(Module &M) { Function *FuncStart = M.getFunction("llvm.dbg.func.start"); Function *StopPoint = M.getFunction("llvm.dbg.stoppoint"); Function *RegionStart = M.getFunction("llvm.dbg.region.start"); Function *RegionEnd = M.getFunction("llvm.dbg.region.end"); Function *Declare = M.getFunction("llvm.dbg.declare"); std::vector<GlobalVariable*> DeadGlobals; // Remove all of the calls to the debugger intrinsics, and remove them from // the module. if (FuncStart) { while (!FuncStart->use_empty()) { CallInst *CI = cast<CallInst>(FuncStart->use_back()); Value *Arg = CI->getOperand(1); assert(CI->use_empty() && "llvm.dbg intrinsic should have void result"); CI->eraseFromParent(); if (Arg->use_empty()) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Arg)) DeadGlobals.push_back(GV); } FuncStart->eraseFromParent(); } if (StopPoint) { while (!StopPoint->use_empty()) { CallInst *CI = cast<CallInst>(StopPoint->use_back()); Value *Arg = CI->getOperand(3); assert(CI->use_empty() && "llvm.dbg intrinsic should have void result"); CI->eraseFromParent(); if (Arg->use_empty()) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Arg)) DeadGlobals.push_back(GV); } StopPoint->eraseFromParent(); } if (RegionStart) { while (!RegionStart->use_empty()) { CallInst *CI = cast<CallInst>(RegionStart->use_back()); Value *Arg = CI->getOperand(1); assert(CI->use_empty() && "llvm.dbg intrinsic should have void result"); CI->eraseFromParent(); if (Arg->use_empty()) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Arg)) DeadGlobals.push_back(GV); } RegionStart->eraseFromParent(); } if (RegionEnd) { while (!RegionEnd->use_empty()) { CallInst *CI = cast<CallInst>(RegionEnd->use_back()); Value *Arg = CI->getOperand(1); assert(CI->use_empty() && "llvm.dbg intrinsic should have void result"); CI->eraseFromParent(); if (Arg->use_empty()) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Arg)) DeadGlobals.push_back(GV); } RegionEnd->eraseFromParent(); } if (Declare) { while (!Declare->use_empty()) { CallInst *CI = cast<CallInst>(Declare->use_back()); Value *Arg = CI->getOperand(2); assert(CI->use_empty() && "llvm.dbg intrinsic should have void result"); CI->eraseFromParent(); if (Arg->use_empty()) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Arg)) DeadGlobals.push_back(GV); } Declare->eraseFromParent(); } // llvm.dbg.compile_units and llvm.dbg.subprograms are marked as linkonce // but since we are removing all debug information, make them internal now. if (Constant *C = M.getNamedGlobal("llvm.dbg.compile_units")) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) GV->setLinkage(GlobalValue::InternalLinkage); if (Constant *C = M.getNamedGlobal("llvm.dbg.subprograms")) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) GV->setLinkage(GlobalValue::InternalLinkage); // Delete all dbg variables. const Type *DbgVTy = M.getTypeByName("llvm.dbg.variable.type"); const Type *DbgGVTy = M.getTypeByName("llvm.dbg.global_variable.type"); if (DbgVTy || DbgGVTy) for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) if (GlobalVariable *GV = dyn_cast<GlobalVariable>(I)) if (GV->hasName() && GV->use_empty() && !strncmp(GV->getNameStart(), "llvm.dbg", 8) && (GV->getType()->getElementType() == DbgVTy || GV->getType()->getElementType() == DbgGVTy)) DeadGlobals.push_back(GV); if (DeadGlobals.empty()) return false; // Delete any internal globals that were only used by the debugger intrinsics. while (!DeadGlobals.empty()) { GlobalVariable *GV = DeadGlobals.back(); DeadGlobals.pop_back(); if (GV->hasInternalLinkage()) RemoveDeadConstant(GV); } // Remove all llvm.dbg types. TypeSymbolTable &ST = M.getTypeSymbolTable(); TypeSymbolTable::iterator TI = ST.begin(); TypeSymbolTable::iterator TE = ST.end(); while ( TI != TE ) { const std::string &Name = TI->first; if (!strncmp(Name.c_str(), "llvm.dbg.", 9)) ST.remove(TI++); else ++TI; } return true; }
Refactor code. Strip debug information before stripping symbol names.
Refactor code. Strip debug information before stripping symbol names. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@59328 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm
df2d8f370da699e88e1ce8122669d44604ebab15
interpreter/cling/lib/Interpreter/ClingPragmas.cpp
interpreter/cling/lib/Interpreter/ClingPragmas.cpp
//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "ClingPragmas.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/Output.h" #include "cling/Utils/Paths.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/TokenKinds.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/Token.h" #include "clang/Parse/Parser.h" #include <cstdlib> using namespace cling; using namespace clang; namespace { typedef std::pair<bool, std::string> ParseResult_t; static ParseResult_t HandlePragmaHelper(Preprocessor &PP, const std::string &pragmaInst, bool stringLiteralArg = true) { struct SkipToEOD_t { Preprocessor& m_PP; SkipToEOD_t(Preprocessor& PParg): m_PP(PParg) {} ~SkipToEOD_t() { m_PP.DiscardUntilEndOfDirective(); } } SkipToEOD(PP); Token Tok; PP.Lex(Tok); if (Tok.isNot(tok::l_paren)) { cling::errs() << "cling::HandlePragmaHelper: expect '(' after #" << pragmaInst << '\n'; return ParseResult_t{false, ""}; } std::string Literal; if (stringLiteralArg) { if (!PP.LexStringLiteral(Tok, Literal, pragmaInst.c_str(), false /*allowMacroExpansion*/)) { // already diagnosed. return ParseResult_t {false, ""}; } utils::ExpandEnvVars(Literal); } else { // integer literal PP.Lex(Tok); if (!Tok.isLiteral()) { cling::errs() << "cling::HandlePragmaHelper: expect integer literal after #" << pragmaInst << '\n'; return ParseResult_t {false, ""}; } Literal = std::string(Tok.getLiteralData(), Tok.getLength()); } return ParseResult_t {true, Literal}; } class PHLoad: public PragmaHandler { Interpreter& m_Interp; public: PHLoad(Interpreter& interp): PragmaHandler("load"), m_Interp(interp) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override { // TODO: use Diagnostics! ParseResult_t Result = HandlePragmaHelper(PP, "pragma cling load"); if (!Result.first) return; if (Result.second.empty()) { cling::errs() << "Cannot load unnamed files.\n" ; return; } clang::Parser& P = m_Interp.getParser(); Parser::ParserCurTokRestoreRAII savedCurToken(P); // After we have saved the token reset the current one to something which // is safe (semi colon usually means empty decl) Token& CurTok = const_cast<Token&>(P.getCurToken()); CurTok.setKind(tok::semi); if (!m_Interp.isInSyntaxOnlyMode()) { // No need to load libraries if we're not executing anything. Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP); // We can't PushDeclContext, because we go up and the routine that pops // the DeclContext assumes that we drill down always. // We have to be on the global context. At that point we are in a // wrapper function so the parent context must be the global. TranslationUnitDecl* TU = m_Interp.getCI()->getASTContext().getTranslationUnitDecl(); Sema::ContextAndScopeRAII pushedDCAndS(m_Interp.getSema(), TU, m_Interp.getSema().TUScope); Interpreter::PushTransactionRAII pushedT(&m_Interp); m_Interp.loadFile(Result.second, true /*allowSharedLib*/); } } }; class PHAddIncPath: public PragmaHandler { Interpreter& m_Interp; public: PHAddIncPath(Interpreter& interp): PragmaHandler("add_include_path"), m_Interp(interp) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override { // TODO: use Diagnostics! ParseResult_t Result = HandlePragmaHelper(PP, "pragma cling add_include_path"); //if the function HandlePragmaHelper returned false, if (!Result.first) return; if (!Result.second.empty()) m_Interp.AddIncludePath(Result.second); } }; class PHAddLibraryPath: public PragmaHandler { Interpreter& m_Interp; public: PHAddLibraryPath(Interpreter& interp): PragmaHandler("add_library_path"), m_Interp(interp) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override { // TODO: use Diagnostics! ParseResult_t Result = HandlePragmaHelper(PP, "pragma cling add_library_path"); //if the function HandlePragmaHelper returned false, if (!Result.first) return; if (!Result.second.empty()) { // if HandlePragmaHelper returned success, this means that //it also returned the path to be included InvocationOptions& Opts = m_Interp.getOptions(); Opts.LibSearchPath.push_back(Result.second); } } }; class PHOptLevel: public PragmaHandler { Interpreter& m_Interp; public: PHOptLevel(Interpreter& interp): PragmaHandler("optimize"), m_Interp(interp) {} void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer, Token &FirstToken) override { // TODO: use Diagnostics! ParseResult_t Result = HandlePragmaHelper(PP, "pragma cling optimize", false /*string literal*/); //if the function HandlePragmaHelper returned false, if (!Result.first) return; if (Result.second.empty()) { cling::errs() << "Missing optimization level.\n" ; return; } char* ConvEnd = nullptr; int OptLevel = std::strtol(Result.second.c_str(), &ConvEnd, 10 /*base*/); if (!ConvEnd || ConvEnd == Result.second.c_str()) { cling::errs() << "cling::PHOptLevel: " "missing or non-numerical optimization level.\n" ; return; } auto T = const_cast<Transaction*>(m_Interp.getCurrentTransaction()); assert(T && "Parsing code without transaction!"); // The topmost Transaction drives the jitting. T = T->getTopmostParent(); CompilationOptions& CO = T->getCompilationOpts(); if (CO.OptLevel != m_Interp.getDefaultOptLevel()) { // Another #pragma already changed the opt level. That's a conflict that // we cannot resolve here; mention that and keep the lower one. cling::errs() << "cling::PHOptLevel: " "conflicting `#pragma cling optimize` directives: " "was already set to " << CO.OptLevel << '\n'; if (CO.OptLevel > OptLevel) { CO.OptLevel = OptLevel; cling::errs() << "Setting to lower value of " << OptLevel << '\n'; } else { cling::errs() << "Ignoring higher value of " << OptLevel << '\n'; } } else { CO.OptLevel = OptLevel; } } }; } void cling::addClingPragmas(Interpreter& interp) { Preprocessor& PP = interp.getCI()->getPreprocessor(); // PragmaNamespace / PP takes ownership of sub-handlers. PP.AddPragmaHandler("cling", new PHLoad(interp)); PP.AddPragmaHandler("cling", new PHAddIncPath(interp)); PP.AddPragmaHandler("cling", new PHAddLibraryPath(interp)); PP.AddPragmaHandler("cling", new PHOptLevel(interp)); }
//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <[email protected]> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "ClingPragmas.h" #include "cling/Interpreter/Interpreter.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/Output.h" #include "cling/Utils/Paths.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/TokenKinds.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/Token.h" #include "clang/Parse/Parser.h" #include "clang/Parse/ParseDiagnostic.h" #include <cstdlib> using namespace cling; using namespace clang; namespace { class ClingPragmaHandler: public PragmaHandler { Interpreter& m_Interp; struct SkipToEOD { Preprocessor& m_PP; Token& m_Tok; SkipToEOD(Preprocessor& PParg, Token& Tok): m_PP(PParg), m_Tok(Tok) { } ~SkipToEOD() { // Can't use Preprocessor::DiscardUntilEndOfDirective, as we may // already be on an eod token while (!m_Tok.isOneOf(tok::eod, tok::eof)) m_PP.LexUnexpandedToken(m_Tok); } }; void ReportCommandErr(Preprocessor& PP, const Token& Tok) { PP.Diag(Tok.getLocation(), diag::err_expected) << "load, add_library_path, or add_include_path"; } enum { kLoadFile, kAddLibrary, kAddInclude, // Put all commands that expand environment variables above this kExpandEnvCommands, kOptimize = kExpandEnvCommands, kInvalidCommand, }; int GetCommand(const StringRef CommandStr) { if (CommandStr == "load") return kLoadFile; else if (CommandStr == "add_library_path") return kAddLibrary; else if (CommandStr == "add_include_path") return kAddInclude; else if (CommandStr == "optimize") return kOptimize; return kInvalidCommand; } public: ClingPragmaHandler(Interpreter& interp): PragmaHandler("cling"), m_Interp(interp) {} void HandlePragma(Preprocessor& PP, PragmaIntroducerKind Introducer, Token& FirstToken) override { Token Tok; PP.Lex(Tok); SkipToEOD OnExit(PP, Tok); if (Tok.isNot(tok::identifier)) { ReportCommandErr(PP, Tok); return; } const StringRef CommandStr = Tok.getIdentifierInfo()->getName(); const int Command = GetCommand(CommandStr); if (Command == kInvalidCommand) { ReportCommandErr(PP, Tok); return; } PP.Lex(Tok); if (Tok.isNot(tok::l_paren)) { PP.Diag(Tok.getLocation(), diag::err_expected_lparen_after) << CommandStr; return; } std::string Literal; if (Command < kExpandEnvCommands) { if (!PP.LexStringLiteral(Tok, Literal, CommandStr.str().c_str(), false /*allowMacroExpansion*/)) { // already diagnosed. return; } utils::ExpandEnvVars(Literal); } else { PP.Lex(Tok); llvm::SmallString<64> Buffer; Literal = PP.getSpelling(Tok, Buffer).str(); } switch (Command) { case kLoadFile: if (!m_Interp.isInSyntaxOnlyMode()) { // No need to load libraries if we're not executing anything. clang::Parser& P = m_Interp.getParser(); Parser::ParserCurTokRestoreRAII savedCurToken(P); // After we have saved the token reset the current one to something // which is safe (semi colon usually means empty decl) Token& CurTok = const_cast<Token&>(P.getCurToken()); CurTok.setKind(tok::semi); Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP); // We can't PushDeclContext, because we go up and the routine that // pops the DeclContext assumes that we drill down always. // We have to be on the global context. At that point we are in a // wrapper function so the parent context must be the global. TranslationUnitDecl* TU = m_Interp.getCI()->getASTContext().getTranslationUnitDecl(); Sema::ContextAndScopeRAII pushedDCAndS(m_Interp.getSema(), TU, m_Interp.getSema().TUScope); Interpreter::PushTransactionRAII pushedT(&m_Interp); m_Interp.loadFile(Literal, true /*allowSharedLib*/); } break; case kAddLibrary: m_Interp.getOptions().LibSearchPath.push_back(std::move(Literal)); break; case kAddInclude: m_Interp.AddIncludePath(Literal); break; case kOptimize: { char* ConvEnd = nullptr; int OptLevel = std::strtol(Literal.c_str(), &ConvEnd, 10 /*base*/); if (!ConvEnd || ConvEnd == Literal.c_str()) { cling::errs() << "cling::PHOptLevel: " "missing or non-numerical optimization level.\n" ; return; } auto T = const_cast<Transaction*>(m_Interp.getCurrentTransaction()); assert(T && "Parsing code without transaction!"); // The topmost Transaction drives the jitting. T = T->getTopmostParent(); CompilationOptions& CO = T->getCompilationOpts(); if (CO.OptLevel != m_Interp.getDefaultOptLevel()) { // Another #pragma already changed the opt level, a conflict that // cannot be resolve here. Mention and keep the lower one. cling::errs() << "cling::PHOptLevel: " "conflicting `#pragma cling optimize` directives: " "was already set to " << CO.OptLevel << '\n'; if (CO.OptLevel > OptLevel) { CO.OptLevel = OptLevel; cling::errs() << "Setting to lower value of " << OptLevel << '\n'; } else { cling::errs() << "Ignoring higher value of " << OptLevel << '\n'; } } else { CO.OptLevel = OptLevel; } } } } }; } void cling::addClingPragmas(Interpreter& interp) { Preprocessor& PP = interp.getCI()->getPreprocessor(); // PragmaNamespace / PP takes ownership of sub-handlers. PP.AddPragmaHandler(StringRef(), new ClingPragmaHandler(interp)); }
Save some memory and only create one ClingPragmaHandler to handle all pragmas. Use clang diagnostics for parsing errors.
Save some memory and only create one ClingPragmaHandler to handle all pragmas. Use clang diagnostics for parsing errors.
C++
lgpl-2.1
mhuwiler/rootauto,zzxuanyuan/root,root-mirror/root,zzxuanyuan/root,simonpf/root,root-mirror/root,mhuwiler/rootauto,zzxuanyuan/root,zzxuanyuan/root,root-mirror/root,mhuwiler/rootauto,mhuwiler/rootauto,mhuwiler/rootauto,zzxuanyuan/root,olifre/root,olifre/root,karies/root,olifre/root,root-mirror/root,simonpf/root,olifre/root,root-mirror/root,simonpf/root,mhuwiler/rootauto,root-mirror/root,olifre/root,olifre/root,karies/root,zzxuanyuan/root,mhuwiler/rootauto,karies/root,mhuwiler/rootauto,olifre/root,simonpf/root,karies/root,simonpf/root,root-mirror/root,olifre/root,zzxuanyuan/root,simonpf/root,simonpf/root,simonpf/root,mhuwiler/rootauto,olifre/root,zzxuanyuan/root,zzxuanyuan/root,root-mirror/root,zzxuanyuan/root,simonpf/root,olifre/root,karies/root,zzxuanyuan/root,simonpf/root,karies/root,simonpf/root,karies/root,root-mirror/root,karies/root,mhuwiler/rootauto,olifre/root,karies/root,zzxuanyuan/root,root-mirror/root,karies/root,mhuwiler/rootauto,root-mirror/root,karies/root
2f632b1e21343cfb3bbd0dcf3712175de9fa85d3
src/base_controller/src/base_controller/base_controller_node.cpp
src/base_controller/src/base_controller/base_controller_node.cpp
#include <iostream> #include <stdio.h> /* Standard input/output definitions */ #include <stdlib.h> /* exit */ #include <string.h> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <ctype.h> /* isxxx() */ #include <ros/ros.h> #include <geometry_msgs/Twist.h> struct termios orig; int filedesc; int fd; unsigned char serialBuffer[16]; // Serial buffer to store data for I/O int openSerialPort(const char * device, int bps) { struct termios neu; char buf[128]; fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); //fprintf(stderr, "speed=%d\n", bps); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } //write(fd,serialBuffer, count); } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } void read_MD49_Data (void){ serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); //Daten lesen und in Array schreiben readBytes(fd, 18); printf("\033[2J"); /* clear the screen */ printf("\033[H"); /* position cursor at top-left corner */ printf ("MD49-Data read from AVR-Master: \n"); printf("====================================================== \n"); printf("Encoder1 Byte1: %i ",serialBuffer[0]); printf("Byte2: %i ",serialBuffer[1]); printf("Byte3: % i ",serialBuffer[2]); printf("Byte4: %i \n",serialBuffer[3]); printf("Encoder2 Byte1: %i ",serialBuffer[4]); printf("Byte2: %i ",serialBuffer[5]); printf("Byte3: %i ",serialBuffer[6]); printf("Byte4: %i \n",serialBuffer[7]); printf("====================================================== \n"); printf("Speed1: %i ",serialBuffer[8]); printf("Speed2: %i \n",serialBuffer[9]); printf("Volts: %i \n",serialBuffer[10]); printf("Current1: %i ",serialBuffer[11]); printf("Current2: %i \n",serialBuffer[12]); printf("Error: %i \n",serialBuffer[13]); printf("Acceleration: %i \n",serialBuffer[14]); printf("Mode: %i \n",serialBuffer[15]); printf("Regulator: %i \n",serialBuffer[16]); printf("Timeout: %i \n",serialBuffer[17]); } void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd) { //ROS_INFO("I heard: [%f]", vel_cmd.linear.y); //std::cout << "Twist Received " << std::endl; if (vel_cmd.linear.x>0){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = 255; // speed1 serialBuffer[3] = 255; // speed2 writeBytes(fd, 4); } if (vel_cmd.linear.x==0){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = 128; // speed1 serialBuffer[3] = 128; // speed2 writeBytes(fd, 4); } } int main( int argc, char* argv[] ) { ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 1000, cmd_vel_callback); filedesc = openSerialPort("/dev/ttyAMA0", B38400); if (filedesc == -1) exit(1); usleep(40000);// Sleep for UART to power up and set options //ROS_INFO_STREAM("serial Port opened \n"); while( n.ok() ) { read_MD49_Data(); usleep(100000);//ca.10Hz ros::spinOnce(); } return 1; }
#include <iostream> #include <stdio.h> /* Standard input/output definitions */ #include <stdlib.h> /* exit */ #include <string.h> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <ctype.h> /* isxxx() */ #include <ros/ros.h> #include <geometry_msgs/Twist.h> struct termios orig; int filedesc; int fd; unsigned char serialBuffer[16]; // Serial buffer to store data for I/O int openSerialPort(const char * device, int bps) { struct termios neu; char buf[128]; fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); //fprintf(stderr, "speed=%d\n", bps); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } //write(fd,serialBuffer, count); } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } void read_MD49_Data (void){ serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); //Daten lesen und in Array schreiben readBytes(fd, 18); printf("\033[2J"); /* clear the screen */ printf("\033[H"); /* position cursor at top-left corner */ printf ("MD49-Data read from AVR-Master: \n"); printf("====================================================== \n"); printf("Encoder1 Byte1: %i ",serialBuffer[0]); printf("Byte2: %i ",serialBuffer[1]); printf("Byte3: % i ",serialBuffer[2]); printf("Byte4: %i \n",serialBuffer[3]); printf("Encoder2 Byte1: %i ",serialBuffer[4]); printf("Byte2: %i ",serialBuffer[5]); printf("Byte3: %i ",serialBuffer[6]); printf("Byte4: %i \n",serialBuffer[7]); printf("====================================================== \n"); printf("Speed1: %i ",serialBuffer[8]); printf("Speed2: %i \n",serialBuffer[9]); printf("Volts: %i \n",serialBuffer[10]); printf("Current1: %i ",serialBuffer[11]); printf("Current2: %i \n",serialBuffer[12]); printf("Error: %i \n",serialBuffer[13]); printf("Acceleration: %i \n",serialBuffer[14]); printf("Mode: %i \n",serialBuffer[15]); printf("Regulator: %i \n",serialBuffer[16]); printf("Timeout: %i \n",serialBuffer[17]); } void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd) { //ROS_INFO("I heard: [%f]", vel_cmd.linear.y); //std::cout << "Twist Received " << std::endl; if (vel_cmd.linear.x>0){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = 255; // speed1 serialBuffer[3] = 255; // speed2 writeBytes(fd, 4); } if (vel_cmd.linear.x<0){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = 0; // speed1 serialBuffer[3] = 0; // speed2 writeBytes(fd, 4); } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = 128; // speed1 serialBuffer[3] = 128; // speed2 writeBytes(fd, 4); } if (vel_cmd.angular.z>0){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = 0; // speed1 serialBuffer[3] = 255; // speed2 writeBytes(fd, 4); } if (vel_cmd.angular.z<0){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = 255; // speed1 serialBuffer[3] = 0; // speed2 writeBytes(fd, 4); } } int main( int argc, char* argv[] ) { ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 1000, cmd_vel_callback); filedesc = openSerialPort("/dev/ttyAMA0", B38400); if (filedesc == -1) exit(1); usleep(40000);// Sleep for UART to power up and set options //ROS_INFO_STREAM("serial Port opened \n"); while( n.ok() ) { read_MD49_Data(); usleep(100000);//ca.10Hz ros::spinOnce(); } return 1; }
Update code
Update code
C++
bsd-3-clause
Scheik/ROS-Workspace,Scheik/ROS-Groovy-Workspace,Scheik/ROS-Groovy-Workspace,Scheik/ROS-Workspace
1fa85bb59736962174a6e00ae62836fd348751b5
src/base_controller/src/base_controller/base_controller_node.cpp
src/base_controller/src/base_controller/base_controller_node.cpp
#include <iostream> /* allows to perform standard input and output operations */ #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ //#include <string> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <ctype.h> /* isxxx() */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ const char* serialport="/dev/ttyAMA0"; /* defines used serialport */ int serialport_bps=B38400; /* defines baudrate od serialport */ int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ bool cmd_vel_received=true; double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ int filedesc; /* filedescriptor serialport */ int fd; /* serial port file descriptor */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ struct termios orig; /* stores original settings */ int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void read_MD49_Data (void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ ROS_DEBUG("geometry_msgs/Twist received: linear.x= %f angular.z= %f", vel_cmd.linear.x, vel_cmd.angular.z); //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; //serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden //serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed //serialBuffer[2] = 255; // speed1 //serialBuffer[3] = 255; // speed2 //writeBytes(fd, 4); } if (vel_cmd.linear.x<0){ speed_l = 0; speed_r = 0; } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; } if (vel_cmd.angular.z>0){ speed_l = 0; speed_r = 255; } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 0; } cmd_vel_received=true; } int main( int argc, char* argv[] ){ ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 100, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",100); // Open serial port // **************** filedesc = openSerialPort("/dev/ttyAMA0", B38400); if (filedesc == -1) exit(1); usleep(40000); // Sleep for UART to power up and set options ROS_DEBUG("Serial Port opened \n"); // Set nodes looprate 10Hz // *********************** ros::Rate loop_rate(10); while( n.ok() ) { // Read encoder and other data from MD49 // ************************************* read_MD49_Data(); // Set speed left and right for MD49 // ******************************** if (cmd_vel_received==true) { set_MD49_speed(speed_l,speed_r); set_MD49_speed(speed_l,speed_r); cmd_vel_received=false; } //set_MD49_speed(speed_l,speed_r); // Publish encoder values to topic /encoders (custom message) // ******************************************************************** base_controller::encoders encoders; encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Loop // **** ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); fd = open(device, O_RDWR | O_NOCTTY); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); //fprintf(stderr, "speed=%d\n", bps); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } //write(fd,serialBuffer, count); } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } void read_MD49_Data (void){ serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); //Daten lesen und in Array schreiben readBytes(fd, 18); printf("\033[2J"); /* clear the screen */ printf("\033[H"); /* position cursor at top-left corner */ printf ("MD49-Data read from AVR-Master: \n"); printf("====================================================== \n"); //printf("Encoder1 Byte1: %i ",serialBuffer[0]); //printf("Byte2: %i ",serialBuffer[1]); //printf("Byte3: % i ",serialBuffer[2]); //printf("Byte4: %i \n",serialBuffer[3]); //printf("Encoder2 Byte1: %i ",serialBuffer[4]); //printf("Byte2: %i ",serialBuffer[5]); //printf("Byte3: %i ",serialBuffer[6]); //printf("Byte4: %i \n",serialBuffer[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("====================================================== \n"); printf("Speed1: %i ",serialBuffer[8]); printf("Speed2: %i \n",serialBuffer[9]); printf("Volts: %i \n",serialBuffer[10]); printf("Current1: %i ",serialBuffer[11]); printf("Current2: %i \n",serialBuffer[12]); printf("Error: %i \n",serialBuffer[13]); printf("Acceleration: %i \n",serialBuffer[14]); printf("Mode: %i \n",serialBuffer[15]); printf("Regulator: %i \n",serialBuffer[16]); printf("Timeout: %i \n",serialBuffer[17]); printf("vl= %f \n", vl); printf("vr= %f \n", vr); EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); } void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = speed_l; // speed1 serialBuffer[3] = speed_r; // speed2 writeBytes(fd, 4); }
#include <iostream> /* allows to perform standard input and output operations */ #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ //#include <string> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <ctype.h> /* isxxx() */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ const char* serialport="/dev/ttyAMA0"; /* defines used serialport */ int serialport_bps=B38400; /* defines baudrate od serialport */ int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ bool cmd_vel_received=true; double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ int filedesc; /* filedescriptor serialport */ int fd; /* serial port file descriptor */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ struct termios orig; /* stores original settings */ int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void read_MD49_Data (void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ ROS_DEBUG("geometry_msgs/Twist received: linear.x= %f angular.z= %f", vel_cmd.linear.x, vel_cmd.angular.z); //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; //serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden //serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed //serialBuffer[2] = 255; // speed1 //serialBuffer[3] = 255; // speed2 //writeBytes(fd, 4); } if (vel_cmd.linear.x<0){ speed_l = 0; speed_r = 0; } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; } if (vel_cmd.angular.z>0){ speed_l = 0; speed_r = 255; } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 0; } cmd_vel_received=true; } int main( int argc, char* argv[] ){ ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 100, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",100); // Open serial port // **************** filedesc = openSerialPort("/dev/ttyAMA0", B38400); if (filedesc == -1) exit(1); usleep(40000); // Sleep for UART to power up and set options ROS_DEBUG("Serial Port opened \n"); // Set nodes looprate 10Hz // *********************** ros::Rate loop_rate(50); while( n.ok() ) { // Read encoder and other data from MD49 // ************************************* read_MD49_Data(); // Set speed left and right for MD49 // ******************************** if (cmd_vel_received==true) { set_MD49_speed(speed_l,speed_r); //set_MD49_speed(speed_l,speed_r); cmd_vel_received=false; } //set_MD49_speed(speed_l,speed_r); // Publish encoder values to topic /encoders (custom message) // ******************************************************************** base_controller::encoders encoders; encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Loop // **** ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); fd = open(device, O_RDWR | O_NOCTTY); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); //fprintf(stderr, "speed=%d\n", bps); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } //write(fd,serialBuffer, count); } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } void read_MD49_Data (void){ serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); //Daten lesen und in Array schreiben readBytes(fd, 18); printf("\033[2J"); /* clear the screen */ printf("\033[H"); /* position cursor at top-left corner */ printf ("MD49-Data read from AVR-Master: \n"); printf("====================================================== \n"); //printf("Encoder1 Byte1: %i ",serialBuffer[0]); //printf("Byte2: %i ",serialBuffer[1]); //printf("Byte3: % i ",serialBuffer[2]); //printf("Byte4: %i \n",serialBuffer[3]); //printf("Encoder2 Byte1: %i ",serialBuffer[4]); //printf("Byte2: %i ",serialBuffer[5]); //printf("Byte3: %i ",serialBuffer[6]); //printf("Byte4: %i \n",serialBuffer[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("====================================================== \n"); printf("Speed1: %i ",serialBuffer[8]); printf("Speed2: %i \n",serialBuffer[9]); printf("Volts: %i \n",serialBuffer[10]); printf("Current1: %i ",serialBuffer[11]); printf("Current2: %i \n",serialBuffer[12]); printf("Error: %i \n",serialBuffer[13]); printf("Acceleration: %i \n",serialBuffer[14]); printf("Mode: %i \n",serialBuffer[15]); printf("Regulator: %i \n",serialBuffer[16]); printf("Timeout: %i \n",serialBuffer[17]); printf("vl= %f \n", vl); printf("vr= %f \n", vr); EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); } void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = speed_l; // speed1 serialBuffer[3] = speed_r; // speed2 writeBytes(fd, 4); }
Update code
Update code
C++
bsd-3-clause
Scheik/ROS-Workspace,Scheik/ROS-Groovy-Workspace,Scheik/ROS-Groovy-Workspace,Scheik/ROS-Workspace
3a2fa4d3cd9d224814f67f19a5a7aabcb8ee1242
src/base_controller/src/base_controller/base_controller_node.cpp
src/base_controller/src/base_controller/base_controller_node.cpp
#include <iostream> /* allows to perform standard input and output operations */ #include <fstream> #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <ctype.h> /* isxxx() */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ #include <base_controller/md49data.h> /* Custom message /encoders */ int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */ double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ unsigned char serialBuffer[18]; /* Serial buffer to store uart data */ void read_MD49_Data (void); void set_md49_speed (unsigned char speed_l, unsigned char speed_r); char* itoa(int value, char* result, int base); using namespace std; base_controller::encoders encoders; base_controller::md49data md49data; void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; } if (vel_cmd.linear.x<0){ speed_l = 100; speed_r = 100; } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; } if (vel_cmd.angular.z>0){ speed_l = 1; speed_r = 255; } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 1; } /* //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative */ } int main( int argc, char* argv[] ){ ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10); ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10); // Set nodes looprate 10Hz // *********************** ros::Rate loop_rate(10); ROS_INFO("base_controller is running:"); ROS_INFO("reading md49data from md49_data.txt"); ROS_INFO("writing md49commands to md49_commands.txt"); ROS_INFO("============================================"); ROS_INFO("base_controller subscribes to topic /cmd_vel"); ROS_INFO("base_controller publises to topic /encoders"); ROS_INFO("base_controller publises to topic /md49data"); while(n.ok()) { // Read encoder values and other data from MD49: // serial_controller_node reads data from AVR-Master // and provides that data in md49_data.txt // ************************************************* read_MD49_Data(); // Set MD49 speed_l and speed_r: // serial_controller_node reads commands from // md49_commands.txt and writes commands to AVR-Master // *************************************************** if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){ set_md49_speed(speed_l,speed_r); last_speed_l=speed_l; last_speed_r=speed_r; } // Publish encoder values to topic /encoders (custom message) // ********************************************************** encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Publish MD49 data to topic /md49data (custom message) // ***************************************************** md49data.speed_l = serialBuffer[8]; md49data.speed_r = serialBuffer[9]; md49data.volt = serialBuffer[10]; md49data.current_l = serialBuffer[11]; md49data.current_r = serialBuffer[12]; md49data.error = serialBuffer[13]; md49data.acceleration = serialBuffer[14]; md49data.mode = serialBuffer[15]; md49data.regulator = serialBuffer[16]; md49data.timeout = serialBuffer[17]; md49data_pub.publish(md49data); ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main void read_MD49_Data (void){ // Read all MD49 data from md49_data.txt // ************************************* string line; ifstream myfile ("md49_data.txt"); if (myfile.is_open()){ int i=0; while (getline (myfile,line)){ //cout << line << '\n'; char data[10]; std::copy(line.begin(), line.end(), data); serialBuffer[i]=atoi(data); i =i++; } myfile.close(); } else ROS_ERROR("Unable to open file: md49_data.txt"); // Put toghether new encodervalues // ******************************* EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); } void set_md49_speed (unsigned char speed_l, unsigned char speed_r){ char buffer[33]; ofstream myfile; myfile.open ("md49_commands.txt"); //myfile << "Writing this to a file.\n"; /* if (speed_l==0){ myfile << "000"; myfile << "\n"; } else if (speed_l<10){ myfile << "00"; myfile << itoa(speed_l,buffer,10); myfile << "\n"; } else if (speed_l<100){ myfile << "0"; myfile << itoa(speed_l,buffer,10); myfile << "\n"; } else{ myfile << itoa(speed_l,buffer,10); myfile << "\n"; } if (speed_r==0){ myfile << "000"; myfile << "\n"; } else if (speed_r<10){ myfile << "00"; myfile << itoa(speed_r,buffer,10); myfile << "\n"; } else if (speed_r<100){ myfile << "0"; myfile << itoa(speed_r,buffer,10); myfile << "\n"; } else{ myfile << itoa(speed_r,buffer,10); myfile << "\n"; } */ myfile << itoa(speed_l,buffer,10); myfile << "\n"; myfile << itoa(speed_r,buffer,10); myfile << "\n"; myfile.close(); } char* itoa(int value, char* result, int base) { // check that the base if valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while(ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; }
#include <iostream> /* allows to perform standard input and output operations */ #include <fstream> #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <ctype.h> /* isxxx() */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ #include <base_controller/md49data.h> /* Custom message /encoders */ int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ unsigned char last_speed_l=128, last_speed_r=128; /* speed to set for MD49 */ double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ unsigned char serialBuffer[18]; /* Serial buffer to store uart data */ void read_MD49_Data (void); void set_md49_speed (unsigned char speed_l, unsigned char speed_r); char* itoa(int value, char* result, int base); using namespace std; base_controller::encoders encoders; base_controller::md49data md49data; void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; } if (vel_cmd.linear.x<0){ speed_l = 0; speed_r = 0; } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; } if (vel_cmd.angular.z>0){ speed_l = 0; speed_r = 255; } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 0; } /* //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative */ } int main( int argc, char* argv[] ){ ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 10, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",10); ros::Publisher md49data_pub = n.advertise<base_controller::md49data>("md49data",10); // Set nodes looprate 10Hz // *********************** ros::Rate loop_rate(10); ROS_INFO("base_controller is running:"); ROS_INFO("reading md49data from md49_data.txt"); ROS_INFO("writing md49commands to md49_commands.txt"); ROS_INFO("============================================"); ROS_INFO("base_controller subscribes to topic /cmd_vel"); ROS_INFO("base_controller publises to topic /encoders"); ROS_INFO("base_controller publises to topic /md49data"); while(n.ok()) { // Read encoder values and other data from MD49: // serial_controller_node reads data from AVR-Master // and provides that data in md49_data.txt // ************************************************* read_MD49_Data(); // Set MD49 speed_l and speed_r: // serial_controller_node reads commands from // md49_commands.txt and writes commands to AVR-Master // *************************************************** if ((speed_l != last_speed_l) || (speed_r != last_speed_r)){ set_md49_speed(speed_l,speed_r); last_speed_l=speed_l; last_speed_r=speed_r; } // Publish encoder values to topic /encoders (custom message) // ********************************************************** encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Publish MD49 data to topic /md49data (custom message) // ***************************************************** md49data.speed_l = serialBuffer[8]; md49data.speed_r = serialBuffer[9]; md49data.volt = serialBuffer[10]; md49data.current_l = serialBuffer[11]; md49data.current_r = serialBuffer[12]; md49data.error = serialBuffer[13]; md49data.acceleration = serialBuffer[14]; md49data.mode = serialBuffer[15]; md49data.regulator = serialBuffer[16]; md49data.timeout = serialBuffer[17]; md49data_pub.publish(md49data); ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main void read_MD49_Data (void){ // Read all MD49 data from md49_data.txt // ************************************* string line; ifstream myfile ("md49_data.txt"); if (myfile.is_open()){ int i=0; while (getline (myfile,line)){ //cout << line << '\n'; char data[10]; std::copy(line.begin(), line.end(), data); serialBuffer[i]=atoi(data); i =i++; } myfile.close(); } else ROS_ERROR("Unable to open file: md49_data.txt"); // Put toghether new encodervalues // ******************************* EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); } void set_md49_speed (unsigned char speed_l, unsigned char speed_r){ char buffer[33]; ofstream myfile; myfile.open ("md49_commands.txt"); //myfile << "Writing this to a file.\n"; /* if (speed_l==0){ myfile << "000"; myfile << "\n"; } else if (speed_l<10){ myfile << "00"; myfile << itoa(speed_l,buffer,10); myfile << "\n"; } else if (speed_l<100){ myfile << "0"; myfile << itoa(speed_l,buffer,10); myfile << "\n"; } else{ myfile << itoa(speed_l,buffer,10); myfile << "\n"; } if (speed_r==0){ myfile << "000"; myfile << "\n"; } else if (speed_r<10){ myfile << "00"; myfile << itoa(speed_r,buffer,10); myfile << "\n"; } else if (speed_r<100){ myfile << "0"; myfile << itoa(speed_r,buffer,10); myfile << "\n"; } else{ myfile << itoa(speed_r,buffer,10); myfile << "\n"; } */ myfile << itoa(speed_l,buffer,10); myfile << "\n"; myfile << itoa(speed_r,buffer,10); myfile << "\n"; myfile.close(); } char* itoa(int value, char* result, int base) { // check that the base if valid if (base < 2 || base > 36) { *result = '\0'; return result; } char* ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while ( value ); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while(ptr1 < ptr) { tmp_char = *ptr; *ptr--= *ptr1; *ptr1++ = tmp_char; } return result; }
Update code
Update code
C++
bsd-3-clause
Scheik/ROS-Groovy-Workspace,Scheik/ROS-Workspace,Scheik/ROS-Workspace,Scheik/ROS-Groovy-Workspace
a7f13d9bd89098254b79701c68026b0df90916a0
src/base_controller/src/base_controller/base_controller_node.cpp
src/base_controller/src/base_controller/base_controller_node.cpp
#include <iostream> /* allows to perform standard input and output operations */ #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ //#include <string> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <ctype.h> /* isxxx() */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ const char* serialport="/dev/ttyAMA0"; /* defines used serialport */ int serialport_bps=B38400; /* defines baudrate od serialport */ int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ bool cmd_vel_received=true; double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ int filedesc; /* filedescriptor serialport */ int fd; /* serial port file descriptor */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ struct termios orig; /* stores original settings */ int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void read_MD49_Data (void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ ROS_DEBUG("geometry_msgs/Twist received: linear.x= %f angular.z= %f", vel_cmd.linear.x, vel_cmd.angular.z); //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; //serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden //serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed //serialBuffer[2] = 255; // speed1 //serialBuffer[3] = 255; // speed2 //writeBytes(fd, 4); } if (vel_cmd.linear.x<0){ speed_l = 0; speed_r = 0; } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; } if (vel_cmd.angular.z>0){ speed_l = 0; speed_r = 255; } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 0; } cmd_vel_received=true; } int main( int argc, char* argv[] ){ ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 100, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",100); // Open serial port // **************** filedesc = openSerialPort("/dev/ttyAMA0", B38400); if (filedesc == -1) exit(1); usleep(40000); // Sleep for UART to power up and set options ROS_DEBUG("Serial Port opened \n"); // Set nodes looprate 10Hz // *********************** ros::Rate loop_rate(5); while( n.ok() ) { // Read encoder and other data from MD49 // ************************************* read_MD49_Data(); // Set speed left and right for MD49 // ******************************** if (cmd_vel_received==true) { set_MD49_speed(speed_l,speed_r); //set_MD49_speed(speed_l,speed_r); cmd_vel_received=false; } //set_MD49_speed(speed_l,speed_r); // Publish encoder values to topic /encoders (custom message) // ******************************************************************** base_controller::encoders encoders; encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Loop // **** ros::spinOnce(); //loop_rate.sleep(); }// end.mainloop return 1; } // end.main int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); fd = open(device, O_RDWR | O_NOCTTY); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); //fprintf(stderr, "speed=%d\n", bps); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } //write(fd,serialBuffer, count); } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } void read_MD49_Data (void){ serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); //Daten lesen und in Array schreiben readBytes(fd, 18); printf("\033[2J"); /* clear the screen */ printf("\033[H"); /* position cursor at top-left corner */ printf ("MD49-Data read from AVR-Master: \n"); printf("====================================================== \n"); //printf("Encoder1 Byte1: %i ",serialBuffer[0]); //printf("Byte2: %i ",serialBuffer[1]); //printf("Byte3: % i ",serialBuffer[2]); //printf("Byte4: %i \n",serialBuffer[3]); //printf("Encoder2 Byte1: %i ",serialBuffer[4]); //printf("Byte2: %i ",serialBuffer[5]); //printf("Byte3: %i ",serialBuffer[6]); //printf("Byte4: %i \n",serialBuffer[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("====================================================== \n"); printf("Speed1: %i ",serialBuffer[8]); printf("Speed2: %i \n",serialBuffer[9]); printf("Volts: %i \n",serialBuffer[10]); printf("Current1: %i ",serialBuffer[11]); printf("Current2: %i \n",serialBuffer[12]); printf("Error: %i \n",serialBuffer[13]); printf("Acceleration: %i \n",serialBuffer[14]); printf("Mode: %i \n",serialBuffer[15]); printf("Regulator: %i \n",serialBuffer[16]); printf("Timeout: %i \n",serialBuffer[17]); printf("vl= %f \n", vl); printf("vr= %f \n", vr); EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); } void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = speed_l; // speed1 serialBuffer[3] = speed_r; // speed2 writeBytes(fd, 4); }
#include <iostream> /* allows to perform standard input and output operations */ #include <stdio.h> /* Standard input/output definitions */ #include <stdint.h> /* Standard input/output definitions */ #include <stdlib.h> /* defines several general purpose functions */ //#include <string> /* String function definitions */ #include <unistd.h> /* UNIX standard function definitions */ #include <fcntl.h> /* File control definitions */ #include <errno.h> /* Error number definitions */ #include <termios.h> /* POSIX terminal control definitions */ #include <ctype.h> /* isxxx() */ #include <ros/ros.h> /* ROS */ #include <geometry_msgs/Twist.h> /* ROS Twist message */ #include <base_controller/encoders.h> /* Custom message /encoders */ const char* serialport="/dev/ttyAMA0"; /* defines used serialport */ int serialport_bps=B38400; /* defines baudrate od serialport */ int32_t EncoderL; /* stores encoder value left read from md49 */ int32_t EncoderR; /* stores encoder value right read from md49 */ unsigned char speed_l=128, speed_r=128; /* speed to set for MD49 */ bool cmd_vel_received=true; double vr = 0.0; double vl = 0.0; double max_vr = 0.2; double max_vl = 0.2; double min_vr = 0.2; double min_vl = 0.2; double base_width = 0.4; /* Base width in meters */ int filedesc; /* filedescriptor serialport */ int fd; /* serial port file descriptor */ unsigned char serialBuffer[16]; /* Serial buffer to store uart data */ struct termios orig; // Port options int openSerialPort(const char * device, int bps); void writeBytes(int descriptor, int count); void readBytes(int descriptor, int count); void read_MD49_Data (void); void set_MD49_speed (unsigned char speed_l, unsigned char speed_r); void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd){ ROS_DEBUG("geometry_msgs/Twist received: linear.x= %f angular.z= %f", vel_cmd.linear.x, vel_cmd.angular.z); //ANFANG Alternative if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){vl=0;vr=0;} else if(vel_cmd.linear.x == 0){ // turning vr = vel_cmd.angular.z * base_width / 2.0; vl = (-1) * vr; } else if(vel_cmd.angular.z == 0){ // forward / backward vl = vr = vel_cmd.linear.x; } else{ // moving doing arcs vl = vel_cmd.linear.x - vel_cmd.angular.z * base_width / 2.0; if (vl > max_vl) {vl=max_vl;} if (vl < min_vl) {vl=min_vl;} vr = vel_cmd.linear.x + vel_cmd.angular.z * base_width / 2.0; if (vr > max_vr) {vr=max_vr;} if (vr < min_vr) {vr=min_vr;} } //ENDE Alternative if (vel_cmd.linear.x>0){ speed_l = 255; speed_r = 255; //serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden //serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed //serialBuffer[2] = 255; // speed1 //serialBuffer[3] = 255; // speed2 //writeBytes(fd, 4); } if (vel_cmd.linear.x<0){ speed_l = 0; speed_r = 0; } if (vel_cmd.linear.x==0 && vel_cmd.angular.z==0){ speed_l = 128; speed_r = 128; } if (vel_cmd.angular.z>0){ speed_l = 0; speed_r = 255; } if (vel_cmd.angular.z<0){ speed_l = 255; speed_r = 0; } cmd_vel_received=true; } int main( int argc, char* argv[] ){ ros::init(argc, argv, "base_controller" ); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("/cmd_vel", 100, cmd_vel_callback); ros::Publisher encoders_pub = n.advertise<base_controller::encoders>("encoders",100); // Open serial port // **************** filedesc = openSerialPort("/dev/ttyAMA0", B38400); if (filedesc == -1) exit(1); usleep(10000); // Sleep for UART to power up and set options ROS_DEBUG("Serial Port opened \n"); // Set nodes looprate 10Hz // *********************** ros::Rate loop_rate(5); while( n.ok() ) { // Read encoder and other data from MD49 // ************************************* read_MD49_Data(); // Set speed left and right for MD49 // ******************************** if (cmd_vel_received==true) { set_MD49_speed(speed_l,speed_r); //set_MD49_speed(speed_l,speed_r); cmd_vel_received=false; } //set_MD49_speed(speed_l,speed_r); // Publish encoder values to topic /encoders (custom message) // ******************************************************************** base_controller::encoders encoders; encoders.encoder_l=EncoderL; encoders.encoder_r=EncoderR; encoders_pub.publish(encoders); // Loop // **** ros::spinOnce(); loop_rate.sleep(); }// end.mainloop return 1; } // end.main int openSerialPort(const char * device, int bps){ struct termios neu; char buf[128]; //fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); fd = open(device, O_RDWR | O_NOCTTY); if (fd == -1) { sprintf(buf, "openSerialPort %s error", device); perror(buf); } else { tcgetattr(fd, &orig); /* save current serial settings */ tcgetattr(fd, &neu); cfmakeraw(&neu); //fprintf(stderr, "speed=%d\n", bps); cfsetispeed(&neu, bps); cfsetospeed(&neu, bps); tcflush(fd, TCIFLUSH); tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */ fcntl (fd, F_SETFL, O_RDWR); } return fd; } void writeBytes(int descriptor, int count) { if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out perror("Error writing"); close(descriptor); // Close port if there is an error exit(1); } //write(fd,serialBuffer, count); } void readBytes(int descriptor, int count) { if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[] perror("Error reading "); close(descriptor); // Close port if there is an error exit(1); } } void read_MD49_Data (void){ serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen writeBytes(fd, 1); //Daten lesen und in Array schreiben readBytes(fd, 18); printf("\033[2J"); /* clear the screen */ printf("\033[H"); /* position cursor at top-left corner */ printf ("MD49-Data read from AVR-Master: \n"); printf("====================================================== \n"); //printf("Encoder1 Byte1: %i ",serialBuffer[0]); //printf("Byte2: %i ",serialBuffer[1]); //printf("Byte3: % i ",serialBuffer[2]); //printf("Byte4: %i \n",serialBuffer[3]); //printf("Encoder2 Byte1: %i ",serialBuffer[4]); //printf("Byte2: %i ",serialBuffer[5]); //printf("Byte3: %i ",serialBuffer[6]); //printf("Byte4: %i \n",serialBuffer[7]); printf("EncoderL: %i ",EncoderL); printf("EncoderR: %i \n",EncoderR); printf("====================================================== \n"); printf("Speed1: %i ",serialBuffer[8]); printf("Speed2: %i \n",serialBuffer[9]); printf("Volts: %i \n",serialBuffer[10]); printf("Current1: %i ",serialBuffer[11]); printf("Current2: %i \n",serialBuffer[12]); printf("Error: %i \n",serialBuffer[13]); printf("Acceleration: %i \n",serialBuffer[14]); printf("Mode: %i \n",serialBuffer[15]); printf("Regulator: %i \n",serialBuffer[16]); printf("Timeout: %i \n",serialBuffer[17]); printf("vl= %f \n", vl); printf("vr= %f \n", vr); EncoderL = serialBuffer[0] << 24; // Put together first encoder value EncoderL |= (serialBuffer[1] << 16); EncoderL |= (serialBuffer[2] << 8); EncoderL |= (serialBuffer[3]); EncoderR = serialBuffer[4] << 24; // Put together second encoder value EncoderR |= (serialBuffer[5] << 16); EncoderR |= (serialBuffer[6] << 8); EncoderR |= (serialBuffer[7]); } void set_MD49_speed (unsigned char speed_l, unsigned char speed_r){ serialBuffer[0] = 88; // 88 =X Steuerbyte um Commands an MD49 zu senden serialBuffer[1] = 115; // 115=s Steuerbyte setSpeed serialBuffer[2] = speed_l; // speed1 serialBuffer[3] = speed_r; // speed2 writeBytes(fd, 4); }
Update code
Update code
C++
bsd-3-clause
Scheik/ROS-Workspace,Scheik/ROS-Groovy-Workspace,Scheik/ROS-Workspace,Scheik/ROS-Groovy-Workspace
471c725e601c70f15dcde8fa8ff7eda53154043c
generation_tests/test_numbers.cpp
generation_tests/test_numbers.cpp
#include "grune/all.hpp" #include <sstream> using namespace grune; sequence digits(int low = 0, int high = 10) { sequence result; for (int i = low; i < high; ++i) { result.push_back(i); } return result; } sequence_list to_seq_list(const sequence& s) { sequence_list result; for (auto sym : s) { result.emplace_back( sequence { sym } ); } return result; } void test_numbers_simple(std::ostream& out) { /* * digit -> "0" | nonzero * nonzero -> "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" * number -> digit | nonzero digit | nonzero nonzero digit */ non_terminal Digit("digit"); non_terminal Nonzero("nonzero"); non_terminal Number("number"); grammar g { { Digit, Nonzero, Number }, digits(0, 1), { { Digit, { { 0 }, { Nonzero } } }, { Nonzero, { to_seq_list(digits(1, 2)) } }, { Number, { { Digit }, { Nonzero, Digit }, { Nonzero, Nonzero, Digit } } } }, Number }; auto begin = sentence_iterator(g); auto end = std::next(begin, 20); for (auto it = begin; it != end; ++it) { out << text(*it) << std::endl; } } void test_numbers(std::ostream& out) { /* * digit -> "0" | nonzero * nonzero -> "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" * number -> digit | nonzero digit | nonzero nonzero digit */ non_terminal Digit("digit"); non_terminal Nonzero("nonzero"); non_terminal Number("number"); grammar g { { Digit, Nonzero, Number }, digits(0, 10), { { Digit, { { 0 }, { Nonzero } } }, { Nonzero, { to_seq_list(digits(1, 10)) } }, { Number, { { Digit }, { Nonzero, Digit }, { Nonzero, Nonzero, Digit } } } }, Number }; auto begin = sentence_iterator(g); auto end = std::next(begin, 20); for (auto it = begin; it != end; ++it) { out << text(*it) << std::endl; } }
#include "grune/all.hpp" #include <sstream> using namespace grune; sequence digits(int low = 0, int high = 10) { sequence result; for (int i = low; i < high; ++i) { result.push_back(i); } return result; } sequence_list to_seq_list(const sequence& s) { sequence_list result; for (auto sym : s) { result.emplace_back( sequence { sym } ); } return result; } void test_numbers_simple(std::ostream& out) { /* * digit -> "0" | nonzero * nonzero -> "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" * number -> digit | nonzero digit | nonzero nonzero digit */ non_terminal Digit("digit"); non_terminal Nonzero("nonzero"); non_terminal Number("number"); grammar g { { Digit, Nonzero, Number }, digits(0, 1), { { Digit, { { 0 } } }, { Digit, { { Nonzero } } }, { Nonzero, to_seq_list(digits(1, 2)) }, { Number, { { Digit } } }, { Number, { { Nonzero, Digit } } }, { Number, { { Nonzero, Nonzero, Digit } } }, }, Number }; auto begin = sentence_iterator(g); auto end = std::next(begin, 20); for (auto it = begin; it != end; ++it) { out << text(*it) << std::endl; } } void test_numbers(std::ostream& out) { /* * digit -> "0" | nonzero * nonzero -> "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" * number -> digit | nonzero digit | nonzero nonzero digit */ non_terminal Digit("digit"); non_terminal Nonzero("nonzero"); non_terminal Number("number"); grammar g { { Digit, Nonzero, Number }, digits(0, 10), { { Digit, { { 0 } } }, { Digit, { { Nonzero } } }, { Nonzero, to_seq_list(digits(1, 10)) }, { Number, { { Digit } } }, { Number, { { Nonzero, Digit } } }, { Number, { { Nonzero, Nonzero, Digit } } } }, Number }; auto begin = sentence_iterator(g); auto end = std::next(begin, 20); for (auto it = begin; it != end; ++it) { out << text(*it) << std::endl; } }
Clean up test_number grammars
Clean up test_number grammars
C++
mit
Fifty-Nine/grune
b5891814142cb8075501b238e3892a9096b552e9
trunk/libmesh/src/solvers/newton_solver.C
trunk/libmesh/src/solvers/newton_solver.C
#include "diff_system.h" #include "libmesh_logging.h" #include "linear_solver.h" #include "newton_solver.h" #include "numeric_vector.h" #include "sparse_matrix.h" NewtonSolver::NewtonSolver (sys_type& s) : Parent(s), require_residual_reduction(false), minsteplength(0.0), linear_solver(LinearSolver<Number>::build()) { } NewtonSolver::~NewtonSolver () { } void NewtonSolver::reinit() { Parent::reinit(); linear_solver->clear(); } void NewtonSolver::solve() { START_LOG("solve()", "NewtonSolver"); // Amount by which nonlinear residual should exceed linear solver // tolerance const Real relative_tolerance = 1.e-3; NumericVector<Number> &solution = *(_system.solution); NumericVector<Number> &newton_iterate = _system.get_vector("_nonlinear_solution"); NumericVector<Number> &rhs = *(_system.rhs); SparseMatrix<Number> &matrix = *(_system.matrix); // Prepare to take incomplete steps Real last_residual=0.; // Set starting linear tolerance Real current_linear_tolerance = initial_linear_tolerance; // Now we begin the nonlinear loop for (unsigned int l=0; l<max_nonlinear_iterations; ++l) { PAUSE_LOG("solve()", "NewtonSolver"); _system.assembly(true, true); RESTART_LOG("solve()", "NewtonSolver"); rhs.close(); Real current_residual = rhs.l2_norm(); last_residual = current_residual; max_residual_norm = std::max (current_residual, max_residual_norm); // Compute the l2 norm of the whole solution Real norm_total = newton_iterate.l2_norm(); max_solution_norm = std::max(max_solution_norm, norm_total); if (!quiet) std::cout << "Nonlinear Residual: " << current_residual << std::endl; // Make sure our linear tolerance is low enough if (current_linear_tolerance > current_residual * relative_tolerance) { current_linear_tolerance = current_residual * relative_tolerance; } // But don't let it be zero if (current_linear_tolerance == 0.) { current_linear_tolerance = TOLERANCE * TOLERANCE; } // At this point newton_iterate is the current guess, and // solution is now about to become the NEGATIVE of the next // Newton step. // Our best initial guess for the solution is zero! solution.zero(); if (!quiet) std::cout << "Linear solve starting" << std::endl; PAUSE_LOG("solve()", "NewtonSolver"); // Solve the linear system. Two cases: const std::pair<unsigned int, Real> rval = (_system.have_matrix("Preconditioner")) ? // 1.) User-supplied preconditioner linear_solver->solve (matrix, _system.get_matrix("Preconditioner"), solution, rhs, current_linear_tolerance, max_linear_iterations) : // 2.) Use system matrix for the preconditioner linear_solver->solve (matrix, solution, rhs, current_linear_tolerance, max_linear_iterations); // We may need to localize a parallel solution _system.update (); RESTART_LOG("solve()", "NewtonSolver"); if (!quiet) std::cout << "Linear solve finished, step " << rval.first << ", residual " << rval.second << ", tolerance " << current_linear_tolerance << std::endl; // Compute the l2 norm of the nonlinear update Real norm_delta = solution.l2_norm(); if (!quiet) std::cout << "Trying full Newton step" << std::endl; // Take a full Newton step newton_iterate.add (-1., solution); newton_iterate.close(); // Check residual with full Newton step Real steplength = 1.; PAUSE_LOG("solve()", "NewtonSolver"); _system.assembly(true, false); RESTART_LOG("solve()", "NewtonSolver"); rhs.close(); current_residual = rhs.l2_norm(); // backtrack if necessary if (require_residual_reduction) { // but don't fiddle around if we've already converged if (test_convergence(l, current_residual, norm_delta)) break; while (current_residual > last_residual) { // Reduce step size to 1/2, 1/4, etc. steplength /= 2.; norm_delta /= 2.; if (!quiet) std::cout << "Shrinking Newton step to " << steplength << std::endl; newton_iterate.add (steplength, solution); newton_iterate.close(); // Check residual with fractional Newton step PAUSE_LOG("solve()", "NewtonSolver"); _system.assembly (true, false); RESTART_LOG("solve()", "NewtonSolver"); current_residual = rhs.l2_norm(); if (!quiet) std::cout << "Current Residual: " << current_residual << std::endl; if (steplength/2. < minsteplength && current_residual > last_residual) { if (!quiet) std::cout << "Inexact Newton step FAILED at step " << l << std::endl; error(); } } } // Compute the l2 norm of the whole solution norm_total = newton_iterate.l2_norm(); max_solution_norm = std::max(max_solution_norm, norm_total); // Print out information for the // nonlinear iterations. if (!quiet) std::cout << " Nonlinear step: |du|/|u| = " << norm_delta / norm_total << ", |du| = " << norm_delta << std::endl; // Terminate the solution iteration if the difference between // this iteration and the last is sufficiently small. if (test_convergence(l, current_residual, norm_delta / steplength)) { break; } if (l >= max_nonlinear_iterations - 1) { std::cout << " Nonlinear solver DIVERGED at step " << l << " with norm " << norm_total << std::endl; error(); continue; } } // end nonlinear loop // Copy the final nonlinear iterate into the current_solution, // for other libMesh functions that expect it solution = newton_iterate; solution.close(); // We may need to localize a parallel solution _system.update (); STOP_LOG("solve()", "NewtonSolver"); } bool NewtonSolver::test_convergence(unsigned int step_num, Real current_residual, Real step_norm) { // We haven't converged unless we pass a convergence test bool has_converged = false; // Is our absolute residual low enough? if (current_residual < absolute_residual_tolerance) { if (!quiet) std::cout << " Nonlinear solver converged, step " << step_num << ", residual " << current_residual << std::endl; has_converged = true; } else if (absolute_residual_tolerance) { if (!quiet) std::cout << " Nonlinear solver current_residual " << current_residual << " > " << (absolute_residual_tolerance) << std::endl; } // Is our relative residual low enough? if ((current_residual / max_residual_norm) < relative_residual_tolerance) { if (!quiet) std::cout << " Nonlinear solver converged, step " << step_num << ", residual reduction " << current_residual / max_residual_norm << " < " << relative_residual_tolerance << std::endl; has_converged = true; } else if (relative_residual_tolerance) { if (!quiet) std::cout << " Nonlinear solver relative residual " << (current_residual / max_residual_norm) << " > " << relative_residual_tolerance << std::endl; } // Is our absolute Newton step size small enough? if (step_norm < absolute_step_tolerance) { if (!quiet) std::cout << " Nonlinear solver converged, step " << step_num << ", absolute step size " << step_norm << " < " << absolute_step_tolerance << std::endl; has_converged = true; } else if (absolute_step_tolerance) { if (!quiet) std::cout << " Nonlinear solver absolute step size " << step_norm << " > " << absolute_step_tolerance << std::endl; } // Is our relative Newton step size small enough? if (step_norm / max_solution_norm < relative_step_tolerance) { if (!quiet) std::cout << " Nonlinear solver converged, step " << step_num << ", relative step size " << (step_norm / max_solution_norm) << " < " << relative_step_tolerance << std::endl; has_converged = true; } else if (relative_step_tolerance) { if (!quiet) std::cout << " Nonlinear solver relative step size " << (step_norm / max_solution_norm) << " > " << relative_step_tolerance << std::endl; } return has_converged; }
#include "diff_system.h" #include "libmesh_logging.h" #include "linear_solver.h" #include "newton_solver.h" #include "numeric_vector.h" #include "sparse_matrix.h" #include "dof_map.h" NewtonSolver::NewtonSolver (sys_type& s) : Parent(s), require_residual_reduction(false), minsteplength(0.0), linear_solver(LinearSolver<Number>::build()) { } NewtonSolver::~NewtonSolver () { } void NewtonSolver::reinit() { Parent::reinit(); linear_solver->clear(); } void NewtonSolver::solve() { START_LOG("solve()", "NewtonSolver"); // Amount by which nonlinear residual should exceed linear solver // tolerance const Real relative_tolerance = 1.e-3; NumericVector<Number> &solution = *(_system.solution); NumericVector<Number> &newton_iterate = _system.get_vector("_nonlinear_solution"); newton_iterate.close(); NumericVector<Number> &rhs = *(_system.rhs); SparseMatrix<Number> &matrix = *(_system.matrix); // Prepare to take incomplete steps Real last_residual=0.; // Set starting linear tolerance Real current_linear_tolerance = initial_linear_tolerance; // Now we begin the nonlinear loop for (unsigned int l=0; l<max_nonlinear_iterations; ++l) { PAUSE_LOG("solve()", "NewtonSolver"); _system.assembly(true, true); RESTART_LOG("solve()", "NewtonSolver"); rhs.close(); Real current_residual = rhs.l2_norm(); last_residual = current_residual; max_residual_norm = std::max (current_residual, max_residual_norm); // Compute the l2 norm of the whole solution Real norm_total = newton_iterate.l2_norm(); max_solution_norm = std::max(max_solution_norm, norm_total); if (!quiet) std::cout << "Nonlinear Residual: " << current_residual << std::endl; // Make sure our linear tolerance is low enough if (current_linear_tolerance > current_residual * relative_tolerance) { current_linear_tolerance = current_residual * relative_tolerance; } // But don't let it be zero if (current_linear_tolerance == 0.) { current_linear_tolerance = TOLERANCE * TOLERANCE; } // At this point newton_iterate is the current guess, and // solution is now about to become the NEGATIVE of the next // Newton step. // Our best initial guess for the solution is zero! solution.zero(); if (!quiet) std::cout << "Linear solve starting" << std::endl; PAUSE_LOG("solve()", "NewtonSolver"); // Solve the linear system. Two cases: const std::pair<unsigned int, Real> rval = (_system.have_matrix("Preconditioner")) ? // 1.) User-supplied preconditioner linear_solver->solve (matrix, _system.get_matrix("Preconditioner"), solution, rhs, current_linear_tolerance, max_linear_iterations) : // 2.) Use system matrix for the preconditioner linear_solver->solve (matrix, solution, rhs, current_linear_tolerance, max_linear_iterations); // We may need to localize a parallel solution _system.update (); RESTART_LOG("solve()", "NewtonSolver"); // The linear solver may not have fit our constraints exactly _system.get_dof_map().enforce_constraints_exactly(_system); if (!quiet) std::cout << "Linear solve finished, step " << rval.first << ", residual " << rval.second << ", tolerance " << current_linear_tolerance << std::endl; // Compute the l2 norm of the nonlinear update Real norm_delta = solution.l2_norm(); if (!quiet) std::cout << "Trying full Newton step" << std::endl; // Take a full Newton step newton_iterate.add (-1., solution); newton_iterate.close(); // Check residual with full Newton step Real steplength = 1.; PAUSE_LOG("solve()", "NewtonSolver"); _system.assembly(true, false); RESTART_LOG("solve()", "NewtonSolver"); rhs.close(); current_residual = rhs.l2_norm(); // backtrack if necessary if (require_residual_reduction) { // but don't fiddle around if we've already converged if (test_convergence(l, current_residual, norm_delta)) break; while (current_residual > last_residual) { // Reduce step size to 1/2, 1/4, etc. steplength /= 2.; norm_delta /= 2.; if (!quiet) std::cout << "Shrinking Newton step to " << steplength << std::endl; newton_iterate.add (steplength, solution); newton_iterate.close(); // Check residual with fractional Newton step PAUSE_LOG("solve()", "NewtonSolver"); _system.assembly (true, false); RESTART_LOG("solve()", "NewtonSolver"); current_residual = rhs.l2_norm(); if (!quiet) std::cout << "Current Residual: " << current_residual << std::endl; if (steplength/2. < minsteplength && current_residual > last_residual) { if (!quiet) std::cout << "Inexact Newton step FAILED at step " << l << std::endl; error(); } } } // Compute the l2 norm of the whole solution norm_total = newton_iterate.l2_norm(); max_solution_norm = std::max(max_solution_norm, norm_total); // Print out information for the // nonlinear iterations. if (!quiet) std::cout << " Nonlinear step: |du|/|u| = " << norm_delta / norm_total << ", |du| = " << norm_delta << std::endl; // Terminate the solution iteration if the difference between // this iteration and the last is sufficiently small. if (test_convergence(l, current_residual, norm_delta / steplength)) { break; } if (l >= max_nonlinear_iterations - 1) { std::cout << " Nonlinear solver DIVERGED at step " << l << " with norm " << norm_total << std::endl; error(); continue; } } // end nonlinear loop // Copy the final nonlinear iterate into the current_solution, // for other libMesh functions that expect it solution = newton_iterate; solution.close(); // We may need to localize a parallel solution _system.update (); STOP_LOG("solve()", "NewtonSolver"); } bool NewtonSolver::test_convergence(unsigned int step_num, Real current_residual, Real step_norm) { // We haven't converged unless we pass a convergence test bool has_converged = false; // Is our absolute residual low enough? if (current_residual < absolute_residual_tolerance) { if (!quiet) std::cout << " Nonlinear solver converged, step " << step_num << ", residual " << current_residual << std::endl; has_converged = true; } else if (absolute_residual_tolerance) { if (!quiet) std::cout << " Nonlinear solver current_residual " << current_residual << " > " << (absolute_residual_tolerance) << std::endl; } // Is our relative residual low enough? if ((current_residual / max_residual_norm) < relative_residual_tolerance) { if (!quiet) std::cout << " Nonlinear solver converged, step " << step_num << ", residual reduction " << current_residual / max_residual_norm << " < " << relative_residual_tolerance << std::endl; has_converged = true; } else if (relative_residual_tolerance) { if (!quiet) std::cout << " Nonlinear solver relative residual " << (current_residual / max_residual_norm) << " > " << relative_residual_tolerance << std::endl; } // Is our absolute Newton step size small enough? if (step_norm < absolute_step_tolerance) { if (!quiet) std::cout << " Nonlinear solver converged, step " << step_num << ", absolute step size " << step_norm << " < " << absolute_step_tolerance << std::endl; has_converged = true; } else if (absolute_step_tolerance) { if (!quiet) std::cout << " Nonlinear solver absolute step size " << step_norm << " > " << absolute_step_tolerance << std::endl; } // Is our relative Newton step size small enough? if (step_norm / max_solution_norm < relative_step_tolerance) { if (!quiet) std::cout << " Nonlinear solver converged, step " << step_num << ", relative step size " << (step_norm / max_solution_norm) << " < " << relative_step_tolerance << std::endl; has_converged = true; } else if (relative_step_tolerance) { if (!quiet) std::cout << " Nonlinear solver relative step size " << (step_norm / max_solution_norm) << " > " << relative_step_tolerance << std::endl; } return has_converged; }
Make sure newton_iterate is closed before beginning work; use enforce_constraints_exactly() on Newton steps to reduce their "drift"
Make sure newton_iterate is closed before beginning work; use enforce_constraints_exactly() on Newton steps to reduce their "drift" git-svn-id: e88a1e38e13faf406e05cc89eca8dd613216f6c4@1580 434f946d-2f3d-0410-ba4c-cb9f52fb0dbf
C++
lgpl-2.1
benkirk/libmesh,benkirk/libmesh,vikramvgarg/libmesh,vikramvgarg/libmesh,capitalaslash/libmesh,capitalaslash/libmesh,cahaynes/libmesh,hrittich/libmesh,dschwen/libmesh,dschwen/libmesh,dschwen/libmesh,friedmud/libmesh,dmcdougall/libmesh,dschwen/libmesh,benkirk/libmesh,benkirk/libmesh,aeslaughter/libmesh,dknez/libmesh,libMesh/libmesh,cahaynes/libmesh,libMesh/libmesh,libMesh/libmesh,cahaynes/libmesh,coreymbryant/libmesh,benkirk/libmesh,90jrong/libmesh,hrittich/libmesh,vikramvgarg/libmesh,pbauman/libmesh,jwpeterson/libmesh,aeslaughter/libmesh,BalticPinguin/libmesh,balborian/libmesh,90jrong/libmesh,dschwen/libmesh,aeslaughter/libmesh,roystgnr/libmesh,vikramvgarg/libmesh,pbauman/libmesh,dknez/libmesh,svallaghe/libmesh,balborian/libmesh,giorgiobornia/libmesh,friedmud/libmesh,libMesh/libmesh,balborian/libmesh,capitalaslash/libmesh,giorgiobornia/libmesh,coreymbryant/libmesh,coreymbryant/libmesh,svallaghe/libmesh,svallaghe/libmesh,svallaghe/libmesh,benkirk/libmesh,jwpeterson/libmesh,benkirk/libmesh,90jrong/libmesh,dknez/libmesh,friedmud/libmesh,BalticPinguin/libmesh,dmcdougall/libmesh,jwpeterson/libmesh,cahaynes/libmesh,roystgnr/libmesh,capitalaslash/libmesh,dmcdougall/libmesh,cahaynes/libmesh,benkirk/libmesh,hrittich/libmesh,balborian/libmesh,dschwen/libmesh,90jrong/libmesh,BalticPinguin/libmesh,giorgiobornia/libmesh,dschwen/libmesh,coreymbryant/libmesh,giorgiobornia/libmesh,roystgnr/libmesh,vikramvgarg/libmesh,jwpeterson/libmesh,pbauman/libmesh,coreymbryant/libmesh,vikramvgarg/libmesh,vikramvgarg/libmesh,hrittich/libmesh,libMesh/libmesh,balborian/libmesh,roystgnr/libmesh,dknez/libmesh,vikramvgarg/libmesh,hrittich/libmesh,giorgiobornia/libmesh,90jrong/libmesh,aeslaughter/libmesh,friedmud/libmesh,friedmud/libmesh,roystgnr/libmesh,cahaynes/libmesh,aeslaughter/libmesh,capitalaslash/libmesh,coreymbryant/libmesh,hrittich/libmesh,pbauman/libmesh,svallaghe/libmesh,giorgiobornia/libmesh,dknez/libmesh,capitalaslash/libmesh,giorgiobornia/libmesh,90jrong/libmesh,dschwen/libmesh,jwpeterson/libmesh,dmcdougall/libmesh,balborian/libmesh,90jrong/libmesh,aeslaughter/libmesh,BalticPinguin/libmesh,libMesh/libmesh,pbauman/libmesh,capitalaslash/libmesh,pbauman/libmesh,BalticPinguin/libmesh,friedmud/libmesh,coreymbryant/libmesh,friedmud/libmesh,hrittich/libmesh,libMesh/libmesh,dmcdougall/libmesh,aeslaughter/libmesh,balborian/libmesh,dknez/libmesh,roystgnr/libmesh,balborian/libmesh,capitalaslash/libmesh,dmcdougall/libmesh,hrittich/libmesh,benkirk/libmesh,BalticPinguin/libmesh,balborian/libmesh,dknez/libmesh,BalticPinguin/libmesh,BalticPinguin/libmesh,aeslaughter/libmesh,svallaghe/libmesh,vikramvgarg/libmesh,libMesh/libmesh,roystgnr/libmesh,90jrong/libmesh,jwpeterson/libmesh,pbauman/libmesh,dmcdougall/libmesh,cahaynes/libmesh,svallaghe/libmesh,roystgnr/libmesh,dknez/libmesh,giorgiobornia/libmesh,aeslaughter/libmesh,90jrong/libmesh,balborian/libmesh,jwpeterson/libmesh,friedmud/libmesh,pbauman/libmesh,pbauman/libmesh,svallaghe/libmesh,svallaghe/libmesh,friedmud/libmesh,giorgiobornia/libmesh,jwpeterson/libmesh,dmcdougall/libmesh,coreymbryant/libmesh,cahaynes/libmesh,hrittich/libmesh
59fa833881cbca4665dfdebffe1a9f73cb8c41ca
containers/test_queue.cpp
containers/test_queue.cpp
/*************************************************************************** * containers/test_queue.cpp * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2005 Roman Dementiev <[email protected]> * Copyright (C) 2009 Andreas Beckmann <[email protected]> * * 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 <queue> #include <stxxl/queue> typedef unsigned my_type; template <class q1type, class q2type> void check(const q1type & q1, const q2type & q2) { assert(q1.empty() == q2.empty()); assert(q1.size() == q2.size()); if (!q1.empty()) { if (q1.front() != q2.front() || q1.back() != q2.back()) STXXL_MSG(q1.size() << ": (" << q1.front() << ", " << q1.back() << ") (" << q2.front() << ", " << q2.back() << ")" << (q1.front() == q2.front() ? "" : " FRONT")); assert(q1.front() == q2.front()); assert(q1.back() == q2.back()); } } int main() { #if 1 //stxxl::set_seed(424648671); // works fine with a single disk, fails with two disks STXXL_MSG("SEED=" << stxxl::get_next_seed()); stxxl::srandom_number32(stxxl::get_next_seed()); stxxl::random_number32_r rnd; #else //stxxl::ran32State = 1028675152; // fails with two disks STXXL_MSG("ran32State=" << stxxl::ran32State); stxxl::random_number32 rnd; #endif unsigned cnt; STXXL_MSG("Elements in a block: " << stxxl::queue<my_type>::block_type::size); // FIXME: can this be raised to recommended (3, 2) without breaking "Testing special case 4" or any other tests? stxxl::queue<my_type> xqueue(2, 2, -1); std::queue<my_type> squeue; check(xqueue, squeue); STXXL_MSG("Testing special case 4"); cnt = stxxl::queue<my_type>::block_type::size; while (cnt--) { my_type val = rnd(); xqueue.push(val); squeue.push(val); check(xqueue, squeue); } cnt = stxxl::queue<my_type>::block_type::size; while (cnt--) { xqueue.pop(); squeue.pop(); check(xqueue, squeue); } STXXL_MSG("Testing other cases "); cnt = 100 * stxxl::queue<my_type>::block_type::size; while (cnt--) { if ((cnt % 1000000) == 0) STXXL_MSG("Operations left: " << cnt << " queue size " << squeue.size()); int rndtmp = rnd() % 3; if (rndtmp > 0 || squeue.empty()) { my_type val = rnd(); xqueue.push(val); squeue.push(val); check(xqueue, squeue); } else { xqueue.pop(); squeue.pop(); check(xqueue, squeue); } } while (!squeue.empty()) { if ((cnt++ % 1000000) == 0) STXXL_MSG("Operations: " << cnt << " queue size " << squeue.size()); int rndtmp = rnd() % 4; if (rndtmp >= 3) { my_type val = rnd(); xqueue.push(val); squeue.push(val); check(xqueue, squeue); } else { xqueue.pop(); squeue.pop(); check(xqueue, squeue); } } cnt = 10 * stxxl::queue<my_type>::block_type::size; while (cnt--) { if ((cnt % 1000000) == 0) STXXL_MSG("Operations left: " << cnt << " queue size " << squeue.size()); int rndtmp = rnd() % 3; if (rndtmp > 0 || squeue.empty()) { my_type val = rnd(); xqueue.push(val); squeue.push(val); check(xqueue, squeue); } else { xqueue.pop(); squeue.pop(); check(xqueue, squeue); } } typedef stxxl::queue<my_type>::block_type block_type; stxxl::read_write_pool<block_type> pool(5, 5); stxxl::queue<my_type> xqueue1(pool, -1); std::queue<my_type> squeue1; cnt = 10 * stxxl::queue<my_type>::block_type::size; while (cnt--) { if ((cnt % 1000000) == 0) STXXL_MSG("Operations left: " << cnt << " queue size " << squeue1.size()); int rndtmp = rnd() % 3; if (rndtmp > 0 || squeue1.empty()) { my_type val = rnd(); xqueue1.push(val); squeue1.push(val); check(xqueue1, squeue1); } else { xqueue1.pop(); squeue1.pop(); check(xqueue1, squeue1); } } }
/*************************************************************************** * containers/test_queue.cpp * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2005 Roman Dementiev <[email protected]> * Copyright (C) 2009 Andreas Beckmann <[email protected]> * * 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 <queue> #include <stxxl/queue> typedef unsigned my_type; template <class q1type, class q2type> void check(const q1type & q1, const q2type & q2) { assert(q1.empty() == q2.empty()); assert(q1.size() == q2.size()); if (!q1.empty()) { if (q1.front() != q2.front() || q1.back() != q2.back()) STXXL_MSG(q1.size() << ": (" << q1.front() << ", " << q1.back() << ") (" << q2.front() << ", " << q2.back() << ")" << (q1.front() == q2.front() ? "" : " FRONT")); assert(q1.front() == q2.front()); assert(q1.back() == q2.back()); } } int main() { #if 1 //stxxl::set_seed(424648671); // works fine with a single disk, fails with two disks STXXL_MSG("SEED=" << stxxl::get_next_seed()); stxxl::srandom_number32(stxxl::get_next_seed()); stxxl::random_number32_r rnd; #else //stxxl::ran32State = 1028675152; // fails with two disks STXXL_MSG("ran32State=" << stxxl::ran32State); stxxl::random_number32 rnd; #endif unsigned cnt; STXXL_MSG("Elements in a block: " << stxxl::queue<my_type>::block_type::size); // FIXME: can this be raised to recommended (3, 2) without breaking "Testing special case 4" or any other tests? stxxl::queue<my_type> xqueue(2, 2, -1); std::queue<my_type> squeue; check(xqueue, squeue); STXXL_MSG("Testing special case 4"); cnt = stxxl::queue<my_type>::block_type::size; while (cnt--) { my_type val = rnd(); xqueue.push(val); squeue.push(val); check(xqueue, squeue); } cnt = stxxl::queue<my_type>::block_type::size; while (cnt--) { xqueue.pop(); squeue.pop(); check(xqueue, squeue); } STXXL_MSG("Testing other cases "); cnt = 100 * stxxl::queue<my_type>::block_type::size; while (cnt--) { if ((cnt % 1000000) == 0) STXXL_MSG("Operations left: " << cnt << " queue size " << squeue.size()); int rndtmp = rnd() % 3; if (rndtmp > 0 || squeue.empty()) { my_type val = rnd(); xqueue.push(val); squeue.push(val); check(xqueue, squeue); } else { xqueue.pop(); squeue.pop(); check(xqueue, squeue); } } while (!squeue.empty()) { if ((cnt++ % 1000000) == 0) STXXL_MSG("Operations: " << cnt << " queue size " << squeue.size()); int rndtmp = rnd() % 4; if (rndtmp >= 3) { my_type val = rnd(); xqueue.push(val); squeue.push(val); check(xqueue, squeue); } else { xqueue.pop(); squeue.pop(); check(xqueue, squeue); } } cnt = 10 * stxxl::queue<my_type>::block_type::size; while (cnt--) { if ((cnt % 1000000) == 0) STXXL_MSG("Operations left: " << cnt << " queue size " << squeue.size()); int rndtmp = rnd() % 3; if (rndtmp > 0 || squeue.empty()) { my_type val = rnd(); xqueue.push(val); squeue.push(val); check(xqueue, squeue); } else { xqueue.pop(); squeue.pop(); check(xqueue, squeue); } } typedef stxxl::queue<my_type>::block_type block_type; stxxl::read_write_pool<block_type> pool(5, 5); stxxl::queue<my_type> xqueue1(pool, -1); std::queue<my_type> squeue1; cnt = 10 * stxxl::queue<my_type>::block_type::size; while (cnt--) { if ((cnt % 1000000) == 0) STXXL_MSG("Operations left: " << cnt << " queue size " << squeue1.size()); int rndtmp = rnd() % 3; if (rndtmp > 0 || squeue1.empty()) { my_type val = rnd(); xqueue1.push(val); squeue1.push(val); check(xqueue1, squeue1); } else { xqueue1.pop(); squeue1.pop(); check(xqueue1, squeue1); } } { // test proper destruction of a single-block queue stxxl::queue<int> q; q.push(42); } }
add test case for single-block queue destruction
add test case for single-block queue destruction git-svn-id: 4e7379b20b57f8e3dde5a0b7363f233184647162@3202 4e380d45-d1fd-0310-85a7-d18ec86df0ad
C++
mit
sriram-mahavadi/extlp,sriram-mahavadi/extlp,sriram-mahavadi/extlp,sriram-mahavadi/extlp
c565aa4cb2a980fd12d0f9f576cd0cd4c428da63
source/examples/ViewerQt/ExampleWindow.cpp
source/examples/ViewerQt/ExampleWindow.cpp
#include "ExampleWindow.h" #include <gloperate-qt/qt-includes-begin.h> #include <QResizeEvent> #include <gloperate-qt/qt-includes-end.h> #include <glbinding/gl/gl.h> #include <globjects/globjects.h> #include <globjects/DebugMessage.h> ExampleWindow::ExampleWindow() { } ExampleWindow::~ExampleWindow() { } void ExampleWindow::onInitialize() { glo::init(); glo::DebugMessage::enable(); gl::glClearColor(0.2f, 0.3f, 0.4f, 1.f); createAndSetupTexture(); createAndSetupGeometry(); } void ExampleWindow::onResize(QResizeEvent * event) { int width = event->size().width(); int height = event->size().height(); int side = std::min<int>(width, height); gl::glViewport((width - side) / 2, (height - side) / 2, side, side); } void ExampleWindow::onPaint() { gl::glClear(gl::GL_COLOR_BUFFER_BIT | gl::GL_DEPTH_BUFFER_BIT); m_quad->draw(); } void ExampleWindow::createAndSetupTexture() { static const int w(256); static const int h(256); unsigned char data[w * h * 4]; std::random_device rd; std::mt19937 generator(rd()); std::poisson_distribution<> r(0.2); for (int i = 0; i < w * h * 4; ++i) { data[i] = static_cast<unsigned char>(255 - static_cast<unsigned char>(r(generator) * 255)); } m_texture = glo::Texture::createDefault(gl::GL_TEXTURE_2D); m_texture->image2D(0, gl::GL_RGBA8, w, h, 0, gl::GL_RGBA, gl::GL_UNSIGNED_BYTE, data); } void ExampleWindow::createAndSetupGeometry() { m_quad = new gloperate::ScreenAlignedQuad(m_texture); m_quad->setSamplerUniform(0); }
#include "ExampleWindow.h" #include <gloperate-qt/qt-includes-begin.h> #include <QResizeEvent> #include <gloperate-qt/qt-includes-end.h> #include <glbinding/gl/gl.h> #include <globjects/globjects.h> #include <globjects/DebugMessage.h> ExampleWindow::ExampleWindow() { } ExampleWindow::~ExampleWindow() { } void ExampleWindow::onInitialize() { glo::init(); glo::DebugMessage::enable(); gl::glClearColor(0.2f, 0.3f, 0.4f, 1.f); createAndSetupTexture(); createAndSetupGeometry(); } void ExampleWindow::onResize(QResizeEvent * event) { int width = event->size().width(); int height = event->size().height(); gl::glViewport(0, 0, width, height); } void ExampleWindow::onPaint() { gl::glClear(gl::GL_COLOR_BUFFER_BIT | gl::GL_DEPTH_BUFFER_BIT); m_quad->draw(); } void ExampleWindow::createAndSetupTexture() { static const int w(256); static const int h(256); unsigned char data[w * h * 4]; std::random_device rd; std::mt19937 generator(rd()); std::poisson_distribution<> r(0.2); for (int i = 0; i < w * h * 4; ++i) { data[i] = static_cast<unsigned char>(255 - static_cast<unsigned char>(r(generator) * 255)); } m_texture = glo::Texture::createDefault(gl::GL_TEXTURE_2D); m_texture->image2D(0, gl::GL_RGBA8, w, h, 0, gl::GL_RGBA, gl::GL_UNSIGNED_BYTE, data); } void ExampleWindow::createAndSetupGeometry() { m_quad = new gloperate::ScreenAlignedQuad(m_texture); m_quad->setSamplerUniform(0); }
Use entire window as viewport
ViewerQt: Use entire window as viewport
C++
mit
lanice/gloperate,Beta-Alf/gloperate,p-otto/gloperate,cginternals/gloperate,hpicgs/gloperate,Beta-Alf/gloperate,hpi-r2d2/gloperate,j-o/gloperate,p-otto/gloperate,hpicgs/gloperate,j-o/gloperate,j-o/gloperate,j-o/gloperate,hpi-r2d2/gloperate,p-otto/gloperate,lanice/gloperate,lanice/gloperate,lanice/gloperate,hpicgs/gloperate,Beta-Alf/gloperate,p-otto/gloperate,Beta-Alf/gloperate,cginternals/gloperate,Beta-Alf/gloperate,hpicgs/gloperate,lanice/gloperate,cginternals/gloperate,p-otto/gloperate,hpicgs/gloperate,cginternals/gloperate
1e3564803d7b52352bff6c39d4daf01c28192268
src/import/chips/p9/procedures/hwp/memory/p9_mss_ddr_phy_reset.C
src/import/chips/p9/procedures/hwp/memory/p9_mss_ddr_phy_reset.C
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_ddr_phy_reset.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,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 p9_mss_ddr_phy_reset.C /// @brief Reset the DDR PHY /// // *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 <stdint.h> #include <string.h> #include <fapi2.H> #include <mss.H> #include <p9_mss_ddr_phy_reset.H> #include <lib/utils/count_dimm.H> #include <lib/phy/adr32s.H> #include <lib/workarounds/dp16_workarounds.H> #include <lib/fir/check.H> #include <lib/fir/unmask.H> using fapi2::TARGET_TYPE_MCBIST; extern "C" { /// /// @brief Perform a phy reset on all the PHY related to this half-chip (mcbist) /// @param[in] the mcbist representing the PHY /// @return FAPI2_RC_SUCCESS iff OK /// fapi2::ReturnCode p9_mss_ddr_phy_reset(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target) { // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup // attributes for the PHY, etc. if (mss::count_dimm(i_target) == 0) { FAPI_INF("... skipping ddr_phy_reset %s - no DIMM ...", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } FAPI_TRY(mss::change_force_mclk_low(i_target, mss::LOW), "force_mclk_low (set high) Failed rc = 0x%08X", uint64_t(fapi2::current_err) ); // 1. Drive all control signals to the PHY to their inactive state, idle state, or inactive value. FAPI_TRY( mss::dp16::reset_sysclk(i_target) ); // (Note: The chip should already be in this state.) FAPI_DBG("All control signals to the PHYs should be set to their inactive state, idle state, or inactive values"); // 2. Assert reset to PHY for 32 memory clocks FAPI_TRY( mss::change_resetn(i_target, mss::HIGH), "change_resetn for %s failed", mss::c_str(i_target) ); fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32)); // 3. Deassert reset_n FAPI_TRY( mss::change_resetn(i_target, mss::LOW), "change_resetn for %s failed", mss::c_str(i_target) ); // // Flush output drivers // // 8. Set FLUSH=1 and INIT_IO=1 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL and DDRPHY_DP16_DATA_BIT_DIR1 register // 9. Wait at least 32 dphy_gckn clock cycles. // 10. Set FLUSH=0 and INIT_IO=0 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL register FAPI_TRY( mss::flush_output_drivers(i_target), "unable to flush output drivers for %s", mss::c_str(i_target) ); // // ZCTL Enable // // 11. Assert the ZCNTL enable to the internal impedance controller in DDRPHY_PC_RESETS register // 12. Wait at least 1024 dphy_gckn cycles // 13. Deassert the ZCNTL impedance controller enable, Check for DONE in DDRPHY_PC_DLL_ZCAL FAPI_TRY( mss::enable_zctl(i_target), "enable_zctl for %s failed", mss::c_str(i_target) ); // // DLL calibration // // 14. Begin DLL calibrations by setting INIT_RXDLL_CAL_RESET=0 in the DDRPHY_DP16_DLL_CNTL{0:1} registers // and DDRPHY_ADR_DLL_CNTL registers // 15. Monitor the DDRPHY_PC_DLL_ZCAL_CAL_STATUS register to determine when calibration is // complete. One of the 3 bits will be asserted for ADR and DP16. FAPI_INF( "starting DLL calibration %s", mss::c_str(i_target) ); FAPI_TRY( mss::dll_calibration(i_target) ); // // Start bang-bang-lock // // 16. Take dphy_nclk/SysClk alignment circuits out of reset and put into continuous update mode, FAPI_INF("set up of phase rotator controls %s", mss::c_str(i_target) ); FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::ON) ); // 17. Wait at least 5932 dphy_nclk clock cycles to allow the dphy_nclk/SysClk alignment circuit to // perform initial alignment. FAPI_INF("Wait at least 5932 memory clock cycles for clock alignment circuit to perform initial alignment %s", mss::c_str(i_target)); FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 5932), 2000) ); // 18. Check for LOCK in DDRPHY_DP16_SYSCLK_PR_VALUE registers and DDRPHY_ADR_SYSCLK_PR_VALUE FAPI_INF("Checking for bang-bang lock %s ...", mss::c_str(i_target)); FAPI_TRY( mss::check_bang_bang_lock(i_target) ); // 19. Write 0b0 into the DDRPHY_PC_RESETS register bit 1. This write de-asserts the SYSCLK_RESET. FAPI_INF("deassert sysclk reset %s", mss::c_str(i_target)); FAPI_TRY( mss::deassert_sysclk_reset(i_target), "deassert_sysclk_reset failed for %s", mss::c_str(i_target) ); // 20. Write 8020h into the DDRPHY_ADR_SYSCLK_CNTL_PR Registers and // DDRPHY_DP16_SYSCLK_PR0/1 registers This write takes the dphy_nclk/ // SysClk alignment circuit out of the Continuous Update mode. FAPI_INF("take sysclk alignment out of cont update mode %s", mss::c_str(i_target)); FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::OFF), "set up of phase rotator controls failed (out of cont update) %s", mss::c_str(i_target) ); // 21. Wait at least 32 dphy_nclk clock cycles. FAPI_DBG("Wait at least 32 memory clock cycles %s", mss::c_str(i_target)); FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32)) ); // // Done bang-bang-lock // // Per J. Bialas, force_mclk_low can be dasserted. FAPI_TRY(mss::change_force_mclk_low(i_target, mss::HIGH), "force_mclk_low (set low) Failed rc = 0x%08X", uint64_t(fapi2::current_err) ); // Workarounds FAPI_TRY( mss::workarounds::dp16::after_phy_reset(i_target) ); // New for Nimbus - perform duty cycle clock distortion calibration (DCD cal) // Per PHY team's characterization, the DCD cal needs to be run after DLL calibration FAPI_TRY( mss::adr32s::duty_cycle_distortion_calibration(i_target) ); // mss::check::during_phy_reset checks to see if there are any FIR. We do this 'twice' once here // (as part of the good-path) and once if we jump to the fapi_try label. if ((fapi2::current_err = mss::check::during_phy_reset(i_target)) != fapi2::FAPI2_RC_SUCCESS) { goto leave_for_real; } // Unmask the FIR we want unmasked after phy reset is complete. Note this is the "good path." // The algorithm is 'good path do after_phy_reset, all paths (error or not) perform the checks // which are defined in during_phy_reset'. We won't run after_phy_reset (unmask of FIR) unless // we're done with a success. FAPI_TRY( mss::unmask::after_phy_reset(i_target) ); // Leave as we're all good and checked the FIR already ... return fapi2::current_err; // ... here on a bad-path, check FIR and leave ... fapi_try_exit: // mss::check::during_phy_reset handles the error/no error case internally. All we need to do is // return the ReturnCode it hands us - it's taken care of commiting anything it needed to. return mss::check::during_phy_reset(i_target); // ... here if the good-path FIR check found an error. We jumped over the unmasking and are // returning an error to the caller. leave_for_real: return fapi2::current_err; } }
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_ddr_phy_reset.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,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 p9_mss_ddr_phy_reset.C /// @brief Reset the DDR PHY /// // *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 <stdint.h> #include <string.h> #include <fapi2.H> #include <mss.H> #include <p9_mss_ddr_phy_reset.H> #include <lib/utils/count_dimm.H> #include <lib/phy/adr32s.H> #include <lib/workarounds/dp16_workarounds.H> #include <lib/workarounds/dll_workarounds.H> #include <lib/fir/check.H> #include <lib/fir/unmask.H> using fapi2::TARGET_TYPE_MCBIST; extern "C" { /// /// @brief Perform a phy reset on all the PHY related to this half-chip (mcbist) /// @param[in] the mcbist representing the PHY /// @return FAPI2_RC_SUCCESS iff OK /// fapi2::ReturnCode p9_mss_ddr_phy_reset(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target) { // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup // attributes for the PHY, etc. if (mss::count_dimm(i_target) == 0) { FAPI_INF("... skipping ddr_phy_reset %s - no DIMM ...", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } FAPI_TRY(mss::change_force_mclk_low(i_target, mss::LOW), "force_mclk_low (set high) Failed rc = 0x%08X", uint64_t(fapi2::current_err) ); // 1. Drive all control signals to the PHY to their inactive state, idle state, or inactive value. FAPI_TRY( mss::dp16::reset_sysclk(i_target) ); // (Note: The chip should already be in this state.) FAPI_DBG("All control signals to the PHYs should be set to their inactive state, idle state, or inactive values"); // 2. Assert reset to PHY for 32 memory clocks FAPI_TRY( mss::change_resetn(i_target, mss::HIGH), "change_resetn for %s failed", mss::c_str(i_target) ); fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32)); // 3. Deassert reset_n FAPI_TRY( mss::change_resetn(i_target, mss::LOW), "change_resetn for %s failed", mss::c_str(i_target) ); // // Flush output drivers // // 8. Set FLUSH=1 and INIT_IO=1 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL and DDRPHY_DP16_DATA_BIT_DIR1 register // 9. Wait at least 32 dphy_gckn clock cycles. // 10. Set FLUSH=0 and INIT_IO=0 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL register FAPI_TRY( mss::flush_output_drivers(i_target), "unable to flush output drivers for %s", mss::c_str(i_target) ); // // ZCTL Enable // // 11. Assert the ZCNTL enable to the internal impedance controller in DDRPHY_PC_RESETS register // 12. Wait at least 1024 dphy_gckn cycles // 13. Deassert the ZCNTL impedance controller enable, Check for DONE in DDRPHY_PC_DLL_ZCAL FAPI_TRY( mss::enable_zctl(i_target), "enable_zctl for %s failed", mss::c_str(i_target) ); // // DLL calibration // // 14. Begin DLL calibrations by setting INIT_RXDLL_CAL_RESET=0 in the DDRPHY_DP16_DLL_CNTL{0:1} registers // and DDRPHY_ADR_DLL_CNTL registers // 15. Monitor the DDRPHY_PC_DLL_ZCAL_CAL_STATUS register to determine when calibration is // complete. One of the 3 bits will be asserted for ADR and DP16. { FAPI_INF( "starting DLL calibration %s", mss::c_str(i_target) ); fapi2::ReturnCode l_rc = mss::dll_calibration(i_target); // Only run DLL workaround if we fail DLL cal and we are a < DD2.0 part if( l_rc != fapi2::FAPI2_RC_SUCCESS && mss::chip_ec_feature_mss_dll_workaround(i_target) ) { FAPI_INF( "%s Applying DLL workaround", mss::c_str(i_target) ); l_rc = mss::workarounds::dll::fix_bad_voltage_settings(i_target); } FAPI_TRY( l_rc, "Failed DLL calibration" ); } // // Start bang-bang-lock // // 16. Take dphy_nclk/SysClk alignment circuits out of reset and put into continuous update mode, FAPI_INF("set up of phase rotator controls %s", mss::c_str(i_target) ); FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::ON) ); // 17. Wait at least 5932 dphy_nclk clock cycles to allow the dphy_nclk/SysClk alignment circuit to // perform initial alignment. FAPI_INF("Wait at least 5932 memory clock cycles for clock alignment circuit to perform initial alignment %s", mss::c_str(i_target)); FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 5932), 2000) ); // 18. Check for LOCK in DDRPHY_DP16_SYSCLK_PR_VALUE registers and DDRPHY_ADR_SYSCLK_PR_VALUE FAPI_INF("Checking for bang-bang lock %s ...", mss::c_str(i_target)); FAPI_TRY( mss::check_bang_bang_lock(i_target) ); // 19. Write 0b0 into the DDRPHY_PC_RESETS register bit 1. This write de-asserts the SYSCLK_RESET. FAPI_INF("deassert sysclk reset %s", mss::c_str(i_target)); FAPI_TRY( mss::deassert_sysclk_reset(i_target), "deassert_sysclk_reset failed for %s", mss::c_str(i_target) ); // 20. Write 8020h into the DDRPHY_ADR_SYSCLK_CNTL_PR Registers and // DDRPHY_DP16_SYSCLK_PR0/1 registers This write takes the dphy_nclk/ // SysClk alignment circuit out of the Continuous Update mode. FAPI_INF("take sysclk alignment out of cont update mode %s", mss::c_str(i_target)); FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::OFF), "set up of phase rotator controls failed (out of cont update) %s", mss::c_str(i_target) ); // 21. Wait at least 32 dphy_nclk clock cycles. FAPI_DBG("Wait at least 32 memory clock cycles %s", mss::c_str(i_target)); FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32)) ); // // Done bang-bang-lock // // Per J. Bialas, force_mclk_low can be dasserted. FAPI_TRY(mss::change_force_mclk_low(i_target, mss::HIGH), "force_mclk_low (set low) Failed rc = 0x%08X", uint64_t(fapi2::current_err) ); // Workarounds FAPI_TRY( mss::workarounds::dp16::after_phy_reset(i_target) ); // New for Nimbus - perform duty cycle clock distortion calibration (DCD cal) // Per PHY team's characterization, the DCD cal needs to be run after DLL calibration FAPI_TRY( mss::adr32s::duty_cycle_distortion_calibration(i_target) ); // mss::check::during_phy_reset checks to see if there are any FIR. We do this 'twice' once here // (as part of the good-path) and once if we jump to the fapi_try label. if ((fapi2::current_err = mss::check::during_phy_reset(i_target)) != fapi2::FAPI2_RC_SUCCESS) { goto leave_for_real; } // Unmask the FIR we want unmasked after phy reset is complete. Note this is the "good path." // The algorithm is 'good path do after_phy_reset, all paths (error or not) perform the checks // which are defined in during_phy_reset'. We won't run after_phy_reset (unmask of FIR) unless // we're done with a success. FAPI_TRY( mss::unmask::after_phy_reset(i_target) ); // Leave as we're all good and checked the FIR already ... return fapi2::current_err; // ... here on a bad-path, check FIR and leave ... fapi_try_exit: // mss::check::during_phy_reset handles the error/no error case internally. All we need to do is // return the ReturnCode it hands us - it's taken care of commiting anything it needed to. return mss::check::during_phy_reset(i_target); // ... here if the good-path FIR check found an error. We jumped over the unmasking and are // returning an error to the caller. leave_for_real: return fapi2::current_err; } }
Add DLL workaround and unit tests
Add DLL workaround and unit tests Change-Id: I81a3b4ea0350fb794a6c71f268da2766c2eb689e Original-Change-Id: I142ecd417abb92f4f8ec7d3748563b30359c486d Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/39673 Tested-by: Jenkins Server <[email protected]> Reviewed-by: STEPHEN GLANCY <[email protected]> Tested-by: PPE CI <[email protected]> Dev-Ready: ANDRE A. MARIN <[email protected]> Tested-by: Hostboot CI <[email protected]> Reviewed-by: Matt K. Light <[email protected]> Reviewed-by: Thi N. Tran <[email protected]> Reviewed-by: Louis Stermole <[email protected]> Reviewed-by: Jennifer A. Stofer <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
103454e8f03cf543fd1ff01abb5e6a6d827a1fdf
chrome/renderer/module_system.cc
chrome/renderer/module_system.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/module_system.h" #include "base/bind.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebScopedMicrotaskSuppression.h" namespace { const char* kModuleSystem = "module_system"; const char* kModuleName = "module_name"; const char* kModuleField = "module_field"; const char* kModulesField = "modules"; } // namespace ModuleSystem::ModuleSystem(v8::Handle<v8::Context> context, SourceMap* source_map) : context_(v8::Persistent<v8::Context>::New(context)), source_map_(source_map), natives_enabled_(0) { RouteFunction("require", base::Bind(&ModuleSystem::RequireForJs, base::Unretained(this))); RouteFunction("requireNative", base::Bind(&ModuleSystem::GetNative, base::Unretained(this))); v8::Handle<v8::Object> global(context_->Global()); global->SetHiddenValue(v8::String::New(kModulesField), v8::Object::New()); global->SetHiddenValue(v8::String::New(kModuleSystem), v8::External::New(this)); } ModuleSystem::~ModuleSystem() { v8::HandleScope handle_scope; // Deleting this value here prevents future lazy field accesses from // referencing ModuleSystem after it has been freed. context_->Global()->DeleteHiddenValue(v8::String::New(kModuleSystem)); context_.Dispose(); } ModuleSystem::NativesEnabledScope::NativesEnabledScope( ModuleSystem* module_system) : module_system_(module_system) { module_system_->natives_enabled_++; } ModuleSystem::NativesEnabledScope::~NativesEnabledScope() { module_system_->natives_enabled_--; CHECK_GE(module_system_->natives_enabled_, 0); } // static bool ModuleSystem::IsPresentInCurrentContext() { v8::Handle<v8::Object> global(v8::Context::GetCurrent()->Global()); v8::Handle<v8::Value> module_system = global->GetHiddenValue(v8::String::New(kModuleSystem)); return !module_system.IsEmpty() && !module_system->IsUndefined(); } // static void ModuleSystem::DumpException(const v8::TryCatch& try_catch) { v8::Handle<v8::Message> message(try_catch.Message()); if (message.IsEmpty()) { LOG(ERROR) << "try_catch has no message"; return; } std::string resource_name = "<unknown resource>"; if (!message->GetScriptResourceName().IsEmpty()) { resource_name = *v8::String::Utf8Value( message->GetScriptResourceName()->ToString()); } std::string error_message = "<no error message>"; if (!message->Get().IsEmpty()) error_message = *v8::String::Utf8Value(message->Get()); std::string stack_trace = "<stack trace unavailable>"; if (!try_catch.StackTrace().IsEmpty()) stack_trace = *v8::String::Utf8Value(try_catch.StackTrace()); LOG(ERROR) << "[" << resource_name << "(" << message->GetLineNumber() << ")] " << error_message << "{" << stack_trace << "}"; } void ModuleSystem::Require(const std::string& module_name) { v8::HandleScope handle_scope; RequireForJsInner(v8::String::New(module_name.c_str())); } v8::Handle<v8::Value> ModuleSystem::RequireForJs(const v8::Arguments& args) { v8::HandleScope handle_scope; v8::Handle<v8::String> module_name = args[0]->ToString(); return handle_scope.Close(RequireForJsInner(module_name)); } v8::Handle<v8::Value> ModuleSystem::RequireForJsInner( v8::Handle<v8::String> module_name) { v8::HandleScope handle_scope; v8::Handle<v8::Object> global(v8::Context::GetCurrent()->Global()); v8::Handle<v8::Object> modules(v8::Handle<v8::Object>::Cast( global->GetHiddenValue(v8::String::New(kModulesField)))); v8::Handle<v8::Value> exports(modules->Get(module_name)); if (!exports->IsUndefined()) return handle_scope.Close(exports); v8::Handle<v8::Value> source(GetSource(module_name)); if (source->IsUndefined()) return handle_scope.Close(v8::Undefined()); v8::Handle<v8::String> wrapped_source(WrapSource( v8::Handle<v8::String>::Cast(source))); v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(RunString(wrapped_source, module_name)); if (func.IsEmpty()) { return ThrowException(std::string(*v8::String::AsciiValue(module_name)) + ": Bad source"); } exports = v8::Object::New(); v8::Handle<v8::Object> natives(NewInstance()); v8::Handle<v8::Value> args[] = { natives->Get(v8::String::NewSymbol("require")), natives->Get(v8::String::NewSymbol("requireNative")), exports, }; { WebKit::WebScopedMicrotaskSuppression suppression; v8::TryCatch try_catch; try_catch.SetCaptureMessage(true); func->Call(global, 3, args); if (try_catch.HasCaught()) { DumpException(try_catch); return v8::Undefined(); } } modules->Set(module_name, exports); return handle_scope.Close(exports); } void ModuleSystem::RegisterNativeHandler(const std::string& name, scoped_ptr<NativeHandler> native_handler) { native_handler_map_[name] = linked_ptr<NativeHandler>(native_handler.release()); } void ModuleSystem::OverrideNativeHandler(const std::string& name) { overridden_native_handlers_.insert(name); } void ModuleSystem::RunString(const std::string& code, const std::string& name) { v8::HandleScope handle_scope; RunString(v8::String::New(code.c_str()), v8::String::New(name.c_str())); } // static v8::Handle<v8::Value> ModuleSystem::LazyFieldGetter( v8::Local<v8::String> property, const v8::AccessorInfo& info) { CHECK(!info.Data().IsEmpty()); CHECK(info.Data()->IsObject()); v8::HandleScope handle_scope; v8::Handle<v8::Object> parameters = v8::Handle<v8::Object>::Cast(info.Data()); v8::Handle<v8::Object> global(v8::Context::GetCurrent()->Global()); v8::Handle<v8::Value> module_system_value = global->GetHiddenValue(v8::String::New(kModuleSystem)); if (module_system_value->IsUndefined()) { // ModuleSystem has been deleted. return v8::Undefined(); } ModuleSystem* module_system = static_cast<ModuleSystem*>( v8::Handle<v8::External>::Cast(module_system_value)->Value()); v8::Handle<v8::Object> module; { NativesEnabledScope scope(module_system); module = v8::Handle<v8::Object>::Cast(module_system->RequireForJsInner( parameters->Get(v8::String::New(kModuleName))->ToString())); } if (module.IsEmpty()) return handle_scope.Close(v8::Handle<v8::Value>()); v8::Handle<v8::String> field = parameters->Get(v8::String::New(kModuleField))->ToString(); return handle_scope.Close(module->Get(field)); } void ModuleSystem::SetLazyField(v8::Handle<v8::Object> object, const std::string& field, const std::string& module_name, const std::string& module_field) { v8::HandleScope handle_scope; v8::Handle<v8::Object> parameters = v8::Object::New(); parameters->Set(v8::String::New(kModuleName), v8::String::New(module_name.c_str())); parameters->Set(v8::String::New(kModuleField), v8::String::New(module_field.c_str())); object->SetAccessor(v8::String::New(field.c_str()), &ModuleSystem::LazyFieldGetter, NULL, parameters); } v8::Handle<v8::Value> ModuleSystem::RunString(v8::Handle<v8::String> code, v8::Handle<v8::String> name) { v8::HandleScope handle_scope; WebKit::WebScopedMicrotaskSuppression suppression; v8::Handle<v8::Value> result; v8::TryCatch try_catch; try_catch.SetCaptureMessage(true); v8::Handle<v8::Script> script(v8::Script::New(code, name)); if (try_catch.HasCaught()) { DumpException(try_catch); return handle_scope.Close(result); } result = script->Run(); if (try_catch.HasCaught()) DumpException(try_catch); return handle_scope.Close(result); } v8::Handle<v8::Value> ModuleSystem::GetSource( v8::Handle<v8::String> source_name) { v8::HandleScope handle_scope; std::string module_name = *v8::String::AsciiValue(source_name); if (!source_map_->Contains(module_name)) return v8::Undefined(); return handle_scope.Close(source_map_->GetSource(module_name)); } v8::Handle<v8::Value> ModuleSystem::GetNative(const v8::Arguments& args) { CHECK_EQ(1, args.Length()); if (natives_enabled_ == 0) return ThrowException("Natives disabled"); std::string native_name = *v8::String::AsciiValue(args[0]->ToString()); if (overridden_native_handlers_.count(native_name) > 0u) return RequireForJs(args); NativeHandlerMap::iterator i = native_handler_map_.find(native_name); if (i == native_handler_map_.end()) return v8::Undefined(); return i->second->NewInstance(); } v8::Handle<v8::String> ModuleSystem::WrapSource(v8::Handle<v8::String> source) { v8::HandleScope handle_scope; v8::Handle<v8::String> left = v8::String::New("(function(require, requireNative, exports) {"); v8::Handle<v8::String> right = v8::String::New("\n})"); return handle_scope.Close( v8::String::Concat(left, v8::String::Concat(source, right))); } v8::Handle<v8::Value> ModuleSystem::ThrowException(const std::string& message) { return v8::ThrowException(v8::String::New(message.c_str())); }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/module_system.h" #include "base/bind.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebScopedMicrotaskSuppression.h" namespace { const char* kModuleSystem = "module_system"; const char* kModuleName = "module_name"; const char* kModuleField = "module_field"; const char* kModulesField = "modules"; } // namespace ModuleSystem::ModuleSystem(v8::Handle<v8::Context> context, SourceMap* source_map) : context_(v8::Persistent<v8::Context>::New(context)), source_map_(source_map), natives_enabled_(0) { RouteFunction("require", base::Bind(&ModuleSystem::RequireForJs, base::Unretained(this))); RouteFunction("requireNative", base::Bind(&ModuleSystem::GetNative, base::Unretained(this))); v8::Handle<v8::Object> global(context_->Global()); global->SetHiddenValue(v8::String::New(kModulesField), v8::Object::New()); global->SetHiddenValue(v8::String::New(kModuleSystem), v8::External::New(this)); } ModuleSystem::~ModuleSystem() { v8::HandleScope handle_scope; // Deleting this value here prevents future lazy field accesses from // referencing ModuleSystem after it has been freed. context_->Global()->DeleteHiddenValue(v8::String::New(kModuleSystem)); context_.Dispose(); } ModuleSystem::NativesEnabledScope::NativesEnabledScope( ModuleSystem* module_system) : module_system_(module_system) { module_system_->natives_enabled_++; } ModuleSystem::NativesEnabledScope::~NativesEnabledScope() { module_system_->natives_enabled_--; CHECK_GE(module_system_->natives_enabled_, 0); } // static bool ModuleSystem::IsPresentInCurrentContext() { v8::Handle<v8::Object> global(v8::Context::GetCurrent()->Global()); v8::Handle<v8::Value> module_system = global->GetHiddenValue(v8::String::New(kModuleSystem)); return !module_system.IsEmpty() && !module_system->IsUndefined(); } // static void ModuleSystem::DumpException(const v8::TryCatch& try_catch) { v8::Handle<v8::Message> message(try_catch.Message()); if (message.IsEmpty()) { LOG(ERROR) << "try_catch has no message"; return; } std::string resource_name = "<unknown resource>"; if (!message->GetScriptResourceName().IsEmpty()) { resource_name = *v8::String::Utf8Value(message->GetScriptResourceName()->ToString()); } std::string error_message = "<no error message>"; if (!message->Get().IsEmpty()) error_message = *v8::String::Utf8Value(message->Get()); std::string stack_trace = "<stack trace unavailable>"; if (!try_catch.StackTrace().IsEmpty()) stack_trace = *v8::String::Utf8Value(try_catch.StackTrace()); LOG(ERROR) << "[" << resource_name << "(" << message->GetLineNumber() << ")] " << error_message << "{" << stack_trace << "}"; } void ModuleSystem::Require(const std::string& module_name) { v8::HandleScope handle_scope; RequireForJsInner(v8::String::New(module_name.c_str())); } v8::Handle<v8::Value> ModuleSystem::RequireForJs(const v8::Arguments& args) { v8::HandleScope handle_scope; v8::Handle<v8::String> module_name = args[0]->ToString(); return handle_scope.Close(RequireForJsInner(module_name)); } v8::Handle<v8::Value> ModuleSystem::RequireForJsInner( v8::Handle<v8::String> module_name) { v8::HandleScope handle_scope; v8::Handle<v8::Object> global(v8::Context::GetCurrent()->Global()); v8::Handle<v8::Object> modules(v8::Handle<v8::Object>::Cast( global->GetHiddenValue(v8::String::New(kModulesField)))); v8::Handle<v8::Value> exports(modules->Get(module_name)); if (!exports->IsUndefined()) return handle_scope.Close(exports); v8::Handle<v8::Value> source(GetSource(module_name)); if (source->IsUndefined()) return handle_scope.Close(v8::Undefined()); v8::Handle<v8::String> wrapped_source(WrapSource( v8::Handle<v8::String>::Cast(source))); v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(RunString(wrapped_source, module_name)); if (func.IsEmpty()) { return ThrowException(std::string(*v8::String::AsciiValue(module_name)) + ": Bad source"); } exports = v8::Object::New(); v8::Handle<v8::Object> natives(NewInstance()); v8::Handle<v8::Value> args[] = { natives->Get(v8::String::NewSymbol("require")), natives->Get(v8::String::NewSymbol("requireNative")), exports, }; { WebKit::WebScopedMicrotaskSuppression suppression; v8::TryCatch try_catch; try_catch.SetCaptureMessage(true); func->Call(global, 3, args); if (try_catch.HasCaught()) { DumpException(try_catch); return v8::Undefined(); } } modules->Set(module_name, exports); return handle_scope.Close(exports); } void ModuleSystem::RegisterNativeHandler(const std::string& name, scoped_ptr<NativeHandler> native_handler) { native_handler_map_[name] = linked_ptr<NativeHandler>(native_handler.release()); } void ModuleSystem::OverrideNativeHandler(const std::string& name) { overridden_native_handlers_.insert(name); } void ModuleSystem::RunString(const std::string& code, const std::string& name) { v8::HandleScope handle_scope; RunString(v8::String::New(code.c_str()), v8::String::New(name.c_str())); } // static v8::Handle<v8::Value> ModuleSystem::LazyFieldGetter( v8::Local<v8::String> property, const v8::AccessorInfo& info) { CHECK(!info.Data().IsEmpty()); CHECK(info.Data()->IsObject()); v8::HandleScope handle_scope; v8::Handle<v8::Object> parameters = v8::Handle<v8::Object>::Cast(info.Data()); v8::Handle<v8::Object> global(v8::Context::GetCurrent()->Global()); v8::Handle<v8::Value> module_system_value = global->GetHiddenValue(v8::String::New(kModuleSystem)); if (module_system_value->IsUndefined()) { // ModuleSystem has been deleted. return v8::Undefined(); } ModuleSystem* module_system = static_cast<ModuleSystem*>( v8::Handle<v8::External>::Cast(module_system_value)->Value()); v8::Handle<v8::Object> module; { NativesEnabledScope scope(module_system); module = v8::Handle<v8::Object>::Cast(module_system->RequireForJsInner( parameters->Get(v8::String::New(kModuleName))->ToString())); } if (module.IsEmpty()) return handle_scope.Close(v8::Handle<v8::Value>()); v8::Handle<v8::String> field = parameters->Get(v8::String::New(kModuleField))->ToString(); return handle_scope.Close(module->Get(field)); } void ModuleSystem::SetLazyField(v8::Handle<v8::Object> object, const std::string& field, const std::string& module_name, const std::string& module_field) { v8::HandleScope handle_scope; v8::Handle<v8::Object> parameters = v8::Object::New(); parameters->Set(v8::String::New(kModuleName), v8::String::New(module_name.c_str())); parameters->Set(v8::String::New(kModuleField), v8::String::New(module_field.c_str())); object->SetAccessor(v8::String::New(field.c_str()), &ModuleSystem::LazyFieldGetter, NULL, parameters); } v8::Handle<v8::Value> ModuleSystem::RunString(v8::Handle<v8::String> code, v8::Handle<v8::String> name) { v8::HandleScope handle_scope; WebKit::WebScopedMicrotaskSuppression suppression; v8::Handle<v8::Value> result; v8::TryCatch try_catch; try_catch.SetCaptureMessage(true); v8::Handle<v8::Script> script(v8::Script::New(code, name)); if (try_catch.HasCaught()) { DumpException(try_catch); return handle_scope.Close(result); } result = script->Run(); if (try_catch.HasCaught()) DumpException(try_catch); return handle_scope.Close(result); } v8::Handle<v8::Value> ModuleSystem::GetSource( v8::Handle<v8::String> source_name) { v8::HandleScope handle_scope; std::string module_name = *v8::String::AsciiValue(source_name); if (!source_map_->Contains(module_name)) return v8::Undefined(); return handle_scope.Close(source_map_->GetSource(module_name)); } v8::Handle<v8::Value> ModuleSystem::GetNative(const v8::Arguments& args) { CHECK_EQ(1, args.Length()); if (natives_enabled_ == 0) return ThrowException("Natives disabled"); std::string native_name = *v8::String::AsciiValue(args[0]->ToString()); if (overridden_native_handlers_.count(native_name) > 0u) return RequireForJs(args); NativeHandlerMap::iterator i = native_handler_map_.find(native_name); if (i == native_handler_map_.end()) return v8::Undefined(); return i->second->NewInstance(); } v8::Handle<v8::String> ModuleSystem::WrapSource(v8::Handle<v8::String> source) { v8::HandleScope handle_scope; v8::Handle<v8::String> left = v8::String::New("(function(require, requireNative, exports) {"); v8::Handle<v8::String> right = v8::String::New("\n})"); return handle_scope.Close( v8::String::Concat(left, v8::String::Concat(source, right))); } v8::Handle<v8::Value> ModuleSystem::ThrowException(const std::string& message) { return v8::ThrowException(v8::String::New(message.c_str())); }
Fix weird indenting in ModuleSystem::DumpException().
Fix weird indenting in ModuleSystem::DumpException(). [email protected] Review URL: https://chromiumcodereview.appspot.com/10883050 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@153445 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
jaruba/chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,dushu1203/chromium.src,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,ltilve/chromium,fujunwei/chromium-crosswalk,Chilledheart/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,markYoungH/chromium.src,ChromiumWebApps/chromium,ltilve/chromium,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,ltilve/chromium,dushu1203/chromium.src,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,dushu1203/chromium.src,littlstar/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,M4sse/chromium.src,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,ltilve/chromium,markYoungH/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,hujiajie/pa-chromium,markYoungH/chromium.src,mogoweb/chromium-crosswalk,markYoungH/chromium.src,littlstar/chromium.src,jaruba/chromium.src,anirudhSK/chromium,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,nacl-webkit/chrome_deps,Jonekee/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,dushu1203/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,anirudhSK/chromium,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,Just-D/chromium-1,jaruba/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,littlstar/chromium.src,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ltilve/chromium,hgl888/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,ltilve/chromium,ondra-novak/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,nacl-webkit/chrome_deps,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,ltilve/chromium,ChromiumWebApps/chromium,dednal/chromium.src,M4sse/chromium.src,littlstar/chromium.src,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,anirudhSK/chromium,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,patrickm/chromium.src,bright-sparks/chromium-spacewalk,anirudhSK/chromium,patrickm/chromium.src,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,littlstar/chromium.src,jaruba/chromium.src,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,Chilledheart/chromium,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,anirudhSK/chromium,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,zcbenz/cefode-chromium,patrickm/chromium.src,Just-D/chromium-1,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,patrickm/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk,dednal/chromium.src,ltilve/chromium,dushu1203/chromium.src,patrickm/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,timopulkkinen/BubbleFish,anirudhSK/chromium,Fireblend/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,dednal/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,patrickm/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,hujiajie/pa-chromium,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,markYoungH/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,M4sse/chromium.src,zcbenz/cefode-chromium,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,chuan9/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src
14b0a497292b97f4fb6c1588914769d58e053fbd
chrome/renderer/renderer_main.cc
chrome/renderer/renderer_main.cc
// 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. #if defined(OS_MACOSX) #include <signal.h> #include <unistd.h> #endif // OS_MACOSX #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/i18n/rtl.h" #include "base/mac/scoped_nsautorelease_pool.h" #include "base/metrics/field_trial.h" #include "base/message_loop.h" #include "base/metrics/histogram.h" #include "base/metrics/stats_counters.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/ref_counted.h" #include "base/string_util.h" #include "base/threading/platform_thread.h" #include "base/time.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_counters.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/gfx_resource_provider.h" #include "chrome/common/logging_chrome.h" #include "chrome/common/net/net_resource_provider.h" #include "chrome/common/pepper_plugin_registry.h" #include "chrome/renderer/renderer_main_platform_delegate.h" #include "chrome/renderer/render_process_impl.h" #include "chrome/renderer/render_thread.h" #include "content/common/main_function_params.h" #include "content/common/hi_res_timer_manager.h" #include "grit/generated_resources.h" #include "net/base/net_module.h" #include "ui/base/system_monitor/system_monitor.h" #include "ui/base/ui_base_switches.h" #include "ui/gfx/gfx_module.h" #if defined(OS_MACOSX) #include "base/eintr_wrapper.h" #include "chrome/app/breakpad_mac.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" #endif // OS_MACOSX #if defined(OS_MACOSX) namespace { // TODO(viettrungluu): crbug.com/28547: The following signal handling is needed, // as a stopgap, to avoid leaking due to not releasing Breakpad properly. // Without this problem, this could all be eliminated. Remove when Breakpad is // fixed? // TODO(viettrungluu): Code taken from browser_main.cc (with a bit of editing). // The code should be properly shared (or this code should be eliminated). int g_shutdown_pipe_write_fd = -1; void SIGTERMHandler(int signal) { RAW_CHECK(signal == SIGTERM); RAW_LOG(INFO, "Handling SIGTERM in renderer."); // Reinstall the default handler. We had one shot at graceful shutdown. struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIG_DFL; CHECK(sigaction(signal, &action, NULL) == 0); RAW_CHECK(g_shutdown_pipe_write_fd != -1); size_t bytes_written = 0; do { int rv = HANDLE_EINTR( write(g_shutdown_pipe_write_fd, reinterpret_cast<const char*>(&signal) + bytes_written, sizeof(signal) - bytes_written)); RAW_CHECK(rv >= 0); bytes_written += rv; } while (bytes_written < sizeof(signal)); RAW_LOG(INFO, "Wrote signal to shutdown pipe."); } class ShutdownDetector : public base::PlatformThread::Delegate { public: explicit ShutdownDetector(int shutdown_fd) : shutdown_fd_(shutdown_fd) { CHECK(shutdown_fd_ != -1); } virtual void ThreadMain() { int signal; size_t bytes_read = 0; ssize_t ret; do { ret = HANDLE_EINTR( read(shutdown_fd_, reinterpret_cast<char*>(&signal) + bytes_read, sizeof(signal) - bytes_read)); if (ret < 0) { NOTREACHED() << "Unexpected error: " << strerror(errno); break; } else if (ret == 0) { NOTREACHED() << "Unexpected closure of shutdown pipe."; break; } bytes_read += ret; } while (bytes_read < sizeof(signal)); if (bytes_read == sizeof(signal)) VLOG(1) << "Handling shutdown for signal " << signal << "."; else VLOG(1) << "Handling shutdown for unknown signal."; // Clean up Breakpad if necessary. if (IsCrashReporterEnabled()) { VLOG(1) << "Cleaning up Breakpad."; DestructCrashReporter(); } else { VLOG(1) << "Breakpad not enabled; no clean-up needed."; } // Something went seriously wrong, so get out. if (bytes_read != sizeof(signal)) { LOG(WARNING) << "Failed to get signal. Quitting ungracefully."; _exit(1); } // Re-raise the signal. kill(getpid(), signal); // The signal may be handled on another thread. Give that a chance to // happen. sleep(3); // We really should be dead by now. For whatever reason, we're not. Exit // immediately, with the exit status set to the signal number with bit 8 // set. On the systems that we care about, this exit status is what is // normally used to indicate an exit by this signal's default handler. // This mechanism isn't a de jure standard, but even in the worst case, it // should at least result in an immediate exit. LOG(WARNING) << "Still here, exiting really ungracefully."; _exit(signal | (1 << 7)); } private: const int shutdown_fd_; DISALLOW_COPY_AND_ASSIGN(ShutdownDetector); }; } // namespace #endif // OS_MACOSX // This function provides some ways to test crash and assertion handling // behavior of the renderer. static void HandleRendererErrorTestParameters(const CommandLine& command_line) { // This parameter causes an assertion. if (command_line.HasSwitch(switches::kRendererAssertTest)) { DCHECK(false); } #if !defined(OFFICIAL_BUILD) // This parameter causes an assertion too. if (command_line.HasSwitch(switches::kRendererCheckFalseTest)) { CHECK(false); } #endif // !defined(OFFICIAL_BUILD) // This parameter causes a null pointer crash (crash reporter trigger). if (command_line.HasSwitch(switches::kRendererCrashTest)) { int* bad_pointer = NULL; *bad_pointer = 0; } if (command_line.HasSwitch(switches::kRendererStartupDialog)) { ChildProcess::WaitForDebugger("Renderer"); } } // This is a simplified version of the browser Jankometer, which measures // the processing time of tasks on the render thread. class RendererMessageLoopObserver : public MessageLoop::TaskObserver { public: RendererMessageLoopObserver() : process_times_(base::Histogram::FactoryGet( "Chrome.ProcMsgL RenderThread", 1, 3600000, 50, base::Histogram::kUmaTargetedHistogramFlag)) {} virtual ~RendererMessageLoopObserver() {} virtual void WillProcessTask(const Task* task) { begin_process_message_ = base::TimeTicks::Now(); } virtual void DidProcessTask(const Task* task) { if (begin_process_message_ != base::TimeTicks()) process_times_->AddTime(base::TimeTicks::Now() - begin_process_message_); } private: base::TimeTicks begin_process_message_; scoped_refptr<base::Histogram> process_times_; DISALLOW_COPY_AND_ASSIGN(RendererMessageLoopObserver); }; // mainline routine for running as the Renderer process int RendererMain(const MainFunctionParams& parameters) { TRACE_EVENT_BEGIN("RendererMain", 0, ""); const CommandLine& parsed_command_line = parameters.command_line_; base::mac::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool_; #if defined(OS_MACOSX) // TODO(viettrungluu): Code taken from browser_main.cc. int pipefd[2]; int ret = pipe(pipefd); if (ret < 0) { PLOG(DFATAL) << "Failed to create pipe"; } else { int shutdown_pipe_read_fd = pipefd[0]; g_shutdown_pipe_write_fd = pipefd[1]; const size_t kShutdownDetectorThreadStackSize = 4096; if (!base::PlatformThread::CreateNonJoinable( kShutdownDetectorThreadStackSize, new ShutdownDetector(shutdown_pipe_read_fd))) { LOG(DFATAL) << "Failed to create shutdown detector task."; } } // crbug.com/28547: When Breakpad is in use, handle SIGTERM to avoid leaking // Mach ports. struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIGTERMHandler; CHECK(sigaction(SIGTERM, &action, NULL) == 0); #endif // OS_MACOSX #if defined(OS_CHROMEOS) // As Zygote process starts up earlier than browser process gets its own // locale (at login time for Chrome OS), we have to set the ICU default // locale for renderer process here. // ICU locale will be used for fallback font selection etc. if (parsed_command_line.HasSwitch(switches::kLang)) { const std::string locale = parsed_command_line.GetSwitchValueASCII(switches::kLang); base::i18n::SetICUDefaultLocale(locale); } #endif // Configure modules that need access to resources. net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider); gfx::GfxModule::SetResourceProvider(chrome::GfxResourceProvider); // This function allows pausing execution using the --renderer-startup-dialog // flag allowing us to attach a debugger. // Do not move this function down since that would mean we can't easily debug // whatever occurs before it. HandleRendererErrorTestParameters(parsed_command_line); RendererMainPlatformDelegate platform(parameters); base::StatsScope<base::StatsCounterTimer> startup_timer(chrome::Counters::renderer_main()); RendererMessageLoopObserver task_observer; #if defined(OS_MACOSX) // As long as we use Cocoa in the renderer (for the forseeable future as of // now; see http://crbug.com/13890 for info) we need to have a UI loop. MessageLoop main_message_loop(MessageLoop::TYPE_UI); #else // The main message loop of the renderer services doesn't have IO or UI tasks, // unless in-process-plugins is used. MessageLoop main_message_loop(RenderProcessImpl::InProcessPlugins() ? MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT); #endif main_message_loop.AddTaskObserver(&task_observer); base::PlatformThread::SetName("CrRendererMain"); ui::SystemMonitor system_monitor; HighResolutionTimerManager hi_res_timer_manager; platform.PlatformInitialize(); bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox); platform.InitSandboxTests(no_sandbox); // Initialize histogram statistics gathering system. // Don't create StatisticsRecorder in the single process mode. scoped_ptr<base::StatisticsRecorder> statistics; if (!base::StatisticsRecorder::IsActive()) { statistics.reset(new base::StatisticsRecorder()); } // Initialize statistical testing infrastructure. base::FieldTrialList field_trial; // Ensure any field trials in browser are reflected into renderer. if (parsed_command_line.HasSwitch(switches::kForceFieldTestNameAndValue)) { std::string persistent = parsed_command_line.GetSwitchValueASCII( switches::kForceFieldTestNameAndValue); bool ret = field_trial.CreateTrialsInChildProcess(persistent); DCHECK(ret); } // Load pepper plugins before engaging the sandbox. PepperPluginRegistry::GetInstance(); { #if !defined(OS_LINUX) // TODO(markus): Check if it is OK to unconditionally move this // instruction down. RenderProcessImpl render_process; render_process.set_main_thread(new RenderThread()); #endif bool run_loop = true; if (!no_sandbox) { run_loop = platform.EnableSandbox(); } else { LOG(ERROR) << "Running without renderer sandbox"; } #if defined(OS_LINUX) RenderProcessImpl render_process; render_process.set_main_thread(new RenderThread()); #endif platform.RunSandboxTests(); startup_timer.Stop(); // End of Startup Time Measurement. if (run_loop) { if (pool) pool->Recycle(); TRACE_EVENT_BEGIN("RendererMain.START_MSG_LOOP", 0, 0); MessageLoop::current()->Run(); TRACE_EVENT_END("RendererMain.START_MSG_LOOP", 0, 0); } } platform.PlatformUninitialize(); TRACE_EVENT_END("RendererMain", 0, ""); return 0; }
// 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. #if defined(OS_MACOSX) #include <signal.h> #include <unistd.h> #endif // OS_MACOSX #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/i18n/rtl.h" #include "base/mac/scoped_nsautorelease_pool.h" #include "base/metrics/field_trial.h" #include "base/message_loop.h" #include "base/metrics/histogram.h" #include "base/metrics/stats_counters.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/string_util.h" #include "base/threading/platform_thread.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_counters.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/gfx_resource_provider.h" #include "chrome/common/logging_chrome.h" #include "chrome/common/net/net_resource_provider.h" #include "chrome/common/pepper_plugin_registry.h" #include "chrome/renderer/renderer_main_platform_delegate.h" #include "chrome/renderer/render_process_impl.h" #include "chrome/renderer/render_thread.h" #include "content/common/main_function_params.h" #include "content/common/hi_res_timer_manager.h" #include "grit/generated_resources.h" #include "net/base/net_module.h" #include "ui/base/system_monitor/system_monitor.h" #include "ui/base/ui_base_switches.h" #include "ui/gfx/gfx_module.h" #if defined(OS_MACOSX) #include "base/eintr_wrapper.h" #include "chrome/app/breakpad_mac.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h" #endif // OS_MACOSX #if defined(OS_MACOSX) namespace { // TODO(viettrungluu): crbug.com/28547: The following signal handling is needed, // as a stopgap, to avoid leaking due to not releasing Breakpad properly. // Without this problem, this could all be eliminated. Remove when Breakpad is // fixed? // TODO(viettrungluu): Code taken from browser_main.cc (with a bit of editing). // The code should be properly shared (or this code should be eliminated). int g_shutdown_pipe_write_fd = -1; void SIGTERMHandler(int signal) { RAW_CHECK(signal == SIGTERM); RAW_LOG(INFO, "Handling SIGTERM in renderer."); // Reinstall the default handler. We had one shot at graceful shutdown. struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIG_DFL; CHECK(sigaction(signal, &action, NULL) == 0); RAW_CHECK(g_shutdown_pipe_write_fd != -1); size_t bytes_written = 0; do { int rv = HANDLE_EINTR( write(g_shutdown_pipe_write_fd, reinterpret_cast<const char*>(&signal) + bytes_written, sizeof(signal) - bytes_written)); RAW_CHECK(rv >= 0); bytes_written += rv; } while (bytes_written < sizeof(signal)); RAW_LOG(INFO, "Wrote signal to shutdown pipe."); } class ShutdownDetector : public base::PlatformThread::Delegate { public: explicit ShutdownDetector(int shutdown_fd) : shutdown_fd_(shutdown_fd) { CHECK(shutdown_fd_ != -1); } virtual void ThreadMain() { int signal; size_t bytes_read = 0; ssize_t ret; do { ret = HANDLE_EINTR( read(shutdown_fd_, reinterpret_cast<char*>(&signal) + bytes_read, sizeof(signal) - bytes_read)); if (ret < 0) { NOTREACHED() << "Unexpected error: " << strerror(errno); break; } else if (ret == 0) { NOTREACHED() << "Unexpected closure of shutdown pipe."; break; } bytes_read += ret; } while (bytes_read < sizeof(signal)); if (bytes_read == sizeof(signal)) VLOG(1) << "Handling shutdown for signal " << signal << "."; else VLOG(1) << "Handling shutdown for unknown signal."; // Clean up Breakpad if necessary. if (IsCrashReporterEnabled()) { VLOG(1) << "Cleaning up Breakpad."; DestructCrashReporter(); } else { VLOG(1) << "Breakpad not enabled; no clean-up needed."; } // Something went seriously wrong, so get out. if (bytes_read != sizeof(signal)) { LOG(WARNING) << "Failed to get signal. Quitting ungracefully."; _exit(1); } // Re-raise the signal. kill(getpid(), signal); // The signal may be handled on another thread. Give that a chance to // happen. sleep(3); // We really should be dead by now. For whatever reason, we're not. Exit // immediately, with the exit status set to the signal number with bit 8 // set. On the systems that we care about, this exit status is what is // normally used to indicate an exit by this signal's default handler. // This mechanism isn't a de jure standard, but even in the worst case, it // should at least result in an immediate exit. LOG(WARNING) << "Still here, exiting really ungracefully."; _exit(signal | (1 << 7)); } private: const int shutdown_fd_; DISALLOW_COPY_AND_ASSIGN(ShutdownDetector); }; } // namespace #endif // OS_MACOSX // This function provides some ways to test crash and assertion handling // behavior of the renderer. static void HandleRendererErrorTestParameters(const CommandLine& command_line) { // This parameter causes an assertion. if (command_line.HasSwitch(switches::kRendererAssertTest)) { DCHECK(false); } #if !defined(OFFICIAL_BUILD) // This parameter causes an assertion too. if (command_line.HasSwitch(switches::kRendererCheckFalseTest)) { CHECK(false); } #endif // !defined(OFFICIAL_BUILD) // This parameter causes a null pointer crash (crash reporter trigger). if (command_line.HasSwitch(switches::kRendererCrashTest)) { int* bad_pointer = NULL; *bad_pointer = 0; } if (command_line.HasSwitch(switches::kRendererStartupDialog)) { ChildProcess::WaitForDebugger("Renderer"); } } // mainline routine for running as the Renderer process int RendererMain(const MainFunctionParams& parameters) { TRACE_EVENT_BEGIN("RendererMain", 0, ""); const CommandLine& parsed_command_line = parameters.command_line_; base::mac::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool_; #if defined(OS_MACOSX) // TODO(viettrungluu): Code taken from browser_main.cc. int pipefd[2]; int ret = pipe(pipefd); if (ret < 0) { PLOG(DFATAL) << "Failed to create pipe"; } else { int shutdown_pipe_read_fd = pipefd[0]; g_shutdown_pipe_write_fd = pipefd[1]; const size_t kShutdownDetectorThreadStackSize = 4096; if (!base::PlatformThread::CreateNonJoinable( kShutdownDetectorThreadStackSize, new ShutdownDetector(shutdown_pipe_read_fd))) { LOG(DFATAL) << "Failed to create shutdown detector task."; } } // crbug.com/28547: When Breakpad is in use, handle SIGTERM to avoid leaking // Mach ports. struct sigaction action; memset(&action, 0, sizeof(action)); action.sa_handler = SIGTERMHandler; CHECK(sigaction(SIGTERM, &action, NULL) == 0); #endif // OS_MACOSX #if defined(OS_CHROMEOS) // As Zygote process starts up earlier than browser process gets its own // locale (at login time for Chrome OS), we have to set the ICU default // locale for renderer process here. // ICU locale will be used for fallback font selection etc. if (parsed_command_line.HasSwitch(switches::kLang)) { const std::string locale = parsed_command_line.GetSwitchValueASCII(switches::kLang); base::i18n::SetICUDefaultLocale(locale); } #endif // Configure modules that need access to resources. net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider); gfx::GfxModule::SetResourceProvider(chrome::GfxResourceProvider); // This function allows pausing execution using the --renderer-startup-dialog // flag allowing us to attach a debugger. // Do not move this function down since that would mean we can't easily debug // whatever occurs before it. HandleRendererErrorTestParameters(parsed_command_line); RendererMainPlatformDelegate platform(parameters); base::StatsScope<base::StatsCounterTimer> startup_timer(chrome::Counters::renderer_main()); #if defined(OS_MACOSX) // As long as we use Cocoa in the renderer (for the forseeable future as of // now; see http://crbug.com/13890 for info) we need to have a UI loop. MessageLoop main_message_loop(MessageLoop::TYPE_UI); #else // The main message loop of the renderer services doesn't have IO or UI tasks, // unless in-process-plugins is used. MessageLoop main_message_loop(RenderProcessImpl::InProcessPlugins() ? MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT); #endif base::PlatformThread::SetName("CrRendererMain"); ui::SystemMonitor system_monitor; HighResolutionTimerManager hi_res_timer_manager; platform.PlatformInitialize(); bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox); platform.InitSandboxTests(no_sandbox); // Initialize histogram statistics gathering system. // Don't create StatisticsRecorder in the single process mode. scoped_ptr<base::StatisticsRecorder> statistics; if (!base::StatisticsRecorder::IsActive()) { statistics.reset(new base::StatisticsRecorder()); } // Initialize statistical testing infrastructure. base::FieldTrialList field_trial; // Ensure any field trials in browser are reflected into renderer. if (parsed_command_line.HasSwitch(switches::kForceFieldTestNameAndValue)) { std::string persistent = parsed_command_line.GetSwitchValueASCII( switches::kForceFieldTestNameAndValue); bool ret = field_trial.CreateTrialsInChildProcess(persistent); DCHECK(ret); } // Load pepper plugins before engaging the sandbox. PepperPluginRegistry::GetInstance(); { #if !defined(OS_LINUX) // TODO(markus): Check if it is OK to unconditionally move this // instruction down. RenderProcessImpl render_process; render_process.set_main_thread(new RenderThread()); #endif bool run_loop = true; if (!no_sandbox) { run_loop = platform.EnableSandbox(); } else { LOG(ERROR) << "Running without renderer sandbox"; } #if defined(OS_LINUX) RenderProcessImpl render_process; render_process.set_main_thread(new RenderThread()); #endif platform.RunSandboxTests(); startup_timer.Stop(); // End of Startup Time Measurement. if (run_loop) { if (pool) pool->Recycle(); TRACE_EVENT_BEGIN("RendererMain.START_MSG_LOOP", 0, 0); MessageLoop::current()->Run(); TRACE_EVENT_END("RendererMain.START_MSG_LOOP", 0, 0); } } platform.PlatformUninitialize(); TRACE_EVENT_END("RendererMain", 0, ""); return 0; }
Revert 78517 - Add a histogram to measure task execution time for the render thread.
Revert 78517 - Add a histogram to measure task execution time for the render thread. BUG=none TEST=none Committed: http://src.chromium.org/viewvc/chrome?view=rev&revision=78511 Review URL: http://codereview.chromium.org/6670029 [email protected] Review URL: http://codereview.chromium.org/6677107 git-svn-id: http://src.chromium.org/svn/trunk/src@78522 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 972c93a6cfecc1cd5c0e1053186b4fd2487771aa
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
11f11d93dc1408ed3e3a575fdcc1fff975084437
test/merge.cpp
test/merge.cpp
#include <gtest/gtest.h> #include <c4/yml/std/std.hpp> #include <c4/yml/yml.hpp> #include <initializer_list> #include <string> #include <iostream> namespace c4 { namespace yml { void test_merge(std::initializer_list<csubstr> li, csubstr expected) { Tree loaded, merged, ref; parse(expected, &ref); // make sure the arena in the loaded tree is never resized size_t arena_dim = 2; for(csubstr src : li) { arena_dim += src.len; } loaded.reserve_arena(arena_dim); for(csubstr src : li) { loaded.clear(); // do not clear the arena of the loaded tree parse(src, &loaded); merged.merge_with(&loaded); } auto buf_result = emitrs<std::string>(merged); auto buf_expected = emitrs<std::string>(ref); EXPECT_EQ(buf_result, buf_expected); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(merge, seq_no_overlap_explicit) { test_merge( {"[0, 1, 2]", "[3, 4, 5]", "[6, 7, 8]"}, "[0, 1, 2, 3, 4, 5, 6, 7, 8]" ); } TEST(merge, seq_no_overlap_implicit) { test_merge( {"0, 1, 2", "3, 4, 5", "6, 7, 8"}, "0, 1, 2, 3, 4, 5, 6, 7, 8" ); } TEST(merge, seq_overlap_explicit) { test_merge( {"[0, 1, 2]", "[1, 2, 3]", "[2, 3, 4]"}, "[0, 1, 2, 1, 2, 3, 2, 3, 4]" // or this? "[0, 1, 2, 3, 4]" ); } TEST(merge, seq_overlap_implicit) { // now a bit more difficult test_merge( {"0, 1, 2", "1, 2, 3", "2, 3, 4"}, "0, 1, 2, 1, 2, 3, 2, 3, 4" // or this? "0, 1, 2, 3, 4" ); } TEST(merge, map_orthogonal) { test_merge( {"a: 0", "b: 1", "c: 2"}, "{a: 0, b: 1, c: 2}" ); } TEST(merge, map_overriding) { test_merge( { "a: 0", "{a: 1, b: 1}", "c: 2" }, "{a: 1, b: 1, c: 2}" ); } TEST(merge, map_overriding_multiple) { test_merge( { "a: 0", "{a: 1, b: 1}", "c: 2", "a: 2", "a: 3", "c: 4", "c: 5", "a: 4", }, "{a: 4, b: 1, c: 5}" ); } TEST(merge, seq_nested_in_map) { test_merge( { "{a: 0, seq: [a, b, c], d: 2}", "{a: 1, seq: [d, e, f], d: 3, c: 3}" }, "{a: 1, seq: [a, b, c, d, e, f], d: 3, c: 3}" ); } TEST(merge, seq_nested_in_map_override_with_map) { test_merge( { "{a: 0, ovr: [a, b, c], d: 2}", "{a: 1, ovr: {d: 0, b: 1, c: 2}, d: 3, c: 3}" }, "{a: 1, ovr: {d: 0, b: 1, c: 2}, d: 3, c: 3}" ); } TEST(merge, seq_nested_in_map_override_with_keyval) { test_merge( { "{a: 0, ovr: [a, b, c], d: 2}", "{a: 1, ovr: foo, d: 3, c: 3}" }, "{a: 1, ovr: foo, d: 3, c: 3}" ); } } // namespace yml } // namespace c4
#include <gtest/gtest.h> #include <c4/yml/std/std.hpp> #include <c4/yml/yml.hpp> #include <initializer_list> #include <string> #include <iostream> #include "./test_case.hpp" namespace c4 { namespace yml { // The other test executables are written to contain the declarative-style // YmlTestCases. This executable does not have any but the build setup // assumes it does, and links with the test lib, which requires an existing // get_case() function. So this is here to act as placeholder until (if?) // proper test cases are added here. This was detected in #47 (thanks // @cburgard). Case const* get_case(csubstr) { return nullptr; } void test_merge(std::initializer_list<csubstr> li, csubstr expected) { Tree loaded, merged, ref; parse(expected, &ref); // make sure the arena in the loaded tree is never resized size_t arena_dim = 2; for(csubstr src : li) { arena_dim += src.len; } loaded.reserve_arena(arena_dim); for(csubstr src : li) { loaded.clear(); // do not clear the arena of the loaded tree parse(src, &loaded); merged.merge_with(&loaded); } auto buf_result = emitrs<std::string>(merged); auto buf_expected = emitrs<std::string>(ref); EXPECT_EQ(buf_result, buf_expected); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(merge, seq_no_overlap_explicit) { test_merge( {"[0, 1, 2]", "[3, 4, 5]", "[6, 7, 8]"}, "[0, 1, 2, 3, 4, 5, 6, 7, 8]" ); } TEST(merge, seq_no_overlap_implicit) { test_merge( {"0, 1, 2", "3, 4, 5", "6, 7, 8"}, "0, 1, 2, 3, 4, 5, 6, 7, 8" ); } TEST(merge, seq_overlap_explicit) { test_merge( {"[0, 1, 2]", "[1, 2, 3]", "[2, 3, 4]"}, "[0, 1, 2, 1, 2, 3, 2, 3, 4]" // or this? "[0, 1, 2, 3, 4]" ); } TEST(merge, seq_overlap_implicit) { // now a bit more difficult test_merge( {"0, 1, 2", "1, 2, 3", "2, 3, 4"}, "0, 1, 2, 1, 2, 3, 2, 3, 4" // or this? "0, 1, 2, 3, 4" ); } TEST(merge, map_orthogonal) { test_merge( {"a: 0", "b: 1", "c: 2"}, "{a: 0, b: 1, c: 2}" ); } TEST(merge, map_overriding) { test_merge( { "a: 0", "{a: 1, b: 1}", "c: 2" }, "{a: 1, b: 1, c: 2}" ); } TEST(merge, map_overriding_multiple) { test_merge( { "a: 0", "{a: 1, b: 1}", "c: 2", "a: 2", "a: 3", "c: 4", "c: 5", "a: 4", }, "{a: 4, b: 1, c: 5}" ); } TEST(merge, seq_nested_in_map) { test_merge( { "{a: 0, seq: [a, b, c], d: 2}", "{a: 1, seq: [d, e, f], d: 3, c: 3}" }, "{a: 1, seq: [a, b, c, d, e, f], d: 3, c: 3}" ); } TEST(merge, seq_nested_in_map_override_with_map) { test_merge( { "{a: 0, ovr: [a, b, c], d: 2}", "{a: 1, ovr: {d: 0, b: 1, c: 2}, d: 3, c: 3}" }, "{a: 1, ovr: {d: 0, b: 1, c: 2}, d: 3, c: 3}" ); } TEST(merge, seq_nested_in_map_override_with_keyval) { test_merge( { "{a: 0, ovr: [a, b, c], d: 2}", "{a: 1, ovr: foo, d: 3, c: 3}" }, "{a: 1, ovr: foo, d: 3, c: 3}" ); } } // namespace yml } // namespace c4
fix linker error for dynamic so/dll in merge test (issue #47)
fix linker error for dynamic so/dll in merge test (issue #47)
C++
mit
biojppm/rapidyaml,biojppm/rapidyaml,biojppm/rapidyaml
0132ca192e8fa9aa99afa17bffd1ed3f8755b701
test/public_api/context_mold_section.cc
test/public_api/context_mold_section.cc
#include <gtest/gtest.h> // PUBLIC API #include <disir/disir.h> #include "test_helper.h" // Test mold API with empty mold. class MoldSectionTest : public testing::DisirTestWrapper { void SetUp() { DisirLogCurrentTestEnter (); context = NULL; context_mold = NULL; context_keyval = NULL; context_section = NULL; status = dc_mold_begin (&context_mold); ASSERT_STATUS (DISIR_STATUS_OK, status); status = dc_begin (context_mold, DISIR_CONTEXT_SECTION, &context_section); ASSERT_STATUS (DISIR_STATUS_OK, status); DisirLogCurrentTest ("SetUp completed - TestBody:"); } void TearDown() { DisirLogCurrentTest ("TestBody completed - TearDown:"); if (context) { status = dc_destroy (&context); EXPECT_STATUS (DISIR_STATUS_OK, status); } if (context_mold) { status = dc_destroy (&context_mold); EXPECT_STATUS (DISIR_STATUS_OK, status); } if (context_keyval) { status = dc_destroy (&context_keyval); EXPECT_STATUS (DISIR_STATUS_OK, status); } if (context_section) { status = dc_destroy (&context_section); EXPECT_STATUS (DISIR_STATUS_OK, status); } DisirLogCurrentTestExit (); } public: enum disir_status status; struct disir_context *context; struct disir_context *context_mold; struct disir_context *context_section; struct disir_context *context_keyval; }; TEST_F (MoldSectionTest, context_type) { ASSERT_EQ (DISIR_CONTEXT_SECTION, dc_context_type (context_section)); } TEST_F (MoldSectionTest, context_type_string) { ASSERT_STREQ ("SECTION", dc_context_type_string (context_section)); } TEST_F (MoldSectionTest, finalizing_without_name_shall_fail) { status = dc_finalize (&context_section); EXPECT_STATUS (DISIR_STATUS_INVALID_CONTEXT, status); EXPECT_STREQ ("Missing name component for section.", dc_context_error (context_section)); } TEST_F (MoldSectionTest, finalize_empty_with_name_shall_succeed) { status = dc_set_name (context_section, "test_name", strlen ("test_name")); ASSERT_STATUS (DISIR_STATUS_OK, status); status = dc_finalize (&context_section); EXPECT_STATUS (DISIR_STATUS_OK, status); } TEST_F (MoldSectionTest, set_name_on_mold) { status = dc_set_name (context_section, "test_name", strlen ("test_name")); EXPECT_STATUS (DISIR_STATUS_OK, status); } TEST_F (MoldSectionTest, begin_keyval_shall_succeed) { status = dc_begin (context_section, DISIR_CONTEXT_KEYVAL, &context); ASSERT_STATUS (DISIR_STATUS_OK, status); } TEST_F (MoldSectionTest, begin_section_shall_succeed) { status = dc_begin (context_section, DISIR_CONTEXT_SECTION, &context); ASSERT_STATUS (DISIR_STATUS_OK, status); } TEST_F (MoldSectionTest, begin_default_shall_fail) { status = dc_begin (context_section, DISIR_CONTEXT_DEFAULT, &context); ASSERT_STATUS (DISIR_STATUS_WRONG_CONTEXT, status); } TEST_F (MoldSectionTest, begin_free_text_shall_fail) { status = dc_begin (context_section, DISIR_CONTEXT_FREE_TEXT, &context); ASSERT_STATUS (DISIR_STATUS_WRONG_CONTEXT, status); } TEST_F (MoldSectionTest, begin_mold_shall_fail) { status = dc_begin (context_section, DISIR_CONTEXT_MOLD, &context); ASSERT_STATUS (DISIR_STATUS_WRONG_CONTEXT, status); } TEST_F (MoldSectionTest, begin_config_shall_fail) { status = dc_begin (context_section, DISIR_CONTEXT_CONFIG, &context); ASSERT_STATUS (DISIR_STATUS_WRONG_CONTEXT, status); } TEST_F (MoldSectionTest, add_keyval) { status = dc_add_keyval_string (context_section, "test_key", "test val", "doc st", NULL, NULL); ASSERT_STATUS (DISIR_STATUS_OK, status); } TEST_F (MoldSectionTest, introduced) { struct semantic_version input; struct semantic_version output; input.sv_patch = 1; input.sv_minor = 1; input.sv_major = 1; status = dc_add_introduced (context_section, &input); ASSERT_STATUS (DISIR_STATUS_OK, status); status = dc_get_introduced (context_section, &output); ASSERT_STATUS (DISIR_STATUS_OK, status); ASSERT_EQ (0, dc_semantic_version_compare (&input, &output)); }
#include <gtest/gtest.h> // PUBLIC API #include <disir/disir.h> #include "test_helper.h" // Test mold API with empty mold. class MoldSectionTest : public testing::DisirTestWrapper { void SetUp() { DisirLogCurrentTestEnter (); context = NULL; context_mold = NULL; context_keyval = NULL; context_section = NULL; status = dc_mold_begin (&context_mold); ASSERT_STATUS (DISIR_STATUS_OK, status); status = dc_begin (context_mold, DISIR_CONTEXT_SECTION, &context_section); ASSERT_STATUS (DISIR_STATUS_OK, status); DisirLogCurrentTest ("SetUp completed - TestBody:"); } void TearDown() { DisirLogCurrentTest ("TestBody completed - TearDown:"); if (context) { status = dc_destroy (&context); EXPECT_STATUS (DISIR_STATUS_OK, status); } if (context_mold) { status = dc_destroy (&context_mold); EXPECT_STATUS (DISIR_STATUS_OK, status); } if (context_keyval) { status = dc_destroy (&context_keyval); EXPECT_STATUS (DISIR_STATUS_OK, status); } if (context_section) { status = dc_destroy (&context_section); EXPECT_STATUS (DISIR_STATUS_OK, status); } DisirLogCurrentTestExit (); } public: enum disir_status status; struct disir_context *context; struct disir_context *context_mold; struct disir_context *context_section; struct disir_context *context_keyval; }; TEST_F (MoldSectionTest, context_type) { ASSERT_EQ (DISIR_CONTEXT_SECTION, dc_context_type (context_section)); } TEST_F (MoldSectionTest, context_type_string) { ASSERT_STREQ ("SECTION", dc_context_type_string (context_section)); } TEST_F (MoldSectionTest, finalizing_without_name_shall_fail) { status = dc_finalize (&context_section); EXPECT_STATUS (DISIR_STATUS_CONTEXT_IN_WRONG_STATE, status); EXPECT_STREQ ("Missing name component for section.", dc_context_error (context_section)); } TEST_F (MoldSectionTest, finalize_empty_with_name_shall_succeed) { status = dc_set_name (context_section, "test_name", strlen ("test_name")); ASSERT_STATUS (DISIR_STATUS_OK, status); status = dc_finalize (&context_section); EXPECT_STATUS (DISIR_STATUS_OK, status); } TEST_F (MoldSectionTest, set_name_on_mold) { status = dc_set_name (context_section, "test_name", strlen ("test_name")); EXPECT_STATUS (DISIR_STATUS_OK, status); } TEST_F (MoldSectionTest, begin_keyval_shall_succeed) { status = dc_begin (context_section, DISIR_CONTEXT_KEYVAL, &context); ASSERT_STATUS (DISIR_STATUS_OK, status); } TEST_F (MoldSectionTest, begin_section_shall_succeed) { status = dc_begin (context_section, DISIR_CONTEXT_SECTION, &context); ASSERT_STATUS (DISIR_STATUS_OK, status); } TEST_F (MoldSectionTest, begin_default_shall_fail) { status = dc_begin (context_section, DISIR_CONTEXT_DEFAULT, &context); ASSERT_STATUS (DISIR_STATUS_WRONG_CONTEXT, status); } TEST_F (MoldSectionTest, begin_free_text_shall_fail) { status = dc_begin (context_section, DISIR_CONTEXT_FREE_TEXT, &context); ASSERT_STATUS (DISIR_STATUS_WRONG_CONTEXT, status); } TEST_F (MoldSectionTest, begin_mold_shall_fail) { status = dc_begin (context_section, DISIR_CONTEXT_MOLD, &context); ASSERT_STATUS (DISIR_STATUS_WRONG_CONTEXT, status); } TEST_F (MoldSectionTest, begin_config_shall_fail) { status = dc_begin (context_section, DISIR_CONTEXT_CONFIG, &context); ASSERT_STATUS (DISIR_STATUS_WRONG_CONTEXT, status); } TEST_F (MoldSectionTest, add_keyval) { status = dc_add_keyval_string (context_section, "test_key", "test val", "doc st", NULL, NULL); ASSERT_STATUS (DISIR_STATUS_OK, status); } TEST_F (MoldSectionTest, introduced) { struct semantic_version input; struct semantic_version output; input.sv_patch = 1; input.sv_minor = 1; input.sv_major = 1; status = dc_add_introduced (context_section, &input); ASSERT_STATUS (DISIR_STATUS_OK, status); status = dc_get_introduced (context_section, &output); ASSERT_STATUS (DISIR_STATUS_OK, status); ASSERT_EQ (0, dc_semantic_version_compare (&input, &output)); }
fix expected return value of dc_finalize
test: fix expected return value of dc_finalize
C++
apache-2.0
veeg/disir-c,veeg/disir-c
68374f31e1f69df1efcbe4775ffb1b6d1eaef24d
KTp/Declarative/contact-list.cpp
KTp/Declarative/contact-list.cpp
/* Copyright (C) 2011 David Edmundson <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contact-list.h" #include <TelepathyQt/AccountFactory> #include <TelepathyQt/ConnectionFactory> #include <TelepathyQt/AccountManager> #include <TelepathyQt/PendingReady> #include <TelepathyQt/PendingChannelRequest> #include <KDebug> #include <KTp/contact-factory.h> #include <KTp/actions.h> ContactList::ContactList(QObject *parent) : QObject(parent), m_contactsModel(new KTp::ContactsListModel(this)), m_filterModel(new KTp::ContactsFilterModel(this)) { m_filterModel->setSourceModel(m_contactsModel); //flat model takes the source as a constructor parameter, the other's don't. //due to a bug somewhere creating the flat model proxy with the filter model as a source before the filter model has a source means the rolenames do not get propgated up Tp::registerTypes(); // Start setting up the Telepathy AccountManager. Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(), Tp::Features() << Tp::Account::FeatureCore << Tp::Account::FeatureAvatar << Tp::Account::FeatureCapabilities << Tp::Account::FeatureProtocolInfo << Tp::Account::FeatureProfile); Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(), Tp::Features() << Tp::Connection::FeatureCore << Tp::Connection::FeatureRosterGroups << Tp::Connection::FeatureRoster << Tp::Connection::FeatureSelfContact); Tp::ContactFactoryPtr contactFactory = KTp::ContactFactory::create(Tp::Features() << Tp::Contact::FeatureAlias << Tp::Contact::FeatureAvatarData << Tp::Contact::FeatureSimplePresence << Tp::Contact::FeatureCapabilities); Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus()); m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(), accountFactory, connectionFactory, channelFactory, contactFactory); connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady(Tp::PendingOperation*))); } void ContactList::onAccountManagerReady(Tp::PendingOperation *op) { Q_UNUSED(op); m_contactsModel->setAccountManager(m_accountManager); } KTp::ContactsFilterModel* ContactList::filterModel() const { return m_filterModel; } void ContactList::startChat(const Tp::AccountPtr &account, const KTp::ContactPtr &contact) { kDebug() << "Requesting chat for contact" << contact->alias(); kDebug() << "account is" << account->normalizedName(); Tp::PendingOperation *op = KTp::Actions::startChat(account, contact, true); connect(op, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onGenericOperationFinished(Tp::PendingOperation*))); } void ContactList::onGenericOperationFinished(Tp::PendingOperation *op) { if (op->isError()) { kDebug() << op->errorName(); kDebug() << op->errorMessage(); } }
/* Copyright (C) 2011 David Edmundson <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "contact-list.h" #include <TelepathyQt/AccountFactory> #include <TelepathyQt/ConnectionFactory> #include <TelepathyQt/AccountManager> #include <TelepathyQt/PendingReady> #include <TelepathyQt/PendingChannelRequest> #include <KDebug> #include <KTp/contact-factory.h> #include <KTp/actions.h> ContactList::ContactList(QObject *parent) : QObject(parent), m_contactsModel(new KTp::ContactsListModel(this)), m_filterModel(new KTp::ContactsFilterModel(this)) { m_filterModel->setSourceModel(m_contactsModel); //flat model takes the source as a constructor parameter, the other's don't. //due to a bug somewhere creating the flat model proxy with the filter model as a source before the filter model has a source means the rolenames do not get propgated up Tp::registerTypes(); // Start setting up the Telepathy AccountManager. Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(), Tp::Features() << Tp::Account::FeatureCore << Tp::Account::FeatureAvatar << Tp::Account::FeatureCapabilities << Tp::Account::FeatureProtocolInfo << Tp::Account::FeatureProfile); Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(), Tp::Features() << Tp::Connection::FeatureCore << Tp::Connection::FeatureRosterGroups << Tp::Connection::FeatureRoster << Tp::Connection::FeatureSelfContact); Tp::ContactFactoryPtr contactFactory = KTp::ContactFactory::create(Tp::Features() << Tp::Contact::FeatureAlias << Tp::Contact::FeatureAvatarData << Tp::Contact::FeatureSimplePresence << Tp::Contact::FeatureCapabilities); Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus()); m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(), accountFactory, connectionFactory, channelFactory, contactFactory); connect(m_accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady(Tp::PendingOperation*))); } void ContactList::onAccountManagerReady(Tp::PendingOperation *op) { Q_UNUSED(op); m_contactsModel->setAccountManager(m_accountManager); } KTp::ContactsFilterModel* ContactList::filterModel() const { return m_filterModel; } void ContactList::startChat(const Tp::AccountPtr &account, const KTp::ContactPtr &contact) { kDebug() << "Requesting chat for contact" << contact->alias(); kDebug() << "account is" << account->normalizedName(); Tp::PendingOperation *op = KTp::Actions::startChat(account, contact, false); connect(op, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onGenericOperationFinished(Tp::PendingOperation*))); } void ContactList::onGenericOperationFinished(Tp::PendingOperation *op) { if (op->isError()) { kDebug() << op->errorName(); kDebug() << op->errorMessage(); } }
Improve behavior of KTP plasmoids
Improve behavior of KTP plasmoids When starting chats from the contact list plasmoid, if there's a ktp-chat, use it. This happens by not forcing the preferred handler when starting a chat. REVIEW: 109033
C++
lgpl-2.1
leonhandreke/ktp-common-internals,KDE/ktp-common-internals,leonhandreke/ktp-common-internals,KDE/ktp-common-internals,KDE/ktp-common-internals,leonhandreke/ktp-common-internals
e317bfa84facf43c7289f1d7c143f596b11b4ab5
mcrouter/lib/fbi/cpp/LogFailure.cpp
mcrouter/lib/fbi/cpp/LogFailure.cpp
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "LogFailure.h" #include <unistd.h> #include <ctime> #include <map> #include <mutex> #include <string> #include <utility> #include <vector> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <folly/Format.h> #include "mcrouter/lib/fbi/cpp/util.h" namespace facebook { namespace memcache { namespace failure { namespace { std::string createMessage(folly::StringPiece service, folly::StringPiece category, folly::StringPiece msg, const std::map<std::string, std::string>& contexts) { auto result = folly::format("{} {} [{}] [{}] [{}] {}\n", time(nullptr), getpid(), service, category, getThreadName(), msg).str(); auto contextIt = contexts.find(service.str()); if (contextIt != contexts.end()) { result += folly::format("\"{}\": {}", contextIt->first, contextIt->second).str(); } else { for (const auto& it : contexts) { result += folly::format("\"{}\": {}\n", it.first, it.second).str(); } } return result; } void logToStdErrorImpl(folly::StringPiece service, folly::StringPiece category, folly::StringPiece msg, const std::map<std::string, std::string>& contexts) { LOG(ERROR) << createMessage(service, category, msg, contexts); } template <class Error> void throwErrorImpl(folly::StringPiece service, folly::StringPiece category, folly::StringPiece msg, const std::map<std::string, std::string>& contexts) { throw Error(createMessage(service, category, msg, contexts)); } struct StaticContainer { std::mutex lock; // service name => contex std::map<std::string, std::string> contexts; // { handler name, handler func } std::vector<std::pair<std::string, HandlerFunc>> handlers = { handlers::logToStdError() }; }; StaticContainer* container = new StaticContainer(); } // anonymous namespace namespace handlers { std::pair<std::string, HandlerFunc> logToStdError() { return std::make_pair<std::string, HandlerFunc>( "logToStdError", &logToStdErrorImpl); } std::pair<std::string, HandlerFunc> throwLogicError() { return std::make_pair<std::string, HandlerFunc>( "throwLogicError", &throwErrorImpl<std::logic_error>); } } //handlers const char* const Category::kBadEnvironment = "bad-environment"; const char* const Category::kInvalidOption = "invalid-option"; const char* const Category::kInvalidConfig = "invalid-config"; const char* const Category::kOutOfResources = "out-of-resources"; const char* const Category::kBrokenLogic = "broken-logic"; const char* const Category::kSystemError = "system-error"; const char* const Category::kOther = "other"; bool addHandler(std::pair<std::string, HandlerFunc> handler) { std::lock_guard<std::mutex> lock(container->lock); for (const auto& it : container->handlers) { if (it.first == handler.first) { return false; } } container->handlers.push_back(std::move(handler)); return true; } void setServiceContext(folly::StringPiece service, std::string context) { std::lock_guard<std::mutex> lock(container->lock); container->contexts[service.str()] = std::move(context); } void log(folly::StringPiece service, folly::StringPiece category, folly::StringPiece msg) { std::map<std::string, std::string> contexts; std::vector<std::pair<std::string, HandlerFunc>> handlers; { std::lock_guard<std::mutex> lock(container->lock); contexts = container->contexts; handlers = container->handlers; } for (auto& handler : handlers) { handler.second(service, category, msg, contexts); } } }}} // facebook::memcache
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #include "LogFailure.h" #include <unistd.h> #include <ctime> #include <map> #include <mutex> #include <string> #include <utility> #include <vector> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> #include <folly/experimental/Singleton.h> #include <folly/Format.h> #include "mcrouter/lib/fbi/cpp/util.h" namespace facebook { namespace memcache { namespace failure { namespace { std::string createMessage(folly::StringPiece service, folly::StringPiece category, folly::StringPiece msg, const std::map<std::string, std::string>& contexts) { auto result = folly::format("{} {} [{}] [{}] [{}] {}\n", time(nullptr), getpid(), service, category, getThreadName(), msg).str(); auto contextIt = contexts.find(service.str()); if (contextIt != contexts.end()) { result += folly::format("\"{}\": {}", contextIt->first, contextIt->second).str(); } else { for (const auto& it : contexts) { result += folly::format("\"{}\": {}\n", it.first, it.second).str(); } } return result; } void logToStdErrorImpl(folly::StringPiece service, folly::StringPiece category, folly::StringPiece msg, const std::map<std::string, std::string>& contexts) { LOG(ERROR) << createMessage(service, category, msg, contexts); } template <class Error> void throwErrorImpl(folly::StringPiece service, folly::StringPiece category, folly::StringPiece msg, const std::map<std::string, std::string>& contexts) { throw Error(createMessage(service, category, msg, contexts)); } struct StaticContainer { std::mutex lock; // service name => contex std::map<std::string, std::string> contexts; // { handler name, handler func } std::vector<std::pair<std::string, HandlerFunc>> handlers = { handlers::logToStdError() }; }; folly::Singleton<StaticContainer> containerSingleton; } // anonymous namespace namespace handlers { std::pair<std::string, HandlerFunc> logToStdError() { return std::make_pair<std::string, HandlerFunc>( "logToStdError", &logToStdErrorImpl); } std::pair<std::string, HandlerFunc> throwLogicError() { return std::make_pair<std::string, HandlerFunc>( "throwLogicError", &throwErrorImpl<std::logic_error>); } } //handlers const char* const Category::kBadEnvironment = "bad-environment"; const char* const Category::kInvalidOption = "invalid-option"; const char* const Category::kInvalidConfig = "invalid-config"; const char* const Category::kOutOfResources = "out-of-resources"; const char* const Category::kBrokenLogic = "broken-logic"; const char* const Category::kSystemError = "system-error"; const char* const Category::kOther = "other"; bool addHandler(std::pair<std::string, HandlerFunc> handler) { if (auto container = containerSingleton.get_weak().lock()) { std::lock_guard<std::mutex> lock(container->lock); for (const auto& it : container->handlers) { if (it.first == handler.first) { return false; } } container->handlers.push_back(std::move(handler)); return true; } return false; } void setServiceContext(folly::StringPiece service, std::string context) { if (auto container = containerSingleton.get_weak().lock()) { std::lock_guard<std::mutex> lock(container->lock); container->contexts[service.str()] = std::move(context); } } void log(folly::StringPiece service, folly::StringPiece category, folly::StringPiece msg) { std::map<std::string, std::string> contexts; std::vector<std::pair<std::string, HandlerFunc>> handlers; if (auto container = containerSingleton.get_weak().lock()) { std::lock_guard<std::mutex> lock(container->lock); contexts = container->contexts; handlers = container->handlers; } for (auto& handler : handlers) { handler.second(service, category, msg, contexts); } } }}} // facebook::memcache
Revert "[mcrouter] Hotfix crashes"
Revert "[mcrouter] Hotfix crashes" Summary: This reverts commit ca008fb74872a781e6a586be8f0651f8d5d49899. After D1615213 + D1615215 got in, it's safe now to use folly::Singleton here. Test Plan: unit tests Reviewed By: [email protected] Subscribers: alikhtarov, chip FB internal diff: D1618433
C++
bsd-3-clause
synecdoche/mcrouter,seem-sky/mcrouter,zhlong73/mcrouter,yqzhang/mcrouter,easyfmxu/mcrouter,synecdoche/mcrouter,glensc/mcrouter,is00hcw/mcrouter,apinski-cavium/mcrouter,yqzhang/mcrouter,tempbottle/mcrouter,easyfmxu/mcrouter,easyfmxu/mcrouter,facebook/mcrouter,apinski-cavium/mcrouter,is00hcw/mcrouter,nvaller/mcrouter,easyfmxu/mcrouter,is00hcw/mcrouter,reddit/mcrouter,facebook/mcrouter,yqzhang/mcrouter,nvaller/mcrouter,leitao/mcrouter,facebook/mcrouter,synecdoche/mcrouter,apinski-cavium/mcrouter,zhlong73/mcrouter,zhlong73/mcrouter,tempbottle/mcrouter,evertrue/mcrouter,nvaller/mcrouter,tempbottle/mcrouter,apinski-cavium/mcrouter,evertrue/mcrouter,evertrue/mcrouter,seem-sky/mcrouter,glensc/mcrouter,facebook/mcrouter,glensc/mcrouter,zhlong73/mcrouter,tempbottle/mcrouter,synecdoche/mcrouter,reddit/mcrouter,reddit/mcrouter,is00hcw/mcrouter,leitao/mcrouter,leitao/mcrouter,leitao/mcrouter,glensc/mcrouter,yqzhang/mcrouter,evertrue/mcrouter,seem-sky/mcrouter,nvaller/mcrouter,seem-sky/mcrouter,reddit/mcrouter
d80e6792c87f16371af5a8b5aefd51b5e091b662
API-Samples/copyblitimage/copyblitimage.cpp
API-Samples/copyblitimage/copyblitimage.cpp
/* * Vulkan Samples * * Copyright (C) 2015-2016 Valve Corporation * Copyright (C) 2015-2016 LunarG, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /* VULKAN_SAMPLE_SHORT_DESCRIPTION Copy/blit image */ /* Create a checkerboard image, and blit a small area of it to the * presentation image. We should see bigger sqaures. Then copy part of * the checkboard to the presentation image - we should see small squares */ #include <util_init.hpp> #include <assert.h> #include <string.h> #include <cstdlib> int sample_main() { VkResult U_ASSERT_ONLY res; struct sample_info info = {}; char sample_title[] = "Copy/Blit Image"; VkImageCreateInfo image_info; VkImage bltSrcImage; VkImage bltDstImage; VkMemoryRequirements memReq; VkMemoryAllocateInfo memAllocInfo; VkDeviceMemory dmem; unsigned char *pImgMem; init_global_layer_properties(info); init_instance_extension_names(info); init_device_extension_names(info); init_instance(info, sample_title); init_enumerate_device(info); init_window_size(info, 640, 640); init_connection(info); init_window(info); init_swapchain_extension(info); init_device(info); init_command_pool(info); init_command_buffer(info); execute_begin_command_buffer(info); init_device_queue(info); init_swap_chain(info); /* VULKAN_KEY_START */ VkFormatProperties formatProps; vkGetPhysicalDeviceFormatProperties(info.gpus[0], info.format, &formatProps); assert( (formatProps.linearTilingFeatures & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) && "Format cannot be used as transfer source"); VkSemaphore presentCompleteSemaphore; VkSemaphoreCreateInfo presentCompleteSemaphoreCreateInfo; presentCompleteSemaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; presentCompleteSemaphoreCreateInfo.pNext = NULL; presentCompleteSemaphoreCreateInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; res = vkCreateSemaphore(info.device, &presentCompleteSemaphoreCreateInfo, NULL, &presentCompleteSemaphore); assert(res == VK_SUCCESS); // Get the index of the next available swapchain image: res = vkAcquireNextImageKHR(info.device, info.swap_chain, UINT64_MAX, presentCompleteSemaphore, NULL, &info.current_buffer); // TODO: Deal with the VK_SUBOPTIMAL_KHR and VK_ERROR_OUT_OF_DATE_KHR // return codes assert(res == VK_SUCCESS); // Create an image, map it, and write some values to the image image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_info.pNext = NULL; image_info.imageType = VK_IMAGE_TYPE_2D; image_info.format = info.format; image_info.extent.width = info.width; image_info.extent.height = info.height; image_info.extent.depth = 1; image_info.mipLevels = 1; image_info.arrayLayers = 1; image_info.samples = NUM_SAMPLES; image_info.queueFamilyIndexCount = 0; image_info.pQueueFamilyIndices = NULL; image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT; image_info.flags = 0; image_info.tiling = VK_IMAGE_TILING_LINEAR; image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; res = vkCreateImage(info.device, &image_info, NULL, &bltSrcImage); memAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; memAllocInfo.pNext = NULL; vkGetImageMemoryRequirements(info.device, bltSrcImage, &memReq); bool pass = memory_type_from_properties(info, memReq.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &memAllocInfo.memoryTypeIndex); assert(pass); memAllocInfo.allocationSize = memReq.size; res = vkAllocateMemory(info.device, &memAllocInfo, NULL, &dmem); res = vkBindImageMemory(info.device, bltSrcImage, dmem, 0); res = vkMapMemory(info.device, dmem, 0, memReq.size, 0, (void **)&pImgMem); // Checkerboard of 8x8 pixel squares for (int row = 0; row < info.height; row++) { for (int col = 0; col < info.width; col++) { unsigned char rgb = (((row & 0x8) == 0) ^ ((col & 0x8) == 0)) * 255; pImgMem[0] = rgb; pImgMem[1] = rgb; pImgMem[2] = rgb; pImgMem[3] = 255; pImgMem += 4; } } // Flush the mapped memory and then unmap it Assume it isn't coherent since // we didn't really confirm VkMappedMemoryRange memRange; memRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; memRange.pNext = NULL; memRange.memory = dmem; memRange.offset = 0; memRange.size = memReq.size; res = vkFlushMappedMemoryRanges(info.device, 1, &memRange); vkUnmapMemory(info.device, dmem); set_image_layout(info, bltSrcImage, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); bltDstImage = info.buffers[info.current_buffer].image; // init_swap_chain will create the images as color attachment optimal // but we want transfer dst optimal set_image_layout(info, bltDstImage, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); // Do a 32x32 blit to all of the dst image - should get big squares VkImageBlit region; region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.srcSubresource.mipLevel = 0; region.srcSubresource.baseArrayLayer = 0; region.srcSubresource.layerCount = 1; region.srcOffsets[0].x = 0; region.srcOffsets[0].y = 0; region.srcOffsets[0].z = 0; region.srcOffsets[1].x = 32; region.srcOffsets[1].y = 32; region.srcOffsets[1].z = 1; region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.dstSubresource.mipLevel = 0; region.dstSubresource.baseArrayLayer = 0; region.dstSubresource.layerCount = 1; region.dstOffsets[0].x = 0; region.dstOffsets[0].y = 0; region.dstOffsets[0].z = 0; region.dstOffsets[1].x = info.width; region.dstOffsets[1].y = info.height; region.dstOffsets[1].z = 1; vkCmdBlitImage(info.cmd, bltSrcImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, bltDstImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region, VK_FILTER_LINEAR); // Do a image copy to part of the dst image - checks should stay small VkImageCopy cregion; cregion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; cregion.srcSubresource.mipLevel = 0; cregion.srcSubresource.baseArrayLayer = 0; cregion.srcSubresource.layerCount = 1; cregion.srcOffset.x = 0; cregion.srcOffset.y = 0; cregion.srcOffset.z = 0; cregion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; cregion.dstSubresource.mipLevel = 0; cregion.dstSubresource.baseArrayLayer = 0; cregion.dstSubresource.layerCount = 1; cregion.dstOffset.x = 256; cregion.dstOffset.y = 256; cregion.dstOffset.z = 0; cregion.extent.width = 128; cregion.extent.height = 128; cregion.extent.depth = 1; vkCmdCopyImage(info.cmd, bltSrcImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, bltDstImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &cregion); VkImageMemoryBarrier prePresentBarrier = {}; prePresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; prePresentBarrier.pNext = NULL; prePresentBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; prePresentBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; prePresentBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; prePresentBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; prePresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; prePresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; prePresentBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; prePresentBarrier.subresourceRange.baseMipLevel = 0; prePresentBarrier.subresourceRange.levelCount = 1; prePresentBarrier.subresourceRange.baseArrayLayer = 0; prePresentBarrier.subresourceRange.layerCount = 1; prePresentBarrier.image = info.buffers[info.current_buffer].image; vkCmdPipelineBarrier(info.cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &prePresentBarrier); res = vkEndCommandBuffer(info.cmd); const VkCommandBuffer cmd_bufs[] = {info.cmd}; VkFenceCreateInfo fenceInfo; VkFence drawFence; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.pNext = NULL; fenceInfo.flags = 0; vkCreateFence(info.device, &fenceInfo, NULL, &drawFence); VkPipelineStageFlags pipe_stage_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; VkSubmitInfo submit_info[1] = {}; submit_info[0].pNext = NULL; submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit_info[0].waitSemaphoreCount = 1; submit_info[0].pWaitSemaphores = &presentCompleteSemaphore; submit_info[0].pWaitDstStageMask = &pipe_stage_flags; submit_info[0].commandBufferCount = 1; submit_info[0].pCommandBuffers = cmd_bufs; submit_info[0].signalSemaphoreCount = 0; submit_info[0].pSignalSemaphores = NULL; /* Queue the command buffer for execution */ res = vkQueueSubmit(info.queue, 1, submit_info, drawFence); assert(res == VK_SUCCESS); res = vkQueueWaitIdle(info.queue); assert(res == VK_SUCCESS); /* Now present the image in the window */ VkPresentInfoKHR present; present.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; present.pNext = NULL; present.swapchainCount = 1; present.pSwapchains = &info.swap_chain; present.pImageIndices = &info.current_buffer; present.pWaitSemaphores = NULL; present.waitSemaphoreCount = 0; present.pResults = NULL; /* Make sure command buffer is finished before presenting */ do { res = vkWaitForFences(info.device, 1, &drawFence, VK_TRUE, FENCE_TIMEOUT); } while (res == VK_TIMEOUT); assert(res == VK_SUCCESS); res = vkQueuePresentKHR(info.queue, &present); assert(res == VK_SUCCESS); wait_seconds(1); /* VULKAN_KEY_END */ vkDestroySemaphore(info.device, presentCompleteSemaphore, NULL); vkDestroyFence(info.device, drawFence, NULL); vkDestroyImage(info.device, bltSrcImage, NULL); vkFreeMemory(info.device, dmem, NULL); destroy_swap_chain(info); destroy_command_buffer(info); destroy_command_pool(info); destroy_window(info); destroy_device(info); destroy_instance(info); return 0; }
/* * Vulkan Samples * * Copyright (C) 2015-2016 Valve Corporation * Copyright (C) 2015-2016 LunarG, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /* VULKAN_SAMPLE_SHORT_DESCRIPTION Copy/blit image */ /* Create a checkerboard image, and blit a small area of it to the * presentation image. We should see bigger sqaures. Then copy part of * the checkboard to the presentation image - we should see small squares */ #include <util_init.hpp> #include <assert.h> #include <string.h> #include <cstdlib> int sample_main() { VkResult U_ASSERT_ONLY res; struct sample_info info = {}; char sample_title[] = "Copy/Blit Image"; VkImageCreateInfo image_info; VkImage bltSrcImage; VkImage bltDstImage; VkMemoryRequirements memReq; VkMemoryAllocateInfo memAllocInfo; VkDeviceMemory dmem; unsigned char *pImgMem; init_global_layer_properties(info); init_instance_extension_names(info); init_device_extension_names(info); init_instance(info, sample_title); init_enumerate_device(info); init_window_size(info, 640, 640); init_connection(info); init_window(info); init_swapchain_extension(info); init_device(info); init_command_pool(info); init_command_buffer(info); execute_begin_command_buffer(info); init_device_queue(info); init_swap_chain(info); /* VULKAN_KEY_START */ VkFormatProperties formatProps; vkGetPhysicalDeviceFormatProperties(info.gpus[0], info.format, &formatProps); assert( (formatProps.linearTilingFeatures & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) && "Format cannot be used as transfer source"); VkSemaphore presentCompleteSemaphore; VkSemaphoreCreateInfo presentCompleteSemaphoreCreateInfo; presentCompleteSemaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO; presentCompleteSemaphoreCreateInfo.pNext = NULL; presentCompleteSemaphoreCreateInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT; res = vkCreateSemaphore(info.device, &presentCompleteSemaphoreCreateInfo, NULL, &presentCompleteSemaphore); assert(res == VK_SUCCESS); // Get the index of the next available swapchain image: res = vkAcquireNextImageKHR(info.device, info.swap_chain, UINT64_MAX, presentCompleteSemaphore, NULL, &info.current_buffer); // TODO: Deal with the VK_SUBOPTIMAL_KHR and VK_ERROR_OUT_OF_DATE_KHR // return codes assert(res == VK_SUCCESS); // Create an image, map it, and write some values to the image image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_info.pNext = NULL; image_info.imageType = VK_IMAGE_TYPE_2D; image_info.format = info.format; image_info.extent.width = info.width; image_info.extent.height = info.height; image_info.extent.depth = 1; image_info.mipLevels = 1; image_info.arrayLayers = 1; image_info.samples = NUM_SAMPLES; image_info.queueFamilyIndexCount = 0; image_info.pQueueFamilyIndices = NULL; image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_info.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT; image_info.flags = 0; image_info.tiling = VK_IMAGE_TILING_LINEAR; image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; res = vkCreateImage(info.device, &image_info, NULL, &bltSrcImage); memAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; memAllocInfo.pNext = NULL; vkGetImageMemoryRequirements(info.device, bltSrcImage, &memReq); bool pass = memory_type_from_properties(info, memReq.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, &memAllocInfo.memoryTypeIndex); assert(pass); memAllocInfo.allocationSize = memReq.size; res = vkAllocateMemory(info.device, &memAllocInfo, NULL, &dmem); res = vkBindImageMemory(info.device, bltSrcImage, dmem, 0); set_image_layout(info, bltSrcImage, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL); res = vkEndCommandBuffer(info.cmd); assert(res == VK_SUCCESS); VkFence cmdFence; init_fence(info, cmdFence); VkPipelineStageFlags pipe_stage_flags = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; VkSubmitInfo submit_info = {}; submit_info.pNext = NULL; submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit_info.waitSemaphoreCount = 1; submit_info.pWaitSemaphores = &presentCompleteSemaphore; submit_info.pWaitDstStageMask = &pipe_stage_flags; submit_info.commandBufferCount = 1; submit_info.pCommandBuffers = &info.cmd; submit_info.signalSemaphoreCount = 0; submit_info.pSignalSemaphores = NULL; /* Queue the command buffer for execution */ res = vkQueueSubmit(info.queue, 1, &submit_info, cmdFence); assert(res == VK_SUCCESS); /* Make sure command buffer is finished before mapping */ do { res = vkWaitForFences(info.device, 1, &cmdFence, VK_TRUE, FENCE_TIMEOUT); } while (res == VK_TIMEOUT); assert(res == VK_SUCCESS); vkDestroyFence(info.device, cmdFence, NULL); res = vkMapMemory(info.device, dmem, 0, memReq.size, 0, (void **)&pImgMem); // Checkerboard of 8x8 pixel squares for (int row = 0; row < info.height; row++) { for (int col = 0; col < info.width; col++) { unsigned char rgb = (((row & 0x8) == 0) ^ ((col & 0x8) == 0)) * 255; pImgMem[0] = rgb; pImgMem[1] = rgb; pImgMem[2] = rgb; pImgMem[3] = 255; pImgMem += 4; } } // Flush the mapped memory and then unmap it Assume it isn't coherent since // we didn't really confirm VkMappedMemoryRange memRange; memRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; memRange.pNext = NULL; memRange.memory = dmem; memRange.offset = 0; memRange.size = memReq.size; res = vkFlushMappedMemoryRanges(info.device, 1, &memRange); vkUnmapMemory(info.device, dmem); vkResetCommandBuffer(info.cmd, 0); execute_begin_command_buffer(info); set_image_layout(info, bltSrcImage, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL); bltDstImage = info.buffers[info.current_buffer].image; // init_swap_chain will create the images as color attachment optimal // but we want transfer dst optimal set_image_layout(info, bltDstImage, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL); // Do a 32x32 blit to all of the dst image - should get big squares VkImageBlit region; region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.srcSubresource.mipLevel = 0; region.srcSubresource.baseArrayLayer = 0; region.srcSubresource.layerCount = 1; region.srcOffsets[0].x = 0; region.srcOffsets[0].y = 0; region.srcOffsets[0].z = 0; region.srcOffsets[1].x = 32; region.srcOffsets[1].y = 32; region.srcOffsets[1].z = 1; region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.dstSubresource.mipLevel = 0; region.dstSubresource.baseArrayLayer = 0; region.dstSubresource.layerCount = 1; region.dstOffsets[0].x = 0; region.dstOffsets[0].y = 0; region.dstOffsets[0].z = 0; region.dstOffsets[1].x = info.width; region.dstOffsets[1].y = info.height; region.dstOffsets[1].z = 1; vkCmdBlitImage(info.cmd, bltSrcImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, bltDstImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region, VK_FILTER_LINEAR); // Do a image copy to part of the dst image - checks should stay small VkImageCopy cregion; cregion.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; cregion.srcSubresource.mipLevel = 0; cregion.srcSubresource.baseArrayLayer = 0; cregion.srcSubresource.layerCount = 1; cregion.srcOffset.x = 0; cregion.srcOffset.y = 0; cregion.srcOffset.z = 0; cregion.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; cregion.dstSubresource.mipLevel = 0; cregion.dstSubresource.baseArrayLayer = 0; cregion.dstSubresource.layerCount = 1; cregion.dstOffset.x = 256; cregion.dstOffset.y = 256; cregion.dstOffset.z = 0; cregion.extent.width = 128; cregion.extent.height = 128; cregion.extent.depth = 1; vkCmdCopyImage(info.cmd, bltSrcImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, bltDstImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &cregion); VkImageMemoryBarrier prePresentBarrier = {}; prePresentBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; prePresentBarrier.pNext = NULL; prePresentBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; prePresentBarrier.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT; prePresentBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; prePresentBarrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; prePresentBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; prePresentBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; prePresentBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; prePresentBarrier.subresourceRange.baseMipLevel = 0; prePresentBarrier.subresourceRange.levelCount = 1; prePresentBarrier.subresourceRange.baseArrayLayer = 0; prePresentBarrier.subresourceRange.layerCount = 1; prePresentBarrier.image = info.buffers[info.current_buffer].image; vkCmdPipelineBarrier(info.cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &prePresentBarrier); res = vkEndCommandBuffer(info.cmd); VkFenceCreateInfo fenceInfo; VkFence drawFence; fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.pNext = NULL; fenceInfo.flags = 0; vkCreateFence(info.device, &fenceInfo, NULL, &drawFence); submit_info.pNext = NULL; submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submit_info.waitSemaphoreCount = 0; submit_info.pWaitSemaphores = NULL; submit_info.pWaitDstStageMask = NULL; submit_info.commandBufferCount = 1; submit_info.pCommandBuffers = &info.cmd; submit_info.signalSemaphoreCount = 0; submit_info.pSignalSemaphores = NULL; /* Queue the command buffer for execution */ res = vkQueueSubmit(info.queue, 1, &submit_info, drawFence); assert(res == VK_SUCCESS); res = vkQueueWaitIdle(info.queue); assert(res == VK_SUCCESS); /* Now present the image in the window */ VkPresentInfoKHR present; present.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR; present.pNext = NULL; present.swapchainCount = 1; present.pSwapchains = &info.swap_chain; present.pImageIndices = &info.current_buffer; present.pWaitSemaphores = NULL; present.waitSemaphoreCount = 0; present.pResults = NULL; /* Make sure command buffer is finished before presenting */ do { res = vkWaitForFences(info.device, 1, &drawFence, VK_TRUE, FENCE_TIMEOUT); } while (res == VK_TIMEOUT); assert(res == VK_SUCCESS); res = vkQueuePresentKHR(info.queue, &present); assert(res == VK_SUCCESS); wait_seconds(1); /* VULKAN_KEY_END */ vkDestroySemaphore(info.device, presentCompleteSemaphore, NULL); vkDestroyFence(info.device, drawFence, NULL); vkDestroyImage(info.device, bltSrcImage, NULL); vkFreeMemory(info.device, dmem, NULL); destroy_swap_chain(info); destroy_command_buffer(info); destroy_command_pool(info); destroy_window(info); destroy_device(info); destroy_instance(info); return 0; }
Make sure image is in LAYOUT_GENERAL before mapping
copyblitimage: Make sure image is in LAYOUT_GENERAL before mapping
C++
apache-2.0
Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples,Radamanthe/VulkanSamples
002b2fe34e798edbc12de35b5f92c1aab4cc6e82
utils_unittest.cc
utils_unittest.cc
// Copyright (c) 2010 The Chromium OS 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 <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <map> #include <string> #include <vector> #include <base/string_util.h> #include <gtest/gtest.h> #include "update_engine/test_utils.h" #include "update_engine/utils.h" using std::map; using std::string; using std::vector; namespace chromeos_update_engine { class UtilsTest : public ::testing::Test { }; TEST(UtilsTest, IsOfficialBuild) { // Pretty lame test... EXPECT_TRUE(utils::IsOfficialBuild()); } TEST(UtilsTest, NormalizePathTest) { EXPECT_EQ("", utils::NormalizePath("", false)); EXPECT_EQ("", utils::NormalizePath("", true)); EXPECT_EQ("/", utils::NormalizePath("/", false)); EXPECT_EQ("", utils::NormalizePath("/", true)); EXPECT_EQ("/", utils::NormalizePath("//", false)); EXPECT_EQ("", utils::NormalizePath("//", true)); EXPECT_EQ("foo", utils::NormalizePath("foo", false)); EXPECT_EQ("foo", utils::NormalizePath("foo", true)); EXPECT_EQ("/foo/", utils::NormalizePath("/foo//", false)); EXPECT_EQ("/foo", utils::NormalizePath("/foo//", true)); EXPECT_EQ("bar/baz/foo/adlr", utils::NormalizePath("bar/baz//foo/adlr", false)); EXPECT_EQ("bar/baz/foo/adlr", utils::NormalizePath("bar/baz//foo/adlr", true)); EXPECT_EQ("/bar/baz/foo/adlr/", utils::NormalizePath("/bar/baz//foo/adlr/", false)); EXPECT_EQ("/bar/baz/foo/adlr", utils::NormalizePath("/bar/baz//foo/adlr/", true)); EXPECT_EQ("\\\\", utils::NormalizePath("\\\\", false)); EXPECT_EQ("\\\\", utils::NormalizePath("\\\\", true)); EXPECT_EQ("\\:/;$PATH\n\\", utils::NormalizePath("\\://;$PATH\n\\", false)); EXPECT_EQ("\\:/;$PATH\n\\", utils::NormalizePath("\\://;$PATH\n\\", true)); EXPECT_EQ("/spaces s/ ok/s / / /", utils::NormalizePath("/spaces s/ ok/s / / /", false)); EXPECT_EQ("/spaces s/ ok/s / / ", utils::NormalizePath("/spaces s/ ok/s / / /", true)); } TEST(UtilsTest, ReadFileFailure) { vector<char> empty; EXPECT_FALSE(utils::ReadFile("/this/doesn't/exist", &empty)); } TEST(UtilsTest, ErrnoNumberAsStringTest) { EXPECT_EQ("No such file or directory", utils::ErrnoNumberAsString(ENOENT)); } TEST(UtilsTest, StringHasSuffixTest) { EXPECT_TRUE(utils::StringHasSuffix("foo", "foo")); EXPECT_TRUE(utils::StringHasSuffix("foo", "o")); EXPECT_TRUE(utils::StringHasSuffix("", "")); EXPECT_TRUE(utils::StringHasSuffix("abcabc", "abc")); EXPECT_TRUE(utils::StringHasSuffix("adlrwashere", "ere")); EXPECT_TRUE(utils::StringHasSuffix("abcdefgh", "gh")); EXPECT_TRUE(utils::StringHasSuffix("abcdefgh", "")); EXPECT_FALSE(utils::StringHasSuffix("foo", "afoo")); EXPECT_FALSE(utils::StringHasSuffix("", "x")); EXPECT_FALSE(utils::StringHasSuffix("abcdefgh", "fg")); EXPECT_FALSE(utils::StringHasSuffix("abcdefgh", "ab")); } TEST(UtilsTest, StringHasPrefixTest) { EXPECT_TRUE(utils::StringHasPrefix("foo", "foo")); EXPECT_TRUE(utils::StringHasPrefix("foo", "f")); EXPECT_TRUE(utils::StringHasPrefix("", "")); EXPECT_TRUE(utils::StringHasPrefix("abcabc", "abc")); EXPECT_TRUE(utils::StringHasPrefix("adlrwashere", "adl")); EXPECT_TRUE(utils::StringHasPrefix("abcdefgh", "ab")); EXPECT_TRUE(utils::StringHasPrefix("abcdefgh", "")); EXPECT_FALSE(utils::StringHasPrefix("foo", "fooa")); EXPECT_FALSE(utils::StringHasPrefix("", "x")); EXPECT_FALSE(utils::StringHasPrefix("abcdefgh", "bc")); EXPECT_FALSE(utils::StringHasPrefix("abcdefgh", "gh")); } TEST(UtilsTest, BootDeviceTest) { // Pretty lame test... EXPECT_FALSE(utils::BootDevice().empty()); } TEST(UtilsTest, BootKernelDeviceTest) { EXPECT_EQ("", utils::BootKernelDevice("foo")); EXPECT_EQ("", utils::BootKernelDevice("/dev/sda0")); EXPECT_EQ("", utils::BootKernelDevice("/dev/sda1")); EXPECT_EQ("", utils::BootKernelDevice("/dev/sda2")); EXPECT_EQ("/dev/sda2", utils::BootKernelDevice("/dev/sda3")); EXPECT_EQ("", utils::BootKernelDevice("/dev/sda4")); EXPECT_EQ("/dev/sda4", utils::BootKernelDevice("/dev/sda5")); EXPECT_EQ("", utils::BootKernelDevice("/dev/sda6")); EXPECT_EQ("/dev/sda6", utils::BootKernelDevice("/dev/sda7")); EXPECT_EQ("", utils::BootKernelDevice("/dev/sda8")); EXPECT_EQ("", utils::BootKernelDevice("/dev/sda9")); } TEST(UtilsTest, RecursiveUnlinkDirTest) { EXPECT_EQ(0, mkdir("RecursiveUnlinkDirTest-a", 0755)); EXPECT_EQ(0, mkdir("RecursiveUnlinkDirTest-b", 0755)); EXPECT_EQ(0, symlink("../RecursiveUnlinkDirTest-a", "RecursiveUnlinkDirTest-b/link")); EXPECT_EQ(0, system("echo hi > RecursiveUnlinkDirTest-b/file")); EXPECT_EQ(0, mkdir("RecursiveUnlinkDirTest-b/dir", 0755)); EXPECT_EQ(0, system("echo ok > RecursiveUnlinkDirTest-b/dir/subfile")); EXPECT_TRUE(utils::RecursiveUnlinkDir("RecursiveUnlinkDirTest-b")); EXPECT_TRUE(utils::FileExists("RecursiveUnlinkDirTest-a")); EXPECT_EQ(0, system("rm -rf RecursiveUnlinkDirTest-a")); EXPECT_FALSE(utils::FileExists("RecursiveUnlinkDirTest-b")); EXPECT_TRUE(utils::RecursiveUnlinkDir("/something/that/doesnt/exist")); } TEST(UtilsTest, TempFilenameTest) { const string original = "/foo.XXXXXX"; const string result = utils::TempFilename(original); EXPECT_EQ(original.size(), result.size()); EXPECT_TRUE(utils::StringHasPrefix(result, "/foo.")); EXPECT_FALSE(utils::StringHasSuffix(result, "XXXXXX")); } TEST(UtilsTest, RootDeviceTest) { EXPECT_EQ("/dev/sda", utils::RootDevice("/dev/sda3")); EXPECT_EQ("/dev/mmc0", utils::RootDevice("/dev/mmc0p3")); EXPECT_EQ("", utils::RootDevice("/dev/foo/bar")); EXPECT_EQ("", utils::RootDevice("/")); EXPECT_EQ("", utils::RootDevice("")); } TEST(UtilsTest, SysfsBlockDeviceTest) { EXPECT_EQ("/sys/block/sda", utils::SysfsBlockDevice("/dev/sda")); EXPECT_EQ("", utils::SysfsBlockDevice("/foo/sda")); EXPECT_EQ("", utils::SysfsBlockDevice("/dev/foo/bar")); EXPECT_EQ("", utils::SysfsBlockDevice("/")); EXPECT_EQ("", utils::SysfsBlockDevice("./")); EXPECT_EQ("", utils::SysfsBlockDevice("")); } TEST(UtilsTest, IsRemovableDeviceTest) { EXPECT_FALSE(utils::IsRemovableDevice("")); EXPECT_FALSE(utils::IsRemovableDevice("/dev/non-existent-device")); } TEST(UtilsTest, PartitionNumberTest) { EXPECT_EQ("3", utils::PartitionNumber("/dev/sda3")); EXPECT_EQ("3", utils::PartitionNumber("/dev/mmc0p3")); } TEST(UtilsTest, ComparePrioritiesTest) { EXPECT_LT(utils::ComparePriorities(utils::kProcessPriorityLow, utils::kProcessPriorityNormal), 0); EXPECT_GT(utils::ComparePriorities(utils::kProcessPriorityNormal, utils::kProcessPriorityLow), 0); EXPECT_EQ(utils::ComparePriorities(utils::kProcessPriorityNormal, utils::kProcessPriorityNormal), 0); EXPECT_GT(utils::ComparePriorities(utils::kProcessPriorityHigh, utils::kProcessPriorityNormal), 0); } TEST(UtilsTest, FuzzIntTest) { static const unsigned int kRanges[] = { 0, 1, 2, 20 }; for (size_t r = 0; r < arraysize(kRanges); ++r) { unsigned int range = kRanges[r]; const int kValue = 50; for (int tries = 0; tries < 100; ++tries) { int value = utils::FuzzInt(kValue, range); EXPECT_GE(value, kValue - range / 2); EXPECT_LE(value, kValue + range - range / 2); } } } TEST(UtilsTest, ApplyMapTest) { int initial_values[] = {1, 2, 3, 4, 6}; vector<int> collection(&initial_values[0], initial_values + arraysize(initial_values)); EXPECT_EQ(arraysize(initial_values), collection.size()); int expected_values[] = {1, 2, 5, 4, 8}; map<int, int> value_map; value_map[3] = 5; value_map[6] = 8; value_map[5] = 10; utils::ApplyMap(&collection, value_map); size_t index = 0; for (vector<int>::iterator it = collection.begin(), e = collection.end(); it != e; ++it) { EXPECT_EQ(expected_values[index++], *it); } } TEST(UtilsTest, RunAsRootGetFilesystemSizeTest) { string img; EXPECT_TRUE(utils::MakeTempFile("/tmp/img.XXXXXX", &img, NULL)); ScopedPathUnlinker img_unlinker(img); CreateExtImageAtPath(img, NULL); // Extend the "partition" holding the file system from 10MiB to 20MiB. EXPECT_EQ(0, System(base::StringPrintf( "dd if=/dev/zero of=%s seek=20971519 bs=1 count=1", img.c_str()))); EXPECT_EQ(20 * 1024 * 1024, utils::FileSize(img)); int block_count = 0; int block_size = 0; EXPECT_TRUE(utils::GetFilesystemSize(img, &block_count, &block_size)); EXPECT_EQ(4096, block_size); EXPECT_EQ(10 * 1024 * 1024 / 4096, block_count); } } // namespace chromeos_update_engine
// Copyright (c) 2010 The Chromium OS 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 <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <map> #include <string> #include <vector> #include <base/string_util.h> #include <gtest/gtest.h> #include "update_engine/test_utils.h" #include "update_engine/utils.h" using std::map; using std::string; using std::vector; namespace chromeos_update_engine { class UtilsTest : public ::testing::Test { }; TEST(UtilsTest, IsOfficialBuild) { // Pretty lame test... EXPECT_TRUE(utils::IsOfficialBuild()); } TEST(UtilsTest, NormalizePathTest) { EXPECT_EQ("", utils::NormalizePath("", false)); EXPECT_EQ("", utils::NormalizePath("", true)); EXPECT_EQ("/", utils::NormalizePath("/", false)); EXPECT_EQ("", utils::NormalizePath("/", true)); EXPECT_EQ("/", utils::NormalizePath("//", false)); EXPECT_EQ("", utils::NormalizePath("//", true)); EXPECT_EQ("foo", utils::NormalizePath("foo", false)); EXPECT_EQ("foo", utils::NormalizePath("foo", true)); EXPECT_EQ("/foo/", utils::NormalizePath("/foo//", false)); EXPECT_EQ("/foo", utils::NormalizePath("/foo//", true)); EXPECT_EQ("bar/baz/foo/adlr", utils::NormalizePath("bar/baz//foo/adlr", false)); EXPECT_EQ("bar/baz/foo/adlr", utils::NormalizePath("bar/baz//foo/adlr", true)); EXPECT_EQ("/bar/baz/foo/adlr/", utils::NormalizePath("/bar/baz//foo/adlr/", false)); EXPECT_EQ("/bar/baz/foo/adlr", utils::NormalizePath("/bar/baz//foo/adlr/", true)); EXPECT_EQ("\\\\", utils::NormalizePath("\\\\", false)); EXPECT_EQ("\\\\", utils::NormalizePath("\\\\", true)); EXPECT_EQ("\\:/;$PATH\n\\", utils::NormalizePath("\\://;$PATH\n\\", false)); EXPECT_EQ("\\:/;$PATH\n\\", utils::NormalizePath("\\://;$PATH\n\\", true)); EXPECT_EQ("/spaces s/ ok/s / / /", utils::NormalizePath("/spaces s/ ok/s / / /", false)); EXPECT_EQ("/spaces s/ ok/s / / ", utils::NormalizePath("/spaces s/ ok/s / / /", true)); } TEST(UtilsTest, ReadFileFailure) { vector<char> empty; EXPECT_FALSE(utils::ReadFile("/this/doesn't/exist", &empty)); } TEST(UtilsTest, ErrnoNumberAsStringTest) { EXPECT_EQ("No such file or directory", utils::ErrnoNumberAsString(ENOENT)); } TEST(UtilsTest, StringHasSuffixTest) { EXPECT_TRUE(utils::StringHasSuffix("foo", "foo")); EXPECT_TRUE(utils::StringHasSuffix("foo", "o")); EXPECT_TRUE(utils::StringHasSuffix("", "")); EXPECT_TRUE(utils::StringHasSuffix("abcabc", "abc")); EXPECT_TRUE(utils::StringHasSuffix("adlrwashere", "ere")); EXPECT_TRUE(utils::StringHasSuffix("abcdefgh", "gh")); EXPECT_TRUE(utils::StringHasSuffix("abcdefgh", "")); EXPECT_FALSE(utils::StringHasSuffix("foo", "afoo")); EXPECT_FALSE(utils::StringHasSuffix("", "x")); EXPECT_FALSE(utils::StringHasSuffix("abcdefgh", "fg")); EXPECT_FALSE(utils::StringHasSuffix("abcdefgh", "ab")); } TEST(UtilsTest, StringHasPrefixTest) { EXPECT_TRUE(utils::StringHasPrefix("foo", "foo")); EXPECT_TRUE(utils::StringHasPrefix("foo", "f")); EXPECT_TRUE(utils::StringHasPrefix("", "")); EXPECT_TRUE(utils::StringHasPrefix("abcabc", "abc")); EXPECT_TRUE(utils::StringHasPrefix("adlrwashere", "adl")); EXPECT_TRUE(utils::StringHasPrefix("abcdefgh", "ab")); EXPECT_TRUE(utils::StringHasPrefix("abcdefgh", "")); EXPECT_FALSE(utils::StringHasPrefix("foo", "fooa")); EXPECT_FALSE(utils::StringHasPrefix("", "x")); EXPECT_FALSE(utils::StringHasPrefix("abcdefgh", "bc")); EXPECT_FALSE(utils::StringHasPrefix("abcdefgh", "gh")); } TEST(UtilsTest, BootDeviceTest) { // Pretty lame test... EXPECT_FALSE(utils::BootDevice().empty()); } TEST(UtilsTest, BootKernelDeviceTest) { EXPECT_EQ("", utils::BootKernelDevice("foo")); EXPECT_EQ("", utils::BootKernelDevice("/dev/sda0")); EXPECT_EQ("", utils::BootKernelDevice("/dev/sda1")); EXPECT_EQ("", utils::BootKernelDevice("/dev/sda2")); EXPECT_EQ("/dev/sda2", utils::BootKernelDevice("/dev/sda3")); EXPECT_EQ("", utils::BootKernelDevice("/dev/sda4")); EXPECT_EQ("/dev/sda4", utils::BootKernelDevice("/dev/sda5")); EXPECT_EQ("", utils::BootKernelDevice("/dev/sda6")); EXPECT_EQ("/dev/sda6", utils::BootKernelDevice("/dev/sda7")); EXPECT_EQ("", utils::BootKernelDevice("/dev/sda8")); EXPECT_EQ("", utils::BootKernelDevice("/dev/sda9")); } TEST(UtilsTest, RecursiveUnlinkDirTest) { EXPECT_EQ(0, mkdir("RecursiveUnlinkDirTest-a", 0755)); EXPECT_EQ(0, mkdir("RecursiveUnlinkDirTest-b", 0755)); EXPECT_EQ(0, symlink("../RecursiveUnlinkDirTest-a", "RecursiveUnlinkDirTest-b/link")); EXPECT_EQ(0, system("echo hi > RecursiveUnlinkDirTest-b/file")); EXPECT_EQ(0, mkdir("RecursiveUnlinkDirTest-b/dir", 0755)); EXPECT_EQ(0, system("echo ok > RecursiveUnlinkDirTest-b/dir/subfile")); EXPECT_TRUE(utils::RecursiveUnlinkDir("RecursiveUnlinkDirTest-b")); EXPECT_TRUE(utils::FileExists("RecursiveUnlinkDirTest-a")); EXPECT_EQ(0, system("rm -rf RecursiveUnlinkDirTest-a")); EXPECT_FALSE(utils::FileExists("RecursiveUnlinkDirTest-b")); EXPECT_TRUE(utils::RecursiveUnlinkDir("/something/that/doesnt/exist")); } TEST(UtilsTest, IsSymlinkTest) { string temp_dir; EXPECT_TRUE(utils::MakeTempDirectory("/tmp/symlink-test.XXXXXX", &temp_dir)); string temp_file = temp_dir + "temp-file"; EXPECT_TRUE(utils::WriteFile(temp_file.c_str(), "", 0)); string temp_symlink = temp_dir + "temp-symlink"; EXPECT_EQ(0, symlink(temp_file.c_str(), temp_symlink.c_str())); EXPECT_FALSE(utils::IsSymlink(temp_dir.c_str())); EXPECT_FALSE(utils::IsSymlink(temp_file.c_str())); EXPECT_TRUE(utils::IsSymlink(temp_symlink.c_str())); EXPECT_FALSE(utils::IsSymlink("/non/existent/path")); EXPECT_TRUE(utils::RecursiveUnlinkDir(temp_dir)); } TEST(UtilsTest, TempFilenameTest) { const string original = "/foo.XXXXXX"; const string result = utils::TempFilename(original); EXPECT_EQ(original.size(), result.size()); EXPECT_TRUE(utils::StringHasPrefix(result, "/foo.")); EXPECT_FALSE(utils::StringHasSuffix(result, "XXXXXX")); } TEST(UtilsTest, RootDeviceTest) { EXPECT_EQ("/dev/sda", utils::RootDevice("/dev/sda3")); EXPECT_EQ("/dev/mmc0", utils::RootDevice("/dev/mmc0p3")); EXPECT_EQ("", utils::RootDevice("/dev/foo/bar")); EXPECT_EQ("", utils::RootDevice("/")); EXPECT_EQ("", utils::RootDevice("")); } TEST(UtilsTest, SysfsBlockDeviceTest) { EXPECT_EQ("/sys/block/sda", utils::SysfsBlockDevice("/dev/sda")); EXPECT_EQ("", utils::SysfsBlockDevice("/foo/sda")); EXPECT_EQ("", utils::SysfsBlockDevice("/dev/foo/bar")); EXPECT_EQ("", utils::SysfsBlockDevice("/")); EXPECT_EQ("", utils::SysfsBlockDevice("./")); EXPECT_EQ("", utils::SysfsBlockDevice("")); } TEST(UtilsTest, IsRemovableDeviceTest) { EXPECT_FALSE(utils::IsRemovableDevice("")); EXPECT_FALSE(utils::IsRemovableDevice("/dev/non-existent-device")); } TEST(UtilsTest, PartitionNumberTest) { EXPECT_EQ("3", utils::PartitionNumber("/dev/sda3")); EXPECT_EQ("3", utils::PartitionNumber("/dev/mmc0p3")); } TEST(UtilsTest, RunAsRootSetProcessPriorityTest) { // getpriority may return -1 on error so the getpriority logic needs to be // enhanced if any of the pre-defined priority constants are changed to -1. ASSERT_NE(-1, utils::kProcessPriorityLow); ASSERT_NE(-1, utils::kProcessPriorityNormal); ASSERT_NE(-1, utils::kProcessPriorityHigh); EXPECT_EQ(utils::kProcessPriorityNormal, getpriority(PRIO_PROCESS, 0)); EXPECT_TRUE(utils::SetProcessPriority(utils::kProcessPriorityHigh)); EXPECT_EQ(utils::kProcessPriorityHigh, getpriority(PRIO_PROCESS, 0)); EXPECT_TRUE(utils::SetProcessPriority(utils::kProcessPriorityLow)); EXPECT_EQ(utils::kProcessPriorityLow, getpriority(PRIO_PROCESS, 0)); EXPECT_TRUE(utils::SetProcessPriority(utils::kProcessPriorityNormal)); EXPECT_EQ(utils::kProcessPriorityNormal, getpriority(PRIO_PROCESS, 0)); } TEST(UtilsTest, ComparePrioritiesTest) { EXPECT_LT(utils::ComparePriorities(utils::kProcessPriorityLow, utils::kProcessPriorityNormal), 0); EXPECT_GT(utils::ComparePriorities(utils::kProcessPriorityNormal, utils::kProcessPriorityLow), 0); EXPECT_EQ(utils::ComparePriorities(utils::kProcessPriorityNormal, utils::kProcessPriorityNormal), 0); EXPECT_GT(utils::ComparePriorities(utils::kProcessPriorityHigh, utils::kProcessPriorityNormal), 0); } TEST(UtilsTest, FuzzIntTest) { static const unsigned int kRanges[] = { 0, 1, 2, 20 }; for (size_t r = 0; r < arraysize(kRanges); ++r) { unsigned int range = kRanges[r]; const int kValue = 50; for (int tries = 0; tries < 100; ++tries) { int value = utils::FuzzInt(kValue, range); EXPECT_GE(value, kValue - range / 2); EXPECT_LE(value, kValue + range - range / 2); } } } TEST(UtilsTest, ApplyMapTest) { int initial_values[] = {1, 2, 3, 4, 6}; vector<int> collection(&initial_values[0], initial_values + arraysize(initial_values)); EXPECT_EQ(arraysize(initial_values), collection.size()); int expected_values[] = {1, 2, 5, 4, 8}; map<int, int> value_map; value_map[3] = 5; value_map[6] = 8; value_map[5] = 10; utils::ApplyMap(&collection, value_map); size_t index = 0; for (vector<int>::iterator it = collection.begin(), e = collection.end(); it != e; ++it) { EXPECT_EQ(expected_values[index++], *it); } } TEST(UtilsTest, RunAsRootGetFilesystemSizeTest) { string img; EXPECT_TRUE(utils::MakeTempFile("/tmp/img.XXXXXX", &img, NULL)); ScopedPathUnlinker img_unlinker(img); CreateExtImageAtPath(img, NULL); // Extend the "partition" holding the file system from 10MiB to 20MiB. EXPECT_EQ(0, System(base::StringPrintf( "dd if=/dev/zero of=%s seek=20971519 bs=1 count=1", img.c_str()))); EXPECT_EQ(20 * 1024 * 1024, utils::FileSize(img)); int block_count = 0; int block_size = 0; EXPECT_TRUE(utils::GetFilesystemSize(img, &block_count, &block_size)); EXPECT_EQ(4096, block_size); EXPECT_EQ(10 * 1024 * 1024 / 4096, block_count); } } // namespace chromeos_update_engine
Add unit tests for utils IsSymlink and SetProcessPriority.
AU: Add unit tests for utils IsSymlink and SetProcessPriority. BUG=6243 TEST=unit tests Change-Id: I50841af0e24df4facdd08b5eb04b2afa053d1e75 Review URL: http://codereview.chromium.org/5265001
C++
bsd-3-clause
marineam/update_engine,endocode/update_engine,mjg59/update_engine,endocode/update_engine,mjg59/update_engine,endocode/update_engine,marineam/update_engine,marineam/update_engine,marineam/update_engine,mjg59/update_engine
20591a7231b4094f16af30fab46cc16ba231417e
test/cpp/test-sphinx.cpp
test/cpp/test-sphinx.cpp
/* * Copyright (c) 2008 Digital Bazaar, Inc. All rights reserved. */ #include <iostream> #include <sstream> #include "db/sphinx/SphinxClient.h" #include "db/data/json/JsonWriter.h" #include "db/io/OStreamOutputStream.h" #include "db/rt/Exception.h" #include "db/test/Test.h" #include "db/test/Tester.h" #include "db/test/TestRunner.h" using namespace std; using namespace db::sphinx; using namespace db::data::json; using namespace db::io; using namespace db::net; using namespace db::rt; using namespace db::test; void runSphinxClientTest(TestRunner &tr, db::test::Tester& tester) { tr.group("SphinxClient"); tr.test("searchd protocol"); { Url url("sphinx://omega:3312"); SphinxCommand cmd; SphinxResponse response; SphinxClient client; cmd["type"] = SPHINX_SEARCHD_CMD_SEARCH; cmd["query"] = "test"; cmd["matchOffset"] = 0; cmd["matchCount"] = 20; cmd["matchMode"] = SPHINX_MATCH_ALL; cmd["rankMode"] = SPHINX_RANK_PROXIMITY_BM25; cmd["sortMode"] = SPHINX_SORT_RELEVANCE; cmd["weights"]->append() = 100; cmd["weights"]->append() = 1; cmd["indexes"] = "*"; cmd["minId"] = 0; cmd["maxId"] = 0; cmd["maxMatches"] = 1000; cmd["groupSort"] = "@group desc"; client.execute(&url, cmd, response); assertNoException(); ostringstream oss; OStreamOutputStream os(&oss); JsonWriter writer; writer.setCompact(false); writer.setIndentation(0, 3); writer.write(response, &os); cout << endl << "Response:" << endl; cout << oss.str() << endl; } tr.passIfNoException(); tr.ungroup(); } class DbSphinxClientTester : public db::test::Tester { public: DbSphinxClientTester() { setName("SphinxClient"); } /** * Run automatic unit tests. */ virtual int runAutomaticTests(TestRunner& tr) { runSphinxClientTest(tr, *this); return 0; } /** * Runs interactive unit tests. */ virtual int runInteractiveTests(TestRunner& tr) { return 0; } }; #ifndef DB_TEST_NO_MAIN DB_TEST_MAIN(DbSphinxClientTester) #endif
/* * Copyright (c) 2008 Digital Bazaar, Inc. All rights reserved. */ #include <iostream> #include <sstream> #include "db/sphinx/SphinxClient.h" #include "db/data/json/JsonWriter.h" #include "db/io/OStreamOutputStream.h" #include "db/rt/Exception.h" #include "db/test/Test.h" #include "db/test/Tester.h" #include "db/test/TestRunner.h" using namespace std; using namespace db::sphinx; using namespace db::data::json; using namespace db::io; using namespace db::net; using namespace db::rt; using namespace db::test; void runSphinxClientTest(TestRunner &tr, db::test::Tester& tester) { tr.group("SphinxClient"); tr.test("searchd protocol"); { Url url("sphinx://omega:3312"); SphinxCommand cmd; SphinxResponse response; SphinxClient client; cmd["type"] = SPHINX_SEARCHD_CMD_SEARCH; cmd["query"] = "test"; cmd["matchOffset"] = 0; cmd["matchCount"] = 20; cmd["matchMode"] = SPHINX_MATCH_ALL; cmd["rankMode"] = SPHINX_RANK_PROXIMITY_BM25; cmd["sortMode"] = SPHINX_SORT_RELEVANCE; cmd["weights"]->append() = 100; cmd["weights"]->append() = 1; cmd["indexes"] = "*"; cmd["minId"] = 0; cmd["maxId"] = 0; cmd["maxMatches"] = 1000; cmd["groupSort"] = "@group desc"; client.execute(&url, cmd, response); assertNoException(); //cout << endl << "Response:" << endl; //dumpDynamicObject(response); } tr.passIfNoException(); tr.ungroup(); } class DbSphinxClientTester : public db::test::Tester { public: DbSphinxClientTester() { setName("SphinxClient"); } /** * Run automatic unit tests. */ virtual int runAutomaticTests(TestRunner& tr) { runSphinxClientTest(tr, *this); return 0; } /** * Runs interactive unit tests. */ virtual int runInteractiveTests(TestRunner& tr) { return 0; } }; #ifndef DB_TEST_NO_MAIN DB_TEST_MAIN(DbSphinxClientTester) #endif
Use dumpDynamicObject() and comment out output.
Use dumpDynamicObject() and comment out output.
C++
agpl-3.0
digitalbazaar/monarch,digitalbazaar/monarch,digitalbazaar/monarch,digitalbazaar/monarch,digitalbazaar/monarch
85b917b737fb82cdd7c19a241c9bba8f8148bc44
himan-plugins/source/dewpoint.cpp
himan-plugins/source/dewpoint.cpp
/** * @file dewpoint.cpp * * @date Jan 21, 2012 * @author partio */ #include "dewpoint.h" #include <iostream> #include "plugin_factory.h" #include "logger_factory.h" #include <boost/lexical_cast.hpp> #define HIMAN_AUXILIARY_INCLUDE #include "fetcher.h" #include "writer.h" #include "neons.h" #include "pcuda.h" #undef HIMAN_AUXILIARY_INCLUDE #ifdef DEBUG #include "timer_factory.h" #endif using namespace std; using namespace himan::plugin; #undef HAVE_CUDA #ifdef HAVE_CUDA namespace himan { namespace plugin { namespace dewpoint_cuda { void doCuda(const float* Tin, float TBase, const float* Pin, float PScale, const float* VVin, float* VVout, size_t N, float PConst, unsigned short deviceIndex); } } } #endif const double RW = 461.5; // Vesihoyryn kaasuvakio (J / K kg) const double L = 2.5e6; // Veden hoyrystymislampo (J / kg) const double RW_div_L = RW / L; dewpoint::dewpoint() : itsUseCuda(false) { itsClearTextFormula = "Td = T / (1 - (T * ln(RH)*(Rw/L)))"; itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("dewpoint")); } void dewpoint::Process(shared_ptr<configuration> conf) { shared_ptr<plugin::pcuda> c = dynamic_pointer_cast<plugin::pcuda> (plugin_factory::Instance()->Plugin("pcuda")); if (c->HaveCuda()) { string msg = "I possess the powers of CUDA"; if (!conf->UseCuda()) { msg += ", but I won't use them"; } else { msg += ", and I'm not afraid to use them"; itsUseCuda = true; } itsLogger->Info(msg); } // Get number of threads to use unsigned short threadCount = ThreadCount(conf->ThreadCount()); boost::thread_group g; /* * The target information is parsed from the configuration file. */ shared_ptr<info> targetInfo = conf->Info(); /* * Get producer information from neons if whole_file_write is false. */ if (!conf->WholeFileWrite()) { shared_ptr<neons> n = dynamic_pointer_cast<neons> (plugin_factory::Instance()->Plugin("neons")); map<string,string> prodInfo = n->ProducerInfo(targetInfo->Producer().Id()); if (prodInfo.size()) { producer prod(targetInfo->Producer().Id()); prod.Process(boost::lexical_cast<long> (prodInfo["process"])); prod.Centre(boost::lexical_cast<long> (prodInfo["centre"])); prod.Name(prodInfo["name"]); targetInfo->Producer(prod); } } /* * Set target parameter to potential temperature * * We need to specify grib and querydata parameter information * since we don't know which one will be the output format. * */ vector<param> params; param requestedParam ("TD-K", 10); requestedParam.GribDiscipline(0); requestedParam.GribCategory(0); requestedParam.GribParameter(6); params.push_back(requestedParam); targetInfo->Params(params); /* * Create data structures. */ targetInfo->Create(); /* * Initialize parent class functions for dimension handling */ Dimension(conf->LeadingDimension()); FeederInfo(targetInfo->Clone()); FeederInfo()->Param(requestedParam); /* * Each thread will have a copy of the target info. */ vector<shared_ptr<info> > targetInfos; targetInfos.resize(threadCount); for (size_t i = 0; i < threadCount; i++) { itsLogger->Info("Thread " + boost::lexical_cast<string> (i + 1) + " starting"); targetInfos[i] = targetInfo->Clone(); boost::thread* t = new boost::thread(&dewpoint::Run, this, targetInfos[i], conf, i + 1); g.add_thread(t); } g.join_all(); if (conf->WholeFileWrite()) { shared_ptr<writer> theWriter = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer")); targetInfo->FirstTime(); string theOutputFile = "himan_" + targetInfo->Param().Name() + "_" + targetInfo->Time().OriginDateTime()->String("%Y%m%d%H"); theWriter->ToFile(targetInfo, conf->OutputFileType(), false, theOutputFile); } } void dewpoint::Run(shared_ptr<info> myTargetInfo, shared_ptr<const configuration> conf, unsigned short threadIndex) { while (AdjustLeadingDimension(myTargetInfo)) { Calculate(myTargetInfo, conf, threadIndex); } } /* * Calculate() * * This function does the actual calculation. */ void dewpoint::Calculate(shared_ptr<info> myTargetInfo, shared_ptr<const configuration> conf, unsigned short threadIndex) { shared_ptr<fetcher> f = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher")); // Required source parameters param TParam("T-K"); param RHParam("RH-PRCNT"); unique_ptr<logger> myThreadedLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("dewpointThread #" + boost::lexical_cast<string> (threadIndex))); ResetNonLeadingDimension(myTargetInfo); myTargetInfo->FirstParam(); while (AdjustNonLeadingDimension(myTargetInfo)) { myThreadedLogger->Debug("Calculating time " + myTargetInfo->Time().ValidDateTime()->String("%Y%m%d%H") + " level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); myTargetInfo->Data()->Resize(conf->Ni(), conf->Nj()); double TBase = 0; shared_ptr<info> TInfo; shared_ptr<info> RHInfo; try { TInfo = f->Fetch(conf, myTargetInfo->Time(), myTargetInfo->Level(), TParam); RHInfo = f->Fetch(conf, myTargetInfo->Time(), myTargetInfo->Level(), RHParam); } catch (HPExceptionType e) { switch (e) { case kFileDataNotFound: itsLogger->Info("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); continue; break; default: throw runtime_error(ClassName() + ": Unable to proceed"); break; } } assert(RHInfo->Param().Unit() == kPrcnt); if (TInfo->Param().Unit() == kC) { TBase = 273.15; } shared_ptr<NFmiGrid> targetGrid = myTargetInfo->ToNewbaseGrid(); shared_ptr<NFmiGrid> TGrid = TInfo->ToNewbaseGrid(); shared_ptr<NFmiGrid> RHGrid = RHInfo->ToNewbaseGrid(); int missingCount = 0; int count = 0; bool equalGrids = (myTargetInfo->GridAndAreaEquals(TInfo) && myTargetInfo->GridAndAreaEquals(RHInfo)); #ifdef HAVE_CUDA if (itsUseCuda && equalGrids) { size_t N = TGrid->Size(); float* VVout = new float[N]; if (!isPressureLevel) { dewpoint_cuda::doCuda(TGrid->DataPool()->Data(), TBase, PGrid->DataPool()->Data(), PScale, VVGrid->DataPool()->Data(), VVout, N, 0, theThreadIndex-1); } else { dewpoint_cuda::doCuda(TGrid->DataPool()->Data(), TBase, 0, 0, VVGrid->DataPool()->Data(), VVout, N, 100 * myTargetInfo->Level().Value(), theThreadIndex-1); } double *data = new double[N]; for (size_t i = 0; i < N; i++) { data[i] = static_cast<float> (VVout[i]); if (data[i] == kFloatMissing) { missingCount++; } count++; } myTargetInfo->Data()->Set(data, N); delete [] data; delete [] VVout; } else { #else if (true) { #endif assert(targetGrid->Size() == myTargetInfo->Data()->Size()); myTargetInfo->ResetLocation(); targetGrid->Reset(); #ifdef DEBUG unique_ptr<timer> t = unique_ptr<timer> (timer_factory::Instance()->GetTimer()); t->Start(); #endif while (myTargetInfo->NextLocation() && targetGrid->Next()) { count++; double T = kFloatMissing; double RH = kFloatMissing; InterpolateToPoint(targetGrid, TGrid, equalGrids, T); InterpolateToPoint(targetGrid, RHGrid, equalGrids, RH); if (T == kFloatMissing || RH == kFloatMissing) { missingCount++; myTargetInfo->Value(kFloatMissing); continue; } double TD = (T+TBase) / (1 - ((T+TBase) * log(RH) * (RW_div_L))); if (!myTargetInfo->Value(TD)) { throw runtime_error(ClassName() + ": Failed to set value to matrix"); } } #ifdef DEBUG t->Stop(); itsLogger->Debug("Calculation took " + boost::lexical_cast<string> (t->GetTime()) + " microseconds on CPU"); #endif } /* * Now we are done for this level * * Clone info-instance to writer since it might change our descriptor places */ myThreadedLogger->Info("Missing values: " + boost::lexical_cast<string> (missingCount) + "/" + boost::lexical_cast<string> (count)); if (!conf->WholeFileWrite()) { shared_ptr<writer> w = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer")); w->ToFile(myTargetInfo->Clone(), conf->OutputFileType(), true); } } }
/** * @file dewpoint.cpp * * @date Jan 21, 2012 * @author partio */ #include "dewpoint.h" #include <iostream> #include "plugin_factory.h" #include "logger_factory.h" #include <boost/lexical_cast.hpp> #define HIMAN_AUXILIARY_INCLUDE #include "fetcher.h" #include "writer.h" #include "neons.h" #include "pcuda.h" #undef HIMAN_AUXILIARY_INCLUDE #ifdef DEBUG #include "timer_factory.h" #endif using namespace std; using namespace himan::plugin; #undef HAVE_CUDA #ifdef HAVE_CUDA namespace himan { namespace plugin { namespace dewpoint_cuda { void doCuda(const float* Tin, float TBase, const float* Pin, float PScale, const float* VVin, float* VVout, size_t N, float PConst, unsigned short deviceIndex); } } } #endif const double RW = 461.5; // Vesihoyryn kaasuvakio (J / K kg) const double L = 2.5e6; // Veden hoyrystymislampo (J / kg) const double RW_div_L = RW / L; dewpoint::dewpoint() : itsUseCuda(false) { itsClearTextFormula = "Td = T / (1 - (T * ln(RH)*(Rw/L)))"; itsLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("dewpoint")); } void dewpoint::Process(shared_ptr<configuration> conf) { shared_ptr<plugin::pcuda> c = dynamic_pointer_cast<plugin::pcuda> (plugin_factory::Instance()->Plugin("pcuda")); if (c->HaveCuda()) { string msg = "I possess the powers of CUDA"; if (!conf->UseCuda()) { msg += ", but I won't use them"; } else { msg += ", and I'm not afraid to use them"; itsUseCuda = true; } itsLogger->Info(msg); } // Get number of threads to use unsigned short threadCount = ThreadCount(conf->ThreadCount()); boost::thread_group g; /* * The target information is parsed from the configuration file. */ shared_ptr<info> targetInfo = conf->Info(); /* * Get producer information from neons if whole_file_write is false. */ if (!conf->WholeFileWrite()) { shared_ptr<neons> n = dynamic_pointer_cast<neons> (plugin_factory::Instance()->Plugin("neons")); map<string,string> prodInfo = n->ProducerInfo(targetInfo->Producer().Id()); if (prodInfo.size()) { producer prod(targetInfo->Producer().Id()); prod.Process(boost::lexical_cast<long> (prodInfo["process"])); prod.Centre(boost::lexical_cast<long> (prodInfo["centre"])); prod.Name(prodInfo["name"]); targetInfo->Producer(prod); } } /* * Set target parameter to potential temperature * * We need to specify grib and querydata parameter information * since we don't know which one will be the output format. * */ vector<param> params; param requestedParam ("TD-K", 10); requestedParam.GribDiscipline(0); requestedParam.GribCategory(0); requestedParam.GribParameter(6); params.push_back(requestedParam); targetInfo->Params(params); /* * Create data structures. */ targetInfo->Create(); /* * Initialize parent class functions for dimension handling */ Dimension(conf->LeadingDimension()); FeederInfo(targetInfo->Clone()); FeederInfo()->Param(requestedParam); /* * Each thread will have a copy of the target info. */ vector<shared_ptr<info> > targetInfos; targetInfos.resize(threadCount); for (size_t i = 0; i < threadCount; i++) { itsLogger->Info("Thread " + boost::lexical_cast<string> (i + 1) + " starting"); targetInfos[i] = targetInfo->Clone(); boost::thread* t = new boost::thread(&dewpoint::Run, this, targetInfos[i], conf, i + 1); g.add_thread(t); } g.join_all(); if (conf->WholeFileWrite()) { shared_ptr<writer> theWriter = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer")); targetInfo->FirstTime(); string theOutputFile = "himan_" + targetInfo->Param().Name() + "_" + targetInfo->Time().OriginDateTime()->String("%Y%m%d%H"); theWriter->ToFile(targetInfo, conf->OutputFileType(), false, theOutputFile); } } void dewpoint::Run(shared_ptr<info> myTargetInfo, shared_ptr<const configuration> conf, unsigned short threadIndex) { while (AdjustLeadingDimension(myTargetInfo)) { Calculate(myTargetInfo, conf, threadIndex); } } /* * Calculate() * * This function does the actual calculation. */ void dewpoint::Calculate(shared_ptr<info> myTargetInfo, shared_ptr<const configuration> conf, unsigned short threadIndex) { shared_ptr<fetcher> f = dynamic_pointer_cast <fetcher> (plugin_factory::Instance()->Plugin("fetcher")); // Required source parameters param TParam("T-K"); param RHParam("RH-PRCNT"); unique_ptr<logger> myThreadedLogger = std::unique_ptr<logger> (logger_factory::Instance()->GetLog("dewpointThread #" + boost::lexical_cast<string> (threadIndex))); ResetNonLeadingDimension(myTargetInfo); myTargetInfo->FirstParam(); while (AdjustNonLeadingDimension(myTargetInfo)) { myThreadedLogger->Debug("Calculating time " + myTargetInfo->Time().ValidDateTime()->String("%Y%m%d%H") + " level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); myTargetInfo->Data()->Resize(conf->Ni(), conf->Nj()); double TBase = 0; shared_ptr<info> TInfo; shared_ptr<info> RHInfo; try { TInfo = f->Fetch(conf, myTargetInfo->Time(), myTargetInfo->Level(), TParam); RHInfo = f->Fetch(conf, myTargetInfo->Time(), myTargetInfo->Level(), RHParam); } catch (HPExceptionType e) { switch (e) { case kFileDataNotFound: itsLogger->Info("Skipping step " + boost::lexical_cast<string> (myTargetInfo->Time().Step()) + ", level " + boost::lexical_cast<string> (myTargetInfo->Level().Value())); continue; break; default: throw runtime_error(ClassName() + ": Unable to proceed"); break; } } assert(RHInfo->Param().Unit() == kPrcnt); if (TInfo->Param().Unit() == kC) { TBase = 273.15; } shared_ptr<NFmiGrid> targetGrid = myTargetInfo->ToNewbaseGrid(); shared_ptr<NFmiGrid> TGrid = TInfo->ToNewbaseGrid(); shared_ptr<NFmiGrid> RHGrid = RHInfo->ToNewbaseGrid(); int missingCount = 0; int count = 0; bool equalGrids = (myTargetInfo->GridAndAreaEquals(TInfo) && myTargetInfo->GridAndAreaEquals(RHInfo)); #ifdef HAVE_CUDA if (itsUseCuda && equalGrids) { size_t N = TGrid->Size(); float* VVout = new float[N]; if (!isPressureLevel) { dewpoint_cuda::doCuda(TGrid->DataPool()->Data(), TBase, PGrid->DataPool()->Data(), PScale, VVGrid->DataPool()->Data(), VVout, N, 0, theThreadIndex-1); } else { dewpoint_cuda::doCuda(TGrid->DataPool()->Data(), TBase, 0, 0, VVGrid->DataPool()->Data(), VVout, N, 100 * myTargetInfo->Level().Value(), theThreadIndex-1); } double *data = new double[N]; for (size_t i = 0; i < N; i++) { data[i] = static_cast<float> (VVout[i]); if (data[i] == kFloatMissing) { missingCount++; } count++; } myTargetInfo->Data()->Set(data, N); delete [] data; delete [] VVout; } else { #else if (true) { #endif assert(targetGrid->Size() == myTargetInfo->Data()->Size()); myTargetInfo->ResetLocation(); targetGrid->Reset(); #ifdef DEBUG unique_ptr<timer> t = unique_ptr<timer> (timer_factory::Instance()->GetTimer()); t->Start(); #endif while (myTargetInfo->NextLocation() && targetGrid->Next()) { count++; double T = kFloatMissing; double RH = kFloatMissing; InterpolateToPoint(targetGrid, TGrid, equalGrids, T); InterpolateToPoint(targetGrid, RHGrid, equalGrids, RH); if (T == kFloatMissing || RH == kFloatMissing) { missingCount++; myTargetInfo->Value(kFloatMissing); continue; } double TD = ((T+TBase) / (1 - ((T+TBase) * log(RH) * (RW_div_L)))) - 273.15 + TBase; if (!myTargetInfo->Value(TD)) { throw runtime_error(ClassName() + ": Failed to set value to matrix"); } } #ifdef DEBUG t->Stop(); itsLogger->Debug("Calculation took " + boost::lexical_cast<string> (t->GetTime()) + " microseconds on CPU"); #endif } /* * Now we are done for this level * * Clone info-instance to writer since it might change our descriptor places */ myThreadedLogger->Info("Missing values: " + boost::lexical_cast<string> (missingCount) + "/" + boost::lexical_cast<string> (count)); if (!conf->WholeFileWrite()) { shared_ptr<writer> w = dynamic_pointer_cast <writer> (plugin_factory::Instance()->Plugin("writer")); w->ToFile(myTargetInfo->Clone(), conf->OutputFileType(), true); } } }
Convert to celsius
Convert to celsius
C++
mit
fmidev/himan,fmidev/himan,fmidev/himan
b29134e4b3cf193e91343c557ca55c4f24f8b76b
himan-plugins/source/dewpoint.cpp
himan-plugins/source/dewpoint.cpp
/** * @file dewpoint.cpp * */ #include "dewpoint.h" #include "forecast_time.h" #include "level.h" #include "logger_factory.h" #include "metutil.h" #include <boost/lexical_cast.hpp> using namespace std; using namespace himan::plugin; dewpoint::dewpoint() { itsClearTextFormula = "Td = T / (1 - (T * ln(RH)*(Rw/L)))"; itsCudaEnabledCalculation = true; itsLogger = logger_factory::Instance()->GetLog("dewpoint"); } void dewpoint::Process(shared_ptr<const plugin_configuration> conf) { Init(conf); /* * Set target parameter to dewpoint. * */ param requestedParam("TD-K", 10, 0, 0, 6); requestedParam.Unit(kK); SetParams({requestedParam}); Start(); } /* * Calculate() * * This function does the actual calculation. */ void dewpoint::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex) { const param TParam("T-K"); const param RHParam("RH-PRCNT"); auto myThreadedLogger = logger_factory::Instance()->GetLog("dewpointThread #" + boost::lexical_cast<string>(threadIndex)); forecast_time forecastTime = myTargetInfo->Time(); level forecastLevel = myTargetInfo->Level(); forecast_type forecastType = myTargetInfo->ForecastType(); myThreadedLogger->Info("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + " level " + static_cast<string>(forecastLevel)); double TBase = 0; double RHScale = 1; info_t TInfo = Fetch(forecastTime, forecastLevel, TParam, forecastType, itsConfiguration->UseCudaForPacking()); info_t RHInfo = Fetch(forecastTime, forecastLevel, RHParam, forecastType, itsConfiguration->UseCudaForPacking()); if (!TInfo || !RHInfo) { myThreadedLogger->Warning("Skipping step " + boost::lexical_cast<string>(forecastTime.Step()) + ", level " + static_cast<string>(forecastLevel)); return; } assert(TInfo->Grid()->AB() == RHInfo->Grid()->AB()); SetAB(myTargetInfo, TInfo); // Special case for harmonie if (itsConfiguration->SourceProducer().Id() == 199) { RHScale = 100; } if (RHInfo->Param().Unit() != kPrcnt) { itsLogger->Warning("Unable to determine RH unit, assuming percent"); } // Formula assumes T == Celsius if (TInfo->Param().Unit() == kC) { TBase = himan::constants::kKelvin; } string deviceType; #ifdef HAVE_CUDA if (itsConfiguration->UseCuda()) { deviceType = "GPU"; auto opts = CudaPrepare(myTargetInfo, TInfo, RHInfo); dewpoint_cuda::Process(*opts); } else #endif { deviceType = "CPU"; LOCKSTEP(myTargetInfo, TInfo, RHInfo) { double T = TInfo->Value(); double RH = RHInfo->Value(); if (T == kFloatMissing || RH == kFloatMissing) { continue; } T += TBase; RH *= RHScale; double TD = metutil::DewPointFromRH_(T, RH); myTargetInfo->Value(TD); } } myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string>(myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<string>(myTargetInfo->Data().Size())); } #ifdef HAVE_CUDA unique_ptr<dewpoint_cuda::options> dewpoint::CudaPrepare(shared_ptr<info> myTargetInfo, shared_ptr<info> TInfo, shared_ptr<info> RHInfo) { unique_ptr<dewpoint_cuda::options> opts(new dewpoint_cuda::options); opts->t = TInfo->ToSimple(); opts->rh = RHInfo->ToSimple(); opts->td = myTargetInfo->ToSimple(); opts->N = opts->td->size_x * opts->td->size_y; if (TInfo->Param().Unit() == kC) { opts->t_base = himan::constants::kKelvin; } if (RHInfo->Param().Unit() != kPrcnt || itsConfiguration->SourceProducer().Id() == 199) { // If unit cannot be detected, assume the values are from 0 .. 1 opts->rh_scale = 100; } return opts; } #endif
/** * @file dewpoint.cpp * */ #include "dewpoint.h" #include "forecast_time.h" #include "level.h" #include "logger_factory.h" #include "metutil.h" #include <boost/lexical_cast.hpp> using namespace std; using namespace himan::plugin; dewpoint::dewpoint() { itsClearTextFormula = "Td = T / (1 - (T * ln(RH)*(Rw/L)))"; itsCudaEnabledCalculation = true; itsLogger = logger_factory::Instance()->GetLog("dewpoint"); } void dewpoint::Process(shared_ptr<const plugin_configuration> conf) { Init(conf); /* * Set target parameter to dewpoint. * */ param requestedParam("TD-K", 10, 0, 0, 6); requestedParam.Unit(kK); SetParams({requestedParam}); Start(); } /* * Calculate() * * This function does the actual calculation. */ void dewpoint::Calculate(shared_ptr<info> myTargetInfo, unsigned short threadIndex) { const param TParam("T-K"); const param RHParam("RH-PRCNT"); auto myThreadedLogger = logger_factory::Instance()->GetLog("dewpointThread #" + boost::lexical_cast<string>(threadIndex)); forecast_time forecastTime = myTargetInfo->Time(); level forecastLevel = myTargetInfo->Level(); forecast_type forecastType = myTargetInfo->ForecastType(); myThreadedLogger->Info("Calculating time " + static_cast<string>(forecastTime.ValidDateTime()) + " level " + static_cast<string>(forecastLevel)); double TBase = 0; double RHScale = 1; info_t TInfo = Fetch(forecastTime, forecastLevel, TParam, forecastType, itsConfiguration->UseCudaForPacking()); info_t RHInfo = Fetch(forecastTime, forecastLevel, RHParam, forecastType, itsConfiguration->UseCudaForPacking()); if (!TInfo || !RHInfo) { myThreadedLogger->Warning("Skipping step " + boost::lexical_cast<string>(forecastTime.Step()) + ", level " + static_cast<string>(forecastLevel)); return; } assert(TInfo->Grid()->AB() == RHInfo->Grid()->AB()); SetAB(myTargetInfo, TInfo); // Special case for harmonie if (RHInfo->Param().Unit() != kPrcnt || itsConfiguration->SourceProducer().Id() == 199) { itsLogger->Warning("Unable to determine RH unit, assuming 0 .. 1"); RHScale = 100.0; } // Formula assumes T == Celsius if (TInfo->Param().Unit() == kC) { TBase = himan::constants::kKelvin; } string deviceType; #ifdef HAVE_CUDA if (itsConfiguration->UseCuda()) { deviceType = "GPU"; auto opts = CudaPrepare(myTargetInfo, TInfo, RHInfo); dewpoint_cuda::Process(*opts); } else #endif { deviceType = "CPU"; LOCKSTEP(myTargetInfo, TInfo, RHInfo) { double T = TInfo->Value(); double RH = RHInfo->Value(); if (T == kFloatMissing || RH == kFloatMissing) { continue; } T += TBase; RH *= RHScale; double TD = metutil::DewPointFromRH_(T, RH); myTargetInfo->Value(TD); } } myThreadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<string>(myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<string>(myTargetInfo->Data().Size())); } #ifdef HAVE_CUDA unique_ptr<dewpoint_cuda::options> dewpoint::CudaPrepare(shared_ptr<info> myTargetInfo, shared_ptr<info> TInfo, shared_ptr<info> RHInfo) { unique_ptr<dewpoint_cuda::options> opts(new dewpoint_cuda::options); opts->t = TInfo->ToSimple(); opts->rh = RHInfo->ToSimple(); opts->td = myTargetInfo->ToSimple(); opts->N = opts->td->size_x * opts->td->size_y; if (TInfo->Param().Unit() == kC) { opts->t_base = himan::constants::kKelvin; } if (RHInfo->Param().Unit() != kPrcnt || itsConfiguration->SourceProducer().Id() == 199) { // If unit cannot be detected, assume the values are from 0 .. 1 opts->rh_scale = 100; } return opts; } #endif
make CPU and GPU behaviour the same
dewpoint: make CPU and GPU behaviour the same
C++
mit
fmidev/himan,fmidev/himan,fmidev/himan
1557c99f29a3b6a39049f1eb0282326a63a8da65
tests/Test.cpp
tests/Test.cpp
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkTLazy.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "gl/SkNativeGLContext.h" #else class GrContext; #endif SK_DEFINE_INST_COUNT(skiatest::Reporter) using namespace skiatest; Reporter::Reporter() { this->resetReporting(); } void Reporter::resetReporting() { fCurrTest = NULL; fTestCount = 0; sk_bzero(fResultCount, sizeof(fResultCount)); } void Reporter::startTest(Test* test) { SkASSERT(NULL == fCurrTest); fCurrTest = test; this->onStart(test); fTestCount += 1; fCurrTestSuccess = true; // we're optimistic } void Reporter::report(const char desc[], Result result) { if (NULL == desc) { desc = "<no description>"; } this->onReport(desc, result); fResultCount[result] += 1; if (kFailed == result) { fCurrTestSuccess = false; } } void Reporter::endTest(Test* test) { SkASSERT(test == fCurrTest); this->onEnd(test); fCurrTest = NULL; } /////////////////////////////////////////////////////////////////////////////// Test::Test() : fReporter(NULL) {} Test::~Test() { SkSafeUnref(fReporter); } void Test::setReporter(Reporter* r) { SkRefCnt_SafeAssign(fReporter, r); } const char* Test::getName() { if (fName.size() == 0) { this->onGetName(&fName); } return fName.c_str(); } bool Test::run() { fReporter->startTest(this); this->onRun(fReporter); fReporter->endTest(this); return fReporter->getCurrSuccess(); } /////////////////////////////////////////////////////////////////////////////// #if SK_SUPPORT_GPU static SkAutoTUnref<SkNativeGLContext> gGLContext; static SkAutoTUnref<GrContext> gGrContext; #endif void GpuTest::DestroyContext() { #if SK_SUPPORT_GPU // preserve this order, we want gGrContext destroyed after gEGLContext gGLContext.reset(NULL); gGrContext.reset(NULL); #endif } GrContext* GpuTest::GetContext() { #if SK_SUPPORT_GPU if (NULL == gGrContext.get()) { gGLContext.reset(new SkNativeGLContext()); if (gGLContext.get()->init(800, 600)) { GrBackendContext ctx = reinterpret_cast<GrBackendContext>(gGLContext.get()->gl()); gGrContext.reset(GrContext::Create(kOpenGL_GrBackend, ctx)); } } if (gGLContext.get()) { gGLContext.get()->makeCurrent(); } return gGrContext.get(); #else return NULL; #endif }
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkTLazy.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "gl/SkNativeGLContext.h" #else class GrContext; #endif SK_DEFINE_INST_COUNT(skiatest::Reporter) using namespace skiatest; Reporter::Reporter() { this->resetReporting(); } void Reporter::resetReporting() { fCurrTest = NULL; fTestCount = 0; sk_bzero(fResultCount, sizeof(fResultCount)); } void Reporter::startTest(Test* test) { SkASSERT(NULL == fCurrTest); fCurrTest = test; this->onStart(test); fTestCount += 1; fCurrTestSuccess = true; // we're optimistic } void Reporter::report(const char desc[], Result result) { if (NULL == desc) { desc = "<no description>"; } this->onReport(desc, result); fResultCount[result] += 1; if (kFailed == result) { fCurrTestSuccess = false; } } void Reporter::endTest(Test* test) { SkASSERT(test == fCurrTest); this->onEnd(test); fCurrTest = NULL; } /////////////////////////////////////////////////////////////////////////////// Test::Test() : fReporter(NULL) {} Test::~Test() { SkSafeUnref(fReporter); } void Test::setReporter(Reporter* r) { SkRefCnt_SafeAssign(fReporter, r); } const char* Test::getName() { if (fName.size() == 0) { this->onGetName(&fName); } return fName.c_str(); } bool Test::run() { fReporter->startTest(this); this->onRun(fReporter); fReporter->endTest(this); return fReporter->getCurrSuccess(); } /////////////////////////////////////////////////////////////////////////////// #if SK_SUPPORT_GPU static SkAutoTUnref<SkNativeGLContext> gGLContext; static SkAutoTUnref<GrContext> gGrContext; #endif void GpuTest::DestroyContext() { #if SK_SUPPORT_GPU // preserve this order, we want gGrContext destroyed before gGLContext gGrContext.reset(NULL); gGLContext.reset(NULL); #endif } GrContext* GpuTest::GetContext() { #if SK_SUPPORT_GPU if (NULL == gGrContext.get()) { gGLContext.reset(new SkNativeGLContext()); if (gGLContext.get()->init(800, 600)) { GrBackendContext ctx = reinterpret_cast<GrBackendContext>(gGLContext.get()->gl()); gGrContext.reset(GrContext::Create(kOpenGL_GrBackend, ctx)); } } if (gGLContext.get()) { gGLContext.get()->makeCurrent(); } return gGrContext.get(); #else return NULL; #endif }
Fix the gr/gl destruction order in Test.cpp
Fix the gr/gl destruction order in Test.cpp [email protected] Review URL: https://codereview.appspot.com/6851126 git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@6602 2bbb7eff-a529-9590-31e7-b0007b416f81
C++
bsd-3-clause
Cue/skia,Cue/skia,Cue/skia,Cue/skia
430e36e25f7a105b940a9a17b8a9d3734157fdfe
tests/init.cpp
tests/init.cpp
#include "catch.hpp" #include <iostream> //#include "Database_Creator.hpp" #include "Database_Sorter.hpp" person readPerson(std::string const & file_name, size_t const index) { person result; std::ifstream file(file_name); for (size_t i = 0; i < index + 1; i++) { file >> result; } file.close(); return result; } bool isANotMoreThanB(person const & A, person const & B) { char * A_name = A.getName(); char * B_name = B.getName(); for (size_t i = 0; i < A.name_length; i++) { char A_char = A_name[i]; char B_char = (i < B.name_length) ? B_name[i] : ' '; if (letterI(A_name[i], i == 0) < letterI(B_name[i], i == 0)) { return true; } else { if (A_name[i] != B_name[i]) { return false; } } } delete []A_name; delete []B_name; return true; } SCENARIO("Sort", "[s]") { size_t n_persons = 200; //system("start www.cyberforum.ru/cpp-beginners/thread82643.html#post458604"); size_t RAM_amount = 1; std::string names_file_name = "F:\\1\\names.txt"; std::string surnames_file_name = "F:\\1\\surnames.txt"; std::string database_file_name = "8.txt"; std::string output_file_name = "F:\\1\\sorted_database.txt"; //Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons); Database_Sorter database_sorter1("8.txt", "1.txt", 1, "1\\"); Database_Sorter database_sorter2("16.txt", "2.txt", 4, "2\\"); Database_Sorter database_sorter3("16.txt", "3.txt", 17, "3\\"); size_t start = clock(); database_sorter1.sortDatabase(); database_sorter2.sortDatabase(); database_sorter3.sortDatabase(); size_t result = clock() - start; database_sorter1.closeDatabase(); database_sorter2.closeDatabase(); database_sorter3.closeDatabase(); std::cout << "Result " << result << std::endl; for (size_t i = 0; i < 100; i++) { size_t person1_i = rand() % n_persons; size_t person2_i = person1_i + rand() % (n_persons - person1_i); person person1 = readPerson("1.txt", person1_i); person person2 = readPerson("1.txt", person2_i); REQUIRE(isANotMoreThanB(person1, person2)); } }
#include "catch.hpp" #include <iostream> //#include "Database_Creator.hpp" #include "Database_Sorter.hpp" person readPerson(std::string const & file_name, size_t const index) { person result; std::ifstream file(file_name); for (size_t i = 0; i < index + 1; i++) { file >> result; } file.close(); return result; } bool isANotMoreThanB(person const & A, person const & B) { char * A_name = A.getName(); char * B_name = B.getName(); for (size_t i = 0; i < A.name_length; i++) { char A_char = A_name[i]; char B_char = (i < B.name_length) ? B_name[i] : ' '; if (letterI(A_name[i], i == 0) < letterI(B_name[i], i == 0)) { return true; } else { if (A_name[i] != B_name[i]) { return false; } } } delete []A_name; delete []B_name; return true; } SCENARIO("Sort", "[s]") { size_t n_persons = 200; //system("start www.cyberforum.ru/cpp-beginners/thread82643.html#post458604"); size_t RAM_amount = 1; std::string names_file_name = "F:\\1\\names.txt"; std::string surnames_file_name = "F:\\1\\surnames.txt"; std::string database_file_name = "8.txt"; std::string output_file_name = "F:\\1\\sorted_database.txt"; //Database_Creator database_creator(database_file_name, names_file_name, surnames_file_name, n_persons); Database_Sorter database_sorter1("8.txt", "1.txt", 1, "1\\"); Database_Sorter database_sorter2("16.txt", "2.txt", 4, "2\\"); Database_Sorter database_sorter3("32.txt", "3.txt", 17, "3\\"); size_t start = clock(); database_sorter1.sortDatabase(); database_sorter2.sortDatabase(); database_sorter3.sortDatabase(); size_t result = clock() - start; database_sorter1.closeDatabase(); database_sorter2.closeDatabase(); database_sorter3.closeDatabase(); std::cout << "Result " << result << std::endl; for (size_t i = 0; i < 100; i++) { size_t person1_i = rand() % n_persons; size_t person2_i = person1_i + rand() % (n_persons - person1_i); person person1 = readPerson("1.txt", person1_i); person person2 = readPerson("1.txt", person2_i); REQUIRE(isANotMoreThanB(person1, person2)); } }
Update init.cpp
Update init.cpp
C++
mit
ArtemKokorinStudent/External-sort
9eac2b2d40d4f2f66e3b1f7fb270118ce5ae4d00
tests/init.cpp
tests/init.cpp
#include "stack.hpp" stack<int> st; TEST_CASE("Thow threads", "[T]") { std::thread thread1([]() { for (size_t i = 0; i < 100; i++) { st.push(rand()); } }); std::thread thread2([]() { for (size_t i = 0; i < 100;) { if (!st.empty()) { std::cout << st.top() << std::endl; st.pop(); i++; } } }); thread1.join(); thread2.join(); } TEST_CASE("Stack can be instantiated by various types", "[instantiation]") { REQUIRE_NOTHROW(stack<int> st1); REQUIRE_NOTHROW(stack<double> st2); REQUIRE_NOTHROW(stack<char> st3); REQUIRE_NOTHROW(stack<int*> st4); REQUIRE_NOTHROW(stack<stack<int>> st5); } TEST_CASE("Push, pop, top", "[push_pop_top]") { stack<int> st; st.push(1); st.push(2); st.top(); REQUIRE(st.top() == 2); st.pop(); REQUIRE(st.top() == 1); st.pop(); } TEST_CASE("count", "[count]") { stack<int> st; REQUIRE(st.count() == 0); st.push(1); REQUIRE(st.count() == 1); st.push(2); REQUIRE(st.count() == 2); st.pop(); REQUIRE(st.count() == 1); st.pop(); REQUIRE(st.count() == 0); } TEST_CASE("Copy constructor", "[copy_ctr]") { stack<double> st1; st1.push(1); st1.push(2); //REQUIRE_NOTHROW(stack<double> st2 = st1); stack<double> st3; st3 = st1; stack<double> st4; st4 = st1; REQUIRE(st1.top() == 2); REQUIRE(st3.top() == 2); st3.pop(); REQUIRE(st3.top() == 1); REQUIRE(st4.top() == 2); st4.pop(); REQUIRE(st4.top() == 1); } TEST_CASE("Equal", "[equal]") { stack<int> st1; REQUIRE_NOTHROW(stack<int> st2; st2 = st1); stack<int> st2; st1.push(1); st1.push(4); st2 = st1; REQUIRE(st2.top() == 4); st2.pop(); REQUIRE(st2.top() == 1); } TEST_CASE("Empty", "[empty]") { stack<int> st1; REQUIRE(st1.empty()); st1.push(38); REQUIRE(!st1.empty()); } TEST_CASE("Allocator doesn't (use or need) default ctors", "[allocator]") { class A { public: A() { throw "ctor is called"; } A(int a) { ; } }; REQUIRE_NOTHROW( stack<A> st; st.push(4); st.push(20); ); class B { public: B(int a) { ; } }; stack<B> st; st.push(40); } bool dtor_is_called12 = false; TEST_CASE("Allocator calls dtor when pop", "[allocator_dtor]") { class A { public: A(int a) { //std::cout << "A(int)" << std::endl; } A(const A & a) { //std::cout << "copy constructor is called " << std::endl; } ~A() { dtor_is_called12 = true; } }; stack<A> st; st.push(32); st.pop(); REQUIRE(dtor_is_called12); }
#include "catch.hpp" #include "stack.hpp" stack<int> st; TEST_CASE("Thow threads", "[T]") { std::thread thread1([]() { for (size_t i = 0; i < 100; i++) { st.push(rand()); } }); std::thread thread2([]() { for (size_t i = 0; i < 100;) { if (!st.empty()) { std::cout << st.top() << std::endl; st.pop(); i++; } } }); thread1.join(); thread2.join(); } TEST_CASE("Stack can be instantiated by various types", "[instantiation]") { REQUIRE_NOTHROW(stack<int> st1); REQUIRE_NOTHROW(stack<double> st2); REQUIRE_NOTHROW(stack<char> st3); REQUIRE_NOTHROW(stack<int*> st4); REQUIRE_NOTHROW(stack<stack<int>> st5); } TEST_CASE("Push, pop, top", "[push_pop_top]") { stack<int> st; st.push(1); st.push(2); st.top(); REQUIRE(st.top() == 2); st.pop(); REQUIRE(st.top() == 1); st.pop(); } TEST_CASE("count", "[count]") { stack<int> st; REQUIRE(st.count() == 0); st.push(1); REQUIRE(st.count() == 1); st.push(2); REQUIRE(st.count() == 2); st.pop(); REQUIRE(st.count() == 1); st.pop(); REQUIRE(st.count() == 0); } TEST_CASE("Copy constructor", "[copy_ctr]") { stack<double> st1; st1.push(1); st1.push(2); //REQUIRE_NOTHROW(stack<double> st2 = st1); stack<double> st3; st3 = st1; stack<double> st4; st4 = st1; REQUIRE(st1.top() == 2); REQUIRE(st3.top() == 2); st3.pop(); REQUIRE(st3.top() == 1); REQUIRE(st4.top() == 2); st4.pop(); REQUIRE(st4.top() == 1); } TEST_CASE("Equal", "[equal]") { stack<int> st1; REQUIRE_NOTHROW(stack<int> st2; st2 = st1); stack<int> st2; st1.push(1); st1.push(4); st2 = st1; REQUIRE(st2.top() == 4); st2.pop(); REQUIRE(st2.top() == 1); } TEST_CASE("Empty", "[empty]") { stack<int> st1; REQUIRE(st1.empty()); st1.push(38); REQUIRE(!st1.empty()); } TEST_CASE("Allocator doesn't (use or need) default ctors", "[allocator]") { class A { public: A() { throw "ctor is called"; } A(int a) { ; } }; REQUIRE_NOTHROW( stack<A> st; st.push(4); st.push(20); ); class B { public: B(int a) { ; } }; stack<B> st; st.push(40); } bool dtor_is_called12 = false; TEST_CASE("Allocator calls dtor when pop", "[allocator_dtor]") { class A { public: A(int a) { //std::cout << "A(int)" << std::endl; } A(const A & a) { //std::cout << "copy constructor is called " << std::endl; } ~A() { dtor_is_called12 = true; } }; stack<A> st; st.push(32); st.pop(); REQUIRE(dtor_is_called12); }
Update init.cpp
Update init.cpp
C++
mit
ArtemKokorinStudent/StackW
d31dede6ac6d90b281f223fc1445f414a612a0e0
SCT-Plugin/hooks/weapon_fire.cpp
SCT-Plugin/hooks/weapon_fire.cpp
//Source file for the Weapon Fire hook module. //This hook controls how weapons are fired. #include "weapon_fire.h" #include <SCBW/scbwdata.h> #include <SCBW/enumerations.h> #include <SCBW/api.h> //-------- Helper function declarations. Do NOT modify! ---------// namespace { typedef void (__stdcall *GetWeaponHitPosFunc)(const CUnit *unit, s32 *x, s32 *y); GetWeaponHitPosFunc const getWeaponHitPos = (GetWeaponHitPosFunc) 0x004762C0; void createBullet(u8 weaponId, const CUnit *source, s16 x, s16 y, u8 attackingPlayer, u8 direction); } //unnamed namespace //-------- Actual hook functions --------// namespace hooks { //Fires a weapon from the @p unit. //This hook affects the following iscript opcodes: attackwith, attack, castspell //This also affects CUnit::fireWeapon(). void fireWeaponHook(const CUnit *unit, u8 weaponId) { //Retrieve the spawning position for the bullet. s32 x, y; if (Weapon::Behavior[weaponId] == WeaponBehavior::AppearOnTargetUnit) { if (unit->orderTarget.unit == NULL) return; getWeaponHitPos(unit, &x, &y); } else if (Weapon::Behavior[weaponId] == WeaponBehavior::AppearOnTargetSite) { x = unit->orderTarget.pt.x; y = unit->orderTarget.pt.y; } else { s32 forwardOffset = Weapon::ForwardOffset[weaponId]; x = unit->getX() + (forwardOffset * angleDistance[unit->currentDirection1].x / 256); y = unit->getY() + (forwardOffset * angleDistance[unit->currentDirection1].y / 256) - Weapon::VerticalOffset[weaponId]; } if (Weapon::FlingyId[weaponId]) { u8 bulletDirection = unit->currentDirection1; //Make Vultures and Lurkers always fire at the target direction if (Weapon::Behavior[weaponId] == WeaponBehavior::GoToMaxRange && unit->orderTarget.unit) bulletDirection = scbw::getAngle(unit->getX(), unit->getY(), unit->orderTarget.unit->getX(), unit->orderTarget.unit->getY()); createBullet(weaponId, unit, x, y, unit->playerId, bulletDirection); } } } //hooks //-------- Helper function definitions. Do NOT modify! --------// namespace { const u32 Helper_CreateBullet = 0x0048C260; void createBullet(u8 weaponId, const CUnit *source, s16 x, s16 y, u8 attackingPlayer, u8 direction) { u32 attackingPlayer_ = attackingPlayer, direction_ = direction; s32 x_ = x, y_ = y; __asm { PUSHAD PUSH direction_ PUSH attackingPlayer_ PUSH y_ PUSH x_ MOV EAX, source MOVZX ECX, weaponId CALL Helper_CreateBullet POPAD } } } //unnamed namespace
//Source file for the Weapon Fire hook module. //This hook controls how weapons are fired. #include "weapon_fire.h" #include <SCBW/scbwdata.h> #include <SCBW/enumerations.h> #include <SCBW/api.h> //-------- Helper function declarations. Do NOT modify! ---------// namespace { typedef void (__stdcall *GetWeaponHitPosFunc)(const CUnit *unit, s32 *x, s32 *y); GetWeaponHitPosFunc const getWeaponHitPos = (GetWeaponHitPosFunc) 0x004762C0; void createBullet(u8 weaponId, const CUnit *source, s16 x, s16 y, u8 attackingPlayer, u8 direction); } //unnamed namespace //-------- Actual hook functions --------// namespace hooks { //Fires a weapon from the @p unit. //This hook affects the following iscript opcodes: attackwith, attack, castspell //This also affects CUnit::fireWeapon(). void fireWeaponHook(const CUnit *unit, u8 weaponId) { //Retrieve the spawning position for the bullet. s32 x, y; if (Weapon::Behavior[weaponId] == WeaponBehavior::AppearOnTargetUnit) { if (unit->orderTarget.unit == NULL) return; getWeaponHitPos(unit, &x, &y); } else if (Weapon::Behavior[weaponId] == WeaponBehavior::AppearOnTargetSite) { x = unit->orderTarget.pt.x; y = unit->orderTarget.pt.y; } else { s32 forwardOffset = Weapon::ForwardOffset[weaponId]; x = unit->getX() + (forwardOffset * angleDistance[unit->currentDirection1].x / 256); y = unit->getY() + (forwardOffset * angleDistance[unit->currentDirection1].y / 256) - Weapon::VerticalOffset[weaponId]; } if (Weapon::FlingyId[weaponId]) { u8 bulletDirection = unit->currentDirection1; //Make Vultures and Lurkers always fire at the target direction if (Weapon::Behavior[weaponId] == WeaponBehavior::GoToMaxRange && unit->orderTarget.unit) bulletDirection = scbw::getAngle( unit->orderTarget.unit->getX(), unit->orderTarget.unit->getY(), unit->getX(), unit->getY()); createBullet(weaponId, unit, x, y, unit->playerId, bulletDirection); } } } //hooks //-------- Helper function definitions. Do NOT modify! --------// namespace { const u32 Helper_CreateBullet = 0x0048C260; void createBullet(u8 weaponId, const CUnit *source, s16 x, s16 y, u8 attackingPlayer, u8 direction) { u32 attackingPlayer_ = attackingPlayer, direction_ = direction; s32 x_ = x, y_ = y; __asm { PUSHAD PUSH direction_ PUSH attackingPlayer_ PUSH y_ PUSH x_ MOV EAX, source MOVZX ECX, weaponId CALL Helper_CreateBullet POPAD } } } //unnamed namespace
Fix a silly bug that caused Vultures to fire backwards.
Fix a silly bug that caused Vultures to fire backwards.
C++
isc
xboi209/general-plugin-template-project,SCMapsAndMods/general-plugin-template-project,xboi209/general-plugin-template-project,SCMapsAndMods/general-plugin-template-project
26dc520cc328df44c70afe327a233207e8db3eaf
tests/ft_wallpaperbusinesslogic/ft_wallpaperbusinesslogic.cpp
tests/ft_wallpaperbusinesslogic/ft_wallpaperbusinesslogic.cpp
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of meegotouch-controlpanelapplets. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "ft_wallpaperbusinesslogic.h" #include "wallpaperbusinesslogic.h" #include "wallpapercurrentdescriptor.h" #include "wallpaperitrans.h" #include <QPixmap> #include <MApplication> #include <MGConfItem> #define DEBUG #include "../../src/debug.h" static const QString PortraitKey = "/desktop/meego/background/portrait/picture_filename"; static const QString LandscapeKey = "/desktop/meego/background/landscape/picture_filename"; /****************************************************************************** * SignalSink implementation. */ SignalSink::SignalSink () { reset (); } void SignalSink::reset () { m_WallpaperChangedCame = false; } void SignalSink::wallpaperChanged () { SYS_DEBUG (""); m_WallpaperChangedCame = true; } /****************************************************************************** * Ft_WallpaperBusinessLogic implementation. */ void Ft_WallpaperBusinessLogic::init() { MGConfItem l(LandscapeKey); MGConfItem p(PortraitKey); /* * Unset the gconf keys, in this way schema values will be used */ l.unset (); p.unset (); } void Ft_WallpaperBusinessLogic::cleanup() { } static int argc = 1; static char* app_name = (char*) "./Ft_WallpaperBusinessLogic"; void Ft_WallpaperBusinessLogic::initTestCase() { bool connectSuccess; m_App = new MApplication (argc, &app_name); m_Api = new WallpaperBusinessLogic; connectSuccess = connect ( m_Api, SIGNAL (wallpaperChanged()), &m_SignalSink, SLOT (wallpaperChanged())); QVERIFY (connectSuccess); } void Ft_WallpaperBusinessLogic::cleanupTestCase() { delete m_App; delete m_Api; } void Ft_WallpaperBusinessLogic::testCreateDirectory () { QString path; path = m_Api->dirPath(); m_Api->ensureHasDirectory (); QDir outputDir (path); QVERIFY (outputDir.exists()); } /*! * Gets the list of the available wallpapers, checks if the list is not empty, * then goes through the potential wallpapers and checks if all of them has the * string type data available. These strings (filename, basename, and so on) * should be available for all offered wallpapers. */ void Ft_WallpaperBusinessLogic::testAvailableWallpapers () { QList<WallpaperDescriptor *> availableWallpapers; int n; availableWallpapers = m_Api->availableWallpapers (); /* * There should be at least one available wallpaper, that is the current * wallpaper. */ SYS_DEBUG ("We have %d available wallpapers.", availableWallpapers.size()); QVERIFY (availableWallpapers.size() > 0); n = 0; foreach (WallpaperDescriptor *desc, availableWallpapers) { QString filename, title, basename; QString extension, mimetype; QString suggestedp, suggestedl; QString originalp, originall; QString imageID; filename = desc->filename (); imageID = desc->imageID (); title = desc->title (); basename = desc->basename (); extension = desc->extension (); mimetype = desc->mimeType (); suggestedp = desc->suggestedOutputFilename (M::Portrait); suggestedl = desc->suggestedOutputFilename (M::Landscape); originalp = desc->originalImageFile (M::Portrait); originall = desc->originalImageFile (M::Landscape); if ((filename.isEmpty() && imageID.isEmpty()) || title.isEmpty() || (basename.isEmpty() && imageID.isEmpty()) || (mimetype.isEmpty() && imageID.isEmpty()) || suggestedp.isEmpty() || suggestedl.isEmpty() || (originalp.isEmpty() && imageID.isEmpty()) || (originall.isEmpty() && imageID.isEmpty())) { /* * These might prove usefull in the future, but obviously generate * too much output. */ SYS_DEBUG ("*** available wallpaper #%3d ***", n); SYS_DEBUG ("*** filename = %s", SYS_STR(filename)); SYS_DEBUG ("*** imageID = %s", SYS_STR(imageID)); SYS_DEBUG ("*** title = %s", SYS_STR(title)); SYS_DEBUG ("*** basename = %s", SYS_STR(basename)); SYS_DEBUG ("*** mimetype = %s", SYS_STR(mimetype)); SYS_DEBUG ("*** extension = %s", SYS_STR(extension)); SYS_DEBUG ("*** suggestedp = %s", SYS_STR(suggestedp)); SYS_DEBUG ("*** suggestedl = %s", SYS_STR(suggestedl)); SYS_DEBUG ("*** originalp = %s", SYS_STR(originalp)); SYS_DEBUG ("*** originall = %s", SYS_STR(originall)); } // QVERIFY (!filename.isEmpty() || !imageID.isEmpty()); // QVERIFY (!title.isEmpty()); // QVERIFY (!basename.isEmpty() || !imageID.isEmpty()); // QVERIFY (!mimetype.isEmpty() || !imageID.isEmpty()); // QVERIFY (!suggestedp.isEmpty()); // QVERIFY (!suggestedl.isEmpty()); // QVERIFY (!originalp.isEmpty() || !imageID.isEmpty()); // QVERIFY (!originall.isEmpty() || !imageID.isEmpty()); ++n; } } /*! * Checks if the current wallpaper descriptor is available and it is valid, it * presents all the string type properties. */ void Ft_WallpaperBusinessLogic::testCurrentWallpaper () { WallpaperCurrentDescriptor *desc = WallpaperCurrentDescriptor::instance (); QString filename, title, basename; QString extension, mimetype; QString suggestedp, suggestedl; QString originalp, originall; QString imageID; QVERIFY (desc != 0); filename = desc->filename (); imageID = desc->imageID (); title = desc->title (); basename = desc->basename (); extension = desc->extension (); mimetype = desc->mimeType (); suggestedp = desc->suggestedOutputFilename (M::Portrait); suggestedl = desc->suggestedOutputFilename (M::Landscape); originalp = desc->originalImageFile (M::Portrait); originall = desc->originalImageFile (M::Landscape); if ((filename.isEmpty() && imageID.isEmpty()) || title.isEmpty() || (basename.isEmpty() && imageID.isEmpty()) || (mimetype.isEmpty() && imageID.isEmpty()) || suggestedp.isEmpty() || suggestedl.isEmpty() || (originalp.isEmpty() && imageID.isEmpty()) || (originall.isEmpty() && imageID.isEmpty())) { /* * These might prove usefull in the future, but obviously generate * too much output. */ SYS_DEBUG ("*** Current wallpaper ***"); SYS_DEBUG ("*** filename = %s", SYS_STR(filename)); SYS_DEBUG ("*** imageID = %s", SYS_STR(imageID)); SYS_DEBUG ("*** title = %s", SYS_STR(title)); SYS_DEBUG ("*** basename = %s", SYS_STR(basename)); SYS_DEBUG ("*** mimetype = %s", SYS_STR(mimetype)); SYS_DEBUG ("*** extension = %s", SYS_STR(extension)); SYS_DEBUG ("*** suggestedp = %s", SYS_STR(suggestedp)); SYS_DEBUG ("*** suggestedl = %s", SYS_STR(suggestedl)); SYS_DEBUG ("*** originalp = %s", SYS_STR(originalp)); SYS_DEBUG ("*** originall = %s", SYS_STR(originall)); } // QVERIFY (!filename.isEmpty() || !imageID.isEmpty()); // QVERIFY (!title.isEmpty()); // QVERIFY (!basename.isEmpty() || !imageID.isEmpty()); // QVERIFY (!mimetype.isEmpty() || !imageID.isEmpty()); // QVERIFY (!suggestedp.isEmpty()); // QVERIFY (!suggestedl.isEmpty()); // QVERIFY (!originalp.isEmpty() || !imageID.isEmpty()); // QVERIFY (!originall.isEmpty() || !imageID.isEmpty()); QVERIFY (desc->isCurrent()); QVERIFY (desc->valid()); } /*! * This function will try to find the first available wallpaper that is not the * current wallpaper and will set it with various image transformations. The * saved images will be loaded to test the availablity and the size. */ void Ft_WallpaperBusinessLogic::testSetWallpapert () { WallpaperITrans landscapeITrans; WallpaperITrans portraitITrans; QList<WallpaperDescriptor *> availableWallpapers; int n; availableWallpapers = m_Api->availableWallpapers (); for (n = 0; n < availableWallpapers.size(); ++n) { if (!availableWallpapers[n]->isCurrent()) break; } SYS_DEBUG ("*** n = %d", n); if (n == availableWallpapers.size()) { SYS_WARNING ("Only one image?"); return; } /* * Testing with scale and offset set to the default. */ // FIXME: setExpectedSize? This should not be needed... landscapeITrans.setExpectedSize (QSize(864, 480)); portraitITrans.setExpectedSize (QSize(480, 864)); m_SignalSink.reset (); m_Api->setBackground ( &landscapeITrans, &portraitITrans, availableWallpapers[n]); // Testing if the images are valid and we got a signal about the change. testValidImages (); QVERIFY (m_SignalSink.m_WallpaperChangedCame); /* * Testing with some arbitrary scale and offset images. */ landscapeITrans.setScale (0.3); portraitITrans.setScale (0.2); landscapeITrans.setOffset (QPointF(10, 20)); portraitITrans.setOffset (QPointF(20, 10)); m_SignalSink.reset (); m_Api->setBackground ( &landscapeITrans, &portraitITrans, availableWallpapers[n]); // Testing if the images are valid and we got a signal about the change. testValidImages (); QVERIFY (m_SignalSink.m_WallpaperChangedCame); /* * Also with magnifying and negative offsets. */ landscapeITrans.setScale (1.5); portraitITrans.setScale (1.3); landscapeITrans.setOffset (QPointF(-10, -200)); portraitITrans.setOffset (QPointF(-800, -300)); m_SignalSink.reset (); m_Api->setBackground ( &landscapeITrans, &portraitITrans, availableWallpapers[n]); // Testing if the images are valid and we got a signal about the change. testValidImages (); QVERIFY (m_SignalSink.m_WallpaperChangedCame); } /****************************************************************************** * Private functions. */ /*! * This low level function will check the GConf database, read the image file * names and see if it is possible to load them. If the images can be loaded the * function will test if the image sizes are correct. * * This test function whould be executed whenever the test program sets a new * wallpaper. */ void Ft_WallpaperBusinessLogic::testValidImages () { MGConfItem *landscapeGConfItem; MGConfItem *portraitGConfItem; QString landscapeFile; QString portraitFile; QPixmap pixmap; bool success; landscapeGConfItem = new MGConfItem (LandscapeKey); portraitGConfItem = new MGConfItem (PortraitKey); landscapeFile = landscapeGConfItem->value().toString(); portraitFile = portraitGConfItem->value().toString(); SYS_DEBUG ("*** landscapeFile = %s", SYS_STR(landscapeFile)); SYS_DEBUG ("*** portraitFile = %s", SYS_STR(portraitFile)); QVERIFY (!landscapeFile.isEmpty()); QVERIFY (!portraitFile.isEmpty()); /* * FIXME: Maybe we should test the theme based values also? How? */ if (landscapeFile.startsWith("/")) { success = pixmap.load (landscapeFile); SYS_DEBUG ("*** landscape size = %dx%d", pixmap.width(), pixmap.height()); QVERIFY (success); QVERIFY (pixmap.width() == 864); QVERIFY (pixmap.height() == 480); } if (portraitFile.startsWith("/")) { success = pixmap.load (portraitFile); SYS_DEBUG ("*** portrait size = %dx%d", pixmap.width(), pixmap.height()); QVERIFY (success); QVERIFY (pixmap.width() == 480); QVERIFY (pixmap.height() == 864); } delete landscapeGConfItem; delete portraitGConfItem; } QTEST_APPLESS_MAIN(Ft_WallpaperBusinessLogic)
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of meegotouch-controlpanelapplets. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** ** 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 ** and appearing in the file LICENSE.LGPL included in the packaging ** of this file. ** ****************************************************************************/ #include "ft_wallpaperbusinesslogic.h" #include "wallpaperbusinesslogic.h" #include "wallpapercurrentdescriptor.h" #include "wallpaperitrans.h" #include <QPixmap> #include <MApplication> #include <MGConfItem> #define DEBUG #include "../../src/debug.h" static const QString PortraitKey = "/desktop/meego/background/portrait/picture_filename"; static const QString LandscapeKey = "/desktop/meego/background/landscape/picture_filename"; /****************************************************************************** * SignalSink implementation. */ SignalSink::SignalSink () { reset (); } void SignalSink::reset () { m_WallpaperChangedCame = false; } void SignalSink::wallpaperChanged () { SYS_DEBUG (""); m_WallpaperChangedCame = true; } /****************************************************************************** * Ft_WallpaperBusinessLogic implementation. */ void Ft_WallpaperBusinessLogic::init() { } void Ft_WallpaperBusinessLogic::cleanup() { } static int argc = 1; static char* app_name = (char*) "./Ft_WallpaperBusinessLogic"; void Ft_WallpaperBusinessLogic::initTestCase() { bool connectSuccess; m_App = new MApplication (argc, &app_name); m_Api = new WallpaperBusinessLogic; connectSuccess = connect ( m_Api, SIGNAL (wallpaperChanged()), &m_SignalSink, SLOT (wallpaperChanged())); QVERIFY (connectSuccess); } void Ft_WallpaperBusinessLogic::cleanupTestCase() { delete m_App; delete m_Api; } void Ft_WallpaperBusinessLogic::testCreateDirectory () { QString path; path = m_Api->dirPath(); m_Api->ensureHasDirectory (); QDir outputDir (path); QVERIFY (outputDir.exists()); } /*! * Gets the list of the available wallpapers, checks if the list is not empty, * then goes through the potential wallpapers and checks if all of them has the * string type data available. These strings (filename, basename, and so on) * should be available for all offered wallpapers. */ void Ft_WallpaperBusinessLogic::testAvailableWallpapers () { QList<WallpaperDescriptor *> availableWallpapers; int n; availableWallpapers = m_Api->availableWallpapers (); /* * There should be at least one available wallpaper, that is the current * wallpaper. */ SYS_DEBUG ("We have %d available wallpapers.", availableWallpapers.size()); QVERIFY (availableWallpapers.size() > 0); n = 0; foreach (WallpaperDescriptor *desc, availableWallpapers) { QString filename, title, basename; QString extension, mimetype; QString suggestedp, suggestedl; QString originalp, originall; QString imageID; filename = desc->filename (); imageID = desc->imageID (); title = desc->title (); basename = desc->basename (); extension = desc->extension (); mimetype = desc->mimeType (); suggestedp = desc->suggestedOutputFilename (M::Portrait); suggestedl = desc->suggestedOutputFilename (M::Landscape); originalp = desc->originalImageFile (M::Portrait); originall = desc->originalImageFile (M::Landscape); if ((filename.isEmpty() && imageID.isEmpty()) || title.isEmpty() || (basename.isEmpty() && imageID.isEmpty()) || (mimetype.isEmpty() && imageID.isEmpty()) || suggestedp.isEmpty() || suggestedl.isEmpty() || (originalp.isEmpty() && imageID.isEmpty()) || (originall.isEmpty() && imageID.isEmpty())) { /* * These might prove usefull in the future, but obviously generate * too much output. */ SYS_DEBUG ("*** available wallpaper #%3d ***", n); SYS_DEBUG ("*** filename = %s", SYS_STR(filename)); SYS_DEBUG ("*** imageID = %s", SYS_STR(imageID)); SYS_DEBUG ("*** title = %s", SYS_STR(title)); SYS_DEBUG ("*** basename = %s", SYS_STR(basename)); SYS_DEBUG ("*** mimetype = %s", SYS_STR(mimetype)); SYS_DEBUG ("*** extension = %s", SYS_STR(extension)); SYS_DEBUG ("*** suggestedp = %s", SYS_STR(suggestedp)); SYS_DEBUG ("*** suggestedl = %s", SYS_STR(suggestedl)); SYS_DEBUG ("*** originalp = %s", SYS_STR(originalp)); SYS_DEBUG ("*** originall = %s", SYS_STR(originall)); } // QVERIFY (!filename.isEmpty() || !imageID.isEmpty()); // QVERIFY (!title.isEmpty()); // QVERIFY (!basename.isEmpty() || !imageID.isEmpty()); // QVERIFY (!mimetype.isEmpty() || !imageID.isEmpty()); // QVERIFY (!suggestedp.isEmpty()); // QVERIFY (!suggestedl.isEmpty()); // QVERIFY (!originalp.isEmpty() || !imageID.isEmpty()); // QVERIFY (!originall.isEmpty() || !imageID.isEmpty()); ++n; } } /*! * Checks if the current wallpaper descriptor is available and it is valid, it * presents all the string type properties. */ void Ft_WallpaperBusinessLogic::testCurrentWallpaper () { WallpaperCurrentDescriptor *desc = WallpaperCurrentDescriptor::instance (); QString filename, title, basename; QString extension, mimetype; QString suggestedp, suggestedl; QString originalp, originall; QString imageID; QVERIFY (desc != 0); filename = desc->filename (); imageID = desc->imageID (); title = desc->title (); basename = desc->basename (); extension = desc->extension (); mimetype = desc->mimeType (); suggestedp = desc->suggestedOutputFilename (M::Portrait); suggestedl = desc->suggestedOutputFilename (M::Landscape); originalp = desc->originalImageFile (M::Portrait); originall = desc->originalImageFile (M::Landscape); if ((filename.isEmpty() && imageID.isEmpty()) || title.isEmpty() || (basename.isEmpty() && imageID.isEmpty()) || (mimetype.isEmpty() && imageID.isEmpty()) || suggestedp.isEmpty() || suggestedl.isEmpty() || (originalp.isEmpty() && imageID.isEmpty()) || (originall.isEmpty() && imageID.isEmpty())) { /* * These might prove usefull in the future, but obviously generate * too much output. */ SYS_DEBUG ("*** Current wallpaper ***"); SYS_DEBUG ("*** filename = %s", SYS_STR(filename)); SYS_DEBUG ("*** imageID = %s", SYS_STR(imageID)); SYS_DEBUG ("*** title = %s", SYS_STR(title)); SYS_DEBUG ("*** basename = %s", SYS_STR(basename)); SYS_DEBUG ("*** mimetype = %s", SYS_STR(mimetype)); SYS_DEBUG ("*** extension = %s", SYS_STR(extension)); SYS_DEBUG ("*** suggestedp = %s", SYS_STR(suggestedp)); SYS_DEBUG ("*** suggestedl = %s", SYS_STR(suggestedl)); SYS_DEBUG ("*** originalp = %s", SYS_STR(originalp)); SYS_DEBUG ("*** originall = %s", SYS_STR(originall)); } // QVERIFY (!filename.isEmpty() || !imageID.isEmpty()); // QVERIFY (!title.isEmpty()); // QVERIFY (!basename.isEmpty() || !imageID.isEmpty()); // QVERIFY (!mimetype.isEmpty() || !imageID.isEmpty()); // QVERIFY (!suggestedp.isEmpty()); // QVERIFY (!suggestedl.isEmpty()); // QVERIFY (!originalp.isEmpty() || !imageID.isEmpty()); // QVERIFY (!originall.isEmpty() || !imageID.isEmpty()); QVERIFY (desc->isCurrent()); QVERIFY (desc->valid()); } /*! * This function will try to find the first available wallpaper that is not the * current wallpaper and will set it with various image transformations. The * saved images will be loaded to test the availablity and the size. */ void Ft_WallpaperBusinessLogic::testSetWallpapert () { WallpaperITrans landscapeITrans; WallpaperITrans portraitITrans; QList<WallpaperDescriptor *> availableWallpapers; int n; availableWallpapers = m_Api->availableWallpapers (); for (n = 0; n < availableWallpapers.size(); ++n) { if (!availableWallpapers[n]->isCurrent()) break; } SYS_DEBUG ("*** n = %d", n); if (n == availableWallpapers.size()) { SYS_WARNING ("Only one image?"); return; } /* * Testing with scale and offset set to the default. */ // FIXME: setExpectedSize? This should not be needed... landscapeITrans.setExpectedSize (QSize(864, 480)); portraitITrans.setExpectedSize (QSize(480, 864)); m_SignalSink.reset (); m_Api->setBackground ( &landscapeITrans, &portraitITrans, availableWallpapers[n]); // Testing if the images are valid and we got a signal about the change. testValidImages (); QVERIFY (m_SignalSink.m_WallpaperChangedCame); /* * Testing with some arbitrary scale and offset images. */ landscapeITrans.setScale (0.3); portraitITrans.setScale (0.2); landscapeITrans.setOffset (QPointF(10, 20)); portraitITrans.setOffset (QPointF(20, 10)); m_SignalSink.reset (); m_Api->setBackground ( &landscapeITrans, &portraitITrans, availableWallpapers[n]); // Testing if the images are valid and we got a signal about the change. testValidImages (); QVERIFY (m_SignalSink.m_WallpaperChangedCame); /* * Also with magnifying and negative offsets. */ landscapeITrans.setScale (1.5); portraitITrans.setScale (1.3); landscapeITrans.setOffset (QPointF(-10, -200)); portraitITrans.setOffset (QPointF(-800, -300)); m_SignalSink.reset (); m_Api->setBackground ( &landscapeITrans, &portraitITrans, availableWallpapers[n]); // Testing if the images are valid and we got a signal about the change. testValidImages (); QVERIFY (m_SignalSink.m_WallpaperChangedCame); } /****************************************************************************** * Private functions. */ /*! * This low level function will check the GConf database, read the image file * names and see if it is possible to load them. If the images can be loaded the * function will test if the image sizes are correct. * * This test function whould be executed whenever the test program sets a new * wallpaper. */ void Ft_WallpaperBusinessLogic::testValidImages () { MGConfItem *landscapeGConfItem; MGConfItem *portraitGConfItem; QString landscapeFile; QString portraitFile; QPixmap pixmap; bool success; landscapeGConfItem = new MGConfItem (LandscapeKey); portraitGConfItem = new MGConfItem (PortraitKey); landscapeFile = landscapeGConfItem->value().toString(); portraitFile = portraitGConfItem->value().toString(); SYS_DEBUG ("*** landscapeFile = %s", SYS_STR(landscapeFile)); SYS_DEBUG ("*** portraitFile = %s", SYS_STR(portraitFile)); QVERIFY (!landscapeFile.isEmpty()); QVERIFY (!portraitFile.isEmpty()); /* * FIXME: Maybe we should test the theme based values also? How? */ if (landscapeFile.startsWith("/")) { success = pixmap.load (landscapeFile); SYS_DEBUG ("*** landscape size = %dx%d", pixmap.width(), pixmap.height()); QVERIFY (success); QVERIFY (pixmap.width() == 864); QVERIFY (pixmap.height() == 480); } if (portraitFile.startsWith("/")) { success = pixmap.load (portraitFile); SYS_DEBUG ("*** portrait size = %dx%d", pixmap.width(), pixmap.height()); QVERIFY (success); QVERIFY (pixmap.width() == 480); QVERIFY (pixmap.height() == 864); } delete landscapeGConfItem; delete portraitGConfItem; } QTEST_APPLESS_MAIN(Ft_WallpaperBusinessLogic)
Revert "Changes: a possible fix for ft_wallpaperbusinesslogic"
Revert "Changes: a possible fix for ft_wallpaperbusinesslogic" This reverts commit 2aa70b5d877ff622954457aba82a3b4b12a0baca.
C++
lgpl-2.1
nemomobile-graveyard/meegotouch-controlpanelapplets,deztructor/meegotouch-controlpanelapplets,nemomobile-graveyard/meegotouch-controlpanelapplets,nemomobile-graveyard/meegotouch-controlpanelapplets,deztructor/meegotouch-controlpanelapplets,deztructor/meegotouch-controlpanelapplets
003267a14e8000fdff4d5b34930cc1b25ffe0068
test/run_http_server.cxx
test/run_http_server.cxx
#include "http_server/http_server.hxx" #include "http_server/Request.hxx" #include "http_server/Handler.hxx" #include "http_headers.hxx" #include "duplex.hxx" #include "direct.hxx" #include "istream/sink_null.hxx" #include "istream/istream_byte.hxx" #include "istream/istream_delayed.hxx" #include "istream/istream_head.hxx" #include "istream/istream_hold.hxx" #include "istream/istream_memory.hxx" #include "istream/istream_zero.hxx" #include "istream/istream.hxx" #include "pool.hxx" #include "async.hxx" #include "event/ShutdownListener.hxx" #include "fb_pool.hxx" #include <event.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct context { struct async_operation operation; ShutdownListener shutdown_listener; enum class Mode { MODE_NULL, MIRROR, DUMMY, FIXED, HUGE_, HOLD, } mode; HttpServerConnection *connection; Istream *request_body; struct event timer; context() :shutdown_listener(ShutdownCallback, this) {} static void ShutdownCallback(void *ctx); }; void context::ShutdownCallback(void *ctx) { struct context *c = (struct context *)ctx; http_server_connection_close(c->connection); } static void timer_callback(gcc_unused int fd, gcc_unused short event, void *_ctx) { struct context *ctx = (struct context *)_ctx; http_server_connection_close(ctx->connection); ctx->shutdown_listener.Disable(); } /* * async operation * */ static void my_abort(struct async_operation *ao) { struct context *ctx = (struct context *)ao; if (ctx->request_body != nullptr) ctx->request_body->CloseUnused(); evtimer_del(&ctx->timer); } static const struct async_operation_class my_operation = { .abort = my_abort, }; /* * http_server handler * */ static void my_request(struct http_server_request *request, void *_ctx, struct async_operation_ref *async_ref gcc_unused) { struct context *ctx = (struct context *)_ctx; switch (ctx->mode) { Istream *body; static char data[0x100]; case context::Mode::MODE_NULL: if (request->body != nullptr) sink_null_new(*request->pool, *request->body); http_server_response(request, HTTP_STATUS_NO_CONTENT, HttpHeaders(), nullptr); break; case context::Mode::MIRROR: http_server_response(request, request->body == nullptr ? HTTP_STATUS_NO_CONTENT : HTTP_STATUS_OK, HttpHeaders(), request->body); break; case context::Mode::DUMMY: if (request->body != nullptr) sink_null_new(*request->pool, *request->body); body = istream_head_new(request->pool, *istream_zero_new(request->pool), 256, false); body = istream_byte_new(*request->pool, *body); http_server_response(request, HTTP_STATUS_OK, HttpHeaders(), body); break; case context::Mode::FIXED: if (request->body != nullptr) sink_null_new(*request->pool, *request->body); http_server_response(request, HTTP_STATUS_OK, HttpHeaders(), istream_memory_new(request->pool, data, sizeof(data))); break; case context::Mode::HUGE_: if (request->body != nullptr) sink_null_new(*request->pool, *request->body); http_server_response(request, HTTP_STATUS_OK, HttpHeaders(), istream_head_new(request->pool, *istream_zero_new(request->pool), 512 * 1024, true)); break; case context::Mode::HOLD: ctx->request_body = request->body != nullptr ? istream_hold_new(*request->pool, *request->body) : nullptr; body = istream_delayed_new(request->pool); ctx->operation.Init(my_operation); istream_delayed_async_ref(*body)->Set(ctx->operation); http_server_response(request, HTTP_STATUS_OK, HttpHeaders(), body); static constexpr struct timeval t{0,0}; evtimer_add(&ctx->timer, &t); break; } } static void my_error(GError *error, void *_ctx) { struct context *ctx = (struct context *)_ctx; evtimer_del(&ctx->timer); ctx->shutdown_listener.Disable(); g_printerr("%s\n", error->message); g_error_free(error); } static void my_free(void *_ctx) { struct context *ctx = (struct context *)_ctx; evtimer_del(&ctx->timer); ctx->shutdown_listener.Disable(); } static constexpr HttpServerConnectionHandler handler = { .request = my_request, .log = nullptr, .error = my_error, .free = my_free, }; /* * main * */ int main(int argc, char **argv) { struct context ctx; if (argc != 4) { fprintf(stderr, "Usage: %s INFD OUTFD {null|mirror|dummy|fixed|huge|hold}\n", argv[0]); return EXIT_FAILURE; } int in_fd, out_fd; if (strcmp(argv[1], "accept") == 0) { const int listen_fd = atoi(argv[2]); in_fd = out_fd = accept(listen_fd, nullptr, 0); if (in_fd < 0) { perror("accept() failed"); return EXIT_FAILURE; } } else { in_fd = atoi(argv[1]); out_fd = atoi(argv[2]); } direct_global_init(); struct event_base *event_base = event_init(); fb_pool_init(false); ctx.shutdown_listener.Enable(); evtimer_set(&ctx.timer, timer_callback, &ctx); struct pool *pool = pool_new_libc(nullptr, "root"); int sockfd; if (in_fd != out_fd) { sockfd = duplex_new(pool, in_fd, out_fd); if (sockfd < 0) { perror("duplex_new() failed"); exit(2); } } else sockfd = in_fd; const char *mode = argv[3]; if (strcmp(mode, "null") == 0) ctx.mode = context::Mode::MODE_NULL; else if (strcmp(mode, "mirror") == 0) ctx.mode = context::Mode::MIRROR; else if (strcmp(mode, "dummy") == 0) ctx.mode = context::Mode::DUMMY; else if (strcmp(mode, "fixed") == 0) ctx.mode = context::Mode::FIXED; else if (strcmp(mode, "huge") == 0) ctx.mode = context::Mode::HUGE_; else if (strcmp(mode, "hold") == 0) ctx.mode = context::Mode::HOLD; else { fprintf(stderr, "Unknown mode: %s\n", mode); return EXIT_FAILURE; } http_server_connection_new(pool, sockfd, FdType::FD_SOCKET, nullptr, nullptr, nullptr, nullptr, true, &handler, &ctx, &ctx.connection); event_dispatch(); pool_unref(pool); pool_commit(); pool_recycler_clear(); fb_pool_deinit(); event_base_free(event_base); direct_global_deinit(); return EXIT_SUCCESS; }
#include "http_server/http_server.hxx" #include "http_server/Request.hxx" #include "http_server/Handler.hxx" #include "http_headers.hxx" #include "duplex.hxx" #include "direct.hxx" #include "istream/sink_null.hxx" #include "istream/istream_byte.hxx" #include "istream/istream_delayed.hxx" #include "istream/istream_head.hxx" #include "istream/istream_hold.hxx" #include "istream/istream_memory.hxx" #include "istream/istream_zero.hxx" #include "istream/istream.hxx" #include "pool.hxx" #include "async.hxx" #include "event/TimerEvent.hxx" #include "event/ShutdownListener.hxx" #include "fb_pool.hxx" #include <event.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct context { struct async_operation operation; ShutdownListener shutdown_listener; enum class Mode { MODE_NULL, MIRROR, DUMMY, FIXED, HUGE_, HOLD, } mode; HttpServerConnection *connection; Istream *request_body; TimerEvent timer; context() :shutdown_listener(ShutdownCallback, this) {} static void ShutdownCallback(void *ctx); }; void context::ShutdownCallback(void *ctx) { struct context *c = (struct context *)ctx; http_server_connection_close(c->connection); } static void timer_callback(gcc_unused int fd, gcc_unused short event, void *_ctx) { struct context *ctx = (struct context *)_ctx; http_server_connection_close(ctx->connection); ctx->shutdown_listener.Disable(); } /* * async operation * */ static void my_abort(struct async_operation *ao) { struct context *ctx = (struct context *)ao; if (ctx->request_body != nullptr) ctx->request_body->CloseUnused(); ctx->timer.Cancel(); } static const struct async_operation_class my_operation = { .abort = my_abort, }; /* * http_server handler * */ static void my_request(struct http_server_request *request, void *_ctx, struct async_operation_ref *async_ref gcc_unused) { struct context *ctx = (struct context *)_ctx; switch (ctx->mode) { Istream *body; static char data[0x100]; case context::Mode::MODE_NULL: if (request->body != nullptr) sink_null_new(*request->pool, *request->body); http_server_response(request, HTTP_STATUS_NO_CONTENT, HttpHeaders(), nullptr); break; case context::Mode::MIRROR: http_server_response(request, request->body == nullptr ? HTTP_STATUS_NO_CONTENT : HTTP_STATUS_OK, HttpHeaders(), request->body); break; case context::Mode::DUMMY: if (request->body != nullptr) sink_null_new(*request->pool, *request->body); body = istream_head_new(request->pool, *istream_zero_new(request->pool), 256, false); body = istream_byte_new(*request->pool, *body); http_server_response(request, HTTP_STATUS_OK, HttpHeaders(), body); break; case context::Mode::FIXED: if (request->body != nullptr) sink_null_new(*request->pool, *request->body); http_server_response(request, HTTP_STATUS_OK, HttpHeaders(), istream_memory_new(request->pool, data, sizeof(data))); break; case context::Mode::HUGE_: if (request->body != nullptr) sink_null_new(*request->pool, *request->body); http_server_response(request, HTTP_STATUS_OK, HttpHeaders(), istream_head_new(request->pool, *istream_zero_new(request->pool), 512 * 1024, true)); break; case context::Mode::HOLD: ctx->request_body = request->body != nullptr ? istream_hold_new(*request->pool, *request->body) : nullptr; body = istream_delayed_new(request->pool); ctx->operation.Init(my_operation); istream_delayed_async_ref(*body)->Set(ctx->operation); http_server_response(request, HTTP_STATUS_OK, HttpHeaders(), body); static constexpr struct timeval t{0,0}; ctx->timer.Add(t); break; } } static void my_error(GError *error, void *_ctx) { struct context *ctx = (struct context *)_ctx; ctx->timer.Cancel(); ctx->shutdown_listener.Disable(); g_printerr("%s\n", error->message); g_error_free(error); } static void my_free(void *_ctx) { struct context *ctx = (struct context *)_ctx; ctx->timer.Cancel(); ctx->shutdown_listener.Disable(); } static constexpr HttpServerConnectionHandler handler = { .request = my_request, .log = nullptr, .error = my_error, .free = my_free, }; /* * main * */ int main(int argc, char **argv) { struct context ctx; if (argc != 4) { fprintf(stderr, "Usage: %s INFD OUTFD {null|mirror|dummy|fixed|huge|hold}\n", argv[0]); return EXIT_FAILURE; } int in_fd, out_fd; if (strcmp(argv[1], "accept") == 0) { const int listen_fd = atoi(argv[2]); in_fd = out_fd = accept(listen_fd, nullptr, 0); if (in_fd < 0) { perror("accept() failed"); return EXIT_FAILURE; } } else { in_fd = atoi(argv[1]); out_fd = atoi(argv[2]); } direct_global_init(); struct event_base *event_base = event_init(); fb_pool_init(false); ctx.shutdown_listener.Enable(); ctx.timer.Init(timer_callback, &ctx); struct pool *pool = pool_new_libc(nullptr, "root"); int sockfd; if (in_fd != out_fd) { sockfd = duplex_new(pool, in_fd, out_fd); if (sockfd < 0) { perror("duplex_new() failed"); exit(2); } } else sockfd = in_fd; const char *mode = argv[3]; if (strcmp(mode, "null") == 0) ctx.mode = context::Mode::MODE_NULL; else if (strcmp(mode, "mirror") == 0) ctx.mode = context::Mode::MIRROR; else if (strcmp(mode, "dummy") == 0) ctx.mode = context::Mode::DUMMY; else if (strcmp(mode, "fixed") == 0) ctx.mode = context::Mode::FIXED; else if (strcmp(mode, "huge") == 0) ctx.mode = context::Mode::HUGE_; else if (strcmp(mode, "hold") == 0) ctx.mode = context::Mode::HOLD; else { fprintf(stderr, "Unknown mode: %s\n", mode); return EXIT_FAILURE; } http_server_connection_new(pool, sockfd, FdType::FD_SOCKET, nullptr, nullptr, nullptr, nullptr, true, &handler, &ctx, &ctx.connection); event_dispatch(); pool_unref(pool); pool_commit(); pool_recycler_clear(); fb_pool_deinit(); event_base_free(event_base); direct_global_deinit(); return EXIT_SUCCESS; }
use class TimerEvent
test/run_http_server: use class TimerEvent
C++
bsd-2-clause
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
0341b31a9a483105668996764252abbb72be7749
include/Pomdog/Utility/Assert.hpp
include/Pomdog/Utility/Assert.hpp
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_ASSERT_7D111D58_HPP #define POMDOG_ASSERT_7D111D58_HPP #include "Pomdog/Basic/Platform.hpp" #include <cassert> #if defined(_MSC_VER) #include <xutility> #endif #if defined(linux) || defined(__linux) || defined(__linux__) #include <csignal> #endif namespace Pomdog { namespace Detail { // How to use: // POMDOG_ASSERT(expr); // POMDOG_ASSERT_MESSAGE(expr, "message"); #if defined(DEBUG) && defined(__APPLE_CC__) # // Debug mode under Xcode # define POMDOG_ASSERT(expression) assert(expression) # define POMDOG_ASSERT_MESSAGE(expression, message) \ do {\ if (!(expression)) {\ assert(message && expression);\ }\ } while(false) #elif defined(DEBUG) && defined(_MSC_VER) # // Debug mode under Visual Studio # define POMDOG_ASSERT(expression) \ static_cast<void>((!!(expression)) \ || (_CrtDbgBreak(), _ASSERT(expression), false)) # define POMDOG_ASSERT_MESSAGE(expression, message) \ static_cast<void>((!!(expression)) \ || (1 != _CrtDbgReportW(_CRT_ASSERT, _CRT_WIDE(__FILE__), __LINE__, nullptr, L"%s", message)) \ || (_CrtDbgBreak(), false)) #elif defined(DEBUG) # // Debug mode # if defined(_MSC_VER) # define POMDOG_DEBUGBREAK() __debugbreak() # elif defined(linux) || defined(__linux) || defined(__linux__) # define POMDOG_DEBUGBREAK() raise(SIGTRAP) # elif defined(POMDOG_ARCHITECTURE_POWERPC) # define POMDOG_DEBUGBREAK() asm {trap} # else # define POMDOG_DEBUGBREAK() __asm { int 3 } // MS-style inline assembly # endif # define POMDOG_ASSERT(expression) assert(expression) # define POMDOG_ASSERT_MESSAGE(expression, message) \ do {\ if (!(expression)) {\ assert(message && expression); \ POMDOG_DEBUGBREAK(); \ }\ } while(false) #else # // Release mode # define POMDOG_ASSERT(expression) # define POMDOG_ASSERT_MESSAGE(expression, message) #endif namespace Assertion { inline constexpr bool ConstexprAssert( bool condition, char const* expression) { return (assert(condition), condition); } } // namespace Assertion #if defined(DEBUG) # // Debug mode # define POMDOG_CONSTEXPR_ASSERT(expression) \ static_cast<void>(Pomdog::Detail::Assertion::ConstexprAssert( \ static_cast<bool>(expression), #expression)) #else # // Release mode # define POMDOG_CONSTEXPR_ASSERT(expression) static_cast<void const>(0) #endif } // namespace Detail } // namespace Pomdog #endif // POMDOG_ASSERT_7D111D58_HPP
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_ASSERT_7D111D58_HPP #define POMDOG_ASSERT_7D111D58_HPP #include "Pomdog/Basic/Platform.hpp" #include <cassert> #if defined(_MSC_VER) #include <xutility> #endif #if defined(linux) || defined(__linux) || defined(__linux__) #include <csignal> #endif namespace Pomdog { namespace Detail { // How to use: // POMDOG_ASSERT(expr); // POMDOG_ASSERT_MESSAGE(expr, "message"); #if defined(DEBUG) && defined(__APPLE_CC__) # // Debug mode under Xcode # define POMDOG_ASSERT(expression) assert(expression) # define POMDOG_ASSERT_MESSAGE(expression, message) \ do {\ if (!(expression)) {\ assert(message && expression);\ }\ } while(false) #elif defined(DEBUG) && defined(_MSC_VER) # // Debug mode under Visual Studio # define POMDOG_ASSERT(expression) \ static_cast<void>((!!(expression)) \ || (_CrtDbgBreak(), _ASSERT(expression), false)) # define POMDOG_ASSERT_MESSAGE(expression, message) \ static_cast<void>((!!(expression)) \ || (1 != _CrtDbgReportW(_CRT_ASSERT, _CRT_WIDE(__FILE__), __LINE__, nullptr, L"%s", message)) \ || (_CrtDbgBreak(), false)) #elif defined(DEBUG) # // Debug mode # if defined(_MSC_VER) # define POMDOG_DEBUGBREAK() __debugbreak() # elif defined(linux) || defined(__linux) || defined(__linux__) # define POMDOG_DEBUGBREAK() raise(SIGTRAP) # elif defined(POMDOG_ARCHITECTURE_POWERPC) # define POMDOG_DEBUGBREAK() asm {trap} # else # define POMDOG_DEBUGBREAK() __asm { int 3 } // MS-style inline assembly # endif # define POMDOG_ASSERT(expression) assert(expression) # define POMDOG_ASSERT_MESSAGE(expression, message) \ do {\ if (!(expression)) {\ assert(message && expression); \ POMDOG_DEBUGBREAK(); \ }\ } while(false) #else # // Release mode # define POMDOG_ASSERT(expression) # define POMDOG_ASSERT_MESSAGE(expression, message) #endif #if defined(DEBUG) namespace Assertion { inline constexpr bool ConstexprAssert(bool condition) { return (assert(condition), condition); } } // namespace Assertion # // Debug mode # define POMDOG_CONSTEXPR_ASSERT(expression) \ static_cast<void>(Pomdog::Detail::Assertion::ConstexprAssert( \ static_cast<bool>(expression))) #else # // Release mode # define POMDOG_CONSTEXPR_ASSERT(expression) static_cast<void const>(0) #endif } // namespace Detail } // namespace Pomdog #endif // POMDOG_ASSERT_7D111D58_HPP
Fix compiler warnings on MSVC
Fix compiler warnings on MSVC
C++
mit
mogemimi/pomdog,mogemimi/pomdog,mogemimi/pomdog
0babebbec2a80e3aa29b765e45d3f4fed30bc31f
include/ips4o/cleanup_margins.hpp
include/ips4o/cleanup_margins.hpp
/****************************************************************************** * include/ips4o/cleanup_margins.hpp * * In-place Parallel Super Scalar Samplesort (IPS⁴o) * ****************************************************************************** * BSD 2-Clause License * * Copyright © 2017, Michael Axtmann <[email protected]> * Copyright © 2017, Daniel Ferizovic <[email protected]> * Copyright © 2017, Sascha Witt <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #pragma once #include <limits> #include <utility> #include "ips4o_fwd.hpp" #include "base_case.hpp" #include "memory.hpp" #include "utils.hpp" namespace ips4o { namespace detail { /** * Saves margins at thread boundaries. */ template <class Cfg> std::pair<int, typename Cfg::difference_type> Sorter<Cfg>::saveMargins(int last_bucket) { // Find last bucket boundary in this thread's area diff_t tail = bucket_start_[last_bucket]; const diff_t end = Cfg::alignToNextBlock(tail); // Don't need to do anything if there is no overlap, or we are in the overflow case if (tail == end || end > (end_ - begin_)) return {-1, 0}; // Find bucket this last block belongs to { const auto start_of_last_block = end - Cfg::kBlockSize; diff_t last_start; do { --last_bucket; last_start = bucket_start_[last_bucket]; } while (last_start > start_of_last_block); } // Check if the last block has been written const auto write = shared_->bucket_pointers[last_bucket].getWrite(); if (write < end) return {-1, 0}; // Read excess elements, if necessary tail = bucket_start_[last_bucket + 1]; local_.swap[0].readFrom(begin_ + tail, end - tail); return {last_bucket, end - tail}; } /** * Fills margins from buffers. */ template <class Cfg> template <bool kIsParallel> void Sorter<Cfg>::writeMargins(const int first_bucket, const int last_bucket, const int overflow_bucket, const int swap_bucket, const diff_t in_swap_buffer) { const bool is_last_level = end_ - begin_ <= Cfg::kSingleLevelThreshold; const auto comp = classifier_->getComparator(); for (int i = first_bucket; i < last_bucket; ++i) { // Get bucket information const auto bstart = bucket_start_[i]; const auto bend = bucket_start_[i + 1]; const auto bwrite = bucket_pointers_[i].getWrite(); // Destination where elements can be written auto dst = begin_ + bstart; auto remaining = Cfg::alignToNextBlock(bstart) - bstart; if (i == overflow_bucket && overflow_) { // Is there overflow? // Overflow buffer has been written => write pointer must be at end of bucket IPS4OML_ASSUME_NOT(Cfg::alignToNextBlock(bend) != bwrite); auto src = overflow_->data(); // There must be space for at least BlockSize elements IPS4OML_ASSUME_NOT((bend - (bwrite - Cfg::kBlockSize)) + remaining < Cfg::kBlockSize); auto tail_size = Cfg::kBlockSize - remaining; // Fill head std::move(src, src + remaining, dst); src += remaining; remaining = std::numeric_limits<diff_t>::max(); // Write remaining elements into tail dst = begin_ + bwrite - Cfg::kBlockSize; dst = std::move(src, src + tail_size, dst); overflow_->reset(Cfg::kBlockSize); } else if (i == swap_bucket && in_swap_buffer) { // Did we save this in saveMargins? // Bucket of last block in this thread's area => write swap buffer auto src = local_.swap[0].data(); // All elements from the buffer must fit IPS4OML_ASSUME_NOT(in_swap_buffer > remaining); // Write to head dst = std::move(src, src + in_swap_buffer, dst); remaining -= in_swap_buffer; local_.swap[0].reset(in_swap_buffer); } else if (bwrite > bend && bend - bstart > Cfg::kBlockSize) { // Final block has been written => move excess elements to head IPS4OML_ASSUME_NOT(Cfg::alignToNextBlock(bend) != bwrite); auto src = begin_ + bend; auto head_size = bwrite - bend; // Must fit, no other empty space left IPS4OML_ASSUME_NOT(head_size > remaining); // Write to head dst = std::move(src, src + head_size, dst); remaining -= head_size; } // Write elements from buffers for (int t = 0; t < num_threads_; ++t) { auto& buffers = kIsParallel ? shared_->local[t]->buffers : local_.buffers; auto src = buffers.data(i); auto count = buffers.size(i); if (count <= remaining) { dst = std::move(src, src + count, dst); remaining -= count; } else { std::move(src, src + remaining, dst); src += remaining; count -= remaining; remaining = std::numeric_limits<diff_t>::max(); dst = begin_ + bwrite; dst = std::move(src, src + count, dst); } buffers.reset(i); } // Perform final base case sort here, while the data is still cached if (is_last_level || ((bend - bstart <= 2 * Cfg::kBaseCaseSize) && !kIsParallel)) { #ifdef IPS4O_TIMER g_cleanup.stop(); g_base_case.start(); #endif detail::baseCaseSort(begin_ + bstart, begin_ + bend, comp); #ifdef IPS4O_TIMER g_base_case.stop(); g_cleanup.start(); #endif } } } } // namespace detail } // namespace ips4o
/****************************************************************************** * include/ips4o/cleanup_margins.hpp * * In-place Parallel Super Scalar Samplesort (IPS⁴o) * ****************************************************************************** * BSD 2-Clause License * * Copyright © 2017, Michael Axtmann <[email protected]> * Copyright © 2017, Daniel Ferizovic <[email protected]> * Copyright © 2017, Sascha Witt <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #pragma once #include <limits> #include <utility> #include "ips4o_fwd.hpp" #include "base_case.hpp" #include "memory.hpp" #include "utils.hpp" namespace ips4o { namespace detail { /** * Saves margins at thread boundaries. */ template <class Cfg> std::pair<int, typename Cfg::difference_type> Sorter<Cfg>::saveMargins(int last_bucket) { // Find last bucket boundary in this thread's area diff_t tail = bucket_start_[last_bucket]; const diff_t end = Cfg::alignToNextBlock(tail); // Don't need to do anything if there is no overlap, or we are in the overflow case if (tail == end || end > (end_ - begin_)) return {-1, 0}; // Find bucket this last block belongs to { const auto start_of_last_block = end - Cfg::kBlockSize; diff_t last_start; do { --last_bucket; last_start = bucket_start_[last_bucket]; } while (last_start > start_of_last_block); } // Check if the last block has been written const auto write = shared_->bucket_pointers[last_bucket].getWrite(); if (write < end) return {-1, 0}; // Read excess elements, if necessary tail = bucket_start_[last_bucket + 1]; local_.swap[0].readFrom(begin_ + tail, end - tail); return {last_bucket, end - tail}; } /** * Fills margins from buffers. */ template <class Cfg> template <bool kIsParallel> void Sorter<Cfg>::writeMargins(const int first_bucket, const int last_bucket, const int overflow_bucket, const int swap_bucket, const diff_t in_swap_buffer) { const bool is_last_level = end_ - begin_ <= Cfg::kSingleLevelThreshold; const auto comp = classifier_->getComparator(); for (int i = first_bucket; i < last_bucket; ++i) { // Get bucket information const auto bstart = bucket_start_[i]; const auto bend = bucket_start_[i + 1]; const auto bwrite = bucket_pointers_[i].getWrite(); // Destination where elements can be written auto dst = begin_ + bstart; auto remaining = Cfg::alignToNextBlock(bstart) - bstart; if (i == overflow_bucket && overflow_) { // Is there overflow? // Overflow buffer has been written => write pointer must be at end of bucket IPS4OML_ASSUME_NOT(Cfg::alignToNextBlock(bend) != bwrite); auto src = overflow_->data(); // There must be space for at least BlockSize elements IPS4OML_ASSUME_NOT((bend - (bwrite - Cfg::kBlockSize)) + remaining < Cfg::kBlockSize); auto tail_size = Cfg::kBlockSize - remaining; // Fill head std::move(src, src + remaining, dst); src += remaining; remaining = std::numeric_limits<diff_t>::max(); // Write remaining elements into tail dst = begin_ + (bwrite - Cfg::kBlockSize); dst = std::move(src, src + tail_size, dst); overflow_->reset(Cfg::kBlockSize); } else if (i == swap_bucket && in_swap_buffer) { // Did we save this in saveMargins? // Bucket of last block in this thread's area => write swap buffer auto src = local_.swap[0].data(); // All elements from the buffer must fit IPS4OML_ASSUME_NOT(in_swap_buffer > remaining); // Write to head dst = std::move(src, src + in_swap_buffer, dst); remaining -= in_swap_buffer; local_.swap[0].reset(in_swap_buffer); } else if (bwrite > bend && bend - bstart > Cfg::kBlockSize) { // Final block has been written => move excess elements to head IPS4OML_ASSUME_NOT(Cfg::alignToNextBlock(bend) != bwrite); auto src = begin_ + bend; auto head_size = bwrite - bend; // Must fit, no other empty space left IPS4OML_ASSUME_NOT(head_size > remaining); // Write to head dst = std::move(src, src + head_size, dst); remaining -= head_size; } // Write elements from buffers for (int t = 0; t < num_threads_; ++t) { auto& buffers = kIsParallel ? shared_->local[t]->buffers : local_.buffers; auto src = buffers.data(i); auto count = buffers.size(i); if (count <= remaining) { dst = std::move(src, src + count, dst); remaining -= count; } else { std::move(src, src + remaining, dst); src += remaining; count -= remaining; remaining = std::numeric_limits<diff_t>::max(); dst = begin_ + bwrite; dst = std::move(src, src + count, dst); } buffers.reset(i); } // Perform final base case sort here, while the data is still cached if (is_last_level || ((bend - bstart <= 2 * Cfg::kBaseCaseSize) && !kIsParallel)) { #ifdef IPS4O_TIMER g_cleanup.stop(); g_base_case.start(); #endif detail::baseCaseSort(begin_ + bstart, begin_ + bend, comp); #ifdef IPS4O_TIMER g_base_case.stop(); g_cleanup.start(); #endif } } } } // namespace detail } // namespace ips4o
Add correct parenthesis
Add correct parenthesis
C++
bsd-2-clause
ips4o/ips4o
2cdf6ef38039f90f688545b2e426194389f1a4e3
include/mockturtle/mockturtle.hpp
include/mockturtle/mockturtle.hpp
/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL * * 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. */ /*! \file mockturtle.hpp \brief Main header file for mockturtle \author Mathias Soeken */ #pragma once #include "mockturtle/traits.hpp" #include "mockturtle/io/write_bench.hpp" #include "mockturtle/io/bench_reader.hpp" #include "mockturtle/io/verilog_reader.hpp" #include "mockturtle/io/write_blif.hpp" #include "mockturtle/io/blif_reader.hpp" #include "mockturtle/io/write_dot.hpp" #include "mockturtle/io/write_verilog.hpp" #include "mockturtle/io/pla_reader.hpp" #include "mockturtle/io/aiger_reader.hpp" #include "mockturtle/io/write_dimacs.hpp" #include "mockturtle/algorithms/simulation.hpp" #include "mockturtle/algorithms/xag_resub_withDC.hpp" #include "mockturtle/algorithms/xmg_resub.hpp" #include "mockturtle/algorithms/dont_cares.hpp" #include "mockturtle/algorithms/equivalence_checking.hpp" #include "mockturtle/algorithms/equivalence_classes.hpp" #include "mockturtle/algorithms/extract_linear.hpp" #include "mockturtle/algorithms/lut_mapping.hpp" #include "mockturtle/algorithms/bi_decomposition.hpp" #include "mockturtle/algorithms/cut_rewriting.hpp" #include "mockturtle/algorithms/cut_enumeration/spectr_cut.hpp" #include "mockturtle/algorithms/cut_enumeration/cnf_cut.hpp" #include "mockturtle/algorithms/cut_enumeration/gia_cut.hpp" #include "mockturtle/algorithms/cut_enumeration/mf_cut.hpp" #include "mockturtle/algorithms/cleanup.hpp" #include "mockturtle/algorithms/xag_optimization.hpp" #include "mockturtle/algorithms/xmg_algebraic_rewriting.hpp" #include "mockturtle/algorithms/dsd_decomposition.hpp" #include "mockturtle/algorithms/cnf.hpp" #include "mockturtle/algorithms/miter.hpp" #include "mockturtle/algorithms/collapse_mapped.hpp" #include "mockturtle/algorithms/reconv_cut.hpp" #include "mockturtle/algorithms/refactoring.hpp" #include "mockturtle/algorithms/node_resynthesis/exact.hpp" #include "mockturtle/algorithms/node_resynthesis/shannon.hpp" #include "mockturtle/algorithms/node_resynthesis/mig_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/xmg3_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/bidecomposition.hpp" #include "mockturtle/algorithms/node_resynthesis/akers.hpp" #include "mockturtle/algorithms/node_resynthesis/dsd.hpp" #include "mockturtle/algorithms/node_resynthesis/xmg_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/xag_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/xag_minmc.hpp" #include "mockturtle/algorithms/node_resynthesis/direct.hpp" #include "mockturtle/algorithms/akers_synthesis.hpp" #include "mockturtle/algorithms/gates_to_nodes.hpp" #include "mockturtle/algorithms/satlut_mapping.hpp" #include "mockturtle/algorithms/mig_algebraic_rewriting.hpp" #include "mockturtle/algorithms/xmg_optimization.hpp" #include "mockturtle/algorithms/cut_enumeration.hpp" #include "mockturtle/algorithms/cell_window.hpp" #include "mockturtle/algorithms/decomposition.hpp" #include "mockturtle/algorithms/node_resynthesis.hpp" #include "mockturtle/algorithms/linear_resynthesis.hpp" #include "mockturtle/algorithms/mig_resub.hpp" #include "mockturtle/algorithms/resubstitution.hpp" #include "mockturtle/algorithms/aig_resub.hpp" #include "mockturtle/algorithms/circuit_validator.hpp" #include "mockturtle/algorithms/pattern_generation.hpp" #include "mockturtle/algorithms/functional_reduction.hpp" #include "mockturtle/utils/stopwatch.hpp" #include "mockturtle/utils/index_list.hpp" #include "mockturtle/utils/truth_table_cache.hpp" #include "mockturtle/utils/string_utils.hpp" #include "mockturtle/utils/algorithm.hpp" #include "mockturtle/utils/progress_bar.hpp" #include "mockturtle/utils/mixed_radix.hpp" #include "mockturtle/utils/node_map.hpp" #include "mockturtle/utils/cuts.hpp" #include "mockturtle/networks/aig.hpp" #include "mockturtle/networks/events.hpp" #include "mockturtle/networks/klut.hpp" #include "mockturtle/networks/xmg.hpp" #include "mockturtle/networks/xag.hpp" #include "mockturtle/networks/storage.hpp" #include "mockturtle/networks/mig.hpp" #include "mockturtle/properties/migcost.hpp" #include "mockturtle/properties/mccost.hpp" #include "mockturtle/mockturtle.hpp" #include "mockturtle/generators/sorting.hpp" #include "mockturtle/generators/arithmetic.hpp" #include "mockturtle/generators/control.hpp" #include "mockturtle/generators/majority.hpp" #include "mockturtle/generators/majority_n.hpp" #include "mockturtle/generators/random_logic_generator.hpp" #include "mockturtle/generators/modular_arithmetic.hpp" #include "mockturtle/views/mffc_view.hpp" #include "mockturtle/views/immutable_view.hpp" #include "mockturtle/views/topo_view.hpp" #include "mockturtle/views/window_view.hpp" #include "mockturtle/views/names_view.hpp" #include "mockturtle/views/mapping_view.hpp" #include "mockturtle/views/fanout_view.hpp" #include "mockturtle/views/cut_view.hpp" #include "mockturtle/views/depth_view.hpp"
/* mockturtle: C++ logic network library * Copyright (C) 2018-2019 EPFL * * 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. */ /*! \file mockturtle.hpp \brief Main header file for mockturtle \author Mathias Soeken \author Heinz Riener */ #pragma once #include "mockturtle/traits.hpp" #include "mockturtle/io/aiger_reader.hpp" #include "mockturtle/io/bench_reader.hpp" #include "mockturtle/io/blif_reader.hpp" #include "mockturtle/io/pla_reader.hpp" #include "mockturtle/io/verilog_reader.hpp" #include "mockturtle/io/write_aiger.hpp" #include "mockturtle/io/write_bench.hpp" #include "mockturtle/io/write_blif.hpp" #include "mockturtle/io/write_dimacs.hpp" #include "mockturtle/io/write_dot.hpp" #include "mockturtle/io/write_verilog.hpp" #include "mockturtle/algorithms/simulation.hpp" #include "mockturtle/algorithms/xag_resub_withDC.hpp" #include "mockturtle/algorithms/xmg_resub.hpp" #include "mockturtle/algorithms/dont_cares.hpp" #include "mockturtle/algorithms/equivalence_checking.hpp" #include "mockturtle/algorithms/equivalence_classes.hpp" #include "mockturtle/algorithms/extract_linear.hpp" #include "mockturtle/algorithms/lut_mapping.hpp" #include "mockturtle/algorithms/bi_decomposition.hpp" #include "mockturtle/algorithms/cut_rewriting.hpp" #include "mockturtle/algorithms/cut_enumeration/spectr_cut.hpp" #include "mockturtle/algorithms/cut_enumeration/cnf_cut.hpp" #include "mockturtle/algorithms/cut_enumeration/gia_cut.hpp" #include "mockturtle/algorithms/cut_enumeration/mf_cut.hpp" #include "mockturtle/algorithms/cleanup.hpp" #include "mockturtle/algorithms/xag_optimization.hpp" #include "mockturtle/algorithms/xmg_algebraic_rewriting.hpp" #include "mockturtle/algorithms/dsd_decomposition.hpp" #include "mockturtle/algorithms/cnf.hpp" #include "mockturtle/algorithms/miter.hpp" #include "mockturtle/algorithms/collapse_mapped.hpp" #include "mockturtle/algorithms/reconv_cut.hpp" #include "mockturtle/algorithms/refactoring.hpp" #include "mockturtle/algorithms/node_resynthesis/exact.hpp" #include "mockturtle/algorithms/node_resynthesis/shannon.hpp" #include "mockturtle/algorithms/node_resynthesis/mig_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/xmg3_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/bidecomposition.hpp" #include "mockturtle/algorithms/node_resynthesis/akers.hpp" #include "mockturtle/algorithms/node_resynthesis/dsd.hpp" #include "mockturtle/algorithms/node_resynthesis/xmg_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/xag_npn.hpp" #include "mockturtle/algorithms/node_resynthesis/xag_minmc.hpp" #include "mockturtle/algorithms/node_resynthesis/direct.hpp" #include "mockturtle/algorithms/akers_synthesis.hpp" #include "mockturtle/algorithms/gates_to_nodes.hpp" #include "mockturtle/algorithms/satlut_mapping.hpp" #include "mockturtle/algorithms/mig_algebraic_rewriting.hpp" #include "mockturtle/algorithms/xmg_optimization.hpp" #include "mockturtle/algorithms/cut_enumeration.hpp" #include "mockturtle/algorithms/cell_window.hpp" #include "mockturtle/algorithms/decomposition.hpp" #include "mockturtle/algorithms/node_resynthesis.hpp" #include "mockturtle/algorithms/linear_resynthesis.hpp" #include "mockturtle/algorithms/mig_resub.hpp" #include "mockturtle/algorithms/resubstitution.hpp" #include "mockturtle/algorithms/aig_resub.hpp" #include "mockturtle/algorithms/circuit_validator.hpp" #include "mockturtle/algorithms/pattern_generation.hpp" #include "mockturtle/algorithms/functional_reduction.hpp" #include "mockturtle/utils/stopwatch.hpp" #include "mockturtle/utils/index_list.hpp" #include "mockturtle/utils/truth_table_cache.hpp" #include "mockturtle/utils/string_utils.hpp" #include "mockturtle/utils/algorithm.hpp" #include "mockturtle/utils/progress_bar.hpp" #include "mockturtle/utils/mixed_radix.hpp" #include "mockturtle/utils/node_map.hpp" #include "mockturtle/utils/cuts.hpp" #include "mockturtle/networks/aig.hpp" #include "mockturtle/networks/events.hpp" #include "mockturtle/networks/klut.hpp" #include "mockturtle/networks/xmg.hpp" #include "mockturtle/networks/xag.hpp" #include "mockturtle/networks/storage.hpp" #include "mockturtle/networks/mig.hpp" #include "mockturtle/properties/migcost.hpp" #include "mockturtle/properties/mccost.hpp" #include "mockturtle/mockturtle.hpp" #include "mockturtle/generators/sorting.hpp" #include "mockturtle/generators/arithmetic.hpp" #include "mockturtle/generators/control.hpp" #include "mockturtle/generators/majority.hpp" #include "mockturtle/generators/majority_n.hpp" #include "mockturtle/generators/random_logic_generator.hpp" #include "mockturtle/generators/modular_arithmetic.hpp" #include "mockturtle/views/mffc_view.hpp" #include "mockturtle/views/immutable_view.hpp" #include "mockturtle/views/topo_view.hpp" #include "mockturtle/views/window_view.hpp" #include "mockturtle/views/names_view.hpp" #include "mockturtle/views/mapping_view.hpp" #include "mockturtle/views/fanout_view.hpp" #include "mockturtle/views/cut_view.hpp" #include "mockturtle/views/depth_view.hpp"
add `write_aiger.hpp` to `mockturtle.hpp`.
add `write_aiger.hpp` to `mockturtle.hpp`.
C++
mit
lsils/mockturtle,lsils/mockturtle,lsils/mockturtle,lsils/mockturtle
8bf29d37da747108d9c51f75491a2649e6060aa5
include/resplunk/event/Events.hpp
include/resplunk/event/Events.hpp
#ifndef resplunk_event_Events_HeaderPlusPlus #define resplunk_event_Events_HeaderPlusPlus #include "resplunk/util/TMP.hpp" #include <cstdint> #include <limits> #include <type_traits> #include <functional> #include <memory> #include <map> namespace resplunk { namespace event { struct Event; struct ListenerPriority final { using Priority_t = std::intmax_t; static constexpr Priority_t FIRST = std::numeric_limits<Priority_t>::min(); static constexpr Priority_t LAST = std::numeric_limits<Priority_t>::max(); constexpr ListenerPriority() noexcept : priority{} { } constexpr ListenerPriority(Priority_t p) noexcept : priority{p} { } constexpr ListenerPriority(ListenerPriority const &) = default; ListenerPriority &operator=(ListenerPriority const &) = delete; constexpr ListenerPriority(ListenerPriority &&) = default; ListenerPriority &operator=(ListenerPriority &&) = delete; constexpr operator Priority_t() const noexcept { return priority; } friend constexpr bool operator==(ListenerPriority const &a, ListenerPriority const &b) noexcept { return a.priority == b.priority; } friend constexpr bool operator<(ListenerPriority const &a, ListenerPriority const &b) noexcept { return a.priority < b.priority; } private: Priority_t const priority; }; struct ProcessorBase { virtual ~ProcessorBase() = 0; }; inline ProcessorBase::~ProcessorBase() = default; template<typename EventT> struct Processor : virtual ProcessorBase { static_assert(std::is_base_of<Event, EventT>::value, "EventT must derive from Event"); using Event_t = EventT; Processor(ListenerPriority priority = ListenerPriority{}) noexcept { listen(priority); } Processor(Processor const &) = delete; Processor &operator=(Processor const &) = delete; Processor(Processor &&) = delete; Processor &operator=(Processor &&) = delete; virtual ~Processor() noexcept { ignore(); } protected: void listen(ListenerPriority priority = ListenerPriority{}) noexcept { return Event_t::listen(*this, priority); } void ignore() noexcept { return Event_t::ignore(*this); } private: virtual void process(Event_t &e) const noexcept = 0; friend typename Event_t::Registrar_t; }; template<typename EventT> struct LambdaProcessor : Processor<EventT> { using Lambda_t = std::function<void (EventT &e) /*const*/>; LambdaProcessor(Lambda_t l, ListenerPriority priority = ListenerPriority{}) noexcept : Processor<EventT>(priority) , lambda{l} { } LambdaProcessor(LambdaProcessor &&from) : lambda{std::move(from.lambda)} { } private: Lambda_t lambda; virtual void process(EventT &e) const noexcept override { return lambda(e); } }; struct ReactorBase { virtual ~ReactorBase() = 0; }; inline ReactorBase::~ReactorBase() = default; template<typename EventT> struct Reactor : virtual ReactorBase { static_assert(std::is_base_of<Event, EventT>::value, "EventT must derive from Event"); using Event_t = EventT; Reactor(ListenerPriority priority = ListenerPriority{}) noexcept { listen(priority); } Reactor(Reactor const &) = delete; Reactor &operator=(Reactor const &) = delete; Reactor(Reactor &&) = delete; Reactor &operator=(Reactor &&) = delete; virtual ~Reactor() noexcept { ignore(); } protected: void listen(ListenerPriority priority = ListenerPriority{}) noexcept { return Event_t::listen(*this, priority); } void ignore() noexcept { return Event_t::ignore(*this); } private: virtual void react(Event_t const &e) noexcept = 0; friend typename Event_t::Registrar_t; }; template<typename EventT> struct LambdaReactor : Reactor<EventT> { using Lambda_t = std::function<void (EventT const &e)>; LambdaReactor(Lambda_t l, ListenerPriority priority = ListenerPriority{}) : Reactor<EventT>(priority) noexcept , lambda{l} { } LambdaReactor(LambdaReactor &&from) : lambda{std::move(from.lambda)} { } private: Lambda_t lambda; virtual void react(EventT const &e) noexcept override { return lambda(e); } }; template<typename EventT> struct Registrar final { static_assert(std::is_base_of<Event, EventT>::value, "EventT must derive from Event"); using Event_t = EventT; using Processor_t = Processor<EventT>; using Reactor_t = Reactor<EventT>; static void listen(Processor_t const &p, ListenerPriority priority = ListenerPriority{}) noexcept { ignore(p); processors().emplace(priority, std::cref(p)); } static void listen(Reactor_t &r, ListenerPriority priority = ListenerPriority{}) noexcept { ignore(r); reactors().emplace(priority, std::ref(r)); } static void ignore(Processor_t const &p) noexcept { auto &procs = processors(); for(auto it = procs.begin(); it != procs.end(); ) { if(std::addressof(p) == std::addressof(it->second.get())) { it = procs.erase(it); } else ++it; } } static void ignore(Reactor_t &r) noexcept { auto &reacts = reactors(); for(auto it = reacts.begin(); it != reacts.end(); ) { if(std::addressof(r) == std::addressof(it->second.get())) { it = reacts.erase(it); } else ++it; } } static void process(Event_t &e) noexcept { for(p : processors()) { if(e.should_process(p.second.get())) { p.second.get().process(e); } } } static void react(Event_t const &e) noexcept { for(r : reactors()) { if(e.should_react(r.second.get())) { r.second.get().react(e); } } } private: friend typename Event_t::Implementor_t; Registrar() = default; using Processors_t = std::multimap<ListenerPriority, std::reference_wrapper<Processor_t const>>; using Reactors_t = std::multimap<ListenerPriority, std::reference_wrapper<Reactor_t>>; Processors_t ps; Reactors_t rs; static auto processors() noexcept -> Processors_t & { return Event_t::registrar().ps; } static auto reactors() noexcept -> Reactors_t & { return Event_t::registrar().rs; } }; namespace impl { template<typename T, typename...> struct Unwrapper; template<typename T, typename First, typename... Rest> struct Unwrapper<T, First, Rest...> final { static_assert(std::is_base_of<Event, First>::value, "ParentT must derive from Event"); using Next = Unwrapper<T, Rest...>; Unwrapper() = delete; static void process(T &t) noexcept { First::Registrar_t::process(t); Next::process(t); } static void react(T const &t) noexcept { First::Registrar_t::react(t); Next::react(t); } static auto parents(T &t) noexcept { return tuple_cat(std::tuple<First &>{t}, Next::parents(t)); } static auto parents(T const &t) noexcept { return tuple_cat(std::tuple<First const &>{t}, Next::parents(t)); } using all_parents_t = typename util::tuple_type_cat < typename First::Unwrapper_t::all_parents_t, typename Rest::Unwrapper_t::all_parents_t..., std::tuple<First>, typename Next::all_parents_t >::type; }; template<typename T> struct Unwrapper<T> final { static_assert(std::is_base_of<Event, typename T::Event_t>::value, "Only Event can be root"); Unwrapper() = delete; static void process(T &t) noexcept { T::Registrar_t::process(dynamic_cast<typename T::Event_t &>(t)); } static void react(T const &t) noexcept { T::Registrar_t::react(dynamic_cast<typename T::Event_t const &>(t)); } static auto parents(T &t) noexcept -> std::tuple<> { return {}; } static auto parents(T const &t) noexcept -> std::tuple<> { return {}; } using all_parents_t = std::tuple<>; }; struct PR { virtual ~PR() noexcept = default; virtual void process() noexcept = 0; virtual void react() const noexcept = 0; }; } template<typename EventT, typename... ParentT> struct Implementor : virtual impl::PR , virtual ParentT... { using Unwrapper_t = impl::Unwrapper<Implementor, ParentT...>; using Event_t = EventT; using Parents_t = std::tuple<ParentT &...>; using ConstParents_t = std::tuple<ParentT const &...>; using Implementor_t = Implementor; using Processor_t = Processor<EventT>; using Reactor_t = Reactor<EventT>; using Registrar_t = Registrar<EventT>; static constexpr bool MI = (sizeof...(ParentT) > 1); static constexpr bool ROOT = (sizeof...(ParentT) == 0); virtual ~Implementor() = 0; static void listen(Processor_t const &p, ListenerPriority priority = ListenerPriority{}) noexcept { return Registrar_t::listen(p, priority); } static void listen(Reactor_t &r, ListenerPriority priority = ListenerPriority{}) noexcept { return Registrar_t::listen(r, priority); } static void ignore(Processor_t const &p) noexcept { return Registrar_t::ignore(p); } static void ignore(Reactor_t &r) noexcept { return Registrar_t::ignore(r); } virtual void process() noexcept override { util::tuple_template_forward < impl::Unwrapper, typename util::tuple_type_cat < std::tuple<Implementor_t>, typename util::tuple_prune < typename Unwrapper_t::all_parents_t >::type >::type >::type::process(*this); } virtual void react() const noexcept override { util::tuple_template_forward < impl::Unwrapper, typename util::tuple_type_cat < std::tuple<Implementor_t>, typename util::tuple_prune < typename Unwrapper_t::all_parents_t >::type >::type >::type::react(*this); } private: friend Event_t; Implementor() = default; friend Registrar_t; static Registrar_t &registrar() noexcept; }; template<typename EventT, typename... ParentT> Implementor<EventT, ParentT...>::~Implementor<EventT, ParentT...>() = default; template<typename EventT, typename... ParentT> auto parents(Implementor<EventT, ParentT...> &e) noexcept -> typename std::remove_reference<decltype(e)>::type::Parents_t { return std::remove_reference<decltype(e)>::type::Unwrapper_t::parents(e); } template<typename EventT, typename... ParentT> auto parents(Implementor<EventT, ParentT...> const &e) noexcept -> typename std::remove_reference<decltype(e)>::type::ConstParents_t { return std::remove_reference<decltype(e)>::type::Unwrapper_t::parents(e); } } } #define RESPLUNK_EVENT(n) \ template<> \ auto ::n::Implementor_t::registrar() noexcept \ -> Registrar_t & \ { \ static Registrar_t r;\ return r;\ } #endif
#ifndef resplunk_event_Events_HeaderPlusPlus #define resplunk_event_Events_HeaderPlusPlus #include "resplunk/util/TMP.hpp" #include <cstdint> #include <limits> #include <type_traits> #include <functional> #include <memory> #include <map> namespace resplunk { namespace event { struct Event; struct ListenerPriority final { using Priority_t = std::intmax_t; static constexpr Priority_t FIRST = std::numeric_limits<Priority_t>::min(); static constexpr Priority_t LAST = std::numeric_limits<Priority_t>::max(); constexpr ListenerPriority() noexcept : priority{} { } constexpr ListenerPriority(Priority_t p) noexcept : priority{p} { } constexpr ListenerPriority(ListenerPriority const &) = default; ListenerPriority &operator=(ListenerPriority const &) = delete; constexpr ListenerPriority(ListenerPriority &&) = default; ListenerPriority &operator=(ListenerPriority &&) = delete; constexpr operator Priority_t() const noexcept { return priority; } friend constexpr bool operator==(ListenerPriority const &a, ListenerPriority const &b) noexcept { return a.priority == b.priority; } friend constexpr bool operator<(ListenerPriority const &a, ListenerPriority const &b) noexcept { return a.priority < b.priority; } private: Priority_t const priority; }; struct ProcessorBase { virtual ~ProcessorBase() = 0; }; inline ProcessorBase::~ProcessorBase() = default; template<typename EventT> struct Processor : virtual ProcessorBase { static_assert(std::is_base_of<Event, EventT>::value, "EventT must derive from Event"); using Event_t = EventT; Processor(ListenerPriority priority = ListenerPriority{}) noexcept { listen(priority); } Processor(Processor const &) = delete; Processor &operator=(Processor const &) = delete; Processor(Processor &&) = delete; Processor &operator=(Processor &&) = delete; virtual ~Processor() noexcept { ignore(); } protected: void listen(ListenerPriority priority = ListenerPriority{}) noexcept { return Event_t::listen(*this, priority); } void ignore() noexcept { return Event_t::ignore(*this); } private: virtual void process(Event_t &e) const noexcept = 0; friend typename Event_t::Registrar_t; }; template<typename EventT> struct LambdaProcessor : Processor<EventT> { using Lambda_t = std::function<void (EventT &e) /*const*/>; LambdaProcessor(Lambda_t l, ListenerPriority priority = ListenerPriority{}) noexcept : Processor<EventT>(priority) , lambda{l} { } LambdaProcessor(LambdaProcessor &&from) : lambda{std::move(from.lambda)} { } private: Lambda_t lambda; virtual void process(EventT &e) const noexcept override { return lambda(e); } }; struct ReactorBase { virtual ~ReactorBase() = 0; }; inline ReactorBase::~ReactorBase() = default; template<typename EventT> struct Reactor : virtual ReactorBase { static_assert(std::is_base_of<Event, EventT>::value, "EventT must derive from Event"); using Event_t = EventT; Reactor(ListenerPriority priority = ListenerPriority{}) noexcept { listen(priority); } Reactor(Reactor const &) = delete; Reactor &operator=(Reactor const &) = delete; Reactor(Reactor &&) = delete; Reactor &operator=(Reactor &&) = delete; virtual ~Reactor() noexcept { ignore(); } protected: void listen(ListenerPriority priority = ListenerPriority{}) noexcept { return Event_t::listen(*this, priority); } void ignore() noexcept { return Event_t::ignore(*this); } private: virtual void react(Event_t const &e) noexcept = 0; friend typename Event_t::Registrar_t; }; template<typename EventT> struct LambdaReactor : Reactor<EventT> { using Lambda_t = std::function<void (EventT const &e)>; LambdaReactor(Lambda_t l, ListenerPriority priority = ListenerPriority{}) : Reactor<EventT>(priority) noexcept , lambda{l} { } LambdaReactor(LambdaReactor &&from) : lambda{std::move(from.lambda)} { } private: Lambda_t lambda; virtual void react(EventT const &e) noexcept override { return lambda(e); } }; template<typename EventT> struct Registrar final { static_assert(std::is_base_of<Event, EventT>::value, "EventT must derive from Event"); using Event_t = EventT; using Processor_t = Processor<EventT>; using Reactor_t = Reactor<EventT>; static void listen(Processor_t const &p, ListenerPriority priority = ListenerPriority{}) noexcept { ignore(p); processors().emplace(priority, std::cref(p)); } static void listen(Reactor_t &r, ListenerPriority priority = ListenerPriority{}) noexcept { ignore(r); reactors().emplace(priority, std::ref(r)); } static void ignore(Processor_t const &p) noexcept { auto &procs = processors(); for(auto it = procs.begin(); it != procs.end(); ) { if(std::addressof(p) == std::addressof(it->second.get())) { it = procs.erase(it); } else ++it; } } static void ignore(Reactor_t &r) noexcept { auto &reacts = reactors(); for(auto it = reacts.begin(); it != reacts.end(); ) { if(std::addressof(r) == std::addressof(it->second.get())) { it = reacts.erase(it); } else ++it; } } static void process(Event_t &e) noexcept { for(p : processors()) { if(e.should_process(p.second.get())) { p.second.get().process(e); } } } static void react(Event_t const &e) noexcept { for(r : reactors()) { if(e.should_react(r.second.get())) { r.second.get().react(e); } } } private: friend typename Event_t::Implementor_t; Registrar() = default; using Processors_t = std::multimap<ListenerPriority, std::reference_wrapper<Processor_t const>>; using Reactors_t = std::multimap<ListenerPriority, std::reference_wrapper<Reactor_t>>; Processors_t ps; Reactors_t rs; static auto processors() noexcept -> Processors_t & { return Event_t::registrar().ps; } static auto reactors() noexcept -> Reactors_t & { return Event_t::registrar().rs; } }; namespace impl { template<typename T, typename...> struct Unwrapper; template<typename T, typename First, typename... Rest> struct Unwrapper<T, First, Rest...> final { static_assert(std::is_base_of<Event, First>::value, "ParentT must derive from Event"); using Next = Unwrapper<T, Rest...>; Unwrapper() = delete; static void process(T &t) noexcept { First::Registrar_t::process(t); Next::process(t); } static void react(T const &t) noexcept { First::Registrar_t::react(t); Next::react(t); } static auto parents(T &t) noexcept { return tuple_cat(std::tuple<First &>{t}, Next::parents(t)); } static auto parents(T const &t) noexcept { return tuple_cat(std::tuple<First const &>{t}, Next::parents(t)); } using all_parents_t = typename util::tuple_type_cat < typename First::Unwrapper_t::all_parents_t, typename Rest::Unwrapper_t::all_parents_t..., std::tuple<First>, typename Next::all_parents_t >::type; }; template<typename T> struct Unwrapper<T> final { static_assert(std::is_base_of<Event, typename T::Event_t>::value, "Only Event can be root"); Unwrapper() = delete; static void process(T &t) noexcept { T::Registrar_t::process(dynamic_cast<typename T::Event_t &>(t)); } static void react(T const &t) noexcept { T::Registrar_t::react(dynamic_cast<typename T::Event_t const &>(t)); } static auto parents(T &t) noexcept -> std::tuple<> { return {}; } static auto parents(T const &t) noexcept -> std::tuple<> { return {}; } using all_parents_t = std::tuple<>; }; struct PR { virtual ~PR() noexcept = default; virtual void process() noexcept = 0; virtual void react() const noexcept = 0; }; } template<typename EventT, typename... ParentT> struct Implementor : virtual impl::PR , virtual ParentT... { using Unwrapper_t = impl::Unwrapper<Implementor, ParentT...>; using Event_t = EventT; using Parents_t = std::tuple<ParentT &...>; using ConstParents_t = std::tuple<ParentT const &...>; using Implementor_t = Implementor; using Processor_t = Processor<EventT>; using Reactor_t = Reactor<EventT>; using Registrar_t = Registrar<EventT>; static constexpr bool MI = (sizeof...(ParentT) > 1); static constexpr bool ROOT = (sizeof...(ParentT) == 0); virtual ~Implementor() = 0; static void listen(Processor_t const &p, ListenerPriority priority = ListenerPriority{}) noexcept { return Registrar_t::listen(p, priority); } static void listen(Reactor_t &r, ListenerPriority priority = ListenerPriority{}) noexcept { return Registrar_t::listen(r, priority); } static void ignore(Processor_t const &p) noexcept { return Registrar_t::ignore(p); } static void ignore(Reactor_t &r) noexcept { return Registrar_t::ignore(r); } virtual void process() noexcept override { util::tuple_template_forward < impl::Unwrapper, typename util::tuple_type_cat < std::tuple<Implementor_t>, typename util::tuple_prune < typename Unwrapper_t::all_parents_t >::type >::type >::type::process(*this); } virtual void react() const noexcept override { util::tuple_template_forward < impl::Unwrapper, typename util::tuple_type_cat < std::tuple<Implementor_t>, typename util::tuple_prune < typename Unwrapper_t::all_parents_t >::type >::type >::type::react(*this); } private: friend Event_t; Implementor() = default; friend Registrar_t; static Registrar_t &registrar() noexcept; }; template<typename EventT, typename... ParentT> Implementor<EventT, ParentT...>::~Implementor<EventT, ParentT...>() = default; template<typename EventT, typename... ParentT> auto parents(Implementor<EventT, ParentT...> &e) noexcept -> typename std::remove_reference<decltype(e)>::type::Parents_t { return std::remove_reference<decltype(e)>::type::Unwrapper_t::parents(e); } template<typename EventT, typename... ParentT> auto parents(Implementor<EventT, ParentT...> const &e) noexcept -> typename std::remove_reference<decltype(e)>::type::ConstParents_t { return std::remove_reference<decltype(e)>::type::Unwrapper_t::parents(e); } } } //Necessary evil is necessary #define RESPLUNK_EVENT(E) \ template<> \ auto ::E::Implementor_t::registrar() noexcept \ -> Registrar_t & \ { \ static Registrar_t r; \ return r; \ } \ //https://github.com/LB--/resplunk/wiki/Event-Handling#the-ugly-part #endif
Comment the macro
Comment the macro
C++
unlicense
LB--/resplunk
6631d35405bf77b2ec1474c5af062d82b509ead6
include/vsmc/utility/progress.hpp
include/vsmc/utility/progress.hpp
//============================================================================ // include/vsmc/utility/progress.hpp //---------------------------------------------------------------------------- // // vSMC: Scalable Monte Carlo // // This file is distribured under the 2-clauses BSD License. // See LICENSE for details. //============================================================================ #ifndef VSMC_UTILITY_PROGRESS_HPP #define VSMC_UTILITY_PROGRESS_HPP #include <vsmc/internal/common.hpp> #include <vsmc/utility/stop_watch.hpp> #include <iostream> #include <string> namespace vsmc { /// \brief Display a progress bar while algorithm proceed /// \ingroup Progress /// /// \tparam ThreadType Any type that (partially) follows C++11 `std::thread` /// interface. In particular, the following calls shal be supported, /// ~~~{.cpp} /// void (task *) (void *); // A function pointer /// void *context; // A void pointer /// ThreadType *thread_ptr_ = new ThreadType(task, context); /// thread_ptr_->joinable(); /// thread_ptr_->join(); /// delete thread_ptr_; /// ~~~ /// \tparam ThisThread This shall be a class that provides a `sleep` static /// member function that allows the calling thread to sleep for a specified /// time in seconds. A simple implementation using C++11 `sleep_for` is as the /// following, /// ~~~{.cpp} /// struct ThisThread /// { /// static void sleep (double s) /// { /// // Make the interval acurate to milliseconds /// double ms = std::max(1.0, std::floor(s * 1000)); /// std::this_thread::sleep_for(std::chrono::milliseconds( /// static_cast<std::chrono::milliseconds::rep>(ms))); /// } /// }; /// ~~~ /// An implementation using Boost is almost the same except for the namespace /// changing from `std` to `boost`. template <typename ThreadType, typename ThisThread> class Progress { public : typedef ThreadType thread_type; /// \brief Construct a Progress with an output stream Progress (std::ostream &os = std::cout) : thread_ptr_(VSMC_NULLPTR), iter_(0), total_(0), interval_(0), print_first_(true), in_progress_(false), num_equal_(0), percent_(0), seconds_(0), last_iter_(0), display_progress_(), display_percent_(), display_time_(), display_iter_(), os_(os) {} /// \brief Start to print the progress /// /// \param total Total amount of work represented by an integer, for /// example file size or SMC algorithm total number of iterations /// \param message A (short) discreptive message /// \param interval The sleep interval in seconds void start (unsigned total, const std::string &message = std::string(), double interval = 0.1) { iter_ = 0; total_ = total; interval_ = interval; print_first_ = true; in_progress_ = true; message_ = message; watch_.reset(); watch_.start(); fork(); } /// \brief Stop to print the progress /// /// \param finished If true, then it is assumed that all work has been /// finished, and at the end the progress will be shown as `100%` and /// `total/total`, where total is the first parameter of `start`. /// Otherwise, whatever progress has been made will be shown. void stop (bool finished = false) { in_progress_ = false; join(); if (finished && iter_ < total_) iter_ = total_; print_stop_(static_cast<void *>(this)); watch_.stop(); } /// \brief Increment the iteration count void increment (unsigned step = 1) {iter_ += step;} private : StopWatch watch_; thread_type *thread_ptr_; unsigned iter_; unsigned total_; double interval_; bool print_first_; bool in_progress_; unsigned num_equal_; unsigned percent_; unsigned seconds_; unsigned last_iter_; std::string message_; char display_progress_[128]; char display_percent_[32]; char display_time_[32]; char display_iter_[64]; std::ostream &os_; static VSMC_CONSTEXPR const unsigned num_equal_max_ = 60; static VSMC_CONSTEXPR const unsigned num_dash_max_ = 1; static VSMC_CONSTEXPR const unsigned percent_max_ = 100; void fork () { join(); thread_ptr_ = new thread_type(print_start_, static_cast<void *>(this)); } void join () { if (thread_ptr_ != VSMC_NULLPTR) { if (thread_ptr_->joinable()) thread_ptr_->join(); delete thread_ptr_; thread_ptr_ = VSMC_NULLPTR; } } static void print_start_ (void *context) { Progress *ptr = static_cast<Progress *>(context); while (ptr->in_progress_) { print_progress(context); ptr->os_ << '\r' << std::flush; ThisThread::sleep(ptr->interval_); } } static void print_stop_ (void *context) { Progress *ptr = static_cast<Progress *>(context); print_progress(context); ptr->os_ << '\n' << std::flush; } static void print_progress (void *context) { Progress *ptr = static_cast<Progress *>(context); ptr->watch_.stop(); ptr->watch_.start(); const unsigned seconds = static_cast<unsigned>(ptr->watch_.seconds()); const unsigned iter = ptr->iter_; const unsigned total = ptr->total_; const unsigned display_iter = iter <= total ? iter : total; unsigned num_equal = total == 0 ? num_equal_max_ : static_cast<unsigned>( static_cast<double>(num_equal_max_) * static_cast<double>(display_iter) / static_cast<double>(total)); num_equal = num_equal <= num_equal_max_ ? num_equal : num_equal_max_; unsigned percent = total == 0 ? percent_max_ : static_cast<unsigned>( static_cast<double>(percent_max_) * static_cast<double>(display_iter) / static_cast<double>(total)); percent = percent <= percent_max_ ? percent : percent_max_; if (ptr->print_first_) { ptr->print_first_ = false; ptr->num_equal_ = num_equal + 1; ptr->percent_ = percent + 1; ptr->seconds_ = seconds + 1; ptr->last_iter_ = iter + 1; } if (ptr->num_equal_ != num_equal) { ptr->num_equal_ = num_equal; unsigned num_space = num_equal_max_ - num_equal; unsigned num_dash = 0; while (num_space > num_dash) { if (num_dash == num_dash_max_) break; --num_space; ++num_dash; } char *cstr = ptr->display_progress_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i != num_equal; ++i) cstr[offset++] = '='; for (unsigned i = 0; i != num_dash; ++i) cstr[offset++] = '-'; for (unsigned i = 0; i != num_space; ++i) cstr[offset++] = ' '; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->percent_ != percent) { ptr->percent_ = percent; const unsigned num_space = 3 - uint_digit(percent); char *cstr = ptr->display_percent_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i != num_space; ++i) cstr[offset++] = ' '; uint_to_char(percent, cstr, offset); cstr[offset++] = '%'; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->seconds_ != seconds) { ptr->seconds_ = seconds; const unsigned display_second = seconds % 60; const unsigned display_minute = (seconds / 60) % 60; const unsigned display_hour = seconds / 3600; char *cstr = ptr->display_time_; std::size_t offset = 0; cstr[offset++] = '['; if (display_hour > 0) { uint_to_char(display_hour, cstr, offset); cstr[offset++] = ':'; } cstr[offset++] = '0' + static_cast<char>(display_minute / 10); cstr[offset++] = '0' + static_cast<char>(display_minute % 10); cstr[offset++] = ':'; cstr[offset++] = '0' + static_cast<char>(display_second / 10); cstr[offset++] = '0' + static_cast<char>(display_second % 10); cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->last_iter_ != iter) { ptr->last_iter_ = iter; const unsigned dtotal = uint_digit(total); const unsigned diter = uint_digit(iter); const unsigned num_space = dtotal > diter ? dtotal - diter : 0; char *cstr = ptr->display_iter_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i < num_space; ++i) cstr[offset++] = ' '; uint_to_char(iter, cstr, offset); cstr[offset++] = '/'; uint_to_char(total, cstr, offset); cstr[offset++] = ']'; cstr[offset++] = '\0'; } ptr->os_ << ptr->message_ << ' '; ptr->os_ << ptr->display_progress_; ptr->os_ << ptr->display_percent_; ptr->os_ << ptr->display_time_; ptr->os_ << ptr->display_iter_; } template <typename UIntType> static void uint_to_char (UIntType num, char *cstr, std::size_t &offset) { if (num == 0) { cstr[offset++] = '0'; return; } char utmp[32]; std::size_t unum = 0; while (num) { utmp[unum++] = '0' + static_cast<char>(num % 10); num /= 10; } for (std::size_t i = unum; i != 0; --i) cstr[offset++] = utmp[i - 1]; } template <typename UIntType> static unsigned uint_digit (UIntType num) { if (num == 0) return 1; unsigned digit = 0; while (num != 0) { ++digit; num /= 10; } return digit; } }; // class Progress } // namespace vsmc #endif // VSMC_UTILITY_PROGRESS_HPP
//============================================================================ // include/vsmc/utility/progress.hpp //---------------------------------------------------------------------------- // // vSMC: Scalable Monte Carlo // // This file is distribured under the 2-clauses BSD License. // See LICENSE for details. //============================================================================ #ifndef VSMC_UTILITY_PROGRESS_HPP #define VSMC_UTILITY_PROGRESS_HPP #include <vsmc/internal/common.hpp> #include <vsmc/utility/stop_watch.hpp> #include <iostream> #include <string> namespace vsmc { /// \brief Display a progress bar while algorithm proceed /// \ingroup Progress /// /// \tparam ThreadType Any type that (partially) follows C++11 `std::thread` /// interface. In particular, the following calls shal be supported, /// ~~~{.cpp} /// void (task *) (void *); // A function pointer /// void *context; // A void pointer /// ThreadType *thread_ptr_ = new ThreadType(task, context); /// thread_ptr_->joinable(); /// thread_ptr_->join(); /// delete thread_ptr_; /// ~~~ /// \tparam ThisThread This shall be a class that provides a `sleep` static /// member function that allows the calling thread to sleep for a specified /// time in seconds. A simple implementation using C++11 `sleep_for` is as the /// following, /// ~~~{.cpp} /// struct ThisThread /// { /// static void sleep (double s) /// { /// // Make the interval acurate to milliseconds /// double ms = std::max(1.0, std::floor(s * 1000)); /// std::this_thread::sleep_for(std::chrono::milliseconds( /// static_cast<std::chrono::milliseconds::rep>(ms))); /// } /// }; /// ~~~ /// An implementation using Boost is almost the same except for the namespace /// changing from `std` to `boost`. template <typename ThreadType, typename ThisThread> class Progress { public : typedef ThreadType thread_type; /// \brief Construct a Progress with an output stream Progress (std::ostream &os = std::cout) : thread_ptr_(VSMC_NULLPTR), iter_(0), total_(0), interval_(0), print_first_(true), in_progress_(false), num_equal_(0), percent_(0), seconds_(0), last_iter_(0), display_progress_(), display_percent_(), display_time_(), display_iter_(), os_(os) {} /// \brief Start to print the progress /// /// \param total Total amount of work represented by an integer, for /// example file size or SMC algorithm total number of iterations /// \param message A (short) discreptive message /// \param interval The sleep interval in seconds void start (unsigned total, const std::string &message = std::string(), double interval = 0.1) { iter_ = 0; total_ = total; interval_ = interval; print_first_ = true; in_progress_ = true; message_ = message; watch_.reset(); watch_.start(); fork(); } /// \brief Stop to print the progress /// /// \param finished If true, then it is assumed that all work has been /// finished, and at the end the progress will be shown as `100%` and /// `total/total`, where total is the first parameter of `start`. /// Otherwise, whatever progress has been made will be shown. void stop (bool finished = false) { in_progress_ = false; join(); if (finished && iter_ < total_) iter_ = total_; print_stop_(static_cast<void *>(this)); watch_.stop(); } /// \brief Increment the iteration count void increment (unsigned step = 1) {iter_ += step;} private : StopWatch watch_; thread_type *thread_ptr_; unsigned iter_; unsigned total_; double interval_; bool print_first_; bool in_progress_; unsigned num_equal_; unsigned percent_; unsigned seconds_; unsigned last_iter_; std::string message_; char display_progress_[128]; char display_percent_[32]; char display_time_[32]; char display_iter_[64]; std::ostream &os_; static VSMC_CONSTEXPR const unsigned num_equal_max_ = 60; static VSMC_CONSTEXPR const unsigned num_dash_max_ = 1; static VSMC_CONSTEXPR const unsigned percent_max_ = 100; void fork () { join(); thread_ptr_ = new thread_type(print_start_, static_cast<void *>(this)); } void join () { if (thread_ptr_ != VSMC_NULLPTR) { if (thread_ptr_->joinable()) thread_ptr_->join(); delete thread_ptr_; thread_ptr_ = VSMC_NULLPTR; } } static void print_start_ (void *context) { Progress *ptr = static_cast<Progress *>(context); while (ptr->in_progress_) { print_progress(context); ptr->os_ << '\r' << std::flush; ThisThread::sleep(ptr->interval_); } } static void print_stop_ (void *context) { Progress *ptr = static_cast<Progress *>(context); print_progress(context); ptr->os_ << '\n' << std::flush; } static void print_progress (void *context) { Progress *ptr = static_cast<Progress *>(context); ptr->watch_.stop(); ptr->watch_.start(); const unsigned seconds = static_cast<unsigned>(ptr->watch_.seconds()); const unsigned iter = ptr->iter_; const unsigned total = ptr->total_; const unsigned display_iter = iter <= total ? iter : total; unsigned num_equal = total == 0 ? num_equal_max_ : static_cast<unsigned>( static_cast<double>(num_equal_max_) * static_cast<double>(display_iter) / static_cast<double>(total)); num_equal = num_equal <= num_equal_max_ ? num_equal : num_equal_max_; unsigned percent = total == 0 ? percent_max_ : static_cast<unsigned>( static_cast<double>(percent_max_) * static_cast<double>(display_iter) / static_cast<double>(total)); percent = percent <= percent_max_ ? percent : percent_max_; if (ptr->print_first_) { ptr->print_first_ = false; ptr->num_equal_ = num_equal + 1; ptr->percent_ = percent + 1; ptr->seconds_ = seconds + 1; ptr->last_iter_ = iter + 1; } if (ptr->num_equal_ != num_equal) { ptr->num_equal_ = num_equal; unsigned num_space = num_equal_max_ - num_equal; unsigned num_dash = 0; while (num_space > num_dash) { if (num_dash == num_dash_max_) break; --num_space; ++num_dash; } char *cstr = ptr->display_progress_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i != num_equal; ++i) cstr[offset++] = '='; for (unsigned i = 0; i != num_dash; ++i) cstr[offset++] = '-'; for (unsigned i = 0; i != num_space; ++i) cstr[offset++] = ' '; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->percent_ != percent) { ptr->percent_ = percent; const unsigned num_space = 3 - uint_digit(percent); char *cstr = ptr->display_percent_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i != num_space; ++i) cstr[offset++] = ' '; uint_to_char(percent, cstr, offset); cstr[offset++] = '%'; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->seconds_ != seconds) { ptr->seconds_ = seconds; const unsigned display_second = seconds % 60; const unsigned display_minute = (seconds / 60) % 60; const unsigned display_hour = seconds / 3600; char *cstr = ptr->display_time_; std::size_t offset = 0; cstr[offset++] = '['; if (display_hour > 0) { uint_to_char(display_hour, cstr, offset); cstr[offset++] = ':'; } cstr[offset++] = '0' + static_cast<char>(display_minute / 10); cstr[offset++] = '0' + static_cast<char>(display_minute % 10); cstr[offset++] = ':'; cstr[offset++] = '0' + static_cast<char>(display_second / 10); cstr[offset++] = '0' + static_cast<char>(display_second % 10); cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->last_iter_ != iter) { ptr->last_iter_ = iter; const unsigned dtotal = uint_digit(total); const unsigned diter = uint_digit(iter); const unsigned num_space = dtotal > diter ? dtotal - diter : 0; char *cstr = ptr->display_iter_; std::size_t offset = 0; cstr[offset++] = '['; for (unsigned i = 0; i < num_space; ++i) cstr[offset++] = ' '; uint_to_char(iter, cstr, offset); cstr[offset++] = '/'; uint_to_char(total, cstr, offset); cstr[offset++] = ']'; cstr[offset++] = '\0'; } ptr->os_ << ' ' << ptr->message_ << ' '; ptr->os_ << ptr->display_progress_; ptr->os_ << ptr->display_percent_; ptr->os_ << ptr->display_time_; ptr->os_ << ptr->display_iter_; } template <typename UIntType> static void uint_to_char (UIntType num, char *cstr, std::size_t &offset) { if (num == 0) { cstr[offset++] = '0'; return; } char utmp[32]; std::size_t unum = 0; while (num) { utmp[unum++] = '0' + static_cast<char>(num % 10); num /= 10; } for (std::size_t i = unum; i != 0; --i) cstr[offset++] = utmp[i - 1]; } template <typename UIntType> static unsigned uint_digit (UIntType num) { if (num == 0) return 1; unsigned digit = 0; while (num != 0) { ++digit; num /= 10; } return digit; } }; // class Progress } // namespace vsmc #endif // VSMC_UTILITY_PROGRESS_HPP
fix message prefix space
fix message prefix space
C++
bsd-2-clause
zhouyan/vSMC,zhouyan/vSMC,zhouyan/vSMC,zhouyan/vSMC
97138f4e23d976d66e9566ebe1d87910decdf684
include/vsmc/utility/progress.hpp
include/vsmc/utility/progress.hpp
//============================================================================ // vSMC/include/vsmc/utility/progress.hpp //---------------------------------------------------------------------------- // vSMC: Scalable Monte Carlo //---------------------------------------------------------------------------- // Copyright (c) 2013-2015, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================ #ifndef VSMC_UTILITY_PROGRESS_HPP #define VSMC_UTILITY_PROGRESS_HPP #include <vsmc/internal/common.hpp> #include <vsmc/utility/stop_watch.hpp> #if VSMC_HAS_CXX11LIB_CHRONO && VSMC_HAS_CXX11LIB_THREAD #include <chrono> #include <thread> #endif namespace vsmc { #if VSMC_HAS_CXX11LIB_CHRONO && VSMC_HAS_CXX11LIB_THREAD namespace internal { struct ProgressThisThread { static void sleep (double s) { double ms = std::floor(s * 1000); if (s < 1.0) s = 1.0; std::this_thread::sleep_for(std::chrono::milliseconds( static_cast<std::chrono::milliseconds::rep>(ms))); } }; // class ProgressThisThread } // namespace vsmc::internal #endif /// \brief Display a progress bar while algorithm proceed /// \ingroup Progress /// /// \tparam ThreadType Any type that (partially) follows C++11 `std::thread` /// interface. In particular, the following calls shal be supported, /// ~~~{.cpp} /// void (task *) (void *); // A function pointer /// void *context; // A void pointer /// ThreadType *thread_ptr_ = new ThreadType(task, context); /// thread_ptr_->joinable(); /// thread_ptr_->join(); /// delete thread_ptr_; /// ~~~ /// \tparam ThisThread This shall be a class that provides a `sleep` static /// member function that allows the calling thread to sleep for a specified /// time in seconds. A simple implementation using C++11 `sleep_for` is as the /// following, /// ~~~{.cpp} /// struct ThisThread /// { /// static void sleep (double s) /// { /// // Make the interval acurate to milliseconds /// double ms = std::max(1.0, std::floor(s * 1000)); /// std::this_thread::sleep_for(std::chrono::milliseconds( /// static_cast<std::chrono::milliseconds::rep>(ms))); /// } /// }; /// ~~~ /// An implementation using Boost is almost the same except for the namespace /// changing from `std` to `boost`. #if VSMC_HAS_CXX11LIB_CHRONO && VSMC_HAS_CXX11LIB_THREAD template <typename ThreadType = std::thread, typename ThisThread = internal::ProgressThisThread> #else template <typename ThreadType, typename ThisThread> #endif class Progress { public : typedef ThreadType thread_type; /// \brief Construct a Progress with an output stream Progress (std::ostream &os = std::cout) : thread_ptr_(VSMC_NULLPTR), interval_(0), iter_(0), total_(0), length_(0), show_iter_(true), print_first_(true), in_progress_(false), num_equal_(0), percent_(0), seconds_(0), last_iter_(0), cstr_bar_(), cstr_percent_(), cstr_time_(), cstr_iter_(), os_(os) {} /// \brief Start to print the progress /// /// \param total Total amount of work represented by an integer, for /// example file size or SMC algorithm total number of iterations /// \param msg A (short) discreptive message /// \param length The length of the progress bar between brackets. If it is /// zero, then no bar is displayed at all /// \param show_iter Shall the iteration count be displayed. /// \param interval The sleep interval in seconds void start (std::size_t total, const std::string &msg = std::string(), std::size_t length = 0, bool show_iter = true, double interval = 0.1) { total_ = total; msg_ = msg; length_ = length; show_iter_ = show_iter; interval_ = interval; iter_ = 0; print_first_ = true; in_progress_ = true; watch_.reset(); watch_.start(); fork(); } /// \brief Stop to print the progress /// /// \param finished If true, then it is assumed that all work has been /// finished, and at the end the progress will be shown as `100%` and /// `total/total`, where total is the first parameter of `start`. /// Otherwise, whatever progress has been made will be shown. void stop (bool finished = true) { in_progress_ = false; join(); if (finished && iter_ < total_) iter_ = total_; print_stop_(this); watch_.stop(); } /// \brief Increment the iteration count void increment (std::size_t step = 1) {iter_ += step;} private : StopWatch watch_; thread_type *thread_ptr_; double interval_; std::size_t iter_; std::size_t total_; std::size_t length_; bool show_iter_; bool print_first_; bool in_progress_; std::size_t num_equal_; std::size_t percent_; std::size_t seconds_; std::size_t last_iter_; std::string msg_; char cstr_bar_[128]; char cstr_percent_[32]; char cstr_time_[32]; char cstr_iter_[64]; std::ostream &os_; void fork () { join(); thread_ptr_ = new thread_type(print_start_, this); } void join () { if (thread_ptr_ != VSMC_NULLPTR) { if (thread_ptr_->joinable()) thread_ptr_->join(); delete thread_ptr_; thread_ptr_ = VSMC_NULLPTR; } } static void print_start_ (void *context) { Progress *ptr = static_cast<Progress *>(context); while (ptr->in_progress_) { print_progress(context); ptr->os_ << '\r' << std::flush; ThisThread::sleep(ptr->interval_); } } static void print_stop_ (void *context) { Progress *ptr = static_cast<Progress *>(context); print_progress(context); ptr->os_ << '\n' << std::flush; } static void print_progress (void *context) { Progress *ptr = static_cast<Progress *>(context); ptr->watch_.stop(); ptr->watch_.start(); const std::size_t seconds = static_cast<std::size_t>(ptr->watch_.seconds()); const std::size_t display_iter = ptr->iter_ <= ptr->total_ ? ptr->iter_ : ptr->total_; std::size_t num_equal = (ptr->total_ | ptr->length_) == 0 ? ptr->length_ : ptr->length_ * display_iter / ptr->total_; num_equal = num_equal <= ptr->length_ ? num_equal : ptr->length_; std::size_t percent = ptr->total_ == 0 ? 100 : 100 * display_iter / ptr->total_; percent = percent <= 100 ? percent : 100; if (ptr->print_first_) { ptr->print_first_ = false; ptr->num_equal_ = num_equal + 1; ptr->percent_ = percent + 1; ptr->seconds_ = seconds + 1; ptr->last_iter_ = ptr->iter_ + 1; } if (ptr->length_ != 0 && ptr->num_equal_ != num_equal) { ptr->num_equal_ = num_equal; std::size_t num_space = ptr->length_ - num_equal; std::size_t num_dash = 0; if (num_space > 0) { num_dash = 1; --num_space; } char *cstr = ptr->cstr_bar_; std::size_t offset = 0; cstr[offset++] = '['; for (std::size_t i = 0; i != num_equal; ++i) cstr[offset++] = '='; for (std::size_t i = 0; i != num_dash; ++i) cstr[offset++] = '-'; for (std::size_t i = 0; i != num_space; ++i) cstr[offset++] = ' '; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->percent_ != percent) { ptr->percent_ = percent; const std::size_t num_space = 3 - uint_digit(percent); char *cstr = ptr->cstr_percent_; std::size_t offset = 0; cstr[offset++] = '['; for (std::size_t i = 0; i != num_space; ++i) cstr[offset++] = ' '; uint_to_char(percent, cstr, offset); cstr[offset++] = '%'; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->seconds_ != seconds) { ptr->seconds_ = seconds; const std::size_t display_second = seconds % 60; const std::size_t display_minute = (seconds / 60) % 60; const std::size_t display_hour = seconds / 3600; char *cstr = ptr->cstr_time_; std::size_t offset = 0; cstr[offset++] = '['; if (display_hour > 0) { uint_to_char(display_hour, cstr, offset); cstr[offset++] = ':'; } cstr[offset++] = '0' + static_cast<char>(display_minute / 10); cstr[offset++] = '0' + static_cast<char>(display_minute % 10); cstr[offset++] = ':'; cstr[offset++] = '0' + static_cast<char>(display_second / 10); cstr[offset++] = '0' + static_cast<char>(display_second % 10); cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->show_iter_ && ptr->last_iter_ != ptr->iter_) { ptr->last_iter_ = ptr->iter_; const std::size_t dtotal = uint_digit(ptr->total_); const std::size_t diter = uint_digit(ptr->iter_); const std::size_t num_space = dtotal > diter ? dtotal - diter : 0; char *cstr = ptr->cstr_iter_; std::size_t offset = 0; cstr[offset++] = '['; for (std::size_t i = 0; i < num_space; ++i) cstr[offset++] = ' '; uint_to_char(ptr->iter_, cstr, offset); cstr[offset++] = '/'; uint_to_char(ptr->total_, cstr, offset); cstr[offset++] = ']'; cstr[offset++] = '\0'; } ptr->os_ << ' '; if (ptr->length_ != 0) ptr->os_ << ptr->cstr_bar_; ptr->os_ << ptr->cstr_percent_; ptr->os_ << ptr->cstr_time_; if (ptr->show_iter_) ptr->os_ << ptr->cstr_iter_; if (ptr->msg_.size() != 0) ptr->os_ << '[' << ptr->msg_ << ']'; } template <typename UIntType> static void uint_to_char (UIntType num, char *cstr, std::size_t &offset) { if (num == 0) { cstr[offset++] = '0'; return; } char utmp[32]; std::size_t unum = 0; while (num) { utmp[unum++] = '0' + static_cast<char>(num % 10); num /= 10; } for (std::size_t i = unum; i != 0; --i) cstr[offset++] = utmp[i - 1]; } template <typename UIntType> static std::size_t uint_digit (UIntType num) { if (num == 0) return 1; std::size_t digit = 0; while (num != 0) { ++digit; num /= 10; } return digit; } }; // class Progress } // namespace vsmc #endif // VSMC_UTILITY_PROGRESS_HPP
//============================================================================ // vSMC/include/vsmc/utility/progress.hpp //---------------------------------------------------------------------------- // vSMC: Scalable Monte Carlo //---------------------------------------------------------------------------- // Copyright (c) 2013-2015, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================ #ifndef VSMC_UTILITY_PROGRESS_HPP #define VSMC_UTILITY_PROGRESS_HPP #include <vsmc/internal/common.hpp> #include <vsmc/utility/stop_watch.hpp> #if VSMC_HAS_CXX11LIB_CHRONO && VSMC_HAS_CXX11LIB_THREAD #include <chrono> #include <thread> #endif namespace vsmc { #if VSMC_HAS_CXX11LIB_CHRONO && VSMC_HAS_CXX11LIB_THREAD namespace internal { struct ProgressThisThread { static void sleep (double s) { double ms = std::floor(s * 1000); if (s < 1.0) s = 1.0; std::this_thread::sleep_for(std::chrono::milliseconds( static_cast<std::chrono::milliseconds::rep>(ms))); } }; // class ProgressThisThread } // namespace vsmc::internal #endif /// \brief Display a progress bar while algorithm proceed /// \ingroup Progress /// /// \tparam ThreadType Any type that (partially) follows C++11 `std::thread` /// interface. In particular, the following calls shal be supported, /// ~~~{.cpp} /// void (task *) (void *); // A function pointer /// void *context; // A void pointer /// ThreadType *thread_ptr_ = new ThreadType(task, context); /// thread_ptr_->joinable(); /// thread_ptr_->join(); /// delete thread_ptr_; /// ~~~ /// \tparam ThisThread This shall be a class that provides a `sleep` static /// member function that allows the calling thread to sleep for a specified /// time in seconds. A simple implementation using C++11 `sleep_for` is as the /// following, /// ~~~{.cpp} /// struct ThisThread /// { /// static void sleep (double s) /// { /// // Make the interval acurate to milliseconds /// double ms = std::max(1.0, std::floor(s * 1000)); /// std::this_thread::sleep_for(std::chrono::milliseconds( /// static_cast<std::chrono::milliseconds::rep>(ms))); /// } /// }; /// ~~~ /// An implementation using Boost is almost the same except for the namespace /// changing from `std` to `boost`. #if VSMC_HAS_CXX11LIB_CHRONO && VSMC_HAS_CXX11LIB_THREAD template <typename ThreadType = std::thread, typename ThisThread = internal::ProgressThisThread> #else template <typename ThreadType, typename ThisThread> #endif class Progress { public : typedef ThreadType thread_type; /// \brief Construct a Progress with an output stream Progress (std::ostream &os = std::cout) : thread_ptr_(VSMC_NULLPTR), interval_(0), iter_(0), total_(0), length_(0), show_iter_(true), print_first_(true), in_progress_(false), num_equal_(0), percent_(0), seconds_(0), last_iter_(0), cstr_bar_(), cstr_percent_(), cstr_time_(), cstr_iter_(), os_(os) {} /// \brief Start to print the progress /// /// \param total Total amount of work represented by an integer, for /// example file size or SMC algorithm total number of iterations /// \param msg A (short) discreptive message /// \param length The length of the progress bar between brackets. If it is /// zero, then no bar is displayed at all /// \param show_iter Shall the iteration count be displayed. /// \param interval The sleep interval in seconds void start (std::size_t total, const std::string &msg = std::string(), std::size_t length = 0, bool show_iter = true, double interval = 0.1) { total_ = total; msg_ = msg; length_ = length; show_iter_ = show_iter; interval_ = interval; iter_ = 0; print_first_ = true; in_progress_ = true; watch_.reset(); watch_.start(); fork(); } /// \brief Stop to print the progress /// /// \param finished If true, then it is assumed that all work has been /// finished, and at the end the progress will be shown as `100%` and /// `total/total`, where total is the first parameter of `start`. /// Otherwise, whatever progress has been made will be shown. void stop (bool finished = true) { in_progress_ = false; join(); if (finished && iter_ < total_) iter_ = total_; print_stop_(this); watch_.stop(); } /// \brief Increment the iteration count void increment (std::size_t step = 1) {iter_ += step;} /// \brief Set a new message for display void message (const std::string &msg) {msg_ = msg;} private : StopWatch watch_; thread_type *thread_ptr_; double interval_; std::size_t iter_; std::size_t total_; std::size_t length_; bool show_iter_; bool print_first_; bool in_progress_; std::size_t num_equal_; std::size_t percent_; std::size_t seconds_; std::size_t last_iter_; std::string msg_; char cstr_bar_[128]; char cstr_percent_[32]; char cstr_time_[32]; char cstr_iter_[64]; std::ostream &os_; void fork () { join(); thread_ptr_ = new thread_type(print_start_, this); } void join () { if (thread_ptr_ != VSMC_NULLPTR) { if (thread_ptr_->joinable()) thread_ptr_->join(); delete thread_ptr_; thread_ptr_ = VSMC_NULLPTR; } } static void print_start_ (void *context) { Progress *ptr = static_cast<Progress *>(context); while (ptr->in_progress_) { print_progress(context); ptr->os_ << '\r' << std::flush; ThisThread::sleep(ptr->interval_); } } static void print_stop_ (void *context) { Progress *ptr = static_cast<Progress *>(context); print_progress(context); ptr->os_ << '\n' << std::flush; } static void print_progress (void *context) { Progress *ptr = static_cast<Progress *>(context); ptr->watch_.stop(); ptr->watch_.start(); const std::size_t seconds = static_cast<std::size_t>(ptr->watch_.seconds()); const std::size_t display_iter = ptr->iter_ <= ptr->total_ ? ptr->iter_ : ptr->total_; std::size_t num_equal = (ptr->total_ | ptr->length_) == 0 ? ptr->length_ : ptr->length_ * display_iter / ptr->total_; num_equal = num_equal <= ptr->length_ ? num_equal : ptr->length_; std::size_t percent = ptr->total_ == 0 ? 100 : 100 * display_iter / ptr->total_; percent = percent <= 100 ? percent : 100; if (ptr->print_first_) { ptr->print_first_ = false; ptr->num_equal_ = num_equal + 1; ptr->percent_ = percent + 1; ptr->seconds_ = seconds + 1; ptr->last_iter_ = ptr->iter_ + 1; } if (ptr->length_ != 0 && ptr->num_equal_ != num_equal) { ptr->num_equal_ = num_equal; std::size_t num_space = ptr->length_ - num_equal; std::size_t num_dash = 0; if (num_space > 0) { num_dash = 1; --num_space; } char *cstr = ptr->cstr_bar_; std::size_t offset = 0; cstr[offset++] = '['; for (std::size_t i = 0; i != num_equal; ++i) cstr[offset++] = '='; for (std::size_t i = 0; i != num_dash; ++i) cstr[offset++] = '-'; for (std::size_t i = 0; i != num_space; ++i) cstr[offset++] = ' '; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->percent_ != percent) { ptr->percent_ = percent; const std::size_t num_space = 3 - uint_digit(percent); char *cstr = ptr->cstr_percent_; std::size_t offset = 0; cstr[offset++] = '['; for (std::size_t i = 0; i != num_space; ++i) cstr[offset++] = ' '; uint_to_char(percent, cstr, offset); cstr[offset++] = '%'; cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->seconds_ != seconds) { ptr->seconds_ = seconds; const std::size_t display_second = seconds % 60; const std::size_t display_minute = (seconds / 60) % 60; const std::size_t display_hour = seconds / 3600; char *cstr = ptr->cstr_time_; std::size_t offset = 0; cstr[offset++] = '['; if (display_hour > 0) { uint_to_char(display_hour, cstr, offset); cstr[offset++] = ':'; } cstr[offset++] = '0' + static_cast<char>(display_minute / 10); cstr[offset++] = '0' + static_cast<char>(display_minute % 10); cstr[offset++] = ':'; cstr[offset++] = '0' + static_cast<char>(display_second / 10); cstr[offset++] = '0' + static_cast<char>(display_second % 10); cstr[offset++] = ']'; cstr[offset++] = '\0'; } if (ptr->show_iter_ && ptr->last_iter_ != ptr->iter_) { ptr->last_iter_ = ptr->iter_; const std::size_t dtotal = uint_digit(ptr->total_); const std::size_t diter = uint_digit(ptr->iter_); const std::size_t num_space = dtotal > diter ? dtotal - diter : 0; char *cstr = ptr->cstr_iter_; std::size_t offset = 0; cstr[offset++] = '['; for (std::size_t i = 0; i < num_space; ++i) cstr[offset++] = ' '; uint_to_char(ptr->iter_, cstr, offset); cstr[offset++] = '/'; uint_to_char(ptr->total_, cstr, offset); cstr[offset++] = ']'; cstr[offset++] = '\0'; } ptr->os_ << ' '; if (ptr->length_ != 0) ptr->os_ << ptr->cstr_bar_; ptr->os_ << ptr->cstr_percent_; ptr->os_ << ptr->cstr_time_; if (ptr->show_iter_) ptr->os_ << ptr->cstr_iter_; if (ptr->msg_.size() != 0) ptr->os_ << '[' << ptr->msg_ << ']'; } template <typename UIntType> static void uint_to_char (UIntType num, char *cstr, std::size_t &offset) { if (num == 0) { cstr[offset++] = '0'; return; } char utmp[32]; std::size_t unum = 0; while (num) { utmp[unum++] = '0' + static_cast<char>(num % 10); num /= 10; } for (std::size_t i = unum; i != 0; --i) cstr[offset++] = utmp[i - 1]; } template <typename UIntType> static std::size_t uint_digit (UIntType num) { if (num == 0) return 1; std::size_t digit = 0; while (num != 0) { ++digit; num /= 10; } return digit; } }; // class Progress } // namespace vsmc #endif // VSMC_UTILITY_PROGRESS_HPP
allow change message in the middle of progress
allow change message in the middle of progress
C++
bsd-2-clause
zhouyan/vSMC,zhouyan/vSMC,zhouyan/vSMC,zhouyan/vSMC
6d6cc17dc852a216395611bf651e57c19c95b9c4
test/test_vector_test.cc
test/test_vector_test.cc
/* * Copyright (c) 2013 The WebM 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 <cstdio> #include <cstdlib> #include <memory> #include <set> #include <string> #include <tuple> #include "third_party/googletest/src/include/gtest/gtest.h" #include "../tools_common.h" #include "./vpx_config.h" #include "test/codec_factory.h" #include "test/decode_test_driver.h" #include "test/ivf_video_source.h" #include "test/md5_helper.h" #include "test/test_vectors.h" #include "test/util.h" #if CONFIG_WEBM_IO #include "test/webm_video_source.h" #endif #include "vpx_mem/vpx_mem.h" namespace { const int kThreads = 0; const int kMtMode = 1; const int kFileName = 2; typedef std::tuple<int, int, const char *> DecodeParam; class TestVectorTest : public ::libvpx_test::DecoderTest, public ::libvpx_test::CodecTestWithParam<DecodeParam> { protected: TestVectorTest() : DecoderTest(GET_PARAM(0)), md5_file_(NULL) { #if CONFIG_VP9_DECODER resize_clips_.insert(::libvpx_test::kVP9TestVectorsResize, ::libvpx_test::kVP9TestVectorsResize + ::libvpx_test::kNumVP9TestVectorsResize); #endif } virtual ~TestVectorTest() { if (md5_file_) fclose(md5_file_); } void OpenMD5File(const std::string &md5_file_name_) { md5_file_ = libvpx_test::OpenTestDataFile(md5_file_name_); ASSERT_TRUE(md5_file_ != NULL) << "Md5 file open failed. Filename: " << md5_file_name_; } #if CONFIG_VP9_DECODER virtual void PreDecodeFrameHook( const libvpx_test::CompressedVideoSource &video, libvpx_test::Decoder *decoder) { if (video.frame_number() == 0 && mt_mode_ >= 0) { if (mt_mode_ == 1) { decoder->Control(VP9D_SET_LOOP_FILTER_OPT, 1); decoder->Control(VP9D_SET_ROW_MT, 0); } else if (mt_mode_ == 2) { decoder->Control(VP9D_SET_LOOP_FILTER_OPT, 0); decoder->Control(VP9D_SET_ROW_MT, 1); } else { decoder->Control(VP9D_SET_LOOP_FILTER_OPT, 0); decoder->Control(VP9D_SET_ROW_MT, 0); } } } #endif virtual void DecompressedFrameHook(const vpx_image_t &img, const unsigned int frame_number) { ASSERT_TRUE(md5_file_ != NULL); char expected_md5[33]; char junk[128]; // Read correct md5 checksums. const int res = fscanf(md5_file_, "%s %s", expected_md5, junk); ASSERT_NE(res, EOF) << "Read md5 data failed"; expected_md5[32] = '\0'; ::libvpx_test::MD5 md5_res; md5_res.Add(&img); const char *actual_md5 = md5_res.Get(); // Check md5 match. ASSERT_STREQ(expected_md5, actual_md5) << "Md5 checksums don't match: frame number = " << frame_number; } #if CONFIG_VP9_DECODER std::set<std::string> resize_clips_; #endif int mt_mode_; private: FILE *md5_file_; }; // This test runs through the whole set of test vectors, and decodes them. // The md5 checksums are computed for each frame in the video file. If md5 // checksums match the correct md5 data, then the test is passed. Otherwise, // the test failed. TEST_P(TestVectorTest, MD5Match) { const DecodeParam input = GET_PARAM(1); const std::string filename = std::get<kFileName>(input); vpx_codec_flags_t flags = 0; vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t(); char str[256]; cfg.threads = std::get<kThreads>(input); mt_mode_ = std::get<kMtMode>(input); snprintf(str, sizeof(str) / sizeof(str[0]) - 1, "file: %s threads: %d MT mode: %d", filename.c_str(), cfg.threads, mt_mode_); SCOPED_TRACE(str); // Open compressed video file. std::unique_ptr<libvpx_test::CompressedVideoSource> video; if (filename.substr(filename.length() - 3, 3) == "ivf") { video.reset(new libvpx_test::IVFVideoSource(filename)); } else if (filename.substr(filename.length() - 4, 4) == "webm") { #if CONFIG_WEBM_IO video.reset(new libvpx_test::WebMVideoSource(filename)); #else fprintf(stderr, "WebM IO is disabled, skipping test vector %s\n", filename.c_str()); return; #endif } ASSERT_TRUE(video.get() != NULL); video->Init(); // Construct md5 file name. const std::string md5_filename = filename + ".md5"; OpenMD5File(md5_filename); // Set decode config and flags. set_cfg(cfg); set_flags(flags); // Decode frame, and check the md5 matching. ASSERT_NO_FATAL_FAILURE(RunLoop(video.get(), cfg)); } #if CONFIG_VP8_DECODER VP8_INSTANTIATE_TEST_CASE( TestVectorTest, ::testing::Combine( ::testing::Values(1), // Single thread. ::testing::Values(-1), // LPF opt and Row MT is not applicable ::testing::ValuesIn(libvpx_test::kVP8TestVectors, libvpx_test::kVP8TestVectors + libvpx_test::kNumVP8TestVectors))); // Test VP8 decode in with different numbers of threads. INSTANTIATE_TEST_CASE_P( VP8MultiThreaded, TestVectorTest, ::testing::Combine( ::testing::Values( static_cast<const libvpx_test::CodecFactory *>(&libvpx_test::kVP8)), ::testing::Combine( ::testing::Range(2, 9), // With 2 ~ 8 threads. ::testing::Values(-1), // LPF opt and Row MT is not applicable ::testing::ValuesIn(libvpx_test::kVP8TestVectors, libvpx_test::kVP8TestVectors + libvpx_test::kNumVP8TestVectors)))); #endif // CONFIG_VP8_DECODER #if CONFIG_VP9_DECODER VP9_INSTANTIATE_TEST_CASE( TestVectorTest, ::testing::Combine( ::testing::Values(1), // Single thread. ::testing::Values(-1), // LPF opt and Row MT is not applicable ::testing::ValuesIn(libvpx_test::kVP9TestVectors, libvpx_test::kVP9TestVectors + libvpx_test::kNumVP9TestVectors))); INSTANTIATE_TEST_CASE_P( VP9MultiThreaded, TestVectorTest, ::testing::Combine( ::testing::Values( static_cast<const libvpx_test::CodecFactory *>(&libvpx_test::kVP9)), ::testing::Combine( ::testing::Range(2, 9), // With 2 ~ 8 threads. ::testing::Range(0, 3), // With multi threads modes 0 ~ 2 // 0: LPF opt and Row MT disabled // 1: LPF opt enabled // 2: Row MT enabled ::testing::ValuesIn(libvpx_test::kVP9TestVectors, libvpx_test::kVP9TestVectors + libvpx_test::kNumVP9TestVectors)))); #endif } // namespace
/* * Copyright (c) 2013 The WebM 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 <cstdio> #include <cstdlib> #include <memory> #include <set> #include <string> #include <tuple> #include "third_party/googletest/src/include/gtest/gtest.h" #include "../tools_common.h" #include "./vpx_config.h" #include "test/codec_factory.h" #include "test/decode_test_driver.h" #include "test/ivf_video_source.h" #include "test/md5_helper.h" #include "test/test_vectors.h" #include "test/util.h" #if CONFIG_WEBM_IO #include "test/webm_video_source.h" #endif #include "vpx_mem/vpx_mem.h" namespace { const int kThreads = 0; const int kMtMode = 1; const int kFileName = 2; typedef std::tuple<int, int, const char *> DecodeParam; class TestVectorTest : public ::libvpx_test::DecoderTest, public ::libvpx_test::CodecTestWithParam<DecodeParam> { protected: TestVectorTest() : DecoderTest(GET_PARAM(0)), md5_file_(NULL) { #if CONFIG_VP9_DECODER resize_clips_.insert(::libvpx_test::kVP9TestVectorsResize, ::libvpx_test::kVP9TestVectorsResize + ::libvpx_test::kNumVP9TestVectorsResize); #endif } virtual ~TestVectorTest() { if (md5_file_) fclose(md5_file_); } void OpenMD5File(const std::string &md5_file_name_) { md5_file_ = libvpx_test::OpenTestDataFile(md5_file_name_); ASSERT_TRUE(md5_file_ != NULL) << "Md5 file open failed. Filename: " << md5_file_name_; } #if CONFIG_VP9_DECODER virtual void PreDecodeFrameHook( const libvpx_test::CompressedVideoSource &video, libvpx_test::Decoder *decoder) { if (video.frame_number() == 0 && mt_mode_ >= 0) { if (mt_mode_ == 1) { decoder->Control(VP9D_SET_LOOP_FILTER_OPT, 1); decoder->Control(VP9D_SET_ROW_MT, 0); } else if (mt_mode_ == 2) { decoder->Control(VP9D_SET_LOOP_FILTER_OPT, 0); decoder->Control(VP9D_SET_ROW_MT, 1); } else { decoder->Control(VP9D_SET_LOOP_FILTER_OPT, 0); decoder->Control(VP9D_SET_ROW_MT, 0); } } } #endif virtual void DecompressedFrameHook(const vpx_image_t &img, const unsigned int frame_number) { ASSERT_TRUE(md5_file_ != NULL); char expected_md5[33]; char junk[128]; // Read correct md5 checksums. const int res = fscanf(md5_file_, "%s %s", expected_md5, junk); ASSERT_NE(res, EOF) << "Read md5 data failed"; expected_md5[32] = '\0'; ::libvpx_test::MD5 md5_res; md5_res.Add(&img); const char *actual_md5 = md5_res.Get(); // Check md5 match. ASSERT_STREQ(expected_md5, actual_md5) << "Md5 checksums don't match: frame number = " << frame_number; } #if CONFIG_VP9_DECODER std::set<std::string> resize_clips_; #endif int mt_mode_; private: FILE *md5_file_; }; // This test runs through the whole set of test vectors, and decodes them. // The md5 checksums are computed for each frame in the video file. If md5 // checksums match the correct md5 data, then the test is passed. Otherwise, // the test failed. TEST_P(TestVectorTest, MD5Match) { const DecodeParam input = GET_PARAM(1); const std::string filename = std::get<kFileName>(input); vpx_codec_flags_t flags = 0; vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t(); char str[256]; cfg.threads = std::get<kThreads>(input); mt_mode_ = std::get<kMtMode>(input); snprintf(str, sizeof(str) / sizeof(str[0]) - 1, "file: %s threads: %d MT mode: %d", filename.c_str(), cfg.threads, mt_mode_); SCOPED_TRACE(str); // Open compressed video file. std::unique_ptr<libvpx_test::CompressedVideoSource> video; if (filename.substr(filename.length() - 3, 3) == "ivf") { video.reset(new libvpx_test::IVFVideoSource(filename)); } else if (filename.substr(filename.length() - 4, 4) == "webm") { #if CONFIG_WEBM_IO video.reset(new libvpx_test::WebMVideoSource(filename)); #else fprintf(stderr, "WebM IO is disabled, skipping test vector %s\n", filename.c_str()); return; #endif } ASSERT_TRUE(video.get() != NULL); video->Init(); // Construct md5 file name. const std::string md5_filename = filename + ".md5"; OpenMD5File(md5_filename); // Set decode config and flags. set_cfg(cfg); set_flags(flags); // Decode frame, and check the md5 matching. ASSERT_NO_FATAL_FAILURE(RunLoop(video.get(), cfg)); } #if CONFIG_VP8_DECODER VP8_INSTANTIATE_TEST_CASE( TestVectorTest, ::testing::Combine( ::testing::Values(1), // Single thread. ::testing::Values(-1), // LPF opt and Row MT is not applicable ::testing::ValuesIn(libvpx_test::kVP8TestVectors, libvpx_test::kVP8TestVectors + libvpx_test::kNumVP8TestVectors))); // Test VP8 decode in with different numbers of threads. INSTANTIATE_TEST_CASE_P( VP8MultiThreaded, TestVectorTest, ::testing::Combine( ::testing::Values( static_cast<const libvpx_test::CodecFactory *>(&libvpx_test::kVP8)), ::testing::Combine( ::testing::Range(2, 9), // With 2 ~ 8 threads. ::testing::Values(-1), // LPF opt and Row MT is not applicable ::testing::ValuesIn(libvpx_test::kVP8TestVectors, libvpx_test::kVP8TestVectors + libvpx_test::kNumVP8TestVectors)))); #endif // CONFIG_VP8_DECODER #if CONFIG_VP9_DECODER VP9_INSTANTIATE_TEST_CASE( TestVectorTest, ::testing::Combine( ::testing::Values(1), // Single thread. ::testing::Values(-1), // LPF opt and Row MT is not applicable ::testing::ValuesIn(libvpx_test::kVP9TestVectors, libvpx_test::kVP9TestVectors + libvpx_test::kNumVP9TestVectors))); INSTANTIATE_TEST_CASE_P( VP9MultiThreaded, TestVectorTest, ::testing::Combine( ::testing::Values( static_cast<const libvpx_test::CodecFactory *>(&libvpx_test::kVP9)), ::testing::Combine( ::testing::Range(2, 9), // With 2 ~ 8 threads. ::testing::Range(0, 2), // With multi threads modes 0 ~ 2 // 0: LPF opt and Row MT disabled // 1: LPF opt enabled // TODO(webm:1626) re-enable Row MT test. // 2: Row MT enabled ::testing::ValuesIn(libvpx_test::kVP9TestVectors, libvpx_test::kVP9TestVectors + libvpx_test::kNumVP9TestVectors)))); #endif } // namespace
disable row mt test
disable row mt test deadlock is being investigated in attached bug. BUG=webm:1626 Change-Id: Ia6d7020b8b1d274433aa89f36c9ed5b9facc5808
C++
bsd-3-clause
webmproject/libvpx,ShiftMediaProject/libvpx,webmproject/libvpx,webmproject/libvpx,ShiftMediaProject/libvpx,ShiftMediaProject/libvpx,webmproject/libvpx,webmproject/libvpx,webmproject/libvpx,ShiftMediaProject/libvpx,ShiftMediaProject/libvpx
ef877d846f7c5a023033ed5201938f31e4ff2e35
test/vp9_ethread_test.cc
test/vp9_ethread_test.cc
/* * Copyright (c) 2014 The WebM 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 <string> #include <vector> #include "third_party/googletest/src/include/gtest/gtest.h" #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/md5_helper.h" #include "test/util.h" #include "test/y4m_video_source.h" namespace { class VPxEncoderThreadTest : public ::libvpx_test::EncoderTest, public ::libvpx_test::CodecTestWith2Params<libvpx_test::TestMode, int> { protected: VPxEncoderThreadTest() : EncoderTest(GET_PARAM(0)), encoder_initialized_(false), tiles_(2), encoding_mode_(GET_PARAM(1)), set_cpu_used_(GET_PARAM(2)) { init_flags_ = VPX_CODEC_USE_PSNR; vpx_codec_dec_cfg_t cfg = vpx_codec_dec_cfg_t(); cfg.w = 1280; cfg.h = 720; decoder_ = codec_->CreateDecoder(cfg, 0); md5_.clear(); } virtual ~VPxEncoderThreadTest() { delete decoder_; } virtual void SetUp() { InitializeConfig(); SetMode(encoding_mode_); if (encoding_mode_ != ::libvpx_test::kRealTime) { cfg_.g_lag_in_frames = 3; cfg_.rc_end_usage = VPX_VBR; cfg_.rc_2pass_vbr_minsection_pct = 5; cfg_.rc_2pass_vbr_maxsection_pct = 2000; } else { cfg_.g_lag_in_frames = 0; cfg_.rc_end_usage = VPX_CBR; cfg_.g_error_resilient = 1; } cfg_.rc_max_quantizer = 56; cfg_.rc_min_quantizer = 0; } virtual void BeginPassHook(unsigned int /*pass*/) { encoder_initialized_ = false; } virtual void PreEncodeFrameHook(::libvpx_test::VideoSource * /*video*/, ::libvpx_test::Encoder *encoder) { if (!encoder_initialized_) { // Encode 4 column tiles. encoder->Control(VP9E_SET_TILE_COLUMNS, tiles_); encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); if (encoding_mode_ != ::libvpx_test::kRealTime) { encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1); encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7); encoder->Control(VP8E_SET_ARNR_STRENGTH, 5); encoder->Control(VP8E_SET_ARNR_TYPE, 3); } else { encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 0); encoder->Control(VP9E_SET_AQ_MODE, 3); } encoder_initialized_ = true; } } virtual void FramePktHook(const vpx_codec_cx_pkt_t *pkt) { #if CONFIG_VP9_DECODER const vpx_codec_err_t res = decoder_->DecodeFrame( reinterpret_cast<uint8_t*>(pkt->data.frame.buf), pkt->data.frame.sz); if (res != VPX_CODEC_OK) { abort_ = true; ASSERT_EQ(VPX_CODEC_OK, res); } const vpx_image_t *img = decoder_->GetDxData().Next(); if (img) { ::libvpx_test::MD5 md5_res; md5_res.Add(img); md5_.push_back(md5_res.Get()); } #else ASSERT_EQ(NULL, decoder_); #endif } bool encoder_initialized_; int tiles_; ::libvpx_test::TestMode encoding_mode_; int set_cpu_used_; ::libvpx_test::Decoder *decoder_; std::vector<std::string> md5_; }; TEST_P(VPxEncoderThreadTest, EncoderResultTest) { std::vector<std::string> single_thr_md5, multi_thr_md5; ::libvpx_test::Y4mVideoSource video("niklas_1280_720_30.y4m", 15, 20); cfg_.rc_target_bitrate = 1000; // Encode using single thread. cfg_.g_threads = 1; init_flags_ = VPX_CODEC_USE_PSNR; ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); single_thr_md5 = md5_; md5_.clear(); // Encode using multiple threads. cfg_.g_threads = 4; ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); multi_thr_md5 = md5_; md5_.clear(); // Compare to check if two vectors are equal. ASSERT_EQ(single_thr_md5, multi_thr_md5); } VP9_INSTANTIATE_TEST_CASE( VPxEncoderThreadTest, ::testing::Values(::libvpx_test::kTwoPassGood, ::libvpx_test::kOnePassGood, ::libvpx_test::kRealTime), ::testing::Range(1, 9)); VP10_INSTANTIATE_TEST_CASE( VPxEncoderThreadTest, ::testing::Values(::libvpx_test::kTwoPassGood, ::libvpx_test::kOnePassGood), ::testing::Range(1, 3)); } // namespace
/* * Copyright (c) 2014 The WebM 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 <string> #include <vector> #include "third_party/googletest/src/include/gtest/gtest.h" #include "test/codec_factory.h" #include "test/encode_test_driver.h" #include "test/md5_helper.h" #include "test/util.h" #include "test/y4m_video_source.h" namespace { class VPxEncoderThreadTest : public ::libvpx_test::EncoderTest, public ::libvpx_test::CodecTestWith2Params<libvpx_test::TestMode, int> { protected: VPxEncoderThreadTest() : EncoderTest(GET_PARAM(0)), encoder_initialized_(false), tiles_(2), encoding_mode_(GET_PARAM(1)), set_cpu_used_(GET_PARAM(2)) { init_flags_ = VPX_CODEC_USE_PSNR; md5_.clear(); } virtual ~VPxEncoderThreadTest() {} virtual void SetUp() { InitializeConfig(); SetMode(encoding_mode_); if (encoding_mode_ != ::libvpx_test::kRealTime) { cfg_.g_lag_in_frames = 3; cfg_.rc_end_usage = VPX_VBR; cfg_.rc_2pass_vbr_minsection_pct = 5; cfg_.rc_2pass_vbr_maxsection_pct = 2000; } else { cfg_.g_lag_in_frames = 0; cfg_.rc_end_usage = VPX_CBR; cfg_.g_error_resilient = 1; } cfg_.rc_max_quantizer = 56; cfg_.rc_min_quantizer = 0; } virtual void BeginPassHook(unsigned int /*pass*/) { encoder_initialized_ = false; } virtual void PreEncodeFrameHook(::libvpx_test::VideoSource * /*video*/, ::libvpx_test::Encoder *encoder) { if (!encoder_initialized_) { // Encode 4 column tiles. encoder->Control(VP9E_SET_TILE_COLUMNS, tiles_); encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_); if (encoding_mode_ != ::libvpx_test::kRealTime) { encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1); encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7); encoder->Control(VP8E_SET_ARNR_STRENGTH, 5); encoder->Control(VP8E_SET_ARNR_TYPE, 3); } else { encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 0); encoder->Control(VP9E_SET_AQ_MODE, 3); } encoder_initialized_ = true; } } virtual void DecompressedFrameHook(const vpx_image_t &img, vpx_codec_pts_t /*pts*/) { ::libvpx_test::MD5 md5_res; md5_res.Add(&img); md5_.push_back(md5_res.Get()); } virtual bool HandleDecodeResult(const vpx_codec_err_t res, const libvpx_test::VideoSource& /*video*/, libvpx_test::Decoder * /*decoder*/) { if (res != VPX_CODEC_OK) { EXPECT_EQ(VPX_CODEC_OK, res); return false; } return true; } bool encoder_initialized_; int tiles_; ::libvpx_test::TestMode encoding_mode_; int set_cpu_used_; std::vector<std::string> md5_; }; TEST_P(VPxEncoderThreadTest, EncoderResultTest) { std::vector<std::string> single_thr_md5, multi_thr_md5; ::libvpx_test::Y4mVideoSource video("niklas_1280_720_30.y4m", 15, 20); cfg_.rc_target_bitrate = 1000; // Encode using single thread. cfg_.g_threads = 1; init_flags_ = VPX_CODEC_USE_PSNR; ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); single_thr_md5 = md5_; md5_.clear(); // Encode using multiple threads. cfg_.g_threads = 4; ASSERT_NO_FATAL_FAILURE(RunLoop(&video)); multi_thr_md5 = md5_; md5_.clear(); // Compare to check if two vectors are equal. ASSERT_EQ(single_thr_md5, multi_thr_md5); } VP9_INSTANTIATE_TEST_CASE( VPxEncoderThreadTest, ::testing::Values(::libvpx_test::kTwoPassGood, ::libvpx_test::kOnePassGood, ::libvpx_test::kRealTime), ::testing::Range(1, 9)); VP10_INSTANTIATE_TEST_CASE( VPxEncoderThreadTest, ::testing::Values(::libvpx_test::kTwoPassGood, ::libvpx_test::kOnePassGood), ::testing::Range(1, 3)); } // namespace
replace FramePktHook w/DecompressedFrameHook
vp9_ethread_test: replace FramePktHook w/DecompressedFrameHook this avoids the decoder test which was only correct for vp9, vp10 was missed in the earlier change Change-Id: Ib789c906d440c0e4169052cf64c74d5e4b196caa
C++
bsd-2-clause
luctrudeau/aom,smarter/aom,GrokImageCompression/aom,webmproject/libvpx,Topopiccione/libvpx,ShiftMediaProject/libvpx,mbebenita/aom,mbebenita/aom,webmproject/libvpx,mwgoldsmith/vpx,GrokImageCompression/aom,ShiftMediaProject/libvpx,GrokImageCompression/aom,mwgoldsmith/vpx,luctrudeau/aom,mwgoldsmith/libvpx,GrokImageCompression/aom,Topopiccione/libvpx,luctrudeau/aom,mbebenita/aom,smarter/aom,luctrudeau/aom,webmproject/libvpx,smarter/aom,webmproject/libvpx,mwgoldsmith/vpx,mwgoldsmith/libvpx,ShiftMediaProject/libvpx,mbebenita/aom,smarter/aom,Topopiccione/libvpx,mbebenita/aom,mwgoldsmith/libvpx,luctrudeau/aom,smarter/aom,Topopiccione/libvpx,webmproject/libvpx,smarter/aom,webmproject/libvpx,mwgoldsmith/vpx,ShiftMediaProject/libvpx,GrokImageCompression/aom,mbebenita/aom,mbebenita/aom,mwgoldsmith/libvpx,mwgoldsmith/libvpx,mwgoldsmith/vpx,GrokImageCompression/aom,ShiftMediaProject/libvpx,Topopiccione/libvpx,mwgoldsmith/vpx,mbebenita/aom,luctrudeau/aom,Topopiccione/libvpx,mbebenita/aom,mwgoldsmith/libvpx
f6584e02f79933e328787e49328fbe33ef9d1731
PathResolver.cpp
PathResolver.cpp
/* * PathResolver.cpp * openc2e * * Created by Bryan Donlan * Copyright (c) 2005 Bryan Donlan. All rights reserved. * * 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. * */ #include "PathResolver.h" #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <set> #include <map> #include <cctype> #include <string> #include <algorithm> #include <iostream> using std::map; using std::set; using std::string; using namespace boost::filesystem; static set<string> dircache; static map<string, string> cache; static bool checkDirCache(path &dir); static bool doCacheDir(path &dir); /* C++ is far too verbose for its own good */ static string toLowerCase(string in) { transform(in.begin(), in.end(), in.begin(), (int(*)(int))tolower); return in; } static path lcpath(path &orig) { return path(toLowerCase(orig.string()), native); } static path lcleaf(path &orig) { path br, leaf; br = orig.branch_path(); leaf = path(toLowerCase(orig.leaf()), native); return br / leaf; } bool resolveFile(path &p) { string s = p.string(); if (!resolveFile(s)) { // Maybe something changed underneath us; reset the cache and try again cache.clear(); dircache.clear(); if (!resolveFile(s)) return false; } p = path(s, native); return true; } bool resolveFile_(string &srcPath) { path orig(srcPath, native); if (exists(orig)) return true; orig.normalize(); path dir = orig.branch_path(); path leaf = path(orig.leaf(), native); if (!checkDirCache(dir)) return false; orig = dir / lcpath(leaf); string fn = orig.string(); if (exists(orig)) { srcPath = fn; return true; } map<string, string>::iterator i = cache.find(fn); if (i == cache.end()) { assert(!exists(orig)); return false; } srcPath = cache[fn]; return true; } bool resolveFile(std::string &path) { std::string orig = path; bool res = resolveFile_(path); #if 0 std::cerr << orig << " -> "; if (!res) std::cerr << "(nil)"; else std::cerr << path; std::cerr << std::endl; #endif return res; } /* If dir is cached, do nothing. * If dir exists, cache it. * If dir does not exist, see if there's one with different capitalization. * * If we find a dir, return true. Else, false. */ bool checkDirCache(path &dir) { if (dir == path()) dir = path("."); // std::cerr << "checkDirCache: " << dir.string() << std::endl; if (dircache.end() != dircache.find(dir.string())) { return true; } if (exists(dir)) return doCacheDir(dir); if (dir.empty()) return false; bool res = resolveFile(dir); if (!res) return false; return checkDirCache(dir); } /* Cache a dir. Return true for success. */ bool doCacheDir(path &dir) { // std::cerr << "cacheing: " << dir.string() << std::endl; directory_iterator it(dir); directory_iterator fsend; while (it != fsend) { path cur = *it++; string key, val; key = cur.string(); val = lcleaf(cur).string(); // std::cerr << "Cache put: " << val << " -> " << key << std::endl; cache[val] = key; } dircache.insert(dir.string()); return true; } static void constructSearchPattern(const std::string &wild, std::vector<std::string> &l) { std::string::const_iterator i = wild.begin(); l.push_back(std::string()); while (i != wild.end()) { if (*i != '*') l.back().push_back(*i); else l.push_back(std::string()); i++; } } static bool checkSearchPattern(const std::string &match, const std::vector<std::string> &l) { size_t p = 0; std::vector<std::string>::const_iterator it = l.begin(); while (it != l.end()) { p = match.find(*it, p); if (p == std::string::npos) return false; it++; } if (match.substr(match.length() - l.back().length()) != l.back()) return false; return true; } // XXX: this might not handle new files too well... std::vector<std::string> findByWildcard(std::string dir, std::string wild) { wild = toLowerCase(wild); path dirp(dir, native); dirp.normalize(); if (!resolveFile(dirp)) return std::vector<std::string>(); dir = dirp.string(); if (!doCacheDir(dirp)) return std::vector<std::string>(); std::vector<std::string> l, results; constructSearchPattern(wild, l); std::string lcdir = toLowerCase(dir); std::map<string, string>::iterator skey = cache.lower_bound(dir); for (; skey != cache.end(); skey++) { if (skey->first.length() < lcdir.length()) break; std::string dirpart, filepart; // XXX: we should use boost fops, maybe dirpart = skey->first.substr(0, lcdir.length()); if (dirpart != dir) break; if (skey->first.length() < lcdir.length() + 2) continue; filepart = toLowerCase(skey->first.substr(lcdir.length() + 1)); if (!checkSearchPattern(filepart, l)) continue; results.push_back(skey->second); } return results; } /* vim: set noet: */
/* * PathResolver.cpp * openc2e * * Created by Bryan Donlan * Copyright (c) 2005 Bryan Donlan. All rights reserved. * * 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. * */ #include "PathResolver.h" #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <set> #include <map> #include <cctype> #include <string> #include <algorithm> #include <iostream> using std::map; using std::set; using std::string; using namespace boost::filesystem; static set<string> dircache; static map<string, string> cache; static bool checkDirCache(path &dir); static bool doCacheDir(path &dir); /* C++ is far too verbose for its own good */ static string toLowerCase(string in) { transform(in.begin(), in.end(), in.begin(), (int(*)(int))tolower); return in; } static path lcpath(path &orig) { return path(toLowerCase(orig.string()), native); } static path lcleaf(path &orig) { path br, leaf; br = orig.branch_path(); leaf = path(toLowerCase(orig.leaf()), native); return br / leaf; } bool resolveFile(path &p) { string s = p.string(); if (!resolveFile(s)) { // Maybe something changed underneath us; reset the cache and try again cache.clear(); dircache.clear(); if (!resolveFile(s)) return false; } p = path(s, native); return true; } bool resolveFile_(string &srcPath) { path orig(srcPath, native); if (exists(orig)) return true; orig.normalize(); path dir = orig.branch_path(); path leaf = path(orig.leaf(), native); if (!checkDirCache(dir)) return false; orig = dir / lcpath(leaf); string fn = orig.string(); if (exists(orig)) { srcPath = fn; return true; } map<string, string>::iterator i = cache.find(fn); if (i == cache.end()) { assert(!exists(orig)); return false; } srcPath = cache[fn]; return true; } bool resolveFile(std::string &path) { std::string orig = path; bool res = resolveFile_(path); #if 0 std::cerr << orig << " -> "; if (!res) std::cerr << "(nil)"; else std::cerr << path; std::cerr << std::endl; #endif return res; } /* If dir is cached, do nothing. * If dir exists, cache it. * If dir does not exist, see if there's one with different capitalization. * * If we find a dir, return true. Else, false. */ bool checkDirCache(path &dir) { if (dir == path()) dir = path("."); // std::cerr << "checkDirCache: " << dir.string() << std::endl; if (dircache.end() != dircache.find(dir.string())) { return true; } if (exists(dir)) return doCacheDir(dir); if (dir.empty()) return false; bool res = resolveFile(dir); if (!res) return false; return checkDirCache(dir); } /* Cache a dir. Return true for success. */ bool doCacheDir(path &dir) { // std::cerr << "cacheing: " << dir.string() << std::endl; directory_iterator it(dir); directory_iterator fsend; while (it != fsend) { path cur = *it++; string key, val; key = cur.string(); val = lcleaf(cur).string(); // std::cerr << "Cache put: " << val << " -> " << key << std::endl; cache[val] = key; } dircache.insert(dir.string()); return true; } static void constructSearchPattern(const std::string &wild, std::vector<std::string> &l) { std::string::const_iterator i = wild.begin(); l.push_back(std::string()); while (i != wild.end()) { if (*i != '*') l.back().push_back(*i); else l.push_back(std::string()); i++; } } static bool checkSearchPattern(const std::string &match, const std::vector<std::string> &l) { size_t p = 0; std::vector<std::string>::const_iterator it = l.begin(); while (it != l.end()) { p = match.find(*it, p); if (p == std::string::npos) return false; it++; } if (match.substr(match.length() - l.back().length()) != l.back()) return false; return true; } std::vector<std::string> findByWildcard(std::string dir, std::string wild) { cache.clear(); dircache.clear(); wild = toLowerCase(wild); path dirp(dir, native); dirp.normalize(); if (!resolveFile(dirp)) return std::vector<std::string>(); dir = dirp.string(); if (!doCacheDir(dirp)) return std::vector<std::string>(); std::vector<std::string> l, results; constructSearchPattern(wild, l); std::string lcdir = toLowerCase(dir); std::map<string, string>::iterator skey = cache.lower_bound(dir); for (; skey != cache.end(); skey++) { if (skey->first.length() < lcdir.length()) break; std::string dirpart, filepart; // XXX: we should use boost fops, maybe dirpart = skey->first.substr(0, lcdir.length()); if (dirpart != dir) break; if (skey->first.length() < lcdir.length() + 2) continue; filepart = toLowerCase(skey->first.substr(lcdir.length() + 1)); if (!checkSearchPattern(filepart, l)) continue; results.push_back(skey->second); } return results; } /* vim: set noet: */
Clear the cache before wildcard-searching
Clear the cache before wildcard-searching
C++
lgpl-2.1
ccdevnet/openc2e,ccdevnet/openc2e,crystalline/openc2e,crystalline/openc2e,crystalline/openc2e,ccdevnet/openc2e,crystalline/openc2e,crystalline/openc2e,bdonlan/openc2e,bdonlan/openc2e,ccdevnet/openc2e,bdonlan/openc2e,ccdevnet/openc2e,bdonlan/openc2e,ccdevnet/openc2e
5e5dc2b5bc2c01d14f000aded9ce6e37c389c4e3
tests/Semaphore_test.cpp
tests/Semaphore_test.cpp
#include <gtest/gtest.h> #include <Semaphore.hpp> ////////////////////////////////////////////////////////////////// TEST(Semaphore, test_01) { using namespace linux::posix; ASSERT_TRUE(true); Name n("/ARTA"); OpenOptions f; Semaphore s(n, false, f, 4); // posix::SharedMemory sm3(n, false, f); // sm3.open().truncate(4096); // posix::MMapOptions mo; // ASSERT_EQ(posix::mmap::READ | // posix::mmap::WRITE, // mo.get_protection().get()); // ASSERT_EQ(posix::mmap::MSHARED, mo.get_flag().get()); } //////////////////////////////////////////////////////////////////
#include <gtest/gtest.h> #include <Semaphore.hpp> ////////////////////////////////////////////////////////////////// TEST(Semaphore, test_01) { using namespace linux::posix; ASSERT_TRUE(true); Name n("/ARTA"); OpenOptions f; Semaphore s1(n, false, f, 4); Semaphore s2(n, false); // ASSERT_EQ(posix::mmap::READ | // posix::mmap::WRITE, // mo.get_protection().get()); // ASSERT_EQ(posix::mmap::MSHARED, mo.get_flag().get()); } TEST(Semaphore, test_02) { using namespace linux::posix; ASSERT_TRUE(true); Name n("/AA"); Semaphore s2(n, true); s2.open(); s2.close(); // ASSERT_EQ(posix::mmap::READ | // posix::mmap::WRITE, // mo.get_protection().get()); // ASSERT_EQ(posix::mmap::MSHARED, mo.get_flag().get()); } //////////////////////////////////////////////////////////////////
add unit test for Semaphore
add unit test for Semaphore
C++
mpl-2.0
popovb/SharMemPlusPlus
84d74cd76b8d85b42d46f6e0d3bbb1c2a483f3d0
tests/src/ml/Context.cpp
tests/src/ml/Context.cpp
#include <gtest/gtest.h> #include <okui/ml/Context.h> #include <okui/ml/Environment.h> TEST(ml_Context, load) { okui::ml::Environment ml; okui::ml::Context context(&ml); auto element = context.load(R"( <view background-color="green"> <view x="20" y="20" width="200" height="40" background-color="blue"></view> </view> )"); auto view = element->view(); ASSERT_TRUE(view); EXPECT_EQ(view->backgroundColor(), okui::Color::kGreen); EXPECT_EQ(view->subviews().size(), 1); view->layout(); EXPECT_EQ(view->subviews().front()->bounds(), okui::Rectangle<double>(20, 20, 200, 40)); EXPECT_EQ(view->subviews().front()->backgroundColor(), okui::Color::kBlue); } TEST(ml_Context, render) { okui::ml::Environment ml; okui::ml::Context context(&ml); // test with no variables EXPECT_EQ(context.render("hello"), "hello"); context.define("foo", "bar"); EXPECT_EQ(context.render("foo{foo}"), "foobar"); context.define("unused", "!!!"); EXPECT_EQ(context.render("foo{foo}"), "foobar"); for (size_t i = 0; i <= fmt::ArgList::MAX_PACKED_ARGS; ++i) { context.define(std::to_string(i), "x"); } EXPECT_EQ(context.render("foo{foo}"), "foobar"); context.define("n", 1.234); EXPECT_EQ(context.render("{n:.2}"), "1.2"); }
#include <gtest/gtest.h> #include <okui/View.h> #include <okui/ml/Context.h> #include <okui/ml/Environment.h> TEST(ml_Context, load) { okui::ml::Environment ml; okui::ml::Context context(&ml); auto element = context.load(R"( <view background-color="green"> <view x="20" y="20" width="200" height="40" background-color="blue"></view> </view> )"); auto view = element->view(); ASSERT_TRUE(view); EXPECT_EQ(view->backgroundColor(), okui::Color::kGreen); EXPECT_EQ(view->subviews().size(), 1); view->layout(); EXPECT_EQ(view->subviews().front()->bounds(), okui::Rectangle<double>(20, 20, 200, 40)); EXPECT_EQ(view->subviews().front()->backgroundColor(), okui::Color::kBlue); } TEST(ml_Context, render) { okui::ml::Environment ml; okui::ml::Context context(&ml); // test with no variables EXPECT_EQ(context.render("hello"), "hello"); context.define("foo", "bar"); EXPECT_EQ(context.render("foo{foo}"), "foobar"); context.define("unused", "!!!"); EXPECT_EQ(context.render("foo{foo}"), "foobar"); for (size_t i = 0; i <= fmt::ArgList::MAX_PACKED_ARGS; ++i) { context.define(std::to_string(i), "x"); } EXPECT_EQ(context.render("foo{foo}"), "foobar"); context.define("n", 1.234); EXPECT_EQ(context.render("{n:.2}"), "1.2"); }
test build fix
test build fix
C++
apache-2.0
bittorrent/okui,bittorrent/okui,bittorrent/okui,bittorrent/okui,bittorrent/okui
f98fb5e07205c3a705f09efb0034b3bb6f612c02
base/time_mac.cc
base/time_mac.cc
// 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 "base/time.h" #include <CoreFoundation/CFDate.h> #include <CoreFoundation/CFTimeZone.h> #include <mach/mach_time.h> #include <sys/time.h> #include <time.h> #include "base/basictypes.h" #include "base/logging.h" #include "base/mac/scoped_cftyperef.h" namespace base { // The Time routines in this file use Mach and CoreFoundation APIs, since the // POSIX definition of time_t in Mac OS X wraps around after 2038--and // there are already cookie expiration dates, etc., past that time out in // the field. Using CFDate prevents that problem, and using mach_absolute_time // for TimeTicks gives us nice high-resolution interval timing. // Time ----------------------------------------------------------------------- // Core Foundation uses a double second count since 2001-01-01 00:00:00 UTC. // The UNIX epoch is 1970-01-01 00:00:00 UTC. // Windows uses a Gregorian epoch of 1601. We need to match this internally // so that our time representations match across all platforms. See bug 14734. // irb(main):010:0> Time.at(0).getutc() // => Thu Jan 01 00:00:00 UTC 1970 // irb(main):011:0> Time.at(-11644473600).getutc() // => Mon Jan 01 00:00:00 UTC 1601 static const int64 kWindowsEpochDeltaSeconds = GG_INT64_C(11644473600); static const int64 kWindowsEpochDeltaMilliseconds = kWindowsEpochDeltaSeconds * Time::kMillisecondsPerSecond; // static const int64 Time::kWindowsEpochDeltaMicroseconds = kWindowsEpochDeltaSeconds * Time::kMicrosecondsPerSecond; // Some functions in time.cc use time_t directly, so we provide an offset // to convert from time_t (Unix epoch) and internal (Windows epoch). // static const int64 Time::kTimeTToMicrosecondsOffset = kWindowsEpochDeltaMicroseconds; // static Time Time::Now() { return FromCFAbsoluteTime(CFAbsoluteTimeGetCurrent()); } // static Time Time::FromCFAbsoluteTime(CFAbsoluteTime t) { if (t == 0) return Time(); // Consider 0 as a null Time. if (t == std::numeric_limits<CFAbsoluteTime>::max()) return Max(); return Time(static_cast<int64>( (t + kCFAbsoluteTimeIntervalSince1970) * kMicrosecondsPerSecond) + kWindowsEpochDeltaMicroseconds); } CFAbsoluteTime Time::ToCFAbsoluteTime() const { if (is_null()) return 0; // Consider 0 as a null Time. if (is_max()) return std::numeric_limits<CFAbsoluteTime>::max(); return (static_cast<CFAbsoluteTime>(us_ - kWindowsEpochDeltaMicroseconds) / kMicrosecondsPerSecond) - kCFAbsoluteTimeIntervalSince1970; } // static Time Time::NowFromSystemTime() { // Just use Now() because Now() returns the system time. return Now(); } // static Time Time::FromExploded(bool is_local, const Exploded& exploded) { CFGregorianDate date; date.second = exploded.second + exploded.millisecond / static_cast<double>(kMillisecondsPerSecond); date.minute = exploded.minute; date.hour = exploded.hour; date.day = exploded.day_of_month; date.month = exploded.month; date.year = exploded.year; base::mac::ScopedCFTypeRef<CFTimeZoneRef> time_zone(is_local ? CFTimeZoneCopySystem() : NULL); CFAbsoluteTime seconds = CFGregorianDateGetAbsoluteTime(date, time_zone) + kCFAbsoluteTimeIntervalSince1970; return Time(static_cast<int64>(seconds * kMicrosecondsPerSecond) + kWindowsEpochDeltaMicroseconds); } void Time::Explode(bool is_local, Exploded* exploded) const { // Avoid rounding issues, by only putting the integral number of seconds // (rounded towards -infinity) into a |CFAbsoluteTime| (which is a |double|). int64 microsecond = us_ % kMicrosecondsPerSecond; if (microsecond < 0) microsecond += kMicrosecondsPerSecond; CFAbsoluteTime seconds = ((us_ - microsecond) / kMicrosecondsPerSecond) - kWindowsEpochDeltaSeconds - kCFAbsoluteTimeIntervalSince1970; base::mac::ScopedCFTypeRef<CFTimeZoneRef> time_zone(is_local ? CFTimeZoneCopySystem() : NULL); CFGregorianDate date = CFAbsoluteTimeGetGregorianDate(seconds, time_zone); // 1 = Monday, ..., 7 = Sunday. int cf_day_of_week = CFAbsoluteTimeGetDayOfWeek(seconds, time_zone); exploded->year = date.year; exploded->month = date.month; exploded->day_of_week = cf_day_of_week % 7; exploded->day_of_month = date.day; exploded->hour = date.hour; exploded->minute = date.minute; // Make sure seconds are rounded down towards -infinity. exploded->second = floor(date.second); // Calculate milliseconds ourselves, since we rounded the |seconds|, making // sure to round towards -infinity. exploded->millisecond = (microsecond >= 0) ? microsecond / kMicrosecondsPerMillisecond : (microsecond - kMicrosecondsPerMillisecond + 1) / kMicrosecondsPerMillisecond; } // TimeTicks ------------------------------------------------------------------ // static TimeTicks TimeTicks::Now() { uint64_t absolute_micro; static mach_timebase_info_data_t timebase_info; if (timebase_info.denom == 0) { // Zero-initialization of statics guarantees that denom will be 0 before // calling mach_timebase_info. mach_timebase_info will never set denom to // 0 as that would be invalid, so the zero-check can be used to determine // whether mach_timebase_info has already been called. This is // recommended by Apple's QA1398. kern_return_t kr = mach_timebase_info(&timebase_info); DCHECK_EQ(KERN_SUCCESS, kr); } // mach_absolute_time is it when it comes to ticks on the Mac. Other calls // with less precision (such as TickCount) just call through to // mach_absolute_time. // timebase_info converts absolute time tick units into nanoseconds. Convert // to microseconds up front to stave off overflows. absolute_micro = mach_absolute_time() / Time::kNanosecondsPerMicrosecond * timebase_info.numer / timebase_info.denom; // Don't bother with the rollover handling that the Windows version does. // With numer and denom = 1 (the expected case), the 64-bit absolute time // reported in nanoseconds is enough to last nearly 585 years. return TimeTicks(absolute_micro); } // static TimeTicks TimeTicks::HighResNow() { return Now(); } // static TimeTicks TimeTicks::NowFromSystemTraceTime() { return HighResNow(); } } // namespace base
// 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 "base/time.h" #include <CoreFoundation/CFDate.h> #include <CoreFoundation/CFTimeZone.h> #include <mach/mach_time.h> #include <sys/sysctl.h> #include <sys/time.h> #include <sys/types.h> #include <time.h> #include "base/basictypes.h" #include "base/logging.h" #include "base/mac/scoped_cftyperef.h" namespace { uint64_t ComputeCurrentTicks() { #if defined(OS_IOS) // On iOS mach_absolute_time stops while the device is sleeping. Instead use // now - KERN_BOOTTIME to get a time difference that is not impacted by clock // changes. KERN_BOOTTIME will be updated by the system whenever the system // clock change. struct timeval boottime; int mib[2] = {CTL_KERN, KERN_BOOTTIME}; size_t size = sizeof(boottime); int kr = sysctl(mib, arraysize(mib), &boottime, &size, NULL, 0); DCHECK_EQ(KERN_SUCCESS, kr); base::TimeDelta time_difference = base::Time::Now() - (base::Time::FromTimeT(boottime.tv_sec) + base::TimeDelta::FromMicroseconds(boottime.tv_usec)); return time_difference.InMicroseconds(); #else uint64_t absolute_micro; static mach_timebase_info_data_t timebase_info; if (timebase_info.denom == 0) { // Zero-initialization of statics guarantees that denom will be 0 before // calling mach_timebase_info. mach_timebase_info will never set denom to // 0 as that would be invalid, so the zero-check can be used to determine // whether mach_timebase_info has already been called. This is // recommended by Apple's QA1398. kern_return_t kr = mach_timebase_info(&timebase_info); DCHECK_EQ(KERN_SUCCESS, kr); } // mach_absolute_time is it when it comes to ticks on the Mac. Other calls // with less precision (such as TickCount) just call through to // mach_absolute_time. // timebase_info converts absolute time tick units into nanoseconds. Convert // to microseconds up front to stave off overflows. absolute_micro = mach_absolute_time() / base::Time::kNanosecondsPerMicrosecond * timebase_info.numer / timebase_info.denom; // Don't bother with the rollover handling that the Windows version does. // With numer and denom = 1 (the expected case), the 64-bit absolute time // reported in nanoseconds is enough to last nearly 585 years. return absolute_micro; #endif // defined(OS_IOS) } } // namespace namespace base { // The Time routines in this file use Mach and CoreFoundation APIs, since the // POSIX definition of time_t in Mac OS X wraps around after 2038--and // there are already cookie expiration dates, etc., past that time out in // the field. Using CFDate prevents that problem, and using mach_absolute_time // for TimeTicks gives us nice high-resolution interval timing. // Time ----------------------------------------------------------------------- // Core Foundation uses a double second count since 2001-01-01 00:00:00 UTC. // The UNIX epoch is 1970-01-01 00:00:00 UTC. // Windows uses a Gregorian epoch of 1601. We need to match this internally // so that our time representations match across all platforms. See bug 14734. // irb(main):010:0> Time.at(0).getutc() // => Thu Jan 01 00:00:00 UTC 1970 // irb(main):011:0> Time.at(-11644473600).getutc() // => Mon Jan 01 00:00:00 UTC 1601 static const int64 kWindowsEpochDeltaSeconds = GG_INT64_C(11644473600); static const int64 kWindowsEpochDeltaMilliseconds = kWindowsEpochDeltaSeconds * Time::kMillisecondsPerSecond; // static const int64 Time::kWindowsEpochDeltaMicroseconds = kWindowsEpochDeltaSeconds * Time::kMicrosecondsPerSecond; // Some functions in time.cc use time_t directly, so we provide an offset // to convert from time_t (Unix epoch) and internal (Windows epoch). // static const int64 Time::kTimeTToMicrosecondsOffset = kWindowsEpochDeltaMicroseconds; // static Time Time::Now() { return FromCFAbsoluteTime(CFAbsoluteTimeGetCurrent()); } // static Time Time::FromCFAbsoluteTime(CFAbsoluteTime t) { if (t == 0) return Time(); // Consider 0 as a null Time. if (t == std::numeric_limits<CFAbsoluteTime>::max()) return Max(); return Time(static_cast<int64>( (t + kCFAbsoluteTimeIntervalSince1970) * kMicrosecondsPerSecond) + kWindowsEpochDeltaMicroseconds); } CFAbsoluteTime Time::ToCFAbsoluteTime() const { if (is_null()) return 0; // Consider 0 as a null Time. if (is_max()) return std::numeric_limits<CFAbsoluteTime>::max(); return (static_cast<CFAbsoluteTime>(us_ - kWindowsEpochDeltaMicroseconds) / kMicrosecondsPerSecond) - kCFAbsoluteTimeIntervalSince1970; } // static Time Time::NowFromSystemTime() { // Just use Now() because Now() returns the system time. return Now(); } // static Time Time::FromExploded(bool is_local, const Exploded& exploded) { CFGregorianDate date; date.second = exploded.second + exploded.millisecond / static_cast<double>(kMillisecondsPerSecond); date.minute = exploded.minute; date.hour = exploded.hour; date.day = exploded.day_of_month; date.month = exploded.month; date.year = exploded.year; base::mac::ScopedCFTypeRef<CFTimeZoneRef> time_zone(is_local ? CFTimeZoneCopySystem() : NULL); CFAbsoluteTime seconds = CFGregorianDateGetAbsoluteTime(date, time_zone) + kCFAbsoluteTimeIntervalSince1970; return Time(static_cast<int64>(seconds * kMicrosecondsPerSecond) + kWindowsEpochDeltaMicroseconds); } void Time::Explode(bool is_local, Exploded* exploded) const { // Avoid rounding issues, by only putting the integral number of seconds // (rounded towards -infinity) into a |CFAbsoluteTime| (which is a |double|). int64 microsecond = us_ % kMicrosecondsPerSecond; if (microsecond < 0) microsecond += kMicrosecondsPerSecond; CFAbsoluteTime seconds = ((us_ - microsecond) / kMicrosecondsPerSecond) - kWindowsEpochDeltaSeconds - kCFAbsoluteTimeIntervalSince1970; base::mac::ScopedCFTypeRef<CFTimeZoneRef> time_zone(is_local ? CFTimeZoneCopySystem() : NULL); CFGregorianDate date = CFAbsoluteTimeGetGregorianDate(seconds, time_zone); // 1 = Monday, ..., 7 = Sunday. int cf_day_of_week = CFAbsoluteTimeGetDayOfWeek(seconds, time_zone); exploded->year = date.year; exploded->month = date.month; exploded->day_of_week = cf_day_of_week % 7; exploded->day_of_month = date.day; exploded->hour = date.hour; exploded->minute = date.minute; // Make sure seconds are rounded down towards -infinity. exploded->second = floor(date.second); // Calculate milliseconds ourselves, since we rounded the |seconds|, making // sure to round towards -infinity. exploded->millisecond = (microsecond >= 0) ? microsecond / kMicrosecondsPerMillisecond : (microsecond - kMicrosecondsPerMillisecond + 1) / kMicrosecondsPerMillisecond; } // TimeTicks ------------------------------------------------------------------ // static TimeTicks TimeTicks::Now() { return TimeTicks(ComputeCurrentTicks()); } // static TimeTicks TimeTicks::HighResNow() { return Now(); } // static TimeTicks TimeTicks::NowFromSystemTraceTime() { return HighResNow(); } } // namespace base
Improve TimeTicks on iOS.
Improve TimeTicks on iOS. TimeTicks stops ticking on iOS when the device is sleeping. This patch compute timeticks by computing the difference between the current time and the boot time, as the system update boot time when it updates the clock. [email protected] BUG=None Review URL: https://chromiumcodereview.appspot.com/11529011 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@172851 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Jonekee/chromium.src,markYoungH/chromium.src,mogoweb/chromium-crosswalk,M4sse/chromium.src,littlstar/chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,patrickm/chromium.src,dednal/chromium.src,Jonekee/chromium.src,ltilve/chromium,anirudhSK/chromium,Chilledheart/chromium,dednal/chromium.src,timopulkkinen/BubbleFish,Just-D/chromium-1,dednal/chromium.src,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,nacl-webkit/chrome_deps,anirudhSK/chromium,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,Chilledheart/chromium,hujiajie/pa-chromium,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,ltilve/chromium,Chilledheart/chromium,Fireblend/chromium-crosswalk,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,M4sse/chromium.src,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,jaruba/chromium.src,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,patrickm/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,M4sse/chromium.src,zcbenz/cefode-chromium,jaruba/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,zcbenz/cefode-chromium,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,zcbenz/cefode-chromium,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,jaruba/chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,Chilledheart/chromium,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,hujiajie/pa-chromium,axinging/chromium-crosswalk,M4sse/chromium.src,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,dednal/chromium.src,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,Jonekee/chromium.src,anirudhSK/chromium,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,ltilve/chromium,zcbenz/cefode-chromium,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,M4sse/chromium.src,Chilledheart/chromium,zcbenz/cefode-chromium,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,dednal/chromium.src,ChromiumWebApps/chromium,anirudhSK/chromium,hujiajie/pa-chromium,Just-D/chromium-1,nacl-webkit/chrome_deps,jaruba/chromium.src,Just-D/chromium-1,ondra-novak/chromium.src,jaruba/chromium.src,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,zcbenz/cefode-chromium,littlstar/chromium.src,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,anirudhSK/chromium,dushu1203/chromium.src,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,anirudhSK/chromium,zcbenz/cefode-chromium,Just-D/chromium-1,M4sse/chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,mogoweb/chromium-crosswalk,patrickm/chromium.src,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,anirudhSK/chromium,nacl-webkit/chrome_deps,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,hujiajie/pa-chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,ltilve/chromium,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,littlstar/chromium.src,dednal/chromium.src,ltilve/chromium,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,ondra-novak/chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,ltilve/chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,zcbenz/cefode-chromium,Jonekee/chromium.src,dushu1203/chromium.src,dednal/chromium.src,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,patrickm/chromium.src,Fireblend/chromium-crosswalk
4ffb76ebb830520b946ff7722d4e44f8a3b227d9
graf2d/gpadv7/src/RStyle.cxx
graf2d/gpadv7/src/RStyle.cxx
/************************************************************************* * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include <ROOT/RStyle.hxx> #include <ROOT/RDrawable.hxx> #include <ROOT/RLogger.hxx> using namespace std::string_literals; /////////////////////////////////////////////////////////////////////////////// /// Evaluate attribute value for provided RDrawable const ROOT::Experimental::RAttrMap::Value_t *ROOT::Experimental::RStyle::Eval(const std::string &field, const RDrawable &drawable) const { for (const auto &block : fBlocks) { if (drawable.MatchSelector(block.selector)) { auto res = block.map.Find(field); if (res) return res; } } return nullptr; } /////////////////////////////////////////////////////////////////////////////// /// Evaluate attribute value for provided selector - exact match is expected const ROOT::Experimental::RAttrMap::Value_t *ROOT::Experimental::RStyle::Eval(const std::string &field, const std::string &selector) const { for (const auto &block : fBlocks) { if (block.selector == selector) { auto res = block.map.Find(field); if (res) return res; } } return nullptr; } /////////////////////////////////////////////////////////////////////////////// /// Parse string with CSS code inside void ROOT::Experimental::RStyle::Clear() { fBlocks.clear(); } /////////////////////////////////////////////////////////////////////////////// /// Parse string with CSS code inside /// All data will be append to existing style records bool ROOT::Experimental::RStyle::ParseString(const std::string &css_code) { if (css_code.empty()) return true; int len = css_code.length(), pos = 0, nline = 1, linebeg = 0; auto error_position = [&css_code, len, nline, linebeg] () -> std::string { std::string res = "\nLine "s + std::to_string(nline) + ": "s; int p = linebeg; while ((p<len) && (p < linebeg+100) && (css_code[p] != '\n')) ++p; return res + css_code.substr(linebeg, p-linebeg); }; /** Skip comments or just empty space */ auto skip_empty = [&css_code, &pos, &nline, &linebeg, len] () -> bool { bool skip_until_newline = false, skip_until_endblock = false; while (pos < len) { if (css_code[pos] == '\n') { skip_until_newline = false; linebeg = ++pos; ++nline; continue; } if (skip_until_endblock && (css_code[pos] == '*') && (pos+1 < len) && (css_code[pos+1] == '/')) { pos+=2; skip_until_endblock = false; continue; } if (skip_until_newline || skip_until_endblock || (css_code[pos] == ' ') || (css_code[pos] == '\t')) { ++pos; continue; } if ((css_code[pos] == '/') && (pos+1 < len)) { if (css_code[pos+1] == '/') { pos+=2; skip_until_newline = true; continue; } else if (css_code[pos+1] == '*') { pos+=2; skip_until_endblock = true; continue; } } return true; } return false; }; auto check_symbol = [] (char symbol, bool isfirst = false) -> bool { if (((symbol >= 'a') && (symbol <= 'z')) || ((symbol >= 'A') && (symbol <= 'Z')) || (symbol == '_')) return true; return (!isfirst && (symbol>='0') && (symbol<='9')); }; auto scan_identifier = [&check_symbol, &css_code, &pos, len] (bool selector = false) -> std::string { if (pos >= len) return ""s; int pos0 = pos; // start symbols of selector if (selector && ((css_code[pos] == '.') || (css_code[pos] == '#'))) ++pos; while ((pos < len) && check_symbol(css_code[pos])) ++pos; return css_code.substr(pos0, pos-pos0); }; auto scan_value = [&css_code, &pos, len] () -> std::string { if (pos >= len) return ""s; int pos0 = pos; while ((pos < len) && (css_code[pos] != ';')) { if (css_code[pos] == '\n') return ""s; pos++; } if (pos >= len) return ""s; ++pos; return css_code.substr(pos0, pos - pos0 - 1); }; RStyle newstyle; while (pos < len) { if (!skip_empty()) return false; auto sel = scan_identifier(true); if (sel.empty()) { R__ERROR_HERE("rstyle") << "Fail to find selector" << error_position(); return false; } if (!skip_empty()) return false; if (css_code[pos] != '{') { R__ERROR_HERE("rstyle") << "Fail to find starting {" << error_position(); return false; } ++pos; if (!skip_empty()) return false; auto &map = newstyle.AddBlock(sel); while (css_code[pos] != '}') { auto name = scan_identifier(); if (name.empty()) { R__ERROR_HERE("rstyle") << "not able to extract identifier" << error_position(); return false; } if (!skip_empty()) return false; if (css_code[pos] != ':') { R__ERROR_HERE("rstyle") << "not able to find separator :" << error_position(); return false; } ++pos; if (!skip_empty()) return false; auto value = scan_value(); if (value.empty()) { R__ERROR_HERE("rstyle") << "not able to find value" << error_position(); return false; } map.AddBestMatch(name, value); if (!skip_empty()) return false; } ++pos; skip_empty(); // after closing } end of file is possible } // finally move all read blocks to this fBlocks.splice(fBlocks.end(), newstyle.fBlocks); return true; }
/************************************************************************* * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #include <ROOT/RStyle.hxx> #include <ROOT/RDrawable.hxx> #include <ROOT/RLogger.hxx> using namespace std::string_literals; /////////////////////////////////////////////////////////////////////////////// /// Evaluate attribute value for provided RDrawable const ROOT::Experimental::RAttrMap::Value_t *ROOT::Experimental::RStyle::Eval(const std::string &field, const RDrawable &drawable) const { for (const auto &block : fBlocks) { if (drawable.MatchSelector(block.selector)) { auto res = block.map.Find(field); if (res) return res; } } return nullptr; } /////////////////////////////////////////////////////////////////////////////// /// Evaluate attribute value for provided selector - exact match is expected const ROOT::Experimental::RAttrMap::Value_t *ROOT::Experimental::RStyle::Eval(const std::string &field, const std::string &selector) const { for (const auto &block : fBlocks) { if (block.selector == selector) { auto res = block.map.Find(field); if (res) return res; } } return nullptr; } /////////////////////////////////////////////////////////////////////////////// /// Parse string with CSS code inside void ROOT::Experimental::RStyle::Clear() { fBlocks.clear(); } /////////////////////////////////////////////////////////////////////////////// /// Parse string with CSS code inside /// All data will be append to existing style records bool ROOT::Experimental::RStyle::ParseString(const std::string &css_code) { if (css_code.empty()) return true; struct RParser { int pos{0}; int nline{1}; int linebeg{0}; int len{0}; const std::string &css_code; RParser(const std::string &_code) : css_code(_code) { len = css_code.length(); } bool more_data() const { return pos < len; } char current() const { return css_code[pos]; } void shift() { ++pos; } bool check_symbol(bool isfirst = false) { auto symbol = current(); if (((symbol >= 'a') && (symbol <= 'z')) || ((symbol >= 'A') && (symbol <= 'Z')) || (symbol == '_')) return true; return (!isfirst && (symbol>='0') && (symbol<='9')); } std::string error_position() const { std::string res = "\nLine "s + std::to_string(nline) + ": "s; int p = linebeg; while ((p<len) && (p < linebeg+100) && (css_code[p] != '\n')) ++p; return res + css_code.substr(linebeg, p-linebeg); } bool skip_empty() { bool skip_until_newline = false, skip_until_endblock = false; while (pos < len) { if (current() == '\n') { skip_until_newline = false; linebeg = ++pos; ++nline; continue; } if (skip_until_endblock && (current() == '*') && (pos+1 < len) && (css_code[pos+1] == '/')) { pos+=2; skip_until_endblock = false; continue; } if (skip_until_newline || skip_until_endblock || (current() == ' ') || (current() == '\t')) { shift(); continue; } if ((current() == '/') && (pos+1 < len)) { if (css_code[pos+1] == '/') { pos+=2; skip_until_newline = true; continue; } else if (css_code[pos+1] == '*') { pos+=2; skip_until_endblock = true; continue; } } return true; } return false; } std::string scan_identifier(bool selector = false) { if (pos >= len) return ""s; int pos0 = pos; // start symbols of selector if (selector && ((current() == '.') || (current() == '#'))) shift(); bool is_first = true; while ((pos < len) && check_symbol(is_first)) { shift(); is_first = false; } return css_code.substr(pos0, pos-pos0); } std::string scan_value() { if (pos >= len) return ""s; int pos0 = pos; while ((pos < len) && (current() != ';') && current() != '\n') shift(); if (pos >= len) return ""s; shift(); return css_code.substr(pos0, pos - pos0 - 1); } }; RParser parser(css_code); RStyle newstyle; while (parser.more_data()) { if (!parser.skip_empty()) return false; auto sel = parser.scan_identifier(true); if (sel.empty()) { R__ERROR_HERE("rstyle") << "Fail to find selector" << parser.error_position(); return false; } if (!parser.skip_empty()) return false; if (parser.current() != '{') { R__ERROR_HERE("rstyle") << "Fail to find starting {" << parser.error_position(); return false; } parser.shift(); if (!parser.skip_empty()) return false; auto &map = newstyle.AddBlock(sel); while (parser.current() != '}') { auto name = parser.scan_identifier(); if (name.empty()) { R__ERROR_HERE("rstyle") << "not able to extract identifier" << parser.error_position(); return false; } if (!parser.skip_empty()) return false; if (parser.current() != ':') { R__ERROR_HERE("rstyle") << "not able to find separator :" << parser.error_position(); return false; } parser.shift(); if (!parser.skip_empty()) return false; auto value = parser.scan_value(); if (value.empty()) { R__ERROR_HERE("rstyle") << "not able to find value" << parser.error_position(); return false; } map.AddBestMatch(name, value); if (!parser.skip_empty()) return false; } parser.shift(); parser.skip_empty(); // after closing } end of file is possible } // finally move all read blocks to this fBlocks.splice(fBlocks.end(), newstyle.fBlocks); return true; }
use internal parser class instead of lambdas
[rstyle] use internal parser class instead of lambdas Fix small issues with decoding
C++
lgpl-2.1
root-mirror/root,olifre/root,karies/root,root-mirror/root,karies/root,root-mirror/root,olifre/root,karies/root,olifre/root,olifre/root,karies/root,karies/root,karies/root,olifre/root,karies/root,root-mirror/root,olifre/root,olifre/root,root-mirror/root,karies/root,root-mirror/root,olifre/root,root-mirror/root,olifre/root,root-mirror/root,karies/root,olifre/root,root-mirror/root,karies/root,karies/root,olifre/root,root-mirror/root,root-mirror/root
a967cc79dc0c84e2cfcedbfd1eece77f62b58602
tools/mlir-translate/mlir-translate.cpp
tools/mlir-translate/mlir-translate.cpp
//===- mlir-translate.cpp - MLIR Translate Driver -------------------------===// // // Copyright 2019 The MLIR 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. // ============================================================================= // // This is a command line utility that translates a file from/to MLIR using one // of the registered translations. // //===----------------------------------------------------------------------===// #include "mlir/IR/MLIRContext.h" #include "mlir/IR/Module.h" #include "mlir/Parser.h" #include "mlir/Support/FileUtilities.h" #include "mlir/Translation.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileUtilities.h" #include "llvm/Support/InitLLVM.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/ToolOutputFile.h" using namespace mlir; static llvm::cl::opt<std::string> inputFilename(llvm::cl::Positional, llvm::cl::desc("<input file>"), llvm::cl::init("-")); static llvm::cl::opt<std::string> outputFilename("o", llvm::cl::desc("Output filename"), llvm::cl::value_desc("filename"), llvm::cl::init("-")); static Module *parseMLIRInput(StringRef inputFilename, MLIRContext *context) { // Set up the input file. std::string errorMessage; auto file = openInputFile(inputFilename, &errorMessage); if (!file) { llvm::errs() << errorMessage << "\n"; return nullptr; } llvm::SourceMgr sourceMgr; sourceMgr.AddNewSourceBuffer(std::move(file), llvm::SMLoc()); return parseSourceFile(sourceMgr, context); } static bool printMLIROutput(const Module &module, llvm::StringRef outputFilename) { auto file = openOutputFile(outputFilename); if (!file) return true; module.print(file->os()); file->keep(); return false; } // Common interface for source-to-source translation functions. using TranslateFunction = std::function<bool(StringRef, StringRef, MLIRContext *)>; // Storage for the translation function wrappers that survive the parser. static llvm::SmallVector<TranslateFunction, 8> wrapperStorage; // Custom parser for TranslateFunction. // Wraps TranslateToMLIRFunctions and TranslateFromMLIRFunctions into // TranslateFunctions before registering them as options. struct TranslationParser : public llvm::cl::parser<const TranslateFunction *> { TranslationParser(llvm::cl::Option &opt) : llvm::cl::parser<const TranslateFunction *>(opt) { for (const auto &kv : getTranslationToMLIRRegistry()) { TranslateToMLIRFunction function = kv.second; TranslateFunction wrapper = [function](StringRef inputFilename, StringRef outputFilename, MLIRContext *context) { std::unique_ptr<Module> module = function(inputFilename, context); if (!module) return true; printMLIROutput(*module, outputFilename); return false; }; wrapperStorage.emplace_back(std::move(wrapper)); addLiteralOption(kv.first(), &wrapperStorage.back(), kv.first()); } for (const auto &kv : getTranslationFromMLIRRegistry()) { TranslateFromMLIRFunction function = kv.second; TranslateFunction wrapper = [function](StringRef inputFilename, StringRef outputFilename, MLIRContext *context) { auto module = std::unique_ptr<Module>(parseMLIRInput(inputFilename, context)); if (!module) return true; return function(module.get(), outputFilename); }; wrapperStorage.emplace_back(std::move(wrapper)); addLiteralOption(kv.first(), &wrapperStorage.back(), kv.first()); } } void printOptionInfo(const llvm::cl::Option &O, size_t GlobalWidth) const override { TranslationParser *TP = const_cast<TranslationParser *>(this); llvm::array_pod_sort(TP->Values.begin(), TP->Values.end(), [](const TranslationParser::OptionInfo *VT1, const TranslationParser::OptionInfo *VT2) { return VT1->Name.compare(VT2->Name); }); using llvm::cl::parser; parser<const TranslateFunction *>::printOptionInfo(O, GlobalWidth); } }; int main(int argc, char **argv) { llvm::PrettyStackTraceProgram x(argc, argv); llvm::InitLLVM y(argc, argv); // Add flags for all the registered translations. llvm::cl::opt<const TranslateFunction *, false, TranslationParser> translationRequested("", llvm::cl::desc("Translation to perform"), llvm::cl::Required); llvm::cl::ParseCommandLineOptions(argc, argv, "MLIR translation driver\n"); MLIRContext context; return (*translationRequested)(inputFilename, outputFilename, &context); }
//===- mlir-translate.cpp - MLIR Translate Driver -------------------------===// // // Copyright 2019 The MLIR 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. // ============================================================================= // // This is a command line utility that translates a file from/to MLIR using one // of the registered translations. // //===----------------------------------------------------------------------===// #include "mlir/IR/MLIRContext.h" #include "mlir/IR/Module.h" #include "mlir/Parser.h" #include "mlir/Support/FileUtilities.h" #include "mlir/Translation.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileUtilities.h" #include "llvm/Support/InitLLVM.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/ToolOutputFile.h" using namespace mlir; static llvm::cl::opt<std::string> inputFilename(llvm::cl::Positional, llvm::cl::desc("<input file>"), llvm::cl::init("-")); static llvm::cl::opt<std::string> outputFilename("o", llvm::cl::desc("Output filename"), llvm::cl::value_desc("filename"), llvm::cl::init("-")); static Module *parseMLIRInput(StringRef inputFilename, MLIRContext *context) { // Set up the input file. std::string errorMessage; auto file = openInputFile(inputFilename, &errorMessage); if (!file) { llvm::errs() << errorMessage << "\n"; return nullptr; } llvm::SourceMgr sourceMgr; sourceMgr.AddNewSourceBuffer(std::move(file), llvm::SMLoc()); return parseSourceFile(sourceMgr, context); } static bool printMLIROutput(const Module &module, llvm::StringRef outputFilename) { if (module.verify()) return true; auto file = openOutputFile(outputFilename); if (!file) return true; module.print(file->os()); file->keep(); return false; } // Common interface for source-to-source translation functions. using TranslateFunction = std::function<bool(StringRef, StringRef, MLIRContext *)>; // Storage for the translation function wrappers that survive the parser. static llvm::SmallVector<TranslateFunction, 8> wrapperStorage; // Custom parser for TranslateFunction. // Wraps TranslateToMLIRFunctions and TranslateFromMLIRFunctions into // TranslateFunctions before registering them as options. struct TranslationParser : public llvm::cl::parser<const TranslateFunction *> { TranslationParser(llvm::cl::Option &opt) : llvm::cl::parser<const TranslateFunction *>(opt) { for (const auto &kv : getTranslationToMLIRRegistry()) { TranslateToMLIRFunction function = kv.second; TranslateFunction wrapper = [function](StringRef inputFilename, StringRef outputFilename, MLIRContext *context) { std::unique_ptr<Module> module = function(inputFilename, context); if (!module) return true; return printMLIROutput(*module, outputFilename); }; wrapperStorage.emplace_back(std::move(wrapper)); addLiteralOption(kv.first(), &wrapperStorage.back(), kv.first()); } for (const auto &kv : getTranslationFromMLIRRegistry()) { TranslateFromMLIRFunction function = kv.second; TranslateFunction wrapper = [function](StringRef inputFilename, StringRef outputFilename, MLIRContext *context) { auto module = std::unique_ptr<Module>(parseMLIRInput(inputFilename, context)); if (!module) return true; return function(module.get(), outputFilename); }; wrapperStorage.emplace_back(std::move(wrapper)); addLiteralOption(kv.first(), &wrapperStorage.back(), kv.first()); } } void printOptionInfo(const llvm::cl::Option &O, size_t GlobalWidth) const override { TranslationParser *TP = const_cast<TranslationParser *>(this); llvm::array_pod_sort(TP->Values.begin(), TP->Values.end(), [](const TranslationParser::OptionInfo *VT1, const TranslationParser::OptionInfo *VT2) { return VT1->Name.compare(VT2->Name); }); using llvm::cl::parser; parser<const TranslateFunction *>::printOptionInfo(O, GlobalWidth); } }; int main(int argc, char **argv) { llvm::PrettyStackTraceProgram x(argc, argv); llvm::InitLLVM y(argc, argv); // Add flags for all the registered translations. llvm::cl::opt<const TranslateFunction *, false, TranslationParser> translationRequested("", llvm::cl::desc("Translation to perform"), llvm::cl::Required); llvm::cl::ParseCommandLineOptions(argc, argv, "MLIR translation driver\n"); MLIRContext context; return (*translationRequested)(inputFilename, outputFilename, &context); }
Verify IR produced by TranslateToMLIR functions
Verify IR produced by TranslateToMLIR functions TESTED with existing unit tests PiperOrigin-RevId: 235623059
C++
apache-2.0
tensorflow/tensorflow-pywrap_saved_model,DavidNorman/tensorflow,petewarden/tensorflow,tensorflow/tensorflow,Intel-Corporation/tensorflow,arborh/tensorflow,annarev/tensorflow,gautam1858/tensorflow,sarvex/tensorflow,gunan/tensorflow,davidzchen/tensorflow,jhseu/tensorflow,gunan/tensorflow,gunan/tensorflow,Intel-Corporation/tensorflow,davidzchen/tensorflow,petewarden/tensorflow,frreiss/tensorflow-fred,gunan/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_saved_model,tensorflow/tensorflow,aam-at/tensorflow,davidzchen/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,frreiss/tensorflow-fred,cxxgtxy/tensorflow,karllessard/tensorflow,yongtang/tensorflow,adit-chandra/tensorflow,gautam1858/tensorflow,xzturn/tensorflow,yongtang/tensorflow,jhseu/tensorflow,Intel-Corporation/tensorflow,xzturn/tensorflow,xzturn/tensorflow,xzturn/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,aldian/tensorflow,arborh/tensorflow,petewarden/tensorflow,tensorflow/tensorflow,davidzchen/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,tensorflow/tensorflow-pywrap_tf_optimizer,frreiss/tensorflow-fred,jhseu/tensorflow,xzturn/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,karllessard/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-pywrap_saved_model,adit-chandra/tensorflow,Intel-Corporation/tensorflow,xzturn/tensorflow,ppwwyyxx/tensorflow,adit-chandra/tensorflow,aam-at/tensorflow,tensorflow/tensorflow,adit-chandra/tensorflow,ppwwyyxx/tensorflow,freedomtan/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-Corporation/tensorflow,davidzchen/tensorflow,aldian/tensorflow,adit-chandra/tensorflow,aam-at/tensorflow,xzturn/tensorflow,renyi533/tensorflow,arborh/tensorflow,aam-at/tensorflow,yongtang/tensorflow,adit-chandra/tensorflow,frreiss/tensorflow-fred,gautam1858/tensorflow,DavidNorman/tensorflow,frreiss/tensorflow-fred,cxxgtxy/tensorflow,frreiss/tensorflow-fred,aam-at/tensorflow,freedomtan/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,tensorflow/tensorflow-pywrap_saved_model,ppwwyyxx/tensorflow,arborh/tensorflow,xzturn/tensorflow,karllessard/tensorflow,annarev/tensorflow,ppwwyyxx/tensorflow,renyi533/tensorflow,aam-at/tensorflow,petewarden/tensorflow,sarvex/tensorflow,annarev/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_saved_model,annarev/tensorflow,yongtang/tensorflow,gautam1858/tensorflow,jhseu/tensorflow,davidzchen/tensorflow,Intel-tensorflow/tensorflow,gunan/tensorflow,yongtang/tensorflow,arborh/tensorflow,arborh/tensorflow,petewarden/tensorflow,aldian/tensorflow,paolodedios/tensorflow,ppwwyyxx/tensorflow,freedomtan/tensorflow,aldian/tensorflow,paolodedios/tensorflow,renyi533/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,annarev/tensorflow,davidzchen/tensorflow,yongtang/tensorflow,freedomtan/tensorflow,xzturn/tensorflow,aam-at/tensorflow,paolodedios/tensorflow,arborh/tensorflow,jhseu/tensorflow,aldian/tensorflow,arborh/tensorflow,arborh/tensorflow,adit-chandra/tensorflow,paolodedios/tensorflow,adit-chandra/tensorflow,sarvex/tensorflow,tensorflow/tensorflow-pywrap_saved_model,adit-chandra/tensorflow,ppwwyyxx/tensorflow,frreiss/tensorflow-fred,gunan/tensorflow,gautam1858/tensorflow,arborh/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,DavidNorman/tensorflow,davidzchen/tensorflow,freedomtan/tensorflow,gunan/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,DavidNorman/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,frreiss/tensorflow-fred,annarev/tensorflow,tensorflow/tensorflow,renyi533/tensorflow,frreiss/tensorflow-fred,freedomtan/tensorflow,annarev/tensorflow,DavidNorman/tensorflow,aam-at/tensorflow,cxxgtxy/tensorflow,Intel-Corporation/tensorflow,gunan/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,sarvex/tensorflow,davidzchen/tensorflow,Intel-Corporation/tensorflow,karllessard/tensorflow,petewarden/tensorflow,petewarden/tensorflow,petewarden/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,cxxgtxy/tensorflow,ppwwyyxx/tensorflow,paolodedios/tensorflow,freedomtan/tensorflow,DavidNorman/tensorflow,sarvex/tensorflow,DavidNorman/tensorflow,cxxgtxy/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_saved_model,renyi533/tensorflow,gautam1858/tensorflow,arborh/tensorflow,Intel-tensorflow/tensorflow,renyi533/tensorflow,karllessard/tensorflow,cxxgtxy/tensorflow,jhseu/tensorflow,davidzchen/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,Intel-tensorflow/tensorflow,ppwwyyxx/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,cxxgtxy/tensorflow,paolodedios/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,aldian/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,ppwwyyxx/tensorflow,adit-chandra/tensorflow,jhseu/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,petewarden/tensorflow,DavidNorman/tensorflow,freedomtan/tensorflow,tensorflow/tensorflow,yongtang/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,frreiss/tensorflow-fred,ppwwyyxx/tensorflow,gunan/tensorflow,renyi533/tensorflow,freedomtan/tensorflow,gautam1858/tensorflow,yongtang/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,xzturn/tensorflow,karllessard/tensorflow,jhseu/tensorflow,annarev/tensorflow,aam-at/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,gautam1858/tensorflow,annarev/tensorflow,freedomtan/tensorflow,renyi533/tensorflow,frreiss/tensorflow-fred,DavidNorman/tensorflow,cxxgtxy/tensorflow,frreiss/tensorflow-fred,renyi533/tensorflow,gautam1858/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,Intel-tensorflow/tensorflow,jhseu/tensorflow,adit-chandra/tensorflow,sarvex/tensorflow,gunan/tensorflow,ppwwyyxx/tensorflow,tensorflow/tensorflow-pywrap_saved_model,gautam1858/tensorflow,jhseu/tensorflow,Intel-tensorflow/tensorflow,karllessard/tensorflow,tensorflow/tensorflow-experimental_link_static_libraries_once,annarev/tensorflow,tensorflow/tensorflow,Intel-Corporation/tensorflow,tensorflow/tensorflow-pywrap_tf_optimizer,karllessard/tensorflow,tensorflow/tensorflow,paolodedios/tensorflow,karllessard/tensorflow,aldian/tensorflow,DavidNorman/tensorflow,renyi533/tensorflow,aldian/tensorflow,gunan/tensorflow,Intel-tensorflow/tensorflow,Intel-tensorflow/tensorflow,ppwwyyxx/tensorflow,DavidNorman/tensorflow,tensorflow/tensorflow,tensorflow/tensorflow-pywrap_saved_model,arborh/tensorflow,paolodedios/tensorflow,petewarden/tensorflow,davidzchen/tensorflow,Intel-tensorflow/tensorflow,yongtang/tensorflow,xzturn/tensorflow,renyi533/tensorflow,petewarden/tensorflow,tensorflow/tensorflow,annarev/tensorflow,tensorflow/tensorflow,gunan/tensorflow,petewarden/tensorflow,freedomtan/tensorflow,renyi533/tensorflow,yongtang/tensorflow,adit-chandra/tensorflow
03b0896981415fc0210d0b5cb558a2235a7ffb0a
SurgSim/Framework/Accessible.cpp
SurgSim/Framework/Accessible.cpp
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include "SurgSim/Framework/Accessible.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Math/Matrix.h" namespace SurgSim { namespace Framework { Accessible::Accessible() { } Accessible::~Accessible() { } template <> boost::any Accessible::getValue(const std::string& name) const { auto functors = m_functors.find(name); if (functors != std::end(m_functors) && functors->second.getter != nullptr) { return functors->second.getter(); } else { SURGSIM_FAILURE() << "Can't get property: " << name << "." << ((functors == std::end(m_functors)) ? "Property not found." : "No getter defined for property."); return boost::any(); } } boost::any Accessible::getValue(const std::string& name) const { return getValue<boost::any>(name); } void Accessible::setValue(const std::string& name, const boost::any& value) { auto functors = m_functors.find(name); if (functors != std::end(m_functors) && functors->second.setter != nullptr) { functors->second.setter(value); } else { SURGSIM_FAILURE() << "Can't set property: " << name << "." << ((functors == std::end(m_functors)) ? "Property not found." : "No setter defined for property."); } } void Accessible::setGetter(const std::string& name, GetterType func) { SURGSIM_ASSERT(func != nullptr) << "Getter functor can't be nullptr"; m_functors[name].getter = func; } void Accessible::setSetter(const std::string& name, SetterType func) { SURGSIM_ASSERT(func != nullptr) << "Setter functor can't be nullptr"; m_functors[name].setter = func; } void Accessible::setAccessors(const std::string& name, GetterType getter, SetterType setter) { setGetter(name, getter); setSetter(name, setter); } void Accessible::removeAccessors(const std::string& name) { auto functors = m_functors.find(name); if (functors != std::end(m_functors)) { functors->second.setter = nullptr; functors->second.getter = nullptr; } } bool Accessible::isReadable(const std::string& name) const { auto functors = m_functors.find(name); return (functors != m_functors.end() && functors->second.getter != nullptr); } bool Accessible::isWriteable(const std::string& name) const { auto functors = m_functors.find(name); return (functors != m_functors.end() && functors->second.setter != nullptr); } void Accessible::setSerializable(const std::string& name, EncoderType encoder, DecoderType decoder) { SURGSIM_ASSERT(encoder != nullptr) << "Encoder functor can't be nullptr."; SURGSIM_ASSERT(decoder != nullptr) << "Decoder functor can't be nullptr."; m_functors[name].encoder = encoder; m_functors[name].decoder = decoder; } YAML::Node Accessible::encode() const { YAML::Node result; for (auto functors = m_functors.cbegin(); functors != m_functors.cend(); ++functors) { auto encoder = functors->second.encoder; if (encoder != nullptr) { result[functors->first] = encoder(); } } return result; } void Accessible::decode(const YAML::Node& node, const std::vector<std::string>& ignoredProperties) { SURGSIM_ASSERT(node.IsMap()) << "Node to be decoded has to be map."; for (auto data = node.begin(); data != node.end(); ++data) { std::string name = data->first.as<std::string>(); if (std::find(std::begin(ignoredProperties), std::end(ignoredProperties), name) != std::end(ignoredProperties)) { continue; } auto functors = m_functors.find(name); if (functors == std::end(m_functors) || !functors->second.decoder) { SURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getLogger("Framework/Accessible")) << "No decoder registered for the property " << name; } else { YAML::Node temporary = data->second; if (!temporary.IsNull() && temporary.IsDefined()) { try { functors->second.decoder(&temporary); } catch (std::exception e) { SURGSIM_FAILURE() << e.what(); } } else { SURGSIM_LOG_INFO(SurgSim::Framework::Logger::getLogger("Framework/Accessible")) << "No value associated with property " << name; } } } } void Accessible::forwardProperty(const std::string& name, const Accessible& target, const std::string& targetValueName) { Functors functors; auto found = target.m_functors.find(targetValueName); if (found != target.m_functors.end()) { functors.getter = found->second.getter; functors.setter = found->second.setter; m_functors[name] = std::move(functors); } else { SURGSIM_FAILURE() << "Target does not have any setters or getters on property " << targetValueName; } } template<> SurgSim::Math::Matrix44f convert(boost::any val) { SurgSim::Math::Matrix44f floatResult; // Use try in case this conversion was created using a Matrix44f, in which case the any_cast will // still fail and throw an exception try { SurgSim::Math::Matrix44d result = boost::any_cast<SurgSim::Math::Matrix44d>(val); floatResult = result.cast<float>(); } catch (boost::bad_any_cast&) { floatResult = boost::any_cast<SurgSim::Math::Matrix44f>(val); } return floatResult; } }; // Framework }; // SurgSim
// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <algorithm> #include "SurgSim/Framework/Accessible.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Math/Matrix.h" namespace SurgSim { namespace Framework { Accessible::Accessible() { } Accessible::~Accessible() { } template <> boost::any Accessible::getValue(const std::string& name) const { auto functors = m_functors.find(name); if (functors != std::end(m_functors) && functors->second.getter != nullptr) { return functors->second.getter(); } else { SURGSIM_FAILURE() << "Can't get property: " << name << "." << ((functors == std::end(m_functors)) ? "Property not found." : "No getter defined for property."); return boost::any(); } } boost::any Accessible::getValue(const std::string& name) const { return getValue<boost::any>(name); } void Accessible::setValue(const std::string& name, const boost::any& value) { auto functors = m_functors.find(name); if (functors != std::end(m_functors) && functors->second.setter != nullptr) { functors->second.setter(value); } else { SURGSIM_FAILURE() << "Can't set property: " << name << "." << ((functors == std::end(m_functors)) ? "Property not found." : "No setter defined for property."); } } void Accessible::setGetter(const std::string& name, GetterType func) { SURGSIM_ASSERT(func != nullptr) << "Getter functor can't be nullptr"; m_functors[name].getter = func; } void Accessible::setSetter(const std::string& name, SetterType func) { SURGSIM_ASSERT(func != nullptr) << "Setter functor can't be nullptr"; m_functors[name].setter = func; } void Accessible::setAccessors(const std::string& name, GetterType getter, SetterType setter) { setGetter(name, getter); setSetter(name, setter); } void Accessible::removeAccessors(const std::string& name) { auto functors = m_functors.find(name); if (functors != std::end(m_functors)) { functors->second.setter = nullptr; functors->second.getter = nullptr; } } bool Accessible::isReadable(const std::string& name) const { auto functors = m_functors.find(name); return (functors != m_functors.end() && functors->second.getter != nullptr); } bool Accessible::isWriteable(const std::string& name) const { auto functors = m_functors.find(name); return (functors != m_functors.end() && functors->second.setter != nullptr); } void Accessible::setSerializable(const std::string& name, EncoderType encoder, DecoderType decoder) { SURGSIM_ASSERT(encoder != nullptr) << "Encoder functor can't be nullptr."; SURGSIM_ASSERT(decoder != nullptr) << "Decoder functor can't be nullptr."; m_functors[name].encoder = encoder; m_functors[name].decoder = decoder; } YAML::Node Accessible::encode() const { YAML::Node result; for (auto functors = m_functors.cbegin(); functors != m_functors.cend(); ++functors) { auto encoder = functors->second.encoder; if (encoder != nullptr) { result[functors->first] = encoder(); } } return result; } void Accessible::decode(const YAML::Node& node, const std::vector<std::string>& ignoredProperties) { SURGSIM_ASSERT(node.IsMap()) << "Node to be decoded has to be map."; for (auto data = node.begin(); data != node.end(); ++data) { std::string name = data->first.as<std::string>(); if (std::find(std::begin(ignoredProperties), std::end(ignoredProperties), name) != std::end(ignoredProperties)) { continue; } auto functors = m_functors.find(name); if (functors == std::end(m_functors) || !functors->second.decoder) { SURGSIM_LOG_WARNING(SurgSim::Framework::Logger::getLogger("Framework/Accessible")) << "Can't find property with name " << name << " in the accessible."; } else { YAML::Node temporary = data->second; if (!temporary.IsNull() && temporary.IsDefined()) { try { functors->second.decoder(&temporary); } catch (std::exception e) { SURGSIM_FAILURE() << e.what(); } } else { SURGSIM_LOG_INFO(SurgSim::Framework::Logger::getLogger("Framework/Accessible")) << "Found property with name " << name << " in the accessible." << " But it seems no value is specified for this property in the YAML file."; } } } } void Accessible::forwardProperty(const std::string& name, const Accessible& target, const std::string& targetValueName) { Functors functors; auto found = target.m_functors.find(targetValueName); if (found != target.m_functors.end()) { functors.getter = found->second.getter; functors.setter = found->second.setter; m_functors[name] = std::move(functors); } else { SURGSIM_FAILURE() << "Target does not have any setters or getters on property " << targetValueName; } } template<> SurgSim::Math::Matrix44f convert(boost::any val) { SurgSim::Math::Matrix44f floatResult; // Use try in case this conversion was created using a Matrix44f, in which case the any_cast will // still fail and throw an exception try { SurgSim::Math::Matrix44d result = boost::any_cast<SurgSim::Math::Matrix44d>(val); floatResult = result.cast<float>(); } catch (boost::bad_any_cast&) { floatResult = boost::any_cast<SurgSim::Math::Matrix44f>(val); } return floatResult; } }; // Framework }; // SurgSim
Update warning message
Update warning message
C++
apache-2.0
simquest/opensurgsim,simquest/opensurgsim,simquest/opensurgsim,simquest/opensurgsim
08f7ea9c56fdb0b5a0f5ce69aa50794aab8fbee4
toml/source_location.hpp
toml/source_location.hpp
// Copyright Toru Niina 2019. // Distributed under the MIT License. #ifndef TOML11_SOURCE_LOCATION_HPP #define TOML11_SOURCE_LOCATION_HPP #include <cstdint> #include "region.hpp" namespace toml { // A struct to contain location in a toml file. // The interface imitates std::experimental::source_location, // but not completely the same. // // It would be constructed by toml::value. It can be used to generate // user-defined error messages. // // - std::uint_least32_t line() const noexcept // - returns the line number where the region is on. // - std::uint_least32_t column() const noexcept // - returns the column number where the region starts. // - std::uint_least32_t region() const noexcept // - returns the size of the region. // // +-- line() +-- region of interest (region() == 9) // v .---+---. // 12 | value = "foo bar" // ^ // +-- column() // // - std::string const& file_name() const noexcept; // - name of the file. // - std::string const& line_str() const noexcept; // - the whole line that contains the region of interest. // struct source_location { public: source_location() : line_num_(1), column_num_(1), region_size_(1), file_name_("unknown file"), line_str_("") {} explicit source_location(const detail::region_base* reg) : line_num_(1), column_num_(1), region_size_(1), file_name_("unknown file"), line_str_("") { if(reg) { if(reg->line_num() != detail::region_base().line_num()) { line_num_ = static_cast<std::uint_least32_t>( std::stoul(reg->line_num())); } column_num_ = static_cast<std::uint_least32_t>(reg->before() + 1); region_size_ = static_cast<std::uint_least32_t>(reg->size()); file_name_ = reg->name(); line_str_ = reg->line(); } } explicit source_location(const detail::region& reg) : line_num_(static_cast<std::uint_least32_t>(std::stoul(reg.line_num()))), column_num_(static_cast<std::uint_least32_t>(reg.before() + 1)), region_size_(static_cast<std::uint_least32_t>(reg.size())), file_name_(reg.name()), line_str_ (reg.line()) {} explicit source_location(const detail::location& loc) : line_num_(static_cast<std::uint_least32_t>(std::stoul(loc.line_num()))), column_num_(static_cast<std::uint_least32_t>(loc.before() + 1)), region_size_(static_cast<std::uint_least32_t>(loc.size())), file_name_(loc.name()), line_str_ (loc.line()) {} ~source_location() = default; source_location(source_location const&) = default; source_location(source_location &&) = default; source_location& operator=(source_location const&) = default; source_location& operator=(source_location &&) = default; std::uint_least32_t line() const noexcept {return line_num_;} std::uint_least32_t column() const noexcept {return column_num_;} std::uint_least32_t region() const noexcept {return region_size_;} std::string const& file_name() const noexcept {return file_name_;} std::string const& line_str() const noexcept {return line_str_;} private: std::uint_least32_t line_num_; std::uint_least32_t column_num_; std::uint_least32_t region_size_; std::string file_name_; std::string line_str_; }; namespace detail { // internal error message generation. inline std::string format_underline(const std::string& message, const std::vector<std::pair<source_location, std::string>>& loc_com, const std::vector<std::string>& helps = {}, const bool colorize = TOML11_ERROR_MESSAGE_COLORIZED) { std::size_t line_num_width = 0; for(const auto& lc : loc_com) { std::uint_least32_t line = lc.first.line(); std::size_t digit = 0; while(line != 0) { line /= 10; digit += 1; } line_num_width = (std::max)(line_num_width, digit); } // 1 is the minimum width line_num_width = std::max<std::size_t>(line_num_width, 1); std::ostringstream retval; if(colorize) { retval << color::colorize; // turn on ANSI color } // XXX // Here, before `colorize` support, it does not output `[error]` prefix // automatically. So some user may output it manually and this change may // duplicate the prefix. To avoid it, check the first 7 characters and // if it is "[error]", it removes that part from the message shown. if(message.size() > 7 && message.substr(0, 7) == "[error]") { retval << color::bold << color::red << "[error]" << color::reset << color::bold << message.substr(7) << color::reset << '\n'; } else { retval << color::bold << color::red << "[error] " << color::reset << color::bold << message << color::reset << '\n'; } const auto format_one_location = [line_num_width] (std::ostringstream& oss, const source_location& loc, const std::string& comment) -> void { oss << ' ' << color::bold << color::blue << std::setw(static_cast<int>(line_num_width)) << std::right << loc.line() << " | " << color::reset << loc.line_str() << '\n'; oss << make_string(line_num_width + 1, ' ') << color::bold << color::blue << " | " << color::reset << make_string(loc.column()-1 /*1-origin*/, ' '); if(loc.region() == 1) { // invalid // ^------ oss << color::bold << color::red << "^---" << color::reset; } else { // invalid // ~~~~~~~ const auto underline_len = (std::min)( static_cast<std::size_t>(loc.region()), loc.line_str().size()); oss << color::bold << color::red << make_string(underline_len, '~') << color::reset; } oss << ' '; oss << comment; return; }; assert(!loc_com.empty()); // --> example.toml // | retval << color::bold << color::blue << " --> " << color::reset << loc_com.front().first.file_name() << '\n'; retval << make_string(line_num_width + 1, ' ') << color::bold << color::blue << " | " << color::reset << '\n'; // 1 | key value // | ^--- missing = format_one_location(retval, loc_com.front().first, loc_com.front().second); // process the rest of the locations for(std::size_t i=1; i<loc_com.size(); ++i) { const auto& prev = loc_com.at(i-1); const auto& curr = loc_com.at(i); retval << '\n'; // if the filenames are the same, print "..." if(prev.first.file_name() == curr.first.file_name()) { retval << color::bold << color::blue << " ...\n" << color::reset; } else // if filename differs, print " --> filename.toml" again { retval << color::bold << color::blue << " --> " << color::reset << curr.first.file_name() << '\n'; retval << make_string(line_num_width + 1, ' ') << color::bold << color::blue << " |\n" << color::reset; } format_one_location(retval, curr.first, curr.second); } if(!helps.empty()) { retval << '\n'; retval << make_string(line_num_width + 1, ' '); retval << color::bold << color::blue << " | " << color::reset; for(const auto& help : helps) { retval << color::bold << "\nHint: " << color::reset; retval << help; } } return retval.str(); } } // detail } // toml #endif// TOML11_SOURCE_LOCATION_HPP
// Copyright Toru Niina 2019. // Distributed under the MIT License. #ifndef TOML11_SOURCE_LOCATION_HPP #define TOML11_SOURCE_LOCATION_HPP #include <cstdint> #include "region.hpp" namespace toml { // A struct to contain location in a toml file. // The interface imitates std::experimental::source_location, // but not completely the same. // // It would be constructed by toml::value. It can be used to generate // user-defined error messages. // // - std::uint_least32_t line() const noexcept // - returns the line number where the region is on. // - std::uint_least32_t column() const noexcept // - returns the column number where the region starts. // - std::uint_least32_t region() const noexcept // - returns the size of the region. // // +-- line() +-- region of interest (region() == 9) // v .---+---. // 12 | value = "foo bar" // ^ // +-- column() // // - std::string const& file_name() const noexcept; // - name of the file. // - std::string const& line_str() const noexcept; // - the whole line that contains the region of interest. // struct source_location { public: source_location() : line_num_(1), column_num_(1), region_size_(1), file_name_("unknown file"), line_str_("") {} explicit source_location(const detail::region_base* reg) : line_num_(1), column_num_(1), region_size_(1), file_name_("unknown file"), line_str_("") { if(reg) { if(reg->line_num() != detail::region_base().line_num()) { line_num_ = static_cast<std::uint_least32_t>( std::stoul(reg->line_num())); } column_num_ = static_cast<std::uint_least32_t>(reg->before() + 1); region_size_ = static_cast<std::uint_least32_t>(reg->size()); file_name_ = reg->name(); line_str_ = reg->line(); } } explicit source_location(const detail::region& reg) : line_num_(static_cast<std::uint_least32_t>(std::stoul(reg.line_num()))), column_num_(static_cast<std::uint_least32_t>(reg.before() + 1)), region_size_(static_cast<std::uint_least32_t>(reg.size())), file_name_(reg.name()), line_str_ (reg.line()) {} explicit source_location(const detail::location& loc) : line_num_(static_cast<std::uint_least32_t>(std::stoul(loc.line_num()))), column_num_(static_cast<std::uint_least32_t>(loc.before() + 1)), region_size_(static_cast<std::uint_least32_t>(loc.size())), file_name_(loc.name()), line_str_ (loc.line()) {} ~source_location() = default; source_location(source_location const&) = default; source_location(source_location &&) = default; source_location& operator=(source_location const&) = default; source_location& operator=(source_location &&) = default; std::uint_least32_t line() const noexcept {return line_num_;} std::uint_least32_t column() const noexcept {return column_num_;} std::uint_least32_t region() const noexcept {return region_size_;} std::string const& file_name() const noexcept {return file_name_;} std::string const& line_str() const noexcept {return line_str_;} private: std::uint_least32_t line_num_; std::uint_least32_t column_num_; std::uint_least32_t region_size_; std::string file_name_; std::string line_str_; }; namespace detail { // internal error message generation. inline std::string format_underline(const std::string& message, const std::vector<std::pair<source_location, std::string>>& loc_com, const std::vector<std::string>& helps = {}, const bool colorize = TOML11_ERROR_MESSAGE_COLORIZED) { std::size_t line_num_width = 0; for(const auto& lc : loc_com) { std::uint_least32_t line = lc.first.line(); std::size_t digit = 0; while(line != 0) { line /= 10; digit += 1; } line_num_width = (std::max)(line_num_width, digit); } // 1 is the minimum width line_num_width = std::max<std::size_t>(line_num_width, 1); std::ostringstream retval; if(colorize) { retval << color::colorize; // turn on ANSI color } // XXX // Here, before `colorize` support, it does not output `[error]` prefix // automatically. So some user may output it manually and this change may // duplicate the prefix. To avoid it, check the first 7 characters and // if it is "[error]", it removes that part from the message shown. if(message.size() > 7 && message.substr(0, 7) == "[error]") { retval << color::bold << color::red << "[error]" << color::reset << color::bold << message.substr(7) << color::reset << '\n'; } else { retval << color::bold << color::red << "[error] " << color::reset << color::bold << message << color::reset << '\n'; } const auto format_one_location = [line_num_width] (std::ostringstream& oss, const source_location& loc, const std::string& comment) -> void { oss << ' ' << color::bold << color::blue << std::setw(static_cast<int>(line_num_width)) << std::right << loc.line() << " | " << color::reset << loc.line_str() << '\n'; oss << make_string(line_num_width + 1, ' ') << color::bold << color::blue << " | " << color::reset << make_string(loc.column()-1 /*1-origin*/, ' '); if(loc.region() == 1) { // invalid // ^------ oss << color::bold << color::red << "^---" << color::reset; } else { // invalid // ~~~~~~~ const auto underline_len = (std::min)( static_cast<std::size_t>(loc.region()), loc.line_str().size()); oss << color::bold << color::red << make_string(underline_len, '~') << color::reset; } oss << ' '; oss << comment; return; }; assert(!loc_com.empty()); // --> example.toml // | retval << color::bold << color::blue << " --> " << color::reset << loc_com.front().first.file_name() << '\n'; retval << make_string(line_num_width + 1, ' ') << color::bold << color::blue << " |\n" << color::reset; // 1 | key value // | ^--- missing = format_one_location(retval, loc_com.front().first, loc_com.front().second); // process the rest of the locations for(std::size_t i=1; i<loc_com.size(); ++i) { const auto& prev = loc_com.at(i-1); const auto& curr = loc_com.at(i); retval << '\n'; // if the filenames are the same, print "..." if(prev.first.file_name() == curr.first.file_name()) { retval << color::bold << color::blue << " ...\n" << color::reset; } else // if filename differs, print " --> filename.toml" again { retval << color::bold << color::blue << " --> " << color::reset << curr.first.file_name() << '\n'; retval << make_string(line_num_width + 1, ' ') << color::bold << color::blue << " |\n" << color::reset; } format_one_location(retval, curr.first, curr.second); } if(!helps.empty()) { retval << '\n'; retval << make_string(line_num_width + 1, ' '); retval << color::bold << color::blue << " |" << color::reset; for(const auto& help : helps) { retval << color::bold << "\nHint: " << color::reset; retval << help; } } return retval.str(); } } // detail } // toml #endif// TOML11_SOURCE_LOCATION_HPP
remove extraneous whitespaces in errmsg
refactor: remove extraneous whitespaces in errmsg
C++
mit
ToruNiina/toml11
d8b7c188dc7f76318bf331dc944253ac59ab193a
tomviz/ModuleContour.cxx
tomviz/ModuleContour.cxx
/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "ModuleContour.h" #include "DataSource.h" #include "DoubleSliderWidget.h" #include "Utilities.h" #include "pqColorChooserButton.h" #include "pqPropertyLinks.h" #include "pqSignalAdaptors.h" #include "pqWidgetRangeDomain.h" #include "vtkDataObject.h" #include "vtkNew.h" #include "vtkSMParaViewPipelineControllerWithRendering.h" #include "vtkSMPropertyHelper.h" #include "vtkSMSessionProxyManager.h" #include "vtkSMSourceProxy.h" #include "vtkSMViewProxy.h" #include "vtkSmartPointer.h" #include <algorithm> #include <string> #include <vector> #include <QCheckBox> #include <QComboBox> #include <QFormLayout> #include <QLabel> namespace tomviz { class ModuleContour::Private { public: std::string ColorArrayName; bool UseSolidColor; pqPropertyLinks Links; }; ModuleContour::ModuleContour(QObject* parentObject) : Superclass(parentObject) { this->Internals = new Private; this->Internals->Links.setAutoUpdateVTKObjects(true); this->Internals->UseSolidColor = false; } ModuleContour::~ModuleContour() { this->finalize(); delete this->Internals; this->Internals = nullptr; } QIcon ModuleContour::icon() const { return QIcon(":/pqWidgets/Icons/pqIsosurface24.png"); } bool ModuleContour::initialize(DataSource* data, vtkSMViewProxy* vtkView) { if (!this->Superclass::initialize(data, vtkView)) { return false; } vtkSMSourceProxy* producer = data->producer(); vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller; vtkSMSessionProxyManager* pxm = producer->GetSessionProxyManager(); vtkSmartPointer<vtkSMProxy> contourProxy; contourProxy.TakeReference(pxm->NewProxy("filters", "FlyingEdges")); this->ContourFilter = vtkSMSourceProxy::SafeDownCast(contourProxy); Q_ASSERT(this->ContourFilter); controller->PreInitializeProxy(this->ContourFilter); vtkSMPropertyHelper(this->ContourFilter, "Input").Set(producer); vtkSMPropertyHelper(this->ContourFilter, "ComputeScalars", /*quiet*/ true) .Set(1); controller->PostInitializeProxy(this->ContourFilter); controller->RegisterPipelineProxy(this->ContourFilter); // Set up a data resampler to add LabelMap values on the contour vtkSmartPointer<vtkSMProxy> probeProxy; probeProxy.TakeReference(pxm->NewProxy("filters", "ResampleWithDataset")); this->ResampleFilter = vtkSMSourceProxy::SafeDownCast(probeProxy); Q_ASSERT(this->ResampleFilter); controller->PreInitializeProxy(this->ResampleFilter); vtkSMPropertyHelper(this->ResampleFilter, "Input").Set(data->producer()); vtkSMPropertyHelper(this->ResampleFilter, "Source").Set(this->ContourFilter); controller->PostInitializeProxy(this->ResampleFilter); controller->RegisterPipelineProxy(this->ResampleFilter); // Create the representation for it. Show the unresampled contour filter to // start. this->ContourRepresentation = controller->Show(this->ContourFilter, 0, vtkView); Q_ASSERT(this->ContourRepresentation); vtkSMPropertyHelper(this->ContourRepresentation, "Representation") .Set("Surface"); vtkSMPropertyHelper(this->ContourRepresentation, "Position") .Set(data->displayPosition(), 3); vtkSMPropertyHelper colorArrayHelper(this->ContourRepresentation, "ColorArrayName"); this->Internals->ColorArrayName = std::string(colorArrayHelper.GetInputArrayNameToProcess()); vtkSMPropertyHelper colorHelper(this->ContourRepresentation, "DiffuseColor"); double white[3] = { 1.0, 1.0, 1.0 }; colorHelper.Set(white, 3); // use proper color map. this->updateColorMap(); this->ContourRepresentation->UpdateVTKObjects(); return true; } void ModuleContour::updateColorMap() { Q_ASSERT(this->ContourRepresentation); vtkSMPropertyHelper(this->ContourRepresentation, "LookupTable") .Set(this->colorMap()); vtkSMPropertyHelper colorArrayHelper(this->ContourRepresentation, "ColorArrayName"); if (this->Internals->UseSolidColor) { colorArrayHelper.SetInputArrayToProcess( vtkDataObject::FIELD_ASSOCIATION_POINTS, ""); } else { colorArrayHelper.SetInputArrayToProcess( vtkDataObject::FIELD_ASSOCIATION_POINTS, this->Internals->ColorArrayName.c_str()); } vtkSMPropertyHelper(this->ContourRepresentation, "Input") .Set(this->ContourFilter); vtkSMPropertyHelper(this->ContourRepresentation, "Visibility") .Set(this->visibility() ? 1 : 0); this->ContourRepresentation->UpdateVTKObjects(); } bool ModuleContour::finalize() { vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller; controller->UnRegisterProxy(this->ResampleFilter); controller->UnRegisterProxy(this->ContourRepresentation); controller->UnRegisterProxy(this->ContourFilter); this->ResampleFilter = nullptr; this->ContourFilter = nullptr; this->ContourRepresentation = nullptr; return true; } bool ModuleContour::setVisibility(bool val) { Q_ASSERT(this->ContourRepresentation); vtkSMPropertyHelper(this->ContourRepresentation, "Visibility") .Set(val ? 1 : 0); this->ContourRepresentation->UpdateVTKObjects(); return true; } bool ModuleContour::visibility() const { Q_ASSERT(this->ContourRepresentation); return vtkSMPropertyHelper(this->ContourRepresentation, "Visibility") .GetAsInt() != 0; } void ModuleContour::setIsoValues(const QList<double>& values) { std::vector<double> vectorValues(values.size()); std::copy(values.begin(), values.end(), vectorValues.begin()); vectorValues.push_back(0); // to avoid having to check for 0 size on Windows. vtkSMPropertyHelper(this->ContourFilter, "ContourValues") .Set(&vectorValues[0], values.size()); this->ContourFilter->UpdateVTKObjects(); } void ModuleContour::addToPanel(QWidget* panel) { Q_ASSERT(this->ContourFilter); Q_ASSERT(this->ContourRepresentation); if (panel->layout()) { delete panel->layout(); } QFormLayout* layout = new QFormLayout; // Solid color QHBoxLayout* colorLayout = new QHBoxLayout; colorLayout->addStretch(); QCheckBox* useSolidColor = new QCheckBox; useSolidColor->setChecked(this->Internals->UseSolidColor); QObject::connect(useSolidColor, &QCheckBox::stateChanged, this, &ModuleContour::setUseSolidColor); colorLayout->addWidget(useSolidColor); QLabel* colorLabel = new QLabel("Select Color"); colorLayout->addWidget(colorLabel); pqColorChooserButton* colorSelector = new pqColorChooserButton(panel); colorLayout->addWidget(colorSelector); layout->addRow("", colorLayout); colorSelector->setShowAlphaChannel(false); DoubleSliderWidget* valueSlider = new DoubleSliderWidget(true); valueSlider->setLineEditWidth(50); layout->addRow("Value", valueSlider); QComboBox* representations = new QComboBox; representations->addItem("Surface"); representations->addItem("Wireframe"); representations->addItem("Points"); layout->addRow("", representations); // TODO connect to update function DoubleSliderWidget* opacitySlider = new DoubleSliderWidget(true); opacitySlider->setLineEditWidth(50); layout->addRow("Opacity", opacitySlider); DoubleSliderWidget* specularSlider = new DoubleSliderWidget(true); specularSlider->setLineEditWidth(50); layout->addRow("Specular", specularSlider); pqSignalAdaptorComboBox* adaptor = new pqSignalAdaptorComboBox(representations); // layout->addStretch(); panel->setLayout(layout); this->Internals->Links.addPropertyLink( valueSlider, "value", SIGNAL(valueEdited(double)), this->ContourFilter, this->ContourFilter->GetProperty("ContourValues"), 0); new pqWidgetRangeDomain(valueSlider, "minimum", "maximum", this->ContourFilter->GetProperty("ContourValues"), 0); this->Internals->Links.addPropertyLink( adaptor, "currentText", SIGNAL(currentTextChanged(QString)), this->ContourRepresentation, this->ContourRepresentation->GetProperty("Representation")); this->Internals->Links.addPropertyLink( opacitySlider, "value", SIGNAL(valueEdited(double)), this->ContourRepresentation, this->ContourRepresentation->GetProperty("Opacity"), 0); this->Internals->Links.addPropertyLink( specularSlider, "value", SIGNAL(valueEdited(double)), this->ContourRepresentation, this->ContourRepresentation->GetProperty("Specular"), 0); // Surface uses DiffuseColor and Wireframe uses AmbientColor so we have to set // both this->Internals->Links.addPropertyLink( colorSelector, "chosenColorRgbF", SIGNAL(chosenColorChanged(const QColor&)), this->ContourRepresentation, this->ContourRepresentation->GetProperty("DiffuseColor")); this->Internals->Links.addPropertyLink( colorSelector, "chosenColorRgbF", SIGNAL(chosenColorChanged(const QColor&)), this->ContourRepresentation, this->ContourRepresentation->GetProperty("AmbientColor")); this->connect(valueSlider, &DoubleSliderWidget::valueEdited, this, &ModuleContour::dataUpdated); this->connect(representations, &QComboBox::currentTextChanged, this, &ModuleContour::dataUpdated); this->connect(opacitySlider, &DoubleSliderWidget::valueEdited, this, &ModuleContour::dataUpdated); this->connect(specularSlider, &DoubleSliderWidget::valueEdited, this, &ModuleContour::dataUpdated); this->connect(colorSelector, &pqColorChooserButton::chosenColorChanged, this, &ModuleContour::dataUpdated); } void ModuleContour::dataUpdated() { this->Internals->Links.accept(); emit this->renderNeeded(); } bool ModuleContour::serialize(pugi::xml_node& ns) const { ns.append_attribute("solid_color").set_value(this->Internals->UseSolidColor); // save stuff that the user can change. pugi::xml_node node = ns.append_child("ContourFilter"); QStringList contourProperties; contourProperties << "ContourValues"; if (tomviz::serialize(this->ContourFilter, node, contourProperties) == false) { qWarning("Failed to serialize ContourFilter."); ns.remove_child(node); return false; } QStringList contourRepresentationProperties; contourRepresentationProperties << "Representation" << "Opacity" << "Specular" << "Visibility" << "DiffuseColor"; node = ns.append_child("ContourRepresentation"); if (tomviz::serialize(this->ContourRepresentation, node, contourRepresentationProperties) == false) { qWarning("Failed to serialize ContourRepresentation."); ns.remove_child(node); return false; } return this->Superclass::serialize(ns); } bool ModuleContour::deserialize(const pugi::xml_node& ns) { if (ns.attribute("solid_color")) { this->Internals->UseSolidColor = ns.attribute("solid_color").as_bool(); } return tomviz::deserialize(this->ContourFilter, ns.child("ContourFilter")) && tomviz::deserialize(this->ContourRepresentation, ns.child("ContourRepresentation")) && this->Superclass::deserialize(ns); } void ModuleContour::dataSourceMoved(double newX, double newY, double newZ) { double pos[3] = { newX, newY, newZ }; vtkSMPropertyHelper(this->ContourRepresentation, "Position").Set(pos, 3); this->ContourRepresentation->MarkDirty(this->ContourRepresentation); this->ContourRepresentation->UpdateVTKObjects(); } bool ModuleContour::isProxyPartOfModule(vtkSMProxy* proxy) { return (proxy == this->ContourFilter.Get()) || (proxy == this->ContourRepresentation.Get()) || (proxy == this->ResampleFilter.Get()); } std::string ModuleContour::getStringForProxy(vtkSMProxy* proxy) { if (proxy == this->ContourFilter.Get()) { return "Contour"; } else if (proxy == this->ContourRepresentation.Get()) { return "Representation"; } else if (proxy == this->ResampleFilter.Get()) { return "Resample"; } else { qWarning("Gave bad proxy to module in save animation state"); return ""; } } vtkSMProxy* ModuleContour::getProxyForString(const std::string& str) { if (str == "Resample") { return this->ResampleFilter.Get(); } else if (str == "Representation") { return this->ContourRepresentation.Get(); } else if (str == "Contour") { return this->ContourFilter.Get(); } else { return nullptr; } } void ModuleContour::setUseSolidColor(int useSolidColor) { this->Internals->UseSolidColor = (useSolidColor != 0); this->updateColorMap(); emit this->renderNeeded(); } } // end of namespace tomviz
/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "ModuleContour.h" #include "DataSource.h" #include "DoubleSliderWidget.h" #include "Utilities.h" #include "pqColorChooserButton.h" #include "pqPropertyLinks.h" #include "pqSignalAdaptors.h" #include "pqWidgetRangeDomain.h" #include "vtkDataObject.h" #include "vtkNew.h" #include "vtkSMParaViewPipelineControllerWithRendering.h" #include "vtkSMPropertyHelper.h" #include "vtkSMSessionProxyManager.h" #include "vtkSMSourceProxy.h" #include "vtkSMViewProxy.h" #include "vtkSmartPointer.h" #include <algorithm> #include <string> #include <vector> #include <QCheckBox> #include <QComboBox> #include <QFormLayout> #include <QLabel> namespace tomviz { class ModuleContour::Private { public: std::string ColorArrayName; bool UseSolidColor; pqPropertyLinks Links; }; ModuleContour::ModuleContour(QObject* parentObject) : Superclass(parentObject) { this->Internals = new Private; this->Internals->Links.setAutoUpdateVTKObjects(true); this->Internals->UseSolidColor = false; } ModuleContour::~ModuleContour() { this->finalize(); delete this->Internals; this->Internals = nullptr; } QIcon ModuleContour::icon() const { return QIcon(":/pqWidgets/Icons/pqIsosurface24.png"); } bool ModuleContour::initialize(DataSource* data, vtkSMViewProxy* vtkView) { if (!this->Superclass::initialize(data, vtkView)) { return false; } vtkSMSourceProxy* producer = data->producer(); vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller; vtkSMSessionProxyManager* pxm = producer->GetSessionProxyManager(); vtkSmartPointer<vtkSMProxy> contourProxy; contourProxy.TakeReference(pxm->NewProxy("filters", "FlyingEdges")); this->ContourFilter = vtkSMSourceProxy::SafeDownCast(contourProxy); Q_ASSERT(this->ContourFilter); controller->PreInitializeProxy(this->ContourFilter); vtkSMPropertyHelper(this->ContourFilter, "Input").Set(producer); vtkSMPropertyHelper(this->ContourFilter, "ComputeScalars", /*quiet*/ true) .Set(1); controller->PostInitializeProxy(this->ContourFilter); controller->RegisterPipelineProxy(this->ContourFilter); // Set up a data resampler to add LabelMap values on the contour vtkSmartPointer<vtkSMProxy> probeProxy; probeProxy.TakeReference(pxm->NewProxy("filters", "ResampleWithDataset")); this->ResampleFilter = vtkSMSourceProxy::SafeDownCast(probeProxy); Q_ASSERT(this->ResampleFilter); controller->PreInitializeProxy(this->ResampleFilter); vtkSMPropertyHelper(this->ResampleFilter, "Input").Set(data->producer()); vtkSMPropertyHelper(this->ResampleFilter, "Source").Set(this->ContourFilter); controller->PostInitializeProxy(this->ResampleFilter); controller->RegisterPipelineProxy(this->ResampleFilter); // Create the representation for it. Show the unresampled contour filter to // start. this->ContourRepresentation = controller->Show(this->ContourFilter, 0, vtkView); Q_ASSERT(this->ContourRepresentation); vtkSMPropertyHelper(this->ContourRepresentation, "Representation") .Set("Surface"); vtkSMPropertyHelper(this->ContourRepresentation, "Position") .Set(data->displayPosition(), 3); vtkSMPropertyHelper colorArrayHelper(this->ContourRepresentation, "ColorArrayName"); this->Internals->ColorArrayName = std::string(colorArrayHelper.GetInputArrayNameToProcess()); vtkSMPropertyHelper colorHelper(this->ContourRepresentation, "DiffuseColor"); double white[3] = { 1.0, 1.0, 1.0 }; colorHelper.Set(white, 3); // use proper color map. this->updateColorMap(); this->ContourRepresentation->UpdateVTKObjects(); return true; } void ModuleContour::updateColorMap() { Q_ASSERT(this->ContourRepresentation); vtkSMPropertyHelper(this->ContourRepresentation, "LookupTable") .Set(this->colorMap()); vtkSMPropertyHelper colorArrayHelper(this->ContourRepresentation, "ColorArrayName"); if (this->Internals->UseSolidColor) { colorArrayHelper.SetInputArrayToProcess( vtkDataObject::FIELD_ASSOCIATION_POINTS, ""); } else { colorArrayHelper.SetInputArrayToProcess( vtkDataObject::FIELD_ASSOCIATION_POINTS, this->Internals->ColorArrayName.c_str()); } vtkSMPropertyHelper(this->ContourRepresentation, "Input") .Set(this->ContourFilter); vtkSMPropertyHelper(this->ContourRepresentation, "Visibility") .Set(this->visibility() ? 1 : 0); this->ContourRepresentation->UpdateVTKObjects(); } bool ModuleContour::finalize() { vtkNew<vtkSMParaViewPipelineControllerWithRendering> controller; controller->UnRegisterProxy(this->ResampleFilter); controller->UnRegisterProxy(this->ContourRepresentation); controller->UnRegisterProxy(this->ContourFilter); this->ResampleFilter = nullptr; this->ContourFilter = nullptr; this->ContourRepresentation = nullptr; return true; } bool ModuleContour::setVisibility(bool val) { Q_ASSERT(this->ContourRepresentation); vtkSMPropertyHelper(this->ContourRepresentation, "Visibility") .Set(val ? 1 : 0); this->ContourRepresentation->UpdateVTKObjects(); return true; } bool ModuleContour::visibility() const { Q_ASSERT(this->ContourRepresentation); return vtkSMPropertyHelper(this->ContourRepresentation, "Visibility") .GetAsInt() != 0; } void ModuleContour::setIsoValues(const QList<double>& values) { std::vector<double> vectorValues(values.size()); std::copy(values.begin(), values.end(), vectorValues.begin()); vectorValues.push_back(0); // to avoid having to check for 0 size on Windows. vtkSMPropertyHelper(this->ContourFilter, "ContourValues") .Set(&vectorValues[0], values.size()); this->ContourFilter->UpdateVTKObjects(); } void ModuleContour::addToPanel(QWidget* panel) { Q_ASSERT(this->ContourFilter); Q_ASSERT(this->ContourRepresentation); if (panel->layout()) { delete panel->layout(); } QFormLayout* layout = new QFormLayout; // Solid color QHBoxLayout* colorLayout = new QHBoxLayout; colorLayout->addStretch(); QCheckBox* useSolidColor = new QCheckBox; useSolidColor->setChecked(this->Internals->UseSolidColor); QObject::connect(useSolidColor, &QCheckBox::stateChanged, this, &ModuleContour::setUseSolidColor); colorLayout->addWidget(useSolidColor); QLabel* colorLabel = new QLabel("Select Color"); colorLayout->addWidget(colorLabel); pqColorChooserButton* colorSelector = new pqColorChooserButton(panel); colorLayout->addWidget(colorSelector); layout->addRow("", colorLayout); colorSelector->setShowAlphaChannel(false); DoubleSliderWidget* valueSlider = new DoubleSliderWidget(true); valueSlider->setLineEditWidth(50); layout->addRow("Value", valueSlider); QComboBox* representations = new QComboBox; representations->addItem("Surface"); representations->addItem("Wireframe"); representations->addItem("Points"); layout->addRow("", representations); // TODO connect to update function DoubleSliderWidget* opacitySlider = new DoubleSliderWidget(true); opacitySlider->setLineEditWidth(50); layout->addRow("Opacity", opacitySlider); DoubleSliderWidget* specularSlider = new DoubleSliderWidget(true); specularSlider->setLineEditWidth(50); layout->addRow("Specular", specularSlider); pqSignalAdaptorComboBox* adaptor = new pqSignalAdaptorComboBox(representations); // layout->addStretch(); panel->setLayout(layout); this->Internals->Links.addPropertyLink( valueSlider, "value", SIGNAL(valueEdited(double)), this->ContourFilter, this->ContourFilter->GetProperty("ContourValues"), 0); new pqWidgetRangeDomain(valueSlider, "minimum", "maximum", this->ContourFilter->GetProperty("ContourValues"), 0); this->Internals->Links.addPropertyLink( adaptor, "currentText", SIGNAL(currentTextChanged(QString)), this->ContourRepresentation, this->ContourRepresentation->GetProperty("Representation")); this->Internals->Links.addPropertyLink( opacitySlider, "value", SIGNAL(valueEdited(double)), this->ContourRepresentation, this->ContourRepresentation->GetProperty("Opacity"), 0); this->Internals->Links.addPropertyLink( specularSlider, "value", SIGNAL(valueEdited(double)), this->ContourRepresentation, this->ContourRepresentation->GetProperty("Specular"), 0); // Surface uses DiffuseColor and Wireframe uses AmbientColor so we have to set // both this->Internals->Links.addPropertyLink( colorSelector, "chosenColorRgbF", SIGNAL(chosenColorChanged(const QColor&)), this->ContourRepresentation, this->ContourRepresentation->GetProperty("DiffuseColor")); this->Internals->Links.addPropertyLink( colorSelector, "chosenColorRgbF", SIGNAL(chosenColorChanged(const QColor&)), this->ContourRepresentation, this->ContourRepresentation->GetProperty("AmbientColor")); this->connect(valueSlider, &DoubleSliderWidget::valueEdited, this, &ModuleContour::dataUpdated); this->connect(representations, &QComboBox::currentTextChanged, this, &ModuleContour::dataUpdated); this->connect(opacitySlider, &DoubleSliderWidget::valueEdited, this, &ModuleContour::dataUpdated); this->connect(specularSlider, &DoubleSliderWidget::valueEdited, this, &ModuleContour::dataUpdated); this->connect(colorSelector, &pqColorChooserButton::chosenColorChanged, this, &ModuleContour::dataUpdated); } void ModuleContour::dataUpdated() { this->Internals->Links.accept(); emit this->renderNeeded(); } bool ModuleContour::serialize(pugi::xml_node& ns) const { ns.append_attribute("solid_color").set_value(this->Internals->UseSolidColor); // save stuff that the user can change. pugi::xml_node node = ns.append_child("ContourFilter"); QStringList contourProperties; contourProperties << "ContourValues"; if (tomviz::serialize(this->ContourFilter, node, contourProperties) == false) { qWarning("Failed to serialize ContourFilter."); ns.remove_child(node); return false; } QStringList contourRepresentationProperties; contourRepresentationProperties << "Representation" << "Opacity" << "Specular" << "Visibility" << "DiffuseColor" << "AmbientColor"; node = ns.append_child("ContourRepresentation"); if (tomviz::serialize(this->ContourRepresentation, node, contourRepresentationProperties) == false) { qWarning("Failed to serialize ContourRepresentation."); ns.remove_child(node); return false; } return this->Superclass::serialize(ns); } bool ModuleContour::deserialize(const pugi::xml_node& ns) { if (ns.attribute("solid_color")) { this->Internals->UseSolidColor = ns.attribute("solid_color").as_bool(); } return tomviz::deserialize(this->ContourFilter, ns.child("ContourFilter")) && tomviz::deserialize(this->ContourRepresentation, ns.child("ContourRepresentation")) && this->Superclass::deserialize(ns); } void ModuleContour::dataSourceMoved(double newX, double newY, double newZ) { double pos[3] = { newX, newY, newZ }; vtkSMPropertyHelper(this->ContourRepresentation, "Position").Set(pos, 3); this->ContourRepresentation->MarkDirty(this->ContourRepresentation); this->ContourRepresentation->UpdateVTKObjects(); } bool ModuleContour::isProxyPartOfModule(vtkSMProxy* proxy) { return (proxy == this->ContourFilter.Get()) || (proxy == this->ContourRepresentation.Get()) || (proxy == this->ResampleFilter.Get()); } std::string ModuleContour::getStringForProxy(vtkSMProxy* proxy) { if (proxy == this->ContourFilter.Get()) { return "Contour"; } else if (proxy == this->ContourRepresentation.Get()) { return "Representation"; } else if (proxy == this->ResampleFilter.Get()) { return "Resample"; } else { qWarning("Gave bad proxy to module in save animation state"); return ""; } } vtkSMProxy* ModuleContour::getProxyForString(const std::string& str) { if (str == "Resample") { return this->ResampleFilter.Get(); } else if (str == "Representation") { return this->ContourRepresentation.Get(); } else if (str == "Contour") { return this->ContourFilter.Get(); } else { return nullptr; } } void ModuleContour::setUseSolidColor(int useSolidColor) { this->Internals->UseSolidColor = (useSolidColor != 0); this->updateColorMap(); emit this->renderNeeded(); } } // end of namespace tomviz
Save the both color properties for contour's solid color
Save the both color properties for contour's solid color Not saving the AmbientColor (needed for coloring wireframes) was causing the solid color to revert to the default ambient color (white) when a state file was loaded.
C++
bsd-3-clause
mathturtle/tomviz,thewtex/tomviz,cjh1/tomviz,OpenChemistry/tomviz,cjh1/tomviz,thewtex/tomviz,mathturtle/tomviz,thewtex/tomviz,OpenChemistry/tomviz,cryos/tomviz,cryos/tomviz,cryos/tomviz,mathturtle/tomviz,cjh1/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz
286938b3c2c767419bcbdafc321d266bfe82e8fe
homework/Feldman/02/calc.cpp
homework/Feldman/02/calc.cpp
#include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <iostream> #include <string.h> using namespace std; int select_operation(int a, int b, char op) {//Функция выбора оберации switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': if (b == 0) throw - 1; return a / b; default: return 0; } } int expr(char*& str); int _expr(char*& str, int left_operand); int term(char*& str); int _term(char*& str, int left_operand); int prim(char*& str); int number(char*& str); void deleteSpace(char* src) { char* dst = src; while (*dst == *src++) if (*dst != ' ') dst++; } int main(int argc, char* argv[]) { if (argc != 2) { //Количество аргументов командной строки не равно 2 cout << "INVALID ARGUMENTS" << endl; return 0; } deleteSpace(argv[1]); for (int i = 0; argv[i] != '\0'; ++i) { if ((argv[1][i] == '+' || argv[1][i] == '-' || argv[1][i] == '*' || argv[1][i] == '/') && (argv[1][i] != '-' && !(isdigit(argv[1][i + 1])))) { cout << "INVALID EXPRESSION!" << endl; return 0; } if (!isdigit(argv[1][i])) if (argv[1][i] != '+' && argv[1][i] != '-' && argv[1][i] != '*' && argv[1][i] != '/') { cout << "INVALID EXPRESSION!" << endl; return 0; } } cout << expr(argv[1]) << endl; return 0; } /*Далее под операндом будем понимать произведение | частное |число * под выражением будем понимать сумму | разность операндов */ int expr(char*& str) { int left_operand = term(str); //Левый операнд выражения if (*str == '+' || *str == '-') { //Если он не единственный return _expr(str, left_operand); } return left_operand; //Если он единственный } int _expr(char*& str, int left_operand) { char operation = *str; //Операция между правым и левым операндом ++str; int right_operand = term(str); //Получаем правый операнд if (*str == '\0') { //Выражение закончилось, возвращаем ответ return select_operation(left_operand, right_operand, operation);; } else { //В выражении есть другие операнды return _expr(str, select_operation(left_operand, right_operand, operation)); } } int term(char*& str) { int left_part = prim(str); //Вычисление левой части операнда if (*str == '*' || *str == '/') {//Если операнд - произведение | частное return _term(str, left_part); } return left_part; //Если операнд - число } int _term(char*& str, int left_part) {//Вычисление операнда - левую часть уже вычислили char operation = *str;//Операция между частями операнда if (operation == '+' || operation == '-') //Если + | - вычисление операнда закончилось throw left_part; //Выкидываем результат ++str; int right_part = prim(str); //Вычисляем правую часть if (*str == '\0') { //Это был последний операнд try { //вычисляем значение операнда return select_operation(left_part, right_part, operation); } catch (int a) { if (a == -1) { //Спецификация - деление на нуль //в ответе получаем мусор cout << "DIVISION BY ZERO!" << endl; } } } else { //это был не последний операнд int right_term; //Вычисляем дальше операнды справа try { right_term = _term(str, select_operation(left_part, right_part, operation)); } catch (int a) { if (a == -1) { //Опять деление на нуль cout << "DIVISION BY ZERO!" << endl; } return a; // Ловим то, что выкинули, если встретили + | - } return right_term; //возвращаем значение } return 0; } int prim(char*& str) { //Получаем число if (*str == '-') { //унарный минус ++str; return -number(str); } return number(str); } int number(char*& str) { char* str_num = (char*)malloc(sizeof(char)); int index = 0; while (*str >= '0' && *str <= '9') { //Читаем символы до первого сивола операции str_num[index] = *str; //записываем их в строку ++index; str_num = (char*)realloc(str_num, (index + 1)*sizeof(char)); str++; } str_num[index] = '\0'; int num = atoi(str_num); //Преобразуем char* в int free(str_num); return num; //возвращаем цифру }
#include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <iostream> #include <string.h> using namespace std; int select_operation(int a, int b, char op) {//Функция выбора оберации switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': if (b == 0) throw - 1; return a / b; default: return 0; } } int expr(char*& str); int _expr(char*& str, int left_operand); int term(char*& str); int _term(char*& str, int left_operand); int prim(char*& str); int number(char*& str); void deleteSpace(char* src) { char* dst = src; while ((*dst = *src++)) if (*dst != ' ') dst++; } int main(int argc, char* argv[]) { if (argc != 2) { //Количество аргументов командной строки не равно 2 cout << "INVALID ARGUMENTS" << endl; return 0; } deleteSpace(argv[1]); for (int i = 0; argv[1][i] != '\0'; ++i) { if ((argv[1][i] == '+' || argv[1][i] == '-' || argv[1][i] == '*' || argv[1][i] == '/') && (argv[1][i] != '-' && !(isdigit(argv[1][i + 1])))) { cout << "INVALID EXPRESSION!" << endl; return 0; } if (!isdigit(argv[1][i])) if (argv[1][i] != '+' && argv[1][i] != '-' && argv[1][i] != '*' && argv[1][i] != '/') { cout << "INVALID EXPRESSION!" << endl; return 0; } } cout << expr(argv[1]) << endl; return 0; } /*Далее под операндом будем понимать произведение | частное |число * под выражением будем понимать сумму | разность операндов */ int expr(char*& str) { int left_operand = term(str); //Левый операнд выражения if (*str == '+' || *str == '-') { //Если он не единственный return _expr(str, left_operand); } return left_operand; //Если он единственный } int _expr(char*& str, int left_operand) { char operation = *str; //Операция между правым и левым операндом ++str; int right_operand = term(str); //Получаем правый операнд if (*str == '\0') { //Выражение закончилось, возвращаем ответ return select_operation(left_operand, right_operand, operation);; } else { //В выражении есть другие операнды return _expr(str, select_operation(left_operand, right_operand, operation)); } } int term(char*& str) { int left_part = prim(str); //Вычисление левой части операнда if (*str == '*' || *str == '/') {//Если операнд - произведение | частное return _term(str, left_part); } return left_part; //Если операнд - число } int _term(char*& str, int left_part) {//Вычисление операнда - левую часть уже вычислили char operation = *str;//Операция между частями операнда if (operation == '+' || operation == '-') //Если + | - вычисление операнда закончилось throw left_part; //Выкидываем результат ++str; int right_part = prim(str); //Вычисляем правую часть if (*str == '\0') { //Это был последний операнд try { //вычисляем значение операнда return select_operation(left_part, right_part, operation); } catch (int a) { if (a == -1) { //Спецификация - деление на нуль //в ответе получаем мусор cout << "DIVISION BY ZERO!" << endl; } } } else { //это был не последний операнд int right_term; //Вычисляем дальше операнды справа try { right_term = _term(str, select_operation(left_part, right_part, operation)); } catch (int a) { if (a == -1) { //Опять деление на нуль cout << "DIVISION BY ZERO!" << endl; } return a; // Ловим то, что выкинули, если встретили + | - } return right_term; //возвращаем значение } return 0; } int prim(char*& str) { //Получаем число if (*str == '-') { //унарный минус ++str; return -number(str); } return number(str); } int number(char*& str) { char* str_num = (char*)malloc(sizeof(char)); int index = 0; while (*str >= '0' && *str <= '9') { //Читаем символы до первого сивола операции str_num[index] = *str; //записываем их в строку ++index; str_num = (char*)realloc(str_num, (index + 1)*sizeof(char)); str++; } str_num[index] = '\0'; int num = atoi(str_num); //Преобразуем char* в int free(str_num); return num; //возвращаем цифру }
Update calc.cpp
Update calc.cpp
C++
mit
mtrempoltsev/msu_cpp_autumn_2017,mtrempoltsev/msu_cpp_autumn_2017,mtrempoltsev/msu_cpp_autumn_2017,mtrempoltsev/msu_cpp_autumn_2017
03eb5020cd399b6a9c5936432763216bb4988612
http/src/common/transmit.cpp
http/src/common/transmit.cpp
#include "transmit.h" #include "error.h" namespace snf { namespace http { /* * Sends the HTTP message data. * * @param [in] data - data to send. * @param [in] datalen - length of the data to be sent. * @param [in] exceptstr - exception message in case of error. * * @throws std::system_error in case of write error. * * @return E_ok on success, -ve error code on failure. */ int transmitter::send_data(const void *data, size_t datalen, const std::string &exceptstr) { int retval = E_ok; int to_write = static_cast<int>(datalen); int bwritten = 0; int syserr = 0; retval = m_io->write(data, to_write, &bwritten, 1000, &syserr); if (retval != E_ok) { throw std::system_error( syserr, std::system_category(), exceptstr); } else if (to_write != bwritten) { retval = E_write_failed; } return retval; } /* * Sends HTTP message body. * * @param [in] body - message body. * * @throws std::system_error in case of write errors. * * @return E_ok on success, -ve error code in case of failure. */ int transmitter::send_body(body *body) { int retval = E_ok; size_t chunklen; bool body_chunked = body->chunked(); int64_t body_length = body->length(); while (body->has_next()) { chunklen = 0; chunk_ext_t cext; const void *buf = body->next(chunklen, &cext); if (body_chunked) { std::ostringstream oss; oss << std::hex << chunklen << cext << "\r\n"; std::string s = std::move(oss.str()); retval = send_data( s.data(), s.size(), "failed to send chunk size"); if (retval != E_ok) break; } retval = send_data( buf, chunklen, body_chunked ? "failed to send chunk" : "failed to send body"); if (retval != E_ok) break; if (!body_chunked) body_length -= chunklen; } if (retval == E_ok) { if (body_chunked) { retval = send_data( "0\r\n\r\n", 5, "failed to send last chunk"); } else if (body_length != 0) { retval = E_write_failed; } } return retval; } /* * Receives a line of HTTP message. * * @param [out] line - message line. * @param [in] exceptstr - exception message in case of error. * * @throws std::system_error in case of read error. * snf::http::exception in case of invalid message line. * * @return E_ok on success, -ve error code in case of failure. */ int transmitter::recv_line(std::string &line, const std::string &exceptstr) { int retval = E_ok; int syserr = 0; retval = m_io->readline(line, 1000, &syserr); if (retval != E_ok) throw std::system_error( syserr, std::system_category(), exceptstr); size_t len = line.size(); if ((len < 2) || (line[len - 1] != '\n') || (line[len - 2] != '\r')) throw bad_message("invalid request line/header"); line.pop_back(); line.pop_back(); return retval; } /* * Sends HTTP request. * * @param [in] req - HTTP request. * * @throws std::system_error in case of write errors. * * @return E_ok on success, -ve error code in case of failure. */ int transmitter::send_request(const request &req) { std::ostringstream oss; oss << req; std::string s = std::move(oss.str()); int retval = send_data(s.data(), s.size(), "failed to send request and headers"); if (retval == E_ok) { body *req_body = req.get_body(); if (req_body) retval = send_body(req_body); } return retval; } /* * Receives HTTP request. * * @throws std::system_error in case of read error. * snf::http::exception in case of invalid message line. * * @return E_ok on success, -ve error code in case of failure. */ request transmitter::recv_request() { std::string req_line; headers hdrs; recv_line(req_line, "unable to get request line"); while (true) { std::string hdr_line; recv_line(hdr_line, "unable to get request header"); if (hdr_line.empty()) break; hdrs.add(hdr_line); } request_builder req_bldr; request req = std::move(req_bldr.request_line(req_line).with_headers(hdrs).build()); body *b = nullptr; if (req.get_headers().is_message_chunked()) b = body_factory::instance().from_socket_chunked(m_io); else if (req.get_headers().content_length() != 0) b = body_factory::instance().from_socket(m_io, req.get_headers().content_length()); if (b != nullptr) req.set_body(b); return req; } /* * Sends HTTP responde. * * @param [in] resp - HTTP response. * * @throws std::system_error in case of write errors. * * @return E_ok on success, -ve error code in case of failure. */ int transmitter::send_response(const response &resp) { std::ostringstream oss; oss << resp; std::string s = std::move(oss.str()); int retval = send_data(s.data(), s.size(), "failed to send response and headers"); if (retval == E_ok) { body *resp_body = resp.get_body(); if (resp_body) retval = send_body(resp_body); } return retval; } /* * Receives HTTP response. * * @throws std::system_error in case of read error. * snf::http::exception in case of invalid message line. * * @return E_ok on success, -ve error code in case of failure. */ response transmitter::recv_response() { std::string resp_line; headers hdrs; recv_line(resp_line, "unable to get response line"); while (true) { std::string hdr_line; recv_line(hdr_line, "unable to get response header"); if (hdr_line.empty()) break; hdrs.add(hdr_line); } response_builder resp_bldr; response resp = std::move(resp_bldr.response_line(resp_line).with_headers(hdrs).build()); body *b = nullptr; if (resp.get_headers().is_message_chunked()) b = body_factory::instance().from_socket_chunked(m_io); else if (resp.get_headers().content_length() != 0) b = body_factory::instance().from_socket(m_io, resp.get_headers().content_length()); if (b != nullptr) resp.set_body(b); return resp; } } // namespace http } // namespace snf
#include "transmit.h" #include "error.h" namespace snf { namespace http { /* * Sends the HTTP message data. * * @param [in] data - data to send. * @param [in] datalen - length of the data to be sent. * @param [in] exceptstr - exception message in case of error. * * @throws std::system_error in case of write error. * * @return E_ok on success, -ve error code on failure. */ int transmitter::send_data(const void *data, size_t datalen, const std::string &exceptstr) { int retval = E_ok; int to_write = static_cast<int>(datalen); int bwritten = 0; int syserr = 0; retval = m_io->write(data, to_write, &bwritten, 1000, &syserr); if (retval != E_ok) { throw std::system_error( syserr, std::system_category(), exceptstr); } else if (to_write != bwritten) { retval = E_write_failed; } return retval; } /* * Sends HTTP message body. * * @param [in] body - message body. * * @throws std::system_error in case of write errors. * * @return E_ok on success, -ve error code in case of failure. */ int transmitter::send_body(body *body) { int retval = E_ok; size_t chunklen; bool body_chunked = body->chunked(); int64_t body_length = body->length(); while (body->has_next()) { chunklen = 0; chunk_ext_t cext; const void *buf = body->next(chunklen, &cext); if (body_chunked) { std::ostringstream oss; oss << std::hex << chunklen << cext << "\r\n"; std::string s = std::move(oss.str()); retval = send_data( s.data(), s.size(), "failed to send chunk size"); if (retval != E_ok) break; } retval = send_data( buf, chunklen, body_chunked ? "failed to send chunk" : "failed to send body"); if (retval != E_ok) break; if (body_chunked) { retval = send_data("\r\n", 2, "failed to send chunk terminator"); if (retval != E_ok) break; } else { body_length -= chunklen; } } if (retval == E_ok) { if (body_chunked) { retval = send_data( "0\r\n\r\n", 5, "failed to send last chunk"); } else if (body_length != 0) { retval = E_write_failed; } } return retval; } /* * Receives a line of HTTP message. * * @param [out] line - message line. * @param [in] exceptstr - exception message in case of error. * * @throws std::system_error in case of read error. * snf::http::exception in case of invalid message line. * * @return E_ok on success, -ve error code in case of failure. */ int transmitter::recv_line(std::string &line, const std::string &exceptstr) { int retval = E_ok; int syserr = 0; retval = m_io->readline(line, 1000, &syserr); if (retval != E_ok) throw std::system_error( syserr, std::system_category(), exceptstr); size_t len = line.size(); if ((len < 2) || (line[len - 1] != '\n') || (line[len - 2] != '\r')) throw bad_message("invalid request line/header"); line.pop_back(); line.pop_back(); return retval; } /* * Sends HTTP request. * * @param [in] req - HTTP request. * * @throws std::system_error in case of write errors. * * @return E_ok on success, -ve error code in case of failure. */ int transmitter::send_request(const request &req) { std::ostringstream oss; oss << req; std::string s = std::move(oss.str()); int retval = send_data(s.data(), s.size(), "failed to send request and headers"); if (retval == E_ok) { body *req_body = req.get_body(); if (req_body) retval = send_body(req_body); } return retval; } /* * Receives HTTP request. * * @throws std::system_error in case of read error. * snf::http::exception in case of invalid message line. * * @return E_ok on success, -ve error code in case of failure. */ request transmitter::recv_request() { std::string req_line; headers hdrs; recv_line(req_line, "unable to get request line"); while (true) { std::string hdr_line; recv_line(hdr_line, "unable to get request header"); if (hdr_line.empty()) break; hdrs.add(hdr_line); } request_builder req_bldr; request req = std::move(req_bldr.request_line(req_line).with_headers(hdrs).build()); body *b = nullptr; if (req.get_headers().is_message_chunked()) b = body_factory::instance().from_socket_chunked(m_io); else if (req.get_headers().content_length() != 0) b = body_factory::instance().from_socket(m_io, req.get_headers().content_length()); if (b != nullptr) req.set_body(b); return req; } /* * Sends HTTP responde. * * @param [in] resp - HTTP response. * * @throws std::system_error in case of write errors. * * @return E_ok on success, -ve error code in case of failure. */ int transmitter::send_response(const response &resp) { std::ostringstream oss; oss << resp; std::string s = std::move(oss.str()); int retval = send_data(s.data(), s.size(), "failed to send response and headers"); if (retval == E_ok) { body *resp_body = resp.get_body(); if (resp_body) retval = send_body(resp_body); } return retval; } /* * Receives HTTP response. * * @throws std::system_error in case of read error. * snf::http::exception in case of invalid message line. * * @return E_ok on success, -ve error code in case of failure. */ response transmitter::recv_response() { std::string resp_line; headers hdrs; recv_line(resp_line, "unable to get response line"); while (true) { std::string hdr_line; recv_line(hdr_line, "unable to get response header"); if (hdr_line.empty()) break; hdrs.add(hdr_line); } response_builder resp_bldr; response resp = std::move(resp_bldr.response_line(resp_line).with_headers(hdrs).build()); body *b = nullptr; if (resp.get_headers().is_message_chunked()) b = body_factory::instance().from_socket_chunked(m_io); else if (resp.get_headers().content_length() != 0) b = body_factory::instance().from_socket(m_io, resp.get_headers().content_length()); if (b != nullptr) resp.set_body(b); return resp; } } // namespace http } // namespace snf
Terminate chunk data with CRLF.
Terminate chunk data with CRLF.
C++
mit
wma1729/simple-n-fast,wma1729/simple-n-fast,wma1729/simple-n-fast,wma1729/simple-n-fast
816e09ae337c8f2c948c2215eb58ae24abebeb22
UnitTests/SupportModuleTests.cpp
UnitTests/SupportModuleTests.cpp
// For conditions of distribution and use, see copyright notice in license.txt #include <boost/test/unit_test.hpp> #include "CoreStdIncludes.h" #include "Core.h" #include "Foundation.h" #include "ServiceInterfaces.h" //! Unit test for framework BOOST_AUTO_TEST_SUITE(test_suite_support_modules) struct TestA { Foundation::Console::CommandResult TestCallbackSuccess(const Core::StringVector &params) { BOOST_CHECK_EQUAL(params[0], "paramA"); BOOST_CHECK_EQUAL(params[1], "paramB"); //Foundation::Console::CommandResult result = {true, "Success"}; return Foundation::Console::ResultSuccess("Success"); } Foundation::Console::CommandResult TestCallbackFailure(const Core::StringVector &params) { BOOST_CHECK_EQUAL(params.size(), 0); return Foundation::Console::ResultFailure(); } }; BOOST_AUTO_TEST_CASE( support_modules_console ) { Foundation::Framework fw; fw.GetModuleManager()->LoadModuleByName("SupportModules", "Console"); BOOST_CHECK (fw.GetModuleManager()->HasModule(Foundation::Module::MT_Console)); Foundation::Console::ConsoleServiceInterface *console = fw.GetService<Foundation::Console::ConsoleServiceInterface> (Foundation::Service::ST_Console); TestA test_class; Foundation::Console::Command commandA = {"Test_CommandA", "Test command Success", Foundation::Console::Bind(&test_class, TestA::TestCallbackSuccess) }; console->RegisterCommand(commandA); Foundation::Console::Command commandB = {"Test_CommandB", "Test command Failure", Foundation::Console::Bind(&test_class, TestA::TestCallbackFailure) }; console->RegisterCommand(commandB); Foundation::Console::CommandResult result = console->ExecuteCommand("Test_CommandA (paramA, paramB )"); BOOST_CHECK_EQUAL (result.success_, true); BOOST_CHECK_EQUAL (result.why_, "Success"); result = console->ExecuteCommand("Test_CommandB"); BOOST_CHECK_EQUAL (result.success_, false); BOOST_CHECK_EQUAL (result.why_.size(), 0); fw.GetModuleManager()->UninitializeModules(); fw.GetModuleManager()->UnloadModules(); } BOOST_AUTO_TEST_SUITE_END()
// For conditions of distribution and use, see copyright notice in license.txt #include <boost/test/unit_test.hpp> #include "CoreStdIncludes.h" #include "Core.h" #include "Foundation.h" #include "ServiceInterfaces.h" //! Unit test for framework BOOST_AUTO_TEST_SUITE(test_suite_support_modules) struct TestA { Foundation::Console::CommandResult TestCallbackSuccess(const Core::StringVector &params) { BOOST_CHECK_EQUAL(params[0], "paramA"); BOOST_CHECK_EQUAL(params[1], "paramB"); //Foundation::Console::CommandResult result = {true, "Success"}; return Foundation::Console::ResultSuccess("Success"); } Foundation::Console::CommandResult TestCallbackFailure(const Core::StringVector &params) { BOOST_CHECK_EQUAL(params.size(), 0); return Foundation::Console::ResultFailure(); } }; BOOST_AUTO_TEST_CASE( support_modules_console ) { Foundation::Framework fw; fw.GetModuleManager()->LoadModuleByName("SupportModules", "Console"); BOOST_CHECK (fw.GetModuleManager()->HasModule(Foundation::Module::MT_Console)); Foundation::Console::ConsoleServiceInterface *console = fw.GetService<Foundation::Console::ConsoleServiceInterface> (Foundation::Service::ST_Console); TestA test_class; Foundation::Console::Command commandA = {"Test_CommandA", "Test command Success", Foundation::Console::Bind(&test_class, &TestA::TestCallbackSuccess) }; console->RegisterCommand(commandA); Foundation::Console::Command commandB = {"Test_CommandB", "Test command Failure", Foundation::Console::Bind(&test_class, &TestA::TestCallbackFailure) }; console->RegisterCommand(commandB); Foundation::Console::CommandResult result = console->ExecuteCommand("Test_CommandA (paramA, paramB )"); BOOST_CHECK_EQUAL (result.success_, true); BOOST_CHECK_EQUAL (result.why_, "Success"); result = console->ExecuteCommand("Test_CommandB"); BOOST_CHECK_EQUAL (result.success_, false); BOOST_CHECK_EQUAL (result.why_.size(), 0); fw.GetModuleManager()->UninitializeModules(); fw.GetModuleManager()->UnloadModules(); } BOOST_AUTO_TEST_SUITE_END()
Fix for member function pointers.
Fix for member function pointers. git-svn-id: 65dd0ccd495961f396d5302e5521154b071f0302@204 5b2332b8-efa3-11de-8684-7d64432d61a3
C++
apache-2.0
antont/tundra,antont/tundra,pharos3d/tundra,AlphaStaxLLC/tundra,pharos3d/tundra,jesterKing/naali,realXtend/tundra,jesterKing/naali,jesterKing/naali,BogusCurry/tundra,AlphaStaxLLC/tundra,jesterKing/naali,realXtend/tundra,jesterKing/naali,antont/tundra,antont/tundra,pharos3d/tundra,AlphaStaxLLC/tundra,AlphaStaxLLC/tundra,antont/tundra,realXtend/tundra,realXtend/tundra,jesterKing/naali,BogusCurry/tundra,pharos3d/tundra,AlphaStaxLLC/tundra,BogusCurry/tundra,jesterKing/naali,AlphaStaxLLC/tundra,pharos3d/tundra,pharos3d/tundra,BogusCurry/tundra,BogusCurry/tundra,antont/tundra,realXtend/tundra,realXtend/tundra,antont/tundra,BogusCurry/tundra
13fa95d743a41b242465065622666a1ec47064ab
include/impl/iutest_port.ipp
include/impl/iutest_port.ipp
//====================================================================== //----------------------------------------------------------------------- /** * @file iutest_port.ipp * @brief iris unit test 依存関数 ファイル * * @author t.shirayanagi * @par copyright * Copyright (C) 2011-2014, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== #ifndef INCG_IRIS_IUTEST_PORT_IPP_7893F685_A1A9_477A_82E8_BF06237697FF_ #define INCG_IRIS_IUTEST_PORT_IPP_7893F685_A1A9_477A_82E8_BF06237697FF_ //====================================================================== // include #include "../internal/iutest_port.hpp" #ifdef IUTEST_OS_NACL # include <ppapi/cpp/var.h> # include <ppapi/cpp/instance.h> # include <ppapi/cpp/module.h> #endif #if IUTEST_HAS_STREAMCAPTURE # include <io.h> # include <sys/stat.h> #endif namespace iutest { #ifdef IUTEST_OS_NACL namespace nacl { namespace detail { IUTEST_IPP_INLINE void PostMessage(const pp::Var& var) { ::pp::Module* module = ::pp::Module::Get(); if( module != NULL ) { if( module->current_instances().size() > 0 ) { module->current_instances().begin()->second->PostMessage(var); } } } } // end of namespace detail IUTEST_IPP_INLINE void vprint_message(const char *fmt, va_list va) { char msg[1024]; vsnprintf(msg, sizeof(msg), fmt, va); char* tp = strtok(msg, "\n"); while( tp != NULL ) { detail::PostMessage(pp::Var(tp)); tp = strtok(NULL, "\n"); } } IUTEST_IPP_INLINE void print_message(const char *fmt, ...) { va_list va; va_start(va, fmt); vprint_message(fmt, va); va_end(va); } } // end of namespace nacl #endif namespace internal { namespace posix { IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_BEGIN() IUTEST_IPP_INLINE const char* GetEnv(const char* name) { #if defined(IUTEST_OS_WINDOWS_PHONE) || defined(IUTEST_OS_WINDOWS_RT) || defined(IUTEST_OS_WINDOWS_MOBILE) || defined(IUTEST_NO_GETENV) IUTEST_UNUSED_VAR(name); return NULL; #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) const char* env = getenv(name); return (env != NULL && env[0] != '\0') ? env : NULL; #else return getenv(name); #endif } IUTEST_IPP_INLINE int PutEnv(const char* expr) { #if defined(IUTEST_OS_WINDOWS_PHONE) || defined(IUTEST_OS_WINDOWS_RT) || defined(IUTEST_OS_WINDOWS_MOBILE) \ || defined(IUTEST_NO_PUTENV) || defined(__STRICT_ANSI__) IUTEST_UNUSED_VAR(expr); return -1; #else return putenv(const_cast<char*>(expr)); #endif } IUTEST_IPP_INLINE const char* GetCWD(char* buf, size_t length) { #if defined(IUTEST_OS_WINDOWS_PHONE) || defined(IUTEST_OS_WINDOWS_RT) || defined(IUTEST_OS_WINDOWS_MOBILE) \ || defined(IUTEST_OS_AVR32) || defined(IUTEST_OS_ARM) || defined(IUTEST_NO_GETCWD) if( buf == NULL || length < 3 ) { return NULL; } buf[0] = '.'; buf[1] = '/'; buf[2] = '\0'; return buf; #elif defined(IUTEST_OS_WINDOWS) return ::GetCurrentDirectoryA(static_cast<DWORD>(length), buf) == 0 ? NULL : buf; #else return getcwd(buf, length); #endif } IUTEST_IPP_INLINE ::std::string GetCWD(void) { char buf[260]; return GetCWD(buf, sizeof(buf)); } IUTEST_IPP_INLINE void SleepMillisec(unsigned int millisec) { #if defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_PHONE) && !defined(IUTEST_OS_WINDOWS_RT) Sleep(millisec); #elif defined(IUTEST_OS_LINUX) || defined(IUTEST_OS_CYGWIN) #if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L const timespec time = { 0, static_cast<long>(millisec) * 1000 * 1000 }; nanosleep(&time, NULL); #elif (defined(_BSD_SOURCE) && _BSD_SOURCE) || (defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED) && (!defined(_POSIX_C_SOURCE) || !(_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700)) ) usleep(millisec*1000); #else usleep(millisec*1000); #endif #else volatile int x=0; for( unsigned int i=0; i < millisec; ++i ) x += 1; IUTEST_UNUSED_VAR(x); #endif } #if defined(IUTEST_OS_WINDOWS_MOBILE) void Abort(void) { DebugBreak(); TerminateProcess(GetCurrentProcess(), 1); } #endif IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_END() } // end of namespace posix } // end of namespace internal namespace detail { IUTEST_IPP_INLINE bool SetEnvironmentVariable(const char* name, const char* value) { #if defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_MOBILE) && !defined(IUTEST_OS_WINDOWS_PHONE) && !defined(IUTEST_OS_WINDOWS_RT) return ::SetEnvironmentVariableA(name, value) ? true : false; #else ::std::string var = name; var += "="; var += value; return internal::posix::PutEnv(var.c_str()) == 0 ? true : false; #endif } IUTEST_IPP_INLINE bool GetEnvironmentVariable(const char* name, char* buf, size_t size) { #if defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_MOBILE) && !defined(IUTEST_OS_WINDOWS_PHONE) && !defined(IUTEST_OS_WINDOWS_RT) const DWORD ret = ::GetEnvironmentVariableA(name, buf, static_cast<DWORD>(size)); if( ret == 0 ) { return false; } if( ret > size ) { return false; } return true; #else IUTEST_UNUSED_VAR(size); const char* env = internal::posix::GetEnv(name); if( env == NULL ) { return false; } IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_BEGIN() strcpy(buf, env); IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_END() return true; #endif } IUTEST_IPP_INLINE bool GetEnvironmentVariable(const char* name, ::std::string& var) { #if defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_MOBILE) char buf[2048]; if( !GetEnvironmentVariable(name, buf, sizeof(buf)) ) { return false; } var = buf; return true; #else const char* env = internal::posix::GetEnv(name); if( env == NULL ) { return false; } var = env; return true; #endif } IUTEST_IPP_INLINE bool GetEnvironmentInt(const char* name, int& var) { #if defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_MOBILE) char buf[128] = {0}; if( !GetEnvironmentVariable(name, buf, sizeof(buf)) ) { return false; } char* end = NULL; var = static_cast<int>(strtol(buf, &end, 0)); return true; #else const char* env = internal::posix::GetEnv(name); if( env == NULL ) { return false; } char* end = NULL; var = static_cast<int>(strtol(env, &end, 0)); return true; #endif } #if defined(IUTEST_OS_WINDOWS) namespace win { IUTEST_IPP_INLINE ::std::string WideStringToMultiByteString(const wchar_t* wide_c_str) { if( wide_c_str == NULL ) return ""; ::std::string str; const int length = static_cast<int>(wcslen(wide_c_str)) * 2 + 1; char* mbs = new char [length]; WideCharToMultiByte(932, 0, wide_c_str, static_cast<int>(wcslen(wide_c_str))+1, mbs, length, NULL, NULL); str = mbs; delete [] mbs; return str; } IUTEST_IPP_INLINE ::std::string GetHResultString(HRESULT hr) { #if !defined(IUTEST_OS_WINDOWS_MOBILE) #if defined(FORMAT_MESSAGE_ALLOCATE_BUFFER) LPSTR buf = NULL; #else CHAR buf[4096]; #endif if( FormatMessageA( #if defined(FORMAT_MESSAGE_ALLOCATE_BUFFER) FORMAT_MESSAGE_ALLOCATE_BUFFER | #endif FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS , NULL , hr , MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) // デフォルト ユーザー言語 #if defined(FORMAT_MESSAGE_ALLOCATE_BUFFER) , (LPSTR)&buf , 0 #else , buf , IUTEST_PP_COUNTOF(buf) #endif , NULL ) == 0 ) { return ""; } ::std::string str = (buf == NULL) ? "" : buf; #if defined(FORMAT_MESSAGE_ALLOCATE_BUFFER) LocalFree(buf); #endif #else LPWSTR buf = NULL; if( FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS , NULL , hr , MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) // デフォルト ユーザー言語 , (LPWSTR)&buf , 0 , NULL ) == 0 ) { return ""; } ::std::string str = (buf == NULL) ? "" : WideStringToMultiByteString(buf); LocalFree(buf); #endif return str; } } // end of namespace win #endif // declare ::std::string FormatFileLocation(const char* file, int line); IUTEST_IPP_INLINE IUTestLog::IUTestLog(Level level, const char* file, int line) : kLevel(level) { const char* const tag = (level == LOG_INFO ) ? "[ INFO ] ": (level == LOG_WARNING) ? "[WARNING] ": (level == LOG_ERROR ) ? "[ ERROR ] ": "[ FATAL ] "; GetStream() << "\r\n" << tag << FormatFileLocation(file, line).c_str() << ": "; } IUTEST_IPP_INLINE IUTestLog::~IUTestLog(void) { GetStream() << "\r\n"; fprintf(stderr, "%s", m_stream.str().c_str()); if( kLevel == LOG_FATAL ) { fflush(stderr); posix::Abort(); } } #if IUTEST_HAS_STREAMCAPTURE IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_BEGIN() IUTEST_IPP_INLINE IUStreamCapture::IUStreamCapture(FILE* fp) : m_fp(fp) { m_buf[0] = '\0'; setbuf(fp, m_buf); } IUTEST_IPP_INLINE IUStreamCapture::~IUStreamCapture(void) { setbuf(m_fp, NULL); } IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_END() #endif } // end of namespace detail } // end of namespace iutest #endif // INCG_IRIS_IUTEST_PORT_IPP_7893F685_A1A9_477A_82E8_BF06237697FF_
//====================================================================== //----------------------------------------------------------------------- /** * @file iutest_port.ipp * @brief iris unit test 依存関数 ファイル * * @author t.shirayanagi * @par copyright * Copyright (C) 2011-2014, Takazumi Shirayanagi\n * This software is released under the new BSD License, * see LICENSE */ //----------------------------------------------------------------------- //====================================================================== #ifndef INCG_IRIS_IUTEST_PORT_IPP_7893F685_A1A9_477A_82E8_BF06237697FF_ #define INCG_IRIS_IUTEST_PORT_IPP_7893F685_A1A9_477A_82E8_BF06237697FF_ //====================================================================== // include #include "../internal/iutest_port.hpp" #ifdef IUTEST_OS_NACL # include <ppapi/cpp/var.h> # include <ppapi/cpp/instance.h> # include <ppapi/cpp/module.h> #endif namespace iutest { #ifdef IUTEST_OS_NACL namespace nacl { namespace detail { IUTEST_IPP_INLINE void PostMessage(const pp::Var& var) { ::pp::Module* module = ::pp::Module::Get(); if( module != NULL ) { if( module->current_instances().size() > 0 ) { module->current_instances().begin()->second->PostMessage(var); } } } } // end of namespace detail IUTEST_IPP_INLINE void vprint_message(const char *fmt, va_list va) { char msg[1024]; vsnprintf(msg, sizeof(msg), fmt, va); char* tp = strtok(msg, "\n"); while( tp != NULL ) { detail::PostMessage(pp::Var(tp)); tp = strtok(NULL, "\n"); } } IUTEST_IPP_INLINE void print_message(const char *fmt, ...) { va_list va; va_start(va, fmt); vprint_message(fmt, va); va_end(va); } } // end of namespace nacl #endif namespace internal { namespace posix { IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_BEGIN() IUTEST_IPP_INLINE const char* GetEnv(const char* name) { #if defined(IUTEST_OS_WINDOWS_PHONE) || defined(IUTEST_OS_WINDOWS_RT) || defined(IUTEST_OS_WINDOWS_MOBILE) || defined(IUTEST_NO_GETENV) IUTEST_UNUSED_VAR(name); return NULL; #elif defined(__BORLANDC__) || defined(__SunOS_5_8) || defined(__SunOS_5_9) const char* env = getenv(name); return (env != NULL && env[0] != '\0') ? env : NULL; #else return getenv(name); #endif } IUTEST_IPP_INLINE int PutEnv(const char* expr) { #if defined(IUTEST_OS_WINDOWS_PHONE) || defined(IUTEST_OS_WINDOWS_RT) || defined(IUTEST_OS_WINDOWS_MOBILE) \ || defined(IUTEST_NO_PUTENV) || defined(__STRICT_ANSI__) IUTEST_UNUSED_VAR(expr); return -1; #else return putenv(const_cast<char*>(expr)); #endif } IUTEST_IPP_INLINE const char* GetCWD(char* buf, size_t length) { #if defined(IUTEST_OS_WINDOWS_PHONE) || defined(IUTEST_OS_WINDOWS_RT) || defined(IUTEST_OS_WINDOWS_MOBILE) \ || defined(IUTEST_OS_AVR32) || defined(IUTEST_OS_ARM) || defined(IUTEST_NO_GETCWD) if( buf == NULL || length < 3 ) { return NULL; } buf[0] = '.'; buf[1] = '/'; buf[2] = '\0'; return buf; #elif defined(IUTEST_OS_WINDOWS) return ::GetCurrentDirectoryA(static_cast<DWORD>(length), buf) == 0 ? NULL : buf; #else return getcwd(buf, length); #endif } IUTEST_IPP_INLINE ::std::string GetCWD(void) { char buf[260]; return GetCWD(buf, sizeof(buf)); } IUTEST_IPP_INLINE void SleepMillisec(unsigned int millisec) { #if defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_PHONE) && !defined(IUTEST_OS_WINDOWS_RT) Sleep(millisec); #elif defined(IUTEST_OS_LINUX) || defined(IUTEST_OS_CYGWIN) #if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L const timespec time = { 0, static_cast<long>(millisec) * 1000 * 1000 }; nanosleep(&time, NULL); #elif (defined(_BSD_SOURCE) && _BSD_SOURCE) || (defined(_XOPEN_SOURCE) && (_XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED) && (!defined(_POSIX_C_SOURCE) || !(_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700)) ) usleep(millisec*1000); #else usleep(millisec*1000); #endif #else volatile int x=0; for( unsigned int i=0; i < millisec; ++i ) x += 1; IUTEST_UNUSED_VAR(x); #endif } #if defined(IUTEST_OS_WINDOWS_MOBILE) void Abort(void) { DebugBreak(); TerminateProcess(GetCurrentProcess(), 1); } #endif IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_END() } // end of namespace posix } // end of namespace internal namespace detail { IUTEST_IPP_INLINE bool SetEnvironmentVariable(const char* name, const char* value) { #if defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_MOBILE) && !defined(IUTEST_OS_WINDOWS_PHONE) && !defined(IUTEST_OS_WINDOWS_RT) return ::SetEnvironmentVariableA(name, value) ? true : false; #else ::std::string var = name; var += "="; var += value; return internal::posix::PutEnv(var.c_str()) == 0 ? true : false; #endif } IUTEST_IPP_INLINE bool GetEnvironmentVariable(const char* name, char* buf, size_t size) { #if defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_MOBILE) && !defined(IUTEST_OS_WINDOWS_PHONE) && !defined(IUTEST_OS_WINDOWS_RT) const DWORD ret = ::GetEnvironmentVariableA(name, buf, static_cast<DWORD>(size)); if( ret == 0 ) { return false; } if( ret > size ) { return false; } return true; #else IUTEST_UNUSED_VAR(size); const char* env = internal::posix::GetEnv(name); if( env == NULL ) { return false; } IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_BEGIN() strcpy(buf, env); IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_END() return true; #endif } IUTEST_IPP_INLINE bool GetEnvironmentVariable(const char* name, ::std::string& var) { #if defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_MOBILE) char buf[2048]; if( !GetEnvironmentVariable(name, buf, sizeof(buf)) ) { return false; } var = buf; return true; #else const char* env = internal::posix::GetEnv(name); if( env == NULL ) { return false; } var = env; return true; #endif } IUTEST_IPP_INLINE bool GetEnvironmentInt(const char* name, int& var) { #if defined(IUTEST_OS_WINDOWS) && !defined(IUTEST_OS_WINDOWS_MOBILE) char buf[128] = {0}; if( !GetEnvironmentVariable(name, buf, sizeof(buf)) ) { return false; } char* end = NULL; var = static_cast<int>(strtol(buf, &end, 0)); return true; #else const char* env = internal::posix::GetEnv(name); if( env == NULL ) { return false; } char* end = NULL; var = static_cast<int>(strtol(env, &end, 0)); return true; #endif } #if defined(IUTEST_OS_WINDOWS) namespace win { IUTEST_IPP_INLINE ::std::string WideStringToMultiByteString(const wchar_t* wide_c_str) { if( wide_c_str == NULL ) return ""; ::std::string str; const int length = static_cast<int>(wcslen(wide_c_str)) * 2 + 1; char* mbs = new char [length]; WideCharToMultiByte(932, 0, wide_c_str, static_cast<int>(wcslen(wide_c_str))+1, mbs, length, NULL, NULL); str = mbs; delete [] mbs; return str; } IUTEST_IPP_INLINE ::std::string GetHResultString(HRESULT hr) { #if !defined(IUTEST_OS_WINDOWS_MOBILE) #if defined(FORMAT_MESSAGE_ALLOCATE_BUFFER) LPSTR buf = NULL; #else CHAR buf[4096]; #endif if( FormatMessageA( #if defined(FORMAT_MESSAGE_ALLOCATE_BUFFER) FORMAT_MESSAGE_ALLOCATE_BUFFER | #endif FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS , NULL , hr , MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) // デフォルト ユーザー言語 #if defined(FORMAT_MESSAGE_ALLOCATE_BUFFER) , (LPSTR)&buf , 0 #else , buf , IUTEST_PP_COUNTOF(buf) #endif , NULL ) == 0 ) { return ""; } ::std::string str = (buf == NULL) ? "" : buf; #if defined(FORMAT_MESSAGE_ALLOCATE_BUFFER) LocalFree(buf); #endif #else LPWSTR buf = NULL; if( FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS , NULL , hr , MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT) // デフォルト ユーザー言語 , (LPWSTR)&buf , 0 , NULL ) == 0 ) { return ""; } ::std::string str = (buf == NULL) ? "" : WideStringToMultiByteString(buf); LocalFree(buf); #endif return str; } } // end of namespace win #endif // declare ::std::string FormatFileLocation(const char* file, int line); IUTEST_IPP_INLINE IUTestLog::IUTestLog(Level level, const char* file, int line) : kLevel(level) { const char* const tag = (level == LOG_INFO ) ? "[ INFO ] ": (level == LOG_WARNING) ? "[WARNING] ": (level == LOG_ERROR ) ? "[ ERROR ] ": "[ FATAL ] "; GetStream() << "\r\n" << tag << FormatFileLocation(file, line).c_str() << ": "; } IUTEST_IPP_INLINE IUTestLog::~IUTestLog(void) { GetStream() << "\r\n"; fprintf(stderr, "%s", m_stream.str().c_str()); if( kLevel == LOG_FATAL ) { fflush(stderr); posix::Abort(); } } #if IUTEST_HAS_STREAMCAPTURE IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_BEGIN() IUTEST_IPP_INLINE IUStreamCapture::IUStreamCapture(FILE* fp) : m_fp(fp) { m_buf[0] = '\0'; setbuf(fp, m_buf); } IUTEST_IPP_INLINE IUStreamCapture::~IUStreamCapture(void) { setbuf(m_fp, NULL); } IUTEST_PRAGMA_CRT_SECURE_WARN_DISABLE_END() #endif } // end of namespace detail } // end of namespace iutest #endif // INCG_IRIS_IUTEST_PORT_IPP_7893F685_A1A9_477A_82E8_BF06237697FF_
update r719
update r719
C++
bsd-3-clause
srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest,srz-zumix/iutest
09e03687504a35ce06f3df293b375fe35e80894f
include/libtorrent/debug.hpp
include/libtorrent/debug.hpp
/* Copyright (c) 2003-2014, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DEBUG_HPP_INCLUDED #define TORRENT_DEBUG_HPP_INCLUDED #include "libtorrent/config.hpp" #if TORRENT_USE_ASSERTS && defined BOOST_HAS_PTHREADS #include <pthread.h> #endif #if defined TORRENT_ASIO_DEBUGGING #include "libtorrent/assert.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/time.hpp" #include <map> #include <cstring> #include <deque> #ifdef __MACH__ #include <mach/task_info.h> #include <mach/task.h> #include <mach/mach_init.h> #endif std::string demangle(char const* name); namespace libtorrent { struct async_t { async_t() : refs(0) {} std::string stack; int refs; }; // defined in session_impl.cpp extern std::map<std::string, async_t> _async_ops; extern int _async_ops_nthreads; extern mutex _async_ops_mutex; // timestamp -> operation struct wakeup_t { ptime timestamp; boost::uint64_t context_switches; char const* operation; }; extern std::deque<wakeup_t> _wakeups; inline bool has_outstanding_async(char const* name) { mutex::scoped_lock l(_async_ops_mutex); std::map<std::string, async_t>::iterator i = _async_ops.find(name); return i != _async_ops.end(); } inline void add_outstanding_async(char const* name) { mutex::scoped_lock l(_async_ops_mutex); async_t& a = _async_ops[name]; if (a.stack.empty()) { char stack_text[10000]; print_backtrace(stack_text, sizeof(stack_text), 9); // skip the stack frame of 'add_outstanding_async' char* ptr = strchr(stack_text, '\n'); if (ptr != NULL) ++ptr; else ptr = stack_text; a.stack = ptr; } ++a.refs; } inline void complete_async(char const* name) { mutex::scoped_lock l(_async_ops_mutex); async_t& a = _async_ops[name]; TORRENT_ASSERT(a.refs > 0); --a.refs; _wakeups.push_back(wakeup_t()); wakeup_t& w = _wakeups.back(); w.timestamp = time_now_hires(); #ifdef __MACH__ task_events_info teinfo; mach_msg_type_number_t t_info_count = TASK_EVENTS_INFO_COUNT; task_info(mach_task_self(), TASK_EVENTS_INFO, (task_info_t)&teinfo , &t_info_count); w.context_switches = teinfo.csw; #else w.context_switches = 0; #endif w.operation = name; } inline void async_inc_threads() { mutex::scoped_lock l(_async_ops_mutex); ++_async_ops_nthreads; } inline void async_dec_threads() { mutex::scoped_lock l(_async_ops_mutex); --_async_ops_nthreads; } inline int log_async() { mutex::scoped_lock l(_async_ops_mutex); int ret = 0; for (std::map<std::string, async_t>::iterator i = _async_ops.begin() , end(_async_ops.end()); i != end; ++i) { if (i->second.refs <= _async_ops_nthreads - 1) continue; ret += i->second.refs; printf("%s: (%d)\n%s\n", i->first.c_str(), i->second.refs, i->second.stack.c_str()); } return ret; } } #endif // TORRENT_ASIO_DEBUGGING namespace libtorrent { #if TORRENT_USE_ASSERTS && defined BOOST_HAS_PTHREADS struct single_threaded { single_threaded(): m_single_thread(0) {} ~single_threaded() { m_single_thread = 0; } bool is_single_thread() const { if (m_single_thread == 0) { m_single_thread = pthread_self(); return true; } return m_single_thread == pthread_self(); } bool is_not_thread() const { if (m_single_thread == 0) return true; return m_single_thread != pthread_self(); } void thread_started() { m_single_thread = pthread_self(); } void transfer_ownership() { m_single_thread = 0; } private: mutable pthread_t m_single_thread; }; #else struct single_threaded { bool is_single_thread() const { return true; } void thread_started() {} bool is_not_thread() const {return true; } }; #endif } #endif // TORRENT_DEBUG_HPP_INCLUDED
/* Copyright (c) 2003-2014, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_DEBUG_HPP_INCLUDED #define TORRENT_DEBUG_HPP_INCLUDED #include "libtorrent/config.hpp" #if TORRENT_USE_ASSERTS && defined BOOST_HAS_PTHREADS #include <pthread.h> #endif #if defined TORRENT_ASIO_DEBUGGING #include "libtorrent/assert.hpp" #include "libtorrent/thread.hpp" #include "libtorrent/time.hpp" #include <map> #include <cstring> #include <deque> #ifdef __MACH__ #include <mach/task_info.h> #include <mach/task.h> #include <mach/mach_init.h> #endif std::string demangle(char const* name); namespace libtorrent { struct async_t { async_t() : refs(0) {} std::string stack; int refs; }; // defined in session_impl.cpp extern std::map<std::string, async_t> _async_ops; extern int _async_ops_nthreads; extern mutex _async_ops_mutex; // timestamp -> operation struct wakeup_t { ptime timestamp; boost::uint64_t context_switches; char const* operation; }; extern std::deque<wakeup_t> _wakeups; inline bool has_outstanding_async(char const* name) { mutex::scoped_lock l(_async_ops_mutex); std::map<std::string, async_t>::iterator i = _async_ops.find(name); return i != _async_ops.end(); } inline void add_outstanding_async(char const* name) { mutex::scoped_lock l(_async_ops_mutex); async_t& a = _async_ops[name]; if (a.stack.empty()) { char stack_text[10000]; print_backtrace(stack_text, sizeof(stack_text), 9); // skip the stack frame of 'add_outstanding_async' char* ptr = strchr(stack_text, '\n'); if (ptr != NULL) ++ptr; else ptr = stack_text; a.stack = ptr; } ++a.refs; } inline void complete_async(char const* name) { mutex::scoped_lock l(_async_ops_mutex); async_t& a = _async_ops[name]; TORRENT_ASSERT(a.refs > 0); --a.refs; // don't let this grow indefinitely if (_wakeups.size() < 100000) { _wakeups.push_back(wakeup_t()); wakeup_t& w = _wakeups.back(); w.timestamp = time_now_hires(); } #ifdef __MACH__ task_events_info teinfo; mach_msg_type_number_t t_info_count = TASK_EVENTS_INFO_COUNT; task_info(mach_task_self(), TASK_EVENTS_INFO, (task_info_t)&teinfo , &t_info_count); w.context_switches = teinfo.csw; #else w.context_switches = 0; #endif w.operation = name; } inline void async_inc_threads() { mutex::scoped_lock l(_async_ops_mutex); ++_async_ops_nthreads; } inline void async_dec_threads() { mutex::scoped_lock l(_async_ops_mutex); --_async_ops_nthreads; } inline int log_async() { mutex::scoped_lock l(_async_ops_mutex); int ret = 0; for (std::map<std::string, async_t>::iterator i = _async_ops.begin() , end(_async_ops.end()); i != end; ++i) { if (i->second.refs <= _async_ops_nthreads - 1) continue; ret += i->second.refs; printf("%s: (%d)\n%s\n", i->first.c_str(), i->second.refs, i->second.stack.c_str()); } return ret; } } #endif // TORRENT_ASIO_DEBUGGING namespace libtorrent { #if TORRENT_USE_ASSERTS && defined BOOST_HAS_PTHREADS struct single_threaded { single_threaded(): m_single_thread(0) {} ~single_threaded() { m_single_thread = 0; } bool is_single_thread() const { if (m_single_thread == 0) { m_single_thread = pthread_self(); return true; } return m_single_thread == pthread_self(); } bool is_not_thread() const { if (m_single_thread == 0) return true; return m_single_thread != pthread_self(); } void thread_started() { m_single_thread = pthread_self(); } void transfer_ownership() { m_single_thread = 0; } private: mutable pthread_t m_single_thread; }; #else struct single_threaded { bool is_single_thread() const { return true; } void thread_started() {} bool is_not_thread() const {return true; } }; #endif } #endif // TORRENT_DEBUG_HPP_INCLUDED
fix wakeup profiling to not grow memory usage indefinitely
fix wakeup profiling to not grow memory usage indefinitely git-svn-id: c39a6fcb73c71bf990fd9353909696546eb40440@10755 a83610d8-ad2a-0410-a6ab-fc0612d85776
C++
bsd-3-clause
mirror/libtorrent,mirror/libtorrent,john-peterson/libtorrent-old,mirror/libtorrent,john-peterson/libtorrent-old,john-peterson/libtorrent-old,john-peterson/libtorrent-old,john-peterson/libtorrent-old,john-peterson/libtorrent-old,mirror/libtorrent,mirror/libtorrent,mirror/libtorrent
32dc598e74de790413521f0e9edcd53e651a9d2c
ionScience/MarchingCubes.cpp
ionScience/MarchingCubes.cpp
#include "MarchingCubes.h" #include "MarchingCubesLookupTables.h" #include "CColorTable.h" void CalculateGradient(SMarchingCubesVolume & Volume) { for (s32 z = 0; z < Volume.Dimensions.Z; ++ z) for (s32 y = 0; y < Volume.Dimensions.Y; ++ y) for (s32 x = 0; x < Volume.Dimensions.X; ++ x) { Volume.Get(x, y, z).Gradient = vec3f( Volume.Get(x+1, y, z).Value - Volume.Get(x-1, y, z).Value, Volume.Get(x, y+1, z).Value - Volume.Get(x, y-1, z).Value, Volume.Get(x, y, z+1).Value - Volume.Get(x, y, z-1).Value) / 2.f; } } ion::Scene::CSimpleMesh * MarchingCubes(SMarchingCubesVolume & Volume) { CalculateGradient(Volume); ion::Scene::CSimpleMesh * Mesh = new ion::Scene::CSimpleMesh(); int CurrentBuffer = 0; Mesh->Vertices.reserve(1 << 14); Mesh->Triangles.reserve(1 << 11); ion::Scene::CSimpleMesh::SVertex Vertices[12]; vec3i VertexIndices[8] = { vec3i(0, 0, 0), vec3i(1, 0, 0), vec3i(1, 0, 1), vec3i(0, 0, 1), vec3i(0, 1, 0), vec3i(1, 1, 0), vec3i(1, 1, 1), vec3i(0, 1, 1), }; for (s32 z = 0; z < Volume.Dimensions.Z; ++ z) for (s32 y = 0; y < Volume.Dimensions.Y; ++ y) for (s32 x = 0; x < Volume.Dimensions.X; ++ x) { int Lookup = 0; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[0]).Value < 0)) Lookup |= 1; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[1]).Value < 0)) Lookup |= 2; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[2]).Value < 0)) Lookup |= 4; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[3]).Value < 0)) Lookup |= 8; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[4]).Value < 0)) Lookup |= 16; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[5]).Value < 0)) Lookup |= 32; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[6]).Value < 0)) Lookup |= 64; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[7]).Value < 0)) Lookup |= 128; auto Interpolate = [&](vec3i const & v1, vec3i const & v2) -> ion::Scene::CSimpleMesh::SVertex { //static CColorTable ColorTable; ion::Scene::CSimpleMesh::SVertex v; f32 const d1 = Volume.Get(v1).Value; f32 const d2 = Volume.Get(v2).Value; f32 ratio = d1 / (d2 - d1); if (ratio < 0.f) ratio += 1.f; v.Position = vec3f(v1) * (ratio) + vec3f(v2) * (1.f - ratio); //v.Color = ColorTable.Get( // Volume.Get(v1x, v1y, v1z).Color * (ratio) + // Volume.Get(v2x, v2y, v2z).Color * (1.f - ratio)); v.Normal = Normalize(Volume.Get(v1).Gradient) * (ratio) + Normalize(Volume.Get(v2).Gradient) * (1.f - ratio); //f32 const valp1 = Volume.Get(v1).Value; //f32 const valp2 = Volume.Get(v2).Value; //vec3f p1 = vec3f(v1); //vec3f p2 = vec3f(v2); //float mu; //if (abs(0 - valp1) < 0.00001) // return(p1); //if (abs(0 - valp2) < 0.00001) // return(p2); //if (abs(valp1 - valp2) < 0.00001) // return(p1); //mu = (0 - valp1) / (valp2 - valp1); //v.Position.X = p1.X + mu * (p2.X - p1.X); //v.Position.Y = p1.Y + mu * (p2.Y - p1.Y); //v.Position.Z = p1.Z + mu * (p2.Z - p1.Z); return v; }; u32 EdgeTableLookup = EdgeTable[Lookup]; if (EdgeTable[Lookup] != 0) { if (EdgeTable[Lookup] & 1) Vertices[0] = Interpolate(vec3i(x, y, z) + VertexIndices[0], vec3i(x, y, z) + VertexIndices[1]); if (EdgeTable[Lookup] & 2) Vertices[1] = Interpolate(vec3i(x, y, z) + VertexIndices[1], vec3i(x, y, z) + VertexIndices[2]); if (EdgeTable[Lookup] & 4) Vertices[2] = Interpolate(vec3i(x, y, z) + VertexIndices[2], vec3i(x, y, z) + VertexIndices[3]); if (EdgeTable[Lookup] & 8) Vertices[3] = Interpolate(vec3i(x, y, z) + VertexIndices[3], vec3i(x, y, z) + VertexIndices[0]); if (EdgeTable[Lookup] & 16) Vertices[4] = Interpolate(vec3i(x, y, z) + VertexIndices[4], vec3i(x, y, z) + VertexIndices[5]); if (EdgeTable[Lookup] & 32) Vertices[5] = Interpolate(vec3i(x, y, z) + VertexIndices[5], vec3i(x, y, z) + VertexIndices[6]); if (EdgeTable[Lookup] & 64) Vertices[6] = Interpolate(vec3i(x, y, z) + VertexIndices[6], vec3i(x, y, z) + VertexIndices[7]); if (EdgeTable[Lookup] & 128) Vertices[7] = Interpolate(vec3i(x, y, z) + VertexIndices[7], vec3i(x, y, z) + VertexIndices[4]); if (EdgeTable[Lookup] & 256) Vertices[8] = Interpolate(vec3i(x, y, z) + VertexIndices[0], vec3i(x, y, z) + VertexIndices[4]); if (EdgeTable[Lookup] & 512) Vertices[9] = Interpolate(vec3i(x, y, z) + VertexIndices[1], vec3i(x, y, z) + VertexIndices[5]); if (EdgeTable[Lookup] & 1024) Vertices[10] = Interpolate(vec3i(x, y, z) + VertexIndices[2], vec3i(x, y, z) + VertexIndices[6]); if (EdgeTable[Lookup] & 2048) Vertices[11] = Interpolate(vec3i(x, y, z) + VertexIndices[3], vec3i(x, y, z) + VertexIndices[7]); for (u32 i = 0; TriTable[Lookup][i] != -1; i += 3) { for (u32 j = i; j < (i+3); ++ j) Mesh->Vertices.push_back(Vertices[TriTable[Lookup][j]]); ion::Scene::CSimpleMesh::STriangle Tri; Tri.Indices[0] = (uint) Mesh->Vertices.size() - 3; Tri.Indices[1] = (uint) Mesh->Vertices.size() - 2; Tri.Indices[2] = (uint) Mesh->Vertices.size() - 1; Mesh->Triangles.push_back(Tri); } } } return Mesh; }
#include "MarchingCubes.h" #include "MarchingCubesLookupTables.h" #include "CColorTable.h" void CalculateGradient(SMarchingCubesVolume & Volume) { for (s32 z = 0; z < Volume.Dimensions.Z; ++ z) for (s32 y = 0; y < Volume.Dimensions.Y; ++ y) for (s32 x = 0; x < Volume.Dimensions.X; ++ x) { Volume.Get(x, y, z).Gradient = vec3f( Volume.Get(x+1, y, z).Value - Volume.Get(x-1, y, z).Value, Volume.Get(x, y+1, z).Value - Volume.Get(x, y-1, z).Value, Volume.Get(x, y, z+1).Value - Volume.Get(x, y, z-1).Value) / 2.f; } } ion::Scene::CSimpleMesh * MarchingCubes(SMarchingCubesVolume & Volume) { CalculateGradient(Volume); ion::Scene::CSimpleMesh * Mesh = new ion::Scene::CSimpleMesh(); int CurrentBuffer = 0; Mesh->Vertices.reserve(1 << 14); Mesh->Triangles.reserve(1 << 11); ion::Scene::CSimpleMesh::SVertex Vertices[12]; vec3i VertexIndices[8] = { vec3i(0, 0, 0), vec3i(1, 0, 0), vec3i(1, 0, 1), vec3i(0, 0, 1), vec3i(0, 1, 0), vec3i(1, 1, 0), vec3i(1, 1, 1), vec3i(0, 1, 1), }; for (s32 z = 0; z < Volume.Dimensions.Z - 1; ++ z) for (s32 y = 0; y < Volume.Dimensions.Y - 1; ++ y) for (s32 x = 0; x < Volume.Dimensions.X - 1; ++ x) { int Lookup = 0; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[0]).Value <= 0)) Lookup |= 1; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[1]).Value <= 0)) Lookup |= 2; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[2]).Value <= 0)) Lookup |= 4; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[3]).Value <= 0)) Lookup |= 8; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[4]).Value <= 0)) Lookup |= 16; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[5]).Value <= 0)) Lookup |= 32; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[6]).Value <= 0)) Lookup |= 64; if ((Volume.Get(vec3i(x, y, z) + VertexIndices[7]).Value <= 0)) Lookup |= 128; auto Interpolate = [&](vec3i const & v1, vec3i const & v2) -> ion::Scene::CSimpleMesh::SVertex { //static CColorTable ColorTable; ion::Scene::CSimpleMesh::SVertex v; f32 const d1 = Volume.Get(v1).Value; f32 const d2 = Volume.Get(v2).Value; f32 ratio = d1 / (d2 - d1); if (ratio <= 0.f) ratio += 1.f; v.Position = vec3f(v1) * (ratio) + vec3f(v2) * (1.f - ratio); //v.Color = ColorTable.Get( // Volume.Get(v1x, v1y, v1z).Color * (ratio) + // Volume.Get(v2x, v2y, v2z).Color * (1.f - ratio)); v.Normal = Normalize(Volume.Get(v1).Gradient) * (ratio) + Normalize(Volume.Get(v2).Gradient) * (1.f - ratio); //f32 const valp1 = Volume.Get(v1).Value; //f32 const valp2 = Volume.Get(v2).Value; //vec3f p1 = vec3f(v1); //vec3f p2 = vec3f(v2); //float mu; //if (abs(0 - valp1) < 0.00001) // return(p1); //if (abs(0 - valp2) < 0.00001) // return(p2); //if (abs(valp1 - valp2) < 0.00001) // return(p1); //mu = (0 - valp1) / (valp2 - valp1); //v.Position.X = p1.X + mu * (p2.X - p1.X); //v.Position.Y = p1.Y + mu * (p2.Y - p1.Y); //v.Position.Z = p1.Z + mu * (p2.Z - p1.Z); return v; }; u32 EdgeTableLookup = EdgeTable[Lookup]; if (EdgeTable[Lookup] != 0) { if (EdgeTable[Lookup] & 1) Vertices[0] = Interpolate(vec3i(x, y, z) + VertexIndices[0], vec3i(x, y, z) + VertexIndices[1]); if (EdgeTable[Lookup] & 2) Vertices[1] = Interpolate(vec3i(x, y, z) + VertexIndices[1], vec3i(x, y, z) + VertexIndices[2]); if (EdgeTable[Lookup] & 4) Vertices[2] = Interpolate(vec3i(x, y, z) + VertexIndices[2], vec3i(x, y, z) + VertexIndices[3]); if (EdgeTable[Lookup] & 8) Vertices[3] = Interpolate(vec3i(x, y, z) + VertexIndices[3], vec3i(x, y, z) + VertexIndices[0]); if (EdgeTable[Lookup] & 16) Vertices[4] = Interpolate(vec3i(x, y, z) + VertexIndices[4], vec3i(x, y, z) + VertexIndices[5]); if (EdgeTable[Lookup] & 32) Vertices[5] = Interpolate(vec3i(x, y, z) + VertexIndices[5], vec3i(x, y, z) + VertexIndices[6]); if (EdgeTable[Lookup] & 64) Vertices[6] = Interpolate(vec3i(x, y, z) + VertexIndices[6], vec3i(x, y, z) + VertexIndices[7]); if (EdgeTable[Lookup] & 128) Vertices[7] = Interpolate(vec3i(x, y, z) + VertexIndices[7], vec3i(x, y, z) + VertexIndices[4]); if (EdgeTable[Lookup] & 256) Vertices[8] = Interpolate(vec3i(x, y, z) + VertexIndices[0], vec3i(x, y, z) + VertexIndices[4]); if (EdgeTable[Lookup] & 512) Vertices[9] = Interpolate(vec3i(x, y, z) + VertexIndices[1], vec3i(x, y, z) + VertexIndices[5]); if (EdgeTable[Lookup] & 1024) Vertices[10] = Interpolate(vec3i(x, y, z) + VertexIndices[2], vec3i(x, y, z) + VertexIndices[6]); if (EdgeTable[Lookup] & 2048) Vertices[11] = Interpolate(vec3i(x, y, z) + VertexIndices[3], vec3i(x, y, z) + VertexIndices[7]); for (u32 i = 0; TriTable[Lookup][i] != -1; i += 3) { for (u32 j = i; j < (i+3); ++ j) Mesh->Vertices.push_back(Vertices[TriTable[Lookup][j]]); ion::Scene::CSimpleMesh::STriangle Tri; Tri.Indices[0] = (uint) Mesh->Vertices.size() - 3; Tri.Indices[1] = (uint) Mesh->Vertices.size() - 2; Tri.Indices[2] = (uint) Mesh->Vertices.size() - 1; Mesh->Triangles.push_back(Tri); } } } return Mesh; }
Fix some issues with border behaviour of marching cubes implementation
[ionScience] Fix some issues with border behaviour of marching cubes implementation
C++
mit
iondune/ionEngine,iondune/ionEngine
a82c2e05b198fc8aa4f56e1ad1b6f42573266d74
plugins/robots/interpreters/trikKitInterpreterCommon/src/trikKitInterpreterPluginBase.cpp
plugins/robots/interpreters/trikKitInterpreterCommon/src/trikKitInterpreterPluginBase.cpp
/* Copyright 2013-2016 CyberTech Labs Ltd. * * 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 "trikKitInterpreterCommon/trikKitInterpreterPluginBase.h" #include <QtWidgets/QApplication> #include <QtWidgets/QLineEdit> #include <twoDModel/engine/twoDModelEngineFacade.h> #include <qrkernel/settingsManager.h> #include <qrkernel/settingsListener.h> #include <qrgui/textEditor/qscintillaTextEdit.h> #include <qrgui/textEditor/languageInfo.h> using namespace trik; using namespace qReal; const Id robotDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "RobotsDiagramNode"); const Id subprogramDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "SubprogramDiagram"); TrikKitInterpreterPluginBase::TrikKitInterpreterPluginBase() : mStart(tr("Start QTS"), nullptr), mStop(tr("Stop QTS"), nullptr) { } TrikKitInterpreterPluginBase::~TrikKitInterpreterPluginBase() { if (mOwnsAdditionalPreferences) { delete mAdditionalPreferences; } if (mOwnsBlocksFactory) { delete mBlocksFactory; } } void TrikKitInterpreterPluginBase::initKitInterpreterPluginBase (robotModel::TrikRobotModelBase * const realRobotModel , robotModel::twoD::TrikTwoDRobotModel * const twoDRobotModel , blocks::TrikBlocksFactoryBase * const blocksFactory ) { mRealRobotModel.reset(realRobotModel); mTwoDRobotModel.reset(twoDRobotModel); mBlocksFactory = blocksFactory; const auto modelEngine = new twoDModel::engine::TwoDModelEngineFacade(*mTwoDRobotModel); mTwoDRobotModel->setEngine(modelEngine->engine()); mTwoDModel.reset(modelEngine); connectDevicesConfigurationProvider(devicesConfigurationProvider()); // ... =( mAdditionalPreferences = new TrikAdditionalPreferences({ mRealRobotModel->name() }); mQtsInterpreter.reset(new TrikQtsInterpreter(mTwoDRobotModel)); } void TrikKitInterpreterPluginBase::startJSInterpretation(const QString &code) { emit codeInterpretationStarted(code); auto model = mTwoDRobotModel; model->stopRobot(); // testStop? const QString modelName = model->robotId(); for (const kitBase::robotModel::PortInfo &port : model->configurablePorts()) { const kitBase::robotModel::DeviceInfo deviceInfo = currentConfiguration(modelName, port); model->configureDevice(port, deviceInfo); } model->applyConfiguration(); qtsInterpreter()->init(); qtsInterpreter()->setCurrentDir(mProjectManager->saveFilePath()); qtsInterpreter()->setRunning(true); emit started(); qtsInterpreter()->interpretScript(code); } void TrikKitInterpreterPluginBase::startJSInterpretation(const QString &code, const QString &inputs) { // we are in exercise mode (maybe rename it later) emit codeInterpretationStarted(code); auto model = mTwoDRobotModel; model->stopRobot(); // testStop? const QString modelName = model->robotId(); for (const kitBase::robotModel::PortInfo &port : model->configurablePorts()) { const kitBase::robotModel::DeviceInfo deviceInfo = currentConfiguration(modelName, port); model->configureDevice(port, deviceInfo); } model->applyConfiguration(); qtsInterpreter()->init(); qtsInterpreter()->setCurrentDir(mProjectManager->saveFilePath()); qtsInterpreter()->setRunning(true); emit started(); qtsInterpreter()->interpretScriptExercise(code, inputs); } TrikQtsInterpreter * TrikKitInterpreterPluginBase::qtsInterpreter() const { return mQtsInterpreter.data(); } void TrikKitInterpreterPluginBase::init(const kitBase::KitPluginConfigurator &configurer) { connect(&configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::robotModelChanged , [this](const QString &modelName) { mCurrentlySelectedModelName = modelName; }); qReal::gui::MainWindowInterpretersInterface &interpretersInterface = configurer.qRealConfigurator().mainWindowInterpretersInterface(); mProjectManager = &configurer.qRealConfigurator().projectManager(); mTwoDModel->init(configurer.eventsForKitPlugin() , configurer.qRealConfigurator().systemEvents() , configurer.qRealConfigurator().logicalModelApi() , configurer.qRealConfigurator().controller() , interpretersInterface , configurer.qRealConfigurator().mainWindowDockInterface() , configurer.qRealConfigurator().projectManager() , configurer.interpreterControl()); mRealRobotModel->setErrorReporter(*interpretersInterface.errorReporter()); mTwoDRobotModel->setErrorReporter(*interpretersInterface.errorReporter()); mQtsInterpreter->setErrorReporter(*interpretersInterface.errorReporter()); mMainWindow = &configurer.qRealConfigurator().mainWindowInterpretersInterface(); mSystemEvents = &configurer.qRealConfigurator().systemEvents(); /// @todo: refactor? mStart.setObjectName("runQts"); mStart.setText(tr("Run program")); mStart.setIcon(QIcon(":/trik/qts/images/run.png")); mStop.setObjectName("stopQts"); mStop.setText(tr("Stop robot")); mStop.setIcon(QIcon(":/trik/qts/images/stop.png")); mStop.setVisible(false); mStart.setVisible(false); connect(&configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretCode , [this](const QString &code, const QString &inputs){ if (mIsModelSelected) { startJSInterpretation(code, inputs); } }); connect(&configurer.robotModelManager() , &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged , [this](kitBase::robotModel::RobotModelInterface &model){ mIsModelSelected = robotModels().contains(&model); /// @todo: would probably make sense to make the current opened tab info available globally somewhere bool isCodeTabOpen = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab()); mStart.setVisible(mIsModelSelected && isCodeTabOpen); mStop.setVisible(false); // interpretation should always stop when switching models? }); connect(&configurer.interpreterControl() , &kitBase::InterpreterControlInterface::stopAllInterpretation , this , [this](qReal::interpretation::StopReason) { if (mQtsInterpreter->isRunning()) { testStop(); } }); connect(&configurer.interpreterControl() , &kitBase::InterpreterControlInterface::startJsInterpretation , this , [this]() { if (!mQtsInterpreter->isRunning() && mIsModelSelected) { // temporary testStart(); } }); connect(&mStart, &QAction::triggered, this, &TrikKitInterpreterPluginBase::testStart); connect(&mStop, &QAction::triggered, this, &TrikKitInterpreterPluginBase::testStop); connect(mQtsInterpreter.data() , &TrikQtsInterpreter::completed , this , &TrikKitInterpreterPluginBase::testStop); // refactor? connect(this , &TrikKitInterpreterPluginBase::started , &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStarted ); connect(this , &TrikKitInterpreterPluginBase::stopped , &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStopped ); // connect(&configurer.qRealConfigurator().systemEvents(), // &kitBase::EventsForKitPluginInterface:) connect(&configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStarted , [this](){ /// @todo const bool isQtsInt = mQtsInterpreter->isRunning(); mStart.setEnabled(isQtsInt); mStop.setEnabled(isQtsInt); } ); QObject::connect( this , &TrikKitInterpreterPluginBase::codeInterpretationStarted , &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::codeInterpretationStarted ); QObject::connect( &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStopped , [this](qReal::interpretation::StopReason reason){ /// @todo Q_UNUSED(reason); mStart.setEnabled(true); mStop.setEnabled(true); } ); connect(mSystemEvents , &qReal::SystemEvents::activeTabChanged , this , &TrikKitInterpreterPluginBase::onTabChanged); connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged , mRealRobotModel.data(), &robotModel::TrikRobotModelBase::rereadSettings); connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged , mTwoDRobotModel.data(), &robotModel::twoD::TrikTwoDRobotModel::rereadSettings); } QList<kitBase::robotModel::RobotModelInterface *> TrikKitInterpreterPluginBase::robotModels() { return {mRealRobotModel.data(), mTwoDRobotModel.data()}; } kitBase::blocksBase::BlocksFactoryInterface *TrikKitInterpreterPluginBase::blocksFactoryFor( const kitBase::robotModel::RobotModelInterface *model) { Q_UNUSED(model); mOwnsBlocksFactory = false; return mBlocksFactory; } kitBase::robotModel::RobotModelInterface *TrikKitInterpreterPluginBase::defaultRobotModel() { return mTwoDRobotModel.data(); } QList<kitBase::AdditionalPreferences *> TrikKitInterpreterPluginBase::settingsWidgets() { mOwnsAdditionalPreferences = false; return {mAdditionalPreferences}; } QWidget *TrikKitInterpreterPluginBase::quickPreferencesFor(const kitBase::robotModel::RobotModelInterface &model) { return model.name().toLower().contains("twod") ? nullptr : produceIpAddressConfigurer(); } QList<qReal::ActionInfo> TrikKitInterpreterPluginBase::customActions() { return { qReal::ActionInfo(&mStart, "interpreters", "tools"), qReal::ActionInfo(&mStop, "interpreters", "tools") }; } QList<HotKeyActionInfo> TrikKitInterpreterPluginBase::hotKeyActions() { return {}; } QString TrikKitInterpreterPluginBase::defaultSettingsFile() const { return ":/trikDefaultSettings.ini"; } QIcon TrikKitInterpreterPluginBase::iconForFastSelector( const kitBase::robotModel::RobotModelInterface &robotModel) const { return &robotModel == mRealRobotModel.data() ? QIcon(":/icons/switch-real-trik.svg") : &robotModel == mTwoDRobotModel.data() ? QIcon(":/icons/switch-2d.svg") : QIcon(); } kitBase::DevicesConfigurationProvider *TrikKitInterpreterPluginBase::devicesConfigurationProvider() { return &mTwoDModel->devicesConfigurationProvider(); } QWidget *TrikKitInterpreterPluginBase::produceIpAddressConfigurer() { QLineEdit * const quickPreferences = new QLineEdit; quickPreferences->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); quickPreferences->setPlaceholderText(tr("Enter robot`s IP-address here...")); const auto updateQuickPreferences = [quickPreferences]() { const QString ip = qReal::SettingsManager::value("TrikTcpServer").toString(); if (quickPreferences->text() != ip) { quickPreferences->setText(ip); } }; updateQuickPreferences(); connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged, updateQuickPreferences); qReal::SettingsListener::listen("TrikTcpServer", updateQuickPreferences, this); connect(quickPreferences, &QLineEdit::textChanged, [](const QString &text) { qReal::SettingsManager::setValue("TrikTcpServer", text); }); connect(this, &QObject::destroyed, [quickPreferences]() { delete quickPreferences; }); return quickPreferences; } void TrikKitInterpreterPluginBase::testStart() { mStop.setVisible(true); mStart.setVisible(false); /// todo: bad auto texttab = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab()); auto isJS = [](const QString &ext){ return ext == "js" || ext == "qts"; }; if (texttab && isJS(texttab->currentLanguage().extension)) { startJSInterpretation(texttab->text()); } else { qDebug("wrong tab selected"); mStop.setVisible(false); mStart.setVisible(true); /// todo: refactor the whole button shenanigans } } void TrikKitInterpreterPluginBase::testStop() { mStop.setVisible(false); mStart.setVisible(true); qtsInterpreter()->abort(); mTwoDRobotModel->stopRobot(); emit stopped(qReal::interpretation::StopReason::userStop); } void TrikKitInterpreterPluginBase::onTabChanged(const TabInfo &info) { if (!mIsModelSelected) { return; } const bool isCodeTab = info.type() == qReal::TabInfo::TabType::code; mStart.setEnabled(isCodeTab); mStop.setEnabled(isCodeTab); if (mQtsInterpreter->isRunning()) { mStop.trigger(); // Should interpretation should always stops at the change of tabs or not? } if (isCodeTab) { mStart.setVisible(true); mStop.setVisible(false); } else { mStart.setVisible(false); mStop.setVisible(false); } }
/* Copyright 2013-2016 CyberTech Labs Ltd. * * 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 "trikKitInterpreterCommon/trikKitInterpreterPluginBase.h" #include <QtWidgets/QApplication> #include <QtWidgets/QLineEdit> #include <twoDModel/engine/twoDModelEngineFacade.h> #include <qrkernel/settingsManager.h> #include <qrkernel/settingsListener.h> #include <qrgui/textEditor/qscintillaTextEdit.h> #include <qrgui/textEditor/languageInfo.h> using namespace trik; using namespace qReal; const Id robotDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "RobotsDiagramNode"); const Id subprogramDiagramType = Id("RobotsMetamodel", "RobotsDiagram", "SubprogramDiagram"); TrikKitInterpreterPluginBase::TrikKitInterpreterPluginBase() : mStart(tr("Start QTS"), nullptr), mStop(tr("Stop QTS"), nullptr) { } TrikKitInterpreterPluginBase::~TrikKitInterpreterPluginBase() { if (mOwnsAdditionalPreferences) { delete mAdditionalPreferences; } if (mOwnsBlocksFactory) { delete mBlocksFactory; } } void TrikKitInterpreterPluginBase::initKitInterpreterPluginBase (robotModel::TrikRobotModelBase * const realRobotModel , robotModel::twoD::TrikTwoDRobotModel * const twoDRobotModel , blocks::TrikBlocksFactoryBase * const blocksFactory ) { mRealRobotModel.reset(realRobotModel); mTwoDRobotModel.reset(twoDRobotModel); mBlocksFactory = blocksFactory; const auto modelEngine = new twoDModel::engine::TwoDModelEngineFacade(*mTwoDRobotModel); mTwoDRobotModel->setEngine(modelEngine->engine()); mTwoDModel.reset(modelEngine); connectDevicesConfigurationProvider(devicesConfigurationProvider()); // ... =( mAdditionalPreferences = new TrikAdditionalPreferences({ mRealRobotModel->name() }); mQtsInterpreter.reset(new TrikQtsInterpreter(mTwoDRobotModel)); } void TrikKitInterpreterPluginBase::startJSInterpretation(const QString &code) { emit codeInterpretationStarted(code); auto model = mTwoDRobotModel; model->stopRobot(); // testStop? const QString modelName = model->robotId(); for (const kitBase::robotModel::PortInfo &port : model->configurablePorts()) { const kitBase::robotModel::DeviceInfo deviceInfo = currentConfiguration(modelName, port); model->configureDevice(port, deviceInfo); } model->applyConfiguration(); qtsInterpreter()->init(); qtsInterpreter()->setCurrentDir(mProjectManager->saveFilePath()); qtsInterpreter()->setRunning(true); emit started(); qtsInterpreter()->interpretScript(code); } void TrikKitInterpreterPluginBase::startJSInterpretation(const QString &code, const QString &inputs) { // we are in exercise mode (maybe rename it later) emit codeInterpretationStarted(code); auto model = mTwoDRobotModel; model->stopRobot(); // testStop? const QString modelName = model->robotId(); for (const kitBase::robotModel::PortInfo &port : model->configurablePorts()) { const kitBase::robotModel::DeviceInfo deviceInfo = currentConfiguration(modelName, port); model->configureDevice(port, deviceInfo); } model->applyConfiguration(); qtsInterpreter()->init(); qtsInterpreter()->setCurrentDir(mProjectManager->saveFilePath()); qtsInterpreter()->setRunning(true); emit started(); qtsInterpreter()->interpretScriptExercise(code, inputs); } TrikQtsInterpreter * TrikKitInterpreterPluginBase::qtsInterpreter() const { return mQtsInterpreter.data(); } void TrikKitInterpreterPluginBase::init(const kitBase::KitPluginConfigurator &configurer) { connect(&configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::robotModelChanged , [this](const QString &modelName) { mCurrentlySelectedModelName = modelName; }); qReal::gui::MainWindowInterpretersInterface &interpretersInterface = configurer.qRealConfigurator().mainWindowInterpretersInterface(); mProjectManager = &configurer.qRealConfigurator().projectManager(); mTwoDModel->init(configurer.eventsForKitPlugin() , configurer.qRealConfigurator().systemEvents() , configurer.qRealConfigurator().logicalModelApi() , configurer.qRealConfigurator().controller() , interpretersInterface , configurer.qRealConfigurator().mainWindowDockInterface() , configurer.qRealConfigurator().projectManager() , configurer.interpreterControl()); mRealRobotModel->setErrorReporter(*interpretersInterface.errorReporter()); mTwoDRobotModel->setErrorReporter(*interpretersInterface.errorReporter()); mQtsInterpreter->setErrorReporter(*interpretersInterface.errorReporter()); mMainWindow = &configurer.qRealConfigurator().mainWindowInterpretersInterface(); mSystemEvents = &configurer.qRealConfigurator().systemEvents(); /// @todo: refactor? mStart.setObjectName("runQts"); mStart.setText(tr("Run program")); mStart.setIcon(QIcon(":/trik/qts/images/run.png")); mStop.setObjectName("stopQts"); mStop.setText(tr("Stop robot")); mStop.setIcon(QIcon(":/trik/qts/images/stop.png")); mStop.setVisible(false); mStart.setVisible(false); connect(&configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretCode , [this](const QString &code, const QString &inputs){ if (mIsModelSelected) { startJSInterpretation(code, inputs); } }); connect(&configurer.robotModelManager() , &kitBase::robotModel::RobotModelManagerInterface::robotModelChanged , [this](kitBase::robotModel::RobotModelInterface &model){ mIsModelSelected = robotModels().contains(&model); /// @todo: would probably make sense to make the current opened tab info available globally somewhere bool isCodeTabOpen = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab()); mStart.setVisible(mIsModelSelected && isCodeTabOpen); mStop.setVisible(false); // interpretation should always stop when switching models? }); connect(&configurer.interpreterControl() , &kitBase::InterpreterControlInterface::stopAllInterpretation , this , [this](qReal::interpretation::StopReason) { if (mQtsInterpreter->isRunning()) { testStop(); } }); connect(&configurer.interpreterControl() , &kitBase::InterpreterControlInterface::startJsInterpretation , this , [this]() { if (!mQtsInterpreter->isRunning() && mIsModelSelected) { // temporary testStart(); } }); connect(&mStart, &QAction::triggered, this, &TrikKitInterpreterPluginBase::testStart); connect(&mStop, &QAction::triggered, this, &TrikKitInterpreterPluginBase::testStop); connect(mQtsInterpreter.data() , &TrikQtsInterpreter::completed , this , &TrikKitInterpreterPluginBase::testStop); // refactor? connect(this , &TrikKitInterpreterPluginBase::started , &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStarted ); connect(this , &TrikKitInterpreterPluginBase::stopped , &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStopped ); // connect(&configurer.qRealConfigurator().systemEvents(), // &kitBase::EventsForKitPluginInterface:) connect(&configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStarted , [this](){ /// @todo const bool isQtsInt = mQtsInterpreter->isRunning(); mStart.setEnabled(isQtsInt); mStop.setEnabled(isQtsInt); } ); QObject::connect( this , &TrikKitInterpreterPluginBase::codeInterpretationStarted , &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::codeInterpretationStarted ); QObject::connect( &configurer.eventsForKitPlugin() , &kitBase::EventsForKitPluginInterface::interpretationStopped , [this](qReal::interpretation::StopReason reason){ /// @todo Q_UNUSED(reason); mStart.setEnabled(true); mStop.setEnabled(true); } ); connect(mSystemEvents , &qReal::SystemEvents::activeTabChanged , this , &TrikKitInterpreterPluginBase::onTabChanged); connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged , mRealRobotModel.data(), &robotModel::TrikRobotModelBase::rereadSettings); connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged , mTwoDRobotModel.data(), &robotModel::twoD::TrikTwoDRobotModel::rereadSettings); } QList<kitBase::robotModel::RobotModelInterface *> TrikKitInterpreterPluginBase::robotModels() { return {mRealRobotModel.data(), mTwoDRobotModel.data()}; } kitBase::blocksBase::BlocksFactoryInterface *TrikKitInterpreterPluginBase::blocksFactoryFor( const kitBase::robotModel::RobotModelInterface *model) { Q_UNUSED(model); mOwnsBlocksFactory = false; return mBlocksFactory; } kitBase::robotModel::RobotModelInterface *TrikKitInterpreterPluginBase::defaultRobotModel() { return mTwoDRobotModel.data(); } QList<kitBase::AdditionalPreferences *> TrikKitInterpreterPluginBase::settingsWidgets() { mOwnsAdditionalPreferences = false; return {mAdditionalPreferences}; } QWidget *TrikKitInterpreterPluginBase::quickPreferencesFor(const kitBase::robotModel::RobotModelInterface &model) { return model.name().toLower().contains("twod") ? nullptr : produceIpAddressConfigurer(); } QList<qReal::ActionInfo> TrikKitInterpreterPluginBase::customActions() { return { qReal::ActionInfo(&mStart, "interpreters", "tools"), qReal::ActionInfo(&mStop, "interpreters", "tools") }; } QList<HotKeyActionInfo> TrikKitInterpreterPluginBase::hotKeyActions() { return {}; } QString TrikKitInterpreterPluginBase::defaultSettingsFile() const { return ":/trikDefaultSettings.ini"; } QIcon TrikKitInterpreterPluginBase::iconForFastSelector( const kitBase::robotModel::RobotModelInterface &robotModel) const { return &robotModel == mRealRobotModel.data() ? QIcon(":/icons/switch-real-trik.svg") : &robotModel == mTwoDRobotModel.data() ? QIcon(":/icons/switch-2d.svg") : QIcon(); } kitBase::DevicesConfigurationProvider *TrikKitInterpreterPluginBase::devicesConfigurationProvider() { return &mTwoDModel->devicesConfigurationProvider(); } QWidget *TrikKitInterpreterPluginBase::produceIpAddressConfigurer() { QLineEdit * const quickPreferences = new QLineEdit; quickPreferences->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); quickPreferences->setPlaceholderText(tr("Enter robot`s IP-address here...")); const auto updateQuickPreferences = [quickPreferences]() { const QString ip = qReal::SettingsManager::value("TrikTcpServer").toString(); if (quickPreferences->text() != ip) { quickPreferences->setText(ip); } }; updateQuickPreferences(); connect(mAdditionalPreferences, &TrikAdditionalPreferences::settingsChanged, updateQuickPreferences); qReal::SettingsListener::listen("TrikTcpServer", updateQuickPreferences, this); connect(quickPreferences, &QLineEdit::textChanged, [](const QString &text) { qReal::SettingsManager::setValue("TrikTcpServer", text); }); connect(this, &QObject::destroyed, [quickPreferences]() { delete quickPreferences; }); return quickPreferences; } void TrikKitInterpreterPluginBase::testStart() { mStop.setVisible(true); mStart.setVisible(false); /// todo: bad auto texttab = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab()); auto isJS = [](const QString &ext){ return ext == "js" || ext == "qts"; }; if (texttab && isJS(texttab->currentLanguage().extension)) { startJSInterpretation(texttab->text()); } else { qDebug("wrong tab selected"); mStop.setVisible(false); mStart.setVisible(true); /// todo: refactor the whole button shenanigans } } void TrikKitInterpreterPluginBase::testStop() { mStop.setVisible(false); mStart.setVisible(true); qtsInterpreter()->abort(); mTwoDRobotModel->stopRobot(); emit stopped(qReal::interpretation::StopReason::userStop); } void TrikKitInterpreterPluginBase::onTabChanged(const TabInfo &info) { if (!mIsModelSelected) { return; } const bool isCodeTab = info.type() == qReal::TabInfo::TabType::code; if (isCodeTab) { auto texttab = dynamic_cast<qReal::text::QScintillaTextEdit *>(mMainWindow->currentTab()); auto isJS = [](const QString &ext){ return ext == "js" || ext == "qts"; }; if (texttab && isJS(texttab->currentLanguage().extension)) { mStart.setEnabled(true); mStop.setEnabled(true); } else { mStart.setEnabled(false); mStop.setEnabled(false); } } else { mStart.setEnabled(false); // Should matter mStop.setEnabled(false); } if (mQtsInterpreter->isRunning()) { mStop.trigger(); // Should interpretation should always stops at the change of tabs or not? } if (isCodeTab) { mStart.setVisible(true); mStop.setVisible(false); } else { mStart.setVisible(false); mStop.setVisible(false); } }
fix active buttons on wrong code
fix active buttons on wrong code
C++
apache-2.0
iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal,iakov/qreal
aa1dbbe59aa6e7a8eb0536e33738e99f5a712f25
Modules/DiffusionImaging/DiffusionCore/Algorithms/Registration/mitkBatchedRegistration.cpp
Modules/DiffusionImaging/DiffusionCore/Algorithms/Registration/mitkBatchedRegistration.cpp
#include "mitkBatchedRegistration.h" #include "mitkPyramidImageRegistrationMethod.h" #include "mitkDiffusionImage.h" #include <mitkRotationOperation.h> #include <mitkDiffusionImageCorrectionFilter.h> #include "itkB0ImageExtractionImageFilter.h" #include <itkScalableAffineTransform.h> #include <vnl/vnl_inverse.h> // VTK #include <vtkTransform.h> // DEBUG #include <mitkIOUtil.h> mitk::BatchedRegistration::BatchedRegistration() : m_RegisteredImagesValid(false) { } void mitk::BatchedRegistration::SetFixedImage(mitk::Image::Pointer& fixedImage) { m_FixedImage = fixedImage; } void mitk::BatchedRegistration::SetMovingReferenceImage(Image::Pointer &movingImage) { m_MovingReference = movingImage; m_RegisteredImagesValid = false; } void mitk::BatchedRegistration::SetBatch(std::vector<mitk::Image::Pointer> imageBatch) { m_ImageBatch.clear(); m_ImageBatch = imageBatch; } std::vector<mitk::Image::Pointer> mitk::BatchedRegistration::GetRegisteredImages() { if (!m_RegisteredImagesValid) { m_RegisteredImages.clear(); // First transform moving reference image RidgidTransformType transf = new double(6); double offset[3]; //GetTransformation(m_FixedImage, m_MovingReference,transf,NULL,offset); // store it as first element in vector // ApplyTransformationToImage(m_MovingReference,transf,NULL,false,offset); m_RegisteredImages.push_back(m_MovingReference); // apply transformation to whole batch std::vector<mitk::Image::Pointer>::const_iterator itEnd = m_ImageBatch.end(); for (std::vector<mitk::Image::Pointer>::iterator it = m_ImageBatch.begin(); it != itEnd; ++it) { //TODO fixme // ApplyTransformationToImage(*it,transf); m_RegisteredImages.push_back(*it); } } return m_RegisteredImages; } void mitk::BatchedRegistration::ApplyTransformationToImage(mitk::Image::Pointer &img, const mitk::BatchedRegistration::RidgidTransformType &transformation,double* offset, mitk::Image::Pointer resampleReference, bool binary) const { typedef mitk::DiffusionImage<short> DiffusionImageType; mitk::Image::Pointer ref; mitk::PyramidImageRegistrationMethod::Pointer registrationMethod = mitk::PyramidImageRegistrationMethod::New(); registrationMethod->SetTransformToRigid(); if (binary) registrationMethod->SetUseNearestNeighborInterpolation(true); if (resampleReference.IsNotNull()) { registrationMethod->SetFixedImage( resampleReference ); } else { // clone image, to prevent recursive access on resampling .. ref = img->Clone(); registrationMethod->SetFixedImage( ref ); } if (dynamic_cast<DiffusionImageType*> (img.GetPointer()) == NULL) { itk::Image<float,3>::Pointer itkImage = itk::Image<float,3>::New(); CastToItkImage(img, itkImage); // typedef itk::Euler3DTransform< double > RigidTransformType; RigidTransformType::Pointer rtransform = RigidTransformType::New(); RigidTransformType::ParametersType parameters(RigidTransformType::ParametersDimension); for (int i = 0; i<6;++i) parameters[i] = transformation[i]; rtransform->SetParameters( parameters ); mitk::Point3D origin = itkImage->GetOrigin(); origin[0]-=offset[0]; origin[1]-=offset[1]; origin[2]-=offset[2]; mitk::Point3D newOrigin = rtransform->GetInverseTransform()->TransformPoint(origin); itk::Matrix<double,3,3> dir = itkImage->GetDirection(); itk::Matrix<double,3,3> transM ( vnl_inverse(rtransform->GetMatrix().GetVnlMatrix())); itk::Matrix<double,3,3> newDirection = transM * dir; itkImage->SetOrigin(newOrigin); itkImage->SetDirection(newDirection); GrabItkImageMemory(itkImage, img); } else { DiffusionImageType::Pointer diffImages = dynamic_cast<DiffusionImageType*>(img.GetPointer()); typedef itk::Euler3DTransform< double > RigidTransformType; RigidTransformType::Pointer rtransform = RigidTransformType::New(); RigidTransformType::ParametersType parameters(RigidTransformType::ParametersDimension); for (int i = 0; i<6;++i) parameters[i] = transformation[i]; rtransform->SetParameters( parameters ); mitk::Point3D b0origin = diffImages->GetVectorImage()->GetOrigin(); b0origin[0]-=offset[0]; b0origin[1]-=offset[1]; b0origin[2]-=offset[2]; mitk::Point3D newOrigin = rtransform->GetInverseTransform()->TransformPoint(b0origin); itk::Matrix<double,3,3> dir = diffImages->GetVectorImage()->GetDirection(); itk::Matrix<double,3,3> transM ( vnl_inverse(rtransform->GetMatrix().GetVnlMatrix())); itk::Matrix<double,3,3> newDirection = transM * dir; diffImages->GetVectorImage()->SetOrigin(newOrigin); diffImages->GetVectorImage()->SetDirection(newDirection); diffImages->Modified(); mitk::DiffusionImageCorrectionFilter<short>::Pointer correctionFilter = mitk::DiffusionImageCorrectionFilter<short>::New(); // For Diff. Images: Need to rotate the gradients correctionFilter->SetImage(diffImages); // works direcrky on input image!! correctionFilter->CorrectDirections(transM.GetVnlMatrix()); img = diffImages; } } void mitk::BatchedRegistration::GetTransformation(mitk::Image::Pointer fixedImage, mitk::Image::Pointer movingImage, RidgidTransformType transformation,double* offset, mitk::Image::Pointer mask) { // Handle case that fixed or moving image is a DWI image mitk::DiffusionImage<short>* fixedDwi = dynamic_cast<mitk::DiffusionImage<short>*> (fixedImage.GetPointer()); mitk::DiffusionImage<short>* movingDwi = dynamic_cast<mitk::DiffusionImage<short>*> (movingImage.GetPointer()); itk::B0ImageExtractionImageFilter<short,short >::Pointer b0Extraction = itk::B0ImageExtractionImageFilter<short,short>::New(); offset[0]=offset[1]=offset[2]=0; if (fixedDwi != NULL) { b0Extraction->SetInput(fixedDwi->GetVectorImage()); b0Extraction->SetDirections(fixedDwi->GetDirections()); b0Extraction->Update(); mitk::Image::Pointer tmp = mitk::Image::New(); tmp->InitializeByItk(b0Extraction->GetOutput()); tmp->SetVolume(b0Extraction->GetOutput()->GetBufferPointer()); fixedImage = tmp; } if (movingDwi != NULL) { b0Extraction->SetInput(movingDwi->GetVectorImage()); b0Extraction->SetDirections(movingDwi->GetDirections()); b0Extraction->Update(); mitk::Image::Pointer tmp = mitk::Image::New(); tmp->InitializeByItk(b0Extraction->GetOutput()); tmp->SetVolume(b0Extraction->GetOutput()->GetBufferPointer()); movingImage = tmp; Point3D origin = fixedImage->GetGeometry()->GetOrigin(); Point3D originMoving = movingImage->GetGeometry()->GetOrigin(); offset[0] = originMoving[0]-origin[0]; offset[1] = originMoving[1]-origin[1]; offset[2] = originMoving[2]-origin[2]; movingImage->GetGeometry()->SetOrigin(origin); } // Start registration mitk::PyramidImageRegistrationMethod::Pointer registrationMethod = mitk::PyramidImageRegistrationMethod::New(); registrationMethod->SetFixedImage( fixedImage ); if (mask.IsNotNull()) { registrationMethod->SetFixedImageMask(mask); registrationMethod->SetUseFixedImageMask(true); } else { registrationMethod->SetUseFixedImageMask(false); } registrationMethod->SetTransformToRigid(); registrationMethod->SetCrossModalityOn(); registrationMethod->SetMovingImage(movingImage); registrationMethod->Update(); registrationMethod->GetParameters(transformation); // first three: euler angles, last three translation }
#include "mitkBatchedRegistration.h" #include "mitkPyramidImageRegistrationMethod.h" #include "mitkDiffusionImage.h" #include <mitkRotationOperation.h> #include <mitkDiffusionImageCorrectionFilter.h> #include "itkB0ImageExtractionImageFilter.h" #include <itkScalableAffineTransform.h> #include <vnl/vnl_inverse.h> // VTK #include <vtkTransform.h> // DEBUG #include <mitkIOUtil.h> mitk::BatchedRegistration::BatchedRegistration() : m_RegisteredImagesValid(false) { } void mitk::BatchedRegistration::SetFixedImage(mitk::Image::Pointer& fixedImage) { m_FixedImage = fixedImage; } void mitk::BatchedRegistration::SetMovingReferenceImage(Image::Pointer &movingImage) { m_MovingReference = movingImage; m_RegisteredImagesValid = false; } void mitk::BatchedRegistration::SetBatch(std::vector<mitk::Image::Pointer> imageBatch) { m_ImageBatch.clear(); m_ImageBatch = imageBatch; } std::vector<mitk::Image::Pointer> mitk::BatchedRegistration::GetRegisteredImages() { if (!m_RegisteredImagesValid) { m_RegisteredImages.clear(); // First transform moving reference image RidgidTransformType transf = new double(6); double offset[3]; //GetTransformation(m_FixedImage, m_MovingReference,transf,NULL,offset); // store it as first element in vector // ApplyTransformationToImage(m_MovingReference,transf,NULL,false,offset); m_RegisteredImages.push_back(m_MovingReference); // apply transformation to whole batch std::vector<mitk::Image::Pointer>::const_iterator itEnd = m_ImageBatch.end(); for (std::vector<mitk::Image::Pointer>::iterator it = m_ImageBatch.begin(); it != itEnd; ++it) { //TODO fixme // ApplyTransformationToImage(*it,transf); m_RegisteredImages.push_back(*it); } } return m_RegisteredImages; } void mitk::BatchedRegistration::ApplyTransformationToImage(mitk::Image::Pointer &img, const mitk::BatchedRegistration::RidgidTransformType &transformation,double* offset, mitk::Image::Pointer resampleReference, bool binary) const { typedef mitk::DiffusionImage<short> DiffusionImageType; mitk::Image::Pointer ref; mitk::PyramidImageRegistrationMethod::Pointer registrationMethod = mitk::PyramidImageRegistrationMethod::New(); registrationMethod->SetTransformToRigid(); if (binary) registrationMethod->SetUseNearestNeighborInterpolation(true); if (resampleReference.IsNotNull()) { registrationMethod->SetFixedImage( resampleReference ); } else { // clone image, to prevent recursive access on resampling .. ref = img->Clone(); registrationMethod->SetFixedImage( ref ); } if (dynamic_cast<DiffusionImageType*> (img.GetPointer()) == NULL) { itk::Image<float,3>::Pointer itkImage = itk::Image<float,3>::New(); CastToItkImage(img, itkImage); // typedef itk::Euler3DTransform< double > RigidTransformType; RigidTransformType::Pointer rtransform = RigidTransformType::New(); RigidTransformType::ParametersType parameters(RigidTransformType::ParametersDimension); for (int i = 0; i<6;++i) parameters[i] = transformation[i]; rtransform->SetParameters( parameters ); mitk::Point3D origin = itkImage->GetOrigin(); origin[0]-=offset[0]; origin[1]-=offset[1]; origin[2]-=offset[2]; mitk::Point3D newOrigin = rtransform->GetInverseTransform()->TransformPoint(origin); itk::Matrix<double,3,3> dir = itkImage->GetDirection(); itk::Matrix<double,3,3> transM ( vnl_inverse(rtransform->GetMatrix().GetVnlMatrix())); itk::Matrix<double,3,3> newDirection = transM * dir; itkImage->SetOrigin(newOrigin); itkImage->SetDirection(newDirection); GrabItkImageMemory(itkImage, img); } else { DiffusionImageType::Pointer diffImages = dynamic_cast<DiffusionImageType*>(img.GetPointer()); typedef itk::Euler3DTransform< double > RigidTransformType; RigidTransformType::Pointer rtransform = RigidTransformType::New(); RigidTransformType::ParametersType parameters(RigidTransformType::ParametersDimension); for (int i = 0; i<6;++i) parameters[i] = transformation[i]; rtransform->SetParameters( parameters ); mitk::Point3D b0origin = diffImages->GetVectorImage()->GetOrigin(); b0origin[0]-=offset[0]; b0origin[1]-=offset[1]; b0origin[2]-=offset[2]; mitk::Point3D newOrigin = rtransform->GetInverseTransform()->TransformPoint(b0origin); itk::Matrix<double,3,3> dir = diffImages->GetVectorImage()->GetDirection(); itk::Matrix<double,3,3> transM ( vnl_inverse(rtransform->GetMatrix().GetVnlMatrix())); itk::Matrix<double,3,3> newDirection = transM * dir; diffImages->GetVectorImage()->SetOrigin(newOrigin); diffImages->GetVectorImage()->SetDirection(newDirection); diffImages->Modified(); mitk::DiffusionImageCorrectionFilter<short>::Pointer correctionFilter = mitk::DiffusionImageCorrectionFilter<short>::New(); // For Diff. Images: Need to rotate the gradients correctionFilter->SetImage(diffImages); // works direcrky on input image!! correctionFilter->CorrectDirections(transM.GetVnlMatrix()); img = diffImages; } } void mitk::BatchedRegistration::GetTransformation(mitk::Image::Pointer fixedImage, mitk::Image::Pointer movingImage, RidgidTransformType transformation,double* offset, mitk::Image::Pointer mask) { // Handle case that fixed or moving image is a DWI image mitk::DiffusionImage<short>* fixedDwi = dynamic_cast<mitk::DiffusionImage<short>*> (fixedImage.GetPointer()); mitk::DiffusionImage<short>* movingDwi = dynamic_cast<mitk::DiffusionImage<short>*> (movingImage.GetPointer()); itk::B0ImageExtractionImageFilter<short,short >::Pointer b0Extraction = itk::B0ImageExtractionImageFilter<short,short>::New(); offset[0]=offset[1]=offset[2]=0; if (fixedDwi != NULL) { b0Extraction->SetInput(fixedDwi->GetVectorImage()); b0Extraction->SetDirections(fixedDwi->GetDirections()); b0Extraction->Update(); mitk::Image::Pointer tmp = mitk::Image::New(); tmp->InitializeByItk(b0Extraction->GetOutput()); tmp->SetVolume(b0Extraction->GetOutput()->GetBufferPointer()); fixedImage = tmp; } if (movingDwi != NULL) { b0Extraction->SetInput(movingDwi->GetVectorImage()); b0Extraction->SetDirections(movingDwi->GetDirections()); b0Extraction->Update(); mitk::Image::Pointer tmp = mitk::Image::New(); tmp->InitializeByItk(b0Extraction->GetOutput()); tmp->SetVolume(b0Extraction->GetOutput()->GetBufferPointer()); movingImage = tmp; Point3D origin = fixedImage->GetGeometry()->GetOrigin(); Point3D originMoving = movingImage->GetGeometry()->GetOrigin(); offset[0] = originMoving[0]-origin[0]; offset[1] = originMoving[1]-origin[1]; offset[2] = originMoving[2]-origin[2]; movingImage->GetGeometry()->SetOrigin(origin); } // Start registration mitk::PyramidImageRegistrationMethod::Pointer registrationMethod = mitk::PyramidImageRegistrationMethod::New(); registrationMethod->SetFixedImage( fixedImage ); if (mask.IsNotNull()) { registrationMethod->SetFixedImageMask(mask); registrationMethod->SetUseFixedImageMask(true); } else { registrationMethod->SetUseFixedImageMask(false); } registrationMethod->SetTransformToRigid(); registrationMethod->SetCrossModalityOn(); registrationMethod->SetMovingImage(movingImage); registrationMethod->Update(); registrationMethod->GetParameters(transformation); // first three: euler angles, last three translation }
Fix Image data access
Fix Image data access
C++
bsd-3-clause
MITK/MITK,iwegner/MITK,rfloca/MITK,rfloca/MITK,danielknorr/MITK,rfloca/MITK,danielknorr/MITK,fmilano/mitk,rfloca/MITK,fmilano/mitk,iwegner/MITK,danielknorr/MITK,danielknorr/MITK,NifTK/MITK,lsanzdiaz/MITK-BiiG,NifTK/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK,lsanzdiaz/MITK-BiiG,danielknorr/MITK,iwegner/MITK,rfloca/MITK,MITK/MITK,iwegner/MITK,RabadanLab/MITKats,NifTK/MITK,fmilano/mitk,iwegner/MITK,RabadanLab/MITKats,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,iwegner/MITK,RabadanLab/MITKats,NifTK/MITK,RabadanLab/MITKats,fmilano/mitk,rfloca/MITK,fmilano/mitk,lsanzdiaz/MITK-BiiG,fmilano/mitk,MITK/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK,RabadanLab/MITKats,MITK/MITK,danielknorr/MITK,lsanzdiaz/MITK-BiiG,NifTK/MITK,lsanzdiaz/MITK-BiiG,fmilano/mitk,danielknorr/MITK,rfloca/MITK,NifTK/MITK
0a1ae6f71589d6ff8d999037455157be95662bb6
components/content_settings/core/browser/plugins_field_trial_unittest.cc
components/content_settings/core/browser/plugins_field_trial_unittest.cc
// Copyright 2015 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 "components/content_settings/core/browser/plugins_field_trial.h" #include "base/command_line.h" #include "base/macros.h" #include "base/metrics/field_trial.h" #include "base/test/mock_entropy_provider.h" #include "components/content_settings/core/browser/content_settings_default_provider.h" #include "components/content_settings/core/browser/website_settings_info.h" #include "components/content_settings/core/browser/website_settings_registry.h" #include "components/content_settings/core/common/content_settings.h" #include "components/plugins/common/plugins_switches.h" #include "components/pref_registry/testing_pref_service_syncable.h" #include "testing/gtest/include/gtest/gtest.h" using base::FieldTrialList; namespace content_settings { const char* kEnableFieldTrial = PluginsFieldTrial::kEnableFieldTrial; const char* kForceFieldTrial = PluginsFieldTrial::kForceFieldTrial; class PluginsFieldTrialTest : public testing::Test { public: PluginsFieldTrialTest() : field_trial_list_(new base::MockEntropyProvider) {} private: base::FieldTrialList field_trial_list_; DISALLOW_COPY_AND_ASSIGN(PluginsFieldTrialTest); }; TEST_F(PluginsFieldTrialTest, DisabledByDefault) { base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); ASSERT_FALSE(cl->HasSwitch(plugins::switches::kDisablePluginPowerSaver)); ASSERT_FALSE(cl->HasSwitch(plugins::switches::kEnablePluginPowerSaver)); ASSERT_FALSE(base::FieldTrialList::TrialExists(kEnableFieldTrial)); ASSERT_FALSE(base::FieldTrialList::TrialExists(kForceFieldTrial)); EXPECT_FALSE(PluginsFieldTrial::IsPluginPowerSaverEnabled()); } TEST_F(PluginsFieldTrialTest, EnabledByFieldTrial) { ASSERT_TRUE(FieldTrialList::CreateFieldTrial(kForceFieldTrial, "Dogfood")); EXPECT_TRUE(PluginsFieldTrial::IsPluginPowerSaverEnabled()); } TEST_F(PluginsFieldTrialTest, DisabledByFieldTrial) { ASSERT_TRUE(FieldTrialList::CreateFieldTrial(kEnableFieldTrial, "Disabled")); EXPECT_FALSE(PluginsFieldTrial::IsPluginPowerSaverEnabled()); } TEST_F(PluginsFieldTrialTest, EnabledBySwitch) { base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); cl->AppendSwitch(plugins::switches::kEnablePluginPowerSaver); EXPECT_TRUE(PluginsFieldTrial::IsPluginPowerSaverEnabled()); } TEST_F(PluginsFieldTrialTest, DisabledBySwitch) { base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); cl->AppendSwitch(plugins::switches::kDisablePluginPowerSaver); EXPECT_FALSE(PluginsFieldTrial::IsPluginPowerSaverEnabled()); } TEST_F(PluginsFieldTrialTest, SwitchOverridesFieldTrial1) { ASSERT_TRUE(FieldTrialList::CreateFieldTrial(kForceFieldTrial, "Disabled")); base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); cl->AppendSwitch(plugins::switches::kEnablePluginPowerSaver); EXPECT_TRUE(PluginsFieldTrial::IsPluginPowerSaverEnabled()); } TEST_F(PluginsFieldTrialTest, SwitchOverridesFieldTrial2) { ASSERT_TRUE(FieldTrialList::CreateFieldTrial(kEnableFieldTrial, "Enabled")); base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); cl->AppendSwitch(plugins::switches::kDisablePluginPowerSaver); EXPECT_FALSE(PluginsFieldTrial::IsPluginPowerSaverEnabled()); } TEST_F(PluginsFieldTrialTest, NoPrefLeftBehind) { ASSERT_TRUE(FieldTrialList::CreateFieldTrial(kEnableFieldTrial, "Enabled")); user_prefs::TestingPrefServiceSyncable prefs; { DefaultProvider::RegisterProfilePrefs(prefs.registry()); DefaultProvider default_provider(&prefs, false); } const std::string& default_plugin_setting_pref_name = WebsiteSettingsRegistry::GetInstance() ->Get(CONTENT_SETTINGS_TYPE_PLUGINS) ->default_value_pref_name(); EXPECT_EQ(CONTENT_SETTING_DETECT_IMPORTANT_CONTENT, prefs.GetInteger(default_plugin_setting_pref_name)); EXPECT_FALSE(prefs.HasPrefPath(default_plugin_setting_pref_name)); } } // namespace content_settings
// Copyright 2015 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 "components/content_settings/core/browser/plugins_field_trial.h" #include "base/command_line.h" #include "base/macros.h" #include "base/metrics/field_trial.h" #include "base/test/mock_entropy_provider.h" #include "components/content_settings/core/browser/content_settings_default_provider.h" #include "components/content_settings/core/browser/website_settings_info.h" #include "components/content_settings/core/browser/website_settings_registry.h" #include "components/content_settings/core/common/content_settings.h" #include "components/plugins/common/plugins_switches.h" #include "components/pref_registry/testing_pref_service_syncable.h" #include "testing/gtest/include/gtest/gtest.h" using base::FieldTrialList; namespace content_settings { const char* kEnableFieldTrial = PluginsFieldTrial::kEnableFieldTrial; const char* kForceFieldTrial = PluginsFieldTrial::kForceFieldTrial; class PluginsFieldTrialTest : public testing::Test { public: PluginsFieldTrialTest() : field_trial_list_(new base::MockEntropyProvider) {} private: base::FieldTrialList field_trial_list_; DISALLOW_COPY_AND_ASSIGN(PluginsFieldTrialTest); }; TEST_F(PluginsFieldTrialTest, DisabledByDefault) { base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); ASSERT_FALSE(cl->HasSwitch(plugins::switches::kDisablePluginPowerSaver)); ASSERT_FALSE(cl->HasSwitch(plugins::switches::kEnablePluginPowerSaver)); ASSERT_FALSE(base::FieldTrialList::TrialExists(kEnableFieldTrial)); ASSERT_FALSE(base::FieldTrialList::TrialExists(kForceFieldTrial)); EXPECT_FALSE(PluginsFieldTrial::IsPluginPowerSaverEnabled()); } TEST_F(PluginsFieldTrialTest, EnabledByFieldTrial) { ASSERT_TRUE(FieldTrialList::CreateFieldTrial(kForceFieldTrial, "Dogfood")); EXPECT_TRUE(PluginsFieldTrial::IsPluginPowerSaverEnabled()); } TEST_F(PluginsFieldTrialTest, DisabledByFieldTrial) { ASSERT_TRUE(FieldTrialList::CreateFieldTrial(kEnableFieldTrial, "Disabled")); EXPECT_FALSE(PluginsFieldTrial::IsPluginPowerSaverEnabled()); } TEST_F(PluginsFieldTrialTest, EnabledBySwitch) { base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); cl->AppendSwitch(plugins::switches::kEnablePluginPowerSaver); EXPECT_TRUE(PluginsFieldTrial::IsPluginPowerSaverEnabled()); } TEST_F(PluginsFieldTrialTest, DisabledBySwitch) { base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); cl->AppendSwitch(plugins::switches::kDisablePluginPowerSaver); EXPECT_FALSE(PluginsFieldTrial::IsPluginPowerSaverEnabled()); } TEST_F(PluginsFieldTrialTest, SwitchOverridesFieldTrial1) { ASSERT_TRUE(FieldTrialList::CreateFieldTrial(kForceFieldTrial, "Disabled")); base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); cl->AppendSwitch(plugins::switches::kEnablePluginPowerSaver); EXPECT_TRUE(PluginsFieldTrial::IsPluginPowerSaverEnabled()); } TEST_F(PluginsFieldTrialTest, SwitchOverridesFieldTrial2) { ASSERT_TRUE(FieldTrialList::CreateFieldTrial(kEnableFieldTrial, "Enabled")); base::CommandLine* cl = base::CommandLine::ForCurrentProcess(); cl->AppendSwitch(plugins::switches::kDisablePluginPowerSaver); EXPECT_FALSE(PluginsFieldTrial::IsPluginPowerSaverEnabled()); } // Disabled on iOS due to flakiness. https://crbug.com/523462 #if defined(OS_IOS) #define MAYBE_NoPrefLeftBehind DISABLED_NoPrefLeftBehind #else #define MAYBE_NoPrefLeftBehind NoPrefLeftBehind #endif TEST_F(PluginsFieldTrialTest, MAYBE_NoPrefLeftBehind) { ASSERT_TRUE(FieldTrialList::CreateFieldTrial(kEnableFieldTrial, "Enabled")); user_prefs::TestingPrefServiceSyncable prefs; { DefaultProvider::RegisterProfilePrefs(prefs.registry()); DefaultProvider default_provider(&prefs, false); } const std::string& default_plugin_setting_pref_name = WebsiteSettingsRegistry::GetInstance() ->Get(CONTENT_SETTINGS_TYPE_PLUGINS) ->default_value_pref_name(); EXPECT_EQ(CONTENT_SETTING_DETECT_IMPORTANT_CONTENT, prefs.GetInteger(default_plugin_setting_pref_name)); EXPECT_FALSE(prefs.HasPrefPath(default_plugin_setting_pref_name)); } } // namespace content_settings
Disable PluginsFieldTrialTest.NoPrefLeftBehind on iOS
Disable PluginsFieldTrialTest.NoPrefLeftBehind on iOS The test is very flaky on iOS bots. [email protected] NOPRESUBMIT=true NOTREECHECKS=true NOTRY=true BUG=523462 Review URL: https://codereview.chromium.org/1308953002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#344856}
C++
bsd-3-clause
ltilve/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,CapOM/ChromiumGStreamerBackend,ltilve/ChromiumGStreamerBackend
5c54030dd456d8e43740cd732917a0624b3c7ced
domains/integrator_chains/dynamaestro/examples/standalone/genproblem.cpp
domains/integrator_chains/dynamaestro/examples/standalone/genproblem.cpp
#include <iostream> #include <cstdlib> #include <Eigen/Dense> #include "problem.h" int main() { Eigen::Vector2i numdim_output_bounds( 2, 2 ); Eigen::Vector2i num_integrators_bounds( 2, 2 ); Eigen::Vector4d Y_max; Y_max << 0, 10, 0, 10; Eigen::Vector4d U_max; U_max << -1, 1, -1, 1; Eigen::Vector2d period_bounds( 0.05, 0.1 ); srand(time(0)); Problem *prob = Problem::random( numdim_output_bounds, num_integrators_bounds, Y_max, U_max, 2, 1, period_bounds ); std::cout << *prob << std::endl; prob->to_formula( std::cerr ); std::cerr << std::endl; delete prob; return 0; }
#include <iostream> #include <cstdlib> #include <Eigen/Dense> #include "problem.h" int main() { Eigen::Vector2i numdim_output_bounds( 2, 2 ); Eigen::Vector2i num_integrators_bounds( 2, 2 ); Eigen::Vector4d Y_box; Y_box << -1, 10, -2, 10; Eigen::Vector4d U_box; U_box << -1, 1, -1, 1; Eigen::Vector2d period_bounds( 0.05, 0.1 ); Eigen::Vector2i number_goals_bounds( 1, 2 ); Eigen::Vector2i number_obstacles_bounds( 0, 1 ); srand(time(0)); Problem *prob = Problem::random( numdim_output_bounds, num_integrators_bounds, Y_box, U_box, number_goals_bounds, number_obstacles_bounds, period_bounds ); std::cout << *prob << std::endl; prob->to_formula( std::cerr ); std::cerr << std::endl; delete prob; return 0; }
Update genproblem for current Problem::random()
EXAMPLE: Update genproblem for current Problem::random() The output can be plotted as before, e.g., ./genproblem | ../../analysis/plotp.py -
C++
bsd-3-clause
fmrchallenge/fmrbenchmark,fmrchallenge/fmrbenchmark,fmrchallenge/fmrbenchmark
88f25328e09d49f122ec9a163a9cb0395f3b9c9d
content/child/runtime_features.cc
content/child/runtime_features.cc
// Copyright 2013 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 "content/child/runtime_features.h" #include "base/command_line.h" #include "base/metrics/field_trial.h" #include "content/common/content_switches_internal.h" #include "content/public/common/content_switches.h" #include "third_party/WebKit/public/web/WebRuntimeFeatures.h" #include "ui/native_theme/native_theme_switches.h" #if defined(OS_ANDROID) #include <cpu-features.h> #include "base/android/build_info.h" #include "base/metrics/field_trial.h" #include "media/base/android/media_codec_bridge.h" #elif defined(OS_WIN) #include "base/win/windows_version.h" #endif using blink::WebRuntimeFeatures; namespace content { static void SetRuntimeFeatureDefaultsForPlatform() { #if defined(OS_ANDROID) // MSE/EME implementation needs Android MediaCodec API. if (!media::MediaCodecBridge::IsAvailable()) { WebRuntimeFeatures::enableMediaSource(false); WebRuntimeFeatures::enablePrefixedEncryptedMedia(false); WebRuntimeFeatures::enableEncryptedMedia(false); } // WebAudio is enabled by default but only when the MediaCodec API // is available. AndroidCpuFamily cpu_family = android_getCpuFamily(); WebRuntimeFeatures::enableWebAudio( media::MediaCodecBridge::IsAvailable() && ((cpu_family == ANDROID_CPU_FAMILY_ARM) || (cpu_family == ANDROID_CPU_FAMILY_ARM64) || (cpu_family == ANDROID_CPU_FAMILY_X86) || (cpu_family == ANDROID_CPU_FAMILY_MIPS))); // Android does not yet support the Web Notification API. crbug.com/115320 WebRuntimeFeatures::enableNotifications(false); // Android does not yet support SharedWorker. crbug.com/154571 WebRuntimeFeatures::enableSharedWorker(false); // Android does not yet support NavigatorContentUtils. WebRuntimeFeatures::enableNavigatorContentUtils(false); WebRuntimeFeatures::enableTouchIconLoading(true); WebRuntimeFeatures::enableOrientationEvent(true); WebRuntimeFeatures::enableFastMobileScrolling(true); WebRuntimeFeatures::enableMediaCapture(true); WebRuntimeFeatures::enableCompositedSelectionUpdate(true); // If navigation transitions gets activated via field trial, enable it in // blink. We don't set this to false in case the user has manually enabled // the feature via experimental web platform features. if (base::FieldTrialList::FindFullName("NavigationTransitions") == "Enabled") WebRuntimeFeatures::enableNavigationTransitions(true); #else WebRuntimeFeatures::enableNavigatorContentUtils(true); #endif // defined(OS_ANDROID) #if !(defined OS_ANDROID || defined OS_CHROMEOS || defined OS_IOS) // Only Android, ChromeOS, and IOS support NetInfo right now. WebRuntimeFeatures::enableNetworkInformation(false); #endif #if defined(OS_WIN) // Screen Orientation API is currently broken on Windows 8 Metro mode and // until we can find how to disable it only for Blink instances running in a // renderer process in Metro, we need to disable the API altogether for Win8. // See http://crbug.com/400846 if (base::win::OSInfo::GetInstance()->version() >= base::win::VERSION_WIN8) WebRuntimeFeatures::enableScreenOrientation(false); #endif // OS_WIN } void SetRuntimeFeaturesDefaultsAndUpdateFromArgs( const base::CommandLine& command_line) { if (command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures)) WebRuntimeFeatures::enableExperimentalFeatures(true); SetRuntimeFeatureDefaultsForPlatform(); if (command_line.HasSwitch(switches::kDisableDatabases)) WebRuntimeFeatures::enableDatabase(false); if (command_line.HasSwitch(switches::kDisableApplicationCache)) WebRuntimeFeatures::enableApplicationCache(false); if (command_line.HasSwitch(switches::kDisableBlinkScheduler)) WebRuntimeFeatures::enableBlinkScheduler(false); if (command_line.HasSwitch(switches::kDisableDesktopNotifications)) WebRuntimeFeatures::enableNotifications(false); if (command_line.HasSwitch(switches::kDisableLocalStorage)) WebRuntimeFeatures::enableLocalStorage(false); if (command_line.HasSwitch(switches::kDisableSessionStorage)) WebRuntimeFeatures::enableSessionStorage(false); if (command_line.HasSwitch(switches::kDisableMediaSource)) WebRuntimeFeatures::enableMediaSource(false); if (command_line.HasSwitch(switches::kDisableSharedWorkers)) WebRuntimeFeatures::enableSharedWorker(false); #if defined(OS_ANDROID) if (command_line.HasSwitch(switches::kDisableWebRTC)) WebRuntimeFeatures::enablePeerConnection(false); if (!command_line.HasSwitch(switches::kEnableSpeechRecognition)) WebRuntimeFeatures::enableScriptedSpeech(false); // WebAudio is enabled by default on ARM and X86, if the MediaCodec // API is available. WebRuntimeFeatures::enableWebAudio( !command_line.HasSwitch(switches::kDisableWebAudio) && media::MediaCodecBridge::IsAvailable()); #else if (command_line.HasSwitch(switches::kDisableWebAudio)) WebRuntimeFeatures::enableWebAudio(false); #endif if (command_line.HasSwitch(switches::kEnableEncryptedMedia)) WebRuntimeFeatures::enableEncryptedMedia(true); if (command_line.HasSwitch(switches::kDisablePrefixedEncryptedMedia)) WebRuntimeFeatures::enablePrefixedEncryptedMedia(false); if (command_line.HasSwitch(switches::kEnableWebMIDI)) WebRuntimeFeatures::enableWebMIDI(true); if (command_line.HasSwitch(switches::kDisableFileSystem)) WebRuntimeFeatures::enableFileSystem(false); if (command_line.HasSwitch(switches::kEnableExperimentalCanvasFeatures)) WebRuntimeFeatures::enableExperimentalCanvasFeatures(true); if (command_line.HasSwitch(switches::kEnableAcceleratedJpegDecoding)) WebRuntimeFeatures::enableDecodeToYUV(true); if (command_line.HasSwitch(switches::kDisableDisplayList2dCanvas)) { WebRuntimeFeatures::enableDisplayList2dCanvas(false); } else if (command_line.HasSwitch(switches::kEnableDisplayList2dCanvas)) { WebRuntimeFeatures::enableDisplayList2dCanvas(true); } else { WebRuntimeFeatures::enableDisplayList2dCanvas( base::FieldTrialList::FindFullName("DisplayList2dCanvas") == "Enabled" ); } if (command_line.HasSwitch(switches::kEnableWebGLDraftExtensions)) WebRuntimeFeatures::enableWebGLDraftExtensions(true); if (command_line.HasSwitch(switches::kEnableWebGLImageChromium)) WebRuntimeFeatures::enableWebGLImageChromium(true); if (command_line.HasSwitch(switches::kEnableOverlayFullscreenVideo)) WebRuntimeFeatures::enableOverlayFullscreenVideo(true); if (ui::IsOverlayScrollbarEnabled()) WebRuntimeFeatures::enableOverlayScrollbars(true); if (command_line.HasSwitch(switches::kEnableBleedingEdgeRenderingFastPaths)) WebRuntimeFeatures::enableBleedingEdgeFastPaths(true); if (command_line.HasSwitch(switches::kEnablePreciseMemoryInfo)) WebRuntimeFeatures::enablePreciseMemoryInfo(true); if (command_line.HasSwitch(switches::kEnableLayerSquashing)) WebRuntimeFeatures::enableLayerSquashing(true); if (command_line.HasSwitch(switches::kEnableNetworkInformation) || command_line.HasSwitch( switches::kEnableExperimentalWebPlatformFeatures)) { WebRuntimeFeatures::enableNetworkInformation(true); } if (command_line.HasSwitch(switches::kEnableCredentialManagerAPI)) WebRuntimeFeatures::enableCredentialManagerAPI(true); } } // namespace content
// Copyright 2013 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 "content/child/runtime_features.h" #include "base/command_line.h" #include "base/metrics/field_trial.h" #include "content/common/content_switches_internal.h" #include "content/public/common/content_switches.h" #include "third_party/WebKit/public/web/WebRuntimeFeatures.h" #include "ui/native_theme/native_theme_switches.h" #if defined(OS_ANDROID) #include <cpu-features.h> #include "base/android/build_info.h" #include "base/metrics/field_trial.h" #include "media/base/android/media_codec_bridge.h" #elif defined(OS_WIN) #include "base/win/windows_version.h" #endif using blink::WebRuntimeFeatures; namespace content { static void SetRuntimeFeatureDefaultsForPlatform() { #if defined(OS_ANDROID) // MSE/EME implementation needs Android MediaCodec API. if (!media::MediaCodecBridge::IsAvailable()) { WebRuntimeFeatures::enableMediaSource(false); WebRuntimeFeatures::enablePrefixedEncryptedMedia(false); WebRuntimeFeatures::enableEncryptedMedia(false); } // WebAudio is enabled by default but only when the MediaCodec API // is available. AndroidCpuFamily cpu_family = android_getCpuFamily(); WebRuntimeFeatures::enableWebAudio( media::MediaCodecBridge::IsAvailable() && ((cpu_family == ANDROID_CPU_FAMILY_ARM) || (cpu_family == ANDROID_CPU_FAMILY_ARM64) || (cpu_family == ANDROID_CPU_FAMILY_X86) || (cpu_family == ANDROID_CPU_FAMILY_MIPS))); // Android does not have support for PagePopup WebRuntimeFeatures::enablePagePopup(false); // Android does not yet support the Web Notification API. crbug.com/115320 WebRuntimeFeatures::enableNotifications(false); // Android does not yet support SharedWorker. crbug.com/154571 WebRuntimeFeatures::enableSharedWorker(false); // Android does not yet support NavigatorContentUtils. WebRuntimeFeatures::enableNavigatorContentUtils(false); WebRuntimeFeatures::enableTouchIconLoading(true); WebRuntimeFeatures::enableOrientationEvent(true); WebRuntimeFeatures::enableFastMobileScrolling(true); WebRuntimeFeatures::enableMediaCapture(true); WebRuntimeFeatures::enableCompositedSelectionUpdate(true); // If navigation transitions gets activated via field trial, enable it in // blink. We don't set this to false in case the user has manually enabled // the feature via experimental web platform features. if (base::FieldTrialList::FindFullName("NavigationTransitions") == "Enabled") WebRuntimeFeatures::enableNavigationTransitions(true); #else WebRuntimeFeatures::enableNavigatorContentUtils(true); #endif // defined(OS_ANDROID) #if !(defined OS_ANDROID || defined OS_CHROMEOS || defined OS_IOS) // Only Android, ChromeOS, and IOS support NetInfo right now. WebRuntimeFeatures::enableNetworkInformation(false); #endif #if defined(OS_WIN) // Screen Orientation API is currently broken on Windows 8 Metro mode and // until we can find how to disable it only for Blink instances running in a // renderer process in Metro, we need to disable the API altogether for Win8. // See http://crbug.com/400846 if (base::win::OSInfo::GetInstance()->version() >= base::win::VERSION_WIN8) WebRuntimeFeatures::enableScreenOrientation(false); #endif // OS_WIN } void SetRuntimeFeaturesDefaultsAndUpdateFromArgs( const base::CommandLine& command_line) { if (command_line.HasSwitch(switches::kEnableExperimentalWebPlatformFeatures)) WebRuntimeFeatures::enableExperimentalFeatures(true); SetRuntimeFeatureDefaultsForPlatform(); if (command_line.HasSwitch(switches::kDisableDatabases)) WebRuntimeFeatures::enableDatabase(false); if (command_line.HasSwitch(switches::kDisableApplicationCache)) WebRuntimeFeatures::enableApplicationCache(false); if (command_line.HasSwitch(switches::kDisableBlinkScheduler)) WebRuntimeFeatures::enableBlinkScheduler(false); if (command_line.HasSwitch(switches::kDisableDesktopNotifications)) WebRuntimeFeatures::enableNotifications(false); if (command_line.HasSwitch(switches::kDisableLocalStorage)) WebRuntimeFeatures::enableLocalStorage(false); if (command_line.HasSwitch(switches::kDisableSessionStorage)) WebRuntimeFeatures::enableSessionStorage(false); if (command_line.HasSwitch(switches::kDisableMediaSource)) WebRuntimeFeatures::enableMediaSource(false); if (command_line.HasSwitch(switches::kDisableSharedWorkers)) WebRuntimeFeatures::enableSharedWorker(false); #if defined(OS_ANDROID) if (command_line.HasSwitch(switches::kDisableWebRTC)) WebRuntimeFeatures::enablePeerConnection(false); if (!command_line.HasSwitch(switches::kEnableSpeechRecognition)) WebRuntimeFeatures::enableScriptedSpeech(false); // WebAudio is enabled by default on ARM and X86, if the MediaCodec // API is available. WebRuntimeFeatures::enableWebAudio( !command_line.HasSwitch(switches::kDisableWebAudio) && media::MediaCodecBridge::IsAvailable()); #else if (command_line.HasSwitch(switches::kDisableWebAudio)) WebRuntimeFeatures::enableWebAudio(false); #endif if (command_line.HasSwitch(switches::kEnableEncryptedMedia)) WebRuntimeFeatures::enableEncryptedMedia(true); if (command_line.HasSwitch(switches::kDisablePrefixedEncryptedMedia)) WebRuntimeFeatures::enablePrefixedEncryptedMedia(false); if (command_line.HasSwitch(switches::kEnableWebMIDI)) WebRuntimeFeatures::enableWebMIDI(true); if (command_line.HasSwitch(switches::kDisableFileSystem)) WebRuntimeFeatures::enableFileSystem(false); if (command_line.HasSwitch(switches::kEnableExperimentalCanvasFeatures)) WebRuntimeFeatures::enableExperimentalCanvasFeatures(true); if (command_line.HasSwitch(switches::kEnableAcceleratedJpegDecoding)) WebRuntimeFeatures::enableDecodeToYUV(true); if (command_line.HasSwitch(switches::kDisableDisplayList2dCanvas)) { WebRuntimeFeatures::enableDisplayList2dCanvas(false); } else if (command_line.HasSwitch(switches::kEnableDisplayList2dCanvas)) { WebRuntimeFeatures::enableDisplayList2dCanvas(true); } else { WebRuntimeFeatures::enableDisplayList2dCanvas( base::FieldTrialList::FindFullName("DisplayList2dCanvas") == "Enabled" ); } if (command_line.HasSwitch(switches::kEnableWebGLDraftExtensions)) WebRuntimeFeatures::enableWebGLDraftExtensions(true); if (command_line.HasSwitch(switches::kEnableWebGLImageChromium)) WebRuntimeFeatures::enableWebGLImageChromium(true); if (command_line.HasSwitch(switches::kEnableOverlayFullscreenVideo)) WebRuntimeFeatures::enableOverlayFullscreenVideo(true); if (ui::IsOverlayScrollbarEnabled()) WebRuntimeFeatures::enableOverlayScrollbars(true); if (command_line.HasSwitch(switches::kEnableBleedingEdgeRenderingFastPaths)) WebRuntimeFeatures::enableBleedingEdgeFastPaths(true); if (command_line.HasSwitch(switches::kEnablePreciseMemoryInfo)) WebRuntimeFeatures::enablePreciseMemoryInfo(true); if (command_line.HasSwitch(switches::kEnableLayerSquashing)) WebRuntimeFeatures::enableLayerSquashing(true); if (command_line.HasSwitch(switches::kEnableNetworkInformation) || command_line.HasSwitch( switches::kEnableExperimentalWebPlatformFeatures)) { WebRuntimeFeatures::enableNetworkInformation(true); } if (command_line.HasSwitch(switches::kEnableCredentialManagerAPI)) WebRuntimeFeatures::enableCredentialManagerAPI(true); } } // namespace content
Revert of Remove PagePopup runtime flag (status=stable) for chromium (patchset #2 id:20001 of https://codereview.chromium.org/586053003/)
Revert of Remove PagePopup runtime flag (status=stable) for chromium (patchset #2 id:20001 of https://codereview.chromium.org/586053003/) Reason for revert: Broke <input type=color> UI on Android. Original issue's description: > Remove PagePopup runtime flag (status=stable) for chromium > > BUG=402536 > > Committed: https://crrev.com/a0a8313cd7d7ae41ebd07c5fcba0c8659613fb87 > Cr-Commit-Position: refs/heads/master@{#298665} [email protected],[email protected] NOTREECHECKS=true NOTRY=true BUG=402536 Review URL: https://codereview.chromium.org/641563002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#298669}
C++
bsd-3-clause
TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,axinging/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,dednal/chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,M4sse/chromium.src,Chilledheart/chromium,Jonekee/chromium.src,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,Just-D/chromium-1,dushu1203/chromium.src,jaruba/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,markYoungH/chromium.src,chuan9/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,Jonekee/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,Just-D/chromium-1,Chilledheart/chromium,fujunwei/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,dushu1203/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,ltilve/chromium,M4sse/chromium.src,jaruba/chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,dednal/chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,ltilve/chromium,ltilve/chromium,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,dednal/chromium.src,Chilledheart/chromium,markYoungH/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,Just-D/chromium-1,Fireblend/chromium-crosswalk,jaruba/chromium.src,Jonekee/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,axinging/chromium-crosswalk,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,ltilve/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,jaruba/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,markYoungH/chromium.src
bb54f0217aeb5746cf82373b11bd750faf59f392
interfaces/python/pyinterface.cpp
interfaces/python/pyinterface.cpp
#include <Python.h> #include <iostream> #include <minizinc/parser.hh> #include <minizinc/model.hh> #include <minizinc/eval_par.hh> #include <minizinc/typecheck.hh> #include <minizinc/flatten.hh> #include <minizinc/optimize.hh> #include <minizinc/builtins.hh> #include <minizinc/file_utils.hh> #include <minizinc/solvers/gecode/gecode_solverinstance.hh> using namespace MiniZinc; using namespace std; static PyObject* mzn_solve(PyObject *self, PyObject *args) { PyObject* obj; Py_ssize_t pos = 0; PyObject* key; PyObject* value; const char* py_filename; if (!PyArg_ParseTuple(args, "sO", &py_filename, &obj)) return NULL; Py_INCREF(obj); stringstream assignments; while (PyDict_Next(obj, &pos, &key, &value)) { if (PyList_Check(value)) { assignments << PyString_AsString(key) << " = ["; for (Py_ssize_t i=0; i<PyList_Size(value); i++) { PyObject* li = PyList_GetItem(value,i); Py_INCREF(li); if (!PyInt_Check(li)) std::cerr << "not an integer for " << PyString_AsString(key) << " at index " << i << std::endl; else assignments << PyInt_AsLong(li); Py_DECREF(li); if (i < PyList_Size(value)-1) assignments << ","; } assignments << "];\n"; } else { assignments << PyString_AsString(key) << " = "; assignments << PyInt_AsLong(value) << ";\n"; } } vector<string> data; string asn = assignments.str(); if (asn.size() > 0) data.push_back("cmd:/"+assignments.str()); string std_lib_dir; if (char* MZNSTDLIBDIR = getenv("MZN_STDLIB_DIR")) { std_lib_dir = string(MZNSTDLIBDIR); } else { std::cerr << "No MiniZinc library directory MZN_STDLIB_DIR defined.\n"; return NULL; } vector<string> includePaths; includePaths.push_back(std_lib_dir+"/gecode/"); includePaths.push_back(std_lib_dir+"/std/"); GC::init(); if (Model* m = parse(string(py_filename), data, includePaths, false, false, false, std::cerr)) { vector<TypeError> typeErrors; MiniZinc::typecheck(m, typeErrors); if (typeErrors.size() > 0) { for (unsigned int i=0; i<typeErrors.size(); i++) { std::cerr << typeErrors[i].loc() << ":" << std::endl; std::cerr << typeErrors[i].what() << ": " << typeErrors[i].msg() << std::endl; } return NULL; } MiniZinc::registerBuiltins(m); Env env(m); try { FlatteningOptions fopts; flatten(env,fopts); } catch (LocationException& e) { std::cerr << e.what() << ": " << std::endl; env.dumpErrorStack(std::cerr); std::cerr << " " << e.msg() << std::endl; return NULL; } for (unsigned int i=0; i<env.warnings().size(); i++) { std::cerr << "Warning: " << env.warnings()[i]; } optimize(env); oldflatzinc(env); GCLock lock; Options options; GecodeSolverInstance gecode(env,options); gecode.processFlatZinc(); SolverInstance::Status status = gecode.solve(); if (status==SolverInstance::SAT || status==SolverInstance::OPT) { PyObject* solutions = PyList_New(0); PyObject* sol = PyDict_New(); GCLock lock; Model* _m = env.output(); for (unsigned int i=0; i<_m->size(); i++) { if (VarDeclI* vdi = (*_m)[i]->dyn_cast<VarDeclI>()) { if (vdi->e()->type() == Type::parint()) { IntVal iv = eval_int(vdi->e()->e()); PyDict_SetItemString(sol, vdi->e()->id()->str().c_str(), PyInt_FromLong(iv.toInt())); } else if (vdi->e()->type() == Type::parint(1)) { ArrayLit* al = eval_par(vdi->e()->e())->cast<ArrayLit>(); PyObject* pa = PyList_New(al->v().size()); for (unsigned int i=al->v().size(); i--;) PyList_SetItem(pa, i, PyInt_FromLong(eval_int(al->v()[i]).toInt())); PyDict_SetItemString(sol, vdi->e()->id()->str().c_str(), pa); } else if (vdi->e()->type() == Type::parint(2)) { ArrayLit* al = eval_par(vdi->e()->e())->cast<ArrayLit>(); int d1 = al->max(0)-al->min(0)+1; int d2 = al->max(1)-al->min(1)+1; PyObject* pa = PyList_New(d1); for (unsigned int i=0; i < d1; i++) { PyObject* pb = PyList_New(d2); for (unsigned int j=0; j<d2; j++) { PyList_SetItem(pb, j, PyInt_FromLong(eval_int(al->v()[i*d2+j]).toInt())); } PyList_SetItem(pa, i, pb); } PyDict_SetItemString(sol, vdi->e()->id()->str().c_str(), pa); } } } PyList_Append(solutions, sol); Py_DECREF(obj); return Py_BuildValue("iO", status, solutions); } } return NULL; } static PyMethodDef MiniZincMethods[] = { {"solve", mzn_solve, METH_VARARGS, "Solve a MiniZinc model"}, {NULL, NULL, 0, NULL} /* Sentinel */ }; PyMODINIT_FUNC initminizinc(void) { (void) Py_InitModule("minizinc", MiniZincMethods); }
#include <Python.h> #include <iostream> #include <cstdio> #include <minizinc/parser.hh> #include <minizinc/model.hh> #include <minizinc/eval_par.hh> #include <minizinc/typecheck.hh> #include <minizinc/flatten.hh> #include <minizinc/optimize.hh> #include <minizinc/builtins.hh> #include <minizinc/file_utils.hh> #include <minizinc/solvers/gecode/gecode_solverinstance.hh> using namespace MiniZinc; using namespace std; // Error Objects static PyObject* mzn_solve_error; static PyObject* mzn_solve_warning; string minizinc_set(int start, int end) { stringstream ret; ret << start << ".." << end; return ret.str(); } int getList(PyObject* value, vector<Py_ssize_t>& dimensions, vector<PyObject*>& simpleArray, const int layer) { for (Py_ssize_t i=0; i<PyList_Size(value); i++) { if (dimensions.size() <= layer) { dimensions.push_back(PyList_Size(value)); } else if (dimensions[layer]!=PyList_Size(value)) return -1; // Inconsistent size of array (should be the same) PyObject* li = PyList_GetItem(value, i); //Py_INCREF(li); if (PyList_Check(li)) { if (getList(li,dimensions,simpleArray,layer+1)==-1) { //Py_DECREF(li); return -1; } //Py_DECREF(li); } else { simpleArray.push_back(li); } } return 0; } string processArguments(PyObject* value, stringstream& assignments) { if (PyList_Check(value)) { if (PyList_Size(value)==0) return "Objects must contain at least 1 value"; vector<Py_ssize_t> dimensions; vector<PyObject*> simpleArray; if (getList(value, dimensions, simpleArray,0) == -1) { //for (int i=0; i!=simpleArray.size(); i++) // Py_DECREF(simpleArray[i]); return "Inconsistency in size of multidimensional array"; } if (dimensions.size()>6) return "Maximum dimension of a multidimensional array is 6"; assignments << "array" << dimensions.size() << "d("; for (vector<Py_ssize_t>::size_type i=0; i!=dimensions.size(); i++) { assignments << minizinc_set(1,dimensions[i]) << ", "; } assignments << '['; if (PyBool_Check(simpleArray[0])) for (vector<PyObject*>::size_type i=0; i!=simpleArray.size(); i++) { if (i!=0) assignments << ", "; if (PyBool_Check(simpleArray[i])) { if (PyInt_AS_LONG(simpleArray[i])) assignments << "true"; else assignments << "false"; } else return "Inconsistency in values type"; } else if (PyInt_Check(simpleArray[0])) for (vector<PyObject*>::size_type i=0; i!=simpleArray.size(); i++) { if (i!=0) assignments << ", "; if (PyInt_Check(simpleArray[i])) assignments << PyInt_AS_LONG(simpleArray[i]); else return "Inconsistency in values type"; } else if (PyFloat_Check(simpleArray[0])) for (vector<PyObject*>::size_type i=0; i!=simpleArray.size(); i++) { if (i!=0) assignments << ", "; if (PyFloat_Check(simpleArray[i])) assignments << PyFloat_AS_DOUBLE(simpleArray[i]); else return "Inconsistency in values type"; } else if (PyString_Check(simpleArray[0])) for (vector<PyObject*>::size_type i=0; i!=simpleArray.size(); i++) { if (i!=0) assignments << ", "; if (PyString_Check(simpleArray[i])) assignments << "\"" << PyString_AS_STRING(simpleArray[i]) << "\""; else return "Inconsistency in values type"; } else return "Object must be an integer, float, boolean or string"; assignments << "])"; } else { // no error checking currently if (PyBool_Check(value)) { if (PyInt_AS_LONG(value)) assignments << "true"; else assignments << "false"; } else if (PyInt_Check(value)) assignments << PyInt_AS_LONG(value); else if (PyFloat_Check(value)) { assignments << PyFloat_AS_DOUBLE(value); } else if (PyString_Check(value)) assignments << PyString_AS_STRING(value); else { return "Object is neither a list or value"; } } assignments << ";\n"; return ""; } /* void processIntList(VarDecl* vdi, PyObject* sol) { if (dim()==0) { IntVal iv = eval_int(vdi->e()->e()); PyDict_SetItemString(sol, vdi->e()->id()->str().c_str(), PyInt_FromLong(iv.toInt())); } else if (dim()==1) { ArrayLit* al = eval_par(vdi->e()->e())->cast<ArrayLit>(); PyObject* p = PyList_New(al->v.size()); for (unsigned int i=al.v().size(); i--;) PyList_SetItem(pa, i, PyInt_FromLong(eval_int(al->v()[i]).toInt())); PyDict_SetItemString(sol, vdi->e()->id()->str().c_str(), pa); } else { ArrayLit* al = eval_par(vdi->e()->e())->cast<ArrayLit>(); } }*/ /*static PyObject* mzn_set(PyObject *self, PyObject *args) { PyObject* obj; const char* args1 = PyString_AsString(args[0]); const char* args2 = PyString_AsString(args[1]); stringstream assignments; assignments << args1 << ".." << args2; }*/ static PyObject* mzn_solve(PyObject *self, PyObject *args) { PyObject* obj; Py_ssize_t pos = 0; PyObject* key; PyObject* value; const char* py_filename; if (!PyArg_ParseTuple(args, "sO", &py_filename, &obj)) { //std::cerr << "usage: minizinc.solve('filename', {dictionary})\n"; PyErr_SetString(mzn_solve_error, "Parsing error"); return NULL; } //Py_INCREF(obj); stringstream assignments; while (PyDict_Next(obj, &pos, &key, &value)) { //cout << PyString_AsString(key) << " - " << PyInt_AsLong(value) << endl; assignments << PyString_AsString(key) << " = "; string errorLog = processArguments(value,assignments); if (errorLog!="") { PyErr_SetString(mzn_solve_error, errorLog.c_str()); return NULL; } } vector<string> data; string asn = assignments.str(); cout << asn << endl; if (asn.size() > 0) data.push_back("cmd:/"+assignments.str()); string std_lib_dir; if (char* MZNSTDLIBDIR = getenv("MZN_STDLIB_DIR")) { std_lib_dir = string(MZNSTDLIBDIR); } else { PyErr_SetString(mzn_solve_error, "No MiniZinc library directory MZN_STDLIB_DIR defined."); return NULL; } vector<string> includePaths; includePaths.push_back(std_lib_dir+"/gecode/"); includePaths.push_back(std_lib_dir+"/std/"); GC::init(); stringstream errorStream; if (Model* m = parse(string(py_filename), data, includePaths, false, false, false, errorStream)) { vector<TypeError> typeErrors; try { MiniZinc::typecheck(m, typeErrors); } catch (LocationException& e) { stringstream errorLog; errorLog << e.what() << ": " << std::endl; errorLog << " " << e.msg() << std::endl; const std::string& tmp = errorLog.str(); const char* cstr = tmp.c_str(); PyErr_SetString(mzn_solve_error, cstr); return NULL; } if (typeErrors.size() > 0) { stringstream errorLog; for (unsigned int i=0; i<typeErrors.size(); i++) { errorLog << typeErrors[i].loc() << ":" << endl; errorLog << typeErrors[i].what() << ": " << typeErrors[i].msg() << "\n"; } const std::string& tmp = errorLog.str(); const char* cstr = tmp.c_str(); PyErr_SetString(mzn_solve_error, cstr); return NULL; } MiniZinc::registerBuiltins(m); Env env(m); try { FlatteningOptions fopts; flatten(env,fopts); } catch (LocationException& e) { stringstream errorLog; errorLog << e.what() << ": " << std::endl; env.dumpErrorStack(errorLog); errorLog << " " << e.msg() << std::endl; const std::string& tmp = errorLog.str(); const char* cstr = tmp.c_str(); PyErr_SetString(mzn_solve_error, cstr); return NULL; } if (env.warnings().size()!=0) { stringstream warningLog; for (unsigned int i=0; i<env.warnings().size(); i++) { warningLog << "Warning: " << env.warnings()[i]; } const std::string& tmp = warningLog.str(); const char* cstr = tmp.c_str(); PyErr_WarnEx(mzn_solve_warning, cstr, 1); } optimize(env); oldflatzinc(env); GCLock lock; Options options; GecodeSolverInstance gecode(env,options); gecode.processFlatZinc(); SolverInstance::Status status = gecode.solve(); if (status==SolverInstance::SAT || status==SolverInstance::OPT) { PyObject* solutions = PyList_New(0); PyObject* sol = PyDict_New(); //GCLock lock; Model* _m = env.output(); for (unsigned int i=0; i<_m->size(); i++) { if (VarDeclI* vdi = (*_m)[i]->dyn_cast<VarDeclI>()) { if (vdi->e()->type().bt() == Type::BT_BOOL) { if (vdi->e()->type().dim() == 0) { IntVal iv = eval_int(vdi->e()->e()); PyDict_SetItemString(sol, vdi->e()->id()->str().c_str(), PyBool_FromLong(iv.toInt())); } else { ArrayLit* al = eval_par(vdi->e()->e())->cast<ArrayLit>(); int dim = vdi->e()->type().dim(); // Maximum size of each dimension vector<int> dmax; // Current size of each dimension vector<int> d; // p[0] holds the final array, p[1+] builds up p[0] vector<PyObject*> p(dim); for (int i=0; i<dim; i++) { d.push_back(0); Py_ssize_t dtemp = al->max(i) - al->min(i) + 1; dmax.push_back(dtemp); p[i] = PyList_New(dtemp); } int i = dim - 1; // next item to be put onto the final array. int currentPos = 0; do { PyList_SetItem(p[i], d[i], PyBool_FromLong(eval_int(al->v()[currentPos]).toInt())); currentPos++; d[i]++; while (d[i]>=dmax[i] && i>0) { PyList_SetItem(p[i-1],d[i-1],p[i]); d[i]=0; p[i]=PyList_New(dmax[i]); i--; d[i]++; } i = dim - 1; } while (d[0]<dmax[0]); PyDict_SetItemString(sol, vdi->e()->id()->str().c_str(),p[0]); } } else if (vdi->e()->type().bt() == Type::BT_INT) { if (vdi->e()->type().dim() == 0) { //IntVal iv = eval_int(vdi->e()->e()); PyDict_SetItemString(sol, vdi->e()->id()->str().c_str(), PyInt_FromLong(eval_bool(vdi->e()->e()))); } else { ArrayLit* al = eval_par(vdi->e()->e())->cast<ArrayLit>(); int dim = vdi->e()->type().dim(); // Maximum size of each dimension vector<int> dmax; // Current size of each dimension vector<int> d; // p[0] holds the final array, p[1+] builds up p[0] vector<PyObject*> p(dim); for (int i=0; i<dim; i++) { d.push_back(0); Py_ssize_t dtemp = al->max(i) - al->min(i) + 1; dmax.push_back(dtemp); p[i] = PyList_New(dtemp); } int i = dim - 1; // next item to be put onto the final array. int currentPos = 0; do { PyList_SetItem(p[i], d[i], PyInt_FromLong(eval_bool(al->v()[currentPos]))); currentPos++; d[i]++; while (d[i]>=dmax[i] && i>0) { PyList_SetItem(p[i-1],d[i-1],p[i]); d[i]=0; p[i]=PyList_New(dmax[i]); i--; d[i]++; } i = dim - 1; } while (d[0]<dmax[0]); PyDict_SetItemString(sol, vdi->e()->id()->str().c_str(),p[0]); } } else if (vdi->e()->type().bt() == Type::BT_STRING) { if (vdi->e()->type().dim() == 0) { //IntVal iv = eval_int(vdi->e()->e()); string temp(eval_string(vdi->e()->e())); PyDict_SetItemString(sol, vdi->e()->id()->str().c_str(), PyString_FromString(temp.c_str())); } else { ArrayLit* al = eval_par(vdi->e()->e())->cast<ArrayLit>(); int dim = vdi->e()->type().dim(); // Maximum size of each dimension vector<int> dmax; // Current size of each dimension vector<int> d; // p[0] holds the final array, p[1+] builds up p[0] vector<PyObject*> p(dim); for (int i=0; i<dim; i++) { d.push_back(0); Py_ssize_t dtemp = al->max(i) - al->min(i) + 1; dmax.push_back(dtemp); p[i] = PyList_New(dtemp); } int i = dim - 1; // next item to be put onto the final array. int currentPos = 0; do { string temp(eval_string(al->v()[currentPos])); PyList_SetItem(p[i], d[i], PyString_FromString(temp.c_str())); currentPos++; d[i]++; while (d[i]>=dmax[i] && i>0) { PyList_SetItem(p[i-1],d[i-1],p[i]); d[i]=0; p[i]=PyList_New(dmax[i]); i--; d[i]++; } i = dim - 1; } while (d[0]<dmax[0]); PyDict_SetItemString(sol, vdi->e()->id()->str().c_str(),p[0]); } } } } PyList_Append(solutions, sol); //Py_DECREF(obj); return Py_BuildValue("iO", status, solutions); } else { //Py_DECREF(obj); PyErr_SetString(mzn_solve_error,"Unknown status code"); return NULL; } } const std::string& tmp = errorStream.str(); const char* cstr = tmp.c_str(); PyErr_SetString(mzn_solve_error, cstr); return NULL; } static PyMethodDef MiniZincMethods[] = { {"solve", mzn_solve, METH_VARARGS, "Solve a MiniZinc model"}, //{"mzn_set", mzn_set, METH_VARARGS, "Create a MiniZinc set: args[1]..args[2]"}, {NULL, NULL, 0, NULL} /* Sentinel */ }; PyMODINIT_FUNC initminizinc(void) { PyObject* model = Py_InitModule("minizinc", MiniZincMethods); if (model == NULL) return; //Error Handling mzn_solve_error = PyErr_NewException("mzn_solve.error", NULL, NULL); if (mzn_solve_error == NULL) return; Py_XINCREF(mzn_solve_error); PyModule_AddObject(model,"error",mzn_solve_error); mzn_solve_warning = PyErr_NewException("mzn_solve.warning", NULL, NULL); if (mzn_solve_error == NULL) return; Py_XINCREF(mzn_solve_error); PyModule_AddObject(model,"warning",mzn_solve_warning); }
add multidimensional array output (float not working yet)
add multidimensional array output (float not working yet)
C++
mpl-2.0
nathanielbaxter/libminizinc,nathanielbaxter/libminizinc,nathanielbaxter/libminizinc,jjdekker/libminizinc,jjdekker/libminizinc,nathanielbaxter/libminizinc,jjdekker/libminizinc,jjdekker/libminizinc
cf97eb5b056e14db387a92f0394f59d208af287b
src/clustering/administration/persist/raft_storage_interface.cc
src/clustering/administration/persist/raft_storage_interface.cc
// Copyright 2010-2015 RethinkDB, all rights reserved. #include "clustering/administration/persist/raft_storage_interface.hpp" #include "clustering/administration/persist/file_keys.hpp" /* The raft state is stored as follows: - There is a single `table_raft_stored_header_t` which stores `current_term` and `voted_for`. - There is a single `table_raft_stored_snapshot_t` which stores `snapshot_state`, `snapshot_config`, `log.prev_index`, and `log.prev_term`. - There are zero or more `raft_log_entry_t`s, which use the log index as part of the B-tree key. */ class table_raft_stored_header_t { public: raft_term_t current_term; raft_member_id_t voted_for; }; RDB_IMPL_SERIALIZABLE_2_SINCE_v2_1(table_raft_stored_header_t, current_term, voted_for); class table_raft_stored_snapshot_t { public: table_raft_state_t snapshot_state; raft_complex_config_t snapshot_config; raft_log_index_t log_prev_index; raft_term_t log_prev_term; }; RDB_IMPL_SERIALIZABLE_4_SINCE_v2_1(table_raft_stored_snapshot_t, snapshot_state, snapshot_config, log_prev_index, log_prev_term); raft_log_index_t str_to_log_index(const std::string &str) { guarantee(str.size() == 16); raft_log_index_t index = 0; for (size_t i = 0; i < 16; ++i) { int val; if (str[i] >= '0' && str[i] <= '9') { val = str[i] - '0'; } else if (str[i] >= 'a' && str[i] <= 'f') { val = 10 + (str[i] - 'a'); } else { crash("bad character in str_to_log_index()"); } index += val << ((15 - i) * 4); } return index; } std::string log_index_to_str(raft_log_index_t log_index) { std::string str; str.reserve(16); for (size_t i = 0; i < 16; ++i) { int val = log_index >> ((15 - i) * 4); str.push_back("0123456789abcdef"[val]); } return str; } table_raft_storage_interface_t::table_raft_storage_interface_t( metadata_file_t *_file, metadata_file_t::read_txn_t *txn, const namespace_id_t &_table_id, signal_t *interruptor) : file(_file), table_id(_table_id) { table_raft_stored_header_t header = txn->read( mdprefix_table_raft_header().suffix(uuid_to_str(table_id)), interruptor); state.current_term = header.current_term; state.voted_for = header.voted_for; table_raft_stored_snapshot_t snapshot = txn->read( mdprefix_table_raft_snapshot().suffix(uuid_to_str(table_id)), interruptor); state.snapshot_state = std::move(snapshot.snapshot_state); state.snapshot_config = std::move(snapshot.snapshot_config); state.log.prev_index = snapshot.log_prev_index; state.log.prev_term = snapshot.log_prev_term; txn->read_many<raft_log_entry_t<table_raft_state_t> >( mdprefix_table_raft_log().suffix(uuid_to_str(table_id) + "/"), [&](const std::string &index_str, const raft_log_entry_t<table_raft_state_t> &entry) { guarantee(str_to_log_index(index_str) == state.log.get_latest_index() + 1); state.log.append(entry); }, interruptor); } table_raft_storage_interface_t::table_raft_storage_interface_t( metadata_file_t *_file, metadata_file_t::write_txn_t *txn, const namespace_id_t &_table_id, const raft_persistent_state_t<table_raft_state_t> &_state, signal_t *interruptor) : file(_file), table_id(_table_id), state(_state) { table_raft_stored_header_t header; header.current_term = state.current_term; header.voted_for = state.voted_for; txn->write( mdprefix_table_raft_header().suffix(uuid_to_str(table_id)), header, interruptor); /* To avoid expensive copies of `state`, we move `state` into the snapshot and then back out after we're done */ table_raft_stored_snapshot_t snapshot; snapshot.snapshot_state = std::move(state.snapshot_state); snapshot.snapshot_config = std::move(state.snapshot_config); snapshot.log_prev_index = state.log.prev_index; snapshot.log_prev_term = state.log.prev_term; txn->write( mdprefix_table_raft_snapshot().suffix(uuid_to_str(table_id)), snapshot, interruptor); state.snapshot_state = std::move(snapshot.snapshot_state); state.snapshot_config = std::move(snapshot.snapshot_config); for (raft_log_index_t i = state.log.prev_index + 1; i <= state.log.get_latest_index(); ++i) { txn->write( mdprefix_table_raft_log().suffix( uuid_to_str(table_id) + "/" + log_index_to_str(i)), state.log.get_entry_ref(i), interruptor); } } void table_raft_storage_interface_t::erase( metadata_file_t::write_txn_t *txn, const namespace_id_t &table_id, signal_t *interruptor) { txn->erase( mdprefix_table_raft_header().suffix(uuid_to_str(table_id)), interruptor); txn->erase( mdprefix_table_raft_snapshot().suffix(uuid_to_str(table_id)), interruptor); std::vector<std::string> log_keys; txn->read_many<raft_log_entry_t<table_raft_state_t> >( mdprefix_table_raft_log().suffix(uuid_to_str(table_id) + "/"), [&](const std::string &index_str, const raft_log_entry_t<table_raft_state_t> &) { log_keys.push_back(index_str); }, interruptor); for (const std::string &key : log_keys) { txn->erase( mdprefix_table_raft_log().suffix(uuid_to_str(table_id) + "/" + key), interruptor); } } const raft_persistent_state_t<table_raft_state_t> * table_raft_storage_interface_t::get() { return &state; } void table_raft_storage_interface_t::write_current_term_and_voted_for( raft_term_t current_term, raft_member_id_t voted_for) { cond_t non_interruptor; metadata_file_t::write_txn_t txn(file, &non_interruptor); table_raft_stored_header_t header; header.current_term = state.current_term = current_term; header.voted_for = state.voted_for = voted_for; txn.write( mdprefix_table_raft_header().suffix(uuid_to_str(table_id)), header, &non_interruptor); } void table_raft_storage_interface_t::write_log_replace_tail( const raft_log_t<table_raft_state_t> &source, raft_log_index_t first_replaced) { cond_t non_interruptor; metadata_file_t::write_txn_t txn(file, &non_interruptor); guarantee(first_replaced > state.log.prev_index); guarantee(first_replaced <= state.log.get_latest_index() + 1); for (raft_log_index_t i = first_replaced; i < std::max(state.log.get_latest_index(), source.get_latest_index()); ++i) { metadata_file_t::key_t<raft_log_entry_t<table_raft_state_t> > key = mdprefix_table_raft_log().suffix( uuid_to_str(table_id) + "/" + log_index_to_str(i)); if (i <= source.get_latest_index()) { txn.write(key, source.get_entry_ref(i), &non_interruptor); } else { txn.erase(key, &non_interruptor); } } if (first_replaced != state.log.get_latest_index() + 1) { state.log.delete_entries_from(first_replaced); } for (raft_log_index_t i = first_replaced; i <= source.get_latest_index(); ++i) { state.log.append(source.get_entry_ref(i)); } } void table_raft_storage_interface_t::write_log_append_one( const raft_log_entry_t<table_raft_state_t> &entry) { cond_t non_interruptor; metadata_file_t::write_txn_t txn(file, &non_interruptor); raft_log_index_t index = state.log.get_latest_index() + 1; txn.write( mdprefix_table_raft_log().suffix( uuid_to_str(table_id) + "/" + log_index_to_str(index)), entry, &non_interruptor); state.log.append(entry); } void table_raft_storage_interface_t::write_snapshot( const table_raft_state_t &snapshot_state, const raft_complex_config_t &snapshot_config, bool clear_log, raft_log_index_t log_prev_index, raft_term_t log_prev_term) { cond_t non_interruptor; metadata_file_t::write_txn_t txn(file, &non_interruptor); table_raft_stored_snapshot_t snapshot; snapshot.snapshot_state = snapshot_state; snapshot.snapshot_config = snapshot_config; snapshot.log_prev_index = log_prev_index; snapshot.log_prev_term = log_prev_term; txn.write( mdprefix_table_raft_snapshot().suffix(uuid_to_str(table_id)), snapshot, &non_interruptor); for (raft_log_index_t i = state.log.prev_index + 1; i <= (clear_log ? state.log.get_latest_index() : log_prev_index); ++i) { txn.erase( mdprefix_table_raft_log().suffix( uuid_to_str(table_id) + "/" + log_index_to_str(i)), &non_interruptor); } state.snapshot_state = std::move(snapshot.snapshot_state); state.snapshot_config = std::move(snapshot.snapshot_config); if (clear_log) { state.log.entries.clear(); state.log.prev_index = log_prev_index; state.log.prev_term = log_prev_term; } else { state.log.delete_entries_to(log_prev_index, log_prev_term); } }
// Copyright 2010-2015 RethinkDB, all rights reserved. #include "clustering/administration/persist/raft_storage_interface.hpp" #include "clustering/administration/persist/file_keys.hpp" /* The raft state is stored as follows: - There is a single `table_raft_stored_header_t` which stores `current_term` and `voted_for`. - There is a single `table_raft_stored_snapshot_t` which stores `snapshot_state`, `snapshot_config`, `log.prev_index`, and `log.prev_term`. - There are zero or more `raft_log_entry_t`s, which use the log index as part of the B-tree key. */ class table_raft_stored_header_t { public: raft_term_t current_term; raft_member_id_t voted_for; }; RDB_IMPL_SERIALIZABLE_2_SINCE_v2_1(table_raft_stored_header_t, current_term, voted_for); class table_raft_stored_snapshot_t { public: table_raft_state_t snapshot_state; raft_complex_config_t snapshot_config; raft_log_index_t log_prev_index; raft_term_t log_prev_term; }; RDB_IMPL_SERIALIZABLE_4_SINCE_v2_1(table_raft_stored_snapshot_t, snapshot_state, snapshot_config, log_prev_index, log_prev_term); raft_log_index_t str_to_log_index(const std::string &str) { guarantee(str.size() == 16); raft_log_index_t index = 0; for (size_t i = 0; i < 16; ++i) { int val; if (str[i] >= '0' && str[i] <= '9') { val = str[i] - '0'; } else if (str[i] >= 'a' && str[i] <= 'f') { val = 10 + (str[i] - 'a'); } else { crash("bad character in str_to_log_index()"); } index += val << ((15 - i) * 4); } return index; } std::string log_index_to_str(raft_log_index_t log_index) { std::string str; str.reserve(16); for (size_t i = 0; i < 16; ++i) { int val = (log_index >> ((15 - i) * 4)) & 0x0f; rassert(val >= 0 && val < 16); str.push_back("0123456789abcdef"[val]); } return str; } table_raft_storage_interface_t::table_raft_storage_interface_t( metadata_file_t *_file, metadata_file_t::read_txn_t *txn, const namespace_id_t &_table_id, signal_t *interruptor) : file(_file), table_id(_table_id) { table_raft_stored_header_t header = txn->read( mdprefix_table_raft_header().suffix(uuid_to_str(table_id)), interruptor); state.current_term = header.current_term; state.voted_for = header.voted_for; table_raft_stored_snapshot_t snapshot = txn->read( mdprefix_table_raft_snapshot().suffix(uuid_to_str(table_id)), interruptor); state.snapshot_state = std::move(snapshot.snapshot_state); state.snapshot_config = std::move(snapshot.snapshot_config); state.log.prev_index = snapshot.log_prev_index; state.log.prev_term = snapshot.log_prev_term; txn->read_many<raft_log_entry_t<table_raft_state_t> >( mdprefix_table_raft_log().suffix(uuid_to_str(table_id) + "/"), [&](const std::string &index_str, const raft_log_entry_t<table_raft_state_t> &entry) { guarantee(str_to_log_index(index_str) == state.log.get_latest_index() + 1, "%" PRIu64 " ('%s') == %" PRIu64, str_to_log_index(index_str), index_str.c_str(), state.log.get_latest_index() + 1); state.log.append(entry); }, interruptor); } table_raft_storage_interface_t::table_raft_storage_interface_t( metadata_file_t *_file, metadata_file_t::write_txn_t *txn, const namespace_id_t &_table_id, const raft_persistent_state_t<table_raft_state_t> &_state, signal_t *interruptor) : file(_file), table_id(_table_id), state(_state) { table_raft_stored_header_t header; header.current_term = state.current_term; header.voted_for = state.voted_for; txn->write( mdprefix_table_raft_header().suffix(uuid_to_str(table_id)), header, interruptor); /* To avoid expensive copies of `state`, we move `state` into the snapshot and then back out after we're done */ table_raft_stored_snapshot_t snapshot; snapshot.snapshot_state = std::move(state.snapshot_state); snapshot.snapshot_config = std::move(state.snapshot_config); snapshot.log_prev_index = state.log.prev_index; snapshot.log_prev_term = state.log.prev_term; txn->write( mdprefix_table_raft_snapshot().suffix(uuid_to_str(table_id)), snapshot, interruptor); state.snapshot_state = std::move(snapshot.snapshot_state); state.snapshot_config = std::move(snapshot.snapshot_config); for (raft_log_index_t i = state.log.prev_index + 1; i <= state.log.get_latest_index(); ++i) { txn->write( mdprefix_table_raft_log().suffix( uuid_to_str(table_id) + "/" + log_index_to_str(i)), state.log.get_entry_ref(i), interruptor); } } void table_raft_storage_interface_t::erase( metadata_file_t::write_txn_t *txn, const namespace_id_t &table_id, signal_t *interruptor) { txn->erase( mdprefix_table_raft_header().suffix(uuid_to_str(table_id)), interruptor); txn->erase( mdprefix_table_raft_snapshot().suffix(uuid_to_str(table_id)), interruptor); std::vector<std::string> log_keys; txn->read_many<raft_log_entry_t<table_raft_state_t> >( mdprefix_table_raft_log().suffix(uuid_to_str(table_id) + "/"), [&](const std::string &index_str, const raft_log_entry_t<table_raft_state_t> &) { log_keys.push_back(index_str); }, interruptor); for (const std::string &key : log_keys) { txn->erase( mdprefix_table_raft_log().suffix(uuid_to_str(table_id) + "/" + key), interruptor); } } const raft_persistent_state_t<table_raft_state_t> * table_raft_storage_interface_t::get() { return &state; } void table_raft_storage_interface_t::write_current_term_and_voted_for( raft_term_t current_term, raft_member_id_t voted_for) { cond_t non_interruptor; metadata_file_t::write_txn_t txn(file, &non_interruptor); table_raft_stored_header_t header; header.current_term = state.current_term = current_term; header.voted_for = state.voted_for = voted_for; txn.write( mdprefix_table_raft_header().suffix(uuid_to_str(table_id)), header, &non_interruptor); } void table_raft_storage_interface_t::write_log_replace_tail( const raft_log_t<table_raft_state_t> &source, raft_log_index_t first_replaced) { cond_t non_interruptor; metadata_file_t::write_txn_t txn(file, &non_interruptor); guarantee(first_replaced > state.log.prev_index); guarantee(first_replaced <= state.log.get_latest_index() + 1); for (raft_log_index_t i = first_replaced; i <= std::max(state.log.get_latest_index(), source.get_latest_index()); ++i) { metadata_file_t::key_t<raft_log_entry_t<table_raft_state_t> > key = mdprefix_table_raft_log().suffix( uuid_to_str(table_id) + "/" + log_index_to_str(i)); if (i <= source.get_latest_index()) { txn.write(key, source.get_entry_ref(i), &non_interruptor); } else { txn.erase(key, &non_interruptor); } } if (first_replaced != state.log.get_latest_index() + 1) { state.log.delete_entries_from(first_replaced); } for (raft_log_index_t i = first_replaced; i <= source.get_latest_index(); ++i) { state.log.append(source.get_entry_ref(i)); } } void table_raft_storage_interface_t::write_log_append_one( const raft_log_entry_t<table_raft_state_t> &entry) { cond_t non_interruptor; metadata_file_t::write_txn_t txn(file, &non_interruptor); raft_log_index_t index = state.log.get_latest_index() + 1; txn.write( mdprefix_table_raft_log().suffix( uuid_to_str(table_id) + "/" + log_index_to_str(index)), entry, &non_interruptor); state.log.append(entry); } void table_raft_storage_interface_t::write_snapshot( const table_raft_state_t &snapshot_state, const raft_complex_config_t &snapshot_config, bool clear_log, raft_log_index_t log_prev_index, raft_term_t log_prev_term) { cond_t non_interruptor; metadata_file_t::write_txn_t txn(file, &non_interruptor); table_raft_stored_snapshot_t snapshot; snapshot.snapshot_state = snapshot_state; snapshot.snapshot_config = snapshot_config; snapshot.log_prev_index = log_prev_index; snapshot.log_prev_term = log_prev_term; txn.write( mdprefix_table_raft_snapshot().suffix(uuid_to_str(table_id)), snapshot, &non_interruptor); for (raft_log_index_t i = state.log.prev_index + 1; i <= (clear_log ? state.log.get_latest_index() : log_prev_index); ++i) { txn.erase( mdprefix_table_raft_log().suffix( uuid_to_str(table_id) + "/" + log_index_to_str(i)), &non_interruptor); } state.snapshot_state = std::move(snapshot.snapshot_state); state.snapshot_config = std::move(snapshot.snapshot_config); if (clear_log) { state.log.entries.clear(); state.log.prev_index = log_prev_index; state.log.prev_term = log_prev_term; } else { state.log.delete_entries_to(log_prev_index, log_prev_term); } }
Fix for #4422, OTS reviewed by @timmaxw.
Fix for #4422, OTS reviewed by @timmaxw.
C++
apache-2.0
yakovenkodenis/rethinkdb,niieani/rethinkdb,robertjpayne/rethinkdb,4talesa/rethinkdb,victorbriz/rethinkdb,sebadiaz/rethinkdb,yaolinz/rethinkdb,yaolinz/rethinkdb,elkingtonmcb/rethinkdb,mquandalle/rethinkdb,elkingtonmcb/rethinkdb,ajose01/rethinkdb,gavioto/rethinkdb,4talesa/rethinkdb,rrampage/rethinkdb,JackieXie168/rethinkdb,ajose01/rethinkdb,gavioto/rethinkdb,mbroadst/rethinkdb,sbusso/rethinkdb,captainpete/rethinkdb,elkingtonmcb/rethinkdb,pap/rethinkdb,pap/rethinkdb,tempbottle/rethinkdb,sbusso/rethinkdb,sontek/rethinkdb,losywee/rethinkdb,gavioto/rethinkdb,greyhwndz/rethinkdb,mcanthony/rethinkdb,lenstr/rethinkdb,KSanthanam/rethinkdb,elkingtonmcb/rethinkdb,yakovenkodenis/rethinkdb,Wilbeibi/rethinkdb,elkingtonmcb/rethinkdb,ayumilong/rethinkdb,Qinusty/rethinkdb,losywee/rethinkdb,yaolinz/rethinkdb,scripni/rethinkdb,wkennington/rethinkdb,grandquista/rethinkdb,matthaywardwebdesign/rethinkdb,eliangidoni/rethinkdb,mcanthony/rethinkdb,catroot/rethinkdb,JackieXie168/rethinkdb,niieani/rethinkdb,mquandalle/rethinkdb,alash3al/rethinkdb,Wilbeibi/rethinkdb,rrampage/rethinkdb,niieani/rethinkdb,bchavez/rethinkdb,RubenKelevra/rethinkdb,mquandalle/rethinkdb,grandquista/rethinkdb,scripni/rethinkdb,Qinusty/rethinkdb,bpradipt/rethinkdb,scripni/rethinkdb,tempbottle/rethinkdb,ajose01/rethinkdb,yakovenkodenis/rethinkdb,4talesa/rethinkdb,RubenKelevra/rethinkdb,wkennington/rethinkdb,jmptrader/rethinkdb,eliangidoni/rethinkdb,mbroadst/rethinkdb,victorbriz/rethinkdb,ajose01/rethinkdb,mquandalle/rethinkdb,KSanthanam/rethinkdb,mcanthony/rethinkdb,sebadiaz/rethinkdb,dparnell/rethinkdb,grandquista/rethinkdb,dparnell/rethinkdb,bpradipt/rethinkdb,mcanthony/rethinkdb,victorbriz/rethinkdb,JackieXie168/rethinkdb,grandquista/rethinkdb,Qinusty/rethinkdb,sontek/rethinkdb,yaolinz/rethinkdb,KSanthanam/rethinkdb,niieani/rethinkdb,robertjpayne/rethinkdb,lenstr/rethinkdb,robertjpayne/rethinkdb,losywee/rethinkdb,losywee/rethinkdb,bchavez/rethinkdb,JackieXie168/rethinkdb,elkingtonmcb/rethinkdb,catroot/rethinkdb,yaolinz/rethinkdb,robertjpayne/rethinkdb,pap/rethinkdb,bpradipt/rethinkdb,alash3al/rethinkdb,Wilbeibi/rethinkdb,Qinusty/rethinkdb,gavioto/rethinkdb,captainpete/rethinkdb,rrampage/rethinkdb,Wilbeibi/rethinkdb,tempbottle/rethinkdb,spblightadv/rethinkdb,grandquista/rethinkdb,rrampage/rethinkdb,jmptrader/rethinkdb,sontek/rethinkdb,captainpete/rethinkdb,JackieXie168/rethinkdb,bpradipt/rethinkdb,Wilbeibi/rethinkdb,mquandalle/rethinkdb,lenstr/rethinkdb,bpradipt/rethinkdb,bchavez/rethinkdb,spblightadv/rethinkdb,captainpete/rethinkdb,niieani/rethinkdb,wkennington/rethinkdb,Qinusty/rethinkdb,mbroadst/rethinkdb,greyhwndz/rethinkdb,losywee/rethinkdb,tempbottle/rethinkdb,Qinusty/rethinkdb,ayumilong/rethinkdb,sebadiaz/rethinkdb,sbusso/rethinkdb,spblightadv/rethinkdb,scripni/rethinkdb,gavioto/rethinkdb,gavioto/rethinkdb,AntouanK/rethinkdb,rrampage/rethinkdb,victorbriz/rethinkdb,mbroadst/rethinkdb,yaolinz/rethinkdb,greyhwndz/rethinkdb,sebadiaz/rethinkdb,jmptrader/rethinkdb,sontek/rethinkdb,bpradipt/rethinkdb,sebadiaz/rethinkdb,matthaywardwebdesign/rethinkdb,scripni/rethinkdb,spblightadv/rethinkdb,greyhwndz/rethinkdb,spblightadv/rethinkdb,mcanthony/rethinkdb,robertjpayne/rethinkdb,RubenKelevra/rethinkdb,JackieXie168/rethinkdb,captainpete/rethinkdb,mquandalle/rethinkdb,ayumilong/rethinkdb,tempbottle/rethinkdb,jmptrader/rethinkdb,AntouanK/rethinkdb,RubenKelevra/rethinkdb,matthaywardwebdesign/rethinkdb,lenstr/rethinkdb,matthaywardwebdesign/rethinkdb,4talesa/rethinkdb,wkennington/rethinkdb,KSanthanam/rethinkdb,matthaywardwebdesign/rethinkdb,catroot/rethinkdb,AntouanK/rethinkdb,RubenKelevra/rethinkdb,wkennington/rethinkdb,mbroadst/rethinkdb,AntouanK/rethinkdb,mbroadst/rethinkdb,sontek/rethinkdb,matthaywardwebdesign/rethinkdb,tempbottle/rethinkdb,eliangidoni/rethinkdb,niieani/rethinkdb,catroot/rethinkdb,sbusso/rethinkdb,4talesa/rethinkdb,sontek/rethinkdb,grandquista/rethinkdb,catroot/rethinkdb,sebadiaz/rethinkdb,greyhwndz/rethinkdb,robertjpayne/rethinkdb,pap/rethinkdb,captainpete/rethinkdb,mbroadst/rethinkdb,yaolinz/rethinkdb,bchavez/rethinkdb,alash3al/rethinkdb,mquandalle/rethinkdb,catroot/rethinkdb,sebadiaz/rethinkdb,yaolinz/rethinkdb,dparnell/rethinkdb,tempbottle/rethinkdb,Wilbeibi/rethinkdb,bchavez/rethinkdb,eliangidoni/rethinkdb,KSanthanam/rethinkdb,scripni/rethinkdb,bpradipt/rethinkdb,Qinusty/rethinkdb,jmptrader/rethinkdb,AntouanK/rethinkdb,AntouanK/rethinkdb,AntouanK/rethinkdb,eliangidoni/rethinkdb,alash3al/rethinkdb,alash3al/rethinkdb,sbusso/rethinkdb,victorbriz/rethinkdb,sbusso/rethinkdb,losywee/rethinkdb,yakovenkodenis/rethinkdb,4talesa/rethinkdb,niieani/rethinkdb,catroot/rethinkdb,JackieXie168/rethinkdb,dparnell/rethinkdb,gavioto/rethinkdb,eliangidoni/rethinkdb,matthaywardwebdesign/rethinkdb,mbroadst/rethinkdb,RubenKelevra/rethinkdb,yakovenkodenis/rethinkdb,grandquista/rethinkdb,pap/rethinkdb,catroot/rethinkdb,sontek/rethinkdb,mcanthony/rethinkdb,bpradipt/rethinkdb,matthaywardwebdesign/rethinkdb,ajose01/rethinkdb,ajose01/rethinkdb,rrampage/rethinkdb,4talesa/rethinkdb,victorbriz/rethinkdb,losywee/rethinkdb,wkennington/rethinkdb,pap/rethinkdb,eliangidoni/rethinkdb,sbusso/rethinkdb,lenstr/rethinkdb,jmptrader/rethinkdb,Qinusty/rethinkdb,RubenKelevra/rethinkdb,eliangidoni/rethinkdb,elkingtonmcb/rethinkdb,ayumilong/rethinkdb,JackieXie168/rethinkdb,sontek/rethinkdb,bchavez/rethinkdb,gavioto/rethinkdb,grandquista/rethinkdb,elkingtonmcb/rethinkdb,alash3al/rethinkdb,RubenKelevra/rethinkdb,ayumilong/rethinkdb,KSanthanam/rethinkdb,greyhwndz/rethinkdb,jmptrader/rethinkdb,spblightadv/rethinkdb,ajose01/rethinkdb,dparnell/rethinkdb,bchavez/rethinkdb,lenstr/rethinkdb,ayumilong/rethinkdb,spblightadv/rethinkdb,losywee/rethinkdb,mquandalle/rethinkdb,bchavez/rethinkdb,dparnell/rethinkdb,4talesa/rethinkdb,victorbriz/rethinkdb,lenstr/rethinkdb,scripni/rethinkdb,ayumilong/rethinkdb,KSanthanam/rethinkdb,mcanthony/rethinkdb,tempbottle/rethinkdb,greyhwndz/rethinkdb,mcanthony/rethinkdb,captainpete/rethinkdb,bchavez/rethinkdb,dparnell/rethinkdb,AntouanK/rethinkdb,niieani/rethinkdb,Qinusty/rethinkdb,yakovenkodenis/rethinkdb,dparnell/rethinkdb,jmptrader/rethinkdb,greyhwndz/rethinkdb,robertjpayne/rethinkdb,yakovenkodenis/rethinkdb,lenstr/rethinkdb,rrampage/rethinkdb,mbroadst/rethinkdb,Wilbeibi/rethinkdb,pap/rethinkdb,captainpete/rethinkdb,ayumilong/rethinkdb,eliangidoni/rethinkdb,yakovenkodenis/rethinkdb,spblightadv/rethinkdb,scripni/rethinkdb,sbusso/rethinkdb,alash3al/rethinkdb,pap/rethinkdb,alash3al/rethinkdb,robertjpayne/rethinkdb,Wilbeibi/rethinkdb,wkennington/rethinkdb,dparnell/rethinkdb,KSanthanam/rethinkdb,robertjpayne/rethinkdb,grandquista/rethinkdb,JackieXie168/rethinkdb,victorbriz/rethinkdb,rrampage/rethinkdb,sebadiaz/rethinkdb,bpradipt/rethinkdb,ajose01/rethinkdb,wkennington/rethinkdb
a8056f4e7bd7a0b3969347c912b8ca8d0a7872a7
test/test_all.cpp
test/test_all.cpp
#define USE_VLD #if defined(_MSC_VER) && defined(_DEBUG) && defined(USE_VLD) # include "C:\\Program Files (x86)\\Visual Leak Detector\\include\\vld.h" #endif #include <cstring> #include <cstdlib> #include <algorithm> #include <stdexcept> #include <vector> #include <locale> #include <sstream> #include <fstream> #include <iostream> #include <iomanip> #include <realm/util/features.h> #include <memory> #include <realm/util/features.h> #include <realm.hpp> #include <realm/utilities.hpp> #include <realm/version.hpp> #include <realm/disable_sync_to_disk.hpp> #include "test_all.hpp" #include "util/timer.hpp" #include "util/resource_limits.hpp" #include "test.hpp" using namespace realm; using namespace realm::util; using namespace realm::test_util; using namespace realm::test_util::unit_test; namespace { const char* file_order[] = { // When choosing order, please try to use these guidelines: // // - If feature A depends on feature B, test feature B first. // // - If feature A has a more central role in the API than feature B, test // feature A first. // "test_self.cpp", // realm/util/ "test_safe_int_ops.cpp", "test_basic_utils.cpp", "test_file*.cpp", "test_thread.cpp", "test_util_network.cpp", "test_utf8.cpp", // /realm/ (helpers) "test_string_data.cpp", "test_binary_data.cpp", // /realm/impl/ (detail) "test_alloc*.cpp", "test_array*.cpp", "test_column*.cpp", "test_index*.cpp", "test_destroy_guard.cpp", // /realm/ (main API) "test_version.cpp", "test_table*.cpp", "test_descriptor*.cpp", "test_group*.cpp", "test_shared*.cpp", "test_transactions*.cpp", "test_query*.cpp", "test_links.cpp", "test_link_query_view.cpp", "test_json.cpp", "test_replication*.cpp", "test_transform.cpp", "test_sync.cpp", "test_lang_bind_helper.cpp", "large_tests*.cpp" }; void fix_max_open_files() { if (system_has_rlimit(resource_NumOpenFiles)) { long soft_limit = get_soft_rlimit(resource_NumOpenFiles); if (soft_limit >= 0) { long hard_limit = get_hard_rlimit(resource_NumOpenFiles); long new_soft_limit = hard_limit < 0 ? 4096 : hard_limit; if (new_soft_limit > soft_limit) { set_soft_rlimit(resource_NumOpenFiles, new_soft_limit); /* std::cout << "\n" "MaxOpenFiles: "<<soft_limit<<" --> "<<new_soft_limit<<"\n"; */ } } } } void fix_async_daemon_path() { // `setenv()` is POSIX. _WIN32 has `_putenv_s()` instead. #ifndef _WIN32 const char* async_daemon; // When running the unit-tests in Xcode, it runs them // in its own temporary directory. So we have to make sure we // look for the daemon there const char* xcode_env = getenv("__XCODE_BUILT_PRODUCTS_DIR_PATHS"); if (xcode_env) { # ifdef REALM_DEBUG async_daemon = "realmd-dbg-noinst"; # else async_daemon = "realmd-noinst"; # endif } else { # ifdef REALM_COVER async_daemon = "../src/realm/realmd-cov-noinst"; # else # ifdef REALM_DEBUG async_daemon = "../src/realm/realmd-dbg-noinst"; # else async_daemon = "../src/realm/realmd-noinst"; # endif # endif } setenv("REALM_ASYNC_DAEMON", async_daemon, 0); #endif // _WIN32 } void display_build_config() { const char* with_debug = Version::has_feature(feature_Debug) ? "Enabled" : "Disabled"; const char* with_replication = Version::has_feature(feature_Replication) ? "Enabled" : "Disabled"; #ifdef REALM_COMPILER_SSE const char* compiler_sse = "Yes"; #else const char* compiler_sse = "No"; #endif #ifdef REALM_COMPILER_AVX const char* compiler_avx = "Yes"; #else const char* compiler_avx = "No"; #endif const char* cpu_sse = realm::sseavx<42>() ? "4.2" : (realm::sseavx<30>() ? "3.0" : "None"); const char* cpu_avx = realm::sseavx<1>() ? "Yes" : "No"; std::cout << "\n" "Realm version: "<<Version::get_version()<<"\n" " with Debug "<<with_debug<<"\n" " with Replication "<<with_replication<<"\n" "\n" "REALM_MAX_BPNODE_SIZE = "<<REALM_MAX_BPNODE_SIZE<<"\n" "\n" // Be aware that ps3/xbox have sizeof (void*) = 4 && sizeof (size_t) == 8 // We decide to print size_t here "sizeof (size_t) * 8 = " << (sizeof (size_t) * 8) << "\n" "\n" "Compiler supported SSE (auto detect): "<<compiler_sse<<"\n" "This CPU supports SSE (auto detect): "<<cpu_sse<<"\n" "Compiler supported AVX (auto detect): "<<compiler_avx<<"\n" "This CPU supports AVX (AVX1) (auto detect): "<<cpu_avx<<"\n" "\n"; } // Records elapsed time for each test and shows a "Top 5" at the end. class CustomReporter: public SimpleReporter { public: explicit CustomReporter(bool report_progress): SimpleReporter(report_progress) { } ~CustomReporter() REALM_NOEXCEPT { } void end(const TestDetails& details, double elapsed_seconds) override { result r; r.m_test_name = details.test_name; r.m_elapsed_seconds = elapsed_seconds; m_results.push_back(r); SimpleReporter::end(details, elapsed_seconds); } void summary(const Summary& summary) override { SimpleReporter::summary(summary); size_t max_n = 5; size_t n = std::min<size_t>(max_n, m_results.size()); if (n < 2) return; partial_sort(m_results.begin(), m_results.begin() + n, m_results.end()); size_t name_col_width = 0, time_col_width = 0; for(size_t i = 0; i != n; ++i) { const result& r = m_results[i]; size_t size = r.m_test_name.size(); if (size > name_col_width) name_col_width = size; size = Timer::format(r.m_elapsed_seconds).size(); if (size > time_col_width) time_col_width = size; } name_col_width += 2; size_t full_width = name_col_width + time_col_width; std::cout.fill('-'); std::cout << "\nTop " << n << " time usage:\n" << std::setw(int(full_width)) << "" << "\n"; std::cout.fill(' '); for(size_t i = 0; i != n; ++i) { const result& r = m_results[i]; std::cout << std::left << std::setw(int(name_col_width)) << r.m_test_name << std::right << std::setw(int(time_col_width)) << Timer::format(r.m_elapsed_seconds) << "\n"; } } private: struct result { std::string m_test_name; double m_elapsed_seconds; bool operator<(const result& r) const { return m_elapsed_seconds > r.m_elapsed_seconds; // Descending order } }; std::vector<result> m_results; }; bool run_tests() { { const char* str = getenv("UNITTEST_RANDOM_SEED"); if (str && strlen(str) != 0) { unsigned long seed; if (strcmp(str, "random") == 0) { seed = produce_nondeterministic_random_seed(); } else { std::istringstream in(str); in.imbue(std::locale::classic()); in.flags(in.flags() & ~std::ios_base::skipws); // Do not accept white space in >> seed; bool bad = !in || in.get() != std::char_traits<char>::eof(); if (bad) throw std::runtime_error("Bad random seed"); } std::cout << "Random seed: "<<seed<<"\n\n"; random_seed(seed); } } { const char* str = getenv("UNITTEST_KEEP_FILES"); if (str && strlen(str) != 0) keep_test_files(); } std::unique_ptr<Reporter> reporter; std::unique_ptr<Filter> filter; // Set up reporter std::ofstream xml_file; bool xml; #ifdef REALM_MOBILE xml = true; #else const char* xml_str = getenv("UNITTEST_XML"); xml = (xml_str && strlen(xml_str) != 0); #endif if (xml) { std::string path = get_test_path_prefix(); std::string xml_path = path + "unit-test-report.xml"; xml_file.open(xml_path.c_str()); reporter.reset(create_xml_reporter(xml_file)); } else { const char* str = getenv("UNITTEST_PROGRESS"); bool report_progress = str && strlen(str) != 0; reporter.reset(new CustomReporter(report_progress)); } // Set up filter const char* filter_str = getenv("UNITTEST_FILTER"); const char* test_only = get_test_only(); if (test_only) filter_str = test_only; if (filter_str && strlen(filter_str) != 0) filter.reset(create_wildcard_filter(filter_str)); int num_threads = 1; { const char* str = getenv("UNITTEST_THREADS"); if (str && strlen(str) != 0) { std::istringstream in(str); in.imbue(std::locale::classic()); in.flags(in.flags() & ~std::ios_base::skipws); // Do not accept white space in >> num_threads; bool bad = !in || in.get() != std::char_traits<char>::eof() || num_threads < 1 || num_threads > 1024; if (bad) throw std::runtime_error("Bad number of threads"); if (num_threads > 1) std::cout << "Number of test threads: "<<num_threads<<"\n\n"; } } bool shuffle = false; { const char* str = getenv("UNITTEST_SHUFFLE"); if (str && strlen(str) != 0) shuffle = true; } // Run TestList& list = get_default_test_list(); list.sort(PatternBasedFileOrder(file_order)); bool success = list.run(reporter.get(), filter.get(), num_threads, shuffle); if (test_only) std::cout << "\n*** BE AWARE THAT MOST TESTS WERE EXCLUDED DUE TO USING 'ONLY' MACRO ***\n"; if (!xml) std::cout << "\n"; return success; } } // anonymous namespace int test_all(int argc, char* argv[]) { // Disable buffering on std::cout so that progress messages can be related to // error messages. std::cout.setf(std::ios::unitbuf); // No need to synchronize file changes to physical medium in the test suite, // as that would only make a difference if the entire system crashes, // e.g. due to power off. disable_sync_to_disk(); bool no_error_exit_staus = 2 <= argc && strcmp(argv[1], "--no-error-exitcode") == 0; #ifdef _MSC_VER // we're in /build/ on Windows if we're in the Visual Studio IDE set_test_resource_path("../../test/"); set_test_path_prefix("../../test/"); #endif fix_max_open_files(); fix_async_daemon_path(); display_build_config(); bool success = run_tests(); #ifdef _MSC_VER getchar(); // wait for key #endif return success || no_error_exit_staus ? EXIT_SUCCESS : EXIT_FAILURE; }
// #define USE_VLD #if defined(_MSC_VER) && defined(_DEBUG) && defined(USE_VLD) # include "C:\\Program Files (x86)\\Visual Leak Detector\\include\\vld.h" #endif #include <cstring> #include <cstdlib> #include <algorithm> #include <stdexcept> #include <vector> #include <locale> #include <sstream> #include <fstream> #include <iostream> #include <iomanip> #include <realm/util/features.h> #include <memory> #include <realm/util/features.h> #include <realm.hpp> #include <realm/utilities.hpp> #include <realm/version.hpp> #include <realm/disable_sync_to_disk.hpp> #include "test_all.hpp" #include "util/timer.hpp" #include "util/resource_limits.hpp" #include "test.hpp" using namespace realm; using namespace realm::util; using namespace realm::test_util; using namespace realm::test_util::unit_test; namespace { const char* file_order[] = { // When choosing order, please try to use these guidelines: // // - If feature A depends on feature B, test feature B first. // // - If feature A has a more central role in the API than feature B, test // feature A first. // "test_self.cpp", // realm/util/ "test_safe_int_ops.cpp", "test_basic_utils.cpp", "test_file*.cpp", "test_thread.cpp", "test_util_network.cpp", "test_utf8.cpp", // /realm/ (helpers) "test_string_data.cpp", "test_binary_data.cpp", // /realm/impl/ (detail) "test_alloc*.cpp", "test_array*.cpp", "test_column*.cpp", "test_index*.cpp", "test_destroy_guard.cpp", // /realm/ (main API) "test_version.cpp", "test_table*.cpp", "test_descriptor*.cpp", "test_group*.cpp", "test_shared*.cpp", "test_transactions*.cpp", "test_query*.cpp", "test_links.cpp", "test_link_query_view.cpp", "test_json.cpp", "test_replication*.cpp", "test_transform.cpp", "test_sync.cpp", "test_lang_bind_helper.cpp", "large_tests*.cpp" }; void fix_max_open_files() { if (system_has_rlimit(resource_NumOpenFiles)) { long soft_limit = get_soft_rlimit(resource_NumOpenFiles); if (soft_limit >= 0) { long hard_limit = get_hard_rlimit(resource_NumOpenFiles); long new_soft_limit = hard_limit < 0 ? 4096 : hard_limit; if (new_soft_limit > soft_limit) { set_soft_rlimit(resource_NumOpenFiles, new_soft_limit); /* std::cout << "\n" "MaxOpenFiles: "<<soft_limit<<" --> "<<new_soft_limit<<"\n"; */ } } } } void fix_async_daemon_path() { // `setenv()` is POSIX. _WIN32 has `_putenv_s()` instead. #ifndef _WIN32 const char* async_daemon; // When running the unit-tests in Xcode, it runs them // in its own temporary directory. So we have to make sure we // look for the daemon there const char* xcode_env = getenv("__XCODE_BUILT_PRODUCTS_DIR_PATHS"); if (xcode_env) { # ifdef REALM_DEBUG async_daemon = "realmd-dbg-noinst"; # else async_daemon = "realmd-noinst"; # endif } else { # ifdef REALM_COVER async_daemon = "../src/realm/realmd-cov-noinst"; # else # ifdef REALM_DEBUG async_daemon = "../src/realm/realmd-dbg-noinst"; # else async_daemon = "../src/realm/realmd-noinst"; # endif # endif } setenv("REALM_ASYNC_DAEMON", async_daemon, 0); #endif // _WIN32 } void display_build_config() { const char* with_debug = Version::has_feature(feature_Debug) ? "Enabled" : "Disabled"; const char* with_replication = Version::has_feature(feature_Replication) ? "Enabled" : "Disabled"; #ifdef REALM_COMPILER_SSE const char* compiler_sse = "Yes"; #else const char* compiler_sse = "No"; #endif #ifdef REALM_COMPILER_AVX const char* compiler_avx = "Yes"; #else const char* compiler_avx = "No"; #endif const char* cpu_sse = realm::sseavx<42>() ? "4.2" : (realm::sseavx<30>() ? "3.0" : "None"); const char* cpu_avx = realm::sseavx<1>() ? "Yes" : "No"; std::cout << "\n" "Realm version: "<<Version::get_version()<<"\n" " with Debug "<<with_debug<<"\n" " with Replication "<<with_replication<<"\n" "\n" "REALM_MAX_BPNODE_SIZE = "<<REALM_MAX_BPNODE_SIZE<<"\n" "\n" // Be aware that ps3/xbox have sizeof (void*) = 4 && sizeof (size_t) == 8 // We decide to print size_t here "sizeof (size_t) * 8 = " << (sizeof (size_t) * 8) << "\n" "\n" "Compiler supported SSE (auto detect): "<<compiler_sse<<"\n" "This CPU supports SSE (auto detect): "<<cpu_sse<<"\n" "Compiler supported AVX (auto detect): "<<compiler_avx<<"\n" "This CPU supports AVX (AVX1) (auto detect): "<<cpu_avx<<"\n" "\n"; } // Records elapsed time for each test and shows a "Top 5" at the end. class CustomReporter: public SimpleReporter { public: explicit CustomReporter(bool report_progress): SimpleReporter(report_progress) { } ~CustomReporter() REALM_NOEXCEPT { } void end(const TestDetails& details, double elapsed_seconds) override { result r; r.m_test_name = details.test_name; r.m_elapsed_seconds = elapsed_seconds; m_results.push_back(r); SimpleReporter::end(details, elapsed_seconds); } void summary(const Summary& summary) override { SimpleReporter::summary(summary); size_t max_n = 5; size_t n = std::min<size_t>(max_n, m_results.size()); if (n < 2) return; partial_sort(m_results.begin(), m_results.begin() + n, m_results.end()); size_t name_col_width = 0, time_col_width = 0; for(size_t i = 0; i != n; ++i) { const result& r = m_results[i]; size_t size = r.m_test_name.size(); if (size > name_col_width) name_col_width = size; size = Timer::format(r.m_elapsed_seconds).size(); if (size > time_col_width) time_col_width = size; } name_col_width += 2; size_t full_width = name_col_width + time_col_width; std::cout.fill('-'); std::cout << "\nTop " << n << " time usage:\n" << std::setw(int(full_width)) << "" << "\n"; std::cout.fill(' '); for(size_t i = 0; i != n; ++i) { const result& r = m_results[i]; std::cout << std::left << std::setw(int(name_col_width)) << r.m_test_name << std::right << std::setw(int(time_col_width)) << Timer::format(r.m_elapsed_seconds) << "\n"; } } private: struct result { std::string m_test_name; double m_elapsed_seconds; bool operator<(const result& r) const { return m_elapsed_seconds > r.m_elapsed_seconds; // Descending order } }; std::vector<result> m_results; }; bool run_tests() { { const char* str = getenv("UNITTEST_RANDOM_SEED"); if (str && strlen(str) != 0) { unsigned long seed; if (strcmp(str, "random") == 0) { seed = produce_nondeterministic_random_seed(); } else { std::istringstream in(str); in.imbue(std::locale::classic()); in.flags(in.flags() & ~std::ios_base::skipws); // Do not accept white space in >> seed; bool bad = !in || in.get() != std::char_traits<char>::eof(); if (bad) throw std::runtime_error("Bad random seed"); } std::cout << "Random seed: "<<seed<<"\n\n"; random_seed(seed); } } { const char* str = getenv("UNITTEST_KEEP_FILES"); if (str && strlen(str) != 0) keep_test_files(); } std::unique_ptr<Reporter> reporter; std::unique_ptr<Filter> filter; // Set up reporter std::ofstream xml_file; bool xml; #ifdef REALM_MOBILE xml = true; #else const char* xml_str = getenv("UNITTEST_XML"); xml = (xml_str && strlen(xml_str) != 0); #endif if (xml) { std::string path = get_test_path_prefix(); std::string xml_path = path + "unit-test-report.xml"; xml_file.open(xml_path.c_str()); reporter.reset(create_xml_reporter(xml_file)); } else { const char* str = getenv("UNITTEST_PROGRESS"); bool report_progress = str && strlen(str) != 0; reporter.reset(new CustomReporter(report_progress)); } // Set up filter const char* filter_str = getenv("UNITTEST_FILTER"); const char* test_only = get_test_only(); if (test_only) filter_str = test_only; if (filter_str && strlen(filter_str) != 0) filter.reset(create_wildcard_filter(filter_str)); int num_threads = 1; { const char* str = getenv("UNITTEST_THREADS"); if (str && strlen(str) != 0) { std::istringstream in(str); in.imbue(std::locale::classic()); in.flags(in.flags() & ~std::ios_base::skipws); // Do not accept white space in >> num_threads; bool bad = !in || in.get() != std::char_traits<char>::eof() || num_threads < 1 || num_threads > 1024; if (bad) throw std::runtime_error("Bad number of threads"); if (num_threads > 1) std::cout << "Number of test threads: "<<num_threads<<"\n\n"; } } bool shuffle = false; { const char* str = getenv("UNITTEST_SHUFFLE"); if (str && strlen(str) != 0) shuffle = true; } // Run TestList& list = get_default_test_list(); list.sort(PatternBasedFileOrder(file_order)); bool success = list.run(reporter.get(), filter.get(), num_threads, shuffle); if (test_only) std::cout << "\n*** BE AWARE THAT MOST TESTS WERE EXCLUDED DUE TO USING 'ONLY' MACRO ***\n"; if (!xml) std::cout << "\n"; return success; } } // anonymous namespace int test_all(int argc, char* argv[]) { // Disable buffering on std::cout so that progress messages can be related to // error messages. std::cout.setf(std::ios::unitbuf); // No need to synchronize file changes to physical medium in the test suite, // as that would only make a difference if the entire system crashes, // e.g. due to power off. disable_sync_to_disk(); bool no_error_exit_staus = 2 <= argc && strcmp(argv[1], "--no-error-exitcode") == 0; #ifdef _MSC_VER // we're in /build/ on Windows if we're in the Visual Studio IDE set_test_resource_path("../../test/"); set_test_path_prefix("../../test/"); #endif fix_max_open_files(); fix_async_daemon_path(); display_build_config(); bool success = run_tests(); #ifdef _MSC_VER getchar(); // wait for key #endif return success || no_error_exit_staus ? EXIT_SUCCESS : EXIT_FAILURE; }
Update test_all.cpp
Update test_all.cpp
C++
apache-2.0
realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core,realm/realm-core
55d6aa791660d90d09810f39ed7d9d6f902196d8
chrome/renderer/devtools_agent.cc
chrome/renderer/devtools_agent.cc
// 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 "chrome/renderer/devtools_agent.h" #include "base/command_line.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/devtools_messages.h" #include "chrome/common/render_messages.h" #include "chrome/renderer/devtools_agent_filter.h" #include "chrome/renderer/render_view.h" #include "grit/webkit_chromium_resources.h" #include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h" #include "third_party/WebKit/WebKit/chromium/public/WebDevToolsMessageData.h" #include "third_party/WebKit/WebKit/chromium/public/WebPoint.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" #include "webkit/glue/devtools_message_data.h" #include "webkit/glue/webkit_glue.h" using WebKit::WebDevToolsAgent; using WebKit::WebDevToolsAgentClient; using WebKit::WebPoint; using WebKit::WebString; using WebKit::WebCString; using WebKit::WebVector; using WebKit::WebView; namespace { class WebKitClientMessageLoopImpl : public WebDevToolsAgentClient::WebKitClientMessageLoop { public: WebKitClientMessageLoopImpl() : message_loop_(MessageLoop::current()) { } virtual ~WebKitClientMessageLoopImpl() { message_loop_ = NULL; } virtual void run() { bool old_state = message_loop_->NestableTasksAllowed(); message_loop_->SetNestableTasksAllowed(true); message_loop_->Run(); message_loop_->SetNestableTasksAllowed(old_state); } virtual void quitNow() { message_loop_->QuitNow(); } private: MessageLoop* message_loop_; }; } // namespace // static std::map<int, DevToolsAgent*> DevToolsAgent::agent_for_routing_id_; DevToolsAgent::DevToolsAgent(int routing_id, RenderView* render_view) : routing_id_(routing_id), render_view_(render_view) { agent_for_routing_id_[routing_id] = this; CommandLine* cmd = CommandLine::ForCurrentProcess(); expose_v8_debugger_protocol_ =cmd->HasSwitch(switches::kRemoteShellPort); } DevToolsAgent::~DevToolsAgent() { agent_for_routing_id_.erase(routing_id_); } void DevToolsAgent::OnNavigate() { WebDevToolsAgent* web_agent = GetWebAgent(); if (web_agent) { web_agent->didNavigate(); } } // Called on the Renderer thread. bool DevToolsAgent::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(DevToolsAgent, message) IPC_MESSAGE_HANDLER(DevToolsAgentMsg_Attach, OnAttach) IPC_MESSAGE_HANDLER(DevToolsAgentMsg_Detach, OnDetach) IPC_MESSAGE_HANDLER(DevToolsAgentMsg_RpcMessage, OnRpcMessage) IPC_MESSAGE_HANDLER(DevToolsAgentMsg_InspectElement, OnInspectElement) IPC_MESSAGE_HANDLER(DevToolsAgentMsg_SetApuAgentEnabled, OnSetApuAgentEnabled) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void DevToolsAgent::sendMessageToFrontend( const WebKit::WebDevToolsMessageData& data) { IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient( routing_id_, DevToolsClientMsg_RpcMessage(DevToolsMessageData(data))); render_view_->Send(m); } int DevToolsAgent::hostIdentifier() { return routing_id_; } void DevToolsAgent::forceRepaint() { render_view_->GenerateFullRepaint(); } void DevToolsAgent::runtimeFeatureStateChanged(const WebKit::WebString& feature, bool enabled) { render_view_->Send(new ViewHostMsg_DevToolsRuntimeFeatureStateChanged( routing_id_, feature.utf8(), enabled)); } WebCString DevToolsAgent::injectedScriptSource() { base::StringPiece injectjsWebkit = webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_WEBKIT_JS); return WebCString(injectjsWebkit.data(), injectjsWebkit.length()); } WebCString DevToolsAgent::injectedScriptDispatcherSource() { base::StringPiece injectDispatchjs = webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_DISPATCH_JS); return WebCString(injectDispatchjs.data(), injectDispatchjs.length()); } WebCString DevToolsAgent::debuggerScriptSource() { base::StringPiece debuggerScriptjs = webkit_glue::GetDataResource(IDR_DEVTOOLS_DEBUGGER_SCRIPT_JS); return WebCString(debuggerScriptjs.data(), debuggerScriptjs.length()); } WebKit::WebDevToolsAgentClient::WebKitClientMessageLoop* DevToolsAgent::createClientMessageLoop() { return new WebKitClientMessageLoopImpl(); } bool DevToolsAgent::exposeV8DebuggerProtocol() { return expose_v8_debugger_protocol_; } // static DevToolsAgent* DevToolsAgent::FromHostId(int host_id) { std::map<int, DevToolsAgent*>::iterator it = agent_for_routing_id_.find(host_id); if (it != agent_for_routing_id_.end()) { return it->second; } return NULL; } void DevToolsAgent::OnAttach(const std::vector<std::string>& runtime_features) { WebDevToolsAgent* web_agent = GetWebAgent(); if (web_agent) { web_agent->attach(); for (std::vector<std::string>::const_iterator it = runtime_features.begin(); it != runtime_features.end(); ++it) { web_agent->setRuntimeFeatureEnabled(WebString::fromUTF8(*it), true); } } } void DevToolsAgent::OnDetach() { WebDevToolsAgent* web_agent = GetWebAgent(); if (web_agent) { web_agent->detach(); } } void DevToolsAgent::OnRpcMessage(const DevToolsMessageData& data) { WebDevToolsAgent* web_agent = GetWebAgent(); if (web_agent) { web_agent->dispatchMessageFromFrontend(data.ToWebDevToolsMessageData()); } } void DevToolsAgent::OnInspectElement(int x, int y) { WebDevToolsAgent* web_agent = GetWebAgent(); if (web_agent) { web_agent->attach(); web_agent->inspectElementAt(WebPoint(x, y)); } } void DevToolsAgent::OnSetApuAgentEnabled(bool enabled) { WebDevToolsAgent* web_agent = GetWebAgent(); if (web_agent) web_agent->setRuntimeFeatureEnabled("apu-agent", enabled); } WebDevToolsAgent* DevToolsAgent::GetWebAgent() { WebView* web_view = render_view_->webview(); if (!web_view) return NULL; return web_view->devToolsAgent(); } // static void WebKit::WebDevToolsAgentClient::sendMessageToFrontendOnIOThread( const WebDevToolsMessageData& data) { DevToolsAgentFilter::SendRpcMessage(DevToolsMessageData(data)); }
// 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 "chrome/renderer/devtools_agent.h" #include "base/command_line.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/devtools_messages.h" #include "chrome/common/render_messages.h" #include "chrome/renderer/devtools_agent_filter.h" #include "chrome/renderer/render_view.h" #include "grit/webkit_chromium_resources.h" #include "third_party/WebKit/WebKit/chromium/public/WebDevToolsAgent.h" #include "third_party/WebKit/WebKit/chromium/public/WebDevToolsMessageData.h" #include "third_party/WebKit/WebKit/chromium/public/WebPoint.h" #include "third_party/WebKit/WebKit/chromium/public/WebString.h" #include "webkit/glue/devtools_message_data.h" #include "webkit/glue/webkit_glue.h" using WebKit::WebDevToolsAgent; using WebKit::WebDevToolsAgentClient; using WebKit::WebPoint; using WebKit::WebString; using WebKit::WebCString; using WebKit::WebVector; using WebKit::WebView; namespace { class WebKitClientMessageLoopImpl : public WebDevToolsAgentClient::WebKitClientMessageLoop { public: WebKitClientMessageLoopImpl() : message_loop_(MessageLoop::current()) { } virtual ~WebKitClientMessageLoopImpl() { message_loop_ = NULL; } virtual void run() { bool old_state = message_loop_->NestableTasksAllowed(); message_loop_->SetNestableTasksAllowed(true); message_loop_->Run(); message_loop_->SetNestableTasksAllowed(old_state); } virtual void quitNow() { message_loop_->QuitNow(); } private: MessageLoop* message_loop_; }; } // namespace // static std::map<int, DevToolsAgent*> DevToolsAgent::agent_for_routing_id_; DevToolsAgent::DevToolsAgent(int routing_id, RenderView* render_view) : routing_id_(routing_id), render_view_(render_view) { agent_for_routing_id_[routing_id] = this; CommandLine* cmd = CommandLine::ForCurrentProcess(); expose_v8_debugger_protocol_ =cmd->HasSwitch(switches::kRemoteShellPort); } DevToolsAgent::~DevToolsAgent() { agent_for_routing_id_.erase(routing_id_); } void DevToolsAgent::OnNavigate() { WebDevToolsAgent* web_agent = GetWebAgent(); if (web_agent) { web_agent->didNavigate(); } } // Called on the Renderer thread. bool DevToolsAgent::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(DevToolsAgent, message) IPC_MESSAGE_HANDLER(DevToolsAgentMsg_Attach, OnAttach) IPC_MESSAGE_HANDLER(DevToolsAgentMsg_Detach, OnDetach) IPC_MESSAGE_HANDLER(DevToolsAgentMsg_RpcMessage, OnRpcMessage) IPC_MESSAGE_HANDLER(DevToolsAgentMsg_InspectElement, OnInspectElement) IPC_MESSAGE_HANDLER(DevToolsAgentMsg_SetApuAgentEnabled, OnSetApuAgentEnabled) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void DevToolsAgent::sendMessageToFrontend( const WebKit::WebDevToolsMessageData& data) { IPC::Message* m = new ViewHostMsg_ForwardToDevToolsClient( routing_id_, DevToolsClientMsg_RpcMessage(DevToolsMessageData(data))); render_view_->Send(m); } int DevToolsAgent::hostIdentifier() { return routing_id_; } void DevToolsAgent::forceRepaint() { render_view_->GenerateFullRepaint(); } void DevToolsAgent::runtimeFeatureStateChanged(const WebKit::WebString& feature, bool enabled) { render_view_->Send(new ViewHostMsg_DevToolsRuntimeFeatureStateChanged( routing_id_, feature.utf8(), enabled)); } WebCString DevToolsAgent::injectedScriptSource() { base::StringPiece injectjsWebkit = webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_WEBKIT_JS); return WebCString(injectjsWebkit.data(), injectjsWebkit.length()); } WebCString DevToolsAgent::injectedScriptDispatcherSource() { base::StringPiece injectDispatchjs = webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_DISPATCH_JS); return WebCString(injectDispatchjs.data(), injectDispatchjs.length()); } WebCString DevToolsAgent::debuggerScriptSource() { base::StringPiece debuggerScriptjs = webkit_glue::GetDataResource(IDR_DEVTOOLS_DEBUGGER_SCRIPT_JS); return WebCString(debuggerScriptjs.data(), debuggerScriptjs.length()); } WebKit::WebDevToolsAgentClient::WebKitClientMessageLoop* DevToolsAgent::createClientMessageLoop() { return new WebKitClientMessageLoopImpl(); } bool DevToolsAgent::exposeV8DebuggerProtocol() { return expose_v8_debugger_protocol_; } // static DevToolsAgent* DevToolsAgent::FromHostId(int host_id) { std::map<int, DevToolsAgent*>::iterator it = agent_for_routing_id_.find(host_id); if (it != agent_for_routing_id_.end()) { return it->second; } return NULL; } void DevToolsAgent::OnAttach(const std::vector<std::string>& runtime_features) { WebDevToolsAgent* web_agent = GetWebAgent(); if (web_agent) { web_agent->attach(); for (std::vector<std::string>::const_iterator it = runtime_features.begin(); it != runtime_features.end(); ++it) { web_agent->setRuntimeFeatureEnabled(WebString::fromUTF8(*it), true); } } } void DevToolsAgent::OnDetach() { WebDevToolsAgent* web_agent = GetWebAgent(); if (web_agent) { web_agent->detach(); } } void DevToolsAgent::OnRpcMessage(const DevToolsMessageData& data) { WebDevToolsAgent* web_agent = GetWebAgent(); if (web_agent) { web_agent->dispatchMessageFromFrontend(data.ToWebDevToolsMessageData()); } } void DevToolsAgent::OnInspectElement(int x, int y) { WebDevToolsAgent* web_agent = GetWebAgent(); if (web_agent) { web_agent->attach(); web_agent->inspectElementAt(WebPoint(x, y)); } } void DevToolsAgent::OnSetApuAgentEnabled(bool enabled) { WebDevToolsAgent* web_agent = GetWebAgent(); if (web_agent) web_agent->setRuntimeFeatureEnabled("apu-agent", enabled); } WebDevToolsAgent* DevToolsAgent::GetWebAgent() { WebView* web_view = render_view_->webview(); if (!web_view) return NULL; return web_view->devToolsAgent(); }
Remove unused static implementation of sendMessageToFrontendOnIOThread.
Remove unused static implementation of sendMessageToFrontendOnIOThread. BUG=none TEST=none Review URL: http://codereview.chromium.org/2852016 git-svn-id: http://src.chromium.org/svn/trunk/src@50451 4ff67af0-8c30-449e-8e8b-ad334ec8d88c Former-commit-id: 3f6f55afd8f892f62f6591eac708faa819290338
C++
bsd-3-clause
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
86a4e5139428a4b2b721d785cea6fa8839f20534
cint/reflex/src/genmap/genmap.cxx
cint/reflex/src/genmap/genmap.cxx
// @(#)root/reflex:$Id: Class.cxx 20883 2007-11-19 11:52:08Z rdm $ // Include files---------------------------------------------------------------- #include "Reflex/Reflex.h" #include "Reflex/PluginService.h" #include "Reflex/SharedLibrary.h" #include "../dir_manip.h" #include <cstdlib> #include <set> #include <ctime> #include <cerrno> #include <fstream> #include <iostream> #include <exception> using namespace std; using namespace ROOT::Reflex; class mapGenerator { fstream m_out; string m_lib; public: mapGenerator(const string& file, const string& lib): m_out(file.c_str(), std::ios_base::out | std::ios_base::trunc), m_lib(lib) {} bool good() const { return m_out.good(); } void genHeader(); void genFactory(const string& name, const string& type); void genTrailer(); }; static string currpath(string lib) { char buff[PATH_MAX]; if (!::getcwd(buff, sizeof(buff))) { // coverity[secure_coding] - PATH_MAX is > 2 strcpy(buff, "."); } string tmp = buff; tmp += "/" + lib; return tmp; } static int help(const char* cmd) { cout << cmd << ": Allowed options" << endl << " -help produce this help message" << endl << " -debug increase verbosity level" << endl << " -input-library library to extract the plugins" << endl << " -output-file output file. default <input-library>.rootmap" << endl; return 1; } //--- Command main program------------------------------------------------------ int main(int argc, char** argv) { struct stat buf; bool deb = false; string rootmap, lib, err, out; string::size_type idx; for (int i = 1; i < argc; ++i) { const char* opt = argv[i], * val = 0; if (*opt == '/' || *opt == '-') { if (*++opt == '/' || *opt == '-') { ++opt; } val = (opt[1] != '=') ? ++i < argc ? argv[i] : 0 : opt + 2; switch (::toupper(opt[0])) { case 'D': deb = true; --i; break; case 'I': lib = val; break; case 'O': rootmap = val; break; default: return help(argv[0]); } } } if (lib.empty()) { cout << "ERROR occurred: input library required" << endl; return help(argv[0]); } if (rootmap.empty()) { string flib = lib; while ((idx = flib.find("\\")) != string::npos) flib.replace(idx, 1, "/"); #ifdef _WIN32 if (flib[1] != ':' && flib[0] != '/') { #else if (!(flib[0] == '/' || flib.find('/') != string::npos)) { #endif flib = currpath(flib); } rootmap = ::dirnameEx(flib); rootmap += "/"; string tmp = ::basenameEx(lib); if (tmp.rfind('.') == std::string::npos) { rootmap += tmp + ".rootmap"; } else if (tmp.find("/") != std::string::npos && tmp.rfind(".") < tmp.rfind("/")) { rootmap += tmp + ".rootmap"; } else { rootmap += tmp.substr(0, tmp.rfind('.')) + ".rootmap"; } } if (deb) { cout << "Input Library: '" << lib << "'" << endl; cout << "ROOT Map file: '" << rootmap << "'" << endl; } if (::stat(rootmap.c_str(), &buf) == -1 && errno == ENOENT) { string dir = ::dirnameEx(rootmap); if (deb) { cout << "Output directory:" << dir << "'" << endl; } if (!dir.empty()) { if (::mkdir(dir.c_str(), S_IRWXU | S_IRGRP | S_IROTH) != 0 && errno != EEXIST) { cout << "ERR0R: error creating directory: '" << dir << "'" << endl; return 1; } } } out = rootmap; //--- Load the library ------------------------------------------------- SharedLibrary sl(lib); if (!sl.Load()) { cout << "ERR0R: error loading library: '" << lib << "'" << endl << sl.Error() << endl; return 1; } mapGenerator map_gen(rootmap.c_str(), lib); if (!map_gen.good()) { cout << "ERR0R: cannot open output file: '" << rootmap << "'" << endl << sl.Error() << endl; sl.Unload(); return 1; } //--- Iterate over component factories --------------------------------------- Scope factories = Scope::ByName(PLUGINSVC_FACTORY_NS); if (factories) { map_gen.genHeader(); set<string> used_names; try { for (Member_Iterator it = factories.FunctionMember_Begin(); it != factories.FunctionMember_End(); ++it) { //string cname = it->Properties().PropertyAsString("name"); string cname = it->Name(); if (used_names.insert(cname).second) { map_gen.genFactory(cname, ""); } } map_gen.genTrailer(); sl.Unload(); return 0; } catch (std::exception& e) { cerr << "GENMAP: error creating map " << rootmap << ": " << e.what() << endl; } return 1; } cout << "library does not contain plugin factories" << endl; sl.Unload(); return 0; } // main //------------------------------------------------------------------------------ void mapGenerator::genHeader() { //------------------------------------------------------------------------------ time_t rawtime; time(&rawtime); m_out << "# ROOT map file generated automatically by genmap on " << ctime(&rawtime) << endl; } //------------------------------------------------------------------------------ void mapGenerator::genFactory(const string& name, const string& /* type */) { //------------------------------------------------------------------------------ string mapname = string(PLUGINSVC_FACTORY_NS) + "@@" + PluginService::FactoryName(name); // for ( string::const_iterator i = name.begin(); i != name.end(); i++) { // switch(*i) { // case ':': { newname += '@'; break; } // case ' ': { break; } // default: { newname += *i; break; } // } // } m_out << "Library." << mapname << ": " << m_lib << endl; } //------------------------------------------------------------------------------ void mapGenerator::genTrailer() { //------------------------------------------------------------------------------ }
// @(#)root/reflex:$Id: Class.cxx 20883 2007-11-19 11:52:08Z rdm $ // Include files---------------------------------------------------------------- #include "Reflex/Reflex.h" #include "Reflex/PluginService.h" #include "Reflex/SharedLibrary.h" #include "../dir_manip.h" #include <cstdlib> #include <set> #include <ctime> #include <cerrno> #include <fstream> #include <iostream> #include <exception> using namespace std; using namespace ROOT::Reflex; class mapGenerator { fstream m_out; string m_lib; public: mapGenerator(const string& file, const string& lib): m_out(file.c_str(), std::ios_base::out | std::ios_base::trunc), m_lib(lib) {} bool good() const { return m_out.good(); } void genHeader(); void genFactory(const string& name, const string& type); void genTrailer(); }; static string currpath(string lib) { char buff[PATH_MAX]; if (!::getcwd(buff, sizeof(buff))) { // coverity[secure_coding] - PATH_MAX is > 2 strcpy(buff, "."); } string tmp = buff; tmp += "/" + lib; return tmp; } static int help(const char* cmd) { cout << cmd << ": Allowed options" << endl << " -help produce this help message" << endl << " -debug increase verbosity level" << endl << " -input-library library to extract the plugins" << endl << " -output-file output file. default <input-library>.rootmap" << endl; return 1; } //--- Command main program------------------------------------------------------ int main(int argc, char** argv) { struct stat buf; bool deb = false; string rootmap, lib, err, out; string::size_type idx; for (int i = 1; i < argc; ++i) { const char* opt = argv[i], * val = 0; if (*opt == '/' || *opt == '-') { if (*++opt == '/' || *opt == '-') { ++opt; } val = (opt[1] != '=') ? ++i < argc ? argv[i] : 0 : opt + 2; switch (::toupper(opt[0])) { case 'D': deb = true; --i; break; case 'I': lib = val; break; case 'O': rootmap = val; break; default: return help(argv[0]); } } } if (lib.empty()) { cout << "ERROR occurred: input library required" << endl; return help(argv[0]); } if (rootmap.empty()) { string flib = lib; while ((idx = flib.find("\\")) != string::npos) flib.replace(idx, 1, "/"); #ifdef _WIN32 if (flib[1] != ':' && flib[0] != '/') { #else if (!(flib[0] == '/' || flib.find('/') != string::npos)) { #endif flib = currpath(flib); } rootmap = ::dirnameEx(flib); rootmap += "/"; string tmp = ::basenameEx(lib); if (tmp.rfind('.') == std::string::npos) { rootmap += tmp + ".rootmap"; } else if (tmp.find("/") != std::string::npos && tmp.rfind(".") < tmp.rfind("/")) { rootmap += tmp + ".rootmap"; } else { rootmap += tmp.substr(0, tmp.rfind('.')) + ".rootmap"; } } if (deb) { cout << "Input Library: '" << lib << "'" << endl; cout << "ROOT Map file: '" << rootmap << "'" << endl; } if (::stat(rootmap.c_str(), &buf) == -1 && errno == ENOENT) { string dir = ::dirnameEx(rootmap); if (deb) { cout << "Output directory:" << dir << "'" << endl; } if (!dir.empty()) { if (::mkdir(dir.c_str(), S_IRWXU | S_IRGRP | S_IROTH) != 0 && errno != EEXIST) { cout << "ERR0R: error creating directory: '" << dir << "'" << endl; return 1; } } } out = rootmap; //--- Load the library ------------------------------------------------- SharedLibrary sl(lib); if (!sl.Load()) { cout << "ERR0R: error loading library: '" << lib << "'" << endl << sl.Error() << endl; return 1; } mapGenerator map_gen(rootmap.c_str(), lib); if (!map_gen.good()) { cout << "ERR0R: cannot open output file: '" << rootmap << "'" << endl << sl.Error() << endl; return 1; } //--- Iterate over component factories --------------------------------------- Scope factories = Scope::ByName(PLUGINSVC_FACTORY_NS); if (factories) { map_gen.genHeader(); set<string> used_names; try { for (Member_Iterator it = factories.FunctionMember_Begin(); it != factories.FunctionMember_End(); ++it) { //string cname = it->Properties().PropertyAsString("name"); string cname = it->Name(); if (used_names.insert(cname).second) { map_gen.genFactory(cname, ""); } } map_gen.genTrailer(); return 0; } catch (std::exception& e) { cerr << "GENMAP: error creating map " << rootmap << ": " << e.what() << endl; } return 1; } cout << "library does not contain plugin factories" << endl; return 0; } // main //------------------------------------------------------------------------------ void mapGenerator::genHeader() { //------------------------------------------------------------------------------ time_t rawtime; time(&rawtime); m_out << "# ROOT map file generated automatically by genmap on " << ctime(&rawtime) << endl; } //------------------------------------------------------------------------------ void mapGenerator::genFactory(const string& name, const string& /* type */) { //------------------------------------------------------------------------------ string mapname = string(PLUGINSVC_FACTORY_NS) + "@@" + PluginService::FactoryName(name); // for ( string::const_iterator i = name.begin(); i != name.end(); i++) { // switch(*i) { // case ':': { newname += '@'; break; } // case ' ': { break; } // default: { newname += *i; break; } // } // } m_out << "Library." << mapname << ": " << m_lib << endl; } //------------------------------------------------------------------------------ void mapGenerator::genTrailer() { //------------------------------------------------------------------------------ }
Undo r42782 - unloading shlibs might cause problems (Savannah 90875)
Undo r42782 - unloading shlibs might cause problems (Savannah 90875) git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@42791 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical
6e4535e192025143f47d7b05ea18dd3d9efacf56
circular-linked-list-deletion.cpp
circular-linked-list-deletion.cpp
/******************************************************************************* Circular linked list deletion ================================= Ref - http://quiz.geeksforgeeks.org/circular-linked-list/ -------------------------------------------------------------------------------- Problem ======= Delete a node in a Circular linked list at some position. -------------------------------------------------------------------------------- Time Complexity =============== O(n) -------------------------------------------------------------------------------- Output ====== Buy on day : 0 Sell on day: 3 Buy on day : 4 Sell on day: 6 *******************************************************************************/ #include <stdio.h> struct CLLNode { int data; CLLNode *next; }; struct CLLNode * getNode(int data) { CLLNode *newNode = new CLLNode(); newNode->data = data; newNode->next = newNode; return newNode; } void insert(CLLNode **head, int data, int position) { CLLNode *newNode = getNode(data); if(!newNode) { printf("Memory error\n"); return; } if(*head == NULL) *head = newNode; else { CLLNode *current = *head, *q; if(position == 0) { newNode->next = current; while(current->next != *head) { current = current->next; } current->next = newNode; *head = newNode; } else { int i = 0; while(current && i < position) { q = current; i++; current = current->next; } newNode->next = current; q->next = newNode; } } } void del(CLLNode **head, int position) { CLLNode *current = *head, *q; if (!current) { printf("List is empty\n"); return; } if(position == 0) { current = current->next; while(current != *head) { q = current; current = current->next; } } for (int i = 0; i < position; ++i) { q = current; current = current->next; } if(current == *head) { *head = (*head)->next; } q->next = current->next; delete(current); } void printList(CLLNode *head) { CLLNode *current = head; do { printf("%d -> ", current->data); current = current->next; } while(current != head); printf("\b\b\b \n"); // destructive backspace } int main() { CLLNode *head = getNode(1); insert(&head, 2, 0); insert(&head, 3, 0); insert(&head, 4, 0); printList(head); del(&head, 0); del(&head, 2); printList(head); return 0; }
/******************************************************************************* Circular linked list deletion ================================= Ref - http://quiz.geeksforgeeks.org/circular-linked-list/ -------------------------------------------------------------------------------- Problem ======= Delete a node in a Circular linked list at some position. -------------------------------------------------------------------------------- Time Complexity =============== O(n) -------------------------------------------------------------------------------- Output ====== 4 -> 3 -> 2 -> 1 3 -> 2 *******************************************************************************/ #include <stdio.h> struct CLLNode { int data; CLLNode *next; }; struct CLLNode * getNode(int data) { CLLNode *newNode = new CLLNode(); newNode->data = data; newNode->next = newNode; return newNode; } void insert(CLLNode **head, int data, int position) { CLLNode *newNode = getNode(data); if(!newNode) { printf("Memory error\n"); return; } if(*head == NULL) *head = newNode; else { CLLNode *current = *head, *q; if(position == 0) { newNode->next = current; while(current->next != *head) { current = current->next; } current->next = newNode; *head = newNode; } else { int i = 0; while(current && i < position) { q = current; i++; current = current->next; } newNode->next = current; q->next = newNode; } } } void del(CLLNode **head, int position) { CLLNode *current = *head, *q; if (!current) { printf("List is empty\n"); return; } if(position == 0) { current = current->next; while(current != *head) { q = current; current = current->next; } } for (int i = 0; i < position; ++i) { q = current; current = current->next; } if(current == *head) { *head = (*head)->next; } q->next = current->next; delete(current); } void printList(CLLNode *head) { CLLNode *current = head; do { printf("%d -> ", current->data); current = current->next; } while(current != head); printf("\b\b\b \n"); // destructive backspace } int main() { CLLNode *head = getNode(1); insert(&head, 2, 0); insert(&head, 3, 0); insert(&head, 4, 0); printList(head); del(&head, 0); del(&head, 2); printList(head); return 0; }
Update circular linked list deletion
Update circular linked list deletion
C++
mit
divyanshu013/algorithm-journey
f2d5b9d5be56afa2c6ab102a7fb506ed8791bc23
clang-tidy/tool/ClangTidyMain.cpp
clang-tidy/tool/ClangTidyMain.cpp
//===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file This file implements a clang-tidy tool. /// /// This tool uses the Clang Tooling infrastructure, see /// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html /// for details on setting it up with LLVM source tree. /// //===----------------------------------------------------------------------===// #include "../ClangTidy.h" #include "clang/Driver/OptTable.h" #include "clang/Driver/Options.h" #include "llvm/Support/CommandLine.h" #include <vector> using namespace clang::ast_matchers; using namespace clang::driver; using namespace clang::tooling; using namespace llvm; cl::OptionCategory ClangTidyCategory("clang-tidy options"); cl::list<std::string> Ranges(cl::Positional, cl::desc("<range0> [... <rangeN>]"), cl::OneOrMore); static cl::opt<std::string> Checks( "checks", cl::desc("Regular expression matching the names of the checks to be run."), cl::init(".*"), cl::cat(ClangTidyCategory)); static cl::opt<bool> Fix("fix", cl::desc("Fix detected errors if possible."), cl::init(false), cl::cat(ClangTidyCategory)); // FIXME: Add option to list name/description of all checks. int main(int argc, const char **argv) { cl::ParseCommandLineOptions(argc, argv, "TBD\n"); OwningPtr<clang::tooling::CompilationDatabase> Compilations( FixedCompilationDatabase::loadFromCommandLine(argc, argv)); if (!Compilations) return 0; // FIXME: Load other compilation databases. SmallVector<clang::tidy::ClangTidyError, 16> Errors; clang::tidy::runClangTidy(Checks, *Compilations, Ranges, &Errors); clang::tidy::handleErrors(Errors, Fix); return 0; }
//===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file This file implements a clang-tidy tool. /// /// This tool uses the Clang Tooling infrastructure, see /// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html /// for details on setting it up with LLVM source tree. /// //===----------------------------------------------------------------------===// #include "../ClangTidy.h" #include "llvm/Option/OptTable.h" #include "llvm/Option/Option.h" #include "llvm/Support/CommandLine.h" #include <vector> using namespace clang::ast_matchers; using namespace clang::driver; using namespace clang::tooling; using namespace llvm; cl::OptionCategory ClangTidyCategory("clang-tidy options"); cl::list<std::string> Ranges(cl::Positional, cl::desc("<range0> [... <rangeN>]"), cl::OneOrMore); static cl::opt<std::string> Checks( "checks", cl::desc("Regular expression matching the names of the checks to be run."), cl::init(".*"), cl::cat(ClangTidyCategory)); static cl::opt<bool> Fix("fix", cl::desc("Fix detected errors if possible."), cl::init(false), cl::cat(ClangTidyCategory)); // FIXME: Add option to list name/description of all checks. int main(int argc, const char **argv) { cl::ParseCommandLineOptions(argc, argv, "TBD\n"); OwningPtr<clang::tooling::CompilationDatabase> Compilations( FixedCompilationDatabase::loadFromCommandLine(argc, argv)); if (!Compilations) return 0; // FIXME: Load other compilation databases. SmallVector<clang::tidy::ClangTidyError, 16> Errors; clang::tidy::runClangTidy(Checks, *Compilations, Ranges, &Errors); clang::tidy::handleErrors(Errors, Fix); return 0; }
Fix build error caused by r187345.
Fix build error caused by r187345. git-svn-id: a34e9779ed74578ad5922b3306b3d80a0c825546@187346 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra,llvm-mirror/clang-tools-extra
6dc519f65c1644be1f045c9dbab5251ccac16609
translator.cpp
translator.cpp
/****************************************************************************** * Copyright (C) 2016 Kitsune Ral <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "translator.h" #include "printer.h" #include "yaml.h" #include <regex> using namespace std; void addTypeAttributes(TypeUsage& typeUsage, const YamlMap& attributesMap) { for (const auto& attr: attributesMap) { auto attrName = attr.first.as<string>(); if (attrName == "type") continue; switch (attr.second.Type()) { case YAML::NodeType::Null: typeUsage.attributes.emplace(move(attrName), string{}); break; case YAML::NodeType::Scalar: typeUsage.attributes.emplace(move(attrName), attr.second.as<string>()); break; case YAML::NodeType::Sequence: if (const auto& seq = attr.second.asSequence()) typeUsage.lists.emplace(move(attrName), seq.asStrings()); break; default: throw YamlException(attr.second, "Malformed attribute"); } } } TypeUsage parseTargetType(const YamlNode& yamlTypeNode) { using YAML::NodeType; if (yamlTypeNode.Type() == NodeType::Null) return {}; if (yamlTypeNode.Type() == NodeType::Scalar) return TypeUsage(yamlTypeNode.as<string>()); const auto yamlTypeMap = yamlTypeNode.asMap(); TypeUsage typeUsage { yamlTypeMap["type"].as<string>("") }; addTypeAttributes(typeUsage, yamlTypeMap); return typeUsage; } TypeUsage parseTargetType(const YamlNode& yamlTypeNode, const YamlMap& commonAttributesYaml) { auto tu = parseTargetType(yamlTypeNode); addTypeAttributes(tu, commonAttributesYaml); return tu; } template <typename FnT> auto parseEntries(const YamlSequence& entriesYaml, const FnT& inserter, const YamlMap& commonAttributesYaml = {}) -> enable_if_t<is_void_v<decltype( inserter(string(), YamlNode(), YamlMap()))>> { for (const YamlMap typesBlockYaml: entriesYaml) // clazy:exclude=range-loop { switch (typesBlockYaml.size()) { case 0: throw YamlException(typesBlockYaml, "Empty type entry"); case 1: { const auto& typeYaml = typesBlockYaml.front(); inserter(typeYaml.first.as<string>(), typeYaml.second, commonAttributesYaml); break; } case 2: if (typesBlockYaml["+on"] && typesBlockYaml["+set"]) { parseEntries(typesBlockYaml.get("+on").asSequence(), inserter, typesBlockYaml.get("+set").asMap()); break; } [[fallthrough]]; default: throw YamlException(typesBlockYaml, "Too many entries in the map, check indentation"); } } } pair_vector_t<TypeUsage> parseTypeEntry(const YamlNode& targetTypeYaml, const YamlMap& commonAttributesYaml = {}) { switch (targetTypeYaml.Type()) { case YAML::NodeType::Scalar: // Use a type with no regard to format case YAML::NodeType::Map: // Same, with attributes for the target type { return { { {}, parseTargetType(targetTypeYaml, commonAttributesYaml) } }; } case YAML::NodeType::Sequence: // A list of formats for the type { pair_vector_t<TypeUsage> targetTypes; parseEntries(targetTypeYaml.asSequence(), [&targetTypes](string formatName, const YamlNode& typeYaml, const YamlMap& commonAttrsYaml) { if (formatName.empty()) formatName = "/"; // Empty format means all formats else if (formatName.size() > 1 && formatName.front() == '/' && formatName.back() == '/') { formatName.pop_back(); } targetTypes.emplace_back(move(formatName), parseTargetType(typeYaml, commonAttrsYaml)); }, commonAttributesYaml); return targetTypes; } default: throw YamlException(targetTypeYaml, "Malformed type entry"); } } pair_vector_t<string> loadStringMap(const YamlMap& yaml) { pair_vector_t<string> stringMap; for (const auto& subst: yaml) { auto pattern = subst.first.as<string>(); if (pattern.empty()) // [[unlikely]] clog << subst.first.location() << ": warning: empty pattern in substitutions, skipping" << endl; else if (pattern.size() > 1 && pattern.front() != '/' && pattern.back() == '/') // [[unlikely]] clog << subst.first.location() << ": warning: invalid regular expression, skipping" << endl << "(use a regex with \\/ to match strings beginning with /)"; else { if (pattern.front() == '/' && pattern.back() == '/') pattern.pop_back(); stringMap.emplace_back(pattern, subst.second.as<string>()); } } return stringMap; } Translator::Translator(const path& configFilePath, path outputDirPath, Verbosity verbosity) : _verbosity(verbosity), _outputDirPath(move(outputDirPath)) { cout << "Using config file at " << configFilePath << endl; const auto configY = YamlMap::loadFromFile(configFilePath); const auto& analyzerYaml = configY["analyzer"].asMap(); _substitutions = loadStringMap(analyzerYaml["subst"].asMap()); _identifiers = loadStringMap(analyzerYaml["identifiers"].asMap()); parseEntries(analyzerYaml["types"].asSequence(), [this](const string& name, const YamlNode& typeYaml, const YamlMap& commonAttrsYaml) { _typesMap.emplace_back(name, parseTypeEntry(typeYaml, commonAttrsYaml)); }); if (_verbosity == Verbosity::Debug) for (const auto& t : _typesMap) { clog << "Type " << t.first << ":" << endl; for (const auto& f : t.second) { clog << " Format " << (f.first.empty() ? "(none)" : f.first) << ":" << endl << " mapped to " << (!f.second.name.empty() ? f.second.name : "(none)") << endl; if (!f.second.attributes.empty()) { clog << " attributes:" << endl; for (const auto& a : f.second.attributes) clog << " " << a.first << " -> " << a.second << endl; } else clog << " no attributes" << endl; if (!f.second.lists.empty()) { clog << " lists:" << endl; for (const auto& l : f.second.lists) clog << " " << l.first << " (entries: " << l.second.size() << ")" << endl; } else clog << " no lists" << endl; } } Printer::context_type env; using namespace kainjow::mustache; const auto& mustacheYaml = configY["mustache"].asMap(); const auto& envYaml = mustacheYaml["constants"].asMap(); for (const auto& p: envYaml) { const auto pName = p.first.as<string>(); if (p.second.IsScalar()) { env.set(pName, p.second.as<string>()); continue; } const auto pDefinition = p.second.asMap().front(); const auto pType = pDefinition.first.as<string>(); const YamlNode defaultVal = pDefinition.second; if (pType == "set") env.set(pName, { data::type::list }); else if (pType == "bool") env.set(pName, { defaultVal.as<bool>() }); else env.set(pName, { defaultVal.as<string>() }); } const auto& partialsYaml = mustacheYaml["partials"].asMap(); for (const auto& p: partialsYaml) { env.set(p.first.as<string>(), partial { [s = p.second.as<string>()] { return s; } }); } const auto& templatesYaml = mustacheYaml["templates"].asMap(); for (auto [templates, nodeName]: { pair{ &_dataTemplates, "data" }, { &_apiTemplates, "api" } }) if (auto extToTemplatesYaml = templatesYaml[nodeName].asMap()) { templates->resize(extToTemplatesYaml.size()); transform(extToTemplatesYaml.begin(), extToTemplatesYaml.end(), templates->begin(), [](const YamlNodePair& p) { return make_pair(p.first.as<string>(), p.second.as<string>()); }); } _printer = make_unique<Printer>(move(env), configFilePath.parent_path(), mustacheYaml["outFilesList"].as<string>(""), *this); } Translator::~Translator() = default; string Translator::mapImport(const string& importBaseName) const { // This code makes quite a few assumptions as yet: // 1. That an import name is actually a file path (rather than some // language entity like in Python or Java). auto result = outputBaseDir() / importBaseName; // 2. That the imported file's extension (.h in C/C++) is // the first on the list, and that only data models can be imported. if (!_dataTemplates.empty()) result += _dataTemplates.front().first; return result.string(); } Translator::output_config_t Translator::outputConfig(const path& filePathBase, const Model& model) const { const auto fNameBase = outputBaseDir() / filePathBase; const auto& srcConfig = model.apiSpec == ApiSpec::JSONSchema ? _dataTemplates : _apiTemplates; output_config_t result; for (const auto& [fExtension, fTemplate]: srcConfig) result.emplace_back(path(fNameBase) += fExtension, fTemplate); return result; } TypeUsage Translator::mapType(const string& swaggerType, const string& swaggerFormat, const string& baseName) const { TypeUsage tu; for (const auto& swTypePair: _typesMap) if (swTypePair.first == swaggerType) for (const auto& swFormatPair: swTypePair.second) { const auto& swFormat = swFormatPair.first; if (swFormat == swaggerFormat || (!swFormat.empty() && swFormat.front() == '/' && regex_search(swaggerFormat, regex(++swFormat.begin(), swFormat.end())))) { // FIXME (#22): a source of great inefficiency. // TypeUsage should become a handle to an instance of // a newly-made TypeDefinition type that would own all // the stuff TypeUsage now has, except paramTypes tu = swFormatPair.second; goto conclusion; } } conclusion: // Fallback chain: baseName, swaggerFormat, swaggerType tu.baseName = baseName.empty() ? swaggerFormat.empty() ? swaggerType : swaggerFormat : baseName; return tu; } string Translator::mapIdentifier(const string& baseName, const Identifier* scope, bool required) const { auto scopedName = scope ? scope->qualifiedName() : string(); scopedName.append(1, '/').append(baseName); string newName = baseName; for (const auto& entry: _identifiers) { const auto& pattn = entry.first; if (!pattn.empty() && pattn.front() == '/') { auto&& replaced = regex_replace(scopedName, regex(++pattn.begin(), pattn.end()), entry.second); if (replaced != scopedName) { // cout << "Regex replace: " << scopedName << " -> " << replaced // << endl; newName = replaced; break; } } else if (pattn == baseName || pattn == scopedName) { newName = entry.second; break; } } if (newName.empty() && required) throw Exception( "Attempt to skip the required variable '" + baseName + "' - check 'identifiers' block in your gtad.yaml"); return newName; }
/****************************************************************************** * Copyright (C) 2016 Kitsune Ral <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "translator.h" #include "printer.h" #include "yaml.h" #include <regex> using namespace std; void addTypeAttributes(TypeUsage& typeUsage, const YamlMap& attributesMap) { for (const auto& attr: attributesMap) { auto attrName = attr.first.as<string>(); if (attrName == "type") continue; switch (attr.second.Type()) { case YAML::NodeType::Null: typeUsage.attributes.emplace(move(attrName), string{}); break; case YAML::NodeType::Scalar: typeUsage.attributes.emplace(move(attrName), attr.second.as<string>()); break; case YAML::NodeType::Sequence: if (const auto& seq = attr.second.asSequence()) typeUsage.lists.emplace(move(attrName), seq.asStrings()); break; default: throw YamlException(attr.second, "Malformed attribute"); } } } TypeUsage parseTargetType(const YamlNode& yamlTypeNode) { using YAML::NodeType; if (yamlTypeNode.Type() == NodeType::Null) return {}; if (yamlTypeNode.Type() == NodeType::Scalar) return TypeUsage(yamlTypeNode.as<string>()); const auto yamlTypeMap = yamlTypeNode.asMap(); TypeUsage typeUsage { yamlTypeMap["type"].as<string>("") }; addTypeAttributes(typeUsage, yamlTypeMap); return typeUsage; } TypeUsage parseTargetType(const YamlNode& yamlTypeNode, const YamlMap& commonAttributesYaml) { auto tu = parseTargetType(yamlTypeNode); addTypeAttributes(tu, commonAttributesYaml); return tu; } template <typename FnT> auto parseEntries(const YamlSequence& entriesYaml, const FnT& inserter, const YamlMap& commonAttributesYaml = {}) -> enable_if_t<is_void_v<decltype( inserter(string(), YamlNode(), YamlMap()))>> { for (const YamlMap typesBlockYaml: entriesYaml) // clazy:exclude=range-loop { switch (typesBlockYaml.size()) { case 0: throw YamlException(typesBlockYaml, "Empty type entry"); case 1: { const auto& typeYaml = typesBlockYaml.front(); inserter(typeYaml.first.as<string>(), typeYaml.second, commonAttributesYaml); break; } case 2: if (typesBlockYaml["+on"] && typesBlockYaml["+set"]) { // #56: merge into the outer common attributes // YamlMap constructors shallow-copy but we need a // one-level-deep copy here to revert to the previous set // after returning from recursion YamlMap newCommonAttributesYaml; // Instead of specialising struct convert<>, simply cast // to YAML::Node that already has a specialisation for (const auto& a : commonAttributesYaml) newCommonAttributesYaml.force_insert( static_cast<const YAML::Node&>(a.first), static_cast<const YAML::Node&>(a.second)); for (const auto& a : typesBlockYaml.get("+set").asMap()) newCommonAttributesYaml[a.first.as<string>()] = a.second; parseEntries(typesBlockYaml.get("+on").asSequence(), inserter, newCommonAttributesYaml); break; } [[fallthrough]]; default: throw YamlException(typesBlockYaml, "Too many entries in the map, check indentation"); } } } pair_vector_t<TypeUsage> parseTypeEntry(const YamlNode& targetTypeYaml, const YamlMap& commonAttributesYaml = {}) { switch (targetTypeYaml.Type()) { case YAML::NodeType::Scalar: // Use a type with no regard to format case YAML::NodeType::Map: // Same, with attributes for the target type { return { { {}, parseTargetType(targetTypeYaml, commonAttributesYaml) } }; } case YAML::NodeType::Sequence: // A list of formats for the type { pair_vector_t<TypeUsage> targetTypes; parseEntries(targetTypeYaml.asSequence(), [&targetTypes](string formatName, const YamlNode& typeYaml, const YamlMap& commonAttrsYaml) { if (formatName.empty()) formatName = "/"; // Empty format means all formats else if (formatName.size() > 1 && formatName.front() == '/' && formatName.back() == '/') { formatName.pop_back(); } targetTypes.emplace_back(move(formatName), parseTargetType(typeYaml, commonAttrsYaml)); }, commonAttributesYaml); return targetTypes; } default: throw YamlException(targetTypeYaml, "Malformed type entry"); } } pair_vector_t<string> loadStringMap(const YamlMap& yaml) { pair_vector_t<string> stringMap; for (const auto& subst: yaml) { auto pattern = subst.first.as<string>(); if (pattern.empty()) // [[unlikely]] clog << subst.first.location() << ": warning: empty pattern in substitutions, skipping" << endl; else if (pattern.size() > 1 && pattern.front() != '/' && pattern.back() == '/') // [[unlikely]] clog << subst.first.location() << ": warning: invalid regular expression, skipping" << endl << "(use a regex with \\/ to match strings beginning with /)"; else { if (pattern.front() == '/' && pattern.back() == '/') pattern.pop_back(); stringMap.emplace_back(pattern, subst.second.as<string>()); } } return stringMap; } Translator::Translator(const path& configFilePath, path outputDirPath, Verbosity verbosity) : _verbosity(verbosity), _outputDirPath(move(outputDirPath)) { cout << "Using config file at " << configFilePath << endl; const auto configY = YamlMap::loadFromFile(configFilePath); const auto& analyzerYaml = configY["analyzer"].asMap(); _substitutions = loadStringMap(analyzerYaml["subst"].asMap()); _identifiers = loadStringMap(analyzerYaml["identifiers"].asMap()); parseEntries(analyzerYaml["types"].asSequence(), [this](const string& name, const YamlNode& typeYaml, const YamlMap& commonAttrsYaml) { _typesMap.emplace_back(name, parseTypeEntry(typeYaml, commonAttrsYaml)); }); if (_verbosity == Verbosity::Debug) for (const auto& t : _typesMap) { clog << "Type " << t.first << ":" << endl; for (const auto& f : t.second) { clog << " Format " << (f.first.empty() ? "(none)" : f.first) << ":" << endl << " mapped to " << (!f.second.name.empty() ? f.second.name : "(none)") << endl; if (!f.second.attributes.empty()) { clog << " attributes:" << endl; for (const auto& a : f.second.attributes) clog << " " << a.first << " -> " << a.second << endl; } else clog << " no attributes" << endl; if (!f.second.lists.empty()) { clog << " lists:" << endl; for (const auto& l : f.second.lists) clog << " " << l.first << " (entries: " << l.second.size() << ")" << endl; } else clog << " no lists" << endl; } } Printer::context_type env; using namespace kainjow::mustache; const auto& mustacheYaml = configY["mustache"].asMap(); const auto& envYaml = mustacheYaml["constants"].asMap(); for (const auto& p: envYaml) { const auto pName = p.first.as<string>(); if (p.second.IsScalar()) { env.set(pName, p.second.as<string>()); continue; } const auto pDefinition = p.second.asMap().front(); const auto pType = pDefinition.first.as<string>(); const YamlNode defaultVal = pDefinition.second; if (pType == "set") env.set(pName, { data::type::list }); else if (pType == "bool") env.set(pName, { defaultVal.as<bool>() }); else env.set(pName, { defaultVal.as<string>() }); } const auto& partialsYaml = mustacheYaml["partials"].asMap(); for (const auto& p: partialsYaml) { env.set(p.first.as<string>(), partial { [s = p.second.as<string>()] { return s; } }); } const auto& templatesYaml = mustacheYaml["templates"].asMap(); for (auto [templates, nodeName]: { pair{ &_dataTemplates, "data" }, { &_apiTemplates, "api" } }) if (auto extToTemplatesYaml = templatesYaml[nodeName].asMap()) { templates->resize(extToTemplatesYaml.size()); transform(extToTemplatesYaml.begin(), extToTemplatesYaml.end(), templates->begin(), [](const YamlNodePair& p) { return make_pair(p.first.as<string>(), p.second.as<string>()); }); } _printer = make_unique<Printer>(move(env), configFilePath.parent_path(), mustacheYaml["outFilesList"].as<string>(""), *this); } Translator::~Translator() = default; string Translator::mapImport(const string& importBaseName) const { // This code makes quite a few assumptions as yet: // 1. That an import name is actually a file path (rather than some // language entity like in Python or Java). auto result = outputBaseDir() / importBaseName; // 2. That the imported file's extension (.h in C/C++) is // the first on the list, and that only data models can be imported. if (!_dataTemplates.empty()) result += _dataTemplates.front().first; return result.string(); } Translator::output_config_t Translator::outputConfig(const path& filePathBase, const Model& model) const { const auto fNameBase = outputBaseDir() / filePathBase; const auto& srcConfig = model.apiSpec == ApiSpec::JSONSchema ? _dataTemplates : _apiTemplates; output_config_t result; for (const auto& [fExtension, fTemplate]: srcConfig) result.emplace_back(path(fNameBase) += fExtension, fTemplate); return result; } TypeUsage Translator::mapType(const string& swaggerType, const string& swaggerFormat, const string& baseName) const { TypeUsage tu; for (const auto& swTypePair: _typesMap) if (swTypePair.first == swaggerType) for (const auto& swFormatPair: swTypePair.second) { const auto& swFormat = swFormatPair.first; if (swFormat == swaggerFormat || (!swFormat.empty() && swFormat.front() == '/' && regex_search(swaggerFormat, regex(++swFormat.begin(), swFormat.end())))) { // FIXME (#22): a source of great inefficiency. // TypeUsage should become a handle to an instance of // a newly-made TypeDefinition type that would own all // the stuff TypeUsage now has, except paramTypes tu = swFormatPair.second; goto conclusion; } } conclusion: // Fallback chain: baseName, swaggerFormat, swaggerType tu.baseName = baseName.empty() ? swaggerFormat.empty() ? swaggerType : swaggerFormat : baseName; return tu; } string Translator::mapIdentifier(const string& baseName, const Identifier* scope, bool required) const { auto scopedName = scope ? scope->qualifiedName() : string(); scopedName.append(1, '/').append(baseName); string newName = baseName; for (const auto& entry: _identifiers) { const auto& pattn = entry.first; if (!pattn.empty() && pattn.front() == '/') { auto&& replaced = regex_replace(scopedName, regex(++pattn.begin(), pattn.end()), entry.second); if (replaced != scopedName) { // cout << "Regex replace: " << scopedName << " -> " << replaced // << endl; newName = replaced; break; } } else if (pattn == baseName || pattn == scopedName) { newName = entry.second; break; } } if (newName.empty() && required) throw Exception( "Attempt to skip the required variable '" + baseName + "' - check 'identifiers' block in your gtad.yaml"); return newName; }
copy and merge common attributes when recursing
parseEntries(): copy and merge common attributes when recursing Closes #56.
C++
agpl-3.0
KitsuneRal/matrix-csapi-generator
6cf18cf425fd2dc51d890ddd039c2017c9d14004
include/mtac/DataFlowDomain.hpp
include/mtac/DataFlowDomain.hpp
//======================================================================= // Copyright Baptiste Wicht 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef MTAC_DATA_FLOW_DOMAIN_H #define MTAC_DATA_FLOW_DOMAIN_H #include <unordered_map> #include <unordered_set> #include <vector> #include <list> namespace eddic { namespace mtac { template<typename DomainValues> struct Domain { typedef DomainValues Values; boost::optional<DomainValues> int_values; Domain(){ //Nothing to init } Domain(DomainValues values) : int_values(values){ //Nothing to init } DomainValues& values(){ return *int_values; } bool top() const { return !int_values; } }; template<typename Key, typename Value, typename Hasher> struct Domain<std::unordered_map<Key, Value, Hasher>> { typedef std::unordered_map<Key, Value, Hasher> Values; boost::optional<Values> int_values; Domain(){ //Nothing to init } Domain(Values values) : int_values(values){ //Nothing to init } Values& values(){ return *int_values; } Value& operator[](Key key){ assert(int_values); return (*int_values)[key]; } auto begin() -> decltype((*int_values).begin()) { assert(int_values); return (*int_values).begin(); } auto end() -> decltype((*int_values).end()) { assert(int_values); return (*int_values).end(); } auto count(Key key) -> decltype((*int_values).count(key)) { assert(int_values); return (*int_values).count(key); } auto find(Key key) -> decltype((*int_values).find(key)) { assert(int_values); return (*int_values).find(key); } void erase(Key key){ assert(int_values); (*int_values).erase(key); } void clear(){ assert(int_values); (*int_values).clear(); } bool top() const { return !int_values; } }; template<typename DomainValues> std::ostream& operator<<(std::ostream& stream, Domain<DomainValues>& domain){ if(domain.top()){ return stream << "top"; } return stream << domain.values(); } template<typename T> std::ostream& operator<<(std::ostream& stream, std::vector<T>& values){ stream << "vector{"; for(auto& value : values){ stream << value << ", "; } return stream << "}"; } template<typename T> std::ostream& operator<<(std::ostream& stream, std::list<T>& values){ stream << "list{"; for(auto& value : values){ stream << value << ", "; } return stream << "}"; } template<typename Key, typename Value, typename Hasher> std::ostream& operator<<(std::ostream& stream, std::unordered_map<Key, Value, Hasher>& values){ stream << "map{"; for(auto& value : values){ stream << value.first << ":" << value.second << ", "; } return stream << "}"; } template<typename Value, typename Hasher> std::ostream& operator<<(std::ostream& stream, std::unordered_set<Value, Hasher>& values){ stream << "set{"; for(auto& value : values){ stream << value << ", "; } return stream << "}"; } } //end of mtac } //end of eddic #endif
//======================================================================= // Copyright Baptiste Wicht 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #ifndef MTAC_DATA_FLOW_DOMAIN_H #define MTAC_DATA_FLOW_DOMAIN_H #include <unordered_map> #include <unordered_set> #include <vector> #include <list> namespace eddic { namespace mtac { template<typename DomainValues> struct Domain { typedef DomainValues Values; boost::optional<DomainValues> int_values; Domain(){ //Nothing to init } Domain(DomainValues values) : int_values(values){ //Nothing to init } DomainValues& values(){ return *int_values; } bool top() const { return !int_values; } }; template<typename Key, typename Value, typename Hasher> struct Domain<std::unordered_map<Key, Value, Hasher>> { typedef std::unordered_map<Key, Value, Hasher> Values; boost::optional<Values> int_values; Domain(){ //Nothing to init } Domain(Values values) : int_values(values){ //Nothing to init } Values& values(){ return *int_values; } Value& operator[](Key key){ assert(int_values); return (*int_values)[key]; } auto begin() -> decltype((*int_values).begin()) { assert(int_values); return (*int_values).begin(); } auto end() -> decltype((*int_values).end()) { assert(int_values); return (*int_values).end(); } auto count(Key key) -> decltype((*int_values).count(key)) { assert(int_values); return (*int_values).count(key); } auto find(Key key) -> decltype((*int_values).find(key)) { assert(int_values); return (*int_values).find(key); } void erase(Key key){ assert(int_values); (*int_values).erase(key); } void clear(){ assert(int_values); (*int_values).clear(); } bool top() const { return !int_values; } }; template<typename T> std::ostream& operator<<(std::ostream& stream, std::vector<T>& values){ stream << "vector{"; for(auto& value : values){ stream << value << ", "; } return stream << "}"; } template<typename T> std::ostream& operator<<(std::ostream& stream, std::list<T>& values){ stream << "list{"; for(auto& value : values){ stream << value << ", "; } return stream << "}"; } template<typename Key, typename Value, typename Hasher> std::ostream& operator<<(std::ostream& stream, std::unordered_map<Key, Value, Hasher>& values){ stream << "map{"; for(auto& value : values){ stream << value.first << ":" << value.second << ", "; } return stream << "}"; } template<typename Value, typename Hasher> std::ostream& operator<<(std::ostream& stream, std::unordered_set<Value, Hasher>& values){ stream << "set{"; for(auto& value : values){ stream << value << ", "; } return stream << "}"; } template<typename DomainValues> std::ostream& operator<<(std::ostream& stream, Domain<DomainValues>& domain){ if(domain.top()){ return stream << "top"; } return stream << domain.values(); } } //end of mtac } //end of eddic #endif
Fix the order of the template functions
Fix the order of the template functions
C++
mit
vogelsgesang/eddic,wichtounet/eddic,wichtounet/eddic,vogelsgesang/eddic,vogelsgesang/eddic,wichtounet/eddic
30496fca8eff98fcf7ff715222013933b4f65dd0
src/common/pixelboost/graphics/renderer/primitive/primitiveRenderer.cpp
src/common/pixelboost/graphics/renderer/primitive/primitiveRenderer.cpp
#ifndef PIXELBOOST_DISABLE_GRAPHICS #include "glm/gtc/matrix_transform.hpp" #include "pixelboost/graphics/device/device.h" #include "pixelboost/graphics/device/indexBuffer.h" #include "pixelboost/graphics/device/program.h" #include "pixelboost/graphics/device/vertexBuffer.h" #include "pixelboost/graphics/renderer/common/renderer.h" #include "pixelboost/graphics/renderer/primitive/primitiveRenderer.h" #include "pixelboost/graphics/shader/shader.h" #include "pixelboost/graphics/shader/manager.h" using namespace pb; PrimitiveRenderable::PrimitiveRenderable(Uid entityUid) : Renderable(entityUid) , _Color(glm::vec4(1,1,1,1)) { } Uid PrimitiveRenderable::GetType() { return PrimitiveRenderable::GetStaticType(); } Uid PrimitiveRenderable::GetStaticType() { return TypeHash("pb::PrimitiveRenderable"); } Shader* PrimitiveRenderable::GetShader() { Shader* baseShader = Renderable::GetShader(); if (baseShader) return baseShader; return Renderer::Instance()->GetShaderManager()->GetShader("/data/shaders/pb_solid.shc"); } void PrimitiveRenderable::SetTransform(const glm::mat4x4& transform) { _Transform = transform; DirtyBounds(); DirtyWorldMatrix(); } glm::vec4 PrimitiveRenderable::GetColor() { return _Color; } void PrimitiveRenderable::SetColor(glm::vec4 color) { _Color = color; } PrimitiveRenderableEllipse::PrimitiveRenderableEllipse(Uid entityUid) : PrimitiveRenderable(entityUid) , _Solid(false) { } void PrimitiveRenderableEllipse::CalculateBounds() { BoundingSphere bounds; glm::vec4 position = GetWorldMatrix() * glm::vec4(0,0,0,1); bounds.Set(glm::vec3(position.x, position.y, position.z), glm::max(_Size.x, _Size.y)); SetBounds(bounds); } void PrimitiveRenderableEllipse::CalculateWorldMatrix() { glm::mat4x4 worldMatrix = glm::translate(glm::mat4x4(), _Position); worldMatrix = glm::scale(worldMatrix, glm::vec3(_Size, 1)); worldMatrix = glm::rotate(worldMatrix, _Rotation[0], glm::vec3(1,0,0)); worldMatrix = glm::rotate(worldMatrix, _Rotation[1], glm::vec3(0,1,0)); worldMatrix = glm::rotate(worldMatrix, _Rotation[2], glm::vec3(0,0,1)); worldMatrix = _Transform * worldMatrix; SetWorldMatrix(worldMatrix); } PrimitiveRenderable::Type PrimitiveRenderableEllipse::GetPrimitiveType() { return kTypeEllipse; } bool PrimitiveRenderableEllipse::GetSolid() { return _Solid; } void PrimitiveRenderableEllipse::SetSolid(bool solid) { _Solid = solid; } glm::vec3 PrimitiveRenderableEllipse::GetPosition() { return _Position; } void PrimitiveRenderableEllipse::SetPosition(glm::vec3 position) { _Position = position; DirtyBounds(); DirtyWorldMatrix(); } glm::vec3 PrimitiveRenderableEllipse::GetRotation() { return _Rotation; } void PrimitiveRenderableEllipse::SetRotation(glm::vec3 rotation) { _Rotation = rotation; DirtyWorldMatrix(); } glm::vec2 PrimitiveRenderableEllipse::GetSize() { return _Size; } void PrimitiveRenderableEllipse::SetSize(glm::vec2 size) { _Size = size; DirtyBounds(); DirtyWorldMatrix(); } PrimitiveRenderableLine::PrimitiveRenderableLine(Uid entityUid) : PrimitiveRenderable(entityUid) { } void PrimitiveRenderableLine::CalculateBounds() { BoundingSphere bounds((_Start+_End)/2.f, glm::distance(_Start, _End)/2.f); SetBounds(bounds); } void PrimitiveRenderableLine::CalculateWorldMatrix() { SetWorldMatrix(glm::mat4x4()); } PrimitiveRenderable::Type PrimitiveRenderableLine::GetPrimitiveType() { return kTypeLine; } glm::vec3 PrimitiveRenderableLine::GetStart() { return _Start; } void PrimitiveRenderableLine::SetStart(glm::vec3 start) { _Start = start; DirtyBounds(); } glm::vec3 PrimitiveRenderableLine::GetEnd() { return _End; } void PrimitiveRenderableLine::SetEnd(glm::vec3 end) { _End = end; DirtyBounds(); } PrimitiveRenderableRectangle::PrimitiveRenderableRectangle(Uid entityUid) : PrimitiveRenderable(entityUid) , _Solid(false) { } void PrimitiveRenderableRectangle::CalculateBounds() { glm::vec4 position = GetWorldMatrix()[3]; BoundingSphere bounds(glm::vec3(position.x, position.y, position.z), glm::max(_Size.x, _Size.y)); SetBounds(bounds); } void PrimitiveRenderableRectangle::CalculateWorldMatrix() { glm::mat4x4 worldMatrix = glm::scale(glm::mat4x4(), glm::vec3(_Size, 1)); worldMatrix = _Transform * worldMatrix; SetWorldMatrix(worldMatrix); } PrimitiveRenderable::Type PrimitiveRenderableRectangle::GetPrimitiveType() { return kTypeRectangle; } bool PrimitiveRenderableRectangle::GetSolid() { return _Solid; } void PrimitiveRenderableRectangle::SetSolid(bool solid) { _Solid = solid; } glm::vec2 PrimitiveRenderableRectangle::GetSize() { return _Size; } void PrimitiveRenderableRectangle::SetSize(glm::vec2 size) { _Size = size; DirtyWorldMatrix(); } PrimitiveRenderer::PrimitiveRenderer() { { _BoxIndexBuffer = GraphicsDevice::Instance()->CreateIndexBuffer(kBufferFormatStatic, 6); _BoxVertexBuffer = GraphicsDevice::Instance()->CreateVertexBuffer(kBufferFormatStatic, kVertexFormat_P_XYZ, 4); _BoxIndexBuffer->Lock(); unsigned short* indicies = _BoxIndexBuffer->GetData(); indicies[0] = 0; indicies[1] = 1; indicies[2] = 2; indicies[3] = 3; indicies[4] = 2; indicies[5] = 0; _BoxIndexBuffer->Unlock(); _BoxVertexBuffer->Lock(); Vertex_PXYZ* vertices = static_cast<Vertex_PXYZ*>(_BoxVertexBuffer->GetData()); vertices[0].position[0] = -0.5; vertices[0].position[1] = -0.5; vertices[0].position[2] = 0; vertices[1].position[0] = -0.5; vertices[1].position[1] = 0.5; vertices[1].position[2] = 0; vertices[2].position[0] = 0.5; vertices[2].position[1] = 0.5; vertices[2].position[2] = 0; vertices[3].position[0] = 0.5; vertices[3].position[1] = -0.5; vertices[3].position[2] = 0; _BoxVertexBuffer->Unlock(); } { _EllipseIndexBuffer = GraphicsDevice::Instance()->CreateIndexBuffer(kBufferFormatStatic, 32); _EllipseVertexBuffer = GraphicsDevice::Instance()->CreateVertexBuffer(kBufferFormatStatic, kVertexFormat_P_XYZ, 32); _EllipseIndexBuffer->Lock(); _EllipseVertexBuffer->Lock(); unsigned short* indices = _EllipseIndexBuffer->GetData(); Vertex_PXYZ* vertices = static_cast<Vertex_PXYZ*>(_EllipseVertexBuffer->GetData()); float angle = 0.f; float step = M_PI * 2.f / 32.f; for (int i=0; i<32; i++) { indices[i] = i; vertices[i].position[0] = cos(angle); vertices[i].position[1] = sin(angle); vertices[i].position[2] = 0.f; angle += step; } _EllipseIndexBuffer->Unlock(); _EllipseVertexBuffer->Unlock(); } { _LineIndexBuffer = GraphicsDevice::Instance()->CreateIndexBuffer(kBufferFormatStatic, 2); _LineVertexBuffer = GraphicsDevice::Instance()->CreateVertexBuffer(kBufferFormatStatic, kVertexFormat_P_XYZ, 2); _LineIndexBuffer->Lock(); unsigned short* indexBuffer = _LineIndexBuffer->GetData(); indexBuffer[0] = 0; indexBuffer[1] = 1; _LineIndexBuffer->Unlock(); } Renderer::Instance()->SetHandler(PrimitiveRenderable::GetStaticType(), this); Renderer::Instance()->GetShaderManager()->LoadShader("/data/shaders/pb_solid.shc"); } PrimitiveRenderer::~PrimitiveRenderer() { Renderer::Instance()->GetShaderManager()->UnloadShader("/data/shaders/pb_solid.shc"); } void PrimitiveRenderer::Render(int count, Renderable** renderables, Viewport* viewport, ShaderPass* shaderPass) { GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateDepthTest, false); GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateTexture2D, false); GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateBlend, true); #ifdef PIXELBOOST_GRAPHICS_PREMULTIPLIED_ALPHA GraphicsDevice::Instance()->SetBlendMode(GraphicsDevice::kBlendSourceAlpha, GraphicsDevice::kBlendOneMinusSourceAlpha); #else GraphicsDevice::Instance()->SetBlendMode(GraphicsDevice::kBlendOne, GraphicsDevice::kBlendOneMinusSourceAlpha); #endif for (int i=0; i < count; i++) { PrimitiveRenderable& primitive = *static_cast<PrimitiveRenderable*>(renderables[i]); shaderPass->GetShaderProgram()->SetUniform("_DiffuseColor", primitive._Color); shaderPass->GetShaderProgram()->SetUniform("PB_ModelViewProj", primitive.GetMVP()); switch (primitive.GetPrimitiveType()) { case PrimitiveRenderable::kTypeEllipse: { PrimitiveRenderableEllipse& ellipse = static_cast<PrimitiveRenderableEllipse&>(primitive); GraphicsDevice::Instance()->BindIndexBuffer(_EllipseIndexBuffer); GraphicsDevice::Instance()->BindVertexBuffer(_EllipseVertexBuffer); if (!ellipse._Solid) GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementLineLoop, 32); else GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementTriangleFan, 32); GraphicsDevice::Instance()->BindIndexBuffer(0); GraphicsDevice::Instance()->BindVertexBuffer(0); break; break; } case PrimitiveRenderable::kTypeRectangle: { PrimitiveRenderableRectangle& rectangle = static_cast<PrimitiveRenderableRectangle&>(primitive); GraphicsDevice::Instance()->BindIndexBuffer(_BoxIndexBuffer); GraphicsDevice::Instance()->BindVertexBuffer(_BoxVertexBuffer); if (!rectangle._Solid) GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementLineLoop, 4); else GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementTriangles, 6); GraphicsDevice::Instance()->BindIndexBuffer(0); GraphicsDevice::Instance()->BindVertexBuffer(0); break; } case PrimitiveRenderable::kTypeLine: { PrimitiveRenderableLine& line = static_cast<PrimitiveRenderableLine&>(primitive); _LineVertexBuffer->Lock(); Vertex_PXYZ* vertices = static_cast<Vertex_PXYZ*>(_LineVertexBuffer->GetData()); vertices[0].position[0] = line._Start[0]; vertices[0].position[1] = line._Start[1]; vertices[0].position[2] = line._Start[2]; vertices[1].position[0] = line._End[0]; vertices[1].position[1] = line._End[1]; vertices[1].position[2] = line._End[2]; _LineVertexBuffer->Unlock(); GraphicsDevice::Instance()->BindIndexBuffer(_LineIndexBuffer); GraphicsDevice::Instance()->BindVertexBuffer(_LineVertexBuffer); GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementLines, 2); GraphicsDevice::Instance()->BindIndexBuffer(0); GraphicsDevice::Instance()->BindVertexBuffer(0); break; } } } GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateDepthTest, false); GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateTexture2D, false); GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateBlend, false); } #endif
#ifndef PIXELBOOST_DISABLE_GRAPHICS #include "glm/gtc/matrix_transform.hpp" #include "pixelboost/graphics/device/device.h" #include "pixelboost/graphics/device/indexBuffer.h" #include "pixelboost/graphics/device/program.h" #include "pixelboost/graphics/device/vertexBuffer.h" #include "pixelboost/graphics/renderer/common/renderer.h" #include "pixelboost/graphics/renderer/primitive/primitiveRenderer.h" #include "pixelboost/graphics/shader/shader.h" #include "pixelboost/graphics/shader/manager.h" using namespace pb; PrimitiveRenderable::PrimitiveRenderable(Uid entityUid) : Renderable(entityUid) , _Color(glm::vec4(1,1,1,1)) { } Uid PrimitiveRenderable::GetType() { return PrimitiveRenderable::GetStaticType(); } Uid PrimitiveRenderable::GetStaticType() { return TypeHash("pb::PrimitiveRenderable"); } Shader* PrimitiveRenderable::GetShader() { Shader* baseShader = Renderable::GetShader(); if (baseShader) return baseShader; return Renderer::Instance()->GetShaderManager()->GetShader("/data/shaders/pb_solid.shc"); } void PrimitiveRenderable::SetTransform(const glm::mat4x4& transform) { _Transform = transform; DirtyBounds(); DirtyWorldMatrix(); } glm::vec4 PrimitiveRenderable::GetColor() { return _Color; } void PrimitiveRenderable::SetColor(glm::vec4 color) { _Color = color; } PrimitiveRenderableEllipse::PrimitiveRenderableEllipse(Uid entityUid) : PrimitiveRenderable(entityUid) , _Solid(false) { } void PrimitiveRenderableEllipse::CalculateBounds() { BoundingSphere bounds; glm::vec4 position = GetWorldMatrix() * glm::vec4(0,0,0,1); bounds.Set(glm::vec3(position.x, position.y, position.z), glm::max(_Size.x, _Size.y)); SetBounds(bounds); } void PrimitiveRenderableEllipse::CalculateWorldMatrix() { glm::mat4x4 worldMatrix = glm::translate(glm::mat4x4(), _Position); worldMatrix = glm::scale(worldMatrix, glm::vec3(_Size, 1)); worldMatrix = glm::rotate(worldMatrix, _Rotation[0], glm::vec3(1,0,0)); worldMatrix = glm::rotate(worldMatrix, _Rotation[1], glm::vec3(0,1,0)); worldMatrix = glm::rotate(worldMatrix, _Rotation[2], glm::vec3(0,0,1)); worldMatrix = _Transform * worldMatrix; SetWorldMatrix(worldMatrix); } PrimitiveRenderable::Type PrimitiveRenderableEllipse::GetPrimitiveType() { return kTypeEllipse; } bool PrimitiveRenderableEllipse::GetSolid() { return _Solid; } void PrimitiveRenderableEllipse::SetSolid(bool solid) { _Solid = solid; } glm::vec3 PrimitiveRenderableEllipse::GetPosition() { return _Position; } void PrimitiveRenderableEllipse::SetPosition(glm::vec3 position) { _Position = position; DirtyBounds(); DirtyWorldMatrix(); } glm::vec3 PrimitiveRenderableEllipse::GetRotation() { return _Rotation; } void PrimitiveRenderableEllipse::SetRotation(glm::vec3 rotation) { _Rotation = rotation; DirtyWorldMatrix(); } glm::vec2 PrimitiveRenderableEllipse::GetSize() { return _Size; } void PrimitiveRenderableEllipse::SetSize(glm::vec2 size) { _Size = size; DirtyBounds(); DirtyWorldMatrix(); } PrimitiveRenderableLine::PrimitiveRenderableLine(Uid entityUid) : PrimitiveRenderable(entityUid) { } void PrimitiveRenderableLine::CalculateBounds() { BoundingSphere bounds((_Start+_End)/2.f, glm::distance(_Start, _End)/2.f); SetBounds(bounds); } void PrimitiveRenderableLine::CalculateWorldMatrix() { SetWorldMatrix(glm::mat4x4()); } PrimitiveRenderable::Type PrimitiveRenderableLine::GetPrimitiveType() { return kTypeLine; } glm::vec3 PrimitiveRenderableLine::GetStart() { return _Start; } void PrimitiveRenderableLine::SetStart(glm::vec3 start) { _Start = start; DirtyBounds(); } glm::vec3 PrimitiveRenderableLine::GetEnd() { return _End; } void PrimitiveRenderableLine::SetEnd(glm::vec3 end) { _End = end; DirtyBounds(); } PrimitiveRenderableRectangle::PrimitiveRenderableRectangle(Uid entityUid) : PrimitiveRenderable(entityUid) , _Solid(false) { } void PrimitiveRenderableRectangle::CalculateBounds() { glm::vec4 position = GetWorldMatrix()[3]; BoundingSphere bounds(glm::vec3(position.x, position.y, position.z), glm::max(_Size.x, _Size.y)); SetBounds(bounds); } void PrimitiveRenderableRectangle::CalculateWorldMatrix() { glm::mat4x4 worldMatrix = glm::scale(glm::mat4x4(), glm::vec3(_Size, 1)); worldMatrix = _Transform * worldMatrix; SetWorldMatrix(worldMatrix); } PrimitiveRenderable::Type PrimitiveRenderableRectangle::GetPrimitiveType() { return kTypeRectangle; } bool PrimitiveRenderableRectangle::GetSolid() { return _Solid; } void PrimitiveRenderableRectangle::SetSolid(bool solid) { _Solid = solid; } glm::vec2 PrimitiveRenderableRectangle::GetSize() { return _Size; } void PrimitiveRenderableRectangle::SetSize(glm::vec2 size) { _Size = size; DirtyWorldMatrix(); } PrimitiveRenderer::PrimitiveRenderer() { { _BoxIndexBuffer = GraphicsDevice::Instance()->CreateIndexBuffer(kBufferFormatStatic, 6); _BoxVertexBuffer = GraphicsDevice::Instance()->CreateVertexBuffer(kBufferFormatStatic, kVertexFormat_P_XYZ, 4); _BoxIndexBuffer->Lock(); unsigned short* indicies = _BoxIndexBuffer->GetData(); indicies[0] = 0; indicies[1] = 1; indicies[2] = 2; indicies[3] = 3; indicies[4] = 2; indicies[5] = 0; _BoxIndexBuffer->Unlock(); _BoxVertexBuffer->Lock(); Vertex_PXYZ* vertices = static_cast<Vertex_PXYZ*>(_BoxVertexBuffer->GetData()); vertices[0].position[0] = -0.5; vertices[0].position[1] = -0.5; vertices[0].position[2] = 0; vertices[1].position[0] = -0.5; vertices[1].position[1] = 0.5; vertices[1].position[2] = 0; vertices[2].position[0] = 0.5; vertices[2].position[1] = 0.5; vertices[2].position[2] = 0; vertices[3].position[0] = 0.5; vertices[3].position[1] = -0.5; vertices[3].position[2] = 0; _BoxVertexBuffer->Unlock(); } { _EllipseIndexBuffer = GraphicsDevice::Instance()->CreateIndexBuffer(kBufferFormatStatic, 32); _EllipseVertexBuffer = GraphicsDevice::Instance()->CreateVertexBuffer(kBufferFormatStatic, kVertexFormat_P_XYZ, 32); _EllipseIndexBuffer->Lock(); _EllipseVertexBuffer->Lock(); unsigned short* indices = _EllipseIndexBuffer->GetData(); Vertex_PXYZ* vertices = static_cast<Vertex_PXYZ*>(_EllipseVertexBuffer->GetData()); float angle = 0.f; float step = M_PI * 2.f / 32.f; for (int i=0; i<32; i++) { indices[i] = i; vertices[i].position[0] = cos(angle); vertices[i].position[1] = sin(angle); vertices[i].position[2] = 0.f; angle += step; } _EllipseIndexBuffer->Unlock(); _EllipseVertexBuffer->Unlock(); } { _LineIndexBuffer = GraphicsDevice::Instance()->CreateIndexBuffer(kBufferFormatStatic, 2); _LineVertexBuffer = GraphicsDevice::Instance()->CreateVertexBuffer(kBufferFormatStatic, kVertexFormat_P_XYZ, 2); _LineIndexBuffer->Lock(); unsigned short* indexBuffer = _LineIndexBuffer->GetData(); indexBuffer[0] = 0; indexBuffer[1] = 1; _LineIndexBuffer->Unlock(); } Renderer::Instance()->SetHandler(PrimitiveRenderable::GetStaticType(), this); Renderer::Instance()->GetShaderManager()->LoadShader("/data/shaders/pb_solid.shc"); } PrimitiveRenderer::~PrimitiveRenderer() { Renderer::Instance()->GetShaderManager()->UnloadShader("/data/shaders/pb_solid.shc"); } void PrimitiveRenderer::Render(int count, Renderable** renderables, Viewport* viewport, ShaderPass* shaderPass) { GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateDepthTest, false); GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateTexture2D, false); GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateBlend, true); #ifdef PIXELBOOST_GRAPHICS_PREMULTIPLIED_ALPHA GraphicsDevice::Instance()->SetBlendMode(GraphicsDevice::kBlendSourceAlpha, GraphicsDevice::kBlendOneMinusSourceAlpha); #else GraphicsDevice::Instance()->SetBlendMode(GraphicsDevice::kBlendOne, GraphicsDevice::kBlendOneMinusSourceAlpha); #endif for (int i=0; i < count; i++) { PrimitiveRenderable& primitive = *static_cast<PrimitiveRenderable*>(renderables[i]); shaderPass->GetShaderProgram()->SetUniform("_DiffuseColor", primitive._Color); shaderPass->GetShaderProgram()->SetUniform("PB_ModelViewProj", primitive.GetMVP()); switch (primitive.GetPrimitiveType()) { case PrimitiveRenderable::kTypeEllipse: { PrimitiveRenderableEllipse& ellipse = static_cast<PrimitiveRenderableEllipse&>(primitive); GraphicsDevice::Instance()->BindIndexBuffer(_EllipseIndexBuffer); GraphicsDevice::Instance()->BindVertexBuffer(_EllipseVertexBuffer); if (!ellipse._Solid) GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementLineLoop, 32); else GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementTriangleFan, 32); GraphicsDevice::Instance()->BindIndexBuffer(0); GraphicsDevice::Instance()->BindVertexBuffer(0); break; } case PrimitiveRenderable::kTypeRectangle: { PrimitiveRenderableRectangle& rectangle = static_cast<PrimitiveRenderableRectangle&>(primitive); GraphicsDevice::Instance()->BindIndexBuffer(_BoxIndexBuffer); GraphicsDevice::Instance()->BindVertexBuffer(_BoxVertexBuffer); if (!rectangle._Solid) GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementLineLoop, 4); else GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementTriangles, 6); GraphicsDevice::Instance()->BindIndexBuffer(0); GraphicsDevice::Instance()->BindVertexBuffer(0); break; } case PrimitiveRenderable::kTypeLine: { PrimitiveRenderableLine& line = static_cast<PrimitiveRenderableLine&>(primitive); _LineVertexBuffer->Lock(); Vertex_PXYZ* vertices = static_cast<Vertex_PXYZ*>(_LineVertexBuffer->GetData()); vertices[0].position[0] = line._Start[0]; vertices[0].position[1] = line._Start[1]; vertices[0].position[2] = line._Start[2]; vertices[1].position[0] = line._End[0]; vertices[1].position[1] = line._End[1]; vertices[1].position[2] = line._End[2]; _LineVertexBuffer->Unlock(); GraphicsDevice::Instance()->BindIndexBuffer(_LineIndexBuffer); GraphicsDevice::Instance()->BindVertexBuffer(_LineVertexBuffer); GraphicsDevice::Instance()->DrawElements(GraphicsDevice::kElementLines, 2); GraphicsDevice::Instance()->BindIndexBuffer(0); GraphicsDevice::Instance()->BindVertexBuffer(0); break; } } } GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateDepthTest, false); GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateTexture2D, false); GraphicsDevice::Instance()->SetState(GraphicsDevice::kStateBlend, false); } #endif
Remove redundant breakpoint
Remove redundant breakpoint
C++
mit
pixelballoon/pixelboost,pixelballoon/pixelboost,pixelballoon/pixelboost,pixelballoon/pixelboost,pixelballoon/pixelboost
ac885200987dae1ffb807a5dd582fc650555bec5
include/vsmc/utility/stdtbb.hpp
include/vsmc/utility/stdtbb.hpp
#ifndef VSMC_UTILITY_STDTBB_HPP #define VSMC_UTILITY_STDTBB_HPP #include <atomic> #include <cstdlib> #include <functional> #include <memory> #include <numeric> #include <utility> #include <thread> #include <vector> #include <vsmc/internal/config.hpp> #include <vsmc/internal/assert.hpp> #include <vsmc/internal/defines.hpp> #include <vsmc/internal/forward.hpp> #if VSMC_HAS_CXX11LIB_FUTURE #include <future> #endif namespace vsmc { namespace thread { /// \brief Blocked range /// \ingroup STDTBB template <typename SizeType> class BlockedRange { public : typedef SizeType size_type; BlockedRange (size_type begin, size_type end) : begin_(begin), end_(end) { VSMC_RUNTIME_ASSERT((begin < end), "INVALID RANG **BlockedRange**"); } size_type begin () const { return begin_; } size_type end () const { return end_; } private : size_type begin_; size_type end_; }; // class BlockedRange /// \brief C++11 Thread safe lock-based stack /// \ingroup STDTBB template <typename T> class LockBasedStack { }; // class LockBasedStack /// \brief C++11 Thread safe lock-free stack /// \ingroup STDTBB template <typename T> class LockFreeStack { }; // class LockFreeStack /// \brief C++11 Thread safe lock-based queue /// \ingroup STDTBB template <typename T> class LockBasedQueue { }; // class LockBasedQuque /// \brief C++11 Thread safe lock-free queue /// \ingroup STDTBB template <typename T> class LockFreeQueue { }; // class LockFreeQueue /// \brief C++11 Thread guard /// \ingroup STDTBB class ThreadGuard { #if VSMC_HAS_CXX11_DELETED_FUNCTIONS public : ThreadGuard (const ThreadGuard &) = delete; ThreadGuard &operator= (const ThreadGuard &) = delete; #else private : ThreadGuard (const ThreadGuard &); ThreadGuard &operator= (const ThreadGuard &); #endif public : ThreadGuard () VSMC_NOEXCEPT {} ThreadGuard (ThreadGuard &&other) VSMC_NOEXCEPT : thread_(std::move(other.thread_)) {} ThreadGuard &operator= (ThreadGuard &&other) VSMC_NOEXCEPT { thread_ = std::move(other.thread_); return *this; } ThreadGuard (std::thread &&thr) VSMC_NOEXCEPT : thread_(std::move(thr)) {} ~ThreadGuard () VSMC_NOEXCEPT { if (thread_.joinable()) thread_.join(); } private : std::thread thread_; }; // class ThreadGuard /// \brief C++11 Thread informations /// \ingroup STDTBB class ThreadInfo { public : static ThreadInfo &instance () { static ThreadInfo info; return info; } unsigned thread_num () const { return thread_num_; } void thread_num (unsigned num) { thread_num_ = num; } template <typename SizeType> std::vector<BlockedRange<SizeType> > partition ( const BlockedRange<SizeType> &range) const { SizeType N = range.end() - range.begin(); SizeType tn = static_cast<SizeType>(thread_num()); SizeType block_size = 0; if (N < tn) block_size = 1; else if (N % tn) block_size = N / tn + 1; else block_size = N / tn; std::vector<BlockedRange<SizeType> > range_vec; range_vec.reserve(thread_num()); SizeType B = range.begin(); while (N > 0) { SizeType next = std::min VSMC_MINMAX_NO_EXPANSION ( N, block_size); range_vec.push_back(BlockedRange<SizeType>(B, B + next)); B += next; N -= next; } VSMC_RUNTIME_ASSERT((range_vec.back().end() == range.end()), "INVALID PARTITION **ThreadInfo::partition**"); return range_vec; } private : unsigned thread_num_; ThreadInfo () : thread_num_(std::max VSMC_MINMAX_NO_EXPANSION (1U, static_cast<unsigned>(std::thread::hardware_concurrency()))) { #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4996) #endif const char *num_str = std::getenv("VSMC_STD_NUM_THREADS"); #ifdef _MSC_VER #pragma warning(pop) #endif if (num_str) { unsigned num = std::atoi(num_str); if (num) thread_num_ = num; } } ThreadInfo (const ThreadInfo &); ThreadInfo &operator= (const ThreadInfo &); }; // class ThreadInfo /// \brief C++11 Thread pool /// \ingroup STDTBB class ThreadPool { public : static ThreadPool &instance () { static ThreadPool pool; return pool; } void submit (); void barrier (); private : ThreadPool (); ThreadPool (const ThreadPool &); ThreadPool &operator= (const ThreadPool &); }; // class ThreadPool /// \brief Parallel for using C++11 thread /// \ingroup STDTBB /// /// \details /// Requirement: WorkType: /// void work (const thread::BlockedRange<size_type> &range); template <typename SizeType, typename WorkType> void parallel_for (const BlockedRange<SizeType> &range, WorkType &&work) { std::vector<BlockedRange<SizeType> > range_vec( ThreadInfo::instance().partition(range)); #if VSMC_HAS_CXX11LIB_FUTURE std::vector<std::future<void> > wg; for (typename std::vector<BlockedRange<SizeType> >::iterator r = range_vec.begin(); r != range_vec.end(); ++r) { wg.push_back(std::async(std::forward<WorkType>(work), *r)); } for (std::vector<std::future<void> >::iterator w = wg.begin(); w != wg.end(); ++w) { w->get(); } #else // start parallelization { std::vector<ThreadGuard> tg; for (typename std::vector<BlockedRange<SizeType> >::iterator r = range_vec.begin(); r != range_vec.end(); ++r) { tg.push_back(ThreadGuard(std::thread(std::forward<WorkType>(work), *r))); } } // stop parallelization #endif } /// \brief Parallel accumulate using C++11 thread /// \ingroup STDTBB /// /// \details /// Requirement: WorkType: /// void work (const thread::BlockedRange<size_type> &range, T &res); template <typename SizeType, typename T, typename WorkType> T parallel_accumulate (const BlockedRange<SizeType> &range, WorkType &&work, T init) { std::vector<BlockedRange<SizeType> > range_vec( ThreadInfo::instance().partition(range)); std::vector<T> result(range_vec.size()); unsigned i = 0; #if VSMC_HAS_CXX11LIB_FUTURE std::vector<std::future<void> > wg; for (typename std::vector<BlockedRange<SizeType> >::iterator r = range_vec.begin(); r != range_vec.end(); ++r, ++i) { wg.push_back(std::async(std::forward<WorkType>(work), *r, std::ref(result[i]))); } for (std::vector<std::future<void> >::iterator w = wg.begin(); w != wg.end(); ++w) { w->get(); } #else // start parallelization { std::vector<ThreadGuard> tg; for (typename std::vector<BlockedRange<SizeType> >::iterator r = range_vec.begin(); r != range_vec.end(); ++r, ++i) { tg.push_back(ThreadGuard(std::thread(std::forward<WorkType>(work), *r, std::ref(result[i])))); } } // stop parallelization #endif return std::accumulate(result.begin(), result.end(), init); } /// \brief Parallel accumulate using C++11 thread /// \ingroup STDTBB /// /// \details /// Requirement: WorkType: /// void work (const thread::BlockedRange<size_type> &range, T &res); template <typename SizeType, typename T, typename BinOp, typename WorkType> T parallel_accumulate (const BlockedRange<SizeType> &range, WorkType &&work, T init, BinOp bin_op) { std::vector<BlockedRange<SizeType> > range_vec( ThreadInfo::instance().partition(range)); std::vector<T> result(range_vec.size()); unsigned i =0; #if VSMC_HAS_CXX11LIB_FUTURE std::vector<std::future<void> > wg; for (typename std::vector<BlockedRange<SizeType> >::iterator r = range_vec.begin(); r != range_vec.end(); ++r, ++i) { wg.push_back(std::async(std::forward<WorkType>(work), *r, std::ref(result[i]))); } for (std::vector<std::future<void> >::iterator w = wg.begin(); w != wg.end(); ++w) { w->get(); } #else // start parallelization { std::vector<ThreadGuard> tg; for (typename std::vector<BlockedRange<SizeType> >::iterator r = range_vec.begin(); r != range_vec.end(); ++r, ++i) { tg.push_back(ThreadGuard(std::thread(std::forward<WorkType>(work), *r, std::ref(result[i])))); } } // stop parallelization #endif return std::accumulate(result.begin(), result.end(), init, bin_op); } } } // namespace vsmc::thread #endif // VSMC_UTILITY_STDTBB_HPP
#ifndef VSMC_UTILITY_STDTBB_HPP #define VSMC_UTILITY_STDTBB_HPP #include <atomic> #include <cstdlib> #include <functional> #include <memory> #include <numeric> #include <utility> #include <thread> #include <vector> #include <vsmc/internal/config.hpp> #include <vsmc/internal/assert.hpp> #include <vsmc/internal/defines.hpp> #include <vsmc/internal/forward.hpp> #if VSMC_HAS_CXX11LIB_FUTURE #include <future> #endif namespace vsmc { namespace thread { /// \brief Blocked range /// \ingroup STDTBB template <typename SizeType> class BlockedRange { public : typedef SizeType size_type; BlockedRange (size_type begin, size_type end) : begin_(begin), end_(end) { VSMC_RUNTIME_ASSERT((begin < end), "INVALID RANG **BlockedRange**"); } size_type begin () const { return begin_; } size_type end () const { return end_; } private : size_type begin_; size_type end_; }; // class BlockedRange /// \brief C++11 Thread safe lock-based stack /// \ingroup STDTBB template <typename T> class LockBasedStack { }; // class LockBasedStack /// \brief C++11 Thread safe lock-free stack /// \ingroup STDTBB template <typename T> class LockFreeStack { }; // class LockFreeStack /// \brief C++11 Thread safe lock-based queue /// \ingroup STDTBB template <typename T> class LockBasedQueue { }; // class LockBasedQuque /// \brief C++11 Thread safe lock-free queue /// \ingroup STDTBB template <typename T> class LockFreeQueue { }; // class LockFreeQueue /// \brief C++11 Thread guard /// \ingroup STDTBB class ThreadGuard { #if VSMC_HAS_CXX11_DELETED_FUNCTIONS public : ThreadGuard (const ThreadGuard &) = delete; ThreadGuard &operator= (const ThreadGuard &) = delete; #else private : ThreadGuard (const ThreadGuard &); ThreadGuard &operator= (const ThreadGuard &); #endif public : ThreadGuard () VSMC_NOEXCEPT {} ThreadGuard (ThreadGuard &&other) VSMC_NOEXCEPT : thread_(std::move(other.thread_)) {} ThreadGuard &operator= (ThreadGuard &&other) VSMC_NOEXCEPT { thread_ = std::move(other.thread_); return *this; } ThreadGuard (std::thread &&thr) VSMC_NOEXCEPT : thread_(std::move(thr)) {} ~ThreadGuard () VSMC_NOEXCEPT { if (thread_.joinable()) thread_.join(); } private : std::thread thread_; }; // class ThreadGuard /// \brief C++11 Thread informations /// \ingroup STDTBB class ThreadInfo { public : static ThreadInfo &instance () { static ThreadInfo info; return info; } unsigned thread_num () const { return thread_num_; } void thread_num (unsigned num) { thread_num_ = num; } template <typename SizeType> std::vector<BlockedRange<SizeType> > partition ( const BlockedRange<SizeType> &range) const { SizeType N = range.end() - range.begin(); SizeType tn = static_cast<SizeType>(thread_num()); SizeType block_size = 0; if (N < tn) block_size = 1; else if (N % tn) block_size = N / tn + 1; else block_size = N / tn; std::vector<BlockedRange<SizeType> > range_vec; range_vec.reserve(thread_num()); SizeType B = range.begin(); while (N > 0) { SizeType next = std::min VSMC_MINMAX_NO_EXPANSION ( N, block_size); range_vec.push_back(BlockedRange<SizeType>(B, B + next)); B += next; N -= next; } VSMC_RUNTIME_ASSERT((range_vec.back().end() == range.end()), "INVALID PARTITION **ThreadInfo::partition**"); return range_vec; } private : unsigned thread_num_; ThreadInfo () : thread_num_(std::max VSMC_MINMAX_NO_EXPANSION (1U, static_cast<unsigned>(std::thread::hardware_concurrency()))) { #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4996) #endif const char *num_str = std::getenv("VSMC_STD_NUM_THREADS"); #ifdef _MSC_VER #pragma warning(pop) #endif if (num_str) { unsigned num = std::atoi(num_str); if (num) thread_num_ = num; } } ThreadInfo (const ThreadInfo &); ThreadInfo &operator= (const ThreadInfo &); }; // class ThreadInfo /// \brief C++11 Thread pool /// \ingroup STDTBB class ThreadPool { public : static ThreadPool &instance () { static ThreadPool pool; return pool; } void submit (); void barrier (); private : ThreadPool (); ThreadPool (const ThreadPool &); ThreadPool &operator= (const ThreadPool &); }; // class ThreadPool /// \brief Parallel for using C++11 thread /// \ingroup STDTBB /// /// \details /// Requirement: WorkType: /// void work (const thread::BlockedRange<size_type> &range); template <typename SizeType, typename WorkType> void parallel_for (const BlockedRange<SizeType> &range, WorkType &&work) { std::vector<BlockedRange<SizeType> > range_vec( ThreadInfo::instance().partition(range)); #if VSMC_HAS_CXX11LIB_FUTURE std::vector<std::future<void> > wg; for (typename std::vector<BlockedRange<SizeType> >::iterator r = range_vec.begin(); r != range_vec.end(); ++r) { wg.push_back(std::async(std::forward<WorkType>(work), *r)); } for (std::vector<std::future<void> >::iterator w = wg.begin(); w != wg.end(); ++w) { w->get(); } #else // start parallelization { std::vector<ThreadGuard> tg; for (typename std::vector<BlockedRange<SizeType> >::iterator r = range_vec.begin(); r != range_vec.end(); ++r) { tg.push_back(ThreadGuard(std::thread(std::forward<WorkType>(work), *r))); } } // stop parallelization // for (typename std::vector<BlockedRange<SizeType> >::iterator // r = range_vec.begin(); r != range_vec.end(); ++r) { // ThreadPool::instance().submit(std::forward<WorkType>(work), *r); // } // ThreadPool::instance().barrier(); #endif } /// \brief Parallel accumulate using C++11 thread /// \ingroup STDTBB /// /// \details /// Requirement: WorkType: /// void work (const thread::BlockedRange<size_type> &range, T &res); template <typename SizeType, typename T, typename WorkType> T parallel_accumulate (const BlockedRange<SizeType> &range, WorkType &&work, T init) { std::vector<BlockedRange<SizeType> > range_vec( ThreadInfo::instance().partition(range)); std::vector<T> result(range_vec.size()); unsigned i = 0; #if VSMC_HAS_CXX11LIB_FUTURE std::vector<std::future<void> > wg; for (typename std::vector<BlockedRange<SizeType> >::iterator r = range_vec.begin(); r != range_vec.end(); ++r, ++i) { wg.push_back(std::async(std::forward<WorkType>(work), *r, std::ref(result[i]))); } for (std::vector<std::future<void> >::iterator w = wg.begin(); w != wg.end(); ++w) { w->get(); } #else // start parallelization { std::vector<ThreadGuard> tg; for (typename std::vector<BlockedRange<SizeType> >::iterator r = range_vec.begin(); r != range_vec.end(); ++r, ++i) { tg.push_back(ThreadGuard(std::thread(std::forward<WorkType>(work), *r, std::ref(result[i])))); } } // stop parallelization // for (typename std::vector<BlockedRange<SizeType> >::iterator // r = range_vec.begin(); r != range_vec.end(); ++r) { // ThreadPool::instance().submit(std::forward<WorkType>(work), *r, // std::ref(result[i])); // } // ThreadPool::instance().barrier(); #endif return std::accumulate(result.begin(), result.end(), init); } /// \brief Parallel accumulate using C++11 thread /// \ingroup STDTBB /// /// \details /// Requirement: WorkType: /// void work (const thread::BlockedRange<size_type> &range, T &res); template <typename SizeType, typename T, typename BinOp, typename WorkType> T parallel_accumulate (const BlockedRange<SizeType> &range, WorkType &&work, T init, BinOp bin_op) { std::vector<BlockedRange<SizeType> > range_vec( ThreadInfo::instance().partition(range)); std::vector<T> result(range_vec.size()); unsigned i =0; #if VSMC_HAS_CXX11LIB_FUTURE std::vector<std::future<void> > wg; for (typename std::vector<BlockedRange<SizeType> >::iterator r = range_vec.begin(); r != range_vec.end(); ++r, ++i) { wg.push_back(std::async(std::forward<WorkType>(work), *r, std::ref(result[i]))); } for (std::vector<std::future<void> >::iterator w = wg.begin(); w != wg.end(); ++w) { w->get(); } #else // start parallelization { std::vector<ThreadGuard> tg; for (typename std::vector<BlockedRange<SizeType> >::iterator r = range_vec.begin(); r != range_vec.end(); ++r, ++i) { tg.push_back(ThreadGuard(std::thread(std::forward<WorkType>(work), *r, std::ref(result[i])))); } } // stop parallelization // for (typename std::vector<BlockedRange<SizeType> >::iterator // r = range_vec.begin(); r != range_vec.end(); ++r) { // ThreadPool::instance().submit(std::forward<WorkType>(work), *r, // std::ref(result[i])); // } // ThreadPool::instance().barrier(); #endif return std::accumulate(result.begin(), result.end(), init, bin_op); } } } // namespace vsmc::thread #endif // VSMC_UTILITY_STDTBB_HPP
add how threadpool shall be used
add how threadpool shall be used
C++
bsd-2-clause
zhouyan/vSMC,zhouyan/vSMC,zhouyan/vSMC,zhouyan/vSMC
9a6447b7f645470a7536f1918101e2164d4f2729
tutorials/roostats/rs101_limitexample.C
tutorials/roostats/rs101_limitexample.C
///////////////////////////////////////////////////////////////////////// // // 'Limit Example' RooStats tutorial macro #101 // author: Kyle Cranmer // date June. 2009 // // This tutorial shows an example of creating a simple // model for a number counting experiment with uncertainty // on both the background rate and signal efficeincy. We then // use a Confidence Interval Calculator to set a limit on the signal. // // ///////////////////////////////////////////////////////////////////////// #ifndef __CINT__ #include "RooGlobalFunc.h" #endif #include "RooProfileLL.h" #include "RooAbsPdf.h" #include "RooStats/HypoTestResult.h" #include "RooRealVar.h" #include "RooPlot.h" #include "RooDataSet.h" #include "RooTreeDataStore.h" #include "TTree.h" #include "TCanvas.h" #include "TLine.h" #include "TStopwatch.h" #include "RooStats/ProfileLikelihoodCalculator.h" #include "RooStats/MCMCCalculator.h" #include "RooStats/UniformProposal.h" #include "RooStats/FeldmanCousins.h" #include "RooStats/NumberCountingPdfFactory.h" #include "RooStats/ConfInterval.h" #include "RooStats/PointSetInterval.h" #include "RooStats/LikelihoodInterval.h" #include "RooStats/LikelihoodIntervalPlot.h" #include "RooStats/RooStatsUtils.h" #include "RooStats/ModelConfig.h" #include "RooStats/MCMCInterval.h" #include "RooStats/MCMCIntervalPlot.h" #include "RooStats/ProposalFunction.h" #include "RooStats/ProposalHelper.h" #include "RooFitResult.h" // use this order for safety on library loading using namespace RooFit ; using namespace RooStats ; void rs101_limitexample() { ///////////////////////////////////////// // An example of setting a limit in a number counting experiment with uncertainty on background and signal ///////////////////////////////////////// // to time the macro TStopwatch t; t.Start(); ///////////////////////////////////////// // The Model building stage ///////////////////////////////////////// RooWorkspace* wspace = new RooWorkspace(); wspace->factory("Poisson::countingModel(obs[150,0,300], sum(s[50,0,120]*ratioSigEff[1.,0,2.],b[100,0,300]*ratioBkgEff[1.,0.,2.]))"); // counting model // wspace->factory("Gaussian::sigConstraint(ratioSigEff,1,0.05)"); // 5% signal efficiency uncertainty // wspace->factory("Gaussian::bkgConstraint(ratioBkgEff,1,0.1)"); // 10% background efficiency uncertainty wspace->factory("Gaussian::sigConstraint(1,ratioSigEff,0.05)"); // 5% signal efficiency uncertainty wspace->factory("Gaussian::bkgConstraint(1,ratioBkgEff,0.1)"); // 10% background efficiency uncertainty wspace->factory("PROD::modelWithConstraints(countingModel,sigConstraint,bkgConstraint)"); // product of terms wspace->Print(); RooAbsPdf* modelWithConstraints = wspace->pdf("modelWithConstraints"); // get the model RooRealVar* obs = wspace->var("obs"); // get the observable RooRealVar* s = wspace->var("s"); // get the signal we care about RooRealVar* b = wspace->var("b"); // get the background and set it to a constant. Uncertainty included in ratioBkgEff b->setConstant(); RooRealVar* ratioSigEff = wspace->var("ratioSigEff"); // get uncertaint parameter to constrain RooRealVar* ratioBkgEff = wspace->var("ratioBkgEff"); // get uncertaint parameter to constrain RooArgSet constrainedParams(*ratioSigEff, *ratioBkgEff); // need to constrain these in the fit (should change default behavior) // Create an example dataset with 160 observed events obs->setVal(160.); RooDataSet* data = new RooDataSet("exampleData", "exampleData", RooArgSet(*obs)); data->add(*obs); RooArgSet all(*s, *ratioBkgEff, *ratioSigEff); // not necessary modelWithConstraints->fitTo(*data, RooFit::Constrain(RooArgSet(*ratioSigEff, *ratioBkgEff))); // Now let's make some confidence intervals for s, our parameter of interest RooArgSet paramOfInterest(*s); ModelConfig modelConfig(new RooWorkspace()); modelConfig.SetPdf(*modelWithConstraints); modelConfig.SetParametersOfInterest(paramOfInterest); // First, let's use a Calculator based on the Profile Likelihood Ratio //ProfileLikelihoodCalculator plc(*data, *modelWithConstraints, paramOfInterest); ProfileLikelihoodCalculator plc(*data, modelConfig); plc.SetTestSize(.05); ConfInterval* lrint = plc.GetInterval(); // that was easy. // Let's make a plot TCanvas* dataCanvas = new TCanvas("dataCanvas"); dataCanvas->Divide(2,1); dataCanvas->cd(1); LikelihoodIntervalPlot plotInt((LikelihoodInterval*)lrint); plotInt.SetTitle("Profile Likelihood Ratio and Posterior for S"); plotInt.Draw(); // Second, use a Calculator based on the Feldman Cousins technique FeldmanCousins fc(*data, modelConfig); fc.UseAdaptiveSampling(true); fc.FluctuateNumDataEntries(false); // number counting analysis: dataset always has 1 entry with N events observed fc.SetNBins(100); // number of points to test per parameter fc.SetTestSize(.05); // fc.SaveBeltToFile(true); // optional ConfInterval* fcint = NULL; fcint = fc.GetInterval(); // that was easy. RooFitResult* fit = modelWithConstraints->fitTo(*data, Save(true)); // Third, use a Calculator based on Markov Chain monte carlo // Before configuring the calculator, let's make a ProposalFunction // that will achieve a high acceptance rate ProposalHelper ph; ph.SetVariables((RooArgSet&)fit->floatParsFinal()); ph.SetCovMatrix(fit->covarianceMatrix()); ph.SetUpdateProposalParameters(true); ph.SetCacheSize(100); ProposalFunction* pdfProp = ph.GetProposalFunction(); // that was easy MCMCCalculator mc(*data, modelConfig); mc.SetNumIters(20000); // steps to propose in the chain mc.SetTestSize(.05); // 95% CL mc.SetNumBurnInSteps(40); // ignore first N steps in chain as "burn in" mc.SetProposalFunction(*pdfProp); mc.SetLeftSideTailFraction(0.5); // find a "central" interval MCMCInterval* mcInt = (MCMCInterval*)mc.GetInterval(); // that was easy // Get Lower and Upper limits from Profile Calculator cout << "Profile lower limit on s = " << ((LikelihoodInterval*) lrint)->LowerLimit(*s) << endl; cout << "Profile upper limit on s = " << ((LikelihoodInterval*) lrint)->UpperLimit(*s) << endl; // Get Lower and Upper limits from FeldmanCousins with profile construction if (fcint != NULL) { double fcul = ((PointSetInterval*) fcint)->UpperLimit(*s); double fcll = ((PointSetInterval*) fcint)->LowerLimit(*s); cout << "FC lower limit on s = " << fcll << endl; cout << "FC upper limit on s = " << fcul << endl; TLine* fcllLine = new TLine(fcll, 0, fcll, 1); TLine* fculLine = new TLine(fcul, 0, fcul, 1); fcllLine->SetLineColor(kRed); fculLine->SetLineColor(kRed); fcllLine->Draw("same"); fculLine->Draw("same"); dataCanvas->Update(); } // Plot MCMC interval and print some statistics MCMCIntervalPlot mcPlot(*mcInt); mcPlot.SetLineColor(kMagenta); mcPlot.SetLineWidth(2); mcPlot.Draw("same"); double mcul = mcInt->UpperLimit(*s); double mcll = mcInt->LowerLimit(*s); cout << "MCMC lower limit on s = " << mcll << endl; cout << "MCMC upper limit on s = " << mcul << endl; cout << "MCMC Actual confidence level: " << mcInt->GetActualConfidenceLevel() << endl; // 3-d plot of the parameter points dataCanvas->cd(2); // also plot the points in the markov chain TTree& chain = ((RooTreeDataStore*) mcInt->GetChainAsDataSet()->store())->tree(); chain.SetMarkerStyle(6); chain.SetMarkerColor(kRed); chain.Draw("s:ratioSigEff:ratioBkgEff","weight_MarkovChain_local_","box"); // 3-d box proporional to posterior // the points used in the profile construction TTree& parameterScan = ((RooTreeDataStore*) fc.GetPointsToScan()->store())->tree(); parameterScan.SetMarkerStyle(24); parameterScan.Draw("s:ratioSigEff:ratioBkgEff","","same"); delete wspace; delete lrint; delete mcInt; delete fcint; delete data; /// print timing info t.Stop(); t.Print(); }
///////////////////////////////////////////////////////////////////////// // // 'Limit Example' RooStats tutorial macro #101 // author: Kyle Cranmer // date June. 2009 // // This tutorial shows an example of creating a simple // model for a number counting experiment with uncertainty // on both the background rate and signal efficeincy. We then // use a Confidence Interval Calculator to set a limit on the signal. // // ///////////////////////////////////////////////////////////////////////// #ifndef __CINT__ #include "RooGlobalFunc.h" #endif #include "RooProfileLL.h" #include "RooAbsPdf.h" #include "RooStats/HypoTestResult.h" #include "RooRealVar.h" #include "RooPlot.h" #include "RooDataSet.h" #include "RooTreeDataStore.h" #include "TTree.h" #include "TCanvas.h" #include "TLine.h" #include "TStopwatch.h" #include "RooStats/ProfileLikelihoodCalculator.h" #include "RooStats/MCMCCalculator.h" #include "RooStats/UniformProposal.h" #include "RooStats/FeldmanCousins.h" #include "RooStats/NumberCountingPdfFactory.h" #include "RooStats/ConfInterval.h" #include "RooStats/PointSetInterval.h" #include "RooStats/LikelihoodInterval.h" #include "RooStats/LikelihoodIntervalPlot.h" #include "RooStats/RooStatsUtils.h" #include "RooStats/ModelConfig.h" #include "RooStats/MCMCInterval.h" #include "RooStats/MCMCIntervalPlot.h" #include "RooStats/ProposalFunction.h" #include "RooStats/ProposalHelper.h" #include "RooFitResult.h" #include "TGraph2D.h" // use this order for safety on library loading using namespace RooFit ; using namespace RooStats ; void rs101_limitexample() { ///////////////////////////////////////// // An example of setting a limit in a number counting experiment with uncertainty on background and signal ///////////////////////////////////////// // to time the macro TStopwatch t; t.Start(); ///////////////////////////////////////// // The Model building stage ///////////////////////////////////////// RooWorkspace* wspace = new RooWorkspace(); wspace->factory("Poisson::countingModel(obs[150,0,300], sum(s[50,0,120]*ratioSigEff[1.,0,2.],b[100,0,300]*ratioBkgEff[1.,0.,2.]))"); // counting model // wspace->factory("Gaussian::sigConstraint(ratioSigEff,1,0.05)"); // 5% signal efficiency uncertainty // wspace->factory("Gaussian::bkgConstraint(ratioBkgEff,1,0.1)"); // 10% background efficiency uncertainty wspace->factory("Gaussian::sigConstraint(1,ratioSigEff,0.05)"); // 5% signal efficiency uncertainty wspace->factory("Gaussian::bkgConstraint(1,ratioBkgEff,0.1)"); // 10% background efficiency uncertainty wspace->factory("PROD::modelWithConstraints(countingModel,sigConstraint,bkgConstraint)"); // product of terms wspace->Print(); RooAbsPdf* modelWithConstraints = wspace->pdf("modelWithConstraints"); // get the model RooRealVar* obs = wspace->var("obs"); // get the observable RooRealVar* s = wspace->var("s"); // get the signal we care about RooRealVar* b = wspace->var("b"); // get the background and set it to a constant. Uncertainty included in ratioBkgEff b->setConstant(); RooRealVar* ratioSigEff = wspace->var("ratioSigEff"); // get uncertaint parameter to constrain RooRealVar* ratioBkgEff = wspace->var("ratioBkgEff"); // get uncertaint parameter to constrain RooArgSet constrainedParams(*ratioSigEff, *ratioBkgEff); // need to constrain these in the fit (should change default behavior) // Create an example dataset with 160 observed events obs->setVal(160.); RooDataSet* data = new RooDataSet("exampleData", "exampleData", RooArgSet(*obs)); data->add(*obs); RooArgSet all(*s, *ratioBkgEff, *ratioSigEff); // not necessary modelWithConstraints->fitTo(*data, RooFit::Constrain(RooArgSet(*ratioSigEff, *ratioBkgEff))); // Now let's make some confidence intervals for s, our parameter of interest RooArgSet paramOfInterest(*s); ModelConfig modelConfig(new RooWorkspace()); modelConfig.SetPdf(*modelWithConstraints); modelConfig.SetParametersOfInterest(paramOfInterest); // First, let's use a Calculator based on the Profile Likelihood Ratio //ProfileLikelihoodCalculator plc(*data, *modelWithConstraints, paramOfInterest); ProfileLikelihoodCalculator plc(*data, modelConfig); plc.SetTestSize(.05); ConfInterval* lrint = plc.GetInterval(); // that was easy. // Let's make a plot TCanvas* dataCanvas = new TCanvas("dataCanvas"); dataCanvas->Divide(2,1); dataCanvas->cd(1); LikelihoodIntervalPlot plotInt((LikelihoodInterval*)lrint); plotInt.SetTitle("Profile Likelihood Ratio and Posterior for S"); plotInt.Draw(); // Second, use a Calculator based on the Feldman Cousins technique FeldmanCousins fc(*data, modelConfig); fc.UseAdaptiveSampling(true); fc.FluctuateNumDataEntries(false); // number counting analysis: dataset always has 1 entry with N events observed fc.SetNBins(100); // number of points to test per parameter fc.SetTestSize(.05); // fc.SaveBeltToFile(true); // optional ConfInterval* fcint = NULL; fcint = fc.GetInterval(); // that was easy. RooFitResult* fit = modelWithConstraints->fitTo(*data, Save(true)); // Third, use a Calculator based on Markov Chain monte carlo // Before configuring the calculator, let's make a ProposalFunction // that will achieve a high acceptance rate ProposalHelper ph; ph.SetVariables((RooArgSet&)fit->floatParsFinal()); ph.SetCovMatrix(fit->covarianceMatrix()); ph.SetUpdateProposalParameters(true); ph.SetCacheSize(100); ProposalFunction* pdfProp = ph.GetProposalFunction(); // that was easy MCMCCalculator mc(*data, modelConfig); mc.SetNumIters(20000); // steps to propose in the chain mc.SetTestSize(.05); // 95% CL mc.SetNumBurnInSteps(40); // ignore first N steps in chain as "burn in" mc.SetProposalFunction(*pdfProp); mc.SetLeftSideTailFraction(0.5); // find a "central" interval MCMCInterval* mcInt = (MCMCInterval*)mc.GetInterval(); // that was easy // Get Lower and Upper limits from Profile Calculator cout << "Profile lower limit on s = " << ((LikelihoodInterval*) lrint)->LowerLimit(*s) << endl; cout << "Profile upper limit on s = " << ((LikelihoodInterval*) lrint)->UpperLimit(*s) << endl; // Get Lower and Upper limits from FeldmanCousins with profile construction if (fcint != NULL) { double fcul = ((PointSetInterval*) fcint)->UpperLimit(*s); double fcll = ((PointSetInterval*) fcint)->LowerLimit(*s); cout << "FC lower limit on s = " << fcll << endl; cout << "FC upper limit on s = " << fcul << endl; TLine* fcllLine = new TLine(fcll, 0, fcll, 1); TLine* fculLine = new TLine(fcul, 0, fcul, 1); fcllLine->SetLineColor(kRed); fculLine->SetLineColor(kRed); fcllLine->Draw("same"); fculLine->Draw("same"); dataCanvas->Update(); } // Plot MCMC interval and print some statistics MCMCIntervalPlot mcPlot(*mcInt); mcPlot.SetLineColor(kMagenta); mcPlot.SetLineWidth(2); mcPlot.Draw("same"); double mcul = mcInt->UpperLimit(*s); double mcll = mcInt->LowerLimit(*s); cout << "MCMC lower limit on s = " << mcll << endl; cout << "MCMC upper limit on s = " << mcul << endl; cout << "MCMC Actual confidence level: " << mcInt->GetActualConfidenceLevel() << endl; // 3-d plot of the parameter points dataCanvas->cd(2); // also plot the points in the markov chain RooDataSet * chainData = mcInt->GetChainAsDataSet(); assert(chainData); std::cout << "plotting the chain data - nentries = " << chainData->numEntries() << std::endl; TTree* chain = RooStats::GetAsTTree("chainTreeData","chainTreeData",*chainData); assert(chain); chain->SetMarkerStyle(6); chain->SetMarkerColor(kRed); chain->Draw("s:ratioSigEff:ratioBkgEff","nll_MarkovChain_local_","box"); // 3-d box proporional to posterior // the points used in the profile construction RooDataSet * parScanData = (RooDataSet*) fc.GetPointsToScan(); assert(parScanData); std::cout << "plotting the scanned points used in the frequentist construction - npoints = " << parScanData->numEntries() << std::endl; // getting the tree and drawing it -crashes (very strange....); // TTree* parameterScan = RooStats::GetAsTTree("parScanTreeData","parScanTreeData",*parScanData); // assert(parameterScan); // parameterScan->Draw("s:ratioSigEff:ratioBkgEff","","candle goff"); TGraph2D *gr = new TGraph2D(parScanData->numEntries()); for (int ievt = 0; ievt < parScanData->numEntries(); ++ievt) { const RooArgSet * evt = parScanData->get(ievt); double x = evt->getRealValue("ratioBkgEff"); double y = evt->getRealValue("ratioSigEff"); double z = evt->getRealValue("s"); gr->SetPoint(ievt, x,y,z); // std::cout << ievt << " " << x << " " << y << " " << z << std::endl; } gr->SetMarkerStyle(24); gr->Draw("P SAME"); delete wspace; delete lrint; delete mcInt; delete fcint; delete data; /// print timing info t.Stop(); t.Print(); }
fix tutorials to avoid a crash when plotting chain and FC scanned points (see https://savannah.cern.ch/bugs/index.php?94761)
fix tutorials to avoid a crash when plotting chain and FC scanned points (see https://savannah.cern.ch/bugs/index.php?94761) git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@45720 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
abhinavmoudgil95/root,simonpf/root,bbockelm/root,zzxuanyuan/root,bbockelm/root,pspe/root,davidlt/root,smarinac/root,sbinet/cxx-root,agarciamontoro/root,dfunke/root,bbockelm/root,mhuwiler/rootauto,satyarth934/root,Duraznos/root,esakellari/root,beniz/root,smarinac/root,dfunke/root,mkret2/root,esakellari/root,sirinath/root,zzxuanyuan/root-compressor-dummy,dfunke/root,lgiommi/root,pspe/root,evgeny-boger/root,mkret2/root,arch1tect0r/root,BerserkerTroll/root,davidlt/root,jrtomps/root,satyarth934/root,vukasinmilosevic/root,krafczyk/root,vukasinmilosevic/root,simonpf/root,bbockelm/root,simonpf/root,sawenzel/root,Y--/root,buuck/root,mkret2/root,jrtomps/root,gganis/root,thomaskeck/root,agarciamontoro/root,esakellari/my_root_for_test,agarciamontoro/root,Duraznos/root,gbitzes/root,mattkretz/root,karies/root,dfunke/root,CristinaCristescu/root,0x0all/ROOT,lgiommi/root,davidlt/root,beniz/root,sbinet/cxx-root,smarinac/root,jrtomps/root,esakellari/my_root_for_test,simonpf/root,mattkretz/root,alexschlueter/cern-root,mhuwiler/rootauto,smarinac/root,beniz/root,georgtroska/root,esakellari/root,karies/root,dfunke/root,gbitzes/root,lgiommi/root,mhuwiler/rootauto,karies/root,abhinavmoudgil95/root,CristinaCristescu/root,bbockelm/root,zzxuanyuan/root,perovic/root,agarciamontoro/root,gganis/root,olifre/root,evgeny-boger/root,mhuwiler/rootauto,jrtomps/root,thomaskeck/root,arch1tect0r/root,sbinet/cxx-root,CristinaCristescu/root,arch1tect0r/root,olifre/root,georgtroska/root,root-mirror/root,satyarth934/root,Y--/root,nilqed/root,omazapa/root-old,root-mirror/root,davidlt/root,jrtomps/root,perovic/root,alexschlueter/cern-root,sawenzel/root,nilqed/root,abhinavmoudgil95/root,sbinet/cxx-root,esakellari/root,olifre/root,gbitzes/root,omazapa/root-old,Duraznos/root,CristinaCristescu/root,Y--/root,zzxuanyuan/root,satyarth934/root,veprbl/root,sawenzel/root,evgeny-boger/root,agarciamontoro/root,satyarth934/root,gganis/root,veprbl/root,vukasinmilosevic/root,davidlt/root,cxx-hep/root-cern,pspe/root,0x0all/ROOT,dfunke/root,BerserkerTroll/root,omazapa/root,satyarth934/root,georgtroska/root,nilqed/root,gganis/root,CristinaCristescu/root,georgtroska/root,agarciamontoro/root,mkret2/root,lgiommi/root,cxx-hep/root-cern,BerserkerTroll/root,CristinaCristescu/root,gganis/root,zzxuanyuan/root,zzxuanyuan/root,omazapa/root-old,omazapa/root-old,buuck/root,georgtroska/root,davidlt/root,abhinavmoudgil95/root,abhinavmoudgil95/root,omazapa/root-old,olifre/root,simonpf/root,sawenzel/root,zzxuanyuan/root-compressor-dummy,sawenzel/root,esakellari/root,omazapa/root,omazapa/root-old,dfunke/root,cxx-hep/root-cern,veprbl/root,mattkretz/root,krafczyk/root,omazapa/root,olifre/root,mattkretz/root,sirinath/root,esakellari/my_root_for_test,Y--/root,cxx-hep/root-cern,mattkretz/root,esakellari/root,sbinet/cxx-root,sirinath/root,karies/root,gganis/root,buuck/root,omazapa/root,perovic/root,perovic/root,gbitzes/root,Y--/root,sirinath/root,root-mirror/root,mkret2/root,Duraznos/root,olifre/root,sbinet/cxx-root,veprbl/root,nilqed/root,lgiommi/root,satyarth934/root,jrtomps/root,sirinath/root,zzxuanyuan/root-compressor-dummy,perovic/root,BerserkerTroll/root,simonpf/root,mhuwiler/rootauto,vukasinmilosevic/root,esakellari/my_root_for_test,zzxuanyuan/root-compressor-dummy,veprbl/root,BerserkerTroll/root,sawenzel/root,bbockelm/root,veprbl/root,thomaskeck/root,arch1tect0r/root,pspe/root,agarciamontoro/root,thomaskeck/root,buuck/root,beniz/root,BerserkerTroll/root,smarinac/root,evgeny-boger/root,veprbl/root,root-mirror/root,karies/root,abhinavmoudgil95/root,esakellari/my_root_for_test,mkret2/root,simonpf/root,georgtroska/root,sirinath/root,simonpf/root,sbinet/cxx-root,jrtomps/root,Y--/root,pspe/root,smarinac/root,thomaskeck/root,karies/root,mattkretz/root,jrtomps/root,mattkretz/root,beniz/root,BerserkerTroll/root,abhinavmoudgil95/root,dfunke/root,buuck/root,mattkretz/root,sirinath/root,zzxuanyuan/root,agarciamontoro/root,sbinet/cxx-root,vukasinmilosevic/root,zzxuanyuan/root,vukasinmilosevic/root,perovic/root,omazapa/root,pspe/root,zzxuanyuan/root,beniz/root,davidlt/root,omazapa/root,lgiommi/root,evgeny-boger/root,root-mirror/root,olifre/root,gganis/root,buuck/root,mkret2/root,evgeny-boger/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root,gbitzes/root,georgtroska/root,krafczyk/root,lgiommi/root,perovic/root,sawenzel/root,Duraznos/root,jrtomps/root,Y--/root,zzxuanyuan/root-compressor-dummy,abhinavmoudgil95/root,gganis/root,vukasinmilosevic/root,zzxuanyuan/root-compressor-dummy,esakellari/my_root_for_test,BerserkerTroll/root,omazapa/root-old,gbitzes/root,buuck/root,krafczyk/root,Duraznos/root,esakellari/root,Duraznos/root,0x0all/ROOT,satyarth934/root,alexschlueter/cern-root,bbockelm/root,zzxuanyuan/root-compressor-dummy,0x0all/ROOT,omazapa/root,smarinac/root,mattkretz/root,Duraznos/root,bbockelm/root,nilqed/root,thomaskeck/root,agarciamontoro/root,esakellari/my_root_for_test,zzxuanyuan/root-compressor-dummy,smarinac/root,zzxuanyuan/root,olifre/root,lgiommi/root,Y--/root,gbitzes/root,perovic/root,bbockelm/root,beniz/root,esakellari/my_root_for_test,gbitzes/root,vukasinmilosevic/root,buuck/root,CristinaCristescu/root,smarinac/root,gbitzes/root,gbitzes/root,smarinac/root,georgtroska/root,beniz/root,satyarth934/root,simonpf/root,cxx-hep/root-cern,krafczyk/root,beniz/root,abhinavmoudgil95/root,vukasinmilosevic/root,root-mirror/root,veprbl/root,Duraznos/root,vukasinmilosevic/root,esakellari/my_root_for_test,krafczyk/root,davidlt/root,pspe/root,karies/root,georgtroska/root,perovic/root,CristinaCristescu/root,evgeny-boger/root,omazapa/root-old,evgeny-boger/root,arch1tect0r/root,zzxuanyuan/root-compressor-dummy,nilqed/root,cxx-hep/root-cern,satyarth934/root,nilqed/root,bbockelm/root,sirinath/root,thomaskeck/root,sbinet/cxx-root,mhuwiler/rootauto,mkret2/root,BerserkerTroll/root,olifre/root,beniz/root,sawenzel/root,BerserkerTroll/root,0x0all/ROOT,karies/root,omazapa/root-old,CristinaCristescu/root,gganis/root,omazapa/root-old,Y--/root,0x0all/ROOT,dfunke/root,dfunke/root,evgeny-boger/root,zzxuanyuan/root,buuck/root,pspe/root,bbockelm/root,gganis/root,krafczyk/root,Y--/root,arch1tect0r/root,thomaskeck/root,arch1tect0r/root,0x0all/ROOT,mhuwiler/rootauto,krafczyk/root,alexschlueter/cern-root,evgeny-boger/root,0x0all/ROOT,gbitzes/root,root-mirror/root,omazapa/root,perovic/root,omazapa/root,satyarth934/root,buuck/root,agarciamontoro/root,mkret2/root,arch1tect0r/root,krafczyk/root,sirinath/root,agarciamontoro/root,arch1tect0r/root,alexschlueter/cern-root,Y--/root,pspe/root,mkret2/root,sawenzel/root,evgeny-boger/root,simonpf/root,veprbl/root,dfunke/root,root-mirror/root,georgtroska/root,jrtomps/root,root-mirror/root,karies/root,lgiommi/root,arch1tect0r/root,omazapa/root,esakellari/root,root-mirror/root,mattkretz/root,mhuwiler/rootauto,davidlt/root,zzxuanyuan/root,esakellari/root,root-mirror/root,veprbl/root,arch1tect0r/root,sirinath/root,Duraznos/root,perovic/root,cxx-hep/root-cern,pspe/root,georgtroska/root,lgiommi/root,karies/root,olifre/root,nilqed/root,davidlt/root,alexschlueter/cern-root,olifre/root,sbinet/cxx-root,beniz/root,pspe/root,vukasinmilosevic/root,krafczyk/root,mhuwiler/rootauto,nilqed/root,krafczyk/root,mhuwiler/rootauto,nilqed/root,davidlt/root,buuck/root,0x0all/ROOT,omazapa/root,sawenzel/root,karies/root,thomaskeck/root,simonpf/root,zzxuanyuan/root-compressor-dummy,veprbl/root,jrtomps/root,sirinath/root,gganis/root,mattkretz/root,abhinavmoudgil95/root,Duraznos/root,alexschlueter/cern-root,mhuwiler/rootauto,lgiommi/root,esakellari/root,thomaskeck/root,cxx-hep/root-cern,sbinet/cxx-root,sawenzel/root,BerserkerTroll/root,esakellari/root,omazapa/root-old,CristinaCristescu/root,abhinavmoudgil95/root,CristinaCristescu/root,mkret2/root,nilqed/root,esakellari/my_root_for_test
927b87bcd418ecff2478516f77313c63ba9c83c5
OgreMain/src/OgreShadowCameraSetupPSSM.cpp
OgreMain/src/OgreShadowCameraSetupPSSM.cpp
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2006 Torus Knot Software Ltd Copyright (c) 2006 Matthias Fink, netAllied GmbH <[email protected]> Also see acknowledgements in Readme.html 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 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreShadowCameraSetupPSSM.h" #include "OgreSceneManager.h" #include "OgreCamera.h" namespace Ogre { //--------------------------------------------------------------------- PSSMShadowCameraSetup::PSSMShadowCameraSetup() : mSplitPadding(1.0f) { calculateSplitPoints(3, 100, 100000); setOptimalAdjustFactor(0, 5); setOptimalAdjustFactor(1, 1); setOptimalAdjustFactor(2, 0); } //--------------------------------------------------------------------- PSSMShadowCameraSetup::~PSSMShadowCameraSetup() { } //--------------------------------------------------------------------- void PSSMShadowCameraSetup::calculateSplitPoints(size_t splitCount, Real nearDist, Real farDist, Real lambda) { if (splitCount < 2) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot specify less than 2 splits", "PSSMShadowCameraSetup::calculateSplitPoints"); mSplitPoints.resize(splitCount + 1); mOptimalAdjustFactors.resize(splitCount); mSplitCount = splitCount; mSplitPoints[0] = nearDist; for (size_t i = 1; i < mSplitCount; i++) { Real fraction = (Real)i / 3.0; Real splitPoint = lambda * nearDist * Math::Pow(farDist / nearDist, fraction) + (1.0 - lambda) * (nearDist + fraction * (farDist - nearDist)); mSplitPoints[i] = splitPoint; } mSplitPoints[splitCount] = farDist; } //--------------------------------------------------------------------- void PSSMShadowCameraSetup::setSplitPoints(const SplitPointList& newSplitPoints) { if (newSplitPoints.size() < 3) // 3, not 2 since splits + 1 points OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot specify less than 2 splits", "PSSMShadowCameraSetup::setSplitPoints"); mSplitCount = newSplitPoints.size() - 1; mSplitPoints = newSplitPoints; mOptimalAdjustFactors.resize(mSplitCount); } //--------------------------------------------------------------------- void PSSMShadowCameraSetup::setOptimalAdjustFactor(size_t splitIndex, Real factor) { if (splitIndex >= mOptimalAdjustFactors.size()) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Split index out of range", "PSSMShadowCameraSetup::setOptimalAdjustFactor"); mOptimalAdjustFactors[splitIndex] = factor; } //--------------------------------------------------------------------- Real PSSMShadowCameraSetup::getOptimalAdjustFactor() const { // simplifies the overriding of the LiSPSM opt adjust factor use return mOptimalAdjustFactors[mCurrentIteration]; } //--------------------------------------------------------------------- void PSSMShadowCameraSetup::getShadowCamera(const Ogre::SceneManager *sm, const Ogre::Camera *cam, const Ogre::Viewport *vp, const Ogre::Light *light, Ogre::Camera *texCam, size_t iteration) const { // apply the right clip distance. Real nearDist = mSplitPoints[iteration]; Real farDist = mSplitPoints[iteration + 1]; // Add a padding factor to internal distances so that the connecting split point will not have bad artifacts. if (iteration > 0) { nearDist -= mSplitPadding; } if (iteration < mSplitCount - 1) { farDist += mSplitPadding; } mCurrentIteration = iteration; // Ouch, I know this is hacky, but it's the easiest way to re-use LiSPSM / Focussed // functionality right now without major changes Camera* _cam = const_cast<Camera*>(cam); Real oldNear = _cam->getNearClipDistance(); Real oldFar = _cam->getFarClipDistance(); _cam->setNearClipDistance(nearDist); _cam->setFarClipDistance(farDist); LiSPSMShadowCameraSetup::getShadowCamera(sm, cam, vp, light, texCam, iteration); // restore near/far _cam->setNearClipDistance(oldNear); _cam->setFarClipDistance(oldFar); } }
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2006 Torus Knot Software Ltd Copyright (c) 2006 Matthias Fink, netAllied GmbH <[email protected]> Also see acknowledgements in Readme.html 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 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/copyleft/lesser.txt. You may alternatively use this source under the terms of a specific version of the OGRE Unrestricted License provided you have obtained such a license from Torus Knot Software Ltd. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreShadowCameraSetupPSSM.h" #include "OgreSceneManager.h" #include "OgreCamera.h" namespace Ogre { //--------------------------------------------------------------------- PSSMShadowCameraSetup::PSSMShadowCameraSetup() : mSplitPadding(1.0f) { calculateSplitPoints(3, 100, 100000); setOptimalAdjustFactor(0, 5); setOptimalAdjustFactor(1, 1); setOptimalAdjustFactor(2, 0); } //--------------------------------------------------------------------- PSSMShadowCameraSetup::~PSSMShadowCameraSetup() { } //--------------------------------------------------------------------- void PSSMShadowCameraSetup::calculateSplitPoints(size_t splitCount, Real nearDist, Real farDist, Real lambda) { if (splitCount < 2) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot specify less than 2 splits", "PSSMShadowCameraSetup::calculateSplitPoints"); mSplitPoints.resize(splitCount + 1); mOptimalAdjustFactors.resize(splitCount); mSplitCount = splitCount; mSplitPoints[0] = nearDist; for (size_t i = 1; i < mSplitCount; i++) { Real fraction = (Real)i / (Real)mSplitCount; Real splitPoint = lambda * nearDist * Math::Pow(farDist / nearDist, fraction) + (1.0 - lambda) * (nearDist + fraction * (farDist - nearDist)); mSplitPoints[i] = splitPoint; } mSplitPoints[splitCount] = farDist; } //--------------------------------------------------------------------- void PSSMShadowCameraSetup::setSplitPoints(const SplitPointList& newSplitPoints) { if (newSplitPoints.size() < 3) // 3, not 2 since splits + 1 points OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot specify less than 2 splits", "PSSMShadowCameraSetup::setSplitPoints"); mSplitCount = newSplitPoints.size() - 1; mSplitPoints = newSplitPoints; mOptimalAdjustFactors.resize(mSplitCount); } //--------------------------------------------------------------------- void PSSMShadowCameraSetup::setOptimalAdjustFactor(size_t splitIndex, Real factor) { if (splitIndex >= mOptimalAdjustFactors.size()) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Split index out of range", "PSSMShadowCameraSetup::setOptimalAdjustFactor"); mOptimalAdjustFactors[splitIndex] = factor; } //--------------------------------------------------------------------- Real PSSMShadowCameraSetup::getOptimalAdjustFactor() const { // simplifies the overriding of the LiSPSM opt adjust factor use return mOptimalAdjustFactors[mCurrentIteration]; } //--------------------------------------------------------------------- void PSSMShadowCameraSetup::getShadowCamera(const Ogre::SceneManager *sm, const Ogre::Camera *cam, const Ogre::Viewport *vp, const Ogre::Light *light, Ogre::Camera *texCam, size_t iteration) const { // apply the right clip distance. Real nearDist = mSplitPoints[iteration]; Real farDist = mSplitPoints[iteration + 1]; // Add a padding factor to internal distances so that the connecting split point will not have bad artifacts. if (iteration > 0) { nearDist -= mSplitPadding; } if (iteration < mSplitCount - 1) { farDist += mSplitPadding; } mCurrentIteration = iteration; // Ouch, I know this is hacky, but it's the easiest way to re-use LiSPSM / Focussed // functionality right now without major changes Camera* _cam = const_cast<Camera*>(cam); Real oldNear = _cam->getNearClipDistance(); Real oldFar = _cam->getFarClipDistance(); _cam->setNearClipDistance(nearDist); _cam->setFarClipDistance(farDist); LiSPSMShadowCameraSetup::getShadowCamera(sm, cam, vp, light, texCam, iteration); // restore near/far _cam->setNearClipDistance(oldNear); _cam->setFarClipDistance(oldFar); } }
Fix PSSMShadowCameraSetup::calculateSplitPoints when using arbitrary number of splits
Fix PSSMShadowCameraSetup::calculateSplitPoints when using arbitrary number of splits
C++
mit
jakzale/ogre,jakzale/ogre,jakzale/ogre,jakzale/ogre,jakzale/ogre
8667a350abd1971e4840a5b1c77be2a7ed0bb950
v8-shell.m.cpp
v8-shell.m.cpp
// v8-shell.m.cpp -*-C++-*- #include <v8.h> #include <fstream> #include <iostream> #include <iterator> #include <sstream> namespace { static const char *toCString(v8::Handle<v8::Value> value) { return *v8::String::Utf8Value(value); } static std::ostream& format(std::ostream& stream, v8::Handle<v8::Message> message) { stream << toCString(message->Get()) << '\n'; v8::Handle<v8::StackTrace> stack = message->GetStackTrace(); if (!stack.IsEmpty()) { for (int i = 0; i < stack->GetFrameCount(); ++i) { v8::Handle<v8::StackFrame> frame = stack->GetFrame(i); stream << " at "; if (frame->GetFunctionName()->Length()) { stream << toCString(frame->GetFunctionName()) << " "; } stream << "(" << toCString(frame->GetScriptName()) << ":" << frame->GetLineNumber() << ":" << frame->GetColumn() << ")" << std::endl; } } return stream; } static std::ostream& format(std::ostream& stream, v8::Handle<v8::Value> value) { return stream << toCString(value) << std::endl; } static int read(std::string *result, std::istream& in, std::ostream& out) { result->clear(); out << ">>> "; bool escape = false; bool append = true; while (true) { std::istream::int_type character = in.get(); switch (character) { case -1: { out << "\n"; } return -1; case '\n': { if (escape) { out << "... "; escape = false; } else { return 0; } } break; case '\\': { escape = true; append = false; } break; } if (append) { result->push_back(std::istream::traits_type::to_char_type( character)); } append = true; } } static int evaluate(v8::Handle<v8::Value> *result, v8::Handle<v8::Message> *errorMessage, const std::string& input, const std::string& inputName) { // This will catch errors within this scope v8::TryCatch tryCatch; // Load the input string v8::Handle<v8::String> source = v8::String::New(input.data(), input.length()); if (tryCatch.HasCaught()) { *errorMessage = tryCatch.Message(); return -1; } // Compile it v8::Handle<v8::Script> script = v8::Script::Compile( source, v8::String::New(inputName.data(), inputName.size())); if (tryCatch.HasCaught()) { *errorMessage = tryCatch.Message(); return -1; } // Evaluate it *result = script->Run(); if (tryCatch.HasCaught()) { *errorMessage = tryCatch.Message(); return -1; } return 0; } static void evaluateAndPrint(std::ostream& outStream, std::ostream& errorStream, const std::string& input, const std::string& inputName) { v8::Handle<v8::Value> result; v8::Handle<v8::Message> errorMessage; if (evaluate(&result, &errorMessage, input, inputName)) { format(errorStream, errorMessage); } else { outStream << "-> "; format(outStream, result); } } static int readFile(std::string *contents, const std::string& fileName) { std::filebuf fileBuffer; fileBuffer.open(fileName, std::ios_base::in); if (!fileBuffer.is_open()) { return -1; } std::copy(std::istreambuf_iterator<char>(&fileBuffer), std::istreambuf_iterator<char>(), std::back_inserter(*contents)); fileBuffer.close(); return 0; } static int evaluateFile(std::ostream& outStream, std::ostream& errorStream, const std::string& programName, const std::string& fileName) { std::string input; if (readFile(&input, fileName)) { errorStream << "Usage: " << programName << " [<filename> | -]*\n" << "Failed to open: " << fileName << std::endl; return -1; } evaluateAndPrint(outStream, errorStream, input, fileName); return 0; } static void beginReplLoop(std::istream& inStream, std::ostream& outStream, std::ostream& errorStream) { std::string input; int command = 0; while (read(&input, inStream, outStream) == 0) { std::ostringstream oss; oss << "<stdin:" << ++command << ">"; evaluateAndPrint(outStream, errorStream, input, oss.str()); } } } // close unnamed namespace int main(int argc, char *argv[]) { // Initialize global v8 variables v8::Isolate *isolate = v8::Isolate::GetCurrent(); v8::V8::SetCaptureStackTraceForUncaughtExceptions( true, 0x100, v8::StackTrace::kDetailed); // Stack-local storage v8::HandleScope handles(isolate); // Create and enter a context v8::Handle<v8::Context> context = v8::Context::New(isolate); v8::Context::Scope scope(context); if (argc == 1) { beginReplLoop(std::cin, std::cout, std::cerr); } else { for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { switch (argv[i][1]) { case '\0': beginReplLoop(std::cin, std::cout, std::cerr); break; case 'h': default: std::cout << "Usage: " << argv[0] << " [<filename> | -]*" << std::endl; break; } } else { evaluateFile(std::cout, std::cerr, argv[0], argv[i]); } } } return 0; }
// v8-shell.m.cpp -*-C++-*- #include <v8.h> #include <fstream> #include <iostream> #include <iterator> #include <sstream> namespace { static const char *toCString(v8::Handle<v8::Value> value) { return *v8::String::Utf8Value(value); } static std::ostream& format(std::ostream& stream, v8::Handle<v8::Message> message) { stream << toCString(message->Get()) << '\n'; auto stack = message->GetStackTrace(); if (!stack.IsEmpty()) { for (int i = 0; i < stack->GetFrameCount(); ++i) { auto frame = stack->GetFrame(i); stream << " at "; if (frame->GetFunctionName()->Length()) { stream << toCString(frame->GetFunctionName()) << " "; } stream << "(" << toCString(frame->GetScriptName()) << ":" << frame->GetLineNumber() << ":" << frame->GetColumn() << ")" << std::endl; } } return stream; } static std::ostream& format(std::ostream& stream, v8::Handle<v8::Value> value) { return stream << toCString(value) << std::endl; } static int read(std::string *result, std::istream& in, std::ostream& out) { result->clear(); out << ">>> "; bool escape = false; bool append = true; while (true) { auto character = in.get(); switch (character) { case -1: { out << "\n"; } return -1; case '\n': { if (escape) { out << "... "; escape = false; } else { return 0; } } break; case '\\': { escape = true; append = false; } break; } if (append) { result->push_back(std::istream::traits_type::to_char_type( character)); } append = true; } } static int evaluate(v8::Handle<v8::Value> *result, v8::Handle<v8::Message> *errorMessage, const std::string& input, const std::string& inputName) { // This will catch errors within this scope v8::TryCatch tryCatch; // Load the input string auto source = v8::String::New(input.data(), input.length()); if (tryCatch.HasCaught()) { *errorMessage = tryCatch.Message(); return -1; } // Compile it auto script = v8::Script::Compile(source, v8::String::New(inputName.data(), inputName.size())); if (tryCatch.HasCaught()) { *errorMessage = tryCatch.Message(); return -1; } // Evaluate it *result = script->Run(); if (tryCatch.HasCaught()) { *errorMessage = tryCatch.Message(); return -1; } return 0; } static void evaluateAndPrint(std::ostream& outStream, std::ostream& errorStream, const std::string& input, const std::string& inputName) { v8::Handle<v8::Value> result; v8::Handle<v8::Message> errorMessage; if (evaluate(&result, &errorMessage, input, inputName)) { format(errorStream, errorMessage); } else { outStream << "-> "; format(outStream, result); } } static int readFile(std::string *contents, const std::string& fileName) { std::filebuf fileBuffer; fileBuffer.open(fileName, std::ios_base::in); if (!fileBuffer.is_open()) { return -1; } std::copy(std::istreambuf_iterator<char>(&fileBuffer), std::istreambuf_iterator<char>(), std::back_inserter(*contents)); fileBuffer.close(); return 0; } static int evaluateFile(std::ostream& outStream, std::ostream& errorStream, const std::string& programName, const std::string& fileName) { std::string input; if (readFile(&input, fileName)) { errorStream << "Usage: " << programName << " [<filename> | -]*\n" << "Failed to open: " << fileName << std::endl; return -1; } evaluateAndPrint(outStream, errorStream, input, fileName); return 0; } static void beginReplLoop(std::istream& inStream, std::ostream& outStream, std::ostream& errorStream) { std::string input; int command = 0; while (read(&input, inStream, outStream) == 0) { std::ostringstream oss; oss << "<stdin:" << ++command << ">"; evaluateAndPrint(outStream, errorStream, input, oss.str()); } } } // close unnamed namespace int main(int argc, char *argv[]) { // Initialize global v8 variables auto *isolate = v8::Isolate::GetCurrent(); v8::V8::SetCaptureStackTraceForUncaughtExceptions( true, 0x100, v8::StackTrace::kDetailed); // Stack-local storage v8::HandleScope handles(isolate); // Create and enter a context auto context = v8::Context::New(isolate); v8::Context::Scope scope(context); if (argc == 1) { beginReplLoop(std::cin, std::cout, std::cerr); } else { for (int i = 1; i < argc; ++i) { if (argv[i][0] == '-') { switch (argv[i][1]) { case '\0': beginReplLoop(std::cin, std::cout, std::cerr); break; case 'h': default: std::cout << "Usage: " << argv[0] << " [<filename> | -]*" << std::endl; break; } } else { evaluateFile(std::cout, std::cerr, argv[0], argv[i]); } } } return 0; }
Use 'auto' where possible.
Use 'auto' where possible.
C++
mit
frutiger/v8-shell
42750865bf323e9fd5bbe8edb0313a9d83997b1c
core/multiproc/src/TMPClient.cxx
core/multiproc/src/TMPClient.cxx
#include "TMPClient.h" #include "TMPWorker.h" #include "MPCode.h" #include "TSocket.h" #include "TGuiFactory.h" //gGuiFactory #include "TVirtualX.h" //gVirtualX #include "TSystem.h" //gSystem #include "TROOT.h" //gROOT #include "TError.h" //gErrorIgnoreLevel #include <unistd.h> // close, fork #include <sys/wait.h> // waitpid #include <errno.h> //errno, used by socketpair #include <sys/socket.h> //socketpair #include <memory> //unique_ptr #include <iostream> ////////////////////////////////////////////////////////////////////////// /// /// \class TMPInterruptHandler /// /// This is an implementation of a TSignalHandler that is added to the /// eventloop in the children processes spawned by a TMPClient. When a SIGINT /// (i.e. kSigInterrupt) is received, TMPInterruptHandler shuts down the /// worker and performs clean-up operations, then exits. /// ////////////////////////////////////////////////////////////////////////// /// Class constructor. TMPInterruptHandler::TMPInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { } /// Executed when SIGINT is received. Clean-up and quit the application Bool_t TMPInterruptHandler::Notify() { std::cerr << "server shutting down on SIGINT" << std::endl; gSystem->Exit(0); return true; } ////////////////////////////////////////////////////////////////////////// /// /// \class TMPClient /// /// Base class for multiprocess applications' clients. It provides a /// simple interface to fork a ROOT session into server/worker sessions /// and exchange messages with them. Multiprocessing applications can build /// on TMPClient and TMPWorker: the class providing multiprocess /// functionalities to users should inherit (possibly privately) from /// TMPClient, and the workers executing tasks should inherit from TMPWorker. /// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// Class constructor. /// \param nWorkers /// \parblock /// the number of children processes that will be created by /// Fork, i.e. the number of workers that will be available after this call. /// The default value (0) means that a number of workers equal to the number /// of cores of the machine is going to be spawned. If that information is /// not available, 2 workers are created instead. /// \endparblock TMPClient::TMPClient(unsigned nWorkers) : fIsParent(true), fWorkerPids(), fMon(), fNWorkers(0) { // decide on number of workers if (nWorkers) { fNWorkers = nWorkers; } else { SysInfo_t si; if (gSystem->GetSysInfo(&si) == 0) fNWorkers = si.fCpus; else fNWorkers = 2; } } ////////////////////////////////////////////////////////////////////////// /// Class destructor. /// This method is in charge of shutting down any remaining worker, /// closing off connections and reap the terminated children processes. TMPClient::~TMPClient() { Broadcast(MPCode::kShutdownOrder); TList *l = fMon.GetListOfActives(); l->Delete(); delete l; l = fMon.GetListOfDeActives(); l->Delete(); delete l; fMon.RemoveAll(); ReapWorkers(); } ////////////////////////////////////////////////////////////////////////// /// This method forks the ROOT session into fNWorkers children processes. /// The ROOT sessions spawned in this way will not have graphical /// capabilities and will not read from standard input, but will be /// connected to the original (interactive) session through TSockets. /// The children processes' PIDs are added to the fWorkerPids vector. /// The parent session can then communicate with the children using the /// Broadcast and MPSend methods, and receive messages through MPRecv.\n /// \param server /// \parblock /// A pointer to an instance of the class that will take control /// of the subprocesses after forking. Applications should implement their /// own class inheriting from TMPWorker. Behaviour can be customized /// overriding TMPWorker::HandleInput. /// \endparblock /// \return true if Fork succeeded, false otherwise bool TMPClient::Fork(TMPWorker &server) { std::string basePath = "/tmp/ROOTMP-"; //fork as many times as needed and save pids pid_t pid = 1; //must be positive to handle the case in which fNWorkers is 0 int sockets[2]; //sockets file descriptors for (unsigned i = 0; i < fNWorkers; ++i) { //create socket pair int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, sockets); if (ret != 0) { std::cerr << "[E][C] Could not create socketpair. Error n. " << errno << ". Now retrying.\n"; --i; continue; } //fork pid = fork(); if (!pid) { //child process, exit loop. sockets[1] is the fd that should be used break; } else { //parent process, create TSocket with current value of sockets[0] close(sockets[1]); //we don't need this TSocket *s = new TSocket(sockets[0], (std::to_string(pid)).c_str()); //TSocket's constructor with this signature seems much faster than TSocket(int fd) if (s && s->IsValid()) { fMon.Add(s); fWorkerPids.push_back(pid); } else { std::cerr << "[E][C] Could not connect to worker with pid " << pid << ". Giving up.\n"; delete s; } } } //parent returns here if (!pid) { //CHILD/SERVER fIsParent = false; //override signal handler (make the servers exit on SIGINT) TSeqCollection *signalHandlers = gSystem->GetListOfSignalHandlers(); TSignalHandler *sh = nullptr; if (signalHandlers && signalHandlers->GetSize() > 0) sh = (TSignalHandler *)signalHandlers->First(); if (sh) gSystem->RemoveSignalHandler(sh); TMPInterruptHandler handler; handler.Add(); //remove stdin from eventloop and close it TSeqCollection *fileHandlers = gSystem->GetListOfFileHandlers(); if (fileHandlers) { for (auto h : *fileHandlers) { if (h && ((TFileHandler *)h)->GetFd() == 0) { gSystem->RemoveFileHandler((TFileHandler *)h); break; } } } close(0); //disable graphics //these instructions were copied from TApplication::MakeBatch gROOT->SetBatch(); if (gGuiFactory != gBatchGuiFactory) delete gGuiFactory; gGuiFactory = gBatchGuiFactory; #ifndef R__WIN32 if (gVirtualX != gGXBatch) delete gVirtualX; #endif gVirtualX = gGXBatch; //prepare server and add it to eventloop server.Init(sockets[1]); gSystem->Run(); } return true; } ////////////////////////////////////////////////////////////////////////// /// Send a message with the specified code to at most nMessages workers. /// Sockets can either be in an "active" or "non-active" state. This method /// activates all the sockets through which the client is connected to the /// workers, and deactivates them when a message is sent to the corresponding /// worker. This way the sockets pertaining to workers who have been left /// idle will be the only ones in the active list /// (TSocket::GetMonitor()->GetListOfActives()) after execution. /// \param code the code to send (e.g. EMPCode) /// \param nMessages /// \parblock /// the maximum number of messages to send. /// If `nMessages == 0 || nMessage > fNWorkers`, send a message to every worker. /// \endparblock /// \return the number of messages successfully sent unsigned TMPClient::Broadcast(unsigned code, unsigned nMessages) { if (nMessages == 0) nMessages = fNWorkers; unsigned count = 0; fMon.ActivateAll(); //send message to all sockets std::unique_ptr<TList> lp(fMon.GetListOfActives()); for (auto s : *lp) { if (count == nMessages) break; if (MPSend((TSocket *)s, code)) { fMon.DeActivate((TSocket *)s); ++count; } else { std::cerr << "[E] Could not send message to server\n"; } } return count; } ////////////////////////////////////////////////////////////////////////// /// DeActivate a certain socket. /// This does not remove it from the monitor: it will be reactivated by /// the next call to Broadcast() (or possibly other methods that are /// specified to do so).\n /// A socket should be DeActivated when the corresponding /// worker is done *for now* and we want to stop listening to this worker's /// socket. If the worker is done *forever*, Remove() should be used instead. /// \param s the socket to be deactivated void TMPClient::DeActivate(TSocket *s) { fMon.DeActivate(s); } ////////////////////////////////////////////////////////////////////////// /// Remove a certain socket from the monitor. /// A socket should be Removed from the monitor when the /// corresponding worker is done *forever*. For example HandleMPCode() /// calls this method on sockets pertaining to workers which sent an /// MPCode::kShutdownNotice.\n /// If the worker is done *for now*, DeActivate should be used instead. /// \param s the socket to be removed from the monitor fMon void TMPClient::Remove(TSocket *s) { fMon.Remove(s); delete s; } ////////////////////////////////////////////////////////////////////////// /// Wait on worker processes and remove their pids from fWorkerPids. /// A blocking waitpid is called, but this should actually not block /// execution since ReapWorkers should only be called when all workers /// have already quit. ReapWorkers is then called not to leave zombie /// processes hanging around, and to clean-up fWorkerPids. void TMPClient::ReapWorkers() { for (auto &pid : fWorkerPids) { waitpid(pid, nullptr, 0); } fWorkerPids.clear(); } ////////////////////////////////////////////////////////////////////////// /// Handle messages containing an EMPCode. /// This method should be called upon receiving a message with a code >= 1000 /// (i.e. EMPCode). It handles the most generic types of messages.\n /// Classes inheriting from TMPClient should implement a similar method /// to handle message codes specific to the application they're part of.\n /// \param msg the MPCodeBufPair returned by a MPRecv call /// \param s /// \parblock /// a pointer to the socket from which the message has been received is passed. /// This way HandleMPCode knows which socket to reply on. /// \endparblock void TMPClient::HandleMPCode(MPCodeBufPair &msg, TSocket *s) { unsigned code = msg.first; //message contains server's pid. retrieve it char *str = new char[msg.second->BufferSize()]; msg.second->ReadString(str, msg.second->BufferSize()); if (code == MPCode::kMessage) { std::cerr << "[I][C] message received: " << str << "\n"; } else if (code == MPCode::kError) { std::cerr << "[E][C] error message received:\n" << str << "\n"; } else if (code == MPCode::kShutdownNotice || code == MPCode::kFatalError) { if (gDebug > 0) //generally users don't want to know this std::cerr << "[I][C] shutdown notice received from " << str << "\n"; Remove(s); } else std::cerr << "[W][C] unknown code received. code=" << code << "\n"; delete [] str; }
#include "TMPClient.h" #include "TMPWorker.h" #include "MPCode.h" #include "TSocket.h" #include "TGuiFactory.h" //gGuiFactory #include "TVirtualX.h" //gVirtualX #include "TSystem.h" //gSystem #include "TROOT.h" //gROOT #include "TError.h" //gErrorIgnoreLevel #include <unistd.h> // close, fork #include <sys/wait.h> // waitpid #include <errno.h> //errno, used by socketpair #include <sys/socket.h> //socketpair #include <memory> //unique_ptr #include <iostream> ////////////////////////////////////////////////////////////////////////// /// /// \class TMPInterruptHandler /// /// This is an implementation of a TSignalHandler that is added to the /// eventloop in the children processes spawned by a TMPClient. When a SIGINT /// (i.e. kSigInterrupt) is received, TMPInterruptHandler shuts down the /// worker and performs clean-up operations, then exits. /// ////////////////////////////////////////////////////////////////////////// /// Class constructor. TMPInterruptHandler::TMPInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { } /// Executed when SIGINT is received. Clean-up and quit the application Bool_t TMPInterruptHandler::Notify() { std::cerr << "server shutting down on SIGINT" << std::endl; gSystem->Exit(0); return true; } ////////////////////////////////////////////////////////////////////////// /// /// \class TMPClient /// /// Base class for multiprocess applications' clients. It provides a /// simple interface to fork a ROOT session into server/worker sessions /// and exchange messages with them. Multiprocessing applications can build /// on TMPClient and TMPWorker: the class providing multiprocess /// functionalities to users should inherit (possibly privately) from /// TMPClient, and the workers executing tasks should inherit from TMPWorker. /// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// Class constructor. /// \param nWorkers /// \parblock /// the number of children processes that will be created by /// Fork, i.e. the number of workers that will be available after this call. /// The default value (0) means that a number of workers equal to the number /// of cores of the machine is going to be spawned. If that information is /// not available, 2 workers are created instead. /// \endparblock TMPClient::TMPClient(unsigned nWorkers) : fIsParent(true), fWorkerPids(), fMon(), fNWorkers(0) { // decide on number of workers if (nWorkers) { fNWorkers = nWorkers; } else { SysInfo_t si; if (gSystem->GetSysInfo(&si) == 0) fNWorkers = si.fCpus; else fNWorkers = 2; } } ////////////////////////////////////////////////////////////////////////// /// Class destructor. /// This method is in charge of shutting down any remaining worker, /// closing off connections and reap the terminated children processes. TMPClient::~TMPClient() { Broadcast(MPCode::kShutdownOrder); TList *l = fMon.GetListOfActives(); l->Delete(); delete l; l = fMon.GetListOfDeActives(); l->Delete(); delete l; fMon.RemoveAll(); ReapWorkers(); } ////////////////////////////////////////////////////////////////////////// /// This method forks the ROOT session into fNWorkers children processes. /// The ROOT sessions spawned in this way will not have graphical /// capabilities and will not read from standard input, but will be /// connected to the original (interactive) session through TSockets. /// The children processes' PIDs are added to the fWorkerPids vector. /// The parent session can then communicate with the children using the /// Broadcast and MPSend methods, and receive messages through MPRecv.\n /// \param server /// \parblock /// A pointer to an instance of the class that will take control /// of the subprocesses after forking. Applications should implement their /// own class inheriting from TMPWorker. Behaviour can be customized /// overriding TMPWorker::HandleInput. /// \endparblock /// \return true if Fork succeeded, false otherwise bool TMPClient::Fork(TMPWorker &server) { std::string basePath = "/tmp/ROOTMP-"; //fork as many times as needed and save pids pid_t pid = 1; //must be positive to handle the case in which fNWorkers is 0 int sockets[2]; //sockets file descriptors for (unsigned i = 0; i < fNWorkers; ++i) { //create socket pair int ret = socketpair(AF_UNIX, SOCK_STREAM, 0, sockets); if (ret != 0) { std::cerr << "[E][C] Could not create socketpair. Error n. " << errno << ". Now retrying.\n"; --i; continue; } //fork pid = fork(); if (!pid) { //child process, exit loop. sockets[1] is the fd that should be used break; } else { //parent process, create TSocket with current value of sockets[0] close(sockets[1]); //we don't need this TSocket *s = new TSocket(sockets[0], (std::to_string(pid)).c_str()); //TSocket's constructor with this signature seems much faster than TSocket(int fd) if (s && s->IsValid()) { fMon.Add(s); fWorkerPids.push_back(pid); } else { std::cerr << "[E][C] Could not connect to worker with pid " << pid << ". Giving up.\n"; delete s; } } } //parent returns here if (!pid) { //CHILD/SERVER fIsParent = false; //override signal handler (make the servers exit on SIGINT) TSeqCollection *signalHandlers = gSystem->GetListOfSignalHandlers(); TSignalHandler *sh = nullptr; if (signalHandlers && signalHandlers->GetSize() > 0) sh = (TSignalHandler *)signalHandlers->First(); if (sh) gSystem->RemoveSignalHandler(sh); TMPInterruptHandler handler; handler.Add(); //remove stdin from eventloop and close it TSeqCollection *fileHandlers = gSystem->GetListOfFileHandlers(); if (fileHandlers) { for (auto h : *fileHandlers) { if (h && ((TFileHandler *)h)->GetFd() == 0) { gSystem->RemoveFileHandler((TFileHandler *)h); break; } } } close(0); //disable graphics //these instructions were copied from TApplication::MakeBatch gROOT->SetBatch(); if (gGuiFactory != gBatchGuiFactory) delete gGuiFactory; gGuiFactory = gBatchGuiFactory; #ifndef R__WIN32 if (gVirtualX != gGXBatch) delete gVirtualX; #endif gVirtualX = gGXBatch; //prepare server and add it to eventloop server.Init(sockets[1]); gSystem->Run(); } return true; } ////////////////////////////////////////////////////////////////////////// /// Send a message with the specified code to at most nMessages workers. /// Sockets can either be in an "active" or "non-active" state. This method /// activates all the sockets through which the client is connected to the /// workers, and deactivates them when a message is sent to the corresponding /// worker. This way the sockets pertaining to workers who have been left /// idle will be the only ones in the active list /// (TSocket::GetMonitor()->GetListOfActives()) after execution. /// \param code the code to send (e.g. EMPCode) /// \param nMessages /// \parblock /// the maximum number of messages to send. /// If `nMessages == 0 || nMessage > fNWorkers`, send a message to every worker. /// \endparblock /// \return the number of messages successfully sent unsigned TMPClient::Broadcast(unsigned code, unsigned nMessages) { if (nMessages == 0) nMessages = fNWorkers; unsigned count = 0; fMon.ActivateAll(); //send message to all sockets std::unique_ptr<TList> lp(fMon.GetListOfActives()); for (auto s : *lp) { if (count == nMessages) break; if (MPSend((TSocket *)s, code)) { fMon.DeActivate((TSocket *)s); ++count; } else { std::cerr << "[E] Could not send message to server\n"; } } return count; } ////////////////////////////////////////////////////////////////////////// /// DeActivate a certain socket. /// This does not remove it from the monitor: it will be reactivated by /// the next call to Broadcast() (or possibly other methods that are /// specified to do so).\n /// A socket should be DeActivated when the corresponding /// worker is done *for now* and we want to stop listening to this worker's /// socket. If the worker is done *forever*, Remove() should be used instead. /// \param s the socket to be deactivated void TMPClient::DeActivate(TSocket *s) { fMon.DeActivate(s); } ////////////////////////////////////////////////////////////////////////// /// Remove a certain socket from the monitor. /// A socket should be Removed from the monitor when the /// corresponding worker is done *forever*. For example HandleMPCode() /// calls this method on sockets pertaining to workers which sent an /// MPCode::kShutdownNotice.\n /// If the worker is done *for now*, DeActivate should be used instead. /// \param s the socket to be removed from the monitor fMon void TMPClient::Remove(TSocket *s) { fMon.Remove(s); delete s; } ////////////////////////////////////////////////////////////////////////// /// Wait on worker processes and remove their pids from fWorkerPids. /// A blocking waitpid is called, but this should actually not block /// execution since ReapWorkers should only be called when all workers /// have already quit. ReapWorkers is then called not to leave zombie /// processes hanging around, and to clean-up fWorkerPids. void TMPClient::ReapWorkers() { for (auto &pid : fWorkerPids) { waitpid(pid, nullptr, 0); } fWorkerPids.clear(); } ////////////////////////////////////////////////////////////////////////// /// Handle messages containing an EMPCode. /// This method should be called upon receiving a message with a code >= 1000 /// (i.e. EMPCode). It handles the most generic types of messages.\n /// Classes inheriting from TMPClient should implement a similar method /// to handle message codes specific to the application they're part of.\n /// \param msg the MPCodeBufPair returned by a MPRecv call /// \param s /// \parblock /// a pointer to the socket from which the message has been received is passed. /// This way HandleMPCode knows which socket to reply on. /// \endparblock void TMPClient::HandleMPCode(MPCodeBufPair &msg, TSocket *s) { unsigned code = msg.first; //message contains server's pid. retrieve it const char *str = ReadBuffer<const char*>(msg.second.get()); if (code == MPCode::kMessage) { std::cerr << "[I][C] message received: " << str << "\n"; } else if (code == MPCode::kError) { std::cerr << "[E][C] error message received:\n" << str << "\n"; } else if (code == MPCode::kShutdownNotice || code == MPCode::kFatalError) { if (gDebug > 0) //generally users don't want to know this std::cerr << "[I][C] shutdown notice received from " << str << "\n"; Remove(s); } else std::cerr << "[W][C] unknown code received. code=" << code << "\n"; delete [] str; }
use ReadBuffer in TMPClient::HandleMPCode
use ReadBuffer in TMPClient::HandleMPCode Signed-off-by: dpiparo <[email protected]>
C++
lgpl-2.1
bbockelm/root,sawenzel/root,veprbl/root,davidlt/root,BerserkerTroll/root,gbitzes/root,georgtroska/root,olifre/root,davidlt/root,zzxuanyuan/root,krafczyk/root,esakellari/root,mkret2/root,gbitzes/root,pspe/root,zzxuanyuan/root-compressor-dummy,lgiommi/root,lgiommi/root,buuck/root,root-mirror/root,pspe/root,zzxuanyuan/root,simonpf/root,zzxuanyuan/root-compressor-dummy,olifre/root,CristinaCristescu/root,zzxuanyuan/root,sirinath/root,mkret2/root,sawenzel/root,sirinath/root,satyarth934/root,satyarth934/root,CristinaCristescu/root,gganis/root,jrtomps/root,jrtomps/root,sawenzel/root,veprbl/root,abhinavmoudgil95/root,agarciamontoro/root,zzxuanyuan/root,sirinath/root,karies/root,thomaskeck/root,lgiommi/root,sawenzel/root,bbockelm/root,agarciamontoro/root,thomaskeck/root,gganis/root,buuck/root,veprbl/root,Y--/root,simonpf/root,davidlt/root,gbitzes/root,CristinaCristescu/root,lgiommi/root,sirinath/root,agarciamontoro/root,krafczyk/root,gbitzes/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root-compressor-dummy,root-mirror/root,BerserkerTroll/root,karies/root,sawenzel/root,root-mirror/root,thomaskeck/root,jrtomps/root,sawenzel/root,karies/root,bbockelm/root,gganis/root,esakellari/root,Y--/root,beniz/root,bbockelm/root,simonpf/root,mkret2/root,sirinath/root,zzxuanyuan/root,veprbl/root,zzxuanyuan/root,agarciamontoro/root,root-mirror/root,lgiommi/root,abhinavmoudgil95/root,davidlt/root,karies/root,lgiommi/root,olifre/root,pspe/root,buuck/root,mkret2/root,esakellari/root,agarciamontoro/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root,olifre/root,zzxuanyuan/root,sirinath/root,esakellari/root,simonpf/root,simonpf/root,jrtomps/root,mkret2/root,lgiommi/root,jrtomps/root,mkret2/root,davidlt/root,buuck/root,abhinavmoudgil95/root,buuck/root,sirinath/root,mhuwiler/rootauto,sirinath/root,gbitzes/root,beniz/root,mattkretz/root,thomaskeck/root,zzxuanyuan/root-compressor-dummy,georgtroska/root,Y--/root,sirinath/root,lgiommi/root,sawenzel/root,pspe/root,agarciamontoro/root,zzxuanyuan/root-compressor-dummy,mattkretz/root,georgtroska/root,satyarth934/root,mattkretz/root,krafczyk/root,thomaskeck/root,georgtroska/root,esakellari/root,lgiommi/root,jrtomps/root,mhuwiler/rootauto,zzxuanyuan/root,BerserkerTroll/root,davidlt/root,Y--/root,BerserkerTroll/root,lgiommi/root,olifre/root,olifre/root,CristinaCristescu/root,gbitzes/root,abhinavmoudgil95/root,krafczyk/root,zzxuanyuan/root-compressor-dummy,simonpf/root,mattkretz/root,root-mirror/root,gganis/root,mhuwiler/rootauto,jrtomps/root,zzxuanyuan/root-compressor-dummy,satyarth934/root,veprbl/root,satyarth934/root,davidlt/root,CristinaCristescu/root,abhinavmoudgil95/root,gbitzes/root,pspe/root,beniz/root,thomaskeck/root,CristinaCristescu/root,olifre/root,mhuwiler/rootauto,thomaskeck/root,Y--/root,simonpf/root,mattkretz/root,agarciamontoro/root,root-mirror/root,mhuwiler/rootauto,mhuwiler/rootauto,mkret2/root,abhinavmoudgil95/root,abhinavmoudgil95/root,satyarth934/root,mattkretz/root,thomaskeck/root,buuck/root,abhinavmoudgil95/root,bbockelm/root,satyarth934/root,simonpf/root,thomaskeck/root,satyarth934/root,davidlt/root,karies/root,Y--/root,buuck/root,pspe/root,gganis/root,krafczyk/root,olifre/root,jrtomps/root,abhinavmoudgil95/root,root-mirror/root,mkret2/root,Y--/root,pspe/root,pspe/root,simonpf/root,satyarth934/root,BerserkerTroll/root,mkret2/root,mattkretz/root,mkret2/root,davidlt/root,olifre/root,esakellari/root,CristinaCristescu/root,abhinavmoudgil95/root,Y--/root,mhuwiler/rootauto,bbockelm/root,mhuwiler/rootauto,veprbl/root,beniz/root,esakellari/root,mhuwiler/rootauto,pspe/root,lgiommi/root,olifre/root,gganis/root,jrtomps/root,karies/root,pspe/root,bbockelm/root,beniz/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root,krafczyk/root,sawenzel/root,krafczyk/root,esakellari/root,gganis/root,gbitzes/root,buuck/root,beniz/root,gganis/root,georgtroska/root,satyarth934/root,georgtroska/root,gganis/root,esakellari/root,agarciamontoro/root,Y--/root,root-mirror/root,BerserkerTroll/root,karies/root,mattkretz/root,krafczyk/root,mhuwiler/rootauto,beniz/root,bbockelm/root,root-mirror/root,beniz/root,krafczyk/root,BerserkerTroll/root,krafczyk/root,sawenzel/root,buuck/root,karies/root,mattkretz/root,BerserkerTroll/root,agarciamontoro/root,davidlt/root,mattkretz/root,georgtroska/root,root-mirror/root,BerserkerTroll/root,zzxuanyuan/root,olifre/root,veprbl/root,gbitzes/root,CristinaCristescu/root,agarciamontoro/root,root-mirror/root,simonpf/root,zzxuanyuan/root-compressor-dummy,karies/root,bbockelm/root,zzxuanyuan/root,veprbl/root,buuck/root,Y--/root,mattkretz/root,sawenzel/root,sirinath/root,sawenzel/root,gbitzes/root,BerserkerTroll/root,gganis/root,krafczyk/root,CristinaCristescu/root,sirinath/root,georgtroska/root,CristinaCristescu/root,veprbl/root,Y--/root,agarciamontoro/root,jrtomps/root,beniz/root,georgtroska/root,beniz/root,georgtroska/root,abhinavmoudgil95/root,buuck/root,thomaskeck/root,bbockelm/root,veprbl/root,CristinaCristescu/root,esakellari/root,davidlt/root,jrtomps/root,gganis/root,mhuwiler/rootauto,karies/root,beniz/root,satyarth934/root,gbitzes/root,esakellari/root,karies/root,simonpf/root,georgtroska/root,mkret2/root,pspe/root,BerserkerTroll/root,bbockelm/root,veprbl/root
81bdeade544eba065c2b85692c7604b0f1c21105
ReactCommon/fabric/uimanager/UIManager.cpp
ReactCommon/fabric/uimanager/UIManager.cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "UIManager.h" #include <react/core/ShadowNodeFragment.h> #include <react/debug/SystraceSection.h> #include <react/graphics/Geometry.h> #include <glog/logging.h> namespace facebook { namespace react { UIManager::~UIManager() { LOG(WARNING) << "UIManager::~UIManager() was called (address: " << this << ")."; } SharedShadowNode UIManager::createNode( Tag tag, std::string const &name, SurfaceId surfaceId, const RawProps &rawProps, SharedEventTarget eventTarget) const { SystraceSection s("UIManager::createNode"); auto &componentDescriptor = componentDescriptorRegistry_->at(name); auto fallbackDescriptor = componentDescriptorRegistry_->getFallbackComponentDescriptor(); auto family = componentDescriptor.createFamily( ShadowNodeFamilyFragment{tag, surfaceId, nullptr}, std::move(eventTarget)); auto const props = componentDescriptor.cloneProps(nullptr, rawProps); auto const state = componentDescriptor.createInitialState(ShadowNodeFragment{props}, family); auto shadowNode = componentDescriptor.createShadowNode( ShadowNodeFragment{ /* .props = */ fallbackDescriptor != nullptr && fallbackDescriptor->getComponentHandle() == componentDescriptor.getComponentHandle() ? componentDescriptor.cloneProps( props, RawProps(folly::dynamic::object("name", name))) : props, /* .children = */ ShadowNodeFragment::childrenPlaceholder(), /* .state = */ state, }, family); if (delegate_) { delegate_->uiManagerDidCreateShadowNode(shadowNode); } return shadowNode; } SharedShadowNode UIManager::cloneNode( const ShadowNode::Shared &shadowNode, const SharedShadowNodeSharedList &children, const RawProps *rawProps) const { SystraceSection s("UIManager::cloneNode"); auto &componentDescriptor = shadowNode->getComponentDescriptor(); auto clonedShadowNode = componentDescriptor.cloneShadowNode( *shadowNode, { /* .props = */ rawProps ? componentDescriptor.cloneProps( shadowNode->getProps(), *rawProps) : ShadowNodeFragment::propsPlaceholder(), /* .children = */ children, }); return clonedShadowNode; } void UIManager::appendChild( const ShadowNode::Shared &parentShadowNode, const ShadowNode::Shared &childShadowNode) const { SystraceSection s("UIManager::appendChild"); auto &componentDescriptor = parentShadowNode->getComponentDescriptor(); componentDescriptor.appendChild(parentShadowNode, childShadowNode); } void UIManager::completeSurface( SurfaceId surfaceId, const SharedShadowNodeUnsharedList &rootChildren) const { SystraceSection s("UIManager::completeSurface"); shadowTreeRegistry_.visit(surfaceId, [&](ShadowTree const &shadowTree) { shadowTree.commit( [&](RootShadowNode::Shared const &oldRootShadowNode) { return std::make_shared<RootShadowNode>( *oldRootShadowNode, ShadowNodeFragment{ /* .props = */ ShadowNodeFragment::propsPlaceholder(), /* .children = */ rootChildren, }); }, true); }); } void UIManager::setJSResponder( const ShadowNode::Shared &shadowNode, const bool blockNativeResponder) const { if (delegate_) { delegate_->uiManagerDidSetJSResponder( shadowNode->getSurfaceId(), shadowNode, blockNativeResponder); } } void UIManager::clearJSResponder() const { if (delegate_) { delegate_->uiManagerDidClearJSResponder(); } } ShadowNode::Shared const *UIManager::getNewestCloneOfShadowNode( ShadowNode const &shadowNode) const { auto findNewestChildInParent = [&](auto const &parentNode) -> ShadowNode::Shared const * { for (auto const &child : parentNode.getChildren()) { if (ShadowNode::sameFamily(*child, shadowNode)) { return &child; } } return nullptr; }; ShadowNode const *ancestorShadowNode; shadowTreeRegistry_.visit( shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit( [&](RootShadowNode::Shared const &oldRootShadowNode) { ancestorShadowNode = oldRootShadowNode.get(); return nullptr; }, true); }); auto ancestors = shadowNode.getFamily().getAncestors(*ancestorShadowNode); if (ancestors.rbegin() == ancestors.rend()) { return nullptr; } return findNewestChildInParent(ancestors.rbegin()->first.get()); } ShadowNode::Shared UIManager::findNodeAtPoint( ShadowNode::Shared const &node, Point point) const { return LayoutableShadowNode::findNodeAtPoint( *getNewestCloneOfShadowNode(*node), point); } void UIManager::setNativeProps( ShadowNode const &shadowNode, RawProps const &rawProps) const { SystraceSection s("UIManager::setNativeProps"); auto &componentDescriptor = shadowNode.getComponentDescriptor(); auto props = componentDescriptor.cloneProps(shadowNode.getProps(), rawProps); shadowTreeRegistry_.visit( shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit( [&](RootShadowNode::Shared const &oldRootShadowNode) { return std::static_pointer_cast<RootShadowNode>( oldRootShadowNode->cloneTree( shadowNode.getFamily(), [&](ShadowNode const &oldShadowNode) { return oldShadowNode.clone({ /* .props = */ props, }); })); }, true); }); } LayoutMetrics UIManager::getRelativeLayoutMetrics( ShadowNode const &shadowNode, ShadowNode const *ancestorShadowNode, LayoutableShadowNode::LayoutInspectingPolicy policy) const { SystraceSection s("UIManager::getRelativeLayoutMetrics"); if (!ancestorShadowNode) { shadowTreeRegistry_.visit( shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit( [&](RootShadowNode::Shared const &oldRootShadowNode) { ancestorShadowNode = oldRootShadowNode.get(); return nullptr; }, true); }); } // Get latest version of both the ShadowNode and its ancestor. // It is possible for JS (or other callers) to have a reference // to a previous version of ShadowNodes, but we enforce that // metrics are only calculated on most recently committed versions. auto newestShadowNode = getNewestCloneOfShadowNode(shadowNode); auto newestAncestorShadowNode = ancestorShadowNode == nullptr ? nullptr : getNewestCloneOfShadowNode(*ancestorShadowNode); auto layoutableShadowNode = traitCast<LayoutableShadowNode const *>(newestShadowNode->get()); auto layoutableAncestorShadowNode = (newestAncestorShadowNode == nullptr ? nullptr : traitCast<LayoutableShadowNode const *>( newestAncestorShadowNode->get())); if (!layoutableShadowNode || !layoutableAncestorShadowNode) { return EmptyLayoutMetrics; } return layoutableShadowNode->getRelativeLayoutMetrics( *layoutableAncestorShadowNode, policy); } void UIManager::updateState(StateUpdate const &stateUpdate) const { auto &callback = stateUpdate.callback; auto &family = stateUpdate.family; auto &componentDescriptor = family->getComponentDescriptor(); shadowTreeRegistry_.visit( family->getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit([&](RootShadowNode::Shared const &oldRootShadowNode) { return std::static_pointer_cast< RootShadowNode>(oldRootShadowNode->cloneTree( *family, [&](ShadowNode const &oldShadowNode) { auto newData = callback(oldShadowNode.getState()->getDataPointer()); auto newState = componentDescriptor.createState(*family, newData); return oldShadowNode.clone({ /* .props = */ ShadowNodeFragment::propsPlaceholder(), /* .children = */ ShadowNodeFragment::childrenPlaceholder(), /* .state = */ newState, }); })); }); }); } void UIManager::dispatchCommand( const ShadowNode::Shared &shadowNode, std::string const &commandName, folly::dynamic const args) const { if (delegate_) { delegate_->uiManagerDidDispatchCommand(shadowNode, commandName, args); } } void UIManager::setComponentDescriptorRegistry( const SharedComponentDescriptorRegistry &componentDescriptorRegistry) { componentDescriptorRegistry_ = componentDescriptorRegistry; } void UIManager::setDelegate(UIManagerDelegate *delegate) { delegate_ = delegate; } UIManagerDelegate *UIManager::getDelegate() { return delegate_; } void UIManager::visitBinding( std::function<void(UIManagerBinding const &uiManagerBinding)> callback) const { if (!uiManagerBinding_) { return; } callback(*uiManagerBinding_); } ShadowTreeRegistry const &UIManager::getShadowTreeRegistry() const { return shadowTreeRegistry_; } #pragma mark - ShadowTreeDelegate void UIManager::shadowTreeDidFinishTransaction( ShadowTree const &shadowTree, MountingCoordinator::Shared const &mountingCoordinator) const { SystraceSection s("UIManager::shadowTreeDidFinishTransaction"); if (delegate_) { delegate_->uiManagerDidFinishTransaction(mountingCoordinator); } } } // namespace react } // namespace facebook
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "UIManager.h" #include <react/core/ShadowNodeFragment.h> #include <react/debug/SystraceSection.h> #include <react/graphics/Geometry.h> #include <glog/logging.h> namespace facebook { namespace react { UIManager::~UIManager() { LOG(WARNING) << "UIManager::~UIManager() was called (address: " << this << ")."; } SharedShadowNode UIManager::createNode( Tag tag, std::string const &name, SurfaceId surfaceId, const RawProps &rawProps, SharedEventTarget eventTarget) const { SystraceSection s("UIManager::createNode"); auto &componentDescriptor = componentDescriptorRegistry_->at(name); auto fallbackDescriptor = componentDescriptorRegistry_->getFallbackComponentDescriptor(); auto family = componentDescriptor.createFamily( ShadowNodeFamilyFragment{tag, surfaceId, nullptr}, std::move(eventTarget)); auto const props = componentDescriptor.cloneProps(nullptr, rawProps); auto const state = componentDescriptor.createInitialState(ShadowNodeFragment{props}, family); auto shadowNode = componentDescriptor.createShadowNode( ShadowNodeFragment{ /* .props = */ fallbackDescriptor != nullptr && fallbackDescriptor->getComponentHandle() == componentDescriptor.getComponentHandle() ? componentDescriptor.cloneProps( props, RawProps(folly::dynamic::object("name", name))) : props, /* .children = */ ShadowNodeFragment::childrenPlaceholder(), /* .state = */ state, }, family); if (delegate_) { delegate_->uiManagerDidCreateShadowNode(shadowNode); } return shadowNode; } SharedShadowNode UIManager::cloneNode( const ShadowNode::Shared &shadowNode, const SharedShadowNodeSharedList &children, const RawProps *rawProps) const { SystraceSection s("UIManager::cloneNode"); auto &componentDescriptor = shadowNode->getComponentDescriptor(); auto clonedShadowNode = componentDescriptor.cloneShadowNode( *shadowNode, { /* .props = */ rawProps ? componentDescriptor.cloneProps( shadowNode->getProps(), *rawProps) : ShadowNodeFragment::propsPlaceholder(), /* .children = */ children, }); return clonedShadowNode; } void UIManager::appendChild( const ShadowNode::Shared &parentShadowNode, const ShadowNode::Shared &childShadowNode) const { SystraceSection s("UIManager::appendChild"); auto &componentDescriptor = parentShadowNode->getComponentDescriptor(); componentDescriptor.appendChild(parentShadowNode, childShadowNode); } void UIManager::completeSurface( SurfaceId surfaceId, const SharedShadowNodeUnsharedList &rootChildren) const { SystraceSection s("UIManager::completeSurface"); shadowTreeRegistry_.visit(surfaceId, [&](ShadowTree const &shadowTree) { shadowTree.commit( [&](RootShadowNode::Shared const &oldRootShadowNode) { return std::make_shared<RootShadowNode>( *oldRootShadowNode, ShadowNodeFragment{ /* .props = */ ShadowNodeFragment::propsPlaceholder(), /* .children = */ rootChildren, }); }, true); }); } void UIManager::setJSResponder( const ShadowNode::Shared &shadowNode, const bool blockNativeResponder) const { if (delegate_) { delegate_->uiManagerDidSetJSResponder( shadowNode->getSurfaceId(), shadowNode, blockNativeResponder); } } void UIManager::clearJSResponder() const { if (delegate_) { delegate_->uiManagerDidClearJSResponder(); } } ShadowNode::Shared const *UIManager::getNewestCloneOfShadowNode( ShadowNode const &shadowNode) const { auto findNewestChildInParent = [&](auto const &parentNode) -> ShadowNode::Shared const * { for (auto const &child : parentNode.getChildren()) { if (ShadowNode::sameFamily(*child, shadowNode)) { return &child; } } return nullptr; }; ShadowNode const *ancestorShadowNode; shadowTreeRegistry_.visit( shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit( [&](RootShadowNode::Shared const &oldRootShadowNode) { ancestorShadowNode = oldRootShadowNode.get(); return nullptr; }, true); }); auto ancestors = shadowNode.getFamily().getAncestors(*ancestorShadowNode); return findNewestChildInParent(ancestors.rbegin()->first.get()); } ShadowNode::Shared UIManager::findNodeAtPoint( ShadowNode::Shared const &node, Point point) const { return LayoutableShadowNode::findNodeAtPoint( *getNewestCloneOfShadowNode(*node), point); } void UIManager::setNativeProps( ShadowNode const &shadowNode, RawProps const &rawProps) const { SystraceSection s("UIManager::setNativeProps"); auto &componentDescriptor = shadowNode.getComponentDescriptor(); auto props = componentDescriptor.cloneProps(shadowNode.getProps(), rawProps); shadowTreeRegistry_.visit( shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit( [&](RootShadowNode::Shared const &oldRootShadowNode) { return std::static_pointer_cast<RootShadowNode>( oldRootShadowNode->cloneTree( shadowNode.getFamily(), [&](ShadowNode const &oldShadowNode) { return oldShadowNode.clone({ /* .props = */ props, }); })); }, true); }); } LayoutMetrics UIManager::getRelativeLayoutMetrics( ShadowNode const &shadowNode, ShadowNode const *ancestorShadowNode, LayoutableShadowNode::LayoutInspectingPolicy policy) const { SystraceSection s("UIManager::getRelativeLayoutMetrics"); if (!ancestorShadowNode) { shadowTreeRegistry_.visit( shadowNode.getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit( [&](RootShadowNode::Shared const &oldRootShadowNode) { ancestorShadowNode = oldRootShadowNode.get(); return nullptr; }, true); }); } else { ancestorShadowNode = getNewestCloneOfShadowNode(*ancestorShadowNode)->get(); } // Get latest version of both the ShadowNode and its ancestor. // It is possible for JS (or other callers) to have a reference // to a previous version of ShadowNodes, but we enforce that // metrics are only calculated on most recently committed versions. auto newestShadowNode = getNewestCloneOfShadowNode(shadowNode); auto layoutableShadowNode = traitCast<LayoutableShadowNode const *>(newestShadowNode->get()); auto layoutableAncestorShadowNode = traitCast<LayoutableShadowNode const *>(ancestorShadowNode); if (!layoutableShadowNode || !layoutableAncestorShadowNode) { return EmptyLayoutMetrics; } return layoutableShadowNode->getRelativeLayoutMetrics( *layoutableAncestorShadowNode, policy); } void UIManager::updateState(StateUpdate const &stateUpdate) const { auto &callback = stateUpdate.callback; auto &family = stateUpdate.family; auto &componentDescriptor = family->getComponentDescriptor(); shadowTreeRegistry_.visit( family->getSurfaceId(), [&](ShadowTree const &shadowTree) { shadowTree.tryCommit([&](RootShadowNode::Shared const &oldRootShadowNode) { return std::static_pointer_cast< RootShadowNode>(oldRootShadowNode->cloneTree( *family, [&](ShadowNode const &oldShadowNode) { auto newData = callback(oldShadowNode.getState()->getDataPointer()); auto newState = componentDescriptor.createState(*family, newData); return oldShadowNode.clone({ /* .props = */ ShadowNodeFragment::propsPlaceholder(), /* .children = */ ShadowNodeFragment::childrenPlaceholder(), /* .state = */ newState, }); })); }); }); } void UIManager::dispatchCommand( const ShadowNode::Shared &shadowNode, std::string const &commandName, folly::dynamic const args) const { if (delegate_) { delegate_->uiManagerDidDispatchCommand(shadowNode, commandName, args); } } void UIManager::setComponentDescriptorRegistry( const SharedComponentDescriptorRegistry &componentDescriptorRegistry) { componentDescriptorRegistry_ = componentDescriptorRegistry; } void UIManager::setDelegate(UIManagerDelegate *delegate) { delegate_ = delegate; } UIManagerDelegate *UIManager::getDelegate() { return delegate_; } void UIManager::visitBinding( std::function<void(UIManagerBinding const &uiManagerBinding)> callback) const { if (!uiManagerBinding_) { return; } callback(*uiManagerBinding_); } ShadowTreeRegistry const &UIManager::getShadowTreeRegistry() const { return shadowTreeRegistry_; } #pragma mark - ShadowTreeDelegate void UIManager::shadowTreeDidFinishTransaction( ShadowTree const &shadowTree, MountingCoordinator::Shared const &mountingCoordinator) const { SystraceSection s("UIManager::shadowTreeDidFinishTransaction"); if (delegate_) { delegate_->uiManagerDidFinishTransaction(mountingCoordinator); } } } // namespace react } // namespace facebook
Fix broken touches on all Fabric surfaces
Fix broken touches on all Fabric surfaces Reviewed By: shergin Differential Revision: D21261996 fbshipit-source-id: f42c19295ac127eca653631faad0ced4900f4758
C++
mit
facebook/react-native,janicduplessis/react-native,hoangpham95/react-native,myntra/react-native,hoangpham95/react-native,janicduplessis/react-native,arthuralee/react-native,facebook/react-native,pandiaraj44/react-native,facebook/react-native,arthuralee/react-native,pandiaraj44/react-native,hoangpham95/react-native,javache/react-native,hoangpham95/react-native,hoangpham95/react-native,arthuralee/react-native,facebook/react-native,facebook/react-native,pandiaraj44/react-native,javache/react-native,javache/react-native,arthuralee/react-native,myntra/react-native,janicduplessis/react-native,janicduplessis/react-native,javache/react-native,myntra/react-native,myntra/react-native,myntra/react-native,pandiaraj44/react-native,javache/react-native,pandiaraj44/react-native,janicduplessis/react-native,myntra/react-native,myntra/react-native,myntra/react-native,javache/react-native,janicduplessis/react-native,arthuralee/react-native,facebook/react-native,hoangpham95/react-native,janicduplessis/react-native,myntra/react-native,hoangpham95/react-native,pandiaraj44/react-native,facebook/react-native,javache/react-native,pandiaraj44/react-native,facebook/react-native,javache/react-native,facebook/react-native,janicduplessis/react-native,pandiaraj44/react-native,javache/react-native,hoangpham95/react-native
eb6a18f6d8a7ef1c2309a79d6507a1ac6c81f314
Rendering/Testing/Cxx/SurfacePlusEdges.cxx
Rendering/Testing/Cxx/SurfacePlusEdges.cxx
/*========================================================================= Program: Visualization Toolkit Module: SurfacePlusEdges.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ // This test draws a sphere with the edges shown. It also turns on coincident // topology resolution with a z-shift to both make sure the wireframe is // visible and to exercise that type of coincident topology resolution. #include "vtkActor.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSphereSource.h" #include "vtkSmartPointer.h" #define VTK_CREATE(type, var) \ vtkSmartPointer<type> var = vtkSmartPointer<type>::New() int SurfacePlusEdges(int argc, char *argv[]) { vtkMapper::SetResolveCoincidentTopologyToShiftZBuffer(); vtkMapper::SetResolveCoincidentTopologyZShift(0.002); VTK_CREATE(vtkSphereSource, sphere); VTK_CREATE(vtkPolyDataMapper, mapper); mapper->SetInputConnection(sphere->GetOutputPort()); VTK_CREATE(vtkActor, actor); actor->SetMapper(mapper); actor->GetProperty()->EdgeVisibilityOn(); actor->GetProperty()->SetEdgeColor(1.0, 0.0, 0.0); VTK_CREATE(vtkRenderer, renderer); renderer->AddActor(actor); renderer->ResetCamera(); VTK_CREATE(vtkRenderWindow, renwin); renwin->AddRenderer(renderer); renwin->SetSize(250, 250); int retVal = vtkRegressionTestImage(renwin); if (retVal == vtkRegressionTester::DO_INTERACTOR) { VTK_CREATE(vtkRenderWindowInteractor, iren); iren->SetRenderWindow(renwin); iren->Initialize(); iren->Start(); retVal = vtkRegressionTester::PASSED; } return (retVal == vtkRegressionTester::PASSED) ? 0 : 1; }
/*========================================================================= Program: Visualization Toolkit Module: SurfacePlusEdges.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information. =========================================================================*/ /*---------------------------------------------------------------------------- Copyright (c) Sandia Corporation See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. ----------------------------------------------------------------------------*/ // This test draws a sphere with the edges shown. It also turns on coincident // topology resolution with a z-shift to both make sure the wireframe is // visible and to exercise that type of coincident topology resolution. #include "vtkActor.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkSphereSource.h" #include "vtkSmartPointer.h" #define VTK_CREATE(type, var) \ vtkSmartPointer<type> var = vtkSmartPointer<type>::New() int SurfacePlusEdges(int argc, char *argv[]) { vtkMapper::SetResolveCoincidentTopologyToShiftZBuffer(); vtkMapper::SetResolveCoincidentTopologyZShift(0.1); VTK_CREATE(vtkSphereSource, sphere); VTK_CREATE(vtkPolyDataMapper, mapper); mapper->SetInputConnection(sphere->GetOutputPort()); VTK_CREATE(vtkActor, actor); actor->SetMapper(mapper); actor->GetProperty()->EdgeVisibilityOn(); actor->GetProperty()->SetEdgeColor(1.0, 0.0, 0.0); VTK_CREATE(vtkRenderer, renderer); renderer->AddActor(actor); renderer->ResetCamera(); VTK_CREATE(vtkRenderWindow, renwin); renwin->AddRenderer(renderer); renwin->SetSize(250, 250); int retVal = vtkRegressionTestImage(renwin); if (retVal == vtkRegressionTester::DO_INTERACTOR) { VTK_CREATE(vtkRenderWindowInteractor, iren); iren->SetRenderWindow(renwin); iren->Initialize(); iren->Start(); retVal = vtkRegressionTester::PASSED; } return (retVal == vtkRegressionTester::PASSED) ? 0 : 1; }
adjust test to hopefully get it to pass on midworld.
ENH: adjust test to hopefully get it to pass on midworld.
C++
bsd-3-clause
hendradarwin/VTK,sumedhasingla/VTK,sankhesh/VTK,sumedhasingla/VTK,jmerkow/VTK,mspark93/VTK,demarle/VTK,biddisco/VTK,Wuteyan/VTK,ashray/VTK-EVM,ashray/VTK-EVM,cjh1/VTK,keithroe/vtkoptix,candy7393/VTK,sankhesh/VTK,berendkleinhaneveld/VTK,candy7393/VTK,ashray/VTK-EVM,hendradarwin/VTK,sumedhasingla/VTK,demarle/VTK,aashish24/VTK-old,aashish24/VTK-old,jmerkow/VTK,arnaudgelas/VTK,naucoin/VTKSlicerWidgets,johnkit/vtk-dev,biddisco/VTK,sankhesh/VTK,demarle/VTK,berendkleinhaneveld/VTK,jmerkow/VTK,sankhesh/VTK,cjh1/VTK,Wuteyan/VTK,demarle/VTK,mspark93/VTK,collects/VTK,aashish24/VTK-old,johnkit/vtk-dev,msmolens/VTK,mspark93/VTK,berendkleinhaneveld/VTK,mspark93/VTK,jeffbaumes/jeffbaumes-vtk,berendkleinhaneveld/VTK,cjh1/VTK,gram526/VTK,jmerkow/VTK,arnaudgelas/VTK,keithroe/vtkoptix,hendradarwin/VTK,ashray/VTK-EVM,msmolens/VTK,mspark93/VTK,naucoin/VTKSlicerWidgets,sumedhasingla/VTK,Wuteyan/VTK,naucoin/VTKSlicerWidgets,collects/VTK,candy7393/VTK,msmolens/VTK,johnkit/vtk-dev,SimVascular/VTK,Wuteyan/VTK,biddisco/VTK,daviddoria/PointGraphsPhase1,spthaolt/VTK,naucoin/VTKSlicerWidgets,candy7393/VTK,jeffbaumes/jeffbaumes-vtk,cjh1/VTK,aashish24/VTK-old,ashray/VTK-EVM,demarle/VTK,mspark93/VTK,mspark93/VTK,cjh1/VTK,hendradarwin/VTK,daviddoria/PointGraphsPhase1,demarle/VTK,SimVascular/VTK,demarle/VTK,ashray/VTK-EVM,candy7393/VTK,candy7393/VTK,spthaolt/VTK,biddisco/VTK,keithroe/vtkoptix,jeffbaumes/jeffbaumes-vtk,sumedhasingla/VTK,cjh1/VTK,aashish24/VTK-old,keithroe/vtkoptix,johnkit/vtk-dev,sumedhasingla/VTK,ashray/VTK-EVM,daviddoria/PointGraphsPhase1,biddisco/VTK,keithroe/vtkoptix,SimVascular/VTK,berendkleinhaneveld/VTK,gram526/VTK,sankhesh/VTK,spthaolt/VTK,jmerkow/VTK,msmolens/VTK,sankhesh/VTK,gram526/VTK,johnkit/vtk-dev,arnaudgelas/VTK,SimVascular/VTK,msmolens/VTK,aashish24/VTK-old,gram526/VTK,berendkleinhaneveld/VTK,msmolens/VTK,daviddoria/PointGraphsPhase1,collects/VTK,daviddoria/PointGraphsPhase1,SimVascular/VTK,Wuteyan/VTK,candy7393/VTK,Wuteyan/VTK,collects/VTK,keithroe/vtkoptix,jeffbaumes/jeffbaumes-vtk,biddisco/VTK,naucoin/VTKSlicerWidgets,jmerkow/VTK,arnaudgelas/VTK,demarle/VTK,jeffbaumes/jeffbaumes-vtk,msmolens/VTK,sumedhasingla/VTK,collects/VTK,jmerkow/VTK,spthaolt/VTK,sumedhasingla/VTK,keithroe/vtkoptix,SimVascular/VTK,arnaudgelas/VTK,hendradarwin/VTK,naucoin/VTKSlicerWidgets,gram526/VTK,berendkleinhaneveld/VTK,johnkit/vtk-dev,johnkit/vtk-dev,biddisco/VTK,SimVascular/VTK,Wuteyan/VTK,collects/VTK,sankhesh/VTK,ashray/VTK-EVM,daviddoria/PointGraphsPhase1,gram526/VTK,gram526/VTK,hendradarwin/VTK,gram526/VTK,keithroe/vtkoptix,mspark93/VTK,spthaolt/VTK,spthaolt/VTK,arnaudgelas/VTK,sankhesh/VTK,spthaolt/VTK,candy7393/VTK,jmerkow/VTK,jeffbaumes/jeffbaumes-vtk,hendradarwin/VTK,msmolens/VTK,SimVascular/VTK
ab8713d7921ba915efb4e2f1f40ad0b3ce1a12f2
src/plugins/remotelinux/genericremotelinuxdeploystepfactory.cpp
src/plugins/remotelinux/genericremotelinuxdeploystepfactory.cpp
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "genericremotelinuxdeploystepfactory.h" #include "genericdirectuploadstep.h" #include "maemopackagecreationstep.h" #include "remotelinuxdeployconfigurationfactory.h" #include "uploadandinstalltarpackagestep.h" #include <projectexplorer/buildsteplist.h> #include <projectexplorer/deployconfiguration.h> using namespace ProjectExplorer; namespace RemoteLinux { namespace Internal { GenericRemoteLinuxDeployStepFactory::GenericRemoteLinuxDeployStepFactory(QObject *parent) : IBuildStepFactory(parent) { } QStringList GenericRemoteLinuxDeployStepFactory::availableCreationIds(BuildStepList *parent) const { QStringList ids; if (qobject_cast<DeployConfiguration *>(parent->parent())->id() != RemoteLinuxDeployConfigurationFactory::genericDeployConfigurationId()) { return ids; } ids << MaemoTarPackageCreationStep::CreatePackageId << UploadAndInstallTarPackageStep::stepId() << GenericDirectUploadStep::stepId(); return ids; } QString GenericRemoteLinuxDeployStepFactory::displayNameForId(const QString &id) const { if (id == MaemoTarPackageCreationStep::CreatePackageId) return tr("Create tarball"); if (id == UploadAndInstallTarPackageStep::stepId()) return UploadAndInstallTarPackageStep::displayName(); if (id == GenericDirectUploadStep::stepId()) return GenericDirectUploadStep::displayName(); return QString(); } bool GenericRemoteLinuxDeployStepFactory::canCreate(BuildStepList *parent, const QString &id) const { return availableCreationIds(parent).contains(id); } BuildStep *GenericRemoteLinuxDeployStepFactory::create(BuildStepList *parent, const QString &id) { Q_ASSERT(canCreate(parent, id)); if (id == MaemoTarPackageCreationStep::CreatePackageId) return new MaemoTarPackageCreationStep(parent); if (id == UploadAndInstallTarPackageStep::stepId()) return new UploadAndInstallTarPackageStep(parent); if (id == GenericDirectUploadStep::stepId()) return new GenericDirectUploadStep(parent, GenericDirectUploadStep::stepId()); return 0; } bool GenericRemoteLinuxDeployStepFactory::canRestore(BuildStepList *parent, const QVariantMap &map) const { return canCreate(parent, idFromMap(map)); } BuildStep *GenericRemoteLinuxDeployStepFactory::restore(BuildStepList *parent, const QVariantMap &map) { Q_ASSERT(canRestore(parent, map)); BuildStep * const step = create(parent, idFromMap(map)); if (!step->fromMap(map)) { delete step; return 0; } return step; } bool GenericRemoteLinuxDeployStepFactory::canClone(BuildStepList *parent, BuildStep *product) const { return canCreate(parent, product->id()); } BuildStep *GenericRemoteLinuxDeployStepFactory::clone(BuildStepList *parent, BuildStep *product) { if (MaemoTarPackageCreationStep * const other = qobject_cast<MaemoTarPackageCreationStep *>(product)) return new MaemoTarPackageCreationStep(parent, other); if (UploadAndInstallTarPackageStep * const other = qobject_cast<UploadAndInstallTarPackageStep*>(product)) return new UploadAndInstallTarPackageStep(parent, other); if (GenericDirectUploadStep * const other = qobject_cast<GenericDirectUploadStep *>(product)) return new GenericDirectUploadStep(parent, other); return 0; } } // namespace Internal } // namespace RemoteLinux
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "genericremotelinuxdeploystepfactory.h" #include "genericdirectuploadstep.h" #include "maemopackagecreationstep.h" #include "remotelinuxdeployconfigurationfactory.h" #include "uploadandinstalltarpackagestep.h" #include <projectexplorer/buildsteplist.h> #include <projectexplorer/deployconfiguration.h> using namespace ProjectExplorer; namespace RemoteLinux { namespace Internal { GenericRemoteLinuxDeployStepFactory::GenericRemoteLinuxDeployStepFactory(QObject *parent) : IBuildStepFactory(parent) { } QStringList GenericRemoteLinuxDeployStepFactory::availableCreationIds(BuildStepList *parent) const { QStringList ids; const DeployConfiguration * const dc = qobject_cast<DeployConfiguration *>(parent->parent()); if (!dc || dc->id() != RemoteLinuxDeployConfigurationFactory::genericDeployConfigurationId()) return ids; ids << MaemoTarPackageCreationStep::CreatePackageId << UploadAndInstallTarPackageStep::stepId() << GenericDirectUploadStep::stepId(); return ids; } QString GenericRemoteLinuxDeployStepFactory::displayNameForId(const QString &id) const { if (id == MaemoTarPackageCreationStep::CreatePackageId) return tr("Create tarball"); if (id == UploadAndInstallTarPackageStep::stepId()) return UploadAndInstallTarPackageStep::displayName(); if (id == GenericDirectUploadStep::stepId()) return GenericDirectUploadStep::displayName(); return QString(); } bool GenericRemoteLinuxDeployStepFactory::canCreate(BuildStepList *parent, const QString &id) const { return availableCreationIds(parent).contains(id); } BuildStep *GenericRemoteLinuxDeployStepFactory::create(BuildStepList *parent, const QString &id) { Q_ASSERT(canCreate(parent, id)); if (id == MaemoTarPackageCreationStep::CreatePackageId) return new MaemoTarPackageCreationStep(parent); if (id == UploadAndInstallTarPackageStep::stepId()) return new UploadAndInstallTarPackageStep(parent); if (id == GenericDirectUploadStep::stepId()) return new GenericDirectUploadStep(parent, GenericDirectUploadStep::stepId()); return 0; } bool GenericRemoteLinuxDeployStepFactory::canRestore(BuildStepList *parent, const QVariantMap &map) const { return canCreate(parent, idFromMap(map)); } BuildStep *GenericRemoteLinuxDeployStepFactory::restore(BuildStepList *parent, const QVariantMap &map) { Q_ASSERT(canRestore(parent, map)); BuildStep * const step = create(parent, idFromMap(map)); if (!step->fromMap(map)) { delete step; return 0; } return step; } bool GenericRemoteLinuxDeployStepFactory::canClone(BuildStepList *parent, BuildStep *product) const { return canCreate(parent, product->id()); } BuildStep *GenericRemoteLinuxDeployStepFactory::clone(BuildStepList *parent, BuildStep *product) { if (MaemoTarPackageCreationStep * const other = qobject_cast<MaemoTarPackageCreationStep *>(product)) return new MaemoTarPackageCreationStep(parent, other); if (UploadAndInstallTarPackageStep * const other = qobject_cast<UploadAndInstallTarPackageStep*>(product)) return new UploadAndInstallTarPackageStep(parent, other); if (GenericDirectUploadStep * const other = qobject_cast<GenericDirectUploadStep *>(product)) return new GenericDirectUploadStep(parent, other); return 0; } } // namespace Internal } // namespace RemoteLinux
Fix crash in deploy config factory.
RemoteLinux: Fix crash in deploy config factory. Change-Id: Ie4742619ae4b1138ba59dfe9ac9162a992cdfc18 Reviewed-on: http://codereview.qt.nokia.com/1697 Reviewed-by: Roberto Raggi <[email protected]>
C++
lgpl-2.1
duythanhphan/qt-creator,omniacreator/qtcreator,KDE/android-qt-creator,Distrotech/qtcreator,maui-packages/qt-creator,hdweiss/qt-creator-visualizer,richardmg/qtcreator,azat/qtcreator,AltarBeastiful/qt-creator,danimo/qt-creator,KDE/android-qt-creator,KDAB/KDAB-Creator,danimo/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,ostash/qt-creator-i18n-uk,malikcjm/qtcreator,hdweiss/qt-creator-visualizer,danimo/qt-creator,jonnor/qt-creator,malikcjm/qtcreator,maui-packages/qt-creator,amyvmiwei/qt-creator,ostash/qt-creator-i18n-uk,azat/qtcreator,azat/qtcreator,darksylinc/qt-creator,dmik/qt-creator-os2,amyvmiwei/qt-creator,Distrotech/qtcreator,martyone/sailfish-qtcreator,jonnor/qt-creator,martyone/sailfish-qtcreator,dmik/qt-creator-os2,kuba1/qtcreator,farseerri/git_code,bakaiadam/collaborative_qt_creator,bakaiadam/collaborative_qt_creator,darksylinc/qt-creator,kuba1/qtcreator,danimo/qt-creator,duythanhphan/qt-creator,colede/qtcreator,malikcjm/qtcreator,KDE/android-qt-creator,ostash/qt-creator-i18n-uk,danimo/qt-creator,AltarBeastiful/qt-creator,KDE/android-qt-creator,duythanhphan/qt-creator,martyone/sailfish-qtcreator,danimo/qt-creator,darksylinc/qt-creator,Distrotech/qtcreator,amyvmiwei/qt-creator,maui-packages/qt-creator,AltarBeastiful/qt-creator,malikcjm/qtcreator,dmik/qt-creator-os2,farseerri/git_code,bakaiadam/collaborative_qt_creator,omniacreator/qtcreator,xianian/qt-creator,colede/qtcreator,KDE/android-qt-creator,maui-packages/qt-creator,duythanhphan/qt-creator,dmik/qt-creator-os2,martyone/sailfish-qtcreator,colede/qtcreator,hdweiss/qt-creator-visualizer,ostash/qt-creator-i18n-uk,syntheticpp/qt-creator,kuba1/qtcreator,maui-packages/qt-creator,amyvmiwei/qt-creator,xianian/qt-creator,xianian/qt-creator,kuba1/qtcreator,omniacreator/qtcreator,colede/qtcreator,duythanhphan/qt-creator,azat/qtcreator,jonnor/qt-creator,danimo/qt-creator,Distrotech/qtcreator,amyvmiwei/qt-creator,omniacreator/qtcreator,bakaiadam/collaborative_qt_creator,xianian/qt-creator,hdweiss/qt-creator-visualizer,farseerri/git_code,farseerri/git_code,bakaiadam/collaborative_qt_creator,hdweiss/qt-creator-visualizer,jonnor/qt-creator,darksylinc/qt-creator,richardmg/qtcreator,AltarBeastiful/qt-creator,syntheticpp/qt-creator,amyvmiwei/qt-creator,colede/qtcreator,KDAB/KDAB-Creator,kuba1/qtcreator,omniacreator/qtcreator,richardmg/qtcreator,dmik/qt-creator-os2,amyvmiwei/qt-creator,jonnor/qt-creator,xianian/qt-creator,ostash/qt-creator-i18n-uk,farseerri/git_code,malikcjm/qtcreator,dmik/qt-creator-os2,KDE/android-qt-creator,KDAB/KDAB-Creator,martyone/sailfish-qtcreator,richardmg/qtcreator,maui-packages/qt-creator,bakaiadam/collaborative_qt_creator,azat/qtcreator,AltarBeastiful/qt-creator,bakaiadam/collaborative_qt_creator,malikcjm/qtcreator,AltarBeastiful/qt-creator,jonnor/qt-creator,darksylinc/qt-creator,duythanhphan/qt-creator,kuba1/qtcreator,dmik/qt-creator-os2,syntheticpp/qt-creator,farseerri/git_code,danimo/qt-creator,AltarBeastiful/qt-creator,syntheticpp/qt-creator,azat/qtcreator,syntheticpp/qt-creator,omniacreator/qtcreator,KDAB/KDAB-Creator,richardmg/qtcreator,richardmg/qtcreator,darksylinc/qt-creator,syntheticpp/qt-creator,xianian/qt-creator,kuba1/qtcreator,Distrotech/qtcreator,ostash/qt-creator-i18n-uk,malikcjm/qtcreator,KDE/android-qt-creator,Distrotech/qtcreator,colede/qtcreator,darksylinc/qt-creator,farseerri/git_code,kuba1/qtcreator,colede/qtcreator,martyone/sailfish-qtcreator,kuba1/qtcreator,xianian/qt-creator,duythanhphan/qt-creator,farseerri/git_code,darksylinc/qt-creator,omniacreator/qtcreator,hdweiss/qt-creator-visualizer,maui-packages/qt-creator,AltarBeastiful/qt-creator,martyone/sailfish-qtcreator,KDE/android-qt-creator,Distrotech/qtcreator,martyone/sailfish-qtcreator,KDAB/KDAB-Creator,richardmg/qtcreator,xianian/qt-creator,danimo/qt-creator,amyvmiwei/qt-creator,syntheticpp/qt-creator,KDAB/KDAB-Creator,ostash/qt-creator-i18n-uk