text
stringlengths
54
60.6k
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.6 2001/05/11 13:26:16 tng * Copyright update. * * Revision 1.5 2001/03/21 21:56:04 tng * Schema: Add Schema Grammar, Schema Validator, and split the DTDValidator into DTDValidator, DTDScanner, and DTDGrammar. * * Revision 1.4 2001/02/26 19:44:14 tng * Schema: add utility class QName, by Pei Yong Zhang. * * Revision 1.3 2000/11/02 01:14:07 andyh * SAX bug fix: Attribute lists were throwing exceptions rather than returning * null when an attribute could not be found by name. Fixed by Tinny Ng. * * Revision 1.2 2000/08/09 22:11:16 jpolast * changes to allow const instances of the sax2 * Attributes class. * * Revision 1.1 2000/08/02 18:09:14 jpolast * initial checkin: attributes vector needed for * Attributes class as defined by sax2 spec * * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/Janitor.hpp> #include <internal/VecAttributesImpl.hpp> // --------------------------------------------------------------------------- // Constructors and Destructor // --------------------------------------------------------------------------- VecAttributesImpl::VecAttributesImpl() : fAdopt(false) , fCount(0) , fVector(0) , fScanner(0) { } VecAttributesImpl::~VecAttributesImpl() { // // Note that some compilers can't deal with the fact that the pointer // is to a const object, so we have to cast off the const'ness here! // if (fAdopt) delete (RefVectorOf<XMLAttr>*)fVector; } // --------------------------------------------------------------------------- // Implementation of the attribute list interface // --------------------------------------------------------------------------- unsigned int VecAttributesImpl::getLength() const { return fCount; } const XMLCh* VecAttributesImpl::getURI(const unsigned int index) const { // since this func really needs to be const, like the rest, not sure how we // make it const and re-use the fURIBuffer member variable. we're currently // creating a buffer each time you need a URI. there has to be a better // way to do this... //XMLBuffer tempBuf; if (index >= fCount) { return 0; } //fValidator->getURIText(fVector->elementAt(index)->getURIId(), tempBuf) ; //return tempBuf.getRawBuffer() ; return fScanner->getURIText(fVector->elementAt(index)->getURIId()); } const XMLCh* VecAttributesImpl::getLocalName(const unsigned int index) const { if (index >= fCount) { return 0; } return fVector->elementAt(index)->getName(); } const XMLCh* VecAttributesImpl::getQName(const unsigned int index) const { if (index >= fCount) { return 0; } return fVector->elementAt(index)->getQName(); } const XMLCh* VecAttributesImpl::getType(const unsigned int index) const { if (index >= fCount) { return 0; } return XMLAttDef::getAttTypeString(fVector->elementAt(index)->getType()); } const XMLCh* VecAttributesImpl::getValue(const unsigned int index) const { if (index >= fCount) { return 0; } return fVector->elementAt(index)->getValue(); } int VecAttributesImpl::getIndex(const XMLCh* const uri, const XMLCh* const localPart ) const { // // Search the vector for the attribute with the given name and return // its type. // XMLBuffer uriBuffer ; for (unsigned int index = 0; index < fCount; index++) { const XMLAttr* curElem = fVector->elementAt(index); fScanner->getURIText(curElem->getURIId(), uriBuffer) ; if ( (!XMLString::compareString(curElem->getName(), localPart)) && (!XMLString::compareString(uriBuffer.getRawBuffer(), uri)) ) return index ; } return -1; } int VecAttributesImpl::getIndex(const XMLCh* const qName ) const { // // Search the vector for the attribute with the given name and return // its type. // for (unsigned int index = 0; index < fCount; index++) { const XMLAttr* curElem = fVector->elementAt(index); if (!XMLString::compareString(curElem->getQName(), qName)) return index ; } return -1; } const XMLCh* VecAttributesImpl::getType(const XMLCh* const uri, const XMLCh* const localPart ) const { return getType(getIndex(uri, localPart)) ; } const XMLCh* VecAttributesImpl::getType(const XMLCh* const qName) const { return getType(getIndex(qName)) ; } const XMLCh* VecAttributesImpl::getValue(const XMLCh* const uri, const XMLCh* const localPart ) const { return getValue(getIndex(uri, localPart)) ; } const XMLCh* VecAttributesImpl::getValue(const XMLCh* const qName) const { return getValue(getIndex(qName)) ; } // --------------------------------------------------------------------------- // Setter methods // --------------------------------------------------------------------------- void VecAttributesImpl::setVector(const RefVectorOf<XMLAttr>* const srcVec , const unsigned int count , const XMLScanner * const scanner , const bool adopt) { // // Delete the previous vector (if any) if we are adopting. Note that some // compilers can't deal with the fact that the pointer is to a const // object, so we have to cast off the const'ness here! // if (fAdopt) delete (RefVectorOf<XMLAttr>*)fVector; fAdopt = adopt; fCount = count; fVector = srcVec; fScanner = scanner ; } <commit_msg>[BUG# 3831]: -1 returned from getIndex() needs to be checked<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2001 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.7 2001/10/05 17:57:39 peiyongz * [BUG# 3831]: -1 returned from getIndex() needs to be checked * * Revision 1.6 2001/05/11 13:26:16 tng * Copyright update. * * Revision 1.5 2001/03/21 21:56:04 tng * Schema: Add Schema Grammar, Schema Validator, and split the DTDValidator into DTDValidator, DTDScanner, and DTDGrammar. * * Revision 1.4 2001/02/26 19:44:14 tng * Schema: add utility class QName, by Pei Yong Zhang. * * Revision 1.3 2000/11/02 01:14:07 andyh * SAX bug fix: Attribute lists were throwing exceptions rather than returning * null when an attribute could not be found by name. Fixed by Tinny Ng. * * Revision 1.2 2000/08/09 22:11:16 jpolast * changes to allow const instances of the sax2 * Attributes class. * * Revision 1.1 2000/08/02 18:09:14 jpolast * initial checkin: attributes vector needed for * Attributes class as defined by sax2 spec * * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <util/Janitor.hpp> #include <internal/VecAttributesImpl.hpp> // --------------------------------------------------------------------------- // Constructors and Destructor // --------------------------------------------------------------------------- VecAttributesImpl::VecAttributesImpl() : fAdopt(false) , fCount(0) , fVector(0) , fScanner(0) { } VecAttributesImpl::~VecAttributesImpl() { // // Note that some compilers can't deal with the fact that the pointer // is to a const object, so we have to cast off the const'ness here! // if (fAdopt) delete (RefVectorOf<XMLAttr>*)fVector; } // --------------------------------------------------------------------------- // Implementation of the attribute list interface // --------------------------------------------------------------------------- unsigned int VecAttributesImpl::getLength() const { return fCount; } const XMLCh* VecAttributesImpl::getURI(const unsigned int index) const { // since this func really needs to be const, like the rest, not sure how we // make it const and re-use the fURIBuffer member variable. we're currently // creating a buffer each time you need a URI. there has to be a better // way to do this... //XMLBuffer tempBuf; if (index >= fCount) { return 0; } //fValidator->getURIText(fVector->elementAt(index)->getURIId(), tempBuf) ; //return tempBuf.getRawBuffer() ; return fScanner->getURIText(fVector->elementAt(index)->getURIId()); } const XMLCh* VecAttributesImpl::getLocalName(const unsigned int index) const { if (index >= fCount) { return 0; } return fVector->elementAt(index)->getName(); } const XMLCh* VecAttributesImpl::getQName(const unsigned int index) const { if (index >= fCount) { return 0; } return fVector->elementAt(index)->getQName(); } const XMLCh* VecAttributesImpl::getType(const unsigned int index) const { if (index >= fCount) { return 0; } return XMLAttDef::getAttTypeString(fVector->elementAt(index)->getType()); } const XMLCh* VecAttributesImpl::getValue(const unsigned int index) const { if (index >= fCount) { return 0; } return fVector->elementAt(index)->getValue(); } int VecAttributesImpl::getIndex(const XMLCh* const uri, const XMLCh* const localPart ) const { // // Search the vector for the attribute with the given name and return // its type. // XMLBuffer uriBuffer ; for (unsigned int index = 0; index < fCount; index++) { const XMLAttr* curElem = fVector->elementAt(index); fScanner->getURIText(curElem->getURIId(), uriBuffer) ; if ( (!XMLString::compareString(curElem->getName(), localPart)) && (!XMLString::compareString(uriBuffer.getRawBuffer(), uri)) ) return index ; } return -1; } int VecAttributesImpl::getIndex(const XMLCh* const qName ) const { // // Search the vector for the attribute with the given name and return // its type. // for (unsigned int index = 0; index < fCount; index++) { const XMLAttr* curElem = fVector->elementAt(index); if (!XMLString::compareString(curElem->getQName(), qName)) return index ; } return -1; } const XMLCh* VecAttributesImpl::getType(const XMLCh* const uri, const XMLCh* const localPart ) const { int retVal = getIndex(uri, localPart); return ((retVal < 0) ? 0 : getType(retVal)); } const XMLCh* VecAttributesImpl::getType(const XMLCh* const qName) const { int retVal = getIndex(qName); return ((retVal < 0) ? 0 : getType(retVal)); } const XMLCh* VecAttributesImpl::getValue(const XMLCh* const uri, const XMLCh* const localPart ) const { int retVal = getIndex(uri, localPart); return ((retVal < 0) ? 0 : getValue(retVal)); } const XMLCh* VecAttributesImpl::getValue(const XMLCh* const qName) const { int retVal = getIndex(qName); return ((retVal < 0) ? 0 : getValue(retVal)); } // --------------------------------------------------------------------------- // Setter methods // --------------------------------------------------------------------------- void VecAttributesImpl::setVector(const RefVectorOf<XMLAttr>* const srcVec , const unsigned int count , const XMLScanner * const scanner , const bool adopt) { // // Delete the previous vector (if any) if we are adopting. Note that some // compilers can't deal with the fact that the pointer is to a const // object, so we have to cast off the const'ness here! // if (fAdopt) delete (RefVectorOf<XMLAttr>*)fVector; fAdopt = adopt; fCount = count; fVector = srcVec; fScanner = scanner ; } <|endoftext|>
<commit_before>#include "convergence/moments/convergence_checker_l1_norm.hpp" namespace bart::convergence::moments { ConvergenceCheckerL1Norm::ConvergenceCheckerL1Norm(const double max_delta) { max_delta_ = max_delta; } bool ConvergenceCheckerL1Norm::IsConverged(const Vector& current_iteration, const Vector& previous_iteration) { Vector difference(current_iteration); difference -= previous_iteration; delta_ = difference.l1_norm()/current_iteration.l1_norm(); is_converged_ = delta_ <= max_delta_; return is_converged_; } auto ConvergenceCheckerL1Norm::SetMaxDelta(const double &to_set) -> void { AssertThrow(to_set > 0, dealii::ExcMessage("Error in ConvergenceCheckerL1Norm::SetMaxDelta, value to set must be " "greater than 0")) this->SetMaxDelta(to_set); } } // namespace bart::convergence::moments<commit_msg>Removed incorrect call to this in ConvergenceCheckerL1Norm::SetMaxDelta.<commit_after>#include "convergence/moments/convergence_checker_l1_norm.hpp" namespace bart::convergence::moments { ConvergenceCheckerL1Norm::ConvergenceCheckerL1Norm(const double max_delta) { max_delta_ = max_delta; } bool ConvergenceCheckerL1Norm::IsConverged(const Vector& current_iteration, const Vector& previous_iteration) { Vector difference(current_iteration); difference -= previous_iteration; delta_ = difference.l1_norm()/current_iteration.l1_norm(); is_converged_ = delta_ <= max_delta_; return is_converged_; } auto ConvergenceCheckerL1Norm::SetMaxDelta(const double &to_set) -> void { AssertThrow(to_set > 0, dealii::ExcMessage("Error in ConvergenceCheckerL1Norm::SetMaxDelta, value to set must be " "greater than 0")) this->max_delta_ = to_set; } } // namespace bart::convergence::moments<|endoftext|>
<commit_before>/* * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors. * License: https://github.com/taylor001/crown/blob/master/LICENSE */ #include "config.h" #include "dynamic_string.h" #include "lua_resource.h" #include "os.h" #include "temp_allocator.h" #include "array.h" #include "compile_options.h" #if CROWN_DEBUG #define LUAJIT_FLAGS "-bg" // Keep debug info #else #define LUAJIT_FLAGS "-b" #endif // CROWN_DEBUG namespace crown { namespace lua_resource { void compile(const char* path, CompileOptions& opts) { TempAllocator1024 alloc; DynamicString res_abs_path(alloc); TempAllocator1024 alloc2; DynamicString bc_abs_path(alloc2); opts.get_absolute_path(path, res_abs_path); opts.get_absolute_path("bc.tmp", bc_abs_path); const char* luajit[] = { #if CROWN_PLATFORM_LINUX "./luajit", #else "luajit.exe", #endif // CROWN_PLATFORM_LINUX LUAJIT_FLAGS, res_abs_path.c_str(), bc_abs_path.c_str(), NULL }; int exitcode = os::execute_process(luajit); CE_ASSERT(exitcode == 0, "Failed to compile lua"); Buffer blob = opts.read(bc_abs_path.c_str()); opts.delete_file(bc_abs_path.c_str()); LuaResource lr; lr.version = SCRIPT_VERSION; lr.size = array::size(blob); opts.write(lr.version); opts.write(lr.size); opts.write(blob); } void* load(File& file, Allocator& a) { const uint32_t file_size = file.size(); void* res = a.allocate(file_size); file.read(res, file_size); CE_ASSERT(*(uint32_t*)res == SCRIPT_VERSION, "Wrong version"); return res; } void online(StringId64 /*id*/, ResourceManager& /*rm*/) { } void offline(StringId64 /*id*/, ResourceManager& /*rm*/) { } void unload(Allocator& allocator, void* resource) { allocator.deallocate(resource); } uint32_t size(const LuaResource* lr) { return lr->size; } const char* program(const LuaResource* lr) { return (char*)lr + sizeof(LuaResource); } } // namespace lua_resource } // namespace crown <commit_msg>Cleanup<commit_after>/* * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors. * License: https://github.com/taylor001/crown/blob/master/LICENSE */ #include "config.h" #include "dynamic_string.h" #include "lua_resource.h" #include "os.h" #include "temp_allocator.h" #include "array.h" #include "compile_options.h" #define LUAJIT_NAME "luajit" #if CROWN_PLATFORM_WINDOWS #define EXE ".exe" #else #define EXE "" #endif // CROWN_PLATFORM_WINDOWS #define LUAJIT_EXE LUAJIT_NAME EXE #if CROWN_DEBUG #define LUAJIT_FLAGS "-bg" // Keep debug info #else #define LUAJIT_FLAGS "-b" #endif // CROWN_DEBUG namespace crown { namespace lua_resource { void compile(const char* path, CompileOptions& opts) { TempAllocator1024 alloc; DynamicString res_abs_path(alloc); TempAllocator1024 alloc2; DynamicString bc_abs_path(alloc2); opts.get_absolute_path(path, res_abs_path); opts.get_absolute_path("bc.tmp", bc_abs_path); const char* luajit[] = { LUAJIT_EXE, LUAJIT_FLAGS, res_abs_path.c_str(), bc_abs_path.c_str(), NULL }; int exitcode = os::execute_process(luajit); CE_ASSERT(exitcode == 0, "Failed to compile lua"); Buffer blob = opts.read(bc_abs_path.c_str()); opts.delete_file(bc_abs_path.c_str()); LuaResource lr; lr.version = SCRIPT_VERSION; lr.size = array::size(blob); opts.write(lr.version); opts.write(lr.size); opts.write(blob); } void* load(File& file, Allocator& a) { const uint32_t file_size = file.size(); void* res = a.allocate(file_size); file.read(res, file_size); CE_ASSERT(*(uint32_t*)res == SCRIPT_VERSION, "Wrong version"); return res; } void online(StringId64 /*id*/, ResourceManager& /*rm*/) { } void offline(StringId64 /*id*/, ResourceManager& /*rm*/) { } void unload(Allocator& allocator, void* resource) { allocator.deallocate(resource); } uint32_t size(const LuaResource* lr) { return lr->size; } const char* program(const LuaResource* lr) { return (char*)lr + sizeof(LuaResource); } } // namespace lua_resource } // namespace crown <|endoftext|>
<commit_before>/************************************************* * HMAC_RNG Source File * * (C) 2008 Jack Lloyd * *************************************************/ #include <botan/hmac_rng.h> #include <botan/entropy.h> #include <botan/loadstor.h> #include <botan/xor_buf.h> #include <botan/util.h> #include <botan/bit_ops.h> #include <botan/stl_util.h> #include <algorithm> namespace Botan { namespace { void hmac_prf(MessageAuthenticationCode* prf, MemoryRegion<byte>& K, u32bit& counter, const std::string& label) { prf->update(K, K.size()); prf->update(label); for(u32bit i = 0; i != 4; ++i) prf->update(get_byte(i, counter)); prf->final(K); ++counter; } } /************************************************* * Generate a buffer of random bytes * *************************************************/ void HMAC_RNG::randomize(byte out[], u32bit length) { /* Attempt to seed if we are either unseeded or have generated enouch counters that it seems wise to roll over keys */ if(!is_seeded() || counter >= 16 * 1024) { reseed(); if(!is_seeded()) throw PRNG_Unseeded(name() + " seeding attempt failed"); } /* HMAC KDF as described in E-t-E, using a CTXinfo of "rng" */ while(length) { hmac_prf(prf, K, counter, "rng"); const u32bit copied = std::min(K.size(), length); copy_mem(out, K.begin(), copied); out += copied; length -= copied; } hmac_prf(prf, K, counter, "rng"); /* Every once in a while do a fast poll of a entropy source */ if(entropy_sources.size() && (counter % 1024 == 0)) { u32bit got = entropy_sources.at(source_index)->fast_poll(io_buffer, io_buffer.size()); source_index = (source_index + 1) % entropy_sources.size(); extractor->update(io_buffer, got); } } /** * Reseed the internal state, also accepting user input to include */ void HMAC_RNG::reseed_with_input(const byte input[], u32bit input_length) { Entropy_Estimator estimate; if(entropy_sources.size()) { /** Using the terminology of E-t-E, XTR is the MAC function (normally HMAC) seeded with XTS (below) and we form SKM, the key material, by fast polling each source, and then slow polling as many as we think we need (in the following loop), and feeding all of the poll results, along with any optional user input, along with, finally, feedback of the current PRK value, into the extractor function. */ for(u32bit j = 0; j < entropy_sources.size(); ++j) { u32bit got = entropy_sources[j]->fast_poll(io_buffer, io_buffer.size()); extractor->update(io_buffer, got); estimate.update(io_buffer, got, 96); } /* Limit assumed entropy from fast polls (to ensure we do at least a few slow polls) */ estimate.set_upper_bound(256); /* Then do a slow poll, until we think we have got enough entropy */ for(u32bit j = 0; j != entropy_sources.size(); ++j) { u32bit got = entropy_sources[j]->slow_poll(io_buffer, io_buffer.size()); extractor->update(io_buffer, got); estimate.update(io_buffer, got, 256); if(estimate.value() > 8 * extractor->OUTPUT_LENGTH) break; } } /* And now add the user-provided input, if any */ if(input_length) { extractor->update(input, input_length); estimate.update(input, input_length); } /* It is necessary to feed forward poll data. Otherwise, a good poll (collecting a large amount of conditional entropy) followed by a bad one (collecting little) would be unsafe. Do this by generating new PRF outputs using the previous key and feeding them into the extractor function. Cycle the RNG once (CTXinfo="rng"), then generate a new PRF output using the CTXinfo "reseed". Provide these values as input to the extractor function. */ hmac_prf(prf, K, counter, "rng"); extractor->update(K); // K is the CTXinfo=rng PRF output hmac_prf(prf, K, counter, "reseed"); extractor->update(K); // K is the CTXinfo=reseed PRF output /* Now derive the new PRK using everything that has been fed into the extractor, and set the PRF key to that*/ prf->set_key(extractor->final()); // Now generate a new PRF output to use as the XTS extractor salt hmac_prf(prf, K, counter, "xts"); extractor->set_key(K, K.size()); // Reset state K.clear(); counter = 0; // Increase entropy estimate (for is_seeded) entropy = std::min<u32bit>(entropy + estimate.value(), 8 * extractor->OUTPUT_LENGTH); } /** * Reseed the internal state */ void HMAC_RNG::reseed() { reseed_with_input(0, 0); } /** Add user-supplied entropy by reseeding and including this input among the poll data */ void HMAC_RNG::add_entropy(const byte input[], u32bit length) { reseed_with_input(input, length); } /************************************************* * Add another entropy source to the list * *************************************************/ void HMAC_RNG::add_entropy_source(EntropySource* src) { entropy_sources.push_back(src); } /************************************************* * Check if the the pool is seeded * *************************************************/ bool HMAC_RNG::is_seeded() const { return (entropy >= 8 * prf->OUTPUT_LENGTH); } /************************************************* * Clear memory of sensitive data * *************************************************/ void HMAC_RNG::clear() throw() { extractor->clear(); prf->clear(); K.clear(); entropy = 0; counter = 0; source_index = 0; } /************************************************* * Return the name of this type * *************************************************/ std::string HMAC_RNG::name() const { return "HMAC_RNG(" + extractor->name() + "," + prf->name() + ")"; } /************************************************* * HMAC_RNG Constructor * *************************************************/ HMAC_RNG::HMAC_RNG(MessageAuthenticationCode* extractor_mac, MessageAuthenticationCode* prf_mac) : extractor(extractor_mac), prf(prf_mac), io_buffer(128) { entropy = 0; // First PRF inputs are all zero, as specified in section 2 K.create(prf->OUTPUT_LENGTH); counter = 0; source_index = 0; /* Normally we want to feedback PRF output into the input to the extractor function to ensure a single bad poll does not damage the RNG, but obviously that is meaningless to do on the first poll. We will want to use the PRF before we set the first key (in reseed_with_input), and it is a pain to keep track if it is set or not. Since the first time it doesn't matter anyway, just set it to a constant: randomize() will not produce output unless is_seeded() returns true, and that will only be the case if the estimated entropy counter is high enough. That variable is only set when a reseeding is performed. */ std::string prf_key = "Botan HMAC_RNG PRF"; prf->set_key(reinterpret_cast<const byte*>(prf_key.c_str()), prf_key.length()); /* This will be used as the first XTS value when extracting input. XTS values after this one are generated using the PRF. If I understand the E-t-E paper correctly (specifically Section 4), using this fixed extractor key is safe to do. */ std::string xts = "Botan HMAC_RNG XTS"; extractor->set_key(reinterpret_cast<const byte*>(xts.c_str()), xts.length()); } /************************************************* * HMAC_RNG Destructor * *************************************************/ HMAC_RNG::~HMAC_RNG() { delete extractor; delete prf; std::for_each(entropy_sources.begin(), entropy_sources.end(), del_fun<EntropySource>()); entropy = 0; counter = 0; } } <commit_msg>Several changes to HMAC_RNG, many on the basis of the paper<commit_after>/************************************************* * HMAC_RNG Source File * * (C) 2008 Jack Lloyd * *************************************************/ #include <botan/hmac_rng.h> #include <botan/entropy.h> #include <botan/loadstor.h> #include <botan/xor_buf.h> #include <botan/util.h> #include <botan/bit_ops.h> #include <botan/stl_util.h> #include <algorithm> namespace Botan { namespace { void hmac_prf(MessageAuthenticationCode* prf, MemoryRegion<byte>& K, u32bit& counter, const std::string& label) { prf->update(K, K.size()); prf->update(label); for(u32bit i = 0; i != 4; ++i) prf->update(get_byte(i, counter)); prf->final(K); ++counter; } } /************************************************* * Generate a buffer of random bytes * *************************************************/ void HMAC_RNG::randomize(byte out[], u32bit length) { /* Attempt to seed if we are currently not seeded, or if the counter is greater than 2^20 If HMAC_RNG is wrapped in an X9.31/AES PRNG (the default), this means a reseed will be kicked off every 16 MiB of RNG output. */ if(!is_seeded() || counter >= 0x100000) { reseed(); if(!is_seeded()) throw PRNG_Unseeded(name() + " seeding attempt failed"); } /* HMAC KDF as described in E-t-E, using a CTXinfo of "rng" */ while(length) { hmac_prf(prf, K, counter, "rng"); const u32bit copied = std::min(K.size(), length); copy_mem(out, K.begin(), copied); out += copied; length -= copied; } /* Every once in a while do a fast poll of a entropy source */ if(entropy_sources.size() && (counter % 65536 == 0)) { u32bit got = entropy_sources.at(source_index)->fast_poll(io_buffer, io_buffer.size()); source_index = (source_index + 1) % entropy_sources.size(); extractor->update(io_buffer, got); } } /** * Reseed the internal state, also accepting user input to include */ void HMAC_RNG::reseed_with_input(const byte input[], u32bit input_length) { if(entropy_sources.size()) { /** Using the terminology of E-t-E, XTR is the MAC function (normally HMAC) seeded with XTS (below) and we form SKM, the key material, by fast polling each source, and then slow polling as many as we think we need (in the following loop), and feeding all of the poll results, along with any optional user input, along with, finally, feedback of the current PRK value, into the extractor function. */ /* Previously this function did entropy estimation. However the paper "Boaz Barak, Shai Halevi: A model and architecture for pseudo-random generation with applications to /dev/random. ACM Conference on Computer and Communications Security 2005." provides a pretty strong case to not even try, since what we are really interested in is the *conditional* entropy from the point of view of an unknown attacker, which is impossible to calculate. They recommend, if an entropy estimate of some kind is needed, to use a low static estimate instead. We use here an estimate of 1 bit per byte. One thing I had been concerned about initially was that people without any randomness source enabled (much more likely in the days when you had to enable them manually) would find the RNG was unseeded and then pull the manuever some OpenSSL users did and seed the RNG with a constant string. However, upon further thought, I've decided that people who do that deserve to lose anyway. */ for(u32bit j = 0; j < entropy_sources.size(); ++j) { const u32bit got = entropy_sources[j]->fast_poll(io_buffer, io_buffer.size()); entropy += got; extractor->update(io_buffer, got); } for(u32bit j = 0; j != entropy_sources.size(); ++j) { const u32bit got = entropy_sources[j]->slow_poll(io_buffer, io_buffer.size()); entropy += got; extractor->update(io_buffer, got); } } /* And now add the user-provided input, if any */ if(input_length) { extractor->update(input, input_length); entropy += input_length; } /* It is necessary to feed forward poll data. Otherwise, a good poll (collecting a large amount of conditional entropy) followed by a bad one (collecting little) would be unsafe. Do this by generating new PRF outputs using the previous key and feeding them into the extractor function. Cycle the RNG once (CTXinfo="rng"), then generate a new PRF output using the CTXinfo "reseed". Provide these values as input to the extractor function. */ hmac_prf(prf, K, counter, "rng"); extractor->update(K); // K is the CTXinfo=rng PRF output hmac_prf(prf, K, counter, "reseed"); extractor->update(K); // K is the CTXinfo=reseed PRF output /* Now derive the new PRK using everything that has been fed into the extractor, and set the PRF key to that */ prf->set_key(extractor->final()); // Now generate a new PRF output to use as the XTS extractor salt hmac_prf(prf, K, counter, "xts"); extractor->set_key(K, K.size()); // Reset state K.clear(); counter = 0; // Upper bound entropy estimate at the extractor output size entropy = std::min<u32bit>(entropy, 8 * extractor->OUTPUT_LENGTH); } /** * Reseed the internal state */ void HMAC_RNG::reseed() { reseed_with_input(0, 0); } /** Add user-supplied entropy by reseeding and including this input among the poll data */ void HMAC_RNG::add_entropy(const byte input[], u32bit length) { reseed_with_input(input, length); } /************************************************* * Add another entropy source to the list * *************************************************/ void HMAC_RNG::add_entropy_source(EntropySource* src) { entropy_sources.push_back(src); } /************************************************* * Check if the the pool is seeded * *************************************************/ bool HMAC_RNG::is_seeded() const { return (entropy >= 8 * prf->OUTPUT_LENGTH); } /************************************************* * Clear memory of sensitive data * *************************************************/ void HMAC_RNG::clear() throw() { extractor->clear(); prf->clear(); K.clear(); entropy = 0; counter = 0; source_index = 0; } /************************************************* * Return the name of this type * *************************************************/ std::string HMAC_RNG::name() const { return "HMAC_RNG(" + extractor->name() + "," + prf->name() + ")"; } /************************************************* * HMAC_RNG Constructor * *************************************************/ HMAC_RNG::HMAC_RNG(MessageAuthenticationCode* extractor_mac, MessageAuthenticationCode* prf_mac) : extractor(extractor_mac), prf(prf_mac), io_buffer(128) { entropy = 0; // First PRF inputs are all zero, as specified in section 2 K.create(prf->OUTPUT_LENGTH); counter = 0; source_index = 0; /* Normally we want to feedback PRF output into the input to the extractor function to ensure a single bad poll does not damage the RNG, but obviously that is meaningless to do on the first poll. We will want to use the PRF before we set the first key (in reseed_with_input), and it is a pain to keep track if it is set or not. Since the first time it doesn't matter anyway, just set it to a constant: randomize() will not produce output unless is_seeded() returns true, and that will only be the case if the estimated entropy counter is high enough. That variable is only set when a reseeding is performed. */ std::string prf_key = "Botan HMAC_RNG PRF"; prf->set_key(reinterpret_cast<const byte*>(prf_key.c_str()), prf_key.length()); /* This will be used as the first XTS value when extracting input. XTS values after this one are generated using the PRF. If I understand the E-t-E paper correctly (specifically Section 4), using this fixed extractor key is safe to do. */ std::string xts = "Botan HMAC_RNG XTS"; extractor->set_key(reinterpret_cast<const byte*>(xts.c_str()), xts.length()); } /************************************************* * HMAC_RNG Destructor * *************************************************/ HMAC_RNG::~HMAC_RNG() { delete extractor; delete prf; std::for_each(entropy_sources.begin(), entropy_sources.end(), del_fun<EntropySource>()); entropy = 0; counter = 0; } } <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2018-2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "VelocitySmoothing.hpp" #include <cstdio> #include <float.h> #include <mathlib/mathlib.h> VelocitySmoothing::VelocitySmoothing(float initial_accel, float initial_vel, float initial_pos) { reset(initial_accel, initial_vel, initial_pos); } void VelocitySmoothing::reset(float accel, float vel, float pos) { _state.j = 0.f; _state.a = accel; _state.v = vel; _state.x = pos; _state_init = _state; } float VelocitySmoothing::saturateT1ForAccel(float a0, float j_max, float T1, float a_max) { /* Check maximum acceleration, saturate and recompute T1 if needed */ float accel_T1 = a0 + j_max * T1; float T1_new = T1; if (accel_T1 > a_max) { T1_new = (a_max - a0) / j_max; } else if (accel_T1 < -a_max) { T1_new = (-a_max - a0) / j_max; } return T1_new; } float VelocitySmoothing::computeT1(float a0, float v3, float j_max, float a_max) { float delta = 2.f * a0 * a0 + 4.f * j_max * v3; if (delta < 0.f) { // Solution is not real return 0.f; } float sqrt_delta = sqrtf(delta); float T1_plus = (-a0 + 0.5f * sqrt_delta) / j_max; float T1_minus = (-a0 - 0.5f * sqrt_delta) / j_max; float T3_plus = a0 / j_max + T1_plus; float T3_minus = a0 / j_max + T1_minus; float T1 = 0.f; if (T1_plus >= 0.f && T3_plus >= 0.f) { T1 = T1_plus; } else if (T1_minus >= 0.f && T3_minus >= 0.f) { T1 = T1_minus; } T1 = saturateT1ForAccel(a0, j_max, T1, a_max); return math::max(T1, 0.f); } float VelocitySmoothing::computeT1(float T123, float a0, float v3, float j_max, float a_max) { float a = -j_max; float b = j_max * T123 - a0; float delta = T123 * T123 * j_max * j_max + 2.f * T123 * a0 * j_max - a0 * a0 - 4.f * j_max * v3; if (delta < 0.f) { // Solution is not real return 0.f; } float sqrt_delta = sqrtf(delta); float denominator_inv = 1.f / (2.f * a); float T1_plus = math::max((-b + sqrt_delta) * denominator_inv, 0.f); float T1_minus = math::max((-b - sqrt_delta) * denominator_inv, 0.f); float T3_plus = a0 / j_max + T1_plus; float T3_minus = a0 / j_max + T1_minus; float T13_plus = T1_plus + T3_plus; float T13_minus = T1_minus + T3_minus; float T1 = 0.f; if (T13_plus > T123) { T1 = T1_minus; } else if (T13_minus > T123) { T1 = T1_plus; } T1 = saturateT1ForAccel(a0, j_max, T1, a_max); return T1; } float VelocitySmoothing::computeT2(float T1, float T3, float a0, float v3, float j_max) { float T2 = 0.f; float den = a0 + j_max * T1; if (math::abs_t(den) > FLT_EPSILON) { T2 = (-0.5f * T1 * T1 * j_max - T1 * T3 * j_max - T1 * a0 + 0.5f * T3 * T3 * j_max - T3 * a0 + v3) / den; } return math::max(T2, 0.f); } float VelocitySmoothing::computeT2(float T123, float T1, float T3) { float T2 = T123 - T1 - T3; return math::max(T2, 0.f); } float VelocitySmoothing::computeT3(float T1, float a0, float j_max) { float T3 = a0 / j_max + T1; return math::max(T3, 0.f); } void VelocitySmoothing::updateDurations(float vel_setpoint) { _vel_sp = math::constrain(vel_setpoint, -_max_vel, _max_vel); _local_time = 0.f; _state_init = _state; _direction = computeDirection(); if (_direction != 0) { updateDurationsMinimizeTotalTime(); } else { _T1 = _T2 = _T3 = 0.f; } } int VelocitySmoothing::computeDirection() { // Compute the velocity at which the trajectory will be // when the acceleration will be zero float vel_zero_acc = computeVelAtZeroAcc(); /* Depending of the direction, start accelerating positively or negatively */ int direction = math::sign(_vel_sp - vel_zero_acc); if (direction == 0) { // If by braking immediately the velocity is exactly // the require one with zero acceleration, then brake direction = math::sign(_state.a); } return direction; } float VelocitySmoothing::computeVelAtZeroAcc() { float vel_zero_acc = _state.v; if (fabsf(_state.a) > FLT_EPSILON) { float j_zero_acc = -math::sign(_state.a) * _max_jerk; // Required jerk to reduce the acceleration float t_zero_acc = -_state.a / j_zero_acc; // Required time to cancel the current acceleration vel_zero_acc = _state.v + _state.a * t_zero_acc + 0.5f * j_zero_acc * t_zero_acc * t_zero_acc; } return vel_zero_acc; } void VelocitySmoothing::updateDurationsMinimizeTotalTime() { float jerk_max_T1 = _direction * _max_jerk; float delta_v = _vel_sp - _state.v; // compute increasing acceleration time _T1 = computeT1(_state.a, delta_v, jerk_max_T1, _max_accel); // compute decreasing acceleration time _T3 = computeT3(_T1, _state.a, jerk_max_T1); // compute constant acceleration time _T2 = computeT2(_T1, _T3, _state.a, delta_v, jerk_max_T1); } Trajectory VelocitySmoothing::evaluatePoly(float j, float a0, float v0, float x0, float t, int d) { Trajectory traj; float jt = d * j; float t2 = t * t; float t3 = t2 * t; traj.j = jt; traj.a = a0 + jt * t; traj.v = v0 + a0 * t + 0.5f * jt * t2; traj.x = x0 + v0 * t + 0.5f * a0 * t2 + 1.f / 6.f * jt * t3; return traj; } void VelocitySmoothing::updateTraj(float dt, float time_stretch) { _local_time += dt * time_stretch; const float t = _local_time; float t1 = 0.f; float t2 = 0.f; float t3 = 0.f; float t4 = 0.f; if (t <= _T1) { t1 = t; } else if (t <= _T1 + _T2) { t1 = _T1; t2 = t - _T1; } else if (t <= _T1 + _T2 + _T3) { t1 = _T1; t2 = _T2; t3 = t - _T1 - _T2; } else { t1 = _T1; t2 = _T2; t3 = _T3; t4 = t - _T1 - _T2 - _T3; } if (t > 0.f) { _state = evaluatePoly(_max_jerk, _state_init.a, _state_init.v, _state_init.x, t1, _direction); } if (t >= _T1) { _state = evaluatePoly(0.f, _state.a, _state.v, _state.x, t2, 0.f); } if (t >= _T1 + _T2) { _state = evaluatePoly(_max_jerk, _state.a, _state.v, _state.x, t3, -_direction); } if (t >= _T1 + _T2 + _T3) { _state = evaluatePoly(0.f, 0.f, _state.v, _state.x, t4, 0.f); } } void VelocitySmoothing::timeSynchronization(VelocitySmoothing *traj, int n_traj) { float desired_time = 0.f; int longest_traj_index = 0; for (int i = 0; i < n_traj; i++) { const float T123 = traj[i].getTotalTime(); if (T123 > desired_time) { desired_time = T123; longest_traj_index = i; } } if (desired_time > FLT_EPSILON) { for (int i = 0; i < n_traj; i++) { if (i != longest_traj_index) { traj[i].updateDurationsGivenTotalTime(desired_time); } } } } void VelocitySmoothing::updateDurationsGivenTotalTime(float T123) { float jerk_max_T1 = _direction * _max_jerk; float delta_v = _vel_sp - _state.v; // compute increasing acceleration time _T1 = computeT1(T123, _state.a, delta_v, jerk_max_T1, _max_accel); // compute decreasing acceleration time _T3 = computeT3(_T1, _state.a, jerk_max_T1); // compute constant acceleration time _T2 = computeT2(T123, _T1, _T3); } <commit_msg>VelocitySmoothing - Clean up updateTraj function based on Matthias' comments<commit_after>/**************************************************************************** * * Copyright (c) 2018-2019 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "VelocitySmoothing.hpp" #include <cstdio> #include <float.h> #include <mathlib/mathlib.h> VelocitySmoothing::VelocitySmoothing(float initial_accel, float initial_vel, float initial_pos) { reset(initial_accel, initial_vel, initial_pos); } void VelocitySmoothing::reset(float accel, float vel, float pos) { _state.j = 0.f; _state.a = accel; _state.v = vel; _state.x = pos; _state_init = _state; } float VelocitySmoothing::saturateT1ForAccel(float a0, float j_max, float T1, float a_max) { /* Check maximum acceleration, saturate and recompute T1 if needed */ float accel_T1 = a0 + j_max * T1; float T1_new = T1; if (accel_T1 > a_max) { T1_new = (a_max - a0) / j_max; } else if (accel_T1 < -a_max) { T1_new = (-a_max - a0) / j_max; } return T1_new; } float VelocitySmoothing::computeT1(float a0, float v3, float j_max, float a_max) { float delta = 2.f * a0 * a0 + 4.f * j_max * v3; if (delta < 0.f) { // Solution is not real return 0.f; } float sqrt_delta = sqrtf(delta); float T1_plus = (-a0 + 0.5f * sqrt_delta) / j_max; float T1_minus = (-a0 - 0.5f * sqrt_delta) / j_max; float T3_plus = a0 / j_max + T1_plus; float T3_minus = a0 / j_max + T1_minus; float T1 = 0.f; if (T1_plus >= 0.f && T3_plus >= 0.f) { T1 = T1_plus; } else if (T1_minus >= 0.f && T3_minus >= 0.f) { T1 = T1_minus; } T1 = saturateT1ForAccel(a0, j_max, T1, a_max); return math::max(T1, 0.f); } float VelocitySmoothing::computeT1(float T123, float a0, float v3, float j_max, float a_max) { float a = -j_max; float b = j_max * T123 - a0; float delta = T123 * T123 * j_max * j_max + 2.f * T123 * a0 * j_max - a0 * a0 - 4.f * j_max * v3; if (delta < 0.f) { // Solution is not real return 0.f; } float sqrt_delta = sqrtf(delta); float denominator_inv = 1.f / (2.f * a); float T1_plus = math::max((-b + sqrt_delta) * denominator_inv, 0.f); float T1_minus = math::max((-b - sqrt_delta) * denominator_inv, 0.f); float T3_plus = a0 / j_max + T1_plus; float T3_minus = a0 / j_max + T1_minus; float T13_plus = T1_plus + T3_plus; float T13_minus = T1_minus + T3_minus; float T1 = 0.f; if (T13_plus > T123) { T1 = T1_minus; } else if (T13_minus > T123) { T1 = T1_plus; } T1 = saturateT1ForAccel(a0, j_max, T1, a_max); return T1; } float VelocitySmoothing::computeT2(float T1, float T3, float a0, float v3, float j_max) { float T2 = 0.f; float den = a0 + j_max * T1; if (math::abs_t(den) > FLT_EPSILON) { T2 = (-0.5f * T1 * T1 * j_max - T1 * T3 * j_max - T1 * a0 + 0.5f * T3 * T3 * j_max - T3 * a0 + v3) / den; } return math::max(T2, 0.f); } float VelocitySmoothing::computeT2(float T123, float T1, float T3) { float T2 = T123 - T1 - T3; return math::max(T2, 0.f); } float VelocitySmoothing::computeT3(float T1, float a0, float j_max) { float T3 = a0 / j_max + T1; return math::max(T3, 0.f); } void VelocitySmoothing::updateDurations(float vel_setpoint) { _vel_sp = math::constrain(vel_setpoint, -_max_vel, _max_vel); _local_time = 0.f; _state_init = _state; _direction = computeDirection(); if (_direction != 0) { updateDurationsMinimizeTotalTime(); } else { _T1 = _T2 = _T3 = 0.f; } } int VelocitySmoothing::computeDirection() { // Compute the velocity at which the trajectory will be // when the acceleration will be zero float vel_zero_acc = computeVelAtZeroAcc(); /* Depending of the direction, start accelerating positively or negatively */ int direction = math::sign(_vel_sp - vel_zero_acc); if (direction == 0) { // If by braking immediately the velocity is exactly // the require one with zero acceleration, then brake direction = math::sign(_state.a); } return direction; } float VelocitySmoothing::computeVelAtZeroAcc() { float vel_zero_acc = _state.v; if (fabsf(_state.a) > FLT_EPSILON) { float j_zero_acc = -math::sign(_state.a) * _max_jerk; // Required jerk to reduce the acceleration float t_zero_acc = -_state.a / j_zero_acc; // Required time to cancel the current acceleration vel_zero_acc = _state.v + _state.a * t_zero_acc + 0.5f * j_zero_acc * t_zero_acc * t_zero_acc; } return vel_zero_acc; } void VelocitySmoothing::updateDurationsMinimizeTotalTime() { float jerk_max_T1 = _direction * _max_jerk; float delta_v = _vel_sp - _state.v; // compute increasing acceleration time _T1 = computeT1(_state.a, delta_v, jerk_max_T1, _max_accel); // compute decreasing acceleration time _T3 = computeT3(_T1, _state.a, jerk_max_T1); // compute constant acceleration time _T2 = computeT2(_T1, _T3, _state.a, delta_v, jerk_max_T1); } Trajectory VelocitySmoothing::evaluatePoly(float j, float a0, float v0, float x0, float t, int d) { Trajectory traj; float jt = d * j; float t2 = t * t; float t3 = t2 * t; traj.j = jt; traj.a = a0 + jt * t; traj.v = v0 + a0 * t + 0.5f * jt * t2; traj.x = x0 + v0 * t + 0.5f * a0 * t2 + 1.f / 6.f * jt * t3; return traj; } void VelocitySmoothing::updateTraj(float dt, float time_stretch) { _local_time += dt * time_stretch; float t_remain = _local_time; float t[3]; t[0] = math::min(t_remain, _T1); _state = evaluatePoly(_max_jerk, _state_init.a, _state_init.v, _state_init.x, t[0], _direction); t_remain -= t[0]; if (t_remain > 0.f) { t[1] = math::min(t_remain, _T2); _state = evaluatePoly(0.f, _state.a, _state.v, _state.x, t[1], 0.f); t_remain -= t[1]; } if (t_remain > 0.f) { t[2] = math::min(t_remain, _T3); _state = evaluatePoly(_max_jerk, _state.a, _state.v, _state.x, t[2], -_direction); t_remain -= t[2]; } if (t_remain > 0.f) { _state = evaluatePoly(0.f, 0.f, _state.v, _state.x, t_remain, 0.f); } } void VelocitySmoothing::timeSynchronization(VelocitySmoothing *traj, int n_traj) { float desired_time = 0.f; int longest_traj_index = 0; for (int i = 0; i < n_traj; i++) { const float T123 = traj[i].getTotalTime(); if (T123 > desired_time) { desired_time = T123; longest_traj_index = i; } } if (desired_time > FLT_EPSILON) { for (int i = 0; i < n_traj; i++) { if (i != longest_traj_index) { traj[i].updateDurationsGivenTotalTime(desired_time); } } } } void VelocitySmoothing::updateDurationsGivenTotalTime(float T123) { float jerk_max_T1 = _direction * _max_jerk; float delta_v = _vel_sp - _state.v; // compute increasing acceleration time _T1 = computeT1(T123, _state.a, delta_v, jerk_max_T1, _max_accel); // compute decreasing acceleration time _T3 = computeT3(_T1, _state.a, jerk_max_T1); // compute constant acceleration time _T2 = computeT2(T123, _T1, _T3); } <|endoftext|>
<commit_before>/** * @file sparse_coding_impl.hpp * @author Nishant Mehta * * Implementation of Sparse Coding with Dictionary Learning using l1 (LASSO) or * l1+l2 (Elastic Net) regularization. */ #ifndef __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP #define __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP // In case it hasn't already been included. #include "sparse_coding.hpp" namespace mlpack { namespace sparse_coding { template<typename DictionaryInitializer> SparseCoding<DictionaryInitializer>::SparseCoding(const arma::mat& data, const size_t atoms, const double lambda1, const double lambda2) : atoms(atoms), data(data), codes(atoms, data.n_cols), lambda1(lambda1), lambda2(lambda2) { // Initialize the dictionary. DictionaryInitializer::Initialize(data, atoms, dictionary); } template<typename DictionaryInitializer> void SparseCoding<DictionaryInitializer>::Encode(const size_t maxIterations, const double objTolerance, const double newtonTolerance) { Timer::Start("sparse_coding"); double lastObjVal = DBL_MAX; // Take the initial coding step, which has to happen before entering the main // optimization loop. Log::Info << "Initial Coding Step." << std::endl; OptimizeCode(); arma::uvec adjacencies = find(codes); Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem)) / ((double) (atoms * data.n_cols)) << "%." << std::endl; Log::Info << " Objective value: " << Objective() << "." << std::endl; for (size_t t = 1; t != maxIterations; ++t) { // Print current iteration, and maximum number of iterations (if it isn't // 0). Log::Info << "Iteration " << t; if (maxIterations != 0) Log::Info << " of " << maxIterations; Log::Info << "." << std::endl; // First step: optimize the dictionary. Log::Info << "Performing dictionary step... " << std::endl; OptimizeDictionary(adjacencies, newtonTolerance); Log::Info << " Objective value: " << Objective() << "." << std::endl; // Second step: perform the coding. Log::Info << "Performing coding step..." << std::endl; OptimizeCode(); // Get the indices of all the nonzero elements in the codes. adjacencies = find(codes); Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem)) / ((double) (atoms * data.n_cols)) << "%." << std::endl; // Find the new objective value and improvement so we can check for // convergence. double curObjVal = Objective(); double improvement = lastObjVal - curObjVal; Log::Info << " Objective value: " << curObjVal << " (improvement " << std::scientific << improvement << ")." << std::endl; // Have we converged? if (improvement < objTolerance) { Log::Info << "Converged within tolerance " << objTolerance << ".\n"; break; } lastObjVal = curObjVal; } Timer::Stop("sparse_coding"); } template<typename DictionaryInitializer> void SparseCoding<DictionaryInitializer>::OptimizeCode() { // When using the Cholesky version of LARS, this is correct even if // lambda2 > 0. arma::mat matGram = trans(dictionary) * dictionary; for (size_t i = 0; i < data.n_cols; ++i) { // Report progress. if ((i % 100) == 0) Log::Debug << "Optimization at point " << i << "." << std::endl; bool useCholesky = true; regression::LARS lars(useCholesky, matGram, lambda1, lambda2); // Create an alias of the code (using the same memory), and then LARS will // place the result directly into that; then we will not need to have an // extra copy. arma::vec code = codes.unsafe_col(i); lars.Regress(dictionary, data.unsafe_col(i), code, false); } } // Dictionary step for optimization. template<typename DictionaryInitializer> double SparseCoding<DictionaryInitializer>::OptimizeDictionary( const arma::uvec& adjacencies, const double newtonTolerance, const size_t maxIterations) { // Count the number of atomic neighbors for each point x^i. arma::uvec neighborCounts = arma::zeros<arma::uvec>(data.n_cols, 1); if (adjacencies.n_elem > 0) { // This gets the column index. Intentional integer division. size_t curPointInd = (size_t) (adjacencies(0) / atoms); size_t nextColIndex = (curPointInd + 1) * atoms; for (size_t l = 1; l < adjacencies.n_elem; ++l) { // If l no longer refers to an element in this column, advance the column // number accordingly. if (adjacencies(l) >= nextColIndex) { curPointInd = (size_t) (adjacencies(l) / atoms); nextColIndex = (curPointInd + 1) * atoms; } ++neighborCounts(curPointInd); } } // Handle the case of inactive atoms (atoms not used in the given coding). std::vector<size_t> inactiveAtoms; for (size_t j = 0; j < atoms; ++j) { if (arma::accu(codes.row(j) != 0) == 0) inactiveAtoms.push_back(j); } const size_t nInactiveAtoms = inactiveAtoms.size(); const size_t nActiveAtoms = atoms - nInactiveAtoms; // Efficient construction of Z restricted to active atoms. arma::mat matActiveZ; if (nInactiveAtoms > 0) { math::RemoveRows(codes, inactiveAtoms, matActiveZ); } if (nInactiveAtoms > 0) { Log::Warn << "There are " << nInactiveAtoms << " inactive atoms. They will be re-initialized randomly.\n"; } Log::Debug << "Solving Dual via Newton's Method.\n"; // Solve using Newton's method in the dual - note that the final dot // multiplication with inv(A) seems to be unavoidable. Although more // expensive, the code written this way (we use solve()) should be more // numerically stable than just using inv(A) for everything. arma::vec dualVars = arma::zeros<arma::vec>(nActiveAtoms); //vec dualVars = 1e-14 * ones<vec>(nActiveAtoms); // Method used by feature sign code - fails miserably here. Perhaps the // MATLAB optimizer fmincon does something clever? //vec dualVars = 10.0 * randu(nActiveAtoms, 1); //vec dualVars = diagvec(solve(dictionary, data * trans(codes)) // - codes * trans(codes)); //for (size_t i = 0; i < dualVars.n_elem; i++) // if (dualVars(i) < 0) // dualVars(i) = 0; bool converged = false; // If we have any inactive atoms, we must construct these differently. arma::mat codesXT; arma::mat codesZT; if (inactiveAtoms.empty()) { codesXT = codes * trans(data); codesZT = codes * trans(codes); } else { codesXT = matActiveZ * trans(data); codesZT = matActiveZ * trans(matActiveZ); } double normGradient; double improvement = 0; for (size_t t = 1; !converged; ++t) { arma::mat A = codesZT + diagmat(dualVars); arma::mat matAInvZXT = solve(A, codesXT); arma::vec gradient = -arma::sum(arma::square(matAInvZXT), 1); gradient += 1; arma::mat hessian = -(-2 * (matAInvZXT * trans(matAInvZXT)) % inv(A)); arma::vec searchDirection = -solve(hessian, gradient); //printf("%e\n", norm(searchDirection, 2)); // Armijo line search. const double c = 1e-4; double alpha = 1.0; const double rho = 0.9; double sufficientDecrease = c * dot(gradient, searchDirection); for (size_t t = 1; t != maxIterations; ++t) { // Calculate objective. double sumDualVars = arma::sum(dualVars); double fOld = -(-trace(trans(codesXT) * matAInvZXT) - sumDualVars); double fNew = -(-trace(trans(codesXT) * solve(codesZT + diagmat(dualVars + alpha * searchDirection), codesXT)) - (sumDualVars + alpha * arma::sum(searchDirection))); if (fNew <= fOld + alpha * sufficientDecrease) { searchDirection = alpha * searchDirection; improvement = fOld - fNew; break; } alpha *= rho; } // Take step and print useful information. dualVars += searchDirection; normGradient = arma::norm(gradient, 2); Log::Debug << "Newton Method iteration " << t << ":" << std::endl; Log::Debug << " Gradient norm: " << std::scientific << normGradient << "." << std::endl; Log::Debug << " Improvement: " << std::scientific << improvement << ".\n"; if (normGradient < newtonTolerance) converged = true; } if (inactiveAtoms.empty()) { // Directly update dictionary. dictionary = trans(solve(codesZT + diagmat(dualVars), codesXT)); } else { arma::mat activeDictionary = trans(solve(codesZT + diagmat(dualVars), codesXT)); // Update all atoms. size_t currentInactiveIndex = 0; for (size_t i = 0; i < atoms; ++i) { if (inactiveAtoms[currentInactiveIndex] == i) { // This atom is inactive. Reinitialize it randomly. dictionary.col(i) = (data.col(math::RandInt(data.n_cols)) + data.col(math::RandInt(data.n_cols)) + data.col(math::RandInt(data.n_cols))); dictionary.col(i) /= arma::norm(dictionary.col(i), 2); // Increment inactive index counter. ++currentInactiveIndex; } else { // Update estimate. dictionary.col(i) = activeDictionary.col(i - currentInactiveIndex); } } } return normGradient; } // Project each atom of the dictionary back into the unit ball (if necessary). template<typename DictionaryInitializer> void SparseCoding<DictionaryInitializer>::ProjectDictionary() { for (size_t j = 0; j < atoms; j++) { double atomNorm = arma::norm(dictionary.col(j), 2); if (atomNorm > 1) { Log::Info << "Norm of atom " << j << " exceeds 1 (" << std::scientific << atomNorm << "). Shrinking...\n"; dictionary.col(j) /= atomNorm; } } } // Compute the objective function. template<typename DictionaryInitializer> double SparseCoding<DictionaryInitializer>::Objective() const { double l11NormZ = arma::sum(arma::sum(arma::abs(codes))); double froNormResidual = arma::norm(data - (dictionary * codes), "fro"); if (lambda2 > 0) { double froNormZ = arma::norm(codes, "fro"); return 0.5 * (std::pow(froNormResidual, 2.0) + (lambda2 * std::pow(froNormZ, 2.0))) + (lambda1 * l11NormZ); } else // It can be simpler. { return 0.5 * std::pow(froNormResidual, 2.0) + lambda1 * l11NormZ; } } template<typename DictionaryInitializer> std::string SparseCoding<DictionaryInitializer>::ToString() const { std::ostringstream convert; convert << "Sparse Coding [" << this << "]" << std::endl; convert << " Data: " << data.n_rows << "x" ; convert << data.n_cols << std::endl; convert << " Atoms: " << atoms << std::endl; convert << " Lambda 1: " << lambda1 << std::endl; convert << " Lambda 2: " << lambda2 << std::endl; return convert.str(); } }; // namespace sparse_coding }; // namespace mlpack #endif <commit_msg>Use maxIterations for Newton method loop instead of nested Armijo line search.<commit_after>/** * @file sparse_coding_impl.hpp * @author Nishant Mehta * * Implementation of Sparse Coding with Dictionary Learning using l1 (LASSO) or * l1+l2 (Elastic Net) regularization. */ #ifndef __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP #define __MLPACK_METHODS_SPARSE_CODING_SPARSE_CODING_IMPL_HPP // In case it hasn't already been included. #include "sparse_coding.hpp" namespace mlpack { namespace sparse_coding { template<typename DictionaryInitializer> SparseCoding<DictionaryInitializer>::SparseCoding(const arma::mat& data, const size_t atoms, const double lambda1, const double lambda2) : atoms(atoms), data(data), codes(atoms, data.n_cols), lambda1(lambda1), lambda2(lambda2) { // Initialize the dictionary. DictionaryInitializer::Initialize(data, atoms, dictionary); } template<typename DictionaryInitializer> void SparseCoding<DictionaryInitializer>::Encode(const size_t maxIterations, const double objTolerance, const double newtonTolerance) { Timer::Start("sparse_coding"); double lastObjVal = DBL_MAX; // Take the initial coding step, which has to happen before entering the main // optimization loop. Log::Info << "Initial Coding Step." << std::endl; OptimizeCode(); arma::uvec adjacencies = find(codes); Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem)) / ((double) (atoms * data.n_cols)) << "%." << std::endl; Log::Info << " Objective value: " << Objective() << "." << std::endl; for (size_t t = 1; t != maxIterations; ++t) { // Print current iteration, and maximum number of iterations (if it isn't // 0). Log::Info << "Iteration " << t; if (maxIterations != 0) Log::Info << " of " << maxIterations; Log::Info << "." << std::endl; // First step: optimize the dictionary. Log::Info << "Performing dictionary step... " << std::endl; OptimizeDictionary(adjacencies, newtonTolerance); Log::Info << " Objective value: " << Objective() << "." << std::endl; // Second step: perform the coding. Log::Info << "Performing coding step..." << std::endl; OptimizeCode(); // Get the indices of all the nonzero elements in the codes. adjacencies = find(codes); Log::Info << " Sparsity level: " << 100.0 * ((double) (adjacencies.n_elem)) / ((double) (atoms * data.n_cols)) << "%." << std::endl; // Find the new objective value and improvement so we can check for // convergence. double curObjVal = Objective(); double improvement = lastObjVal - curObjVal; Log::Info << " Objective value: " << curObjVal << " (improvement " << std::scientific << improvement << ")." << std::endl; // Have we converged? if (improvement < objTolerance) { Log::Info << "Converged within tolerance " << objTolerance << ".\n"; break; } lastObjVal = curObjVal; } Timer::Stop("sparse_coding"); } template<typename DictionaryInitializer> void SparseCoding<DictionaryInitializer>::OptimizeCode() { // When using the Cholesky version of LARS, this is correct even if // lambda2 > 0. arma::mat matGram = trans(dictionary) * dictionary; for (size_t i = 0; i < data.n_cols; ++i) { // Report progress. if ((i % 100) == 0) Log::Debug << "Optimization at point " << i << "." << std::endl; bool useCholesky = true; regression::LARS lars(useCholesky, matGram, lambda1, lambda2); // Create an alias of the code (using the same memory), and then LARS will // place the result directly into that; then we will not need to have an // extra copy. arma::vec code = codes.unsafe_col(i); lars.Regress(dictionary, data.unsafe_col(i), code, false); } } // Dictionary step for optimization. template<typename DictionaryInitializer> double SparseCoding<DictionaryInitializer>::OptimizeDictionary( const arma::uvec& adjacencies, const double newtonTolerance, const size_t maxIterations) { // Count the number of atomic neighbors for each point x^i. arma::uvec neighborCounts = arma::zeros<arma::uvec>(data.n_cols, 1); if (adjacencies.n_elem > 0) { // This gets the column index. Intentional integer division. size_t curPointInd = (size_t) (adjacencies(0) / atoms); size_t nextColIndex = (curPointInd + 1) * atoms; for (size_t l = 1; l < adjacencies.n_elem; ++l) { // If l no longer refers to an element in this column, advance the column // number accordingly. if (adjacencies(l) >= nextColIndex) { curPointInd = (size_t) (adjacencies(l) / atoms); nextColIndex = (curPointInd + 1) * atoms; } ++neighborCounts(curPointInd); } } // Handle the case of inactive atoms (atoms not used in the given coding). std::vector<size_t> inactiveAtoms; for (size_t j = 0; j < atoms; ++j) { if (arma::accu(codes.row(j) != 0) == 0) inactiveAtoms.push_back(j); } const size_t nInactiveAtoms = inactiveAtoms.size(); const size_t nActiveAtoms = atoms - nInactiveAtoms; // Efficient construction of Z restricted to active atoms. arma::mat matActiveZ; if (nInactiveAtoms > 0) { math::RemoveRows(codes, inactiveAtoms, matActiveZ); } if (nInactiveAtoms > 0) { Log::Warn << "There are " << nInactiveAtoms << " inactive atoms. They will be re-initialized randomly.\n"; } Log::Debug << "Solving Dual via Newton's Method.\n"; // Solve using Newton's method in the dual - note that the final dot // multiplication with inv(A) seems to be unavoidable. Although more // expensive, the code written this way (we use solve()) should be more // numerically stable than just using inv(A) for everything. arma::vec dualVars = arma::zeros<arma::vec>(nActiveAtoms); //vec dualVars = 1e-14 * ones<vec>(nActiveAtoms); // Method used by feature sign code - fails miserably here. Perhaps the // MATLAB optimizer fmincon does something clever? //vec dualVars = 10.0 * randu(nActiveAtoms, 1); //vec dualVars = diagvec(solve(dictionary, data * trans(codes)) // - codes * trans(codes)); //for (size_t i = 0; i < dualVars.n_elem; i++) // if (dualVars(i) < 0) // dualVars(i) = 0; bool converged = false; // If we have any inactive atoms, we must construct these differently. arma::mat codesXT; arma::mat codesZT; if (inactiveAtoms.empty()) { codesXT = codes * trans(data); codesZT = codes * trans(codes); } else { codesXT = matActiveZ * trans(data); codesZT = matActiveZ * trans(matActiveZ); } double normGradient; double improvement = 0; for (size_t t = 1; (t != maxIterations) && !converged; ++t) { arma::mat A = codesZT + diagmat(dualVars); arma::mat matAInvZXT = solve(A, codesXT); arma::vec gradient = -arma::sum(arma::square(matAInvZXT), 1); gradient += 1; arma::mat hessian = -(-2 * (matAInvZXT * trans(matAInvZXT)) % inv(A)); arma::vec searchDirection = -solve(hessian, gradient); //printf("%e\n", norm(searchDirection, 2)); // Armijo line search. const double c = 1e-4; double alpha = 1.0; const double rho = 0.9; double sufficientDecrease = c * dot(gradient, searchDirection); // A maxIterations parameter for the Armijo line search may be a good idea, // but it doesn't seem to be causing any problems for now. while (true) { // Calculate objective. double sumDualVars = arma::sum(dualVars); double fOld = -(-trace(trans(codesXT) * matAInvZXT) - sumDualVars); double fNew = -(-trace(trans(codesXT) * solve(codesZT + diagmat(dualVars + alpha * searchDirection), codesXT)) - (sumDualVars + alpha * arma::sum(searchDirection))); if (fNew <= fOld + alpha * sufficientDecrease) { searchDirection = alpha * searchDirection; improvement = fOld - fNew; break; } alpha *= rho; } // Take step and print useful information. dualVars += searchDirection; normGradient = arma::norm(gradient, 2); Log::Debug << "Newton Method iteration " << t << ":" << std::endl; Log::Debug << " Gradient norm: " << std::scientific << normGradient << "." << std::endl; Log::Debug << " Improvement: " << std::scientific << improvement << ".\n"; if (normGradient < newtonTolerance) converged = true; } if (inactiveAtoms.empty()) { // Directly update dictionary. dictionary = trans(solve(codesZT + diagmat(dualVars), codesXT)); } else { arma::mat activeDictionary = trans(solve(codesZT + diagmat(dualVars), codesXT)); // Update all atoms. size_t currentInactiveIndex = 0; for (size_t i = 0; i < atoms; ++i) { if (inactiveAtoms[currentInactiveIndex] == i) { // This atom is inactive. Reinitialize it randomly. dictionary.col(i) = (data.col(math::RandInt(data.n_cols)) + data.col(math::RandInt(data.n_cols)) + data.col(math::RandInt(data.n_cols))); dictionary.col(i) /= arma::norm(dictionary.col(i), 2); // Increment inactive index counter. ++currentInactiveIndex; } else { // Update estimate. dictionary.col(i) = activeDictionary.col(i - currentInactiveIndex); } } } return normGradient; } // Project each atom of the dictionary back into the unit ball (if necessary). template<typename DictionaryInitializer> void SparseCoding<DictionaryInitializer>::ProjectDictionary() { for (size_t j = 0; j < atoms; j++) { double atomNorm = arma::norm(dictionary.col(j), 2); if (atomNorm > 1) { Log::Info << "Norm of atom " << j << " exceeds 1 (" << std::scientific << atomNorm << "). Shrinking...\n"; dictionary.col(j) /= atomNorm; } } } // Compute the objective function. template<typename DictionaryInitializer> double SparseCoding<DictionaryInitializer>::Objective() const { double l11NormZ = arma::sum(arma::sum(arma::abs(codes))); double froNormResidual = arma::norm(data - (dictionary * codes), "fro"); if (lambda2 > 0) { double froNormZ = arma::norm(codes, "fro"); return 0.5 * (std::pow(froNormResidual, 2.0) + (lambda2 * std::pow(froNormZ, 2.0))) + (lambda1 * l11NormZ); } else // It can be simpler. { return 0.5 * std::pow(froNormResidual, 2.0) + lambda1 * l11NormZ; } } template<typename DictionaryInitializer> std::string SparseCoding<DictionaryInitializer>::ToString() const { std::ostringstream convert; convert << "Sparse Coding [" << this << "]" << std::endl; convert << " Data: " << data.n_rows << "x" ; convert << data.n_cols << std::endl; convert << " Atoms: " << atoms << std::endl; convert << " Lambda 1: " << lambda1 << std::endl; convert << " Lambda 2: " << lambda2 << std::endl; return convert.str(); } }; // namespace sparse_coding }; // namespace mlpack #endif <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qtquickplugin.h" #include <widgetplugin_helper.h> #include <QtCore/QtPlugin> #include <private/qdeclarativerectangle_p.h> #include <private/qdeclarativescalegrid_p_p.h> #include <MComponentData> namespace QmlDesigner { QtQuickPlugin::QtQuickPlugin() { qApp->setProperty("NoMStyle", true); if(!MComponentData::instance()) { // This is a workaround because we can't use a default // constructor for MComponentData int argc = 1; char *argv0 = "meegotouch"; (void) new MComponentData(argc, &argv0); } qmlRegisterType<QDeclarativePen>("Qt", 4, 7, "Pen"); qmlRegisterType<QDeclarativeScaleGrid>("Qt", 4, 7, "ScaleGrid"); } QString QtQuickPlugin::pluginName() { return ("QtQuickPlugin"); } QString QtQuickPlugin::metaInfo() { return QString(":/qtquickplugin/quick.metainfo"); } } Q_EXPORT_PLUGIN(QmlDesigner::QtQuickPlugin) <commit_msg>QmlDesigner: compile fix<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, 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. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "qtquickplugin.h" #include <widgetplugin_helper.h> #include <QtCore/QtPlugin> #include <private/qdeclarativerectangle_p.h> #include <private/qdeclarativescalegrid_p_p.h> namespace QmlDesigner { QtQuickPlugin::QtQuickPlugin() { qmlRegisterType<QDeclarativePen>("Qt", 4, 7, "Pen"); qmlRegisterType<QDeclarativeScaleGrid>("Qt", 4, 7, "ScaleGrid"); } QString QtQuickPlugin::pluginName() { return ("QtQuickPlugin"); } QString QtQuickPlugin::metaInfo() { return QString(":/qtquickplugin/quick.metainfo"); } } Q_EXPORT_PLUGIN(QmlDesigner::QtQuickPlugin) <|endoftext|>
<commit_before>/**************************************************************************** ** ** This file is part of QtCompositor** ** ** Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** ** Contact: Nokia Corporation [email protected] ** ** You may use this file under the terms of the BSD license as follows: ** ** 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 Nokia Corporation and its Subsidiary(-ies) nor the ** names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ****************************************************************************/ #include "waylandsurfaceitem.h" #include "waylandsurface.h" #include <qsgengine.h> #include <private/qsgitem_p.h> #include <QKeyEvent> #include <qsgsimpletexturenode.h> #include <qsgsimplerectnode.h> void WaylandSurfaceItem::surfaceDamaged(const QRect &) { if (m_texture) delete m_texture; if (m_surface->type() == WaylandSurface::Texture) { m_texture = canvas()->sceneGraphEngine()->createTextureFromId(m_surface->texture(), m_surface->geometry().size()); } else { m_texture = canvas()->sceneGraphEngine()->createTextureFromImage(m_surface->image()); } emit textureChanged(); } WaylandSurfaceItem::WaylandSurfaceItem(QSGItem *parent) : QSGItem(parent) , m_surface(0) , m_texture(0) { } WaylandSurfaceItem::WaylandSurfaceItem(WaylandSurface *surface, QSGItem *parent) : QSGItem(parent) , m_surface(0) , m_texture(0) { init(surface); } void WaylandSurfaceItem::init(WaylandSurface *surface) { if (!surface) return; m_surface = surface; setWidth(surface->geometry().width()); setHeight(surface->geometry().height()); setSmooth(true); setFlag(ItemHasContents); setAcceptedMouseButtons(Qt::LeftButton | Qt::RightButton); connect(surface, SIGNAL(mapped(const QRect &)), this, SLOT(surfaceMapped(const QRect &))); connect(surface, SIGNAL(destroyed(QObject *)), this, SLOT(surfaceDestroyed(QObject *))); connect(this, SIGNAL(textureChanged()), this, SLOT(update())); connect(surface, SIGNAL(damaged(const QRect &)), this, SLOT(surfaceDamaged(const QRect &))); } WaylandSurfaceItem::~WaylandSurfaceItem() { delete m_texture; } void WaylandSurfaceItem::setSurface(WaylandSurface *surface) { init(surface); } QSGTexture *WaylandSurfaceItem::texture() const { if (m_texture) m_texture->setFiltering(smooth() ? QSGTexture::Linear : QSGTexture::Nearest); return m_texture; } void WaylandSurfaceItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { if (m_surface) m_surface->sendMousePressEvent(toSurface(event->pos()), event->button()); } void WaylandSurfaceItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if (m_surface) m_surface->sendMouseMoveEvent(toSurface(event->pos())); } void WaylandSurfaceItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { if (m_surface) m_surface->sendMouseReleaseEvent(toSurface(event->pos()), event->button()); } void WaylandSurfaceItem::keyPressEvent(QKeyEvent *event) { if (m_surface && hasFocus()) m_surface->sendKeyPressEvent(event->nativeScanCode()); } void WaylandSurfaceItem::keyReleaseEvent(QKeyEvent *event) { if (m_surface && hasFocus()) m_surface->sendKeyReleaseEvent(event->nativeScanCode()); } void WaylandSurfaceItem::takeFocus() { setFocus(true); if (m_surface) m_surface->setInputFocus(); } QPoint WaylandSurfaceItem::toSurface(const QPointF &pos) const { return pos.toPoint(); } void WaylandSurfaceItem::surfaceMapped(const QRect &rect) { setWidth(rect.width()); setHeight(rect.height()); } void WaylandSurfaceItem::surfaceDestroyed(QObject *) { m_surface = 0; } QSGNode *WaylandSurfaceItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) { QSGSimpleTextureNode *node = static_cast<QSGSimpleTextureNode *>(oldNode); if (!m_texture) { delete oldNode; return 0; } if (!node) { node = new QSGSimpleTextureNode(); node->setTexture(m_texture); } node->setRect(QRectF(0, height(), width(), -height())); node->setFiltering(smooth() ? QSGTexture::Linear : QSGTexture::Nearest); return node; } <commit_msg>Avoid crash when texture changes.<commit_after>/**************************************************************************** ** ** This file is part of QtCompositor** ** ** Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** ** Contact: Nokia Corporation [email protected] ** ** You may use this file under the terms of the BSD license as follows: ** ** 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 Nokia Corporation and its Subsidiary(-ies) nor the ** names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ****************************************************************************/ #include "waylandsurfaceitem.h" #include "waylandsurface.h" #include <qsgengine.h> #include <private/qsgitem_p.h> #include <QKeyEvent> #include <qsgsimpletexturenode.h> #include <qsgsimplerectnode.h> void WaylandSurfaceItem::surfaceDamaged(const QRect &) { if (m_texture) delete m_texture; if (m_surface->type() == WaylandSurface::Texture) { //qDebug() << "createTextureFromId" << m_surface->texture() << m_surface->geometry().size(); m_texture = canvas()->sceneGraphEngine()->createTextureFromId(m_surface->texture(), m_surface->geometry().size()); } else { m_texture = canvas()->sceneGraphEngine()->createTextureFromImage(m_surface->image()); } emit textureChanged(); } WaylandSurfaceItem::WaylandSurfaceItem(QSGItem *parent) : QSGItem(parent) , m_surface(0) , m_texture(0) { } WaylandSurfaceItem::WaylandSurfaceItem(WaylandSurface *surface, QSGItem *parent) : QSGItem(parent) , m_surface(0) , m_texture(0) { init(surface); } void WaylandSurfaceItem::init(WaylandSurface *surface) { if (!surface) return; m_surface = surface; setWidth(surface->geometry().width()); setHeight(surface->geometry().height()); setSmooth(true); setFlag(ItemHasContents); setAcceptedMouseButtons(Qt::LeftButton | Qt::RightButton); connect(surface, SIGNAL(mapped(const QRect &)), this, SLOT(surfaceMapped(const QRect &))); connect(surface, SIGNAL(destroyed(QObject *)), this, SLOT(surfaceDestroyed(QObject *))); connect(this, SIGNAL(textureChanged()), this, SLOT(update())); connect(surface, SIGNAL(damaged(const QRect &)), this, SLOT(surfaceDamaged(const QRect &))); } WaylandSurfaceItem::~WaylandSurfaceItem() { delete m_texture; } void WaylandSurfaceItem::setSurface(WaylandSurface *surface) { init(surface); } QSGTexture *WaylandSurfaceItem::texture() const { if (m_texture) m_texture->setFiltering(smooth() ? QSGTexture::Linear : QSGTexture::Nearest); return m_texture; } void WaylandSurfaceItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { if (m_surface) m_surface->sendMousePressEvent(toSurface(event->pos()), event->button()); } void WaylandSurfaceItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if (m_surface) m_surface->sendMouseMoveEvent(toSurface(event->pos())); } void WaylandSurfaceItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { if (m_surface) m_surface->sendMouseReleaseEvent(toSurface(event->pos()), event->button()); } void WaylandSurfaceItem::keyPressEvent(QKeyEvent *event) { if (m_surface && hasFocus()) m_surface->sendKeyPressEvent(event->nativeScanCode()); } void WaylandSurfaceItem::keyReleaseEvent(QKeyEvent *event) { if (m_surface && hasFocus()) m_surface->sendKeyReleaseEvent(event->nativeScanCode()); } void WaylandSurfaceItem::takeFocus() { setFocus(true); if (m_surface) m_surface->setInputFocus(); } QPoint WaylandSurfaceItem::toSurface(const QPointF &pos) const { return pos.toPoint(); } void WaylandSurfaceItem::surfaceMapped(const QRect &rect) { setWidth(rect.width()); setHeight(rect.height()); } void WaylandSurfaceItem::surfaceDestroyed(QObject *) { m_surface = 0; } QSGNode *WaylandSurfaceItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *) { QSGSimpleTextureNode *node = static_cast<QSGSimpleTextureNode *>(oldNode); if (!m_texture) { delete oldNode; return 0; } if (!node) { node = new QSGSimpleTextureNode(); } node->setTexture(m_texture); node->setRect(QRectF(0, height(), width(), -height())); node->setFiltering(smooth() ? QSGTexture::Linear : QSGTexture::Nearest); return node; } <|endoftext|>
<commit_before>#include <qif> #include "pybind11_aux.h" namespace py = pybind11; using namespace py::literals; using namespace qif; void init_channel_module(py::module); void init_probab_module(py::module); void init_metric_module(py::module); void init_measure_module(py::module); void init_mechanism_module(py::module); void init_refinement_module(py::module); void init_utility_module(py::module); void init_lp_module(py::module); py::handle def_c, double_c, uint_c, rat_c, point_c; PYBIND11_MODULE(qif, m) { m.doc() = R"pbdoc( Quantitative Information Flow library. .. autosummary:: :toctree: _autosummary :template: template.rst channel probab metric measure mechanism refinement utility lp | )pbdoc"; // import np, user-friendly error message if not available py::module np; try { np = py::module::import("numpy"); } catch(py::error_already_set) { throw std::runtime_error("numpy is required by qif"); } // use np.random.randint to get a seed. Use int32_t instead of uint, cause numpy uses int32 for some reason on windows! uint seed = np.attr("random").attr("randint")(std::numeric_limits<int32_t>::max()).cast<uint>(); arma::arma_rng::set_seed(seed); // Init mp++'s pybind11 integration mppp_pybind11::init(); // Types py::class_<point>(m, "point") .def(py::init<double,double>()) .def_readwrite("x", &point::x) .def_readwrite("y", &point::y) .def_static("from_polar", &point::from_polar) .def_static("from_cell", &point::from_cell) .def(py::self + py::self) .def("__repr__", &point::to_string); m.attr("double") = np.attr("float64"); m.attr("uint") = np.attr("uint64"); m.attr("rat") = py::module::import("fractions").attr("Fraction"); // global class references double_c = m.attr("double"); uint_c = m.attr("uint"); rat_c = m.attr("rat"); point_c = m.attr("point"); def_c = double_c; m.def("set_default_type", [](py::object t) { def_c = t; }); // initialize modules init_channel_module (m.def_submodule("channel", "")); init_probab_module (m.def_submodule("probab", "")); init_metric_module (m.def_submodule("metric", "")); init_measure_module (m.def_submodule("measure", "")); init_mechanism_module (m.def_submodule("mechanism", "")); init_refinement_module(m.def_submodule("refinement","")); init_utility_module (m.def_submodule("utility", "")); init_lp_module (m.def_submodule("lp", "")); // numpy formatter, so that rats are nicely displayed std::function<py::object(py::object)> fmt = [](py::object x) { return py::str(x); }; np.attr("set_printoptions")("formatter"_a = py::dict("object"_a = fmt)); #ifdef QIF_VERSION m.attr("__version__") = QIF_VERSION; #else m.attr("__version__") = "dev"; #endif } <commit_msg>python_lib: fix warning<commit_after>#include <qif> #include "pybind11_aux.h" namespace py = pybind11; using namespace py::literals; using namespace qif; void init_channel_module(py::module); void init_probab_module(py::module); void init_metric_module(py::module); void init_measure_module(py::module); void init_mechanism_module(py::module); void init_refinement_module(py::module); void init_utility_module(py::module); void init_lp_module(py::module); py::handle def_c, double_c, uint_c, rat_c, point_c; PYBIND11_MODULE(qif, m) { m.doc() = R"pbdoc( Quantitative Information Flow library. .. autosummary:: :toctree: _autosummary :template: template.rst channel probab metric measure mechanism refinement utility lp | )pbdoc"; // import np, user-friendly error message if not available py::module np; try { np = py::module::import("numpy"); } catch(py::error_already_set&) { throw std::runtime_error("numpy is required by qif"); } // use np.random.randint to get a seed. Use int32_t instead of uint, cause numpy uses int32 for some reason on windows! uint seed = np.attr("random").attr("randint")(std::numeric_limits<int32_t>::max()).cast<uint>(); arma::arma_rng::set_seed(seed); // Init mp++'s pybind11 integration mppp_pybind11::init(); // Types py::class_<point>(m, "point") .def(py::init<double,double>()) .def_readwrite("x", &point::x) .def_readwrite("y", &point::y) .def_static("from_polar", &point::from_polar) .def_static("from_cell", &point::from_cell) .def(py::self + py::self) .def("__repr__", &point::to_string); m.attr("double") = np.attr("float64"); m.attr("uint") = np.attr("uint64"); m.attr("rat") = py::module::import("fractions").attr("Fraction"); // global class references double_c = m.attr("double"); uint_c = m.attr("uint"); rat_c = m.attr("rat"); point_c = m.attr("point"); def_c = double_c; m.def("set_default_type", [](py::object t) { def_c = t; }); // initialize modules init_channel_module (m.def_submodule("channel", "")); init_probab_module (m.def_submodule("probab", "")); init_metric_module (m.def_submodule("metric", "")); init_measure_module (m.def_submodule("measure", "")); init_mechanism_module (m.def_submodule("mechanism", "")); init_refinement_module(m.def_submodule("refinement","")); init_utility_module (m.def_submodule("utility", "")); init_lp_module (m.def_submodule("lp", "")); // numpy formatter, so that rats are nicely displayed std::function<py::object(py::object)> fmt = [](py::object x) { return py::str(x); }; np.attr("set_printoptions")("formatter"_a = py::dict("object"_a = fmt)); #ifdef QIF_VERSION m.attr("__version__") = QIF_VERSION; #else m.attr("__version__") = "dev"; #endif } <|endoftext|>
<commit_before>#pragma once /* ** Copyright (C) 2013 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QITYPE_ANYFUNCTION_HPP_ #define _QITYPE_ANYFUNCTION_HPP_ #include <qitype/api.hpp> #include <boost/function.hpp> #include <vector> namespace qi { class AnyValue; class AutoAnyReference; template <typename T = AnyValue> class QITYPE_API VarArguments { public: VarArguments() {}; VarArguments(const T& t) { _args.push_back(t); } VarArguments& operator()(const T& t) { _args.push_back(t); return *this; } typedef std::vector<T> VectorType; VectorType &args() { return _args; } const VectorType &args() const { return _args; } private: VectorType _args; }; template <> class QITYPE_API VarArguments<AnyValue> { public: VarArguments() {}; VarArguments(const AutoAnyReference& t); VarArguments& operator()(const AutoAnyReference& t); typedef std::vector<AnyValue> VectorType; VectorType &args() { return _args; } const VectorType &args() const { return _args; } private: VectorType _args; }; typedef VarArguments<> AnyVarArguments; } #include <qitype/typeinterface.hpp> #ifdef _MSC_VER # pragma warning( push ) # pragma warning( disable: 4251 ) #endif namespace qi { inline VarArguments<AnyValue>::VarArguments(const AutoAnyReference& t) { _args.push_back(qi::AnyValue(t)); } inline VarArguments<AnyValue>& VarArguments<AnyValue>::operator()(const AutoAnyReference& t) { _args.push_back(qi::AnyValue(t)); return *this; } /// Signature information for both callable types FunctionTypeInterface and MethodType class QITYPE_API CallableTypeInterface { public: CallableTypeInterface(); TypeInterface* resultType(); const std::vector<TypeInterface*>& argumentsType(); qi::Signature parametersSignature() const; qi::Signature returnSignature() const; protected: TypeInterface* _resultType; // C4251 std::vector<TypeInterface*> _argumentsType; }; class QITYPE_API FunctionTypeInterface: public TypeInterface, public CallableTypeInterface { public: /** Call the function func with argument args that must be of the correct type. * @return the return value of type resultType(). This value is allocated and must be destroyed. */ virtual void* call(void* storage, void** args, unsigned int argc) = 0; }; template<typename T> FunctionTypeInterface* makeFunctionTypeInterface(); struct ArgumentTransformation { public: // Drop first argument bool dropFirst; // Prepend boundValue to argument list bool prependValue; // So if both dropFirst and prependValue are set, first argument is // replaced with boundValue. ArgumentTransformation(bool dropFirst = false, bool prependValue=false, void* value = 0) : dropFirst(dropFirst) , prependValue(prependValue) , boundValue(value) {} void* boundValue; }; template <typename T = AnyValue> class QITYPE_API KeywordArguments { public: KeywordArguments& operator()(const std::string& name, const T& t) { values[name] = t; return *this; } std::map<std::string, T> values; }; /// A function with AnyArguments as its sole argument will behave as if AnyFunction::fromDynamicFunction was called. // This is going to be deprecated in profit of VarArgument and AnyVarArgument class QITYPE_API AnyArguments { public: AnyArguments() {}; AnyArguments(const AnyValueVector& args) : _args(args) {} operator const AnyValueVector&() const { return _args;} AnyValueVector &args() { return _args; } const AnyValueVector &args() const { return _args; } private: AnyValueVector _args; }; typedef boost::function<AnyReference(const AnyReferenceVector&)> DynamicFunction; /** Represents a generic callable function. * This class has value semantic. * */ class QITYPE_API AnyFunction { public: AnyFunction(); ~AnyFunction(); AnyFunction(const AnyFunction& b); AnyFunction(FunctionTypeInterface* type, void* value); AnyFunction& operator = (const AnyFunction& b); AnyReference call(const AnyReferenceVector& args); AnyReference call(AnyReference arg1, const AnyReferenceVector& args); AnyReference operator()(const AnyReferenceVector& args); /// Change signature, drop the first argument passed to call. const AnyFunction& dropFirstArgument() const; /// Replace first argument by \p value which must be storage for correct type. const AnyFunction& replaceFirstArgument(void* value) const; /// Prepend extra argument \p value to argument list const AnyFunction& prependArgument(void* value) const; /// Return expected argument types, taking transform into account std::vector<TypeInterface*> argumentsType() const; TypeInterface* resultType() const; //dropfirst is useful when you want the parameters signature of a method. Signature parametersSignature(bool dropFirst=false) const; Signature returnSignature() const; void swap(AnyFunction& b); operator bool() const; FunctionTypeInterface* functionType() const; /*** @return an AnyFunction wrapping func. * func can be: * - a boost::bind object * - a boost::function * - a function pointer * - a member function pointer * */ template<typename F> static AnyFunction from(F func); /// @return a AnyFunction binding \p instance to member function \p func template<typename F, typename C> static AnyFunction from(F func, C instance); /// @return a AnyFunction that takes arguments as a list of unconverted AnyReference. static AnyFunction fromDynamicFunction(DynamicFunction f); private: FunctionTypeInterface* type; void* value; //type-dependant storage mutable ArgumentTransformation transform; }; /** Store function parameters as a list of AnyReference. * Storage can be on the stack or allocated * Memory management is the responsibility of the user. * If GenericFunctionParameters is obtained throug copy(), convert() or * fromBuffer(), it must be cleared by destroy() */ class QITYPE_API GenericFunctionParameters: public AnyReferenceVector { public: GenericFunctionParameters(); GenericFunctionParameters(const AnyReferenceVector&); /// Copy arguments. destroy() must be called on the result GenericFunctionParameters copy(bool notFirst=false) const; /// Convert the arguments to given signature. destroy() must be called on the result. GenericFunctionParameters convert(const Signature& sig) const; qi::Signature signature(bool dyn) const; void destroy(bool notFirst = false); }; /// @return the type used by dynamic functions QITYPE_API FunctionTypeInterface* dynamicFunctionTypeInterface(); } #include <qitype/details/anyfunction.hxx> #include <qitype/details/anyfunctionfactory.hxx> #ifdef _MSC_VER # pragma warning( pop ) #endif #endif // _QITYPE_ANYFUNCTION_HPP_ <commit_msg>VarArguments: do not export template classes<commit_after>#pragma once /* ** Copyright (C) 2013 Aldebaran Robotics ** See COPYING for the license */ #ifndef _QITYPE_ANYFUNCTION_HPP_ #define _QITYPE_ANYFUNCTION_HPP_ #include <qitype/api.hpp> #include <boost/function.hpp> #include <vector> namespace qi { class AnyValue; class AutoAnyReference; template <typename T = AnyValue> class VarArguments { public: VarArguments() {}; VarArguments(const T& t) { _args.push_back(t); } VarArguments& operator()(const T& t) { _args.push_back(t); return *this; } typedef std::vector<T> VectorType; VectorType &args() { return _args; } const VectorType &args() const { return _args; } private: VectorType _args; }; template <> class VarArguments<AnyValue> { public: VarArguments() {}; VarArguments(const AutoAnyReference& t); VarArguments& operator()(const AutoAnyReference& t); typedef std::vector<AnyValue> VectorType; VectorType &args() { return _args; } const VectorType &args() const { return _args; } private: VectorType _args; }; typedef VarArguments<> AnyVarArguments; } #include <qitype/typeinterface.hpp> #ifdef _MSC_VER # pragma warning( push ) # pragma warning( disable: 4251 ) #endif namespace qi { inline VarArguments<AnyValue>::VarArguments(const AutoAnyReference& t) { _args.push_back(qi::AnyValue(t)); } inline VarArguments<AnyValue>& VarArguments<AnyValue>::operator()(const AutoAnyReference& t) { _args.push_back(qi::AnyValue(t)); return *this; } /// Signature information for both callable types FunctionTypeInterface and MethodType class QITYPE_API CallableTypeInterface { public: CallableTypeInterface(); TypeInterface* resultType(); const std::vector<TypeInterface*>& argumentsType(); qi::Signature parametersSignature() const; qi::Signature returnSignature() const; protected: TypeInterface* _resultType; // C4251 std::vector<TypeInterface*> _argumentsType; }; class QITYPE_API FunctionTypeInterface: public TypeInterface, public CallableTypeInterface { public: /** Call the function func with argument args that must be of the correct type. * @return the return value of type resultType(). This value is allocated and must be destroyed. */ virtual void* call(void* storage, void** args, unsigned int argc) = 0; }; template<typename T> FunctionTypeInterface* makeFunctionTypeInterface(); struct ArgumentTransformation { public: // Drop first argument bool dropFirst; // Prepend boundValue to argument list bool prependValue; // So if both dropFirst and prependValue are set, first argument is // replaced with boundValue. ArgumentTransformation(bool dropFirst = false, bool prependValue=false, void* value = 0) : dropFirst(dropFirst) , prependValue(prependValue) , boundValue(value) {} void* boundValue; }; template <typename T = AnyValue> class QITYPE_API KeywordArguments { public: KeywordArguments& operator()(const std::string& name, const T& t) { values[name] = t; return *this; } std::map<std::string, T> values; }; /// A function with AnyArguments as its sole argument will behave as if AnyFunction::fromDynamicFunction was called. // This is going to be deprecated in profit of VarArgument and AnyVarArgument class QITYPE_API AnyArguments { public: AnyArguments() {}; AnyArguments(const AnyValueVector& args) : _args(args) {} operator const AnyValueVector&() const { return _args;} AnyValueVector &args() { return _args; } const AnyValueVector &args() const { return _args; } private: AnyValueVector _args; }; typedef boost::function<AnyReference(const AnyReferenceVector&)> DynamicFunction; /** Represents a generic callable function. * This class has value semantic. * */ class QITYPE_API AnyFunction { public: AnyFunction(); ~AnyFunction(); AnyFunction(const AnyFunction& b); AnyFunction(FunctionTypeInterface* type, void* value); AnyFunction& operator = (const AnyFunction& b); AnyReference call(const AnyReferenceVector& args); AnyReference call(AnyReference arg1, const AnyReferenceVector& args); AnyReference operator()(const AnyReferenceVector& args); /// Change signature, drop the first argument passed to call. const AnyFunction& dropFirstArgument() const; /// Replace first argument by \p value which must be storage for correct type. const AnyFunction& replaceFirstArgument(void* value) const; /// Prepend extra argument \p value to argument list const AnyFunction& prependArgument(void* value) const; /// Return expected argument types, taking transform into account std::vector<TypeInterface*> argumentsType() const; TypeInterface* resultType() const; //dropfirst is useful when you want the parameters signature of a method. Signature parametersSignature(bool dropFirst=false) const; Signature returnSignature() const; void swap(AnyFunction& b); operator bool() const; FunctionTypeInterface* functionType() const; /*** @return an AnyFunction wrapping func. * func can be: * - a boost::bind object * - a boost::function * - a function pointer * - a member function pointer * */ template<typename F> static AnyFunction from(F func); /// @return a AnyFunction binding \p instance to member function \p func template<typename F, typename C> static AnyFunction from(F func, C instance); /// @return a AnyFunction that takes arguments as a list of unconverted AnyReference. static AnyFunction fromDynamicFunction(DynamicFunction f); private: FunctionTypeInterface* type; void* value; //type-dependant storage mutable ArgumentTransformation transform; }; /** Store function parameters as a list of AnyReference. * Storage can be on the stack or allocated * Memory management is the responsibility of the user. * If GenericFunctionParameters is obtained throug copy(), convert() or * fromBuffer(), it must be cleared by destroy() */ class QITYPE_API GenericFunctionParameters: public AnyReferenceVector { public: GenericFunctionParameters(); GenericFunctionParameters(const AnyReferenceVector&); /// Copy arguments. destroy() must be called on the result GenericFunctionParameters copy(bool notFirst=false) const; /// Convert the arguments to given signature. destroy() must be called on the result. GenericFunctionParameters convert(const Signature& sig) const; qi::Signature signature(bool dyn) const; void destroy(bool notFirst = false); }; /// @return the type used by dynamic functions QITYPE_API FunctionTypeInterface* dynamicFunctionTypeInterface(); } #include <qitype/details/anyfunction.hxx> #include <qitype/details/anyfunctionfactory.hxx> #ifdef _MSC_VER # pragma warning( pop ) #endif #endif // _QITYPE_ANYFUNCTION_HPP_ <|endoftext|>
<commit_before> #pragma once #include "quantities/si.hpp" namespace principia { namespace quantities { namespace si { template<typename D> std::string Format() { auto const format_unit = [](std::string const& name, int const exponent) -> std::string { switch (exponent) { case 0: return ""; break; case 1: return " " + name; default: return " " + name + "^" + std::to_string(exponent); } }; // This string has a leading space if it's not empty. auto const format = format_unit("m", D::Length) + format_unit("kg", D::Mass) + format_unit("s", D::Time) + format_unit("A", D::Current) + format_unit("K", D::Temperature) + format_unit("mol", D::Amount) + format_unit("cd", D::LuminousIntensity) + format_unit("rad", D::Angle); if (format.empty()) { return format; } else { return format.substr(1, format.size() - 1); } } template<typename D> constexpr Quantity<D> Yotta(Quantity<D> base) { return 1e24 * base; } template<typename D> constexpr Quantity<D> Zetta(Quantity<D> base) { return 1e21 * base; } template<typename D> constexpr Quantity<D> Exa(Quantity<D> base) { return 1e18 * base; } template<typename D> constexpr Quantity<D> Peta(Quantity<D> base) { return 1e15 * base; } template<typename D> constexpr Quantity<D> Tera(Quantity<D> base) { return 1e12 * base; } template<typename D> constexpr Quantity<D> Giga(Quantity<D> base) { return 1e9 * base; } template<typename D> constexpr Quantity<D> Mega(Quantity<D> base) { return 1e6 * base; } template<typename D> constexpr Quantity<D> Kilo(Quantity<D> base) { return 1e3 * base; } template<typename D> constexpr Quantity<D> Hecto(Quantity<D> base) { return 1e2 * base; } template<typename D> constexpr Quantity<D> Deca(Quantity<D> base) { return 1e1 * base; } template<typename D> constexpr Quantity<D> Deci(Quantity<D> base) { return 1e-1 * base; } template<typename D> constexpr Quantity<D> Centi(Quantity<D> base) { return 1e-2 * base; } template<typename D> constexpr Quantity<D> Milli(Quantity<D> base) { return 1e-3 * base; } template<typename D> constexpr Quantity<D> Micro(Quantity<D> base) { return 1e-6 * base; } template<typename D> constexpr Quantity<D> Nano(Quantity<D> base) { return 1e-9 * base; } template<typename D> constexpr Quantity<D> Pico(Quantity<D> base) { return 1e-12 * base; } template<typename D> constexpr Quantity<D> Femto(Quantity<D> base) { return 1e-15 * base; } template<typename D> constexpr Quantity<D> Atto(Quantity<D> base) { return 1e-18 * base; } template<typename D> constexpr Quantity<D> Zepto(Quantity<D> base) { return 1e-21 * base; } template<typename D> constexpr Quantity<D> Yocto(Quantity<D> base) { return 1e-24 * base; } } // namespace si } // namespace quantities } // namespace principia <commit_msg>Lint.<commit_after> #pragma once #include "quantities/si.hpp" #include <string> namespace principia { namespace quantities { namespace si { template<typename D> std::string Format() { auto const format_unit = [](std::string const& name, int const exponent) -> std::string { switch (exponent) { case 0: return ""; break; case 1: return " " + name; default: return " " + name + "^" + std::to_string(exponent); } }; // This string has a leading space if it's not empty. auto const format = format_unit("m", D::Length) + format_unit("kg", D::Mass) + format_unit("s", D::Time) + format_unit("A", D::Current) + format_unit("K", D::Temperature) + format_unit("mol", D::Amount) + format_unit("cd", D::LuminousIntensity) + format_unit("rad", D::Angle); if (format.empty()) { return format; } else { return format.substr(1, format.size() - 1); } } template<typename D> constexpr Quantity<D> Yotta(Quantity<D> base) { return 1e24 * base; } template<typename D> constexpr Quantity<D> Zetta(Quantity<D> base) { return 1e21 * base; } template<typename D> constexpr Quantity<D> Exa(Quantity<D> base) { return 1e18 * base; } template<typename D> constexpr Quantity<D> Peta(Quantity<D> base) { return 1e15 * base; } template<typename D> constexpr Quantity<D> Tera(Quantity<D> base) { return 1e12 * base; } template<typename D> constexpr Quantity<D> Giga(Quantity<D> base) { return 1e9 * base; } template<typename D> constexpr Quantity<D> Mega(Quantity<D> base) { return 1e6 * base; } template<typename D> constexpr Quantity<D> Kilo(Quantity<D> base) { return 1e3 * base; } template<typename D> constexpr Quantity<D> Hecto(Quantity<D> base) { return 1e2 * base; } template<typename D> constexpr Quantity<D> Deca(Quantity<D> base) { return 1e1 * base; } template<typename D> constexpr Quantity<D> Deci(Quantity<D> base) { return 1e-1 * base; } template<typename D> constexpr Quantity<D> Centi(Quantity<D> base) { return 1e-2 * base; } template<typename D> constexpr Quantity<D> Milli(Quantity<D> base) { return 1e-3 * base; } template<typename D> constexpr Quantity<D> Micro(Quantity<D> base) { return 1e-6 * base; } template<typename D> constexpr Quantity<D> Nano(Quantity<D> base) { return 1e-9 * base; } template<typename D> constexpr Quantity<D> Pico(Quantity<D> base) { return 1e-12 * base; } template<typename D> constexpr Quantity<D> Femto(Quantity<D> base) { return 1e-15 * base; } template<typename D> constexpr Quantity<D> Atto(Quantity<D> base) { return 1e-18 * base; } template<typename D> constexpr Quantity<D> Zepto(Quantity<D> base) { return 1e-21 * base; } template<typename D> constexpr Quantity<D> Yocto(Quantity<D> base) { return 1e-24 * base; } } // namespace si } // namespace quantities } // namespace principia <|endoftext|>
<commit_before>// Created by 乔磊 on 2015/8/7. // Copyright (c) 2015年 乔磊. All rights reserved. // #include <NSolver/linearVelocityPotential/linearVelocityPotential.h> namespace velocityPotential { using namespace dealii; template <int dim> void LinearVelocityPotential<dim>::transfer_solution ( const FESystem<dim> &fe_NS, const DoFHandler<dim> &dof_handler_NS, LA::MPI::Vector &NS_solution) const { // Set quadrature points on NS FE supporting points. // Then extract desired values on these quadrature points. // If the quadrature points and the supporting points are arranged in // the same order, then we can loop through all the quadrature points and // assign corresponding values the NS solution vector. const FE_Q<dim> &fe_potential = fe; const DoFHandler<dim> &dof_handler_potential =dof_handler; const LA::MPI::Vector &potential_solution = locally_relevant_solution; // Here we assume all Finite Element types are the same in the NS system. Quadrature<dim> quadrature_on_NS_support_points (fe_NS.base_element (0).get_unit_support_points()); FEValues<dim> fe_values_potential (fe_potential, quadrature_on_NS_support_points, update_values | update_gradients | update_quadrature_points); const unsigned int n_q_points = quadrature_on_NS_support_points.size(); const unsigned int dofs_per_cell = fe_NS.dofs_per_cell; std::vector<types::global_dof_index> global_indices_of_local_dofs (dofs_per_cell); std::vector< Tensor<1,dim,double> > potential_grad_on_cell (n_q_points); // The two DoFHandlers are initialized from the same triangulation typename DoFHandler<dim>::active_cell_iterator cell_potential = dof_handler_potential.begin_active(), cell_NS = dof_handler_NS.begin_active(), endc_NS = dof_handler_NS.end(); for (; cell_NS!=endc_NS; ++cell_NS, ++cell_potential) { Assert (cell_potential != dof_handler_potential.end(), ExcMessage ("Reached end of tria for potential equation before NS equation!")); if (cell_NS->is_locally_owned()) { fe_values_potential.reinit (cell_potential); fe_values_potential.get_function_gradients ( potential_solution, potential_grad_on_cell); cell_NS->get_dof_indices (global_indices_of_local_dofs); // Since the quadrature is extracted according to the target FE supporting // points, we just have to loop through all the quadrature points. // We assume that the quadrature points and supporting points are // arranged in the same order. for (unsigned int q_point=0; q_point<n_q_points; ++q_point) { double Mach_local = 0.0; for (unsigned d=0; d<dim; ++d) { const double velocity = velocity_infty[d] + potential_grad_on_cell[q_point][d]; Mach_local += velocity * velocity; const unsigned int system_index = fe_NS.component_to_system_index (d, q_point); NS_solution[global_indices_of_local_dofs[system_index]] = velocity; } const double gas_gamma (1.4); const double Mach_infty (velocity_infty.square()); const double Mach_ratio = (1.0 + 0.5* (gas_gamma-1.0) * Mach_infty) / (1.0 + 0.5* (gas_gamma-1.0) * Mach_local); { // Density component const unsigned int system_index = fe_NS.component_to_system_index (dim, q_point); NS_solution[global_indices_of_local_dofs[system_index]] = std::pow (Mach_ratio, 1.0/ (gas_gamma - 1.0)); } { //Pressure component const unsigned int system_index = fe_NS.component_to_system_index (dim+1, q_point); NS_solution[global_indices_of_local_dofs[system_index]] = std::pow (Mach_ratio, gas_gamma/ (gas_gamma - 1.0)) / gas_gamma; } } } } } #include "linearVelocityPotential.inst" } <commit_msg>format code<commit_after>// Created by 乔磊 on 2015/8/7. // Copyright (c) 2015年 乔磊. All rights reserved. // #include <NSolver/linearVelocityPotential/linearVelocityPotential.h> namespace velocityPotential { using namespace dealii; template <int dim> void LinearVelocityPotential<dim>::transfer_solution ( const FESystem<dim> &fe_NS, const DoFHandler<dim> &dof_handler_NS, LA::MPI::Vector &NS_solution) const { // Set quadrature points on NS FE supporting points. // Then extract desired values on these quadrature points. // If the quadrature points and the supporting points are arranged in // the same order, then we can loop through all the quadrature points and // assign corresponding values the NS solution vector. const FE_Q<dim> &fe_potential = fe; const DoFHandler<dim> &dof_handler_potential =dof_handler; const LA::MPI::Vector &potential_solution = locally_relevant_solution; // Here we assume all Finite Element types are the same in the NS system. Quadrature<dim> quadrature_on_NS_support_points (fe_NS.base_element (0).get_unit_support_points()); FEValues<dim> fe_values_potential (fe_potential, quadrature_on_NS_support_points, update_values | update_gradients | update_quadrature_points); const unsigned int n_q_points = quadrature_on_NS_support_points.size(); const unsigned int dofs_per_cell = fe_NS.dofs_per_cell; std::vector<types::global_dof_index> global_indices_of_local_dofs (dofs_per_cell); std::vector<Tensor<1,dim,double> > potential_grad_on_cell (n_q_points); // The two DoFHandlers are initialized from the same triangulation typename DoFHandler<dim>::active_cell_iterator cell_potential = dof_handler_potential.begin_active(), cell_NS = dof_handler_NS.begin_active(), endc_NS = dof_handler_NS.end(); for (; cell_NS!=endc_NS; ++cell_NS, ++cell_potential) { Assert (cell_potential != dof_handler_potential.end(), ExcMessage ("Reached end of tria for potential equation before NS equation!")); if (cell_NS->is_locally_owned()) { fe_values_potential.reinit (cell_potential); fe_values_potential.get_function_gradients ( potential_solution, potential_grad_on_cell); cell_NS->get_dof_indices (global_indices_of_local_dofs); // Since the quadrature is extracted according to the target FE supporting // points, we just have to loop through all the quadrature points. // We assume that the quadrature points and supporting points are // arranged in the same order. for (unsigned int q_point=0; q_point<n_q_points; ++q_point) { double Mach_local = 0.0; for (unsigned d=0; d<dim; ++d) { const double velocity = velocity_infty[d] + potential_grad_on_cell[q_point][d]; Mach_local += velocity * velocity; const unsigned int system_index = fe_NS.component_to_system_index (d, q_point); NS_solution[global_indices_of_local_dofs[system_index]] = velocity; } const double gas_gamma (1.4); const double Mach_infty (velocity_infty.square()); const double Mach_ratio = (1.0 + 0.5* (gas_gamma-1.0) * Mach_infty) / (1.0 + 0.5* (gas_gamma-1.0) * Mach_local); { // Density component const unsigned int system_index = fe_NS.component_to_system_index (dim, q_point); NS_solution[global_indices_of_local_dofs[system_index]] = std::pow (Mach_ratio, 1.0/ (gas_gamma - 1.0)); } { //Pressure component const unsigned int system_index = fe_NS.component_to_system_index (dim+1, q_point); NS_solution[global_indices_of_local_dofs[system_index]] = std::pow (Mach_ratio, gas_gamma/ (gas_gamma - 1.0)) / gas_gamma; } } } } } #include "linearVelocityPotential.inst" } <|endoftext|>
<commit_before>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "fxaa.hpp" #include "math.hpp" namespace Granite { void setup_fxaa_postprocess(RenderGraph &graph, const std::string &input, const std::string &output, VkFormat output_format) { graph.get_texture_resource(input).get_attachment_info().unorm_srgb_alias = true; auto &fxaa = graph.add_pass("fxaa", RenderGraph::get_default_post_graphics_queue()); AttachmentInfo fxaa_output; fxaa_output.size_class = SizeClass::InputRelative; fxaa_output.size_relative_name = input; fxaa_output.format = output_format; fxaa.add_color_output(output, fxaa_output); auto &fxaa_input = fxaa.add_texture_input(input); fxaa.set_build_render_pass([&, input](Vulkan::CommandBuffer &cmd) { auto &input_image = graph.get_physical_texture_resource(fxaa_input); cmd.set_unorm_texture(0, 0, input_image); cmd.set_sampler(0, 0, Vulkan::StockSampler::LinearClamp); vec2 inv_size(1.0f / input_image.get_image().get_create_info().width, 1.0f / input_image.get_image().get_create_info().height); cmd.push_constants(&inv_size, 0, sizeof(inv_size)); auto &output_image = graph.get_physical_texture_resource(fxaa.get_color_outputs()[0]->get_physical_index()); bool srgb = Vulkan::format_is_srgb(output_image.get_format()); Vulkan::CommandBufferUtil::draw_fullscreen_quad(cmd, "builtin://shaders/quad.vert", "builtin://shaders/post/fxaa.frag", {{"FXAA_TARGET_SRGB", srgb ? 1 : 0}}); }); } }<commit_msg>Add prerotate support to FXAA.<commit_after>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "fxaa.hpp" #include "math.hpp" namespace Granite { void setup_fxaa_postprocess(RenderGraph &graph, const std::string &input, const std::string &output, VkFormat output_format) { graph.get_texture_resource(input).get_attachment_info().unorm_srgb_alias = true; auto &fxaa = graph.add_pass("fxaa", RenderGraph::get_default_post_graphics_queue()); AttachmentInfo fxaa_output; fxaa_output.supports_prerotate = true; fxaa_output.size_class = SizeClass::InputRelative; fxaa_output.size_relative_name = input; fxaa_output.format = output_format; fxaa.add_color_output(output, fxaa_output); auto &fxaa_input = fxaa.add_texture_input(input); fxaa.set_build_render_pass([&, input](Vulkan::CommandBuffer &cmd) { auto &input_image = graph.get_physical_texture_resource(fxaa_input); cmd.set_unorm_texture(0, 0, input_image); cmd.set_sampler(0, 0, Vulkan::StockSampler::LinearClamp); vec2 inv_size(1.0f / input_image.get_image().get_create_info().width, 1.0f / input_image.get_image().get_create_info().height); cmd.push_constants(&inv_size, 0, sizeof(inv_size)); auto &output_image = graph.get_physical_texture_resource(fxaa.get_color_outputs()[0]->get_physical_index()); bool srgb = Vulkan::format_is_srgb(output_image.get_format()); Vulkan::CommandBufferUtil::draw_fullscreen_quad(cmd, "builtin://shaders/quad.vert", "builtin://shaders/post/fxaa.frag", {{"FXAA_TARGET_SRGB", srgb ? 1 : 0}}); }); } }<|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Interface/Modules/Forward/BuildBEMatrixDialog.h> #include <Core/Algorithms/Legacy/Forward/BuildBEMatrixAlgo.h> using namespace SCIRun::Gui; using namespace SCIRun::Dataflow::Networks; using namespace SCIRun::Core::Algorithms; using namespace SCIRun::Core::Algorithms::Forward; namespace TableColumns { const int MinColumn = 0; const int FieldName = 0; const int FieldType = 1; const int BoundaryCondition = 2; const int InsideConductivity = 3; const int OutsideConductivity = 4; const int MaxColumn = OutsideConductivity + 1; } BuildBEMatrixDialog::BuildBEMatrixDialog(const std::string& name, ModuleStateHandle state, QWidget* parent /* = 0 */) : ModuleDialogGeneric(state, parent) { setupUi(this); setWindowTitle(QString::fromStdString(name)); fixSize(); WidgetStyleMixin::tableHeaderStyle(this->tableWidget); tableWidget->resizeColumnsToContents(); connect(tableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(pushTable(int,int))); } void BuildBEMatrixDialog::updateFromPortChange(int numPorts, const std::string&) { //std::cout << "updateFromPortChange " << numPorts << std::endl; auto oldRowCount = tableWidget->rowCount(); tableWidget->setRowCount(numPorts - 1); tableWidget->blockSignals(true); for (int i = oldRowCount; i < tableWidget->rowCount(); ++i) { using namespace TableColumns; tableWidget->setItem(i, FieldName, new QTableWidgetItem("field" + QString::number(i))); tableWidget->setItem(i, FieldType, new QTableWidgetItem("[populated on execute]")); tableWidget->setCellWidget(i, BoundaryCondition, makeComboBoxItem(i)); tableWidget->setCellWidget(i, InsideConductivity, makeDoubleEntryItem(i, InsideConductivity)); tableWidget->setCellWidget(i, OutsideConductivity, makeDoubleEntryItem(i, OutsideConductivity)); // type is readonly auto type = tableWidget->item(i, FieldType); type->setFlags(type->flags() & ~Qt::ItemIsEditable); pushTableRow(i); } pull(); tableWidget->resizeColumnsToContents(); tableWidget->blockSignals(false); } QComboBox* BuildBEMatrixDialog::makeComboBoxItem(int i) const { QStringList bcList; bcList << "Measurement (Neumann)" << "Source (Dirichlet)"; QComboBox* bcBox = new QComboBox(); bcBox->addItems(bcList); bcBox->setCurrentIndex(i == 0 ? 1 : 0); connect(bcBox, SIGNAL(currentIndexChanged(int)), this, SLOT(pushBoundaryConditions())); return bcBox; } QDoubleSpinBox* BuildBEMatrixDialog::makeDoubleEntryItem(int row, int col) const { auto spin = new QDoubleSpinBox(); spin->setValue((row + col + 1) % 6); const char* slot = col == TableColumns::InsideConductivity ? SLOT(pushInsides()) : SLOT(pushOutsides()); connect(spin, SIGNAL(valueChanged(double)), this, slot); return spin; } void BuildBEMatrixDialog::pushTable(int row, int col) { using namespace TableColumns; if (FieldName == col) pushNames(); else if (BoundaryCondition == col) pushBoundaryConditions(); else if (InsideConductivity == col) pushInsides(); else if (OutsideConductivity == col) pushOutsides(); } void BuildBEMatrixDialog::pushTableRow(int row) { using namespace TableColumns; for (int col = MinColumn; col < MaxColumn; ++col) pushTable(row, col); } void BuildBEMatrixDialog::pushNames() { using namespace TableColumns; if (!pulling_) { VariableList names; for (int i = 0; i < tableWidget->rowCount(); ++i) { auto item = tableWidget->item(i, FieldName); names.push_back(makeVariable("", item->text().toStdString())); } state_->setValue(Parameters::FieldNameList, names); } } void BuildBEMatrixDialog::pushBoundaryConditions() { using namespace TableColumns; if (!pulling_) { VariableList names; for (int i = 0; i < tableWidget->rowCount(); ++i) { auto box = qobject_cast<QComboBox*>(tableWidget->cellWidget(i, BoundaryCondition)); names.push_back(makeVariable("", box->currentText().toStdString())); } state_->setValue(Parameters::BoundaryConditionList, names); } } void BuildBEMatrixDialog::pushInsides() { using namespace TableColumns; if (!pulling_) { VariableList names; for (int i = 0; i < tableWidget->rowCount(); ++i) { auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(i, InsideConductivity)); names.push_back(makeVariable("", box->value())); } state_->setValue(Parameters::InsideConductivityList, names); } } void BuildBEMatrixDialog::pushOutsides() { using namespace TableColumns; if (!pulling_) { VariableList names; for (int i = 0; i < tableWidget->rowCount(); ++i) { auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(i, OutsideConductivity)); names.push_back(makeVariable("", box->value())); } state_->setValue(Parameters::OutsideConductivityList, names); } } void BuildBEMatrixDialog::pullSpecial() { pullNames(); pullFieldTypes(); pullBoundaryConditions(); pullInsides(); pullOutsides(); } void BuildBEMatrixDialog::pullNames() { using namespace TableColumns; Pulling p(this); auto nameList = state_->getValue(Parameters::FieldNameList).toVector(); const int rows = std::min(static_cast<int>(nameList.size()), tableWidget->rowCount()); for (int row = 0; row < rows; ++row) { auto item = tableWidget->item(row, FieldName); item->setText(QString::fromStdString(nameList[row].toString())); } } void BuildBEMatrixDialog::pullFieldTypes() { using namespace TableColumns; Pulling p(this); auto typeList = transient_value_cast<FieldTypeListType>(state_->getTransientValue(Parameters::FieldTypeList)); const int rows = std::min(static_cast<int>(typeList.size()), tableWidget->rowCount()); for (int row = 0; row < rows; ++row) { auto item = tableWidget->item(row, FieldType); item->setText(QString::fromStdString(typeList[row])); } } void BuildBEMatrixDialog::pullBoundaryConditions() { using namespace TableColumns; Pulling p(this); auto bdyList = state_->getValue(Parameters::BoundaryConditionList).toVector(); const int rows = std::min(static_cast<int>(bdyList.size()), tableWidget->rowCount()); for (int row = 0; row < rows; ++row) { auto box = qobject_cast<QComboBox*>(tableWidget->cellWidget(row, BoundaryCondition)); auto str = QString::fromStdString(bdyList[row].toString()); box->setCurrentIndex(box->findText(str)); } } void BuildBEMatrixDialog::pullInsides() { using namespace TableColumns; Pulling p(this); auto condList = state_->getValue(Parameters::InsideConductivityList).toVector(); const int rows = std::min(static_cast<int>(condList.size()), tableWidget->rowCount()); for (int row = 0; row < rows; ++row) { auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(row, InsideConductivity)); box->setValue(condList[row].toDouble()); } } void BuildBEMatrixDialog::pullOutsides() { using namespace TableColumns; Pulling p(this); auto condList = state_->getValue(Parameters::OutsideConductivityList).toVector(); const int rows = std::min(static_cast<int>(condList.size()), tableWidget->rowCount()); for (int row = 0; row < rows; ++row) { auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(row, OutsideConductivity)); box->setValue(condList[row].toDouble()); } } <commit_msg>fiddling with resolution of conductivity<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <Interface/Modules/Forward/BuildBEMatrixDialog.h> #include <Core/Algorithms/Legacy/Forward/BuildBEMatrixAlgo.h> using namespace SCIRun::Gui; using namespace SCIRun::Dataflow::Networks; using namespace SCIRun::Core::Algorithms; using namespace SCIRun::Core::Algorithms::Forward; namespace TableColumns { const int MinColumn = 0; const int FieldName = 0; const int FieldType = 1; const int BoundaryCondition = 2; const int InsideConductivity = 3; const int OutsideConductivity = 4; const int MaxColumn = OutsideConductivity + 1; } BuildBEMatrixDialog::BuildBEMatrixDialog(const std::string& name, ModuleStateHandle state, QWidget* parent /* = 0 */) : ModuleDialogGeneric(state, parent) { setupUi(this); setWindowTitle(QString::fromStdString(name)); fixSize(); WidgetStyleMixin::tableHeaderStyle(this->tableWidget); tableWidget->resizeColumnsToContents(); connect(tableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(pushTable(int,int))); } void BuildBEMatrixDialog::updateFromPortChange(int numPorts, const std::string&) { //std::cout << "updateFromPortChange " << numPorts << std::endl; auto oldRowCount = tableWidget->rowCount(); tableWidget->setRowCount(numPorts - 1); tableWidget->blockSignals(true); for (int i = oldRowCount; i < tableWidget->rowCount(); ++i) { using namespace TableColumns; tableWidget->setItem(i, FieldName, new QTableWidgetItem("field" + QString::number(i))); tableWidget->setItem(i, FieldType, new QTableWidgetItem("[populated on execute]")); tableWidget->setCellWidget(i, BoundaryCondition, makeComboBoxItem(i)); tableWidget->setCellWidget(i, InsideConductivity, makeDoubleEntryItem(i, InsideConductivity)); tableWidget->setCellWidget(i, OutsideConductivity, makeDoubleEntryItem(i, OutsideConductivity)); // type is readonly auto type = tableWidget->item(i, FieldType); type->setFlags(type->flags() & ~Qt::ItemIsEditable); pushTableRow(i); } pull(); tableWidget->resizeColumnsToContents(); tableWidget->blockSignals(false); } QComboBox* BuildBEMatrixDialog::makeComboBoxItem(int i) const { QStringList bcList; bcList << "Measurement (Neumann)" << "Source (Dirichlet)"; QComboBox* bcBox = new QComboBox(); bcBox->addItems(bcList); bcBox->setCurrentIndex(i == 0 ? 1 : 0); connect(bcBox, SIGNAL(currentIndexChanged(int)), this, SLOT(pushBoundaryConditions())); return bcBox; } QDoubleSpinBox* BuildBEMatrixDialog::makeDoubleEntryItem(int row, int col) const { auto spin = new QDoubleSpinBox(); spin->setValue((row + col + 1) % 2); const char* slot = col == TableColumns::InsideConductivity ? SLOT(pushInsides()) : SLOT(pushOutsides()); connect(spin, SIGNAL(valueChanged(double)), this, slot); return spin; } void BuildBEMatrixDialog::pushTable(int row, int col) { using namespace TableColumns; if (FieldName == col) pushNames(); else if (BoundaryCondition == col) pushBoundaryConditions(); else if (InsideConductivity == col) pushInsides(); else if (OutsideConductivity == col) pushOutsides(); } void BuildBEMatrixDialog::pushTableRow(int row) { using namespace TableColumns; for (int col = MinColumn; col < MaxColumn; ++col) pushTable(row, col); } void BuildBEMatrixDialog::pushNames() { using namespace TableColumns; if (!pulling_) { VariableList names; for (int i = 0; i < tableWidget->rowCount(); ++i) { auto item = tableWidget->item(i, FieldName); names.push_back(makeVariable("", item->text().toStdString())); } state_->setValue(Parameters::FieldNameList, names); } } void BuildBEMatrixDialog::pushBoundaryConditions() { using namespace TableColumns; if (!pulling_) { VariableList names; for (int i = 0; i < tableWidget->rowCount(); ++i) { auto box = qobject_cast<QComboBox*>(tableWidget->cellWidget(i, BoundaryCondition)); names.push_back(makeVariable("", box->currentText().toStdString())); } state_->setValue(Parameters::BoundaryConditionList, names); } } void BuildBEMatrixDialog::pushInsides() { using namespace TableColumns; if (!pulling_) { VariableList names; for (int i = 0; i < tableWidget->rowCount(); ++i) { auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(i, InsideConductivity)); names.push_back(makeVariable("", box->value())); } state_->setValue(Parameters::InsideConductivityList, names); } } void BuildBEMatrixDialog::pushOutsides() { using namespace TableColumns; if (!pulling_) { VariableList names; for (int i = 0; i < tableWidget->rowCount(); ++i) { auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(i, OutsideConductivity)); names.push_back(makeVariable("", box->value())); } state_->setValue(Parameters::OutsideConductivityList, names); } } void BuildBEMatrixDialog::pullSpecial() { pullNames(); pullFieldTypes(); pullBoundaryConditions(); pullInsides(); pullOutsides(); } void BuildBEMatrixDialog::pullNames() { using namespace TableColumns; Pulling p(this); auto nameList = state_->getValue(Parameters::FieldNameList).toVector(); const int rows = std::min(static_cast<int>(nameList.size()), tableWidget->rowCount()); for (int row = 0; row < rows; ++row) { auto item = tableWidget->item(row, FieldName); item->setText(QString::fromStdString(nameList[row].toString())); } } void BuildBEMatrixDialog::pullFieldTypes() { using namespace TableColumns; Pulling p(this); auto typeList = transient_value_cast<FieldTypeListType>(state_->getTransientValue(Parameters::FieldTypeList)); const int rows = std::min(static_cast<int>(typeList.size()), tableWidget->rowCount()); for (int row = 0; row < rows; ++row) { auto item = tableWidget->item(row, FieldType); item->setText(QString::fromStdString(typeList[row])); } } void BuildBEMatrixDialog::pullBoundaryConditions() { using namespace TableColumns; Pulling p(this); auto bdyList = state_->getValue(Parameters::BoundaryConditionList).toVector(); const int rows = std::min(static_cast<int>(bdyList.size()), tableWidget->rowCount()); for (int row = 0; row < rows; ++row) { auto box = qobject_cast<QComboBox*>(tableWidget->cellWidget(row, BoundaryCondition)); auto str = QString::fromStdString(bdyList[row].toString()); box->setCurrentIndex(box->findText(str)); } } void BuildBEMatrixDialog::pullInsides() { using namespace TableColumns; Pulling p(this); auto condList = state_->getValue(Parameters::InsideConductivityList).toVector(); const int rows = std::min(static_cast<int>(condList.size()), tableWidget->rowCount()); for (int row = 0; row < rows; ++row) { auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(row, InsideConductivity)); box->setValue(condList[row].toDouble()); } } void BuildBEMatrixDialog::pullOutsides() { using namespace TableColumns; Pulling p(this); auto condList = state_->getValue(Parameters::OutsideConductivityList).toVector(); const int rows = std::min(static_cast<int>(condList.size()), tableWidget->rowCount()); for (int row = 0; row < rows; ++row) { auto box = qobject_cast<QDoubleSpinBox*>(tableWidget->cellWidget(row, OutsideConductivity)); box->setValue(condList[row].toDouble()); } } <|endoftext|>
<commit_before>// // // Copyright 2020 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // #include <grpc/support/port_platform.h> #include "src/core/lib/security/authorization/evaluate_args.h" #include "src/core/lib/slice/slice_utils.h" namespace grpc_core { absl::string_view EvaluateArgs::GetPath() const { absl::string_view path; if (metadata_ != nullptr && metadata_->idx.named.path != nullptr) { grpc_linked_mdelem* elem = metadata_->idx.named.path; const grpc_slice& val = GRPC_MDVALUE(elem->md); path = StringViewFromSlice(val); } return path; } absl::string_view EvaluateArgs::GetHost() const { absl::string_view host; if (metadata_ != nullptr && metadata_->idx.named.host != nullptr) { grpc_linked_mdelem* elem = metadata_->idx.named.host; const grpc_slice& val = GRPC_MDVALUE(elem->md); host = StringViewFromSlice(val); } return host; } absl::string_view EvaluateArgs::GetMethod() const { absl::string_view method; if (metadata_ != nullptr && metadata_->idx.named.method != nullptr) { grpc_linked_mdelem* elem = metadata_->idx.named.method; const grpc_slice& val = GRPC_MDVALUE(elem->md); method = StringViewFromSlice(val); } return method; } std::multimap<absl::string_view, absl::string_view> EvaluateArgs::GetHeaders() const { std::multimap<absl::string_view, absl::string_view> headers; if (metadata_ == nullptr) { return headers; } for (grpc_linked_mdelem* elem = metadata_->list.head; elem != nullptr; elem = elem->next) { const grpc_slice& key = GRPC_MDKEY(elem->md); const grpc_slice& val = GRPC_MDVALUE(elem->md); headers.emplace(StringViewFromSlice(key), StringViewFromSlice(val)); } return headers; } absl::string_view EvaluateArgs::GetSpiffeId() const { if (auth_context_ == nullptr) { return ""; } grpc_auth_property_iterator it = grpc_auth_context_find_properties_by_name( auth_context_, GRPC_PEER_SPIFFE_ID_PROPERTY_NAME); const grpc_auth_property* prop = grpc_auth_property_iterator_next(&it); if (prop == nullptr || grpc_auth_property_iterator_next(&it) != nullptr) return ""; return absl::string_view( reinterpret_cast<const char*>(prop->value, prop->value_length)); } absl::string_view EvaluateArgs::GetCertServerName() const { if (auth_context_ == nullptr) { return ""; } grpc_auth_property_iterator it = grpc_auth_context_find_properties_by_name( auth_context_, GRPC_X509_CN_PROPERTY_NAME); const grpc_auth_property* prop = grpc_auth_property_iterator_next(&it); if (prop == nullptr || grpc_auth_property_iterator_next(&it) != nullptr) return ""; return absl::string_view(prop->value, prop->value_length); } } // namespace grpc_core <commit_msg>Remove cast.<commit_after>// // // Copyright 2020 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // #include <grpc/support/port_platform.h> #include "src/core/lib/security/authorization/evaluate_args.h" #include "src/core/lib/slice/slice_utils.h" namespace grpc_core { absl::string_view EvaluateArgs::GetPath() const { absl::string_view path; if (metadata_ != nullptr && metadata_->idx.named.path != nullptr) { grpc_linked_mdelem* elem = metadata_->idx.named.path; const grpc_slice& val = GRPC_MDVALUE(elem->md); path = StringViewFromSlice(val); } return path; } absl::string_view EvaluateArgs::GetHost() const { absl::string_view host; if (metadata_ != nullptr && metadata_->idx.named.host != nullptr) { grpc_linked_mdelem* elem = metadata_->idx.named.host; const grpc_slice& val = GRPC_MDVALUE(elem->md); host = StringViewFromSlice(val); } return host; } absl::string_view EvaluateArgs::GetMethod() const { absl::string_view method; if (metadata_ != nullptr && metadata_->idx.named.method != nullptr) { grpc_linked_mdelem* elem = metadata_->idx.named.method; const grpc_slice& val = GRPC_MDVALUE(elem->md); method = StringViewFromSlice(val); } return method; } std::multimap<absl::string_view, absl::string_view> EvaluateArgs::GetHeaders() const { std::multimap<absl::string_view, absl::string_view> headers; if (metadata_ == nullptr) { return headers; } for (grpc_linked_mdelem* elem = metadata_->list.head; elem != nullptr; elem = elem->next) { const grpc_slice& key = GRPC_MDKEY(elem->md); const grpc_slice& val = GRPC_MDVALUE(elem->md); headers.emplace(StringViewFromSlice(key), StringViewFromSlice(val)); } return headers; } absl::string_view EvaluateArgs::GetSpiffeId() const { if (auth_context_ == nullptr) { return ""; } grpc_auth_property_iterator it = grpc_auth_context_find_properties_by_name( auth_context_, GRPC_PEER_SPIFFE_ID_PROPERTY_NAME); const grpc_auth_property* prop = grpc_auth_property_iterator_next(&it); if (prop == nullptr || grpc_auth_property_iterator_next(&it) != nullptr) { return ""; } return absl::string_view(prop->value, prop->value_length); } absl::string_view EvaluateArgs::GetCertServerName() const { if (auth_context_ == nullptr) { return ""; } grpc_auth_property_iterator it = grpc_auth_context_find_properties_by_name( auth_context_, GRPC_X509_CN_PROPERTY_NAME); const grpc_auth_property* prop = grpc_auth_property_iterator_next(&it); if (prop == nullptr || grpc_auth_property_iterator_next(&it) != nullptr) { return ""; } return absl::string_view(prop->value, prop->value_length); } } // namespace grpc_core <|endoftext|>
<commit_before>#include "dockerappmanager.h" #include <sstream> /** * @brief This package manager compliments the OSTreePackageManager by also including optional Docker Apps. * * A full description of the Docker App project can be found here: * https://github.com/docker/app/ * * Docker Apps are very analogous to docker-compose. In fact, this module * currently "renders" the docker-app file into a docker-compose file. Each * Docker App appears as a Target in the TUF targets list. Each OStree target * can then reference these docker apps in its custom data section. eg: * * "targets": { * httpd.dockerapp-1 : { * "custom" : {"hardwareIds" : ["all"], "name" : "httpd.dockerapp", "version" : "1"}, * "hashes" : {"sha256" : "f0ad4e3ce6a5e9cb70c9d747e977fddfacd08419deec0714622029b12dde8338"}, * "length" : 889 * }, * "raspberrypi3-64-lmp-144" : { * "custom" : { * "docker_apps" : { * "httpd" : { * "filename" : "httpd.dockerapp-1" * } * }, * "hardwareIds" : ["raspberrypi3-64"], * "name" : "raspberrypi3-64-lmp", * "targetFormat" : "OSTREE", * "version" : "144" * }, * "hashes" : {"sha256" : "20ac4f7cd50cda6bfed0caa1f8231cc9a7e40bec60026c66df5f7e143af96942"}, * "length" : 0 * } * } */ struct DockerApp { DockerApp(std::string app_name, const PackageConfig &config) : name(std::move(app_name)), app_root(config.docker_apps_root / name), app_params(config.docker_app_params), app_bin(config.docker_app_bin), compose_bin(config.docker_compose_bin) {} bool render(const std::string &app_content, bool persist) { auto bin = boost::filesystem::canonical(app_bin).string(); Utils::writeFile(app_root / (name + ".dockerapp"), app_content); std::string cmd("cd " + app_root.string() + " && " + bin + " render " + name); if (!app_params.empty()) { cmd += " -f " + app_params.string(); } std::string yaml; if (Utils::shell(cmd, &yaml, true) != 0) { LOG_ERROR << "Unable to run " << cmd << " output:\n" << yaml; return false; } if (persist) { Utils::writeFile(app_root / "docker-compose.yml", yaml); } return true; } bool start() { // Depending on the number and size of the containers in the docker-app, // this command can take a bit of time to complete. Rather than using, // Utils::shell which isn't interactive, we'll use std::system so that // stdout/stderr is streamed while docker sets things up. auto bin = boost::filesystem::canonical(compose_bin).string(); std::string cmd("cd " + app_root.string() + " && " + bin + " up --remove-orphans -d"); return std::system(cmd.c_str()) == 0; } void remove() { auto bin = boost::filesystem::canonical(compose_bin).string(); std::string cmd("cd " + app_root.string() + " && " + bin + " down"); if (std::system(cmd.c_str()) == 0) { boost::filesystem::remove_all(app_root); } else { LOG_ERROR << "docker-compose was unable to bring down: " << app_root; } } std::string name; boost::filesystem::path app_root; boost::filesystem::path app_params; boost::filesystem::path app_bin; boost::filesystem::path compose_bin; }; bool DockerAppManager::iterate_apps(const Uptane::Target &target, const DockerAppCb &cb) const { auto apps = target.custom_data()["docker_apps"]; bool res = true; Uptane::ImagesRepository repo; // checkMetaOffline pulls in data from INvStorage to properly initialize // the targets member of the instance so that we can use the LazyTargetList repo.checkMetaOffline(*storage_); if (!apps) { LOG_DEBUG << "Detected an update target from Director with no docker-apps data"; for (const auto &t : Uptane::LazyTargetsList(repo, storage_, fake_fetcher_)) { if (t.MatchTarget(target)) { LOG_DEBUG << "Found the match " << t; apps = t.custom_data()["docker_apps"]; break; } } } for (const auto &t : Uptane::LazyTargetsList(repo, storage_, fake_fetcher_)) { for (Json::ValueIterator i = apps.begin(); i != apps.end(); ++i) { if ((*i).isObject() && (*i).isMember("filename")) { for (const auto &app : config.docker_apps) { if (i.key().asString() == app && (*i)["filename"].asString() == t.filename()) { if (!cb(app, t)) { res = false; } } } } else { LOG_ERROR << "Invalid custom data for docker-app: " << i.key().asString() << " -> " << *i; } } } return res; } bool DockerAppManager::fetchTarget(const Uptane::Target &target, Uptane::Fetcher &fetcher, const KeyManager &keys, FetcherProgressCb progress_cb, const api::FlowControlToken *token) { if (!OstreeManager::fetchTarget(target, fetcher, keys, progress_cb, token)) { return false; } LOG_INFO << "Looking for DockerApps to fetch"; auto cb = [this, &fetcher, &keys, progress_cb, token](const std::string &app, const Uptane::Target &app_target) { LOG_INFO << "Fetching " << app << " -> " << app_target; return PackageManagerInterface::fetchTarget(app_target, fetcher, keys, progress_cb, token); }; return iterate_apps(target, cb); } data::InstallationResult DockerAppManager::install(const Uptane::Target &target) const { auto res = OstreeManager::install(target); handleRemovedApps(); auto cb = [this](const std::string &app, const Uptane::Target &app_target) { LOG_INFO << "Installing " << app << " -> " << app_target; std::stringstream ss; ss << *storage_->openTargetFile(app_target); DockerApp dapp(app, config); return dapp.render(ss.str(), true) && dapp.start(); }; if (!iterate_apps(target, cb)) { return data::InstallationResult(data::ResultCode::Numeric::kInstallFailed, "Could not render docker app"); } return res; } // Handle the case like: // 1) sota.toml is configured with 2 docker apps: "app1, app2" // 2) update is applied, so we are now running both app1 and app2 // 3) sota.toml is updated with 1 docker app: "app1" // At this point we should stop app2 and remove it. void DockerAppManager::handleRemovedApps() const { if (!boost::filesystem::is_directory(config.docker_apps_root)) { LOG_DEBUG << "config.docker_apps_root does not exist"; return; } for (auto &entry : boost::make_iterator_range(boost::filesystem::directory_iterator(config.docker_apps_root), {})) { if (boost::filesystem::is_directory(entry)) { std::string name = entry.path().filename().native(); if (std::find(config.docker_apps.begin(), config.docker_apps.end(), name) == config.docker_apps.end()) { LOG_WARNING << "Docker App(" << name << ") installed, but is now removed from configuration. Removing from system"; DockerApp(name, config).remove(); } } } } TargetStatus DockerAppManager::verifyTarget(const Uptane::Target &target) const { TargetStatus status; if (target.IsOstree()) { status = OstreeManager::verifyTarget(target); if (status != TargetStatus::kGood) { return status; } } auto cb = [this](const std::string &app, const Uptane::Target &app_target) { LOG_INFO << "Verifying " << app << " -> " << app_target; std::stringstream ss; ss << *storage_->openTargetFile(app_target); DockerApp dapp(app, config); return dapp.render(ss.str(), false); }; if (!iterate_apps(target, cb)) { return TargetStatus::kInvalid; } return TargetStatus::kGood; } <commit_msg>docker-app: Fix bad parameters file logic<commit_after>#include "dockerappmanager.h" #include <sstream> /** * @brief This package manager compliments the OSTreePackageManager by also including optional Docker Apps. * * A full description of the Docker App project can be found here: * https://github.com/docker/app/ * * Docker Apps are very analogous to docker-compose. In fact, this module * currently "renders" the docker-app file into a docker-compose file. Each * Docker App appears as a Target in the TUF targets list. Each OStree target * can then reference these docker apps in its custom data section. eg: * * "targets": { * httpd.dockerapp-1 : { * "custom" : {"hardwareIds" : ["all"], "name" : "httpd.dockerapp", "version" : "1"}, * "hashes" : {"sha256" : "f0ad4e3ce6a5e9cb70c9d747e977fddfacd08419deec0714622029b12dde8338"}, * "length" : 889 * }, * "raspberrypi3-64-lmp-144" : { * "custom" : { * "docker_apps" : { * "httpd" : { * "filename" : "httpd.dockerapp-1" * } * }, * "hardwareIds" : ["raspberrypi3-64"], * "name" : "raspberrypi3-64-lmp", * "targetFormat" : "OSTREE", * "version" : "144" * }, * "hashes" : {"sha256" : "20ac4f7cd50cda6bfed0caa1f8231cc9a7e40bec60026c66df5f7e143af96942"}, * "length" : 0 * } * } */ struct DockerApp { DockerApp(std::string app_name, const PackageConfig &config) : name(std::move(app_name)), app_root(config.docker_apps_root / name), app_params(config.docker_app_params), app_bin(config.docker_app_bin), compose_bin(config.docker_compose_bin) {} bool render(const std::string &app_content, bool persist) { auto bin = boost::filesystem::canonical(app_bin).string(); Utils::writeFile(app_root / (name + ".dockerapp"), app_content); std::string cmd("cd " + app_root.string() + " && " + bin + " render " + name); if (!app_params.empty()) { cmd += " --parameters-file " + app_params.string(); } std::string yaml; if (Utils::shell(cmd, &yaml, true) != 0) { LOG_ERROR << "Unable to run " << cmd << " output:\n" << yaml; return false; } if (persist) { Utils::writeFile(app_root / "docker-compose.yml", yaml); } return true; } bool start() { // Depending on the number and size of the containers in the docker-app, // this command can take a bit of time to complete. Rather than using, // Utils::shell which isn't interactive, we'll use std::system so that // stdout/stderr is streamed while docker sets things up. auto bin = boost::filesystem::canonical(compose_bin).string(); std::string cmd("cd " + app_root.string() + " && " + bin + " up --remove-orphans -d"); return std::system(cmd.c_str()) == 0; } void remove() { auto bin = boost::filesystem::canonical(compose_bin).string(); std::string cmd("cd " + app_root.string() + " && " + bin + " down"); if (std::system(cmd.c_str()) == 0) { boost::filesystem::remove_all(app_root); } else { LOG_ERROR << "docker-compose was unable to bring down: " << app_root; } } std::string name; boost::filesystem::path app_root; boost::filesystem::path app_params; boost::filesystem::path app_bin; boost::filesystem::path compose_bin; }; bool DockerAppManager::iterate_apps(const Uptane::Target &target, const DockerAppCb &cb) const { auto apps = target.custom_data()["docker_apps"]; bool res = true; Uptane::ImagesRepository repo; // checkMetaOffline pulls in data from INvStorage to properly initialize // the targets member of the instance so that we can use the LazyTargetList repo.checkMetaOffline(*storage_); if (!apps) { LOG_DEBUG << "Detected an update target from Director with no docker-apps data"; for (const auto &t : Uptane::LazyTargetsList(repo, storage_, fake_fetcher_)) { if (t.MatchTarget(target)) { LOG_DEBUG << "Found the match " << t; apps = t.custom_data()["docker_apps"]; break; } } } for (const auto &t : Uptane::LazyTargetsList(repo, storage_, fake_fetcher_)) { for (Json::ValueIterator i = apps.begin(); i != apps.end(); ++i) { if ((*i).isObject() && (*i).isMember("filename")) { for (const auto &app : config.docker_apps) { if (i.key().asString() == app && (*i)["filename"].asString() == t.filename()) { if (!cb(app, t)) { res = false; } } } } else { LOG_ERROR << "Invalid custom data for docker-app: " << i.key().asString() << " -> " << *i; } } } return res; } bool DockerAppManager::fetchTarget(const Uptane::Target &target, Uptane::Fetcher &fetcher, const KeyManager &keys, FetcherProgressCb progress_cb, const api::FlowControlToken *token) { if (!OstreeManager::fetchTarget(target, fetcher, keys, progress_cb, token)) { return false; } LOG_INFO << "Looking for DockerApps to fetch"; auto cb = [this, &fetcher, &keys, progress_cb, token](const std::string &app, const Uptane::Target &app_target) { LOG_INFO << "Fetching " << app << " -> " << app_target; return PackageManagerInterface::fetchTarget(app_target, fetcher, keys, progress_cb, token); }; return iterate_apps(target, cb); } data::InstallationResult DockerAppManager::install(const Uptane::Target &target) const { auto res = OstreeManager::install(target); handleRemovedApps(); auto cb = [this](const std::string &app, const Uptane::Target &app_target) { LOG_INFO << "Installing " << app << " -> " << app_target; std::stringstream ss; ss << *storage_->openTargetFile(app_target); DockerApp dapp(app, config); return dapp.render(ss.str(), true) && dapp.start(); }; if (!iterate_apps(target, cb)) { return data::InstallationResult(data::ResultCode::Numeric::kInstallFailed, "Could not render docker app"); } return res; } // Handle the case like: // 1) sota.toml is configured with 2 docker apps: "app1, app2" // 2) update is applied, so we are now running both app1 and app2 // 3) sota.toml is updated with 1 docker app: "app1" // At this point we should stop app2 and remove it. void DockerAppManager::handleRemovedApps() const { if (!boost::filesystem::is_directory(config.docker_apps_root)) { LOG_DEBUG << "config.docker_apps_root does not exist"; return; } for (auto &entry : boost::make_iterator_range(boost::filesystem::directory_iterator(config.docker_apps_root), {})) { if (boost::filesystem::is_directory(entry)) { std::string name = entry.path().filename().native(); if (std::find(config.docker_apps.begin(), config.docker_apps.end(), name) == config.docker_apps.end()) { LOG_WARNING << "Docker App(" << name << ") installed, but is now removed from configuration. Removing from system"; DockerApp(name, config).remove(); } } } } TargetStatus DockerAppManager::verifyTarget(const Uptane::Target &target) const { TargetStatus status; if (target.IsOstree()) { status = OstreeManager::verifyTarget(target); if (status != TargetStatus::kGood) { return status; } } auto cb = [this](const std::string &app, const Uptane::Target &app_target) { LOG_INFO << "Verifying " << app << " -> " << app_target; std::stringstream ss; ss << *storage_->openTargetFile(app_target); DockerApp dapp(app, config); return dapp.render(ss.str(), false); }; if (!iterate_apps(target, cb)) { return TargetStatus::kInvalid; } return TargetStatus::kGood; } <|endoftext|>
<commit_before>/* Copyright 2017 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. ==============================================================================*/ #define EIGEN_USE_THREADS #include <algorithm> #include <numeric> #include <unordered_map> #include <utility> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_util.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/util/sparse/sparse_tensor.h" namespace tensorflow { using CPUDevice = Eigen::ThreadPoolDevice; template <typename T> class SparseFillEmptyRowsOp : public OpKernel { public: explicit SparseFillEmptyRowsOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor* indices_t; const Tensor* values_t; const Tensor* dense_shape_t; const Tensor* default_value_t; OP_REQUIRES_OK(context, context->input("indices", &indices_t)); OP_REQUIRES_OK(context, context->input("values", &values_t)); OP_REQUIRES_OK(context, context->input("dense_shape", &dense_shape_t)); OP_REQUIRES_OK(context, context->input("default_value", &default_value_t)); const CPUDevice& d = context->eigen_device<CPUDevice>(); OP_REQUIRES(context, TensorShapeUtils::IsVector(dense_shape_t->shape()), errors::InvalidArgument("dense_shape must be a vector, saw: ", dense_shape_t->shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices_t->shape()), errors::InvalidArgument("indices must be a matrix, saw: ", indices_t->shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVector(values_t->shape()), errors::InvalidArgument("values must be a vector, saw: ", values_t->shape().DebugString())); OP_REQUIRES( context, TensorShapeUtils::IsScalar(default_value_t->shape()), errors::InvalidArgument("default_value must be a scalar, saw: ", default_value_t->shape().DebugString())); // TODO(ebrevdo): add shape checks between values, indices, // dense_shape. Also add check that dense rank > 0. const T& default_value = default_value_t->scalar<T>()(); const auto indices = indices_t->matrix<int64>(); const auto values = values_t->vec<T>(); const auto dense_shape = dense_shape_t->vec<int64>(); const int64 N = indices_t->shape().dim_size(0); const int64 dense_rows = dense_shape(0); Tensor* empty_row_indicator_t; OP_REQUIRES_OK(context, context->allocate_output("empty_row_indicator", TensorShape({dense_rows}), &empty_row_indicator_t)); auto empty_row_indicator = empty_row_indicator_t->vec<bool>(); Tensor* reverse_index_map_t; OP_REQUIRES_OK( context, context->allocate_output("reverse_index_map", TensorShape({N}), &reverse_index_map_t)); auto reverse_index_map = reverse_index_map_t->vec<int64>(); int rank = indices_t->shape().dim_size(1); if (dense_rows == 0) { OP_REQUIRES( context, N == 0, errors::InvalidArgument("Received SparseTensor with dense_shape[0] = " "0 but indices.shape[0] = ", N)); Tensor* output_indices_t; TensorShape output_indices_shape({0, rank}); OP_REQUIRES_OK(context, context->allocate_output("output_indices", output_indices_shape, &output_indices_t)); Tensor* output_values_t; OP_REQUIRES_OK(context, context->allocate_output("output_values", TensorShape({0}), &output_values_t)); // Exit early, nothing more to do. return; } Tensor scratch_t; OP_REQUIRES_OK(context, context->allocate_temp(DT_INT64, TensorShape({dense_rows}), &scratch_t)); auto scratch = scratch_t.vec<int64>(); scratch.device(d) = scratch.constant(0); for (int i = 0; i < N; ++i) { const int64 row = indices(i, 0); OP_REQUIRES(context, row >= 0 && row < dense_rows, errors::InvalidArgument("indices(", i, ", 0) is invalid: ", row, " >= ", dense_rows)); ++scratch(indices(i, 0)); } for (int row = 0; row < dense_rows; ++row) { // Scratch here describes the number of elements in this dense row empty_row_indicator(row) = (scratch(row) == 0); // In filled version, each row has at least one element. scratch(row) = std::max(scratch(row), int64{1}); // Update scratch to represent the number of elements up to and // including dense_row + 1: // scratch(0) == #{elements of row 0} // scratch(1) == #{elements of row 1} + #{elements of row 0} // .. // scratch(i) == starting index for elements in row i + 1. if (row > 0) { scratch(row) += scratch(row - 1); } } Tensor* output_indices_t; const int64 N_full = scratch(dense_rows - 1); TensorShape output_indices_shape({N_full, rank}); OP_REQUIRES_OK(context, context->allocate_output("output_indices", output_indices_shape, &output_indices_t)); auto output_indices = output_indices_t->matrix<int64>(); output_indices.device(d) = output_indices.constant(0); Tensor* output_values_t; OP_REQUIRES_OK( context, context->allocate_output( "output_values", TensorShape({N_full}), &output_values_t)); auto output_values = output_values_t->vec<T>(); output_values.device(d) = output_values.constant(default_value); Tensor filled_count_t; OP_REQUIRES_OK(context, context->allocate_temp(DT_INT64, TensorShape({dense_rows}), &filled_count_t)); auto filled_count = filled_count_t.vec<int64>(); filled_count.device(d) = filled_count.constant(0); // Fill in values for rows that are not missing for (int64 i = 0; i < N; ++i) { const int64 row = indices(i, 0); int64& offset = filled_count(row); const int64 output_i = ((row == 0) ? 0 : scratch(row - 1)) + offset; offset++; // Increment the filled count for this row. std::copy_n(&indices(i, 0), rank, &output_indices(output_i, 0)); output_values(output_i) = values(i); // We'll need this reverse index map to backprop correctly. reverse_index_map(i) = output_i; } // Fill in values for rows that are missing for (int64 row = 0; row < dense_rows; ++row) { const int64 row_count = filled_count(row); if (row_count == 0) { // We haven't filled this row const int64 starting_index = (row == 0) ? 0 : scratch(row - 1); // Remaining index values were set to zero already. // The value at this index was set to default_value already. // Just need to set the row index in the right location. output_indices(starting_index, 0) = row; } } } }; #define REGISTER_KERNELS(type) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRows") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T"), \ SparseFillEmptyRowsOp<type>) TF_CALL_ALL_TYPES(REGISTER_KERNELS); #undef REGISTER_KERNELS template <typename T> class SparseFillEmptyRowsGradOp : public OpKernel { public: explicit SparseFillEmptyRowsGradOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor* reverse_index_map_t; const Tensor* grad_values_t; OP_REQUIRES_OK(context, context->input("reverse_index_map", &reverse_index_map_t)); OP_REQUIRES_OK(context, context->input("grad_values", &grad_values_t)); const CPUDevice& d = context->eigen_device<CPUDevice>(); OP_REQUIRES( context, TensorShapeUtils::IsVector(reverse_index_map_t->shape()), errors::InvalidArgument("reverse_index_map must be a vector, saw: ", reverse_index_map_t->shape().DebugString())); const auto reverse_index_map = reverse_index_map_t->vec<int64>(); const auto grad_values = grad_values_t->vec<T>(); const int64 N = reverse_index_map_t->shape().dim_size(0); const int64 N_full = grad_values_t->shape().dim_size(0); Tensor* d_values_t; OP_REQUIRES_OK(context, context->allocate_output( "d_values", TensorShape({N}), &d_values_t)); auto d_values = d_values_t->vec<T>(); Tensor* d_default_value_t; OP_REQUIRES_OK(context, context->allocate_output("d_default_value", TensorShape({}), &d_default_value_t)); T& d_default_value = d_default_value_t->scalar<T>()(); d_default_value = T(); Tensor visited_t; OP_REQUIRES_OK(context, context->allocate_temp( DT_BOOL, TensorShape({N_full}), &visited_t)); auto visited = visited_t.vec<bool>(); visited.device(d) = visited.constant(false); for (int i = 0; i < N; ++i) { // Locate the index of the output of the forward prop associated // with this location in the input of the forward prop. Copy // the gradient into it. Mark it as visited. d_values(i) = grad_values(reverse_index_map(i)); visited(reverse_index_map(i)) = true; } for (int j = 0; j < N_full; ++j) { // The default value gradient gets the accumulated remainder of // the backprop values (since the default value was used to fill // in these slots in the forward calculation). if (!visited(j)) { d_default_value += grad_values(j); } } } }; #define REGISTER_KERNELS(type) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRowsGrad") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T"), \ SparseFillEmptyRowsGradOp<type>) TF_CALL_NUMBER_TYPES(REGISTER_KERNELS); #undef REGISTER_KERNELS } // namespace tensorflow <commit_msg>[SparseFillEmptyRowsOp] Use integer input/output indices instead of string names.<commit_after>/* Copyright 2017 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. ==============================================================================*/ #define EIGEN_USE_THREADS #include <algorithm> #include <numeric> #include <unordered_map> #include <utility> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_util.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/util/sparse/sparse_tensor.h" namespace tensorflow { using CPUDevice = Eigen::ThreadPoolDevice; template <typename T> class SparseFillEmptyRowsOp : public OpKernel { public: explicit SparseFillEmptyRowsOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const int kIndicesInput = 0; const int kValuesInput = 1; const int kDenseShapeInput = 2; const int kDefaultValueInput = 3; const int kOutputIndicesOutput = 0; const int kOutputValuesOutput = 1; const int kEmptyRowIndicatorOutput = 2; const int kReverseIndexMapOutput = 3; const Tensor& indices_t = context->input(kIndicesInput); const Tensor& values_t = context->input(kValuesInput); const Tensor& dense_shape_t = context->input(kDenseShapeInput); const Tensor& default_value_t = context->input(kDefaultValueInput); const CPUDevice& d = context->eigen_device<CPUDevice>(); OP_REQUIRES(context, TensorShapeUtils::IsVector(dense_shape_t.shape()), errors::InvalidArgument("dense_shape must be a vector, saw: ", dense_shape_t.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices_t.shape()), errors::InvalidArgument("indices must be a matrix, saw: ", indices_t.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVector(values_t.shape()), errors::InvalidArgument("values must be a vector, saw: ", values_t.shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsScalar(default_value_t.shape()), errors::InvalidArgument("default_value must be a scalar, saw: ", default_value_t.shape().DebugString())); // TODO(ebrevdo): add shape checks between values, indices, // dense_shape. Also add check that dense rank > 0. const T& default_value = default_value_t.scalar<T>()(); const auto indices = indices_t.matrix<int64>(); const auto values = values_t.vec<T>(); const auto dense_shape = dense_shape_t.vec<int64>(); const int64 N = indices_t.shape().dim_size(0); const int64 dense_rows = dense_shape(0); Tensor* empty_row_indicator_t; OP_REQUIRES_OK(context, context->allocate_output(kEmptyRowIndicatorOutput, TensorShape({dense_rows}), &empty_row_indicator_t)); auto empty_row_indicator = empty_row_indicator_t->vec<bool>(); Tensor* reverse_index_map_t; OP_REQUIRES_OK(context, context->allocate_output(kReverseIndexMapOutput, TensorShape({N}), &reverse_index_map_t)); auto reverse_index_map = reverse_index_map_t->vec<int64>(); int rank = indices_t.shape().dim_size(1); if (dense_rows == 0) { OP_REQUIRES( context, N == 0, errors::InvalidArgument("Received SparseTensor with dense_shape[0] = " "0 but indices.shape[0] = ", N)); Tensor* output_indices_t; TensorShape output_indices_shape({0, rank}); OP_REQUIRES_OK(context, context->allocate_output(kOutputIndicesOutput, output_indices_shape, &output_indices_t)); Tensor* output_values_t; OP_REQUIRES_OK(context, context->allocate_output(kOutputValuesOutput, TensorShape({0}), &output_values_t)); // Exit early, nothing more to do. return; } Tensor scratch_t; OP_REQUIRES_OK(context, context->allocate_temp(DT_INT64, TensorShape({dense_rows}), &scratch_t)); auto scratch = scratch_t.vec<int64>(); scratch.device(d) = scratch.constant(0); for (int i = 0; i < N; ++i) { const int64 row = indices(i, 0); OP_REQUIRES(context, row >= 0 && row < dense_rows, errors::InvalidArgument("indices(", i, ", 0) is invalid: ", row, " >= ", dense_rows)); ++scratch(indices(i, 0)); } for (int row = 0; row < dense_rows; ++row) { // Scratch here describes the number of elements in this dense row empty_row_indicator(row) = (scratch(row) == 0); // In filled version, each row has at least one element. scratch(row) = std::max(scratch(row), int64{1}); // Update scratch to represent the number of elements up to and // including dense_row + 1: // scratch(0) == #{elements of row 0} // scratch(1) == #{elements of row 1} + #{elements of row 0} // .. // scratch(i) == starting index for elements in row i + 1. if (row > 0) { scratch(row) += scratch(row - 1); } } Tensor* output_indices_t; const int64 N_full = scratch(dense_rows - 1); TensorShape output_indices_shape({N_full, rank}); OP_REQUIRES_OK(context, context->allocate_output(kOutputIndicesOutput, output_indices_shape, &output_indices_t)); auto output_indices = output_indices_t->matrix<int64>(); output_indices.device(d) = output_indices.constant(0); Tensor* output_values_t; OP_REQUIRES_OK(context, context->allocate_output(kOutputValuesOutput, TensorShape({N_full}), &output_values_t)); auto output_values = output_values_t->vec<T>(); output_values.device(d) = output_values.constant(default_value); Tensor filled_count_t; OP_REQUIRES_OK(context, context->allocate_temp(DT_INT64, TensorShape({dense_rows}), &filled_count_t)); auto filled_count = filled_count_t.vec<int64>(); filled_count.device(d) = filled_count.constant(0); // Fill in values for rows that are not missing for (int64 i = 0; i < N; ++i) { const int64 row = indices(i, 0); int64& offset = filled_count(row); const int64 output_i = ((row == 0) ? 0 : scratch(row - 1)) + offset; offset++; // Increment the filled count for this row. std::copy_n(&indices(i, 0), rank, &output_indices(output_i, 0)); output_values(output_i) = values(i); // We'll need this reverse index map to backprop correctly. reverse_index_map(i) = output_i; } // Fill in values for rows that are missing for (int64 row = 0; row < dense_rows; ++row) { const int64 row_count = filled_count(row); if (row_count == 0) { // We haven't filled this row const int64 starting_index = (row == 0) ? 0 : scratch(row - 1); // Remaining index values were set to zero already. // The value at this index was set to default_value already. // Just need to set the row index in the right location. output_indices(starting_index, 0) = row; } } } }; #define REGISTER_KERNELS(type) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRows") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T"), \ SparseFillEmptyRowsOp<type>) TF_CALL_ALL_TYPES(REGISTER_KERNELS); #undef REGISTER_KERNELS template <typename T> class SparseFillEmptyRowsGradOp : public OpKernel { public: explicit SparseFillEmptyRowsGradOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor* reverse_index_map_t; const Tensor* grad_values_t; OP_REQUIRES_OK(context, context->input("reverse_index_map", &reverse_index_map_t)); OP_REQUIRES_OK(context, context->input("grad_values", &grad_values_t)); const CPUDevice& d = context->eigen_device<CPUDevice>(); OP_REQUIRES( context, TensorShapeUtils::IsVector(reverse_index_map_t->shape()), errors::InvalidArgument("reverse_index_map must be a vector, saw: ", reverse_index_map_t->shape().DebugString())); const auto reverse_index_map = reverse_index_map_t->vec<int64>(); const auto grad_values = grad_values_t->vec<T>(); const int64 N = reverse_index_map_t->shape().dim_size(0); const int64 N_full = grad_values_t->shape().dim_size(0); Tensor* d_values_t; OP_REQUIRES_OK(context, context->allocate_output( "d_values", TensorShape({N}), &d_values_t)); auto d_values = d_values_t->vec<T>(); Tensor* d_default_value_t; OP_REQUIRES_OK(context, context->allocate_output("d_default_value", TensorShape({}), &d_default_value_t)); T& d_default_value = d_default_value_t->scalar<T>()(); d_default_value = T(); Tensor visited_t; OP_REQUIRES_OK(context, context->allocate_temp( DT_BOOL, TensorShape({N_full}), &visited_t)); auto visited = visited_t.vec<bool>(); visited.device(d) = visited.constant(false); for (int i = 0; i < N; ++i) { // Locate the index of the output of the forward prop associated // with this location in the input of the forward prop. Copy // the gradient into it. Mark it as visited. d_values(i) = grad_values(reverse_index_map(i)); visited(reverse_index_map(i)) = true; } for (int j = 0; j < N_full; ++j) { // The default value gradient gets the accumulated remainder of // the backprop values (since the default value was used to fill // in these slots in the forward calculation). if (!visited(j)) { d_default_value += grad_values(j); } } } }; #define REGISTER_KERNELS(type) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRowsGrad") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T"), \ SparseFillEmptyRowsGradOp<type>) TF_CALL_NUMBER_TYPES(REGISTER_KERNELS); #undef REGISTER_KERNELS } // namespace tensorflow <|endoftext|>
<commit_before>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <thrift/lib/cpp2/util/ScopedServerInterfaceThread.h> #include <folly/SocketAddress.h> #include <thrift/lib/cpp2/async/PooledRequestChannel.h> #include <thrift/lib/cpp2/server/BaseThriftServer.h> #include <thrift/lib/cpp2/server/ThriftServer.h> using namespace std; using namespace folly; using namespace apache::thrift::concurrency; namespace apache { namespace thrift { ScopedServerInterfaceThread::ScopedServerInterfaceThread( shared_ptr<AsyncProcessorFactory> apf, SocketAddress const& addr, ServerConfigCb configCb) { auto tf = make_shared<PosixThreadFactory>(PosixThreadFactory::ATTACHED); auto tm = ThreadManager::newSimpleThreadManager(1); tm->threadFactory(move(tf)); tm->start(); auto ts = make_shared<ThriftServer>(); ts->setAddress(addr); // Allow plaintext on loopback so the plaintext clients created by default by // the newClient methods can still connect. ts->setAllowPlaintextOnLoopback(true); ts->setProcessorFactory(move(apf)); ts->setNumIOWorkerThreads(1); ts->setNumCPUWorkerThreads(1); ts->setThreadManager(tm); // The default behavior is to keep N recent requests per IO worker in memory. // In unit-tests, this defers memory reclamation and potentially masks // use-after-free bugs. Because this facility is used mostly in tests, it is // better not to keep any recent requests in memory. ts->setMaxFinishedDebugPayloadsPerWorker(0); if (configCb) { configCb(*ts); } ts_ = ts; sst_.start(ts_, [ts]() { ts->getEventBaseManager()->clearEventBase(); }); } ScopedServerInterfaceThread::ScopedServerInterfaceThread( shared_ptr<AsyncProcessorFactory> apf, const string& host, uint16_t port, ServerConfigCb configCb) : ScopedServerInterfaceThread( move(apf), SocketAddress(host, port), move(configCb)) {} ScopedServerInterfaceThread::ScopedServerInterfaceThread( shared_ptr<AsyncProcessorFactory> apf, ServerConfigCb configCb) : ScopedServerInterfaceThread(move(apf), "::1", 0, move(configCb)) {} ScopedServerInterfaceThread::ScopedServerInterfaceThread( shared_ptr<BaseThriftServer> bts) { ts_ = bts; sst_.start(ts_); } BaseThriftServer& ScopedServerInterfaceThread::getThriftServer() const { return *ts_; } const SocketAddress& ScopedServerInterfaceThread::getAddress() const { return *sst_.getAddress(); } uint16_t ScopedServerInterfaceThread::getPort() const { return getAddress().getPort(); } RequestChannel::Ptr ScopedServerInterfaceThread::newChannel( folly::Executor* callbackExecutor, MakeChannelFunc makeChannel, size_t numThreads) const { return PooledRequestChannel::newChannel( callbackExecutor, [makeChannel = std::move(makeChannel), address = getAddress()](folly::EventBase& eb) mutable { return makeChannel(folly::AsyncSocket::UniquePtr( new folly::AsyncSocket(&eb, address))); }, numThreads); } namespace { struct TestClientRunner { ScopedServerInterfaceThread runner; RequestChannel::Ptr channel; explicit TestClientRunner(std::shared_ptr<AsyncProcessorFactory> apf) : runner(std::move(apf)) {} }; } // namespace std::shared_ptr<RequestChannel> ScopedServerInterfaceThread::makeTestClientChannel( std::shared_ptr<AsyncProcessorFactory> apf, ScopedServerInterfaceThread::FaultInjectionFunc injectFault) { auto runner = std::make_shared<TestClientRunner>(std::move(apf)); auto innerChannel = runner->runner.newChannel( folly::getGlobalCPUExecutor().get(), RocketClientChannel::newChannel); if (injectFault) { runner->channel.reset(new apache::thrift::detail::FaultInjectionChannel( std::move(innerChannel), std::move(injectFault))); } else { runner->channel = std::move(innerChannel); } auto* channel = runner->channel.get(); return folly::to_shared_ptr_aliasing(std::move(runner), channel); } namespace detail { void validateServiceName(AsyncProcessorFactory& apf, const char* serviceName) { if (auto* service = dynamic_cast<ServerInterface*>(&apf)) { std::string actualServiceName{service->getGeneratedName()}; CHECK_STREQ(actualServiceName.c_str(), serviceName) << "Client and handler type mismatch"; } } } // namespace detail } // namespace thrift } // namespace apache <commit_msg>Don't use setThreadManager in ScopedServerInterfaceThread<commit_after>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <thrift/lib/cpp2/util/ScopedServerInterfaceThread.h> #include <folly/SocketAddress.h> #include <thrift/lib/cpp2/async/PooledRequestChannel.h> #include <thrift/lib/cpp2/server/BaseThriftServer.h> #include <thrift/lib/cpp2/server/ThriftServer.h> using namespace std; using namespace folly; using namespace apache::thrift::concurrency; namespace apache { namespace thrift { ScopedServerInterfaceThread::ScopedServerInterfaceThread( shared_ptr<AsyncProcessorFactory> apf, SocketAddress const& addr, ServerConfigCb configCb) { auto ts = make_shared<ThriftServer>(); ts->setAddress(addr); // Allow plaintext on loopback so the plaintext clients created by default // by the newClient methods can still connect. ts->setAllowPlaintextOnLoopback(true); ts->setProcessorFactory(move(apf)); ts->setNumIOWorkerThreads(1); ts->setNumCPUWorkerThreads(1); auto tf = make_shared<PosixThreadFactory>(PosixThreadFactory::ATTACHED); ts->setThreadFactory(std::move(tf)); ts->setThreadManagerType( apache::thrift::BaseThriftServer::ThreadManagerType::SIMPLE); // The default behavior is to keep N recent requests per IO worker in // memory. In unit-tests, this defers memory reclamation and potentially // masks use-after-free bugs. Because this facility is used mostly in tests, // it is better not to keep any recent requests in memory. ts->setMaxFinishedDebugPayloadsPerWorker(0); if (configCb) { configCb(*ts); } ts_ = ts; sst_.start(ts_, [ts]() { ts->getEventBaseManager()->clearEventBase(); }); } ScopedServerInterfaceThread::ScopedServerInterfaceThread( shared_ptr<AsyncProcessorFactory> apf, const string& host, uint16_t port, ServerConfigCb configCb) : ScopedServerInterfaceThread( move(apf), SocketAddress(host, port), move(configCb)) {} ScopedServerInterfaceThread::ScopedServerInterfaceThread( shared_ptr<AsyncProcessorFactory> apf, ServerConfigCb configCb) : ScopedServerInterfaceThread(move(apf), "::1", 0, move(configCb)) {} ScopedServerInterfaceThread::ScopedServerInterfaceThread( shared_ptr<BaseThriftServer> bts) { ts_ = bts; sst_.start(ts_); } BaseThriftServer& ScopedServerInterfaceThread::getThriftServer() const { return *ts_; } const SocketAddress& ScopedServerInterfaceThread::getAddress() const { return *sst_.getAddress(); } uint16_t ScopedServerInterfaceThread::getPort() const { return getAddress().getPort(); } RequestChannel::Ptr ScopedServerInterfaceThread::newChannel( folly::Executor* callbackExecutor, MakeChannelFunc makeChannel, size_t numThreads) const { return PooledRequestChannel::newChannel( callbackExecutor, [makeChannel = std::move(makeChannel), address = getAddress()](folly::EventBase& eb) mutable { return makeChannel(folly::AsyncSocket::UniquePtr( new folly::AsyncSocket(&eb, address))); }, numThreads); } namespace { struct TestClientRunner { ScopedServerInterfaceThread runner; RequestChannel::Ptr channel; explicit TestClientRunner(std::shared_ptr<AsyncProcessorFactory> apf) : runner(std::move(apf)) {} }; } // namespace std::shared_ptr<RequestChannel> ScopedServerInterfaceThread::makeTestClientChannel( std::shared_ptr<AsyncProcessorFactory> apf, ScopedServerInterfaceThread::FaultInjectionFunc injectFault) { auto runner = std::make_shared<TestClientRunner>(std::move(apf)); auto innerChannel = runner->runner.newChannel( folly::getGlobalCPUExecutor().get(), RocketClientChannel::newChannel); if (injectFault) { runner->channel.reset(new apache::thrift::detail::FaultInjectionChannel( std::move(innerChannel), std::move(injectFault))); } else { runner->channel = std::move(innerChannel); } auto* channel = runner->channel.get(); return folly::to_shared_ptr_aliasing(std::move(runner), channel); } namespace detail { void validateServiceName(AsyncProcessorFactory& apf, const char* serviceName) { if (auto* service = dynamic_cast<ServerInterface*>(&apf)) { std::string actualServiceName{service->getGeneratedName()}; CHECK_STREQ(actualServiceName.c_str(), serviceName) << "Client and handler type mismatch"; } } } // namespace detail } // namespace thrift } // namespace apache <|endoftext|>
<commit_before>#include <QtTest/QtTest> #include <QProcess> #include "../cutehmi.dirs.hpp" namespace cutehmi { namespace daemon { class test_cutehmi_daemon: public QObject { Q_OBJECT private slots: void initTestCase(); void helpOption(); void versionOption(); void countDaemonExample(); private: QString m_installDir; QString m_programPath; }; void test_cutehmi_daemon::initTestCase() { QString m_installDir = qEnvironmentVariable("CUTEHMI_INSTALL_DIR"); QVERIFY(!m_installDir.isEmpty()); QString toolsInstallSubdir = CUTEHMI_DIRS_TOOLS_INSTALL_SUBDIR; if (!toolsInstallSubdir.isEmpty()) m_installDir += "/" + toolsInstallSubdir; m_programPath = m_installDir + "/cutehmi.daemon.3"; #ifndef CUTEHMI_NDEBUG m_programPath += ".debug"; #endif } void test_cutehmi_daemon::helpOption() { QList<QStringList> argumentsList; argumentsList << QStringList({"--help"}) << QStringList({"--h"}); for (auto arguments : argumentsList) { QProcess process; process.start(m_programPath, arguments); process.waitForFinished(1000); QCOMPARE(process.error(), QProcess::UnknownError); QVERIFY(!process.readAllStandardError().contains("Unknown option")); QVERIFY(!process.readAllStandardOutput().isEmpty()); QCOMPARE(process.exitStatus(), QProcess::NormalExit); QCOMPARE(process.exitCode(), EXIT_SUCCESS); } } void test_cutehmi_daemon::versionOption() { QList<QStringList> argumentsList; argumentsList << QStringList({"--version"}) << QStringList({"--v"}); for (auto arguments : argumentsList) { QProcess process; process.start(m_programPath, arguments); process.waitForFinished(1000); QCOMPARE(process.error(), QProcess::UnknownError); QVERIFY(!process.readAllStandardError().contains("Unknown option")); QVERIFY(!process.readAllStandardOutput().isEmpty()); QCOMPARE(process.exitStatus(), QProcess::NormalExit); QCOMPARE(process.exitCode(), EXIT_SUCCESS); } } void test_cutehmi_daemon::countDaemonExample() { QProcess process; QStringList arguments { {"--app"}, {"--extension=CuteHMI.Examples.CountDaemon.2"} }; process.start(m_programPath, arguments); QVERIFY(process.waitForFinished()); QString stdOut = QString::fromLocal8Bit(process.readAllStandardOutput()); QString stdErr = QString::fromLocal8Bit(process.readAllStandardError()); QVERIFY(stdErr.contains("I can count")); QCOMPARE(process.error(), QProcess::UnknownError); QCOMPARE(process.exitStatus(), QProcess::NormalExit); QCOMPARE(process.exitCode(), EXIT_SUCCESS); } } } QTEST_MAIN(cutehmi::daemon::test_cutehmi_daemon) #include "test_cutehmi_daemon.moc" //(c)C: Copyright © 2020, Michał Policht <[email protected]>. All rights reserved. //(c)C: This file is a part of CuteHMI. //(c)C: CuteHMI 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. //(c)C: CuteHMI 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. //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>. <commit_msg>Fix countDaemonExample() arguments.<commit_after>#include <QtTest/QtTest> #include <QProcess> #include "../cutehmi.dirs.hpp" namespace cutehmi { namespace daemon { class test_cutehmi_daemon: public QObject { Q_OBJECT private slots: void initTestCase(); void helpOption(); void versionOption(); void countDaemonExample(); private: QString m_installDir; QString m_programPath; }; void test_cutehmi_daemon::initTestCase() { QString m_installDir = qEnvironmentVariable("CUTEHMI_INSTALL_DIR"); QVERIFY(!m_installDir.isEmpty()); QString toolsInstallSubdir = CUTEHMI_DIRS_TOOLS_INSTALL_SUBDIR; if (!toolsInstallSubdir.isEmpty()) m_installDir += "/" + toolsInstallSubdir; m_programPath = m_installDir + "/cutehmi.daemon.3"; #ifndef CUTEHMI_NDEBUG m_programPath += ".debug"; #endif } void test_cutehmi_daemon::helpOption() { QList<QStringList> argumentsList; argumentsList << QStringList({"--help"}) << QStringList({"--h"}); for (auto arguments : argumentsList) { QProcess process; process.start(m_programPath, arguments); process.waitForFinished(1000); QCOMPARE(process.error(), QProcess::UnknownError); QVERIFY(!process.readAllStandardError().contains("Unknown option")); QVERIFY(!process.readAllStandardOutput().isEmpty()); QCOMPARE(process.exitStatus(), QProcess::NormalExit); QCOMPARE(process.exitCode(), EXIT_SUCCESS); } } void test_cutehmi_daemon::versionOption() { QList<QStringList> argumentsList; argumentsList << QStringList({"--version"}) << QStringList({"--v"}); for (auto arguments : argumentsList) { QProcess process; process.start(m_programPath, arguments); process.waitForFinished(1000); QCOMPARE(process.error(), QProcess::UnknownError); QVERIFY(!process.readAllStandardError().contains("Unknown option")); QVERIFY(!process.readAllStandardOutput().isEmpty()); QCOMPARE(process.exitStatus(), QProcess::NormalExit); QCOMPARE(process.exitCode(), EXIT_SUCCESS); } } void test_cutehmi_daemon::countDaemonExample() { QProcess process; QStringList arguments { {"--app"}, {"CuteHMI.Examples.CountDaemon.3"} }; process.start(m_programPath, arguments); QVERIFY(process.waitForFinished()); QString stdOut = QString::fromLocal8Bit(process.readAllStandardOutput()); QString stdErr = QString::fromLocal8Bit(process.readAllStandardError()); QVERIFY(stdErr.contains("I can count")); QCOMPARE(process.error(), QProcess::UnknownError); QCOMPARE(process.exitStatus(), QProcess::NormalExit); QCOMPARE(process.exitCode(), EXIT_SUCCESS); } } } QTEST_MAIN(cutehmi::daemon::test_cutehmi_daemon) #include "test_cutehmi_daemon.moc" //(c)C: Copyright © 2020, Michał Policht <[email protected]>. All rights reserved. //(c)C: This file is a part of CuteHMI. //(c)C: CuteHMI 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. //(c)C: CuteHMI 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. //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>. <|endoftext|>
<commit_before>809e926a-2d15-11e5-af21-0401358ea401<commit_msg>809e926b-2d15-11e5-af21-0401358ea401<commit_after>809e926b-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>7f6cf578-2d15-11e5-af21-0401358ea401<commit_msg>7f6cf579-2d15-11e5-af21-0401358ea401<commit_after>7f6cf579-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include "Piezas.h" #include <vector> /** CLASS Piezas * Class for representing a Piezas vertical board, which is roughly based * on the game "Connect Four" where pieces are placed in a column and * fall to the bottom of the column, or on top of other pieces already in * that column. For an illustration of the board, see: * https://en.wikipedia.org/wiki/Connect_Four * * Board coordinates [row,col] should match with: * [2,0][2,1][2,2][2,3] * [1,0][1,1][1,2][1,3] * [0,0][0,1][0,2][0,3] * So that a piece dropped in column 2 should take [0,2] and the next one * dropped in column 2 should take [1,2]. **/ /** * Constructor sets an empty board (default 3 rows, 4 columns) and * specifies it is X's turn first **/ Piezas::Piezas(); { reset(); turn = X; } /** * Resets each board location to the Blank Piece value, with a board of the * same size as previously specified **/ void Piezas::reset(); { for(int i = 0; i < BOARD_ROWS; i++) { for(int j = 0; j < BOARD_COLS; j++) { board[i][j] = Blank; } } } /** * Places a piece of the current turn on the board, returns what * piece is placed, and toggles which Piece's turn it is. dropPiece does * NOT allow to place a piece in a location where a column is full. * In that case, placePiece returns Piece Blank value * Out of bounds coordinates return the Piece Invalid value * Trying to drop a piece where it cannot be placed loses the player's turn **/ Piece Piezas::dropPiece(int column); { //Out of bounds placement means turn switches, return valid if(column > 3 || column < 0) { if(turn == X) { turn = O; } else { turn = X; } return Invalid; } //checking from bottom of column to the top, else return nothing if(board[2][column] == Blank) { board[2][column] = turn; if(turn == X) { turn = O; } else { turn = X; } return board[2][column]; } else if(board[1][column] == Blank) { board[1][column] == turn; if(turn == X) { turn = O; } else { turn = X; } return board[1][column]; } else if(board[0][column] == Blank) { board[0][column] == turn; if(turn == X) { turn = O; } else { turn = X; } return board[0][column]; } else { return Blank; } } /** * Returns what piece is at the provided coordinates, or Blank if there * are no pieces there, or Invalid if the coordinates are out of bounds **/ Piece Piezas::pieceAt(int row, int column); { if((row > 2 || row < 0) || (column < 0 || column > 3)) { return Invalid; } if(board[row][column] != Blank) { return board[row][column]; } else { return Blank; } } /** * Returns which Piece has won, if there is a winner, Invalid if the game * is not over, or Blank if the board is filled and no one has won ("tie"). * For a game to be over, all locations on the board must be filled with X's * and O's (i.e. no remaining Blank spaces). The winner is which player has * the most adjacent pieces in a single line. Lines can go either vertically * or horizontally. If both X's and O's have the same max number of pieces in a * line, it is a tie. **/ Piece Piezas::gameState(); { int max_x = 0; int max_o = 0; int x_amount; int o_amount; bool full_col_x = false; bool full_col_o = false; bool three_adj_x = false; bool three_adj_o = false; bool two_adj_x = false; bool two_adj_o = false; for(int i = 0; i < BOARD_ROWS; i++) { for(int j = 0; j < BOARD_COLS; j++) { if(board[i][j] == Blank) { return Invalid; } } } //check horizontal for(int i = 0; i < BOARD_ROWS; i++) { x_amount = 0; o_amount = 0; for(int j = 0; j < BOARD_COLS; j++) { if(board[i][j] == X) { x_amount++; } else { o_amount++; } } if(x_amount > max_x) { max_x = x_amount; } if(o_amount > max_o) { max_o = o_amount; } } //check for any max values of 4, that would automatically win or tie if(max_x == BOARD_COLS && max_o == BOARD_COLS) { return Blank; } else if(max_x == BOARD_COLS) { return X; } else if(max_o == BOARD_COLS) { return O; } //check verticals //check column 0 if(board[0][0] == X) { if(board[1][0] == X) { if(board][2][0] == X) { x_amount = 3; full_col_x = true; } else { x_amount = 2; } } else { x_amount = 1; } } else { if(board[1][0] == O) { if(board[2][0] == O) { o_amount = 3; full_col_o = true; } else { o_amount = 2; } } else { o_amount = 1; } } if(x_amount > max_x) { max_x = x_amount; } if(o_amount > max_o) { max_o = o_amount; } //check column 1 if(board[0][1] == X) { if(board[1][1] == X) { if(board][2][1] == X) { x_amount = 3; full_col_x = true; } else { x_amount = 2; } } else { x_amount = 1; } } else { if(board[1][1] == O) { if(board[2][1] == O) { o_amount = 3; full_col_o = true; } else { o_amount = 2; } } else { o_amount = 1; } } if(x_amount > max_x) { max_x = x_amount; } if(o_amount > max_o) { max_o = o_amount; } //check column 2 if(board[0][2] == X) { if(board[1][2] == X) { if(board][2][2] == X) { x_amount = 3; full_col_x = true; } else { x_amount = 2; } } else { x_amount = 1; } } else { if(board[1][2] == O) { if(board[2][2] == O) { o_amount = 3; full_col_o = true; } else { o_amount = 2; } } else { o_amount = 1; } } if(x_amount > max_x) { max_x = x_amount; } if(o_amount > max_o) { max_o = o_amount; } //check column 3 if(board[0][3] == X) { if(board[1][3] == X) { if(board][2][3] == X) { x_amount = 3; full_col_x = true; } else { x_amount = 2; } } else { x_amount = 1; } } else { if(board[1][3] == O) { if(board[2][3] == O) { o_amount = 3; full_col_o = true; } else { o_amount = 2; } } else { o_amount = 1; } } if(x_amount > max_x) { max_x = x_amount; } if(o_amount > max_o) { max_o = o_amount; } //check for 3 x's in a row if(max_x == BOARD_ROWS) { if(full_col_x == true) { three_adj_x = true; } else { for(int i = 0; i < BOARD_ROWS; i++) { if(board[i][0] == X) { if(board[i][1] == X && board[i][2] == X) { three_adj_x = true; } } else if(board[i][1] == X) { if(board[i][2] == X && board[i][3] == X) { three_adj_x = true; } } } } } //check for 3 o's in a row if(max_o == BOARD_ROWS) { if(full_col_o == true) { three_adj_o = true; } else { for(int i = 0; i < BOARD_ROWS; i++) { if(board[i][0] == O) { if(board[i][1] == O && board[i][2] == O) { three_adj_o = true; } } else if(board[i][1] == O) { if(board[i][2] == O && board[i][3] == O) { three_adj_o = true; } } } } } //check for tie of 3 in a row if(three_adj_x && three_adj_o) { return Blank; } else if(three_adj_x) { return X; } else if(three_adj_o) { return O; } //if max is 2 for either, check if they are in a row if(max_x == 2) { for(int i = 0; i < BOARD_ROWS; i++) { if(board[i][0] == X && board[i][1] == X) { two_adj_x = true; } else if(board[i][1] == X && board[i][2] == X) { two_adj_x = true; } else if(board[i][2] == X && board[i][3] == X) { two_adj_x = true; } } for(int j = 0; j < BOARD_COLS; j++) { if(board[0][j] == X && board[1][j] == X) { two_adj_x = true; } else if(board[1][j] == X && board[2][j] == X) { two_adj_x = true; } } } if(max_o == 2) { for(int i = 0; i < BOARD_ROWS; i++) { if(board[i][0] == O && board[i][1] == O) { two_adj_o = true; } else if(board[i][1] == O && board[i][2] == O) { two_adj_o = true; } else if(board[i][2] == O && board[i][3] == O) { two_adj_o = true; } } for(int j = 0; j < BOARD_COLS; j++) { if(board[0][j] == O && board[1][j] == O) { two_adj_o = true; } else if(board[1][j] == O && board[2][j] == O) { two_adj_o = true; } } } //check for tie of 2 in a row if(two_adj_x && two_adj_o) { return Blank; } else if(two_adj_x) { return X; } else if(two_adj_o) { return O; } //if all above fails to return, max is 1 for both, results in tie return Blank; }<commit_msg>Add files via upload<commit_after>#include "Piezas.h" #include <vector> /** CLASS Piezas * Class for representing a Piezas vertical board, which is roughly based * on the game "Connect Four" where pieces are placed in a column and * fall to the bottom of the column, or on top of other pieces already in * that column. For an illustration of the board, see: * https://en.wikipedia.org/wiki/Connect_Four * * Board coordinates [row,col] should match with: * [2,0][2,1][2,2][2,3] * [1,0][1,1][1,2][1,3] * [0,0][0,1][0,2][0,3] * So that a piece dropped in column 2 should take [0,2] and the next one * dropped in column 2 should take [1,2]. **/ /** * Constructor sets an empty board (default 3 rows, 4 columns) and * specifies it is X's turn first **/ Piezas::Piezas() { reset(); turn = X; } /** * Resets each board location to the Blank Piece value, with a board of the * same size as previously specified **/ void Piezas::reset() { for(int i = 0; i < BOARD_ROWS; i++) { for(int j = 0; j < BOARD_COLS; j++) { board[i][j] = Blank; } } } /** * Places a piece of the current turn on the board, returns what * piece is placed, and toggles which Piece's turn it is. dropPiece does * NOT allow to place a piece in a location where a column is full. * In that case, placePiece returns Piece Blank value * Out of bounds coordinates return the Piece Invalid value * Trying to drop a piece where it cannot be placed loses the player's turn **/ Piece Piezas::dropPiece(int column) { //Out of bounds placement means turn switches, return valid if(column > 3 || column < 0) { if(turn == X) { turn = O; } else { turn = X; } return Invalid; } //checking from bottom of column to the top, else return nothing if(board[2][column] == Blank) { board[2][column] = turn; if(turn == X) { turn = O; } else { turn = X; } return board[2][column]; } else if(board[1][column] == Blank) { board[1][column] == turn; if(turn == X) { turn = O; } else { turn = X; } return board[1][column]; } else if(board[0][column] == Blank) { board[0][column] == turn; if(turn == X) { turn = O; } else { turn = X; } return board[0][column]; } else { return Blank; } } /** * Returns what piece is at the provided coordinates, or Blank if there * are no pieces there, or Invalid if the coordinates are out of bounds **/ Piece Piezas::pieceAt(int row, int column) { if((row > 2 || row < 0) || (column < 0 || column > 3)) { return Invalid; } if(board[row][column] != Blank) { return board[row][column]; } else { return Blank; } } /** * Returns which Piece has won, if there is a winner, Invalid if the game * is not over, or Blank if the board is filled and no one has won ("tie"). * For a game to be over, all locations on the board must be filled with X's * and O's (i.e. no remaining Blank spaces). The winner is which player has * the most adjacent pieces in a single line. Lines can go either vertically * or horizontally. If both X's and O's have the same max number of pieces in a * line, it is a tie. **/ Piece Piezas::gameState() { int max_x = 0; int max_o = 0; int x_amount; int o_amount; bool full_col_x = false; bool full_col_o = false; bool three_adj_x = false; bool three_adj_o = false; bool two_adj_x = false; bool two_adj_o = false; for(int i = 0; i < BOARD_ROWS; i++) { for(int j = 0; j < BOARD_COLS; j++) { if(board[i][j] == Blank) { return Invalid; } } } //check horizontal for(int i = 0; i < BOARD_ROWS; i++) { x_amount = 0; o_amount = 0; for(int j = 0; j < BOARD_COLS; j++) { if(board[i][j] == X) { x_amount++; } else { o_amount++; } } if(x_amount > max_x) { max_x = x_amount; } if(o_amount > max_o) { max_o = o_amount; } } //check for any max values of 4, that would automatically win or tie if(max_x == BOARD_COLS && max_o == BOARD_COLS) { return Blank; } else if(max_x == BOARD_COLS) { return X; } else if(max_o == BOARD_COLS) { return O; } //check verticals //check column 0 if(board[0][0] == X) { if(board[1][0] == X) { if(board][2][0] == X) { x_amount = 3; full_col_x = true; } else { x_amount = 2; } } else { x_amount = 1; } } else { if(board[1][0] == O) { if(board[2][0] == O) { o_amount = 3; full_col_o = true; } else { o_amount = 2; } } else { o_amount = 1; } } if(x_amount > max_x) { max_x = x_amount; } if(o_amount > max_o) { max_o = o_amount; } //check column 1 if(board[0][1] == X) { if(board[1][1] == X) { if(board][2][1] == X) { x_amount = 3; full_col_x = true; } else { x_amount = 2; } } else { x_amount = 1; } } else { if(board[1][1] == O) { if(board[2][1] == O) { o_amount = 3; full_col_o = true; } else { o_amount = 2; } } else { o_amount = 1; } } if(x_amount > max_x) { max_x = x_amount; } if(o_amount > max_o) { max_o = o_amount; } //check column 2 if(board[0][2] == X) { if(board[1][2] == X) { if(board][2][2] == X) { x_amount = 3; full_col_x = true; } else { x_amount = 2; } } else { x_amount = 1; } } else { if(board[1][2] == O) { if(board[2][2] == O) { o_amount = 3; full_col_o = true; } else { o_amount = 2; } } else { o_amount = 1; } } if(x_amount > max_x) { max_x = x_amount; } if(o_amount > max_o) { max_o = o_amount; } //check column 3 if(board[0][3] == X) { if(board[1][3] == X) { if(board][2][3] == X) { x_amount = 3; full_col_x = true; } else { x_amount = 2; } } else { x_amount = 1; } } else { if(board[1][3] == O) { if(board[2][3] == O) { o_amount = 3; full_col_o = true; } else { o_amount = 2; } } else { o_amount = 1; } } if(x_amount > max_x) { max_x = x_amount; } if(o_amount > max_o) { max_o = o_amount; } //check for 3 x's in a row if(max_x == BOARD_ROWS) { if(full_col_x == true) { three_adj_x = true; } else { for(int i = 0; i < BOARD_ROWS; i++) { if(board[i][0] == X) { if(board[i][1] == X && board[i][2] == X) { three_adj_x = true; } } else if(board[i][1] == X) { if(board[i][2] == X && board[i][3] == X) { three_adj_x = true; } } } } } //check for 3 o's in a row if(max_o == BOARD_ROWS) { if(full_col_o == true) { three_adj_o = true; } else { for(int i = 0; i < BOARD_ROWS; i++) { if(board[i][0] == O) { if(board[i][1] == O && board[i][2] == O) { three_adj_o = true; } } else if(board[i][1] == O) { if(board[i][2] == O && board[i][3] == O) { three_adj_o = true; } } } } } //check for tie of 3 in a row if(three_adj_x && three_adj_o) { return Blank; } else if(three_adj_x) { return X; } else if(three_adj_o) { return O; } //if max is 2 for either, check if they are in a row if(max_x == 2) { for(int i = 0; i < BOARD_ROWS; i++) { if(board[i][0] == X && board[i][1] == X) { two_adj_x = true; } else if(board[i][1] == X && board[i][2] == X) { two_adj_x = true; } else if(board[i][2] == X && board[i][3] == X) { two_adj_x = true; } } for(int j = 0; j < BOARD_COLS; j++) { if(board[0][j] == X && board[1][j] == X) { two_adj_x = true; } else if(board[1][j] == X && board[2][j] == X) { two_adj_x = true; } } } if(max_o == 2) { for(int i = 0; i < BOARD_ROWS; i++) { if(board[i][0] == O && board[i][1] == O) { two_adj_o = true; } else if(board[i][1] == O && board[i][2] == O) { two_adj_o = true; } else if(board[i][2] == O && board[i][3] == O) { two_adj_o = true; } } for(int j = 0; j < BOARD_COLS; j++) { if(board[0][j] == O && board[1][j] == O) { two_adj_o = true; } else if(board[1][j] == O && board[2][j] == O) { two_adj_o = true; } } } //check for tie of 2 in a row if(two_adj_x && two_adj_o) { return Blank; } else if(two_adj_x) { return X; } else if(two_adj_o) { return O; } //if all above fails to return, max is 1 for both, results in tie return Blank; }<|endoftext|>
<commit_before>#include <set.hpp> #include <kdb> #include <iostream> using namespace std; using namespace kdb; SetCommand::SetCommand() {} int SetCommand::execute(int argc, char**argv) { if (argc != 3 && argc != 4) { cerr << "Please provide a name and a value to set" << endl; cerr << "Usage: set <name> [<value>]" << endl; cerr << "If no value is given, it will be set to a null-value" << endl; cerr << "To get an empty value you need to quote like \"\" (depending on shell)" << endl; return 1; } std::string name = argv[2]; bool nullValue = false; if (argc == 3) nullValue = true; std::string value; if (!nullValue) value = argv[3]; KeySet conf; Key k(name, KEY_END); try { kdb.get(conf, k); printWarnings(k); } catch (...) { printError(k); cerr << "kdb get failed, but still resume" << endl; } Key key = conf.lookup(name); if (!key) { cout << "create a new key with " << name << " and " << value << endl; key = Key(name, KEY_END); if (!nullValue) key.setString(value); if (!key.isValid()) { cerr << "no valid name supplied" << endl; return 1; } conf.append(key); } else { cout << "Set string to " << value << endl; if (!nullValue) key.setString(value); } Key n; kdb.set(conf, n); printWarnings(n); return 0; } SetCommand::~SetCommand() {} <commit_msg>dont commit when get failed<commit_after>#include <set.hpp> #include <kdb> #include <iostream> using namespace std; using namespace kdb; SetCommand::SetCommand() {} int SetCommand::execute(int argc, char**argv) { if (argc != 3 && argc != 4) { cerr << "Please provide a name and a value to set" << endl; cerr << "Usage: set <name> [<value>]" << endl; cerr << "If no value is given, it will be set to a null-value" << endl; cerr << "To get an empty value you need to quote like \"\" (depending on shell)" << endl; return 1; } std::string name = argv[2]; bool nullValue = false; if (argc == 3) nullValue = true; std::string value; if (!nullValue) value = argv[3]; KeySet conf; Key k(name, KEY_END); // do not resume on any get errors // otherwise the user might break // the config kdb.get(conf, k); printWarnings(k); Key key = conf.lookup(name); if (!key) { cout << "create a new key with " << name << " and " << value << endl; key = Key(name, KEY_END); if (!nullValue) key.setString(value); if (!key.isValid()) { cerr << "no valid name supplied" << endl; return 1; } conf.append(key); } else { cout << "Set string to " << value << endl; if (!nullValue) key.setString(value); } Key n; kdb.set(conf, n); printWarnings(n); return 0; } SetCommand::~SetCommand() {} <|endoftext|>
<commit_before>#include "log.h" // boost includes are not always warning-clean. Disable warnings that // cause problems before including the headers, then re-enable the warnings. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wextra" #include <boost/log/support/date_time.hpp> #include <boost/log/expressions/attr.hpp> #include <boost/log/expressions/formatters/date_time.hpp> #include <boost/log/utility/setup/console.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/attributes/scoped_attribute.hpp> #include <boost/log/attributes/current_thread_id.hpp> #include <vector> #include <unistd.h> #pragma GCC diagnostic pop namespace Cthun { bool Log::is_log_enabled(const std::string &logger, Log::log_level level) { // If the severity_logger returns a record for the specified // level, logging is enabled. Otherwise it isn't. // This is the guard call used in BOOST_LOG_SEV; see // www.boost.org/doc/libs/1_54_0/libs/log/doc/html/log/detailed/sources.html boost::log::sources::severity_logger<Log::log_level> slg; return (slg.open_record(boost::log::keywords::severity = level) ? true : false); } void Log::configure_logging(Log::log_level level, std::ostream &dst) { // Set filtering based on log_level (info, warning, debug, etc). auto sink = boost::log::add_console_log(dst); sink->set_formatter(boost::log::expressions::stream << boost::log::expressions::format_date_time<boost::posix_time::ptime>( "TimeStamp", "%Y-%m-%d %H:%M:%S.%f") << " " << boost::log::expressions::attr< boost::log::attributes::current_thread_id::value_type>("ThreadID") << " " << std::left << std::setfill(' ') << std::setw(5) << Log::log_level_attr << " " << Log::namespace_attr << " " << boost::log::expressions::smessage); sink->set_filter(log_level_attr >= level); boost::log::add_common_attributes(); } std::ostream& Log::operator<<(std::ostream& strm, Log::log_level level) { std::vector<std::string> levels { "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL" }; if (static_cast<size_t>(level) < levels.size()) { strm << levels[static_cast<size_t>(level)]; } else { strm << static_cast<int>(level); } return strm; } void Log::log(const std::string &logger, Log::log_level level, int line_num, boost::format& message) { log(logger, level, line_num, message.str()); } // // POSIX implementation of log() // // HERE(ale): we don't have the Win32 implementation; see cfacter static std::string cyan(std::string const& message) { return "\33[0;36m" + message + "\33[0m"; } static std::string green(std::string const& message) { return "\33[0;32m" + message + "\33[0m"; } static std::string yellow(std::string const& message) { return "\33[0;33m" + message + "\33[0m"; } static std::string red(std::string const& message) { return "\33[0;31m" + message + "\33[0m"; } void Log::log(const std::string &logger, Log::log_level level, int line_num, std::string const& message) { boost::log::sources::severity_logger<Log::log_level> slg; slg.add_attribute("Namespace", boost::log::attributes::constant<std::string>(logger)); static bool color = isatty(fileno(stderr)); if (!color) { BOOST_LOG_SEV(slg, level) << message; return; } switch (level) { case Log::log_level::trace: BOOST_LOG_SEV(slg, level) << line_num << " - " << cyan(message); break; case Log::log_level::debug: BOOST_LOG_SEV(slg, level) << line_num << " - " << cyan(message); break; case Log::log_level::info: BOOST_LOG_SEV(slg, level) << line_num << " - " << green(message); break; case Log::log_level::warning: BOOST_LOG_SEV(slg, level) << line_num << " - " << yellow(message); break; case Log::log_level::error: BOOST_LOG_SEV(slg, level) << line_num << " - " << red(message); break; case Log::log_level::fatal: BOOST_LOG_SEV(slg, level) << line_num << " - " << red(message); break; default: BOOST_LOG_SEV(slg, level) << line_num << " - " << "Invalid logging level used."; break; } } } // namespace Cthun <commit_msg>(maint) - updating log format<commit_after>#include "log.h" // boost includes are not always warning-clean. Disable warnings that // cause problems before including the headers, then re-enable the warnings. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wextra" #include <boost/log/support/date_time.hpp> #include <boost/log/expressions/attr.hpp> #include <boost/log/expressions/formatters/date_time.hpp> #include <boost/log/utility/setup/console.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/attributes/scoped_attribute.hpp> #include <boost/log/attributes/current_thread_id.hpp> #include <vector> #include <unistd.h> #pragma GCC diagnostic pop namespace Cthun { bool Log::is_log_enabled(const std::string &logger, Log::log_level level) { // If the severity_logger returns a record for the specified // level, logging is enabled. Otherwise it isn't. // This is the guard call used in BOOST_LOG_SEV; see // www.boost.org/doc/libs/1_54_0/libs/log/doc/html/log/detailed/sources.html boost::log::sources::severity_logger<Log::log_level> slg; return (slg.open_record(boost::log::keywords::severity = level) ? true : false); } void Log::configure_logging(Log::log_level level, std::ostream &dst) { // Set filtering based on log_level (info, warning, debug, etc). auto sink = boost::log::add_console_log(dst); sink->set_formatter(boost::log::expressions::stream << boost::log::expressions::format_date_time<boost::posix_time::ptime>( "TimeStamp", "%Y-%m-%d %H:%M:%S.%f") << " " << boost::log::expressions::attr< boost::log::attributes::current_thread_id::value_type>("ThreadID") << " " << std::left << std::setfill(' ') << std::setw(5) << Log::log_level_attr << " [" << Log::namespace_attr << ":" << boost::log::expressions::smessage); sink->set_filter(log_level_attr >= level); boost::log::add_common_attributes(); } std::ostream& Log::operator<<(std::ostream& strm, Log::log_level level) { std::vector<std::string> levels { "TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL" }; if (static_cast<size_t>(level) < levels.size()) { strm << levels[static_cast<size_t>(level)]; } else { strm << static_cast<int>(level); } return strm; } void Log::log(const std::string &logger, Log::log_level level, int line_num, boost::format& message) { log(logger, level, line_num, message.str()); } // // POSIX implementation of log() // // HERE(ale): we don't have the Win32 implementation; see cfacter static std::string cyan(std::string const& message) { return "\33[0;36m" + message + "\33[0m"; } static std::string green(std::string const& message) { return "\33[0;32m" + message + "\33[0m"; } static std::string yellow(std::string const& message) { return "\33[0;33m" + message + "\33[0m"; } static std::string red(std::string const& message) { return "\33[0;31m" + message + "\33[0m"; } void Log::log(const std::string &logger, Log::log_level level, int line_num, std::string const& message) { boost::log::sources::severity_logger<Log::log_level> slg; slg.add_attribute("Namespace", boost::log::attributes::constant<std::string>(logger)); static bool color = isatty(fileno(stderr)); if (!color) { BOOST_LOG_SEV(slg, level) << message; return; } switch (level) { case Log::log_level::trace: BOOST_LOG_SEV(slg, level) << line_num << "] - " << cyan(message); break; case Log::log_level::debug: BOOST_LOG_SEV(slg, level) << line_num << "] - " << cyan(message); break; case Log::log_level::info: BOOST_LOG_SEV(slg, level) << line_num << "] - " << green(message); break; case Log::log_level::warning: BOOST_LOG_SEV(slg, level) << line_num << "] - " << yellow(message); break; case Log::log_level::error: BOOST_LOG_SEV(slg, level) << line_num << "] - " << red(message); break; case Log::log_level::fatal: BOOST_LOG_SEV(slg, level) << line_num << "] - " << red(message); break; default: BOOST_LOG_SEV(slg, level) << line_num << "] - " << "Invalid logging level used."; break; } } } // namespace Cthun <|endoftext|>
<commit_before>/* * Copyright 2014 The Imaging Source Europe GmbH * * 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 "logging.h" #include "version.h" #include <stdio.h> /* printf, fopen */ #include <stdarg.h> /* va_args */ #include <string.h> /* memcpy */ #include <time.h> /* time_t */ static const char* loglevel2string (const enum TCAM_LOG_LEVEL level) { switch (level) { case TCAM_LOG_OFF: return "OFF"; case TCAM_LOG_TRACE: return "TRACE"; case TCAM_LOG_DEBUG: return "DEBUG"; case TCAM_LOG_INFO: return "INFO"; case TCAM_LOG_WARNING: return "WARNING"; case TCAM_LOG_ERROR: return "ERROR"; default: return NULL; } } static enum TCAM_LOG_LEVEL string2loglevel (const char* level) { if (strcmp("OFF", level) == 0) { return TCAM_LOG_OFF; } else if (strcmp("TRACE", level) == 0) { return TCAM_LOG_TRACE; } else if (strcmp("DEBUG", level) == 0) { return TCAM_LOG_DEBUG; } else if (strcmp("INFO", level) == 0) { return TCAM_LOG_INFO; } else if (strcmp("WARNING", level) == 0) { return TCAM_LOG_WARNING; } else if (strcmp("ERROR", level) == 0) { return TCAM_LOG_ERROR; } else return TCAM_LOG_ERROR; } Logger::Logger (): callback(nullptr), logfile(nullptr) { #ifndef TCAM_LOG_ENV_NAME #define TCAM_LOG_ENV_NAME "TCAM_LOG" #endif static const char* env_name = TCAM_LOG_ENV_NAME; load_default_settings(); char* log_def = getenv(env_name); if (log_def != nullptr) { level = string2loglevel(log_def); } if (level >= TCAM_LOG_DEBUG) { char b[1024]; sprintf(b, "\nThe following library versions are used:\n\tTcam:\t%s\n\tAravis:\t%s", get_version(), get_aravis_version()); va_list args; log("", TCAM_LOG_DEBUG, "Logger", __LINE__, b, args); } } void Logger::load_default_settings () { level = TCAM_LOG_OFF; target = STDIO; log_file = "/tmp/tis.log"; } void Logger::log (const char* module __attribute__((unused)), enum TCAM_LOG_LEVEL _level, const char* function, int line, const char* message, va_list args) { if (_level < level) { return; } // local copy of va_list // required because vsnprintf calls va_arg() // thus making reusage in the 2. vsnprintf call impossible va_list tmp_args; va_copy(tmp_args, args); size_t size = vsnprintf(NULL, 0, message, tmp_args) + 1; char *msg = new char[size]; va_end(tmp_args); vsnprintf(msg, size, message, args); // use clock_t and not time_t // we want the time the program uses based on the // cpu and not on a human readable clock. clock_t t; t = clock(); #pragma GCC diagnostic ignored "-Wformat-truncation" size_t buffer_size = snprintf(nullptr, 0, "%-10ld <%s> %s:%d: %s\n", /* ctime(&timer), */ t, loglevel2string(_level), function, line, msg) + 1; #pragma GCC diagnostic pop /* write complete message */ char *buffer = new char[buffer_size]; sprintf(buffer, "%-10ld <%s> %s:%d: %s\n", /* ctime(&timer), */ t, loglevel2string(_level), function, line, msg); switch (target) { case STDIO: { log_to_stdout(buffer); if (callback) { callback(cb_user_data, _level, function, line, message, args); } break; } case LOGFILE: { log_to_file(buffer); break; } case USER_DEFINED: { //logger.callback(_level, file, line, message, args); break; } default: break; } delete [] buffer; delete [] msg; } void Logger::log_to_stdout (const char* message) { fprintf(stdout, "%s", message); fflush(stdout); } void Logger::log_to_file (const char* message __attribute__((unused))) {} void Logger::set_log_level (enum TCAM_LOG_LEVEL l) { level = l; } enum TCAM_LOG_LEVEL Logger::get_log_level () const { return level; } void Logger::set_target (enum TCAM_LOG_TARGET t) { target = t; } enum TCAM_LOG_TARGET Logger::get_target () const { return target; } void Logger::set_log_file (const std::string& filename) { log_file = filename; } std::string Logger::get_log_file () const { return log_file; } void Logger::set_external_callback (logging_callback c, void* user_data) { callback = c; cb_user_data = user_data; } void Logger::delete_external_callback () { callback = nullptr; } void Logger::open_logfile () { if (!log_file.empty()) logfile = fopen(log_file.c_str(), "a+"); } void Logger::close_logfile () { if (logfile != NULL) { fclose(logfile); logfile = NULL; } } Logger& Logger::getInstance () { static Logger instance; return instance; } void tcam_set_logging_level (enum TCAM_LOG_LEVEL level) { Logger::getInstance().set_log_level(level); } enum TCAM_LOG_LEVEL tcam_get_logging_level () { return Logger::getInstance().get_log_level(); } void tcam_logging_init(enum TCAM_LOG_TARGET target, enum TCAM_LOG_LEVEL level) { tcam_set_logging_target(target); tcam_set_logging_level(level); } void tcam_set_logging_target (enum TCAM_LOG_TARGET target) { Logger::getInstance().set_target(target); } void tcam_set_logging_file (const char* logfile_name) { Logger::getInstance().set_log_file(logfile_name); } const char* tcam_get_logging_file () { return Logger::getInstance().get_log_file().c_str(); } void tcam_logging (enum TCAM_LOG_LEVEL level, const char* file, int line, const char* message, ...) { if (Logger::getInstance().get_log_level() > level || Logger::getInstance().get_log_level() == TCAM_LOG_OFF) { return; } va_list args; va_start(args, message); Logger::getInstance().log("", level, file, line, message, args); va_end(args); } void tcam_logging (const char* module, enum TCAM_LOG_LEVEL level, const char* function, int line, const char* message, ...) { if (Logger::getInstance().get_log_level() > level || Logger::getInstance().get_log_level() == TCAM_LOG_OFF) { return; } va_list args; va_start(args, message); Logger::getInstance().log(module, level, function, line, message, args); va_end(args); } <commit_msg>logging: Make timestamps human readable<commit_after>/* * Copyright 2014 The Imaging Source Europe GmbH * * 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 "logging.h" #include "version.h" #include <stdio.h> /* printf, fopen */ #include <stdarg.h> /* va_args */ #include <string.h> /* memcpy */ #include <time.h> /* time_t */ #include <vector> #include <chrono> static const char* loglevel2string (const enum TCAM_LOG_LEVEL level) { switch (level) { case TCAM_LOG_OFF: return "OFF"; case TCAM_LOG_TRACE: return "TRACE"; case TCAM_LOG_DEBUG: return "DEBUG"; case TCAM_LOG_INFO: return "INFO"; case TCAM_LOG_WARNING: return "WARNING"; case TCAM_LOG_ERROR: return "ERROR"; default: return NULL; } } static enum TCAM_LOG_LEVEL string2loglevel (const char* level) { if (strcmp("OFF", level) == 0) { return TCAM_LOG_OFF; } else if (strcmp("TRACE", level) == 0) { return TCAM_LOG_TRACE; } else if (strcmp("DEBUG", level) == 0) { return TCAM_LOG_DEBUG; } else if (strcmp("INFO", level) == 0) { return TCAM_LOG_INFO; } else if (strcmp("WARNING", level) == 0) { return TCAM_LOG_WARNING; } else if (strcmp("ERROR", level) == 0) { return TCAM_LOG_ERROR; } else return TCAM_LOG_ERROR; } Logger::Logger (): callback(nullptr), logfile(nullptr) { #ifndef TCAM_LOG_ENV_NAME #define TCAM_LOG_ENV_NAME "TCAM_LOG" #endif static const char* env_name = TCAM_LOG_ENV_NAME; load_default_settings(); char* log_def = getenv(env_name); if (log_def != nullptr) { level = string2loglevel(log_def); } if (level >= TCAM_LOG_DEBUG) { char b[1024]; sprintf(b, "\nThe following library versions are used:\n\tTcam:\t%s\n\tAravis:\t%s", get_version(), get_aravis_version()); va_list args; log("", TCAM_LOG_DEBUG, "Logger", __LINE__, b, args); } } void Logger::load_default_settings () { level = TCAM_LOG_OFF; target = STDIO; log_file = "/tmp/tis.log"; } void Logger::log (const char* module __attribute__((unused)), enum TCAM_LOG_LEVEL _level, const char* function, int line, const char* message, va_list args) { if (_level < level) { return; } // local copy of va_list // required because vsnprintf calls va_arg() // thus making reusage in the 2. vsnprintf call impossible va_list tmp_args; va_copy(tmp_args, args); size_t size = vsnprintf(NULL, 0, message, tmp_args) + 1; char *msg = new char[size]; va_end(tmp_args); vsnprintf(msg, size, message, args); // get current time auto now = std::chrono::system_clock::now(); auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000; std::time_t now_c = std::chrono::system_clock::to_time_t(now); std::tm now_tm = *std::localtime(&now_c); const size_t t_size = 80; std::vector<char> t0(t_size); std::vector<char> t(t_size); strftime(t0.data(), t_size -1, "%Y.%m.%dT%H:%M:%S:%%03u", &now_tm); snprintf(t.data(), t_size -1, t0.data(), ms); #pragma GCC diagnostic ignored "-Wformat-truncation" size_t buffer_size = snprintf(nullptr, 0, "%-30s <%s> %s:%d: %s\n", /* ctime(&timer), */ t.data(), loglevel2string(_level), function, line, msg) + 1; #pragma GCC diagnostic pop /* write complete message */ char *buffer = new char[buffer_size]; sprintf(buffer, "%-30s <%s> %s:%d: %s\n", /* ctime(&timer), */ t.data(), loglevel2string(_level), function, line, msg); switch (target) { case STDIO: { log_to_stdout(buffer); if (callback) { callback(cb_user_data, _level, function, line, message, args); } break; } case LOGFILE: { log_to_file(buffer); break; } case USER_DEFINED: { //logger.callback(_level, file, line, message, args); break; } default: break; } delete [] buffer; delete [] msg; } void Logger::log_to_stdout (const char* message) { fprintf(stdout, "%s", message); fflush(stdout); } void Logger::log_to_file (const char* message __attribute__((unused))) {} void Logger::set_log_level (enum TCAM_LOG_LEVEL l) { level = l; } enum TCAM_LOG_LEVEL Logger::get_log_level () const { return level; } void Logger::set_target (enum TCAM_LOG_TARGET t) { target = t; } enum TCAM_LOG_TARGET Logger::get_target () const { return target; } void Logger::set_log_file (const std::string& filename) { log_file = filename; } std::string Logger::get_log_file () const { return log_file; } void Logger::set_external_callback (logging_callback c, void* user_data) { callback = c; cb_user_data = user_data; } void Logger::delete_external_callback () { callback = nullptr; } void Logger::open_logfile () { if (!log_file.empty()) logfile = fopen(log_file.c_str(), "a+"); } void Logger::close_logfile () { if (logfile != NULL) { fclose(logfile); logfile = NULL; } } Logger& Logger::getInstance () { static Logger instance; return instance; } void tcam_set_logging_level (enum TCAM_LOG_LEVEL level) { Logger::getInstance().set_log_level(level); } enum TCAM_LOG_LEVEL tcam_get_logging_level () { return Logger::getInstance().get_log_level(); } void tcam_logging_init(enum TCAM_LOG_TARGET target, enum TCAM_LOG_LEVEL level) { tcam_set_logging_target(target); tcam_set_logging_level(level); } void tcam_set_logging_target (enum TCAM_LOG_TARGET target) { Logger::getInstance().set_target(target); } void tcam_set_logging_file (const char* logfile_name) { Logger::getInstance().set_log_file(logfile_name); } const char* tcam_get_logging_file () { return Logger::getInstance().get_log_file().c_str(); } void tcam_logging (enum TCAM_LOG_LEVEL level, const char* file, int line, const char* message, ...) { if (Logger::getInstance().get_log_level() > level || Logger::getInstance().get_log_level() == TCAM_LOG_OFF) { return; } va_list args; va_start(args, message); Logger::getInstance().log("", level, file, line, message, args); va_end(args); } void tcam_logging (const char* module, enum TCAM_LOG_LEVEL level, const char* function, int line, const char* message, ...) { if (Logger::getInstance().get_log_level() > level || Logger::getInstance().get_log_level() == TCAM_LOG_OFF) { return; } va_list args; va_start(args, message); Logger::getInstance().log(module, level, function, line, message, args); va_end(args); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // The Loki Library // Copyright (c) 2005 by Curtis Krauskopf // Copyright (c) 2005 by Peter Kuemmel // // Code covered by the MIT License // The authors make no representations about the suitability of this software // for any purpose. It is provided "as is" without express or implied warranty. //////////////////////////////////////////////////////////////////////////////// // This is an example of using the SetLongevity function for both // singletons and globally and locally defined dynamically allocated // objects. // // The program defines three classes: Example, Keyboard and LogClass. // // The purpose of the Example class is to send a message to cout // when an Example object is being destroyed. // // The Keyboard class is a singleton. // // The LogClass class is also a singleton. // // The pGlobal object is deleted using an adapter functor to // customize Example's destruction (see destGlobal()). // The glue that binds the adapter functor (above) with Loki's // SetLongevity function is: // // Loki::Private::Adapter<Example>exampleAdapter = {&destGlobal}; // SetLongevity(pGlobal, globalPriority, exampleAdapter); // // An alternative Loki-compatible way of destroying pGlobal (without // defining a global static functor) is to use the default parameter // on SetLongevity: // // Example *pLocal = new Example("Destroying local Example"); // SetLongevity(pLocal, localPriority); // // The parameters passed by the user on main define the longevity values // for (respectively): // 1) The global object // 2) The local object // 3) The Keyboard singleton // 4) The LogClass singleton // // Examples: // longevity 1 2 3 4 // longevity 40 30 20 10 // #include <iostream> #include <loki/Singleton.h> // for Loki::SingletonHolder using namespace std; // okay for small programs using namespace Loki; // okay for small programs // These globals allow the priority for each object to be // set in main() but used anywhere in the program. int globalPriority; int localPriority; int keyboardPriority; int logPriority; // A generic example class that stores and echoes a const char. // class Example { public: Example(const char * s) { msg = s; }; virtual ~Example() { echo(msg); } void echo(const char *s) { cout << s << endl; } protected: const char *msg; }; // A singleton Keyboard object derived from the Example class. // Its longevity is set by the user on the command line. // class Keyboard : public Example { public: Keyboard() : Example("Destroying Keyboard") { } } ; inline unsigned int GetLongevity(Keyboard *) { return keyboardPriority; } typedef SingletonHolder<Keyboard, CreateUsingNew, SingletonWithLongevity> keyboard; // A singleton LogClass object derived from the Example class. // Its longevity is set by the user on the command line. // class LogClass : public Example { public: LogClass() : Example("Destroying LogClass") { } } ; inline unsigned int GetLongevity(LogClass *) { return logPriority; } typedef SingletonHolder<LogClass, CreateUsingNew, SingletonWithLongevity> LogBook; // Instantiate a global Example object. It's not a singleton // but because it's instantiated with new (and therefore it isn't // automatically destroyed) it can use the SetLongevity template function. // Its longevity is determined by the user on the command line. // Example* pGlobal( new Example("Destroying global Example") ); // destGlobal() is called when the pGlobal object needs to be destroyed. static void destGlobal() { cout << "Going to delete pGlobal\n"; delete pGlobal; } void help(const char *s) { cout << "To use:\n"; cout << s << " par1 par2 par3 par4\n"; cout << " where each par is a number that represents the object's "; cout << " longevity:\n"; cout << " par1: global object\n"; cout << " par2: local object\n"; cout << " par3: keyboard singleton\n"; cout << " par4: LogBook singleton\n"; cout << "Example: " << s << " 1 2 3 4" << endl; } int main(int argc, char *argv[]) { if (argc != 5) { help(argv[0]); return 0; } globalPriority = atoi(argv[1]); localPriority = atoi(argv[2]); keyboardPriority = atoi(argv[3]); logPriority = atoi(argv[4]); // Use an adapter functor to tie the destGlobal function to the // destruction priority for pGlobal. Loki::Private::Adapter<Example> exampleAdapter = { &destGlobal }; SetLongevity(pGlobal, globalPriority, exampleAdapter); // Use Loki's private Deleter template function to destroy the // pLocal object for a user-defined priority. Example *pLocal = new Example("Destroying local Example"); SetLongevity<Example, void (*)(Example*)>(pLocal, localPriority, &Loki::Private::Deleter<Example>::Delete); // Make the global and local objects announce their presense. pGlobal->echo("pGlobal created during program initialization."); pLocal->echo("pLocal created after main() started."); // Instantiate both singletons by calling them... LogBook::Instance().echo("LogClass singleton instantiated"); keyboard::Instance().echo("Keyboard singleton instantiated"); return 0; } <commit_msg>swap names<commit_after>//////////////////////////////////////////////////////////////////////////////// // The Loki Library // Copyright (c) 2005 by Peter Kuemmel // // Code covered by the MIT License // The author make no representations about the suitability of this software // for any purpose. It is provided "as is" without express or implied warranty. //////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <loki/Singleton.h> struct L1 { L1(){std::cout << "create L1: " << this << "\n";} ~L1(){std::cout << "delete L1: " << this <<" \n";} }; struct L2 { L2(){std::cout << "create L2 \n";} ~L2(){std::cout << "delete L2 \n";} }; struct L3 { L3(){std::cout << "create L3 \n";} ~L3(){std::cout << "delete L3 \n";} }; int main() { Loki::SetLongevity (new L1, 1); Loki::SetLongevity<L1, void (*)(L1*)> (new L1, 1, Loki::Private::Deleter<L1>::Delete); Loki::SetLongevity<L1, Loki::Private::Deleter<L1>::Type> (new L1, 1, Loki::Private::Deleter<L1>::Delete); Loki::SetLongevity(new L2, 2); Loki::SetLongevity(new L1, 1); Loki::SetLongevity(new L3, 3); Loki::SetLongevity(new L1, 1); std::cout << "\n"; } <|endoftext|>
<commit_before>/* * Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved. */ #include <iostream> #include <sstream> #include "db/rt/Exception.h" #include "db/test/Test.h" #include "db/test/Tester.h" #include "db/test/TestRunner.h" #include "db/config/ConfigManager.h" #include "db/data/json/JsonWriter.h" using namespace std; using namespace db::rt; using namespace db::test; using namespace db::config; void runConfigManagerTest(TestRunner& tr) { tr.group("ConfigManager"); tr.test("init"); { DynamicObject expect; expect->setType(Map); ConfigManager cm; Config cfg; cfg[ConfigManager::ID] = "config"; cfg[ConfigManager::MERGE]->setType(Map); assert(cm.addConfig(cfg)); assertDynoCmp(cm.getConfig("config", true), cfg); assertDynoCmp(cm.getConfig("config", false), expect); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("init & clear"); { DynamicObject expect; expect->setType(Map); ConfigManager cm; Config cfg; cfg[ConfigManager::ID] = "config"; cfg[ConfigManager::MERGE]->setType(Map); assert(cm.addConfig(cfg)); cm.clear(); Config cfg2 = cm.getConfig("config"); assert(cfg2.isNull()); } tr.passIfException(); tr.test("1 config"); { DynamicObject expect; expect->setType(Map); expect["a"] = 0; ConfigManager cm; Config cfg; cfg[ConfigManager::ID] = "config"; cfg[ConfigManager::MERGE]["a"] = 0; assert(cm.addConfig(cfg)); assertNoException(); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("config change"); { ConfigManager cm; Config cfg; cfg[ConfigManager::ID] = "config"; cfg[ConfigManager::MERGE]["a"] = 0; assert(cm.addConfig(cfg)); DynamicObject a; a["a"] = 0; assertDynoCmp(cm.getConfig("config"), a); Config change = cm.getConfig("config", true); change[ConfigManager::MERGE]["a"] = 1; assert(cm.setConfig(change)); DynamicObject expect; expect["a"] = 1; assert(cm.getConfig("config") != a); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("add"); { DynamicObject expect; expect["a"] = 0; expect["b"] = 1; expect["c"] = 2; ConfigManager cm; Config a; a[ConfigManager::ID] = "config"; a[ConfigManager::MERGE]["a"] = 0; Config b; b[ConfigManager::ID] = "config"; b[ConfigManager::MERGE]["b"] = 1; Config c; c[ConfigManager::ID] = "config"; c[ConfigManager::MERGE]["c"] = 2; assert(cm.addConfig(a)); assertNoException(); assert(cm.addConfig(b)); assertNoException(); assert(cm.addConfig(c)); assertNoException(); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("bad remove"); { ConfigManager cm; assert(!cm.removeConfig("error")); assertException(); Exception::clearLast(); } tr.passIfNoException(); tr.test("remove"); { DynamicObject expect; expect["a"] = 0; expect["b"] = 1; expect["c"] = 2; ConfigManager cm; Config a; a[ConfigManager::ID] = "config a"; a[ConfigManager::GROUP] = "group"; a[ConfigManager::MERGE]["a"] = 0; Config b; b[ConfigManager::ID] = "config b"; b[ConfigManager::GROUP] = "group"; b[ConfigManager::MERGE]["b"] = 1; Config c; c[ConfigManager::ID] = "config c"; c[ConfigManager::GROUP] = "group"; c[ConfigManager::MERGE]["c"] = 2; assert(cm.addConfig(a)); assertNoException(); assert(cm.addConfig(b)); assertNoException(); assert(cm.addConfig(c)); assertNoException(); assertDynoCmp(cm.getConfig("group"), expect); DynamicObject expect2; expect2["a"] = 0; expect2["c"] = 2; assert(cm.removeConfig("config b")); assertDynoCmp(cm.getConfig("group"), expect2); } tr.passIfNoException(); tr.test("default value"); { ConfigManager cm; Config a; a[ConfigManager::ID] = "config a"; a[ConfigManager::MERGE] = 1; assert(cm.addConfig(a)); assertNoException(); Config b; b[ConfigManager::ID] = "config b"; b[ConfigManager::PARENT] = "config a"; b[ConfigManager::MERGE] = "__default__"; assert(cm.addConfig(b)); assertNoException(); DynamicObject expect; expect = 1; assertDynoCmp(cm.getConfig("config b"), expect); } tr.passIfNoException(); tr.test("default values"); { ConfigManager cm; Config cfga; cfga[ConfigManager::ID] = "config a"; Config& a = cfga[ConfigManager::MERGE]; a[0] = 10; a[1] = 11; a[2]["0"] = 120; a[2]["1"] = 121; assert(cm.addConfig(cfga)); assertNoException(); Config cfgb; cfgb[ConfigManager::ID] = "config b"; cfgb[ConfigManager::PARENT] = "config a"; Config& b = cfgb[ConfigManager::MERGE]; b[0] = "__default__"; b[1] = 21; b[2]["0"] = "__default__"; b[2]["1"] = 221; assert(cm.addConfig(cfgb)); assertNoException(); DynamicObject expect; expect[0] = 10; expect[1] = 21; expect[2]["0"] = 120; expect[2]["1"] = 221; assertDynoCmp(cm.getConfig("config b"), expect); } tr.passIfNoException(); #if 0 tr.test("user preferences"); { ConfigManager cm; // node // built in or loaded defaults DynamicObject nodec; nodec["node"]["host"] = "localhost"; nodec["node"]["port"] = 19100; nodec["node"]["modulePath"] = "/usr/lib/bitmunk/modules"; nodec["node"]["userModulePath"] = "~/.bitmunk/modules"; assert(cm.addConfig(nodec)); assertNoException(); // user // loaded defaults DynamicObject userc; userc["node"]["port"] = 19100; userc["node"]["comment"] = "My precious..."; assert(cm.addConfig(userc, ConfigManager::Custom)); assertNoException(); // user makes changes during runtime DynamicObject c = cm.getConfig(); c["node"]["port"] = 19200; c["node"]["userModulePath"] = "~/.bitmunk/modules:~/.bitmunk/modules-dev"; c["node"][ConfigManager::TMP]["not in changes"] = true; // get the changes from defaults to current config // serialize this to disk as needed DynamicObject changes; cm.getChanges(changes); // check it's correct DynamicObject expect; expect["node"]["port"] = 19200; expect["node"]["comment"] = "My precious..."; expect["node"]["userModulePath"] = "~/.bitmunk/modules:~/.bitmunk/modules-dev"; // NOTE: will not have TMP var assertDynoCmp(changes, expect); } tr.passIfNoException(); #endif tr.test("versioning"); { ConfigManager cm; cm.getVersions()->clear(); Config c; c[ConfigManager::ID] = "config"; assert(cm.addConfig(c)); assertNoException(); cm.addVersion("1"); assert(!cm.addConfig(c)); assertException(); Exception::clearLast(); c[ConfigManager::VERSION] = "2"; cm.removeConfig("config"); assert(!cm.addConfig(c)); assertException(); Exception::clearLast(); c[ConfigManager::VERSION] = "1"; assert(cm.addConfig(c)); assertNoException(); c[ConfigManager::VERSION] = "2"; cm.removeConfig("config"); cm.addVersion("2"); assert(cm.addConfig(c)); assertNoException(); } tr.passIfNoException(); tr.test("empty array & map"); { ConfigManager cm; DynamicObject a; a[ConfigManager::ID] = "config"; a[ConfigManager::MERGE][0]->setType(Array); a[ConfigManager::MERGE][1]->setType(Map); assert(cm.addConfig(a)); assertNoException(); DynamicObject expect; expect[0]->setType(Array); expect[1]->setType(Map); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.ungroup(); } class DbConfigTester : public db::test::Tester { public: DbConfigTester() { setName("config"); } /** * Run automatic unit tests. */ virtual int runAutomaticTests(TestRunner& tr) { runConfigManagerTest(tr); return 0; } /** * Runs interactive unit tests. */ virtual int runInteractiveTests(TestRunner& tr) { return 0; } }; #ifndef DB_TEST_NO_MAIN DB_TEST_MAIN(DbConfigTester) #endif <commit_msg>Fixed bugs in config test.<commit_after>/* * Copyright (c) 2007-2008 Digital Bazaar, Inc. All rights reserved. */ #include <iostream> #include <sstream> #include "db/rt/Exception.h" #include "db/test/Test.h" #include "db/test/Tester.h" #include "db/test/TestRunner.h" #include "db/config/ConfigManager.h" #include "db/data/json/JsonWriter.h" using namespace std; using namespace db::rt; using namespace db::test; using namespace db::config; void runConfigManagerTest(TestRunner& tr) { tr.group("ConfigManager"); tr.test("init"); { DynamicObject expect; expect->setType(Map); ConfigManager cm; Config cfg; cfg[ConfigManager::ID] = "config"; cfg[ConfigManager::MERGE]->setType(Map); assert(cm.addConfig(cfg)); assertDynoCmp(cm.getConfig("config", true), cfg); assertDynoCmp(cm.getConfig("config", false), expect); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("init & clear"); { DynamicObject expect; expect->setType(Map); ConfigManager cm; Config cfg; cfg[ConfigManager::ID] = "config"; cfg[ConfigManager::MERGE]->setType(Map); assert(cm.addConfig(cfg)); cm.clear(); Config cfg2 = cm.getConfig("config"); assert(cfg2.isNull()); } tr.passIfException(); tr.test("1 config"); { DynamicObject expect; expect->setType(Map); expect["a"] = 0; ConfigManager cm; Config cfg; cfg[ConfigManager::ID] = "config"; cfg[ConfigManager::MERGE]["a"] = 0; assert(cm.addConfig(cfg)); assertNoException(); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("config change"); { ConfigManager cm; Config cfg; cfg[ConfigManager::ID] = "config"; cfg[ConfigManager::MERGE]["a"] = 0; assert(cm.addConfig(cfg)); DynamicObject a; a["a"] = 0; assertDynoCmp(cm.getConfig("config"), a); Config change = cm.getConfig("config", true); change[ConfigManager::MERGE]["a"] = 1; assert(cm.setConfig(change)); DynamicObject expect; expect["a"] = 1; assert(cm.getConfig("config") != a); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("add"); { DynamicObject expect; expect["a"] = 0; expect["b"] = 1; expect["c"] = 2; ConfigManager cm; Config a; a[ConfigManager::ID] = "config"; a[ConfigManager::MERGE]["a"] = 0; Config b; b[ConfigManager::ID] = "config"; b[ConfigManager::MERGE]["b"] = 1; Config c; c[ConfigManager::ID] = "config"; c[ConfigManager::MERGE]["c"] = 2; assert(cm.addConfig(a)); assertNoException(); assert(cm.addConfig(b)); assertNoException(); assert(cm.addConfig(c)); assertNoException(); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.test("bad remove"); { ConfigManager cm; assert(!cm.removeConfig("error")); assertException(); Exception::clearLast(); } tr.passIfNoException(); tr.test("remove"); { DynamicObject expect; expect["a"] = 0; expect["b"] = 1; expect["c"] = 2; ConfigManager cm; Config a; a[ConfigManager::ID] = "config a"; a[ConfigManager::GROUP] = "group"; a[ConfigManager::MERGE]["a"] = 0; Config b; b[ConfigManager::ID] = "config b"; b[ConfigManager::GROUP] = "group"; b[ConfigManager::MERGE]["b"] = 1; Config c; c[ConfigManager::ID] = "config c"; c[ConfigManager::GROUP] = "group"; c[ConfigManager::MERGE]["c"] = 2; assert(cm.addConfig(a)); assertNoException(); assert(cm.addConfig(b)); assertNoException(); assert(cm.addConfig(c)); assertNoException(); assertDynoCmp(cm.getConfig("group"), expect); DynamicObject expect2; expect2["a"] = 0; expect2["c"] = 2; assert(cm.removeConfig("config b")); assertDynoCmp(cm.getConfig("group"), expect2); } tr.passIfNoException(); tr.test("default value"); { ConfigManager cm; Config a; a[ConfigManager::ID] = "config a"; a[ConfigManager::MERGE] = 1; assert(cm.addConfig(a)); assertNoException(); Config b; b[ConfigManager::ID] = "config b"; b[ConfigManager::PARENT] = "config a"; b[ConfigManager::MERGE] = ConfigManager::DEFAULT_VALUE; assert(cm.addConfig(b)); assertNoException(); DynamicObject expect; expect = 1; assertDynoCmp(cm.getConfig("config b"), expect); } tr.passIfNoException(); tr.test("default values"); { ConfigManager cm; Config cfga; cfga[ConfigManager::ID] = "config a"; Config& a = cfga[ConfigManager::MERGE]; a[0] = 10; a[1] = 11; a[2]["0"] = 120; a[2]["1"] = 121; assert(cm.addConfig(cfga)); assertNoException(); Config cfgb; cfgb[ConfigManager::ID] = "config b"; cfgb[ConfigManager::PARENT] = "config a"; Config& b = cfgb[ConfigManager::MERGE]; b[0] = ConfigManager::DEFAULT_VALUE; b[1] = 21; b[2]["0"] = ConfigManager::DEFAULT_VALUE; b[2]["1"] = 221; assert(cm.addConfig(cfgb)); assertNoException(); DynamicObject expect; expect[0] = 10; expect[1] = 21; expect[2]["0"] = 120; expect[2]["1"] = 221; assertDynoCmp(cm.getConfig("config b"), expect); } tr.passIfNoException(); #if 0 tr.test("user preferences"); { ConfigManager cm; // node // built in or loaded defaults DynamicObject nodec; nodec["node"]["host"] = "localhost"; nodec["node"]["port"] = 19100; nodec["node"]["modulePath"] = "/usr/lib/bitmunk/modules"; nodec["node"]["userModulePath"] = "~/.bitmunk/modules"; assert(cm.addConfig(nodec)); assertNoException(); // user // loaded defaults DynamicObject userc; userc["node"]["port"] = 19100; userc["node"]["comment"] = "My precious..."; assert(cm.addConfig(userc, ConfigManager::Custom)); assertNoException(); // user makes changes during runtime DynamicObject c = cm.getConfig(); c["node"]["port"] = 19200; c["node"]["userModulePath"] = "~/.bitmunk/modules:~/.bitmunk/modules-dev"; c["node"][ConfigManager::TMP]["not in changes"] = true; // get the changes from defaults to current config // serialize this to disk as needed DynamicObject changes; cm.getChanges(changes); // check it's correct DynamicObject expect; expect["node"]["port"] = 19200; expect["node"]["comment"] = "My precious..."; expect["node"]["userModulePath"] = "~/.bitmunk/modules:~/.bitmunk/modules-dev"; // NOTE: will not have TMP var assertDynoCmp(changes, expect); } tr.passIfNoException(); #endif tr.test("versioning"); { ConfigManager cm; cm.getVersions()->clear(); Config c; c[ConfigManager::ID] = "config"; assert(cm.addConfig(c)); assertNoException(); cm.addVersion("1"); assert(!cm.addConfig(c)); assertException(); Exception::clearLast(); c[ConfigManager::VERSION] = "2"; cm.removeConfig("config"); assert(!cm.addConfig(c)); assertException(); Exception::clearLast(); c[ConfigManager::VERSION] = "1"; assert(cm.addConfig(c)); assertNoException(); c[ConfigManager::VERSION] = "2"; cm.removeConfig("config"); cm.addVersion("2"); assert(cm.addConfig(c)); assertNoException(); } tr.passIfNoException(); tr.test("empty array & map"); { ConfigManager cm; DynamicObject a; a[ConfigManager::ID] = "config"; a[ConfigManager::MERGE][0]->setType(Array); a[ConfigManager::MERGE][1]->setType(Map); assert(cm.addConfig(a)); assertNoException(); DynamicObject expect; expect[0]->setType(Array); expect[1]->setType(Map); assertDynoCmp(cm.getConfig("config"), expect); } tr.passIfNoException(); tr.ungroup(); } class DbConfigTester : public db::test::Tester { public: DbConfigTester() { setName("config"); } /** * Run automatic unit tests. */ virtual int runAutomaticTests(TestRunner& tr) { runConfigManagerTest(tr); return 0; } /** * Runs interactive unit tests. */ virtual int runInteractiveTests(TestRunner& tr) { return 0; } }; #ifndef DB_TEST_NO_MAIN DB_TEST_MAIN(DbConfigTester) #endif <|endoftext|>
<commit_before>////////////////////////////////////////////////// // // ChCCollisionSystemBullet.cpp // // ------------------------------------------------ // Copyright:Alessandro Tasora / DeltaKnowledge // www.deltaknowledge.com // ------------------------------------------------ /////////////////////////////////////////////////// #include "ChCCollisionSystemBulletParallel.h" #include "collision/ChCModelBullet.h" #include "collision/ChCCollisionSystem.h" #include "physics/ChBody.h" #include "physics/ChProximityContainerBase.h" #include "chrono_parallel/ChParallelDefines.h" #include "chrono_parallel/ChLcpSystemDescriptorParallel.h" namespace chrono { namespace collision { /* void defaultChronoNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo) { btCollisionDispatcher::defaultNearCallback(collisionPair, dispatcher, dispatchInfo); if (broad_callback) broad_callback(collisionPair, dispatcher, dispatchInfo); } */ ChCollisionSystemBulletParallel::ChCollisionSystemBulletParallel(unsigned int max_objects, double scene_size) { // btDefaultCollisionConstructionInfo conf_info(...); ***TODO*** bt_collision_configuration = new btDefaultCollisionConfiguration(); bt_dispatcher = new btCollisionDispatcher(bt_collision_configuration); //***OLD*** btScalar sscene_size = (btScalar) scene_size; btVector3 worldAabbMin(-sscene_size, -sscene_size, -sscene_size); btVector3 worldAabbMax(sscene_size, sscene_size, sscene_size); bt_broadphase = new bt32BitAxisSweep3(worldAabbMin, worldAabbMax, max_objects, 0, true); // true for disabling raycast accelerator //***NEW*** //bt_broadphase = new btDbvtBroadphase(); bt_collision_world = new btCollisionWorld(bt_dispatcher, bt_broadphase, bt_collision_configuration); // custom collision for sphere-sphere case ***OBSOLETE*** //bt_dispatcher->registerCollisionCreateFunc(SPHERE_SHAPE_PROXYTYPE,SPHERE_SHAPE_PROXYTYPE,new btSphereSphereCollisionAlgorithm::CreateFunc); // register custom collision for GIMPACT mesh case too btGImpactCollisionAlgorithm::registerAlgorithm(bt_dispatcher); counter = 0; } ChCollisionSystemBulletParallel::~ChCollisionSystemBulletParallel() { if (bt_collision_world) delete bt_collision_world; if (bt_broadphase) delete bt_broadphase; if (bt_dispatcher) delete bt_dispatcher; if (bt_collision_configuration) delete bt_collision_configuration; } void ChCollisionSystemBulletParallel::Clear(void) { int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i); contactManifold->clearManifold(); } } void ChCollisionSystemBulletParallel::Add(ChCollisionModel* model) { if (((ChModelBullet*) model)->GetBulletModel()->getCollisionShape()) { model->SyncPosition(); btCollisionObject* collision_object = ((ChModelBullet*) model)->GetBulletModel(); collision_object->setCompanionId(counter); int family_group = ((ChModelBullet*) model)->GetFamilyGroup(); int family_mask = ((ChModelBullet*) model)->GetFamilyMask(); bt_collision_world->addCollisionObject(collision_object,family_group, family_mask); counter++; data_container->num_models++; } } void ChCollisionSystemBulletParallel::Remove(ChCollisionModel* model) { if (((ChModelBullet*) model)->GetBulletModel()->getCollisionShape()) { bt_collision_world->removeCollisionObject(((ChModelBullet*) model)->GetBulletModel()); } } void ChCollisionSystemBulletParallel::Run() { data_container->system_timer.start("collision_broad"); if (bt_collision_world) { bt_collision_world->performDiscreteCollisionDetection(); } data_container->system_timer.stop("collision_broad"); } void ChCollisionSystemBulletParallel::ReportContacts(ChContactContainerBase* mcontactcontainer) { data_container->system_timer.start("collision_narrow"); data_container->host_data.norm_rigid_rigid.clear(); data_container->host_data.cpta_rigid_rigid.clear(); data_container->host_data.cptb_rigid_rigid.clear(); data_container->host_data.dpth_rigid_rigid.clear(); data_container->host_data.bids_rigid_rigid.clear(); data_container->num_contacts = 0; mcontactcontainer->BeginAddContact(); ChCollisionInfo icontact; int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i); btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0()); btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1()); contactManifold->refreshContactPoints(obA->getWorldTransform(), obB->getWorldTransform()); icontact.modelA = (ChCollisionModel*) obA->getUserPointer(); icontact.modelB = (ChCollisionModel*) obB->getUserPointer(); double envelopeA = icontact.modelA->GetEnvelope(); double envelopeB = icontact.modelB->GetEnvelope(); double marginA = icontact.modelA->GetSafeMargin(); double marginB = icontact.modelB->GetSafeMargin(); bool activeA = ((ChBody*) (icontact.modelA->GetPhysicsItem()))->IsActive(); bool activeB = ((ChBody*) (icontact.modelB->GetPhysicsItem()))->IsActive(); if (activeA == 0 && activeB == 0) { continue; } // Execute custom broadphase callback, if any bool do_narrow_contactgeneration = true; if (this->broad_callback) do_narrow_contactgeneration = this->broad_callback->BroadCallback(icontact.modelA, icontact.modelB); if (do_narrow_contactgeneration) { int numContacts = contactManifold->getNumContacts(); for (int j = 0; j < numContacts; j++) { btManifoldPoint& pt = contactManifold->getContactPoint(j); if (pt.getDistance() < marginA + marginB) // to discard "too far" constraints (the Bullet engine also has its threshold) { btVector3 ptA = pt.getPositionWorldOnA(); btVector3 ptB = pt.getPositionWorldOnB(); icontact.vpA.Set(ptA.getX(), ptA.getY(), ptA.getZ()); icontact.vpB.Set(ptB.getX(), ptB.getY(), ptB.getZ()); icontact.vN.Set(-pt.m_normalWorldOnB.getX(), -pt.m_normalWorldOnB.getY(), -pt.m_normalWorldOnB.getZ()); icontact.vN.Normalize(); double ptdist = pt.getDistance(); icontact.vpA = icontact.vpA - icontact.vN * envelopeA; icontact.vpB = icontact.vpB + icontact.vN * envelopeB; //Required because parallel code expects the offset to be done before hand, this is for performance reasons later on. icontact.vpA = icontact.vpA - ((ChBody*) (icontact.modelA->GetPhysicsItem()))->GetPos(); icontact.vpB = icontact.vpB - ((ChBody*) (icontact.modelB->GetPhysicsItem()))->GetPos(); icontact.distance = ptdist + envelopeA + envelopeB; icontact.reaction_cache = pt.reactions_cache; // Execute some user custom callback, if any if (this->narrow_callback) this->narrow_callback->NarrowCallback(icontact); // Add to contact container mcontactcontainer->AddContact(icontact); data_container->host_data.norm_rigid_rigid.push_back(R3(icontact.vN.x, icontact.vN.y, icontact.vN.z)); data_container->host_data.cpta_rigid_rigid.push_back(R3(icontact.vpA.x, icontact.vpA.y, icontact.vpA.z)); data_container->host_data.cptb_rigid_rigid.push_back(R3(icontact.vpB.x, icontact.vpB.y, icontact.vpB.z)); data_container->host_data.dpth_rigid_rigid.push_back(icontact.distance); data_container->host_data.bids_rigid_rigid.push_back(I2(obA->getCompanionId(), obB->getCompanionId())); data_container->num_contacts++; } } } //you can un-comment out this line, and then all points are removed //contactManifold->clearManifold(); } mcontactcontainer->EndAddContact(); data_container->system_timer.stop("collision_narrow"); } } // END_OF_NAMESPACE____ } // END_OF_NAMESPACE____ <commit_msg>contact container does not need to be filled<commit_after>////////////////////////////////////////////////// // // ChCCollisionSystemBullet.cpp // // ------------------------------------------------ // Copyright:Alessandro Tasora / DeltaKnowledge // www.deltaknowledge.com // ------------------------------------------------ /////////////////////////////////////////////////// #include "ChCCollisionSystemBulletParallel.h" #include "collision/ChCModelBullet.h" #include "collision/ChCCollisionSystem.h" #include "physics/ChBody.h" #include "physics/ChProximityContainerBase.h" #include "chrono_parallel/ChParallelDefines.h" #include "chrono_parallel/ChLcpSystemDescriptorParallel.h" namespace chrono { namespace collision { /* void defaultChronoNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo) { btCollisionDispatcher::defaultNearCallback(collisionPair, dispatcher, dispatchInfo); if (broad_callback) broad_callback(collisionPair, dispatcher, dispatchInfo); } */ ChCollisionSystemBulletParallel::ChCollisionSystemBulletParallel(unsigned int max_objects, double scene_size) { // btDefaultCollisionConstructionInfo conf_info(...); ***TODO*** bt_collision_configuration = new btDefaultCollisionConfiguration(); bt_dispatcher = new btCollisionDispatcher(bt_collision_configuration); //***OLD*** btScalar sscene_size = (btScalar) scene_size; btVector3 worldAabbMin(-sscene_size, -sscene_size, -sscene_size); btVector3 worldAabbMax(sscene_size, sscene_size, sscene_size); bt_broadphase = new bt32BitAxisSweep3(worldAabbMin, worldAabbMax, max_objects, 0, true); // true for disabling raycast accelerator //***NEW*** //bt_broadphase = new btDbvtBroadphase(); bt_collision_world = new btCollisionWorld(bt_dispatcher, bt_broadphase, bt_collision_configuration); // custom collision for sphere-sphere case ***OBSOLETE*** //bt_dispatcher->registerCollisionCreateFunc(SPHERE_SHAPE_PROXYTYPE,SPHERE_SHAPE_PROXYTYPE,new btSphereSphereCollisionAlgorithm::CreateFunc); // register custom collision for GIMPACT mesh case too btGImpactCollisionAlgorithm::registerAlgorithm(bt_dispatcher); counter = 0; } ChCollisionSystemBulletParallel::~ChCollisionSystemBulletParallel() { if (bt_collision_world) delete bt_collision_world; if (bt_broadphase) delete bt_broadphase; if (bt_dispatcher) delete bt_dispatcher; if (bt_collision_configuration) delete bt_collision_configuration; } void ChCollisionSystemBulletParallel::Clear(void) { int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i); contactManifold->clearManifold(); } } void ChCollisionSystemBulletParallel::Add(ChCollisionModel* model) { if (((ChModelBullet*) model)->GetBulletModel()->getCollisionShape()) { model->SyncPosition(); btCollisionObject* collision_object = ((ChModelBullet*) model)->GetBulletModel(); collision_object->setCompanionId(counter); int family_group = ((ChModelBullet*) model)->GetFamilyGroup(); int family_mask = ((ChModelBullet*) model)->GetFamilyMask(); bt_collision_world->addCollisionObject(collision_object, family_group, family_mask); counter++; data_container->num_models++; } } void ChCollisionSystemBulletParallel::Remove(ChCollisionModel* model) { if (((ChModelBullet*) model)->GetBulletModel()->getCollisionShape()) { bt_collision_world->removeCollisionObject(((ChModelBullet*) model)->GetBulletModel()); } } void ChCollisionSystemBulletParallel::Run() { data_container->system_timer.start("collision_broad"); if (bt_collision_world) { bt_collision_world->performDiscreteCollisionDetection(); } data_container->system_timer.stop("collision_broad"); } void ChCollisionSystemBulletParallel::ReportContacts(ChContactContainerBase* mcontactcontainer) { data_container->system_timer.start("collision_narrow"); data_container->host_data.norm_rigid_rigid.clear(); data_container->host_data.cpta_rigid_rigid.clear(); data_container->host_data.cptb_rigid_rigid.clear(); data_container->host_data.dpth_rigid_rigid.clear(); data_container->host_data.bids_rigid_rigid.clear(); data_container->num_contacts = 0; //mcontactcontainer->BeginAddContact(); ChCollisionInfo icontact; int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i); btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0()); btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1()); contactManifold->refreshContactPoints(obA->getWorldTransform(), obB->getWorldTransform()); icontact.modelA = (ChCollisionModel*) obA->getUserPointer(); icontact.modelB = (ChCollisionModel*) obB->getUserPointer(); double envelopeA = icontact.modelA->GetEnvelope(); double envelopeB = icontact.modelB->GetEnvelope(); double marginA = icontact.modelA->GetSafeMargin(); double marginB = icontact.modelB->GetSafeMargin(); bool activeA = ((ChBody*) (icontact.modelA->GetPhysicsItem()))->IsActive(); bool activeB = ((ChBody*) (icontact.modelB->GetPhysicsItem()))->IsActive(); if (activeA == 0 && activeB == 0) { continue; } // Execute custom broadphase callback, if any bool do_narrow_contactgeneration = true; if (this->broad_callback) do_narrow_contactgeneration = this->broad_callback->BroadCallback(icontact.modelA, icontact.modelB); if (do_narrow_contactgeneration) { int numContacts = contactManifold->getNumContacts(); for (int j = 0; j < numContacts; j++) { btManifoldPoint& pt = contactManifold->getContactPoint(j); if (pt.getDistance() < marginA + marginB) // to discard "too far" constraints (the Bullet engine also has its threshold) { btVector3 ptA = pt.getPositionWorldOnA(); btVector3 ptB = pt.getPositionWorldOnB(); icontact.vpA.Set(ptA.getX(), ptA.getY(), ptA.getZ()); icontact.vpB.Set(ptB.getX(), ptB.getY(), ptB.getZ()); icontact.vN.Set(-pt.m_normalWorldOnB.getX(), -pt.m_normalWorldOnB.getY(), -pt.m_normalWorldOnB.getZ()); icontact.vN.Normalize(); double ptdist = pt.getDistance(); icontact.vpA = icontact.vpA - icontact.vN * envelopeA; icontact.vpB = icontact.vpB + icontact.vN * envelopeB; //Required because parallel code expects the offset to be done before hand, this is for performance reasons later on. icontact.vpA = icontact.vpA - ((ChBody*) (icontact.modelA->GetPhysicsItem()))->GetPos(); icontact.vpB = icontact.vpB - ((ChBody*) (icontact.modelB->GetPhysicsItem()))->GetPos(); icontact.distance = ptdist + envelopeA + envelopeB; icontact.reaction_cache = pt.reactions_cache; // Execute some user custom callback, if any if (this->narrow_callback) this->narrow_callback->NarrowCallback(icontact); // Add to contact container //mcontactcontainer->AddContact(icontact); data_container->host_data.norm_rigid_rigid.push_back(R3(icontact.vN.x, icontact.vN.y, icontact.vN.z)); data_container->host_data.cpta_rigid_rigid.push_back(R3(icontact.vpA.x, icontact.vpA.y, icontact.vpA.z)); data_container->host_data.cptb_rigid_rigid.push_back(R3(icontact.vpB.x, icontact.vpB.y, icontact.vpB.z)); data_container->host_data.dpth_rigid_rigid.push_back(icontact.distance); data_container->host_data.bids_rigid_rigid.push_back(I2(obA->getCompanionId(), obB->getCompanionId())); data_container->num_contacts++; } } } //you can un-comment out this line, and then all points are removed //contactManifold->clearManifold(); } //mcontactcontainer->EndAddContact(); data_container->system_timer.stop("collision_narrow"); } } // END_OF_NAMESPACE____ } // END_OF_NAMESPACE____ <|endoftext|>
<commit_before>#include <archie/utils/fused/find.h> #include <archie/utils/test.h> #include <type_traits> namespace fused = archie::utils::fused; void canUseFusedFind() { unsigned a = 0u; int b = 1; char c = '2'; double d = 3.0; unsigned e = 4u; auto x = fused::find<unsigned&>(a, b, c, d, e); auto y = fused::find<double&>(a, b, c, d, e); EXPECT_EQ(a, x); EXPECT_EQ(d, y); } template <typename Tp> using is_u = std::is_unsigned<std::decay_t<Tp>>; template <typename Tp> using is_s = std::is_signed<std::decay_t<Tp>>; void canUseFusedFindIf() { unsigned a = 0u; int b = 1; char c = '2'; double d = 3.0; unsigned e = 4u; auto x = fused::find_if<is_u>(a, b, c, d, e); auto y = fused::find_if<is_s>(a, b, c, d, e); EXPECT_EQ(a, x); EXPECT_EQ(b, y); } int main() { canUseFusedFind(); canUseFusedFindIf(); return 0; } <commit_msg>fused::find with rvalue<commit_after>#include <archie/utils/fused/find.h> #include <archie/utils/test.h> #include <type_traits> namespace fused = archie::utils::fused; void canUseFusedFind() { unsigned a = 0u; int b = 1; char c = '2'; double d = 3.0; unsigned e = 4u; auto x = fused::find<unsigned&>(a, b, c, d, e); auto y = fused::find<double&>(a, b, c, d, e); EXPECT_EQ(a, x); EXPECT_EQ(d, y); EXPECT_EQ(1, fused::find<int>(1, 2u, 3.0, '4')); EXPECT_EQ(2u, fused::find<unsigned>(1, 2u, 3.0, '4')); EXPECT_EQ(3.0, fused::find<double>(1, 2u, 3.0, '4')); EXPECT_EQ('4', fused::find<char>(1, 2u, 3.0, '4')); } template <typename Tp> using is_u = std::is_unsigned<std::decay_t<Tp>>; template <typename Tp> using is_s = std::is_signed<std::decay_t<Tp>>; void canUseFusedFindIf() { unsigned a = 0u; int b = 1; char c = '2'; double d = 3.0; unsigned e = 4u; auto x = fused::find_if<is_u>(a, b, c, d, e); auto y = fused::find_if<is_s>(a, b, c, d, e); EXPECT_EQ(a, x); EXPECT_EQ(b, y); } int main() { canUseFusedFind(); canUseFusedFindIf(); return 0; } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Mathematics (glm.g-truc.net) /// /// Copyright (c) 2005 - 2015 G-Truc Creation (www.g-truc.net) /// 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. /// /// Restrictions: /// By making use of the Software for military purposes, you choose to make /// a Bunny unhappy. /// /// 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 test/gtx/gtx_integer.cpp /// @date 2011-10-11 / 2014-11-25 /// @author Christophe Riccio /////////////////////////////////////////////////////////////////////////////////// #include <glm/exponential.hpp> #include <glm/gtc/epsilon.hpp> #include <glm/gtx/integer.hpp> #include <cstdio> /* int test_floor_log2() { int Error = 0; for(std::size_t i = 1; i < 1000000; ++i) { glm::uint A = glm::floor_log2(glm::uint(i)); glm::uint B = glm::uint(glm::floor(glm::log2(double(i)))); // Will fail with float, lack of accuracy Error += A == B ? 0 : 1; assert(!Error); } return Error; } */ int test_log2() { int Error = 0; for(std::size_t i = 1; i < 24; ++i) { glm::uint A = glm::log2(glm::uint(1 << i)); glm::uint B = glm::uint(glm::log2(double(1 << i))); //Error += glm::equalEpsilon(double(A), B, 1.0) ? 0 : 1; Error += glm::abs(double(A) - B) <= 24 ? 0 : 1; assert(!Error); printf("Log2(%d) Error: %d, %d\n", 1 << i, A, B); } printf("log2 error: %d\n", Error); return Error; } int test_nlz() { int Error = 0; for(glm::uint i = 1; i < glm::uint(33); ++i) Error += glm::nlz(i) == glm::uint(31u) - glm::findMSB(i) ? 0 : 1; //printf("%d, %d\n", glm::nlz(i), 31u - glm::findMSB(i)); return Error; } int main() { int Error = 0; Error += test_nlz(); // Error += test_floor_log2(); Error += test_log2(); return Error; } <commit_msg>test: Don't use 'Error:' or 'error:' in test output<commit_after>/////////////////////////////////////////////////////////////////////////////////// /// OpenGL Mathematics (glm.g-truc.net) /// /// Copyright (c) 2005 - 2015 G-Truc Creation (www.g-truc.net) /// 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. /// /// Restrictions: /// By making use of the Software for military purposes, you choose to make /// a Bunny unhappy. /// /// 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 test/gtx/gtx_integer.cpp /// @date 2011-10-11 / 2014-11-25 /// @author Christophe Riccio /////////////////////////////////////////////////////////////////////////////////// #include <glm/exponential.hpp> #include <glm/gtc/epsilon.hpp> #include <glm/gtx/integer.hpp> #include <cstdio> /* int test_floor_log2() { int Error = 0; for(std::size_t i = 1; i < 1000000; ++i) { glm::uint A = glm::floor_log2(glm::uint(i)); glm::uint B = glm::uint(glm::floor(glm::log2(double(i)))); // Will fail with float, lack of accuracy Error += A == B ? 0 : 1; assert(!Error); } return Error; } */ int test_log2() { int Error = 0; for(std::size_t i = 1; i < 24; ++i) { glm::uint A = glm::log2(glm::uint(1 << i)); glm::uint B = glm::uint(glm::log2(double(1 << i))); //Error += glm::equalEpsilon(double(A), B, 1.0) ? 0 : 1; Error += glm::abs(double(A) - B) <= 24 ? 0 : 1; assert(!Error); printf("Log2(%d) error A=%d, B=%d\n", 1 << i, A, B); } printf("log2 error=%d\n", Error); return Error; } int test_nlz() { int Error = 0; for(glm::uint i = 1; i < glm::uint(33); ++i) Error += glm::nlz(i) == glm::uint(31u) - glm::findMSB(i) ? 0 : 1; //printf("%d, %d\n", glm::nlz(i), 31u - glm::findMSB(i)); return Error; } int main() { int Error = 0; Error += test_nlz(); // Error += test_floor_log2(); Error += test_log2(); return Error; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LogarithmicRegressionCurveCalculator.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-09-17 13:26:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "LogarithmicRegressionCurveCalculator.hxx" #include "macros.hxx" #include "RegressionCalculationHelper.hxx" #ifndef INCLUDED_RTL_MATH_HXX #include <rtl/math.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif using namespace ::com::sun::star; using ::rtl::OUString; using ::rtl::OUStringBuffer; namespace chart { LogarithmicRegressionCurveCalculator::LogarithmicRegressionCurveCalculator() : m_fSlope( 0.0 ), m_fIntercept( 0.0 ), m_fCorrelationCoeffitient( 0.0 ) { ::rtl::math::setNan( & m_fSlope ); ::rtl::math::setNan( & m_fIntercept ); ::rtl::math::setNan( & m_fCorrelationCoeffitient ); } LogarithmicRegressionCurveCalculator::~LogarithmicRegressionCurveCalculator() {} // ____ XRegressionCurve ____ void SAL_CALL LogarithmicRegressionCurveCalculator::recalculateRegression( const uno::Sequence< double >& aXValues, const uno::Sequence< double >& aYValues ) throw (uno::RuntimeException) { RegressionCalculationHelper::tDoubleVectorPair aValues( RegressionCalculationHelper::cleanup( aXValues, aYValues, RegressionCalculationHelper::isValidAndXPositive())); const size_t nMax = aValues.first.size(); if( nMax == 0 ) { ::rtl::math::setNan( & m_fSlope ); ::rtl::math::setNan( & m_fIntercept ); ::rtl::math::setNan( & m_fCorrelationCoeffitient ); return; } double fAverageX = 0.0, fAverageY = 0.0; size_t i = 0; for( i = 0; i < nMax; ++i ) { fAverageX += log( aValues.first[i] ); fAverageY += aValues.second[i]; } const double fN = static_cast< double >( nMax ); fAverageX /= fN; fAverageY /= fN; double fQx = 0.0, fQy = 0.0, fQxy = 0.0; for( i = 0; i < nMax; ++i ) { double fDeltaX = log( aValues.first[i] ) - fAverageX; double fDeltaY = aValues.second[i] - fAverageY; fQx += fDeltaX * fDeltaX; fQy += fDeltaY * fDeltaY; fQxy += fDeltaX * fDeltaY; } m_fSlope = fQxy / fQx; m_fIntercept = fAverageY - m_fSlope * fAverageX; m_fCorrelationCoeffitient = fQxy / sqrt( fQx * fQy ); } double SAL_CALL LogarithmicRegressionCurveCalculator::getCurveValue( double x ) throw (lang::IllegalArgumentException, uno::RuntimeException) { double fResult; ::rtl::math::setNan( & fResult ); if( ! ( ::rtl::math::isNan( m_fSlope ) || ::rtl::math::isNan( m_fIntercept ))) { fResult = m_fSlope * log( x ) + m_fIntercept; } return fResult; } double SAL_CALL LogarithmicRegressionCurveCalculator::getCorrelationCoefficient() throw (uno::RuntimeException) { return m_fCorrelationCoeffitient; } OUString SAL_CALL LogarithmicRegressionCurveCalculator::getRepresentation() throw (uno::RuntimeException) { OUStringBuffer aBuf( C2U( "f(x) = " )); bool bHaveSlope = false; if( m_fSlope != 0.0 ) { if( ! ::rtl::math::approxEqual( m_fSlope, 1.0 )) { aBuf.append( NUMBER_TO_STR( m_fSlope )); aBuf.append( sal_Unicode( ' ' )); aBuf.append( sal_Unicode( 0x00b7 )); aBuf.append( sal_Unicode( ' ' )); } aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "log(x)" )); bHaveSlope = true; } if( m_fIntercept != 0.0 ) { if( ! bHaveSlope ) { aBuf.append( NUMBER_TO_STR( m_fIntercept )); } else { if( m_fIntercept < 0.0 ) { aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( " - " )); aBuf.append( NUMBER_TO_STR( fabs( m_fIntercept ))); } else { aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( " + " )); aBuf.append( NUMBER_TO_STR( m_fIntercept )); } } } return aBuf.makeStringAndClear(); } } // namespace chart <commit_msg>INTEGRATION: CWS chart17 (1.6.110); FILE MERGED 2007/10/23 15:02:36 bm 1.6.110.2: #i82891# improve rendering of regression curves using XRegressionCurveCalculator::getCurveValues() 2007/10/12 12:35:09 bm 1.6.110.1: #i7998# equations for regression curves<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: LogarithmicRegressionCurveCalculator.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: ihi $ $Date: 2007-11-23 12:05:55 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_chart2.hxx" #include "LogarithmicRegressionCurveCalculator.hxx" #include "macros.hxx" #include "RegressionCalculationHelper.hxx" #include <rtl/math.hxx> #include <rtl/ustrbuf.hxx> using namespace ::com::sun::star; using ::rtl::OUString; using ::rtl::OUStringBuffer; namespace chart { LogarithmicRegressionCurveCalculator::LogarithmicRegressionCurveCalculator() : m_fSlope( 0.0 ), m_fIntercept( 0.0 ) { ::rtl::math::setNan( & m_fSlope ); ::rtl::math::setNan( & m_fIntercept ); } LogarithmicRegressionCurveCalculator::~LogarithmicRegressionCurveCalculator() {} // ____ XRegressionCurve ____ void SAL_CALL LogarithmicRegressionCurveCalculator::recalculateRegression( const uno::Sequence< double >& aXValues, const uno::Sequence< double >& aYValues ) throw (uno::RuntimeException) { RegressionCalculationHelper::tDoubleVectorPair aValues( RegressionCalculationHelper::cleanup( aXValues, aYValues, RegressionCalculationHelper::isValidAndXPositive())); const size_t nMax = aValues.first.size(); if( nMax == 0 ) { ::rtl::math::setNan( & m_fSlope ); ::rtl::math::setNan( & m_fIntercept ); ::rtl::math::setNan( & m_fCorrelationCoeffitient ); return; } double fAverageX = 0.0, fAverageY = 0.0; size_t i = 0; for( i = 0; i < nMax; ++i ) { fAverageX += log( aValues.first[i] ); fAverageY += aValues.second[i]; } const double fN = static_cast< double >( nMax ); fAverageX /= fN; fAverageY /= fN; double fQx = 0.0, fQy = 0.0, fQxy = 0.0; for( i = 0; i < nMax; ++i ) { double fDeltaX = log( aValues.first[i] ) - fAverageX; double fDeltaY = aValues.second[i] - fAverageY; fQx += fDeltaX * fDeltaX; fQy += fDeltaY * fDeltaY; fQxy += fDeltaX * fDeltaY; } m_fSlope = fQxy / fQx; m_fIntercept = fAverageY - m_fSlope * fAverageX; m_fCorrelationCoeffitient = fQxy / sqrt( fQx * fQy ); } double SAL_CALL LogarithmicRegressionCurveCalculator::getCurveValue( double x ) throw (lang::IllegalArgumentException, uno::RuntimeException) { double fResult; ::rtl::math::setNan( & fResult ); if( ! ( ::rtl::math::isNan( m_fSlope ) || ::rtl::math::isNan( m_fIntercept ))) { fResult = m_fSlope * log( x ) + m_fIntercept; } return fResult; } uno::Sequence< geometry::RealPoint2D > SAL_CALL LogarithmicRegressionCurveCalculator::getCurveValues( double min, double max, ::sal_Int32 nPointCount, const uno::Reference< chart2::XScaling >& xScalingX, const uno::Reference< chart2::XScaling >& xScalingY, ::sal_Bool bMaySkipPointsInCalculation ) throw (lang::IllegalArgumentException, uno::RuntimeException) { if( bMaySkipPointsInCalculation && isLogarithmicScaling( xScalingX ) && isLinearScaling( xScalingY )) { // optimize result uno::Sequence< geometry::RealPoint2D > aResult( 2 ); aResult[0].X = min; aResult[0].Y = this->getCurveValue( min ); aResult[1].X = max; aResult[1].Y = this->getCurveValue( max ); return aResult; } return RegressionCurveCalculator::getCurveValues( min, max, nPointCount, xScalingX, xScalingY, bMaySkipPointsInCalculation ); } OUString LogarithmicRegressionCurveCalculator::ImplGetRepresentation( const uno::Reference< util::XNumberFormatter >& xNumFormatter, ::sal_Int32 nNumberFormatKey ) const { OUStringBuffer aBuf( C2U( "f(x) = " )); bool bHaveSlope = false; if( m_fSlope != 0.0 ) { if( ::rtl::math::approxEqual( fabs( m_fSlope ), 1.0 )) { if( m_fSlope < 0 ) aBuf.append( UC_MINUS_SIGN ); } else { aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fSlope )); aBuf.append( UC_SPACE ); } aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "log(x)" )); bHaveSlope = true; } if( bHaveSlope ) { if( m_fIntercept < 0.0 ) { aBuf.append( UC_SPACE ); aBuf.append( UC_MINUS_SIGN ); aBuf.append( UC_SPACE ); aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, fabs( m_fIntercept ))); } else if( m_fIntercept > 0.0 ) { aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( " + " )); aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fIntercept )); } } else { aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fIntercept )); } return aBuf.makeStringAndClear(); } } // namespace chart <|endoftext|>
<commit_before>// Copyright (c) 2006-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 <string> #include "app/l10n_util.h" #include "base/file_path.h" #include "base/gfx/rect.h" #include "chrome/browser/view_ids.h" #include "chrome/common/chrome_constants.h" #include "chrome/test/automation/automation_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/generated_resources.h" #include "net/base/net_util.h" #include "views/event.h" class BlockedPopupContainerInteractiveTest : public UITest { protected: BlockedPopupContainerInteractiveTest() { show_window_ = true; } virtual void SetUp() { UITest::SetUp(); browser_ = automation()->GetBrowserWindow(0); ASSERT_TRUE(browser_.get()); window_ = browser_->GetWindow(); ASSERT_TRUE(window_.get()); tab_ = browser_->GetTab(0); ASSERT_TRUE(tab_.get()); } void NavigateMainTabTo(const std::wstring& file_name) { FilePath filename(test_data_directory_); filename = filename.AppendASCII("constrained_files"); filename = filename.Append(FilePath::FromWStringHack(file_name)); ASSERT_TRUE(tab_->NavigateToURL(net::FilePathToFileURL(filename))); } void SimulateClickInCenterOf(const scoped_refptr<WindowProxy>& window) { gfx::Rect tab_view_bounds; ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds, true)); // Simulate a click of the actual link to force user_gesture to be // true; if we don't, the resulting popup will be constrained, which // isn't what we want to test. ASSERT_TRUE(window->SimulateOSClick(tab_view_bounds.CenterPoint(), views::Event::EF_LEFT_BUTTON_DOWN)); } scoped_refptr<BrowserProxy> browser_; scoped_refptr<WindowProxy> window_; scoped_refptr<TabProxy> tab_; }; TEST_F(BlockedPopupContainerInteractiveTest, TestOpenAndResizeTo) { NavigateMainTabTo(L"constrained_window_onload_resizeto.html"); SimulateClickInCenterOf(window_); ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000)); scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1)); ASSERT_TRUE(popup_browser != NULL); scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow()); ASSERT_TRUE(popup_window != NULL); // Make sure we were created with the correct width and height. gfx::Rect rect; bool is_timeout = false; ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout( VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout)); ASSERT_FALSE(is_timeout); #if !defined(OS_LINUX) // TODO(estade): This is a real failure; we create popups with the wrong size. // Fix it. Note: it appears that we are setting the window's bounds to 300,320 // instead of setting the content's bounds to 300,320. EXPECT_EQ(300, rect.width()); EXPECT_EQ(320, rect.height()); #endif SimulateClickInCenterOf(popup_window); // No idea how to wait here other then sleeping. This timeout used to be // lower, then we started hitting it before it was done. :( PlatformThread::Sleep(5000); // The actual content will be LESS than (200, 200) because resizeTo // deals with a window's outer{Width,Height} instead of its // inner{Width,Height}. is_timeout = false; ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout( VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout)); ASSERT_FALSE(is_timeout); EXPECT_LT(rect.height(), 200); #if defined(OS_LINUX) // On Linux we may run in an environment where there is no window frame. In // this case our width might be exactly 200. The height will still be less // because we have to show the location bar. EXPECT_LE(rect.width(), 200); #else EXPECT_LT(rect.width(), 200); #endif } // Helper function used to get the number of blocked popups out of the window // title. bool ParseCountOutOfTitle(const std::wstring& title, int* output) { // Since we will be reading the number of popup windows open by grabbing the // number out of the window title, and that format string is localized, we // need to find out the offset into that string. const wchar_t* placeholder = L"XXXX"; size_t offset = l10n_util::GetStringF(IDS_POPUPS_BLOCKED_COUNT, placeholder). find(placeholder); std::wstring number; while (offset < title.size() && iswdigit(title[offset])) { number += title[offset]; offset++; } return StringToInt(WideToUTF16(number), output); } // Tests that in the window.open() equivalent of a fork bomb, we stop building // windows. TEST_F(BlockedPopupContainerInteractiveTest, DontSpawnEndlessPopups) { NavigateMainTabTo(L"infinite_popups.html"); SimulateClickInCenterOf(window_); ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000)); scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1)); ASSERT_TRUE(popup_browser.get()); scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0)); ASSERT_TRUE(popup_tab.get()); // And now we spin, waiting to make sure that we don't spawn popup // windows endlessly. The current limit is 25, so allowing for possible race // conditions and one off errors, don't break out until we go over 30 popup // windows (in which case we are bork bork bork). const int kMaxPopupWindows = 30; int popup_window_count = 0; int new_popup_window_count = 0; int times_slept = 0; bool continuing = true; while (continuing && popup_window_count < kMaxPopupWindows) { ASSERT_TRUE(popup_tab->GetBlockedPopupCount(&new_popup_window_count)); if (new_popup_window_count == popup_window_count) { if (times_slept == 10) { continuing = false; } else { // Nothing intereseting is going on wait it out. PlatformThread::Sleep(automation::kSleepTime); times_slept++; } } else { times_slept = 0; } EXPECT_GE(new_popup_window_count, popup_window_count); EXPECT_LE(new_popup_window_count, kMaxPopupWindows); popup_window_count = new_popup_window_count; } } // Make sure that we refuse to close windows when a constrained popup is // displayed. TEST_F(BlockedPopupContainerInteractiveTest, WindowOpenWindowClosePopup) { NavigateMainTabTo(L"openclose_main.html"); SimulateClickInCenterOf(window_); ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000)); // Make sure we have a blocked popup notification scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1)); ASSERT_TRUE(popup_browser.get()); scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow()); ASSERT_TRUE(popup_window.get()); scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0)); ASSERT_TRUE(popup_tab.get()); ASSERT_TRUE(popup_tab->WaitForBlockedPopupCountToChangeTo(1, 1000)); // Ensure we didn't close the first popup window. ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 3000)); } TEST_F(BlockedPopupContainerInteractiveTest, BlockAlertFromBlockedPopup) { NavigateMainTabTo(L"block_alert.html"); // Wait for there to be an app modal dialog (and fail if it's shown). ASSERT_FALSE(automation()->WaitForAppModalDialog(4000)); // Ensure one browser window. int browser_window_count; ASSERT_TRUE(automation()->GetBrowserWindowCount(&browser_window_count)); ASSERT_EQ(1, browser_window_count); // Ensure one blocked popup window: the popup didn't escape. int popup_count = 0; ASSERT_TRUE(tab_->GetBlockedPopupCount(&popup_count)); ASSERT_EQ(1, popup_count); } TEST_F(BlockedPopupContainerInteractiveTest, ShowAlertFromNormalPopup) { NavigateMainTabTo(L"show_alert.html"); SimulateClickInCenterOf(window_); ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000)); scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1)); ASSERT_TRUE(popup_browser.get()); scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow()); ASSERT_TRUE(popup_window.get()); scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0)); ASSERT_TRUE(popup_tab.get()); SimulateClickInCenterOf(popup_window); // Wait for there to be an app modal dialog. ASSERT_TRUE(automation()->WaitForAppModalDialog(5000)); } // Make sure that window focus works while creating a popup window so that we // don't TEST_F(BlockedPopupContainerInteractiveTest, DontBreakOnBlur) { NavigateMainTabTo(L"window_blur_test.html"); SimulateClickInCenterOf(window_); // Wait for the popup window to open. ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000)); // We popup shouldn't be closed by the onblur handler. ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 1500)); } <commit_msg>Fix 2 failing BlockedPopupContainerInteractiveTests on Linux.<commit_after>// Copyright (c) 2006-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 <string> #include "app/l10n_util.h" #include "base/file_path.h" #include "base/gfx/rect.h" #include "chrome/browser/view_ids.h" #include "chrome/common/chrome_constants.h" #include "chrome/test/automation/automation_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/generated_resources.h" #include "net/base/net_util.h" #include "views/event.h" class BlockedPopupContainerInteractiveTest : public UITest { protected: BlockedPopupContainerInteractiveTest() { show_window_ = true; } virtual void SetUp() { UITest::SetUp(); browser_ = automation()->GetBrowserWindow(0); ASSERT_TRUE(browser_.get()); window_ = browser_->GetWindow(); ASSERT_TRUE(window_.get()); tab_ = browser_->GetTab(0); ASSERT_TRUE(tab_.get()); } void NavigateMainTabTo(const std::wstring& file_name) { FilePath filename(test_data_directory_); filename = filename.AppendASCII("constrained_files"); filename = filename.Append(FilePath::FromWStringHack(file_name)); ASSERT_TRUE(tab_->NavigateToURL(net::FilePathToFileURL(filename))); } void SimulateClickInCenterOf(const scoped_refptr<WindowProxy>& window) { gfx::Rect tab_view_bounds; ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds, true)); // Simulate a click of the actual link to force user_gesture to be // true; if we don't, the resulting popup will be constrained, which // isn't what we want to test. ASSERT_TRUE(window->SimulateOSClick(tab_view_bounds.CenterPoint(), views::Event::EF_LEFT_BUTTON_DOWN)); } scoped_refptr<BrowserProxy> browser_; scoped_refptr<WindowProxy> window_; scoped_refptr<TabProxy> tab_; }; TEST_F(BlockedPopupContainerInteractiveTest, TestOpenAndResizeTo) { NavigateMainTabTo(L"constrained_window_onload_resizeto.html"); SimulateClickInCenterOf(window_); ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000)); scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1)); ASSERT_TRUE(popup_browser != NULL); scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow()); ASSERT_TRUE(popup_window != NULL); // Make sure we were created with the correct width and height. gfx::Rect rect; bool is_timeout = false; ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout( VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout)); ASSERT_FALSE(is_timeout); #if !defined(OS_LINUX) // TODO(estade): This is a real failure; we create popups with the wrong size. // Fix it. Note: it appears that we are setting the window's bounds to 300,320 // instead of setting the content's bounds to 300,320. EXPECT_EQ(300, rect.width()); EXPECT_EQ(320, rect.height()); #endif #if defined(OS_LINUX) // It seems we have to wait a little bit for the widgets to spin up before // we can start clicking on them. PlatformThread::Sleep(500); #endif SimulateClickInCenterOf(popup_window); // No idea how to wait here other then sleeping. This timeout used to be // lower, then we started hitting it before it was done. :( PlatformThread::Sleep(5000); // The actual content will be LESS than (200, 200) because resizeTo // deals with a window's outer{Width,Height} instead of its // inner{Width,Height}. is_timeout = false; ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout( VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout)); ASSERT_FALSE(is_timeout); EXPECT_LT(rect.height(), 200); #if defined(OS_LINUX) // On Linux we may run in an environment where there is no window frame. In // this case our width might be exactly 200. The height will still be less // because we have to show the location bar. EXPECT_LE(rect.width(), 200); #else EXPECT_LT(rect.width(), 200); #endif } // Helper function used to get the number of blocked popups out of the window // title. bool ParseCountOutOfTitle(const std::wstring& title, int* output) { // Since we will be reading the number of popup windows open by grabbing the // number out of the window title, and that format string is localized, we // need to find out the offset into that string. const wchar_t* placeholder = L"XXXX"; size_t offset = l10n_util::GetStringF(IDS_POPUPS_BLOCKED_COUNT, placeholder). find(placeholder); std::wstring number; while (offset < title.size() && iswdigit(title[offset])) { number += title[offset]; offset++; } return StringToInt(WideToUTF16(number), output); } // Tests that in the window.open() equivalent of a fork bomb, we stop building // windows. TEST_F(BlockedPopupContainerInteractiveTest, DontSpawnEndlessPopups) { NavigateMainTabTo(L"infinite_popups.html"); SimulateClickInCenterOf(window_); ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000)); scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1)); ASSERT_TRUE(popup_browser.get()); scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0)); ASSERT_TRUE(popup_tab.get()); // And now we spin, waiting to make sure that we don't spawn popup // windows endlessly. The current limit is 25, so allowing for possible race // conditions and one off errors, don't break out until we go over 30 popup // windows (in which case we are bork bork bork). const int kMaxPopupWindows = 30; int popup_window_count = 0; int new_popup_window_count = 0; int times_slept = 0; bool continuing = true; while (continuing && popup_window_count < kMaxPopupWindows) { ASSERT_TRUE(popup_tab->GetBlockedPopupCount(&new_popup_window_count)); if (new_popup_window_count == popup_window_count) { if (times_slept == 10) { continuing = false; } else { // Nothing intereseting is going on wait it out. PlatformThread::Sleep(automation::kSleepTime); times_slept++; } } else { times_slept = 0; } EXPECT_GE(new_popup_window_count, popup_window_count); EXPECT_LE(new_popup_window_count, kMaxPopupWindows); popup_window_count = new_popup_window_count; } } // Make sure that we refuse to close windows when a constrained popup is // displayed. TEST_F(BlockedPopupContainerInteractiveTest, WindowOpenWindowClosePopup) { NavigateMainTabTo(L"openclose_main.html"); SimulateClickInCenterOf(window_); ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000)); // Make sure we have a blocked popup notification scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1)); ASSERT_TRUE(popup_browser.get()); scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow()); ASSERT_TRUE(popup_window.get()); scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0)); ASSERT_TRUE(popup_tab.get()); ASSERT_TRUE(popup_tab->WaitForBlockedPopupCountToChangeTo(1, 1000)); // Ensure we didn't close the first popup window. ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 3000)); } TEST_F(BlockedPopupContainerInteractiveTest, BlockAlertFromBlockedPopup) { NavigateMainTabTo(L"block_alert.html"); // Wait for there to be an app modal dialog (and fail if it's shown). ASSERT_FALSE(automation()->WaitForAppModalDialog(4000)); // Ensure one browser window. int browser_window_count; ASSERT_TRUE(automation()->GetBrowserWindowCount(&browser_window_count)); ASSERT_EQ(1, browser_window_count); // Ensure one blocked popup window: the popup didn't escape. int popup_count = 0; ASSERT_TRUE(tab_->GetBlockedPopupCount(&popup_count)); ASSERT_EQ(1, popup_count); } TEST_F(BlockedPopupContainerInteractiveTest, ShowAlertFromNormalPopup) { NavigateMainTabTo(L"show_alert.html"); SimulateClickInCenterOf(window_); ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000)); scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1)); ASSERT_TRUE(popup_browser.get()); scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow()); ASSERT_TRUE(popup_window.get()); scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0)); ASSERT_TRUE(popup_tab.get()); #if defined(OS_LINUX) // It seems we have to wait a little bit for the widgets to spin up before // we can start clicking on them. PlatformThread::Sleep(500); #endif SimulateClickInCenterOf(popup_window); // Wait for there to be an app modal dialog. ASSERT_TRUE(automation()->WaitForAppModalDialog(5000)); } // Make sure that window focus works while creating a popup window so that we // don't TEST_F(BlockedPopupContainerInteractiveTest, DontBreakOnBlur) { NavigateMainTabTo(L"window_blur_test.html"); SimulateClickInCenterOf(window_); // Wait for the popup window to open. ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000)); // We popup shouldn't be closed by the onblur handler. ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 1500)); } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/task_manager/task_manager.h" #include "chrome/browser/task_manager/task_manager_browsertest_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/browser_window.h" #include "extensions/common/switches.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Processes) { ASSERT_TRUE(RunExtensionTest("processes/api")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ProcessesVsTaskManager) { // Ensure task manager is not yet updating TaskManagerModel* model = TaskManager::GetInstance()->model(); EXPECT_EQ(0, model->update_requests_); EXPECT_EQ(TaskManagerModel::IDLE, model->update_state_); // Load extension that adds listener in background page ExtensionTestMessageListener listener("ready", false); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("processes").AppendASCII("onupdated"))); ASSERT_TRUE(listener.WaitUntilSatisfied()); // Ensure the task manager has started updating EXPECT_EQ(1, model->update_requests_); EXPECT_EQ(TaskManagerModel::TASK_PENDING, model->update_state_); // Now show the task manager and wait for it to be ready chrome::ShowTaskManager(browser()); EXPECT_EQ(2, model->update_requests_); EXPECT_EQ(TaskManagerModel::TASK_PENDING, model->update_state_); // Unload the extension and check that listener count decreases UnloadExtension(last_loaded_extension_id()); EXPECT_EQ(1, model->update_requests_); } <commit_msg>Disable flaky test: ExtensionApiTest.Processes<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_test_message_listener.h" #include "chrome/browser/task_manager/task_manager.h" #include "chrome/browser/task_manager/task_manager_browsertest_util.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/browser/ui/browser_window.h" #include "extensions/common/switches.h" // Test is flaky: http://crbug.com/346990 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Processes) { ASSERT_TRUE(RunExtensionTest("processes/api")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ProcessesVsTaskManager) { // Ensure task manager is not yet updating TaskManagerModel* model = TaskManager::GetInstance()->model(); EXPECT_EQ(0, model->update_requests_); EXPECT_EQ(TaskManagerModel::IDLE, model->update_state_); // Load extension that adds listener in background page ExtensionTestMessageListener listener("ready", false); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("processes").AppendASCII("onupdated"))); ASSERT_TRUE(listener.WaitUntilSatisfied()); // Ensure the task manager has started updating EXPECT_EQ(1, model->update_requests_); EXPECT_EQ(TaskManagerModel::TASK_PENDING, model->update_state_); // Now show the task manager and wait for it to be ready chrome::ShowTaskManager(browser()); EXPECT_EQ(2, model->update_requests_); EXPECT_EQ(TaskManagerModel::TASK_PENDING, model->update_state_); // Unload the extension and check that listener count decreases UnloadExtension(last_loaded_extension_id()); EXPECT_EQ(1, model->update_requests_); } <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "base/process.h" #include "base/scoped_ptr.h" #include "chrome/browser/renderer_host/audio_renderer_host.h" #include "testing/gtest/include/gtest/gtest.h" class AudioRendererHostTest : public testing::Test { protected: virtual void SetUp() { // Create a message loop so AudioRendererHost can use it. message_loop_.reset(new MessageLoop(MessageLoop::TYPE_IO)); host_ = new AudioRendererHost(message_loop_.get()); } virtual void TearDown() { // This task post a task to message_loop_ to do internal destruction on // message_loop_. host_->Destroy(); // We need to continue running message_loop_ to complete all destructions. message_loop_->RunAllPending(); } scoped_refptr<AudioRendererHost> host_; scoped_ptr<MessageLoop> message_loop_; }; TEST_F(AudioRendererHostTest, NoTest) { // TODO(hclam): come up with useful tests. } <commit_msg>Unit tests for AudioRendererHost TEST=AudioRendererHostTest.CreateStream AudioRendererHostTest.MockStreamDataConversation BUG=16035<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/message_loop.h" #include "base/process.h" #include "base/process_util.h" #include "base/scoped_ptr.h" #include "chrome/browser/renderer_host/audio_renderer_host.h" #include "chrome/common/render_messages.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Return; using ::testing::SetArgumentPointee; namespace { const int kInvalidId = -1; const int kProcessId = 100; const int kRouteId = 200; const int kBufferCapacity = 65536; const int kPacketSize = 16384; } // namespace class MockAudioRendererHost : public AudioRendererHost { public: MockAudioRendererHost(MessageLoop* loop) : AudioRendererHost(loop) { } // A list of mock methods. MOCK_METHOD4(OnRequestPacket, void(int routing_id, int stream_id, size_t bytes_in_buffer, int64 message_timestamp)); MOCK_METHOD3(OnStreamCreated, void(int routing_id, int stream_id, int length)); MOCK_METHOD4(OnStreamStateChanged, void(int routing_id, int stream_id, AudioOutputStream::State state, int info)); MOCK_METHOD4(OnStreamVolume, void(int routing_id, int stream_id, double left, double right)); base::SharedMemory* shared_memory() { return shared_memory_.get(); } protected: // This method is used to dispatch IPC messages to the renderer. We intercept // these messages here and dispatch to our mock methods to verify the // conversation between this object and the renderer. virtual void Send(IPC::Message* message) { CHECK(message); // In this method we dispatch the messages to the according handlers as if // we are the renderer. bool handled = true; IPC_BEGIN_MESSAGE_MAP(MockAudioRendererHost, *message) IPC_MESSAGE_HANDLER(ViewMsg_RequestAudioPacket, OnRequestPacket) IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamCreated, OnStreamCreated) IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamStateChanged, OnStreamStateChanged) IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamVolume, OnStreamVolume) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() EXPECT_TRUE(handled); delete message; } private: // These handler methods do minimal things and delegate to the mock methods. void OnRequestPacket(const IPC::Message& msg, int stream_id, size_t bytes_in_buffer, int64 message_timestamp) { OnRequestPacket(msg.routing_id(), stream_id, bytes_in_buffer, message_timestamp); } void OnStreamCreated(const IPC::Message& msg, int stream_id, base::SharedMemoryHandle handle, int length) { // Maps the shared memory. shared_memory_.reset(new base::SharedMemory(handle, true)); CHECK(shared_memory_->Map(length)); CHECK(shared_memory_->memory()); // And then delegate the call to the mock method. OnStreamCreated(msg.routing_id(), stream_id, length); } void OnStreamStateChanged(const IPC::Message& msg, int stream_id, AudioOutputStream::State state, int info) { OnStreamStateChanged(msg.routing_id(), stream_id, state, info); } void OnStreamVolume(const IPC::Message& msg, int stream_id, double left, double right) { OnStreamVolume(msg.routing_id(), stream_id, left, right); } scoped_ptr<base::SharedMemory> shared_memory_; DISALLOW_COPY_AND_ASSIGN(MockAudioRendererHost); }; class AudioRendererHostTest : public testing::Test { public: AudioRendererHostTest() : current_stream_id_(0) { } protected: virtual void SetUp() { // Create a message loop so AudioRendererHost can use it. message_loop_.reset(new MessageLoop(MessageLoop::TYPE_IO)); host_ = new MockAudioRendererHost(message_loop_.get()); CHECK(host_); } virtual void TearDown() { // This task post a task to message_loop_ to do internal destruction on // message_loop_. host_->Destroy(); // We need to continue running message_loop_ to complete all destructions. message_loop_->RunAllPending(); } AudioRendererHost::IPCAudioSource* CreateAudioStream( AudioManager::Format format) { InSequence s; // 1. We will first receive a OnStreamCreated() signal. EXPECT_CALL(*host_, OnStreamCreated(kRouteId, current_stream_id_, kPacketSize)); // 2. First packet request will arrive. This request is sent by // IPCAudioSource::CreateIPCAudioSource to start buffering. EXPECT_CALL(*host_, OnRequestPacket(kRouteId, current_stream_id_, 0, _)); AudioRendererHost::IPCAudioSource* source = AudioRendererHost::IPCAudioSource::CreateIPCAudioSource( host_, kProcessId, kRouteId, current_stream_id_, base::GetCurrentProcessHandle(), format, 2, AudioManager::kAudioCDSampleRate, 16, kPacketSize, kBufferCapacity); EXPECT_TRUE(source); EXPECT_EQ(kProcessId, source->process_id()); EXPECT_EQ(kRouteId, source->route_id()); EXPECT_EQ(current_stream_id_, source->stream_id()); return source; } AudioRendererHost::IPCAudioSource* CreateRealStream() { return CreateAudioStream(AudioManager::AUDIO_PCM_LINEAR); } AudioRendererHost::IPCAudioSource* CreateMockStream() { return CreateAudioStream(AudioManager::AUDIO_MOCK); } int current_stream_id_; scoped_refptr<MockAudioRendererHost> host_; scoped_ptr<MessageLoop> message_loop_; private: DISALLOW_COPY_AND_ASSIGN(AudioRendererHostTest); }; // Audio output stream only works stably on windows. Also there's no mock // audio output streams for mac and linux. // TODO(hclam): make these tests work on mac and linux. #if defined(OS_WIN) TEST_F(AudioRendererHostTest, CreateMockStream) { scoped_ptr<AudioRendererHost::IPCAudioSource> source(CreateMockStream()); } TEST_F(AudioRendererHostTest, MockStreamDataConversation) { scoped_ptr<AudioRendererHost::IPCAudioSource> source(CreateMockStream()); // We will receive packet requests until the buffer is full. We first send // three packets of 16KB, then we send packets of 1KB until the buffer is // full. Then there will no more packet requests. EXPECT_CALL(*host_, OnRequestPacket(kRouteId, current_stream_id_, kPacketSize, _)); EXPECT_CALL(*host_, OnRequestPacket(kRouteId, current_stream_id_, 2 * kPacketSize, _)); for (int size = 3 * kPacketSize; size < kBufferCapacity; size += 1024) { EXPECT_CALL(*host_, OnRequestPacket(kRouteId, current_stream_id_, size, _)); } source->NotifyPacketReady(kPacketSize); source->NotifyPacketReady(kPacketSize); source->NotifyPacketReady(kPacketSize); for (int size = 0; size < kPacketSize; size += 1024) { source->NotifyPacketReady(1024); } } #endif <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/search_engines/ui_thread_search_terms_data.h" #include "base/command_line.h" #include "base/logging.h" #include "base/metrics/field_trial.h" #include "base/prefs/pref_service.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/google/google_brand.h" #include "chrome/browser/google/google_profile_helper.h" #include "chrome/browser/omnibox/omnibox_field_trial.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/instant_service.h" #include "chrome/browser/search/instant_service_factory.h" #include "chrome/browser/search/search.h" #include "chrome/browser/sync/glue/device_info.h" #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/pref_names.h" #include "components/google/core/browser/google_util.h" #include "components/search/search.h" #include "content/public/browser/browser_thread.h" #include "sync/protocol/sync.pb.h" #include "url/gurl.h" #if defined(ENABLE_RLZ) #include "chrome/browser/rlz/rlz.h" #endif using content::BrowserThread; // static std::string* UIThreadSearchTermsData::google_base_url_ = NULL; UIThreadSearchTermsData::UIThreadSearchTermsData(Profile* profile) : profile_(profile) { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); } std::string UIThreadSearchTermsData::GoogleBaseURLValue() const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); if (google_base_url_) return *google_base_url_; GURL base_url(google_util::CommandLineGoogleBaseURL()); if (base_url.is_valid()) return base_url.spec(); return profile_ ? google_profile_helper::GetGoogleHomePageURL(profile_).spec() : SearchTermsData::GoogleBaseURLValue(); } std::string UIThreadSearchTermsData::GetApplicationLocale() const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); return g_browser_process->GetApplicationLocale(); } // Android implementations are in ui_thread_search_terms_data_android.cc. #if !defined(OS_ANDROID) base::string16 UIThreadSearchTermsData::GetRlzParameterValue( bool from_app_list) const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); base::string16 rlz_string; #if defined(ENABLE_RLZ) // For organic brandcodes do not use rlz at all. Empty brandcode usually // means a chromium install. This is ok. std::string brand; if (google_brand::GetBrand(&brand) && !brand.empty() && !google_brand::IsOrganic(brand)) { // This call will return false the first time(s) it is called until the // value has been cached. This normally would mean that at most one omnibox // search might not send the RLZ data but this is not really a problem. rlz_lib::AccessPoint access_point = RLZTracker::ChromeOmnibox(); #if !defined(OS_IOS) if (from_app_list) access_point = RLZTracker::ChromeAppList(); #endif RLZTracker::GetAccessPointRlz(access_point, &rlz_string); } #endif return rlz_string; } // We can enable this on non-Android if other platforms ever want a non-empty // search client string. There is already a unit test in place for Android // called TemplateURLTest::SearchClient. std::string UIThreadSearchTermsData::GetSearchClient() const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); return std::string(); } #endif std::string UIThreadSearchTermsData::GetSuggestClient() const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); #if defined(OS_ANDROID) sync_pb::SyncEnums::DeviceType device_type = browser_sync::DeviceInfo::GetLocalDeviceType(); return device_type == sync_pb::SyncEnums_DeviceType_TYPE_PHONE ? "chrome" : "chrome-omni"; #else return chrome::IsInstantExtendedAPIEnabled() ? "chrome-omni" : "chrome"; #endif } std::string UIThreadSearchTermsData::GetSuggestRequestIdentifier() const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); #if defined(OS_ANDROID) sync_pb::SyncEnums::DeviceType device_type = browser_sync::DeviceInfo::GetLocalDeviceType(); if (device_type == sync_pb::SyncEnums_DeviceType_TYPE_PHONE) { return OmniboxFieldTrial::EnableAnswersInSuggest() ? "chrome-mobile-ext-ansg" : "chrome-mobile-ext"; } return OmniboxFieldTrial::EnableAnswersInSuggest() ? "chrome-ext-ansg" : "chrome-ext"; #else return "chrome-ext"; #endif } bool UIThreadSearchTermsData::EnableAnswersInSuggest() const { return OmniboxFieldTrial::EnableAnswersInSuggest(); } bool UIThreadSearchTermsData::IsShowingSearchTermsOnSearchResultsPages() const { return chrome::IsInstantExtendedAPIEnabled() && chrome::IsQueryExtractionEnabled(); } std::string UIThreadSearchTermsData::InstantExtendedEnabledParam( bool for_search) const { return chrome::InstantExtendedEnabledParam(for_search); } std::string UIThreadSearchTermsData::ForceInstantResultsParam( bool for_prerender) const { return chrome::ForceInstantResultsParam(for_prerender); } int UIThreadSearchTermsData::OmniboxStartMargin() const { InstantService* instant_service = InstantServiceFactory::GetForProfile(profile_); // Android and iOS have no InstantService. return instant_service ? instant_service->omnibox_start_margin() : chrome::kDisableStartMargin; } std::string UIThreadSearchTermsData::NTPIsThemedParam() const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); #if defined(ENABLE_THEMES) if (!chrome::IsInstantExtendedAPIEnabled()) return std::string(); // TODO(dhollowa): Determine fraction of custom themes that don't affect the // NTP background and/or color. ThemeService* theme_service = ThemeServiceFactory::GetForProfile(profile_); // NTP is considered themed if the theme is not default and not native (GTK+). if (theme_service && !theme_service->UsingDefaultTheme() && !theme_service->UsingSystemTheme()) return "es_th=1&"; #endif // defined(ENABLE_THEMES) return std::string(); } // It's acutally OK to call this method on any thread, but it's currently placed // in UIThreadSearchTermsData since SearchTermsData cannot depend on // VersionInfo. std::string UIThreadSearchTermsData::GoogleImageSearchSource() const { chrome::VersionInfo version_info; if (version_info.is_valid()) { std::string version(version_info.Name() + " " + version_info.Version()); if (version_info.IsOfficialBuild()) version += " (Official)"; version += " " + version_info.OSType(); std::string modifier(version_info.GetVersionStringModifier()); if (!modifier.empty()) version += " " + modifier; return version; } return "unknown"; } // static void UIThreadSearchTermsData::SetGoogleBaseURL(const std::string& base_url) { delete google_base_url_; google_base_url_ = base_url.empty() ? NULL : new std::string(base_url); } <commit_msg>[AiS] widen AiS to iOS.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/search_engines/ui_thread_search_terms_data.h" #include "base/command_line.h" #include "base/logging.h" #include "base/metrics/field_trial.h" #include "base/prefs/pref_service.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/google/google_brand.h" #include "chrome/browser/google/google_profile_helper.h" #include "chrome/browser/omnibox/omnibox_field_trial.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/instant_service.h" #include "chrome/browser/search/instant_service_factory.h" #include "chrome/browser/search/search.h" #include "chrome/browser/sync/glue/device_info.h" #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/pref_names.h" #include "components/google/core/browser/google_util.h" #include "components/search/search.h" #include "content/public/browser/browser_thread.h" #include "sync/protocol/sync.pb.h" #include "url/gurl.h" #if defined(ENABLE_RLZ) #include "chrome/browser/rlz/rlz.h" #endif using content::BrowserThread; // static std::string* UIThreadSearchTermsData::google_base_url_ = NULL; UIThreadSearchTermsData::UIThreadSearchTermsData(Profile* profile) : profile_(profile) { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); } std::string UIThreadSearchTermsData::GoogleBaseURLValue() const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); if (google_base_url_) return *google_base_url_; GURL base_url(google_util::CommandLineGoogleBaseURL()); if (base_url.is_valid()) return base_url.spec(); return profile_ ? google_profile_helper::GetGoogleHomePageURL(profile_).spec() : SearchTermsData::GoogleBaseURLValue(); } std::string UIThreadSearchTermsData::GetApplicationLocale() const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); return g_browser_process->GetApplicationLocale(); } // Android implementations are in ui_thread_search_terms_data_android.cc. #if !defined(OS_ANDROID) base::string16 UIThreadSearchTermsData::GetRlzParameterValue( bool from_app_list) const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); base::string16 rlz_string; #if defined(ENABLE_RLZ) // For organic brandcodes do not use rlz at all. Empty brandcode usually // means a chromium install. This is ok. std::string brand; if (google_brand::GetBrand(&brand) && !brand.empty() && !google_brand::IsOrganic(brand)) { // This call will return false the first time(s) it is called until the // value has been cached. This normally would mean that at most one omnibox // search might not send the RLZ data but this is not really a problem. rlz_lib::AccessPoint access_point = RLZTracker::ChromeOmnibox(); #if !defined(OS_IOS) if (from_app_list) access_point = RLZTracker::ChromeAppList(); #endif RLZTracker::GetAccessPointRlz(access_point, &rlz_string); } #endif return rlz_string; } // We can enable this on non-Android if other platforms ever want a non-empty // search client string. There is already a unit test in place for Android // called TemplateURLTest::SearchClient. std::string UIThreadSearchTermsData::GetSearchClient() const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); return std::string(); } #endif std::string UIThreadSearchTermsData::GetSuggestClient() const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); #if defined(OS_ANDROID) sync_pb::SyncEnums::DeviceType device_type = browser_sync::DeviceInfo::GetLocalDeviceType(); return device_type == sync_pb::SyncEnums_DeviceType_TYPE_PHONE ? "chrome" : "chrome-omni"; #else return chrome::IsInstantExtendedAPIEnabled() ? "chrome-omni" : "chrome"; #endif } std::string UIThreadSearchTermsData::GetSuggestRequestIdentifier() const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); #if defined(OS_ANDROID) sync_pb::SyncEnums::DeviceType device_type = browser_sync::DeviceInfo::GetLocalDeviceType(); if (device_type == sync_pb::SyncEnums_DeviceType_TYPE_PHONE) { return OmniboxFieldTrial::EnableAnswersInSuggest() ? "chrome-mobile-ext-ansg" : "chrome-mobile-ext"; } return OmniboxFieldTrial::EnableAnswersInSuggest() ? "chrome-ext-ansg" : "chrome-ext"; #elif defined(OS_IOS) return OmniboxFieldTrial::EnableAnswersInSuggest() ? "chrome-ext-ansg" : "chrome-ext"; #else return "chrome-ext"; #endif } bool UIThreadSearchTermsData::EnableAnswersInSuggest() const { return OmniboxFieldTrial::EnableAnswersInSuggest(); } bool UIThreadSearchTermsData::IsShowingSearchTermsOnSearchResultsPages() const { return chrome::IsInstantExtendedAPIEnabled() && chrome::IsQueryExtractionEnabled(); } std::string UIThreadSearchTermsData::InstantExtendedEnabledParam( bool for_search) const { return chrome::InstantExtendedEnabledParam(for_search); } std::string UIThreadSearchTermsData::ForceInstantResultsParam( bool for_prerender) const { return chrome::ForceInstantResultsParam(for_prerender); } int UIThreadSearchTermsData::OmniboxStartMargin() const { InstantService* instant_service = InstantServiceFactory::GetForProfile(profile_); // Android and iOS have no InstantService. return instant_service ? instant_service->omnibox_start_margin() : chrome::kDisableStartMargin; } std::string UIThreadSearchTermsData::NTPIsThemedParam() const { DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) || BrowserThread::CurrentlyOn(BrowserThread::UI)); #if defined(ENABLE_THEMES) if (!chrome::IsInstantExtendedAPIEnabled()) return std::string(); // TODO(dhollowa): Determine fraction of custom themes that don't affect the // NTP background and/or color. ThemeService* theme_service = ThemeServiceFactory::GetForProfile(profile_); // NTP is considered themed if the theme is not default and not native (GTK+). if (theme_service && !theme_service->UsingDefaultTheme() && !theme_service->UsingSystemTheme()) return "es_th=1&"; #endif // defined(ENABLE_THEMES) return std::string(); } // It's acutally OK to call this method on any thread, but it's currently placed // in UIThreadSearchTermsData since SearchTermsData cannot depend on // VersionInfo. std::string UIThreadSearchTermsData::GoogleImageSearchSource() const { chrome::VersionInfo version_info; if (version_info.is_valid()) { std::string version(version_info.Name() + " " + version_info.Version()); if (version_info.IsOfficialBuild()) version += " (Official)"; version += " " + version_info.OSType(); std::string modifier(version_info.GetVersionStringModifier()); if (!modifier.empty()) version += " " + modifier; return version; } return "unknown"; } // static void UIThreadSearchTermsData::SetGoogleBaseURL(const std::string& base_url) { delete google_base_url_; google_base_url_ = base_url.empty() ? NULL : new std::string(base_url); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/tab_specific_content_settings.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browsing_data_appcache_helper.h" #include "chrome/browser/browsing_data_database_helper.h" #include "chrome/browser/browsing_data_indexed_db_helper.h" #include "chrome/browser/browsing_data_local_storage_helper.h" #include "chrome/browser/cookies_tree_model.h" #include "chrome/browser/prerender/prerender_manager.h" #include "net/base/cookie_monster.h" bool TabSpecificContentSettings::LocalSharedObjectsContainer::empty() const { return cookies_->GetAllCookies().empty() && appcaches_->empty() && databases_->empty() && indexed_dbs_->empty() && local_storages_->empty() && session_storages_->empty(); } bool TabSpecificContentSettings::IsContentBlocked( ContentSettingsType content_type) const { DCHECK(content_type != CONTENT_SETTINGS_TYPE_GEOLOCATION) << "Geolocation settings handled by ContentSettingGeolocationImageModel"; DCHECK(content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS) << "Notifications settings handled by " << "ContentSettingsNotificationsImageModel"; if (content_type == CONTENT_SETTINGS_TYPE_IMAGES || content_type == CONTENT_SETTINGS_TYPE_JAVASCRIPT || content_type == CONTENT_SETTINGS_TYPE_PLUGINS || content_type == CONTENT_SETTINGS_TYPE_COOKIES || content_type == CONTENT_SETTINGS_TYPE_POPUPS) return content_blocked_[content_type]; NOTREACHED(); return false; } bool TabSpecificContentSettings::IsBlockageIndicated( ContentSettingsType content_type) const { return content_blockage_indicated_to_user_[content_type]; } void TabSpecificContentSettings::SetBlockageHasBeenIndicated( ContentSettingsType content_type) { content_blockage_indicated_to_user_[content_type] = true; } bool TabSpecificContentSettings::IsContentAccessed( ContentSettingsType content_type) const { // This method currently only returns meaningful values for cookies. if (content_type != CONTENT_SETTINGS_TYPE_COOKIES) return false; return content_accessed_[content_type]; } const std::set<std::string>& TabSpecificContentSettings::BlockedResourcesForType( ContentSettingsType content_type) const { if (blocked_resources_[content_type].get()) { return *blocked_resources_[content_type]; } else { static std::set<std::string> empty_set; return empty_set; } } void TabSpecificContentSettings::AddBlockedResource( ContentSettingsType content_type, const std::string& resource_identifier) { if (!blocked_resources_[content_type].get()) blocked_resources_[content_type].reset(new std::set<std::string>()); blocked_resources_[content_type]->insert(resource_identifier); } void TabSpecificContentSettings::OnContentBlocked( ContentSettingsType type, const std::string& resource_identifier) { DCHECK(type != CONTENT_SETTINGS_TYPE_GEOLOCATION) << "Geolocation settings handled by OnGeolocationPermissionSet"; content_accessed_[type] = true; if (!resource_identifier.empty()) AddBlockedResource(type, resource_identifier); if (!content_blocked_[type]) { content_blocked_[type] = true; if (delegate_) delegate_->OnContentSettingsAccessed(true); } } void TabSpecificContentSettings::OnContentAccessed(ContentSettingsType type) { DCHECK(type != CONTENT_SETTINGS_TYPE_GEOLOCATION) << "Geolocation settings handled by OnGeolocationPermissionSet"; if (!content_accessed_[type]) { content_accessed_[type] = true; if (delegate_) delegate_->OnContentSettingsAccessed(false); } } void TabSpecificContentSettings::OnCookiesRead( const GURL& url, const net::CookieList& cookie_list, bool blocked_by_policy) { if (cookie_list.empty()) return; LocalSharedObjectsContainer& container = blocked_by_policy ? blocked_local_shared_objects_ : allowed_local_shared_objects_; typedef net::CookieList::const_iterator cookie_iterator; for (cookie_iterator cookie = cookie_list.begin(); cookie != cookie_list.end(); ++cookie) { container.cookies()->ValidateMap(prerender::PrerenderManager::GetMode()); container.cookies()->SetCookieWithDetails(url, cookie->Name(), cookie->Value(), cookie->Domain(), cookie->Path(), cookie->ExpiryDate(), cookie->IsSecure(), cookie->IsHttpOnly()); container.cookies()->ValidateMap(prerender::PrerenderManager::GetMode()); } if (blocked_by_policy) OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string()); else OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES); } void TabSpecificContentSettings::OnCookieChanged( const GURL& url, const std::string& cookie_line, const net::CookieOptions& options, bool blocked_by_policy) { if (blocked_by_policy) { blocked_local_shared_objects_.cookies()->ValidateMap( prerender::PrerenderManager::GetMode()); blocked_local_shared_objects_.cookies()->SetCookieWithOptions( url, cookie_line, options); blocked_local_shared_objects_.cookies()->ValidateMap( prerender::PrerenderManager::GetMode()); OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string()); } else { allowed_local_shared_objects_.cookies()->ValidateMap( prerender::PrerenderManager::GetMode()); allowed_local_shared_objects_.cookies()->SetCookieWithOptions( url, cookie_line, options); allowed_local_shared_objects_.cookies()->ValidateMap( prerender::PrerenderManager::GetMode()); OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES); } } void TabSpecificContentSettings::OnIndexedDBAccessed( const GURL& url, const string16& description, bool blocked_by_policy) { if (blocked_by_policy) { blocked_local_shared_objects_.indexed_dbs()->AddIndexedDB( url, description); OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string()); }else { allowed_local_shared_objects_.indexed_dbs()->AddIndexedDB( url, description); OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES); } } void TabSpecificContentSettings::OnLocalStorageAccessed( const GURL& url, DOMStorageType storage_type, bool blocked_by_policy) { LocalSharedObjectsContainer& container = blocked_by_policy ? blocked_local_shared_objects_ : allowed_local_shared_objects_; CannedBrowsingDataLocalStorageHelper* helper = storage_type == DOM_STORAGE_LOCAL ? container.local_storages() : container.session_storages(); helper->AddLocalStorage(url); if (blocked_by_policy) OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string()); else OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES); } void TabSpecificContentSettings::OnWebDatabaseAccessed( const GURL& url, const string16& name, const string16& display_name, unsigned long estimated_size, bool blocked_by_policy) { if (blocked_by_policy) { blocked_local_shared_objects_.databases()->AddDatabase( url, UTF16ToUTF8(name), UTF16ToUTF8(display_name)); OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string()); } else { allowed_local_shared_objects_.databases()->AddDatabase( url, UTF16ToUTF8(name), UTF16ToUTF8(display_name)); OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES); } } void TabSpecificContentSettings::OnAppCacheAccessed( const GURL& manifest_url, bool blocked_by_policy) { if (blocked_by_policy) { blocked_local_shared_objects_.appcaches()->AddAppCache(manifest_url); OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string()); } else { allowed_local_shared_objects_.appcaches()->AddAppCache(manifest_url); OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES); } } void TabSpecificContentSettings::OnGeolocationPermissionSet( const GURL& requesting_origin, bool allowed) { geolocation_settings_state_.OnGeolocationPermissionSet(requesting_origin, allowed); if (delegate_) delegate_->OnContentSettingsAccessed(!allowed); } TabSpecificContentSettings::TabSpecificContentSettings( Delegate* delegate, Profile* profile) : allowed_local_shared_objects_(profile), blocked_local_shared_objects_(profile), geolocation_settings_state_(profile), load_plugins_link_enabled_(true), delegate_(NULL) { ClearBlockedContentSettingsExceptForCookies(); ClearCookieSpecificContentSettings(); delegate_ = delegate; } void TabSpecificContentSettings::ClearBlockedContentSettingsExceptForCookies() { for (size_t i = 0; i < arraysize(content_blocked_); ++i) { if (i == CONTENT_SETTINGS_TYPE_COOKIES) continue; blocked_resources_[i].reset(); content_blocked_[i] = false; content_accessed_[i] = false; content_blockage_indicated_to_user_[i] = false; } load_plugins_link_enabled_ = true; if (delegate_) delegate_->OnContentSettingsAccessed(false); } void TabSpecificContentSettings::ClearCookieSpecificContentSettings() { blocked_local_shared_objects_.Reset(); allowed_local_shared_objects_.Reset(); content_blocked_[CONTENT_SETTINGS_TYPE_COOKIES] = false; content_accessed_[CONTENT_SETTINGS_TYPE_COOKIES] = false; content_blockage_indicated_to_user_[CONTENT_SETTINGS_TYPE_COOKIES] = false; if (delegate_) delegate_->OnContentSettingsAccessed(false); } void TabSpecificContentSettings::SetPopupsBlocked(bool blocked) { content_blocked_[CONTENT_SETTINGS_TYPE_POPUPS] = blocked; content_blockage_indicated_to_user_[CONTENT_SETTINGS_TYPE_POPUPS] = false; if (delegate_) delegate_->OnContentSettingsAccessed(blocked); } void TabSpecificContentSettings::GeolocationDidNavigate( const NavigationController::LoadCommittedDetails& details) { geolocation_settings_state_.DidNavigate(details); } void TabSpecificContentSettings::ClearGeolocationContentSettings() { geolocation_settings_state_.ClearStateMap(); } CookiesTreeModel* TabSpecificContentSettings::GetAllowedCookiesTreeModel() { return allowed_local_shared_objects_.GetCookiesTreeModel(); } CookiesTreeModel* TabSpecificContentSettings::GetBlockedCookiesTreeModel() { return blocked_local_shared_objects_.GetCookiesTreeModel(); } TabSpecificContentSettings::LocalSharedObjectsContainer:: LocalSharedObjectsContainer(Profile* profile) : cookies_(new net::CookieMonster(NULL, NULL)), appcaches_(new CannedBrowsingDataAppCacheHelper(profile)), databases_(new CannedBrowsingDataDatabaseHelper(profile)), indexed_dbs_(new CannedBrowsingDataIndexedDBHelper(profile)), local_storages_(new CannedBrowsingDataLocalStorageHelper(profile)), session_storages_(new CannedBrowsingDataLocalStorageHelper(profile)) { } TabSpecificContentSettings::LocalSharedObjectsContainer:: ~LocalSharedObjectsContainer() { cookies_->ValidateMap(prerender::PrerenderManager::GetMode()); } void TabSpecificContentSettings::LocalSharedObjectsContainer::Reset() { cookies_->ValidateMap(prerender::PrerenderManager::GetMode()); cookies_->DeleteAll(false); cookies_->ValidateMap(prerender::PrerenderManager::GetMode()); appcaches_->Reset(); databases_->Reset(); indexed_dbs_->Reset(); local_storages_->Reset(); session_storages_->Reset(); } CookiesTreeModel* TabSpecificContentSettings::LocalSharedObjectsContainer::GetCookiesTreeModel() { return new CookiesTreeModel(cookies_, databases_, local_storages_, session_storages_, appcaches_, indexed_dbs_); } <commit_msg>Replace the cookie monster on navigations instead of reusing it.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/tab_contents/tab_specific_content_settings.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browsing_data_appcache_helper.h" #include "chrome/browser/browsing_data_database_helper.h" #include "chrome/browser/browsing_data_indexed_db_helper.h" #include "chrome/browser/browsing_data_local_storage_helper.h" #include "chrome/browser/cookies_tree_model.h" #include "chrome/browser/prerender/prerender_manager.h" #include "net/base/cookie_monster.h" bool TabSpecificContentSettings::LocalSharedObjectsContainer::empty() const { return cookies_->GetAllCookies().empty() && appcaches_->empty() && databases_->empty() && indexed_dbs_->empty() && local_storages_->empty() && session_storages_->empty(); } bool TabSpecificContentSettings::IsContentBlocked( ContentSettingsType content_type) const { DCHECK(content_type != CONTENT_SETTINGS_TYPE_GEOLOCATION) << "Geolocation settings handled by ContentSettingGeolocationImageModel"; DCHECK(content_type != CONTENT_SETTINGS_TYPE_NOTIFICATIONS) << "Notifications settings handled by " << "ContentSettingsNotificationsImageModel"; if (content_type == CONTENT_SETTINGS_TYPE_IMAGES || content_type == CONTENT_SETTINGS_TYPE_JAVASCRIPT || content_type == CONTENT_SETTINGS_TYPE_PLUGINS || content_type == CONTENT_SETTINGS_TYPE_COOKIES || content_type == CONTENT_SETTINGS_TYPE_POPUPS) return content_blocked_[content_type]; NOTREACHED(); return false; } bool TabSpecificContentSettings::IsBlockageIndicated( ContentSettingsType content_type) const { return content_blockage_indicated_to_user_[content_type]; } void TabSpecificContentSettings::SetBlockageHasBeenIndicated( ContentSettingsType content_type) { content_blockage_indicated_to_user_[content_type] = true; } bool TabSpecificContentSettings::IsContentAccessed( ContentSettingsType content_type) const { // This method currently only returns meaningful values for cookies. if (content_type != CONTENT_SETTINGS_TYPE_COOKIES) return false; return content_accessed_[content_type]; } const std::set<std::string>& TabSpecificContentSettings::BlockedResourcesForType( ContentSettingsType content_type) const { if (blocked_resources_[content_type].get()) { return *blocked_resources_[content_type]; } else { static std::set<std::string> empty_set; return empty_set; } } void TabSpecificContentSettings::AddBlockedResource( ContentSettingsType content_type, const std::string& resource_identifier) { if (!blocked_resources_[content_type].get()) blocked_resources_[content_type].reset(new std::set<std::string>()); blocked_resources_[content_type]->insert(resource_identifier); } void TabSpecificContentSettings::OnContentBlocked( ContentSettingsType type, const std::string& resource_identifier) { DCHECK(type != CONTENT_SETTINGS_TYPE_GEOLOCATION) << "Geolocation settings handled by OnGeolocationPermissionSet"; content_accessed_[type] = true; if (!resource_identifier.empty()) AddBlockedResource(type, resource_identifier); if (!content_blocked_[type]) { content_blocked_[type] = true; if (delegate_) delegate_->OnContentSettingsAccessed(true); } } void TabSpecificContentSettings::OnContentAccessed(ContentSettingsType type) { DCHECK(type != CONTENT_SETTINGS_TYPE_GEOLOCATION) << "Geolocation settings handled by OnGeolocationPermissionSet"; if (!content_accessed_[type]) { content_accessed_[type] = true; if (delegate_) delegate_->OnContentSettingsAccessed(false); } } void TabSpecificContentSettings::OnCookiesRead( const GURL& url, const net::CookieList& cookie_list, bool blocked_by_policy) { if (cookie_list.empty()) return; LocalSharedObjectsContainer& container = blocked_by_policy ? blocked_local_shared_objects_ : allowed_local_shared_objects_; typedef net::CookieList::const_iterator cookie_iterator; for (cookie_iterator cookie = cookie_list.begin(); cookie != cookie_list.end(); ++cookie) { container.cookies()->ValidateMap(prerender::PrerenderManager::GetMode()); container.cookies()->SetCookieWithDetails(url, cookie->Name(), cookie->Value(), cookie->Domain(), cookie->Path(), cookie->ExpiryDate(), cookie->IsSecure(), cookie->IsHttpOnly()); container.cookies()->ValidateMap(prerender::PrerenderManager::GetMode()); } if (blocked_by_policy) OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string()); else OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES); } void TabSpecificContentSettings::OnCookieChanged( const GURL& url, const std::string& cookie_line, const net::CookieOptions& options, bool blocked_by_policy) { if (blocked_by_policy) { blocked_local_shared_objects_.cookies()->ValidateMap( prerender::PrerenderManager::GetMode()); blocked_local_shared_objects_.cookies()->SetCookieWithOptions( url, cookie_line, options); blocked_local_shared_objects_.cookies()->ValidateMap( prerender::PrerenderManager::GetMode()); OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string()); } else { allowed_local_shared_objects_.cookies()->ValidateMap( prerender::PrerenderManager::GetMode()); allowed_local_shared_objects_.cookies()->SetCookieWithOptions( url, cookie_line, options); allowed_local_shared_objects_.cookies()->ValidateMap( prerender::PrerenderManager::GetMode()); OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES); } } void TabSpecificContentSettings::OnIndexedDBAccessed( const GURL& url, const string16& description, bool blocked_by_policy) { if (blocked_by_policy) { blocked_local_shared_objects_.indexed_dbs()->AddIndexedDB( url, description); OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string()); }else { allowed_local_shared_objects_.indexed_dbs()->AddIndexedDB( url, description); OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES); } } void TabSpecificContentSettings::OnLocalStorageAccessed( const GURL& url, DOMStorageType storage_type, bool blocked_by_policy) { LocalSharedObjectsContainer& container = blocked_by_policy ? blocked_local_shared_objects_ : allowed_local_shared_objects_; CannedBrowsingDataLocalStorageHelper* helper = storage_type == DOM_STORAGE_LOCAL ? container.local_storages() : container.session_storages(); helper->AddLocalStorage(url); if (blocked_by_policy) OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string()); else OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES); } void TabSpecificContentSettings::OnWebDatabaseAccessed( const GURL& url, const string16& name, const string16& display_name, unsigned long estimated_size, bool blocked_by_policy) { if (blocked_by_policy) { blocked_local_shared_objects_.databases()->AddDatabase( url, UTF16ToUTF8(name), UTF16ToUTF8(display_name)); OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string()); } else { allowed_local_shared_objects_.databases()->AddDatabase( url, UTF16ToUTF8(name), UTF16ToUTF8(display_name)); OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES); } } void TabSpecificContentSettings::OnAppCacheAccessed( const GURL& manifest_url, bool blocked_by_policy) { if (blocked_by_policy) { blocked_local_shared_objects_.appcaches()->AddAppCache(manifest_url); OnContentBlocked(CONTENT_SETTINGS_TYPE_COOKIES, std::string()); } else { allowed_local_shared_objects_.appcaches()->AddAppCache(manifest_url); OnContentAccessed(CONTENT_SETTINGS_TYPE_COOKIES); } } void TabSpecificContentSettings::OnGeolocationPermissionSet( const GURL& requesting_origin, bool allowed) { geolocation_settings_state_.OnGeolocationPermissionSet(requesting_origin, allowed); if (delegate_) delegate_->OnContentSettingsAccessed(!allowed); } TabSpecificContentSettings::TabSpecificContentSettings( Delegate* delegate, Profile* profile) : allowed_local_shared_objects_(profile), blocked_local_shared_objects_(profile), geolocation_settings_state_(profile), load_plugins_link_enabled_(true), delegate_(NULL) { ClearBlockedContentSettingsExceptForCookies(); ClearCookieSpecificContentSettings(); delegate_ = delegate; } void TabSpecificContentSettings::ClearBlockedContentSettingsExceptForCookies() { for (size_t i = 0; i < arraysize(content_blocked_); ++i) { if (i == CONTENT_SETTINGS_TYPE_COOKIES) continue; blocked_resources_[i].reset(); content_blocked_[i] = false; content_accessed_[i] = false; content_blockage_indicated_to_user_[i] = false; } load_plugins_link_enabled_ = true; if (delegate_) delegate_->OnContentSettingsAccessed(false); } void TabSpecificContentSettings::ClearCookieSpecificContentSettings() { blocked_local_shared_objects_.Reset(); allowed_local_shared_objects_.Reset(); content_blocked_[CONTENT_SETTINGS_TYPE_COOKIES] = false; content_accessed_[CONTENT_SETTINGS_TYPE_COOKIES] = false; content_blockage_indicated_to_user_[CONTENT_SETTINGS_TYPE_COOKIES] = false; if (delegate_) delegate_->OnContentSettingsAccessed(false); } void TabSpecificContentSettings::SetPopupsBlocked(bool blocked) { content_blocked_[CONTENT_SETTINGS_TYPE_POPUPS] = blocked; content_blockage_indicated_to_user_[CONTENT_SETTINGS_TYPE_POPUPS] = false; if (delegate_) delegate_->OnContentSettingsAccessed(blocked); } void TabSpecificContentSettings::GeolocationDidNavigate( const NavigationController::LoadCommittedDetails& details) { geolocation_settings_state_.DidNavigate(details); } void TabSpecificContentSettings::ClearGeolocationContentSettings() { geolocation_settings_state_.ClearStateMap(); } CookiesTreeModel* TabSpecificContentSettings::GetAllowedCookiesTreeModel() { return allowed_local_shared_objects_.GetCookiesTreeModel(); } CookiesTreeModel* TabSpecificContentSettings::GetBlockedCookiesTreeModel() { return blocked_local_shared_objects_.GetCookiesTreeModel(); } TabSpecificContentSettings::LocalSharedObjectsContainer:: LocalSharedObjectsContainer(Profile* profile) : cookies_(new net::CookieMonster(NULL, NULL)), appcaches_(new CannedBrowsingDataAppCacheHelper(profile)), databases_(new CannedBrowsingDataDatabaseHelper(profile)), indexed_dbs_(new CannedBrowsingDataIndexedDBHelper(profile)), local_storages_(new CannedBrowsingDataLocalStorageHelper(profile)), session_storages_(new CannedBrowsingDataLocalStorageHelper(profile)) { } TabSpecificContentSettings::LocalSharedObjectsContainer:: ~LocalSharedObjectsContainer() { cookies_->ValidateMap(prerender::PrerenderManager::GetMode()); } void TabSpecificContentSettings::LocalSharedObjectsContainer::Reset() { cookies_ = new net::CookieMonster(NULL, NULL); appcaches_->Reset(); databases_->Reset(); indexed_dbs_->Reset(); local_storages_->Reset(); session_storages_->Reset(); } CookiesTreeModel* TabSpecificContentSettings::LocalSharedObjectsContainer::GetCookiesTreeModel() { return new CookiesTreeModel(cookies_, databases_, local_storages_, session_storages_, appcaches_, indexed_dbs_); } <|endoftext|>
<commit_before>#pragma once #include "net.hpp" #include "net_raw.hpp" #include "net_raw_utils.hpp" #include "net_gpu_impl.hpp" template <typename activation, typename error> inline void gpu_train_batch(FeedForward_Network<activation, error>& network, arma::Mat<float> inputs, arma::Mat<float> targets, float learning_rate, int batch_size) { network.resize_activation(batch_size); Raw_FeedForward_Network<activation, error> raw_net = convert_to_raw(network); Raw_FeedForward_Network<activation, error> * d_network = network_to_gpu(raw_net); int input_size = network.input_size; int hidden_size = network.hidden_size; int output_size = network.output_size; int batches_in_train = targets.n_rows/batch_size - 1; //batches_in_train = 1000; for (int i = 0; i < batches_in_train; ++i) { arma::Mat<float> input_slice = inputs.rows(i*batch_size, (i+1) * batch_size - 1); Raw_Matrix raw_input = to_raw(input_slice); Raw_Matrix * d_input = matrix_to_gpu(raw_input); int num_trials = input_slice.n_rows; calculate_activation(num_trials, input_size, hidden_size, output_size, d_network, d_input); //TODO make this memory shared as to not realloc free_gpu_matrix(d_input); arma::Mat<float> targets_slice = targets.rows(i*batch_size, (i+1) * batch_size - 1); Raw_Matrix raw_targets = to_raw(targets_slice); Raw_Matrix * d_targets = matrix_to_gpu(raw_targets); backprop(num_trials, input_size, hidden_size, output_size, d_network, d_targets, learning_rate); free_gpu_matrix(d_targets); } network_to_cpu_free(d_network, raw_net); update_from_raw(network, raw_net); } template <typename activation, typename error> inline arma::Mat<float> gpu_predict(FeedForward_Network<activation, error>& network, arma::Mat<float> inputs) { network.resize_activation(inputs.n_rows); Raw_FeedForward_Network<activation, error> raw_net = convert_to_raw(network); Raw_FeedForward_Network<activation, error> * d_network = network_to_gpu(raw_net); Raw_Matrix raw_inputs = to_raw(inputs); Raw_Matrix * d_inputs = matrix_to_gpu(raw_inputs); int num_trials = inputs.n_rows; int input_size = network.input_size; int hidden_size = network.hidden_size; int output_size = network.output_size; calculate_activation(num_trials, input_size, hidden_size, output_size, d_network, d_inputs); network_to_cpu_free(d_network, raw_net); update_from_raw(network, raw_net); return network.activation_output; } <commit_msg>fixed a few more cuda Memory leaks.<commit_after>#pragma once #include "net.hpp" #include "net_raw.hpp" #include "net_raw_utils.hpp" #include "net_gpu_impl.hpp" template <typename activation, typename error> inline void gpu_train_batch(FeedForward_Network<activation, error>& network, arma::Mat<float> inputs, arma::Mat<float> targets, float learning_rate, int batch_size) { network.resize_activation(batch_size); Raw_FeedForward_Network<activation, error> raw_net = convert_to_raw(network); Raw_FeedForward_Network<activation, error> * d_network = network_to_gpu(raw_net); int input_size = network.input_size; int hidden_size = network.hidden_size; int output_size = network.output_size; int batches_in_train = targets.n_rows/batch_size - 1; //batches_in_train = 1000; for (int i = 0; i < batches_in_train; ++i) { arma::Mat<float> input_slice = inputs.rows(i*batch_size, (i+1) * batch_size - 1); Raw_Matrix raw_input = to_raw(input_slice); Raw_Matrix * d_input = matrix_to_gpu(raw_input); int num_trials = input_slice.n_rows; calculate_activation(num_trials, input_size, hidden_size, output_size, d_network, d_input); //TODO make this memory shared as to not realloc free_gpu_matrix(d_input); arma::Mat<float> targets_slice = targets.rows(i*batch_size, (i+1) * batch_size - 1); Raw_Matrix raw_targets = to_raw(targets_slice); Raw_Matrix * d_targets = matrix_to_gpu(raw_targets); backprop(num_trials, input_size, hidden_size, output_size, d_network, d_targets, learning_rate); free_gpu_matrix(d_targets); } network_to_cpu_free(d_network, raw_net); update_from_raw(network, raw_net); } template <typename activation, typename error> inline arma::Mat<float> gpu_predict(FeedForward_Network<activation, error>& network, arma::Mat<float> inputs) { network.resize_activation(inputs.n_rows); Raw_FeedForward_Network<activation, error> raw_net = convert_to_raw(network); Raw_FeedForward_Network<activation, error> * d_network = network_to_gpu(raw_net); Raw_Matrix raw_inputs = to_raw(inputs); Raw_Matrix * d_inputs = matrix_to_gpu(raw_inputs); int num_trials = inputs.n_rows; int input_size = network.input_size; int hidden_size = network.hidden_size; int output_size = network.output_size; calculate_activation(num_trials, input_size, hidden_size, output_size, d_network, d_inputs); free_gpu_matrix(d_inputs); network_to_cpu_free(d_network, raw_net); update_from_raw(network, raw_net); return network.activation_output; } <|endoftext|>
<commit_before>#include <cstdint> #include <iostream> #include <memory> #include <algorithm> #include <boost/regex.hpp> #include <osmium/area/assembler.hpp> #include <osmium/area/multipolygon_collector.hpp> #include <osmium/index/map/dummy.hpp> #include <osmium/index/map/sparse_mem_array.hpp> #include <osmium/handler/node_locations_for_ways.hpp> #include <osmium/io/any_input.hpp> #include <osmium/handler.hpp> #include <osmium/visitor.hpp> #include <proj_api.h> //#include "earcut.hxx" #include "ObjWriter.hxx" #include "elevation.hxx" using namespace std; using namespace boost; using namespace osmwave; typedef osmium::index::map::Map<osmium::unsigned_object_id_type, osmium::Location> index_type; typedef osmium::handler::NodeLocationsForWays<index_type> location_handler_type; projPJ wgs84 = pj_init_plus("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"); const double METERS_PER_LEVEL = 3.0; class ObjHandler : public osmium::handler::Handler { projPJ proj; ObjWriter writer; vector<double> wayCoords; Elevation& elevation; double defaultBuildingHeight; public: ObjHandler(projPJ p, ObjWriter writer, Elevation& elevation, double defaultBuildingHeight = 8) : proj(p), writer(writer), elevation(elevation), defaultBuildingHeight(defaultBuildingHeight) {} void area(osmium::Area& area) { const osmium::TagList& tags = area.tags(); const char* building = tags.get_value_by_key("building"); const char* highway = tags.get_value_by_key("highway"); if (!building /*&& !highway*/) { return; } double height = getBuildingHeight(tags, defaultBuildingHeight, "height", "building:levels"); double baseHeight = getBuildingHeight(tags, 0, "min_height", "building:min_level"); for (auto oit = area.cbegin<osmium::OuterRing>(); oit != area.cend<osmium::OuterRing>(); ++oit) { const osmium::NodeRefList& nodes = *oit; int nNodes = nodes.size(); if (wayCoords.capacity() < nNodes) { wayCoords.reserve(nNodes * 2); } double minElevation = numeric_limits<double>::max(); for (auto& nr : nodes) { double lon = nr.lon(); double lat = nr.lat(); wayCoords.push_back(lon * DEG_TO_RAD); wayCoords.push_back(lat * DEG_TO_RAD); minElevation = min(minElevation, elevation.elevation(lat, lon)); } pj_transform(wgs84, proj, nodes.size(), 2, wayCoords.data(), wayCoords.data() + 1, nullptr); ringWalls(wayCoords, minElevation + baseHeight, height - baseHeight); flatRoof(nNodes); wayCoords.clear(); } } private: void ringWalls(vector<double> wayCoords, double elevation, double height) { int nVerts = wayCoords.size() / 2; int vertexCount = 0; writer.checkpoint(); for (vector<double>::iterator i = wayCoords.begin(); i != wayCoords.end(); i += 2) { writer.vertex(*(i + 1), elevation, *i); writer.vertex(*(i + 1), elevation + height, *i); if (vertexCount) { writer.beginFace(); writer << (vertexCount - 2) << (vertexCount) << (vertexCount + 1) << (vertexCount - 1); writer.endFace(); } vertexCount += 2; } } void flatRoof(int nVerts) { writer.beginFace(); for (int i = 0; i < nVerts; i++) { writer << (i * 2 + 1); } writer.endFace(); } double getBuildingHeight(const osmium::TagList& tags, double defaultHeight, const char* heightTagName, const char* levelTagName) { regex heightexpr("^\\s*([0-9\\.]+)\\s*(\\S*)\\s*$"); const char* heightTag = tags[heightTagName]; double height = defaultHeight; if (heightTag) { string heightStr(heightTag); auto match_begin = sregex_iterator(heightStr.begin(), heightStr.end(), heightexpr); auto match_end = sregex_iterator(); if (match_begin != match_end) { smatch match = *match_begin; height = stod(match[1]); } } else { const char* levelsTag = tags[levelTagName]; if (levelsTag) { string levelsStr(levelsTag); try { double levels = stod(levelsStr); height = levels * METERS_PER_LEVEL; } catch (const invalid_argument& ia) { cerr << "Unparseable value for \"building:levels\" tag: \"" << levelsStr << "\"" << endl; } } } return height; } }; string* get_proj(osmium::io::Header& header) { auto& box = header.boxes()[0]; float clat = (box.bottom_left().lat() + box.top_right().lat()) / 2; float clon = (box.bottom_left().lon() + box.top_right().lon()) / 2; ostringstream stream; stream << "+proj=tmerc +lat_0=" << clat << " +lon_0=" << clon << " +k=1.000000 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"; return new string(stream.str()); } namespace osmwave { void write_obj_header(ObjWriter& objWriter, const string& osmFile, const osmium::Location& sw, const osmium::Location& ne, projPJ proj) { ostringstream c; c.precision(7); objWriter.comment("Created with OSMWAVE"); objWriter.comment(""); c << "Input file: " << osmFile; objWriter.comment(c.str()); cerr << c.str() << endl; c.str(""); c << "Lat/lng bounds: (" << sw.lat() << ", " << sw.lon() << ") - (" << ne.lat() << ", " << ne.lon() << ")"; objWriter.comment(c.str()); cerr << c.str() << endl; c.str(""); c << "Projection: " << pj_get_def(proj, 0); objWriter.comment(c.str()); cerr << c.str() << endl; double coord[2]; c.str(""); c << "Projected bounds: ("; coord[0] = sw.lon() * DEG_TO_RAD; coord[1] = sw.lat() * DEG_TO_RAD; pj_transform(wgs84, proj, 1, 2, coord, coord + 1, nullptr); c << coord[0] << ", " << coord[1]; c << ") - ("; coord[0] = ne.lon() * DEG_TO_RAD; coord[1] = ne.lat() * DEG_TO_RAD; pj_transform(wgs84, proj, 1, 2, coord, coord + 1, nullptr); c << coord[0] << ", " << coord[1]; c << ")"; objWriter.comment(c.str()); cerr << c.str() << endl; } void osm_to_obj(const std::string& osmFile, const std::string& elevationPath, const std::string* projDef) { ObjWriter objWriter(cout); osmium::io::File infile(osmFile); osmium::area::Assembler::config_type assembler_config; osmium::area::MultipolygonCollector<osmium::area::Assembler> collector(assembler_config); osmium::io::Reader reader1(infile, osmium::osm_entity_bits::relation); collector.read_relations(reader1); reader1.close(); osmium::io::Reader reader2(osmFile); osmium::io::Header header = reader2.header(); projPJ proj; auto& box = header.boxes()[0]; auto& sw = box.bottom_left(); auto& ne = box.top_right(); float clat = (box.bottom_left().lat() + box.top_right().lat()) / 2; float clon = (box.bottom_left().lon() + box.top_right().lon()) / 2; if (!projDef) { projDef = get_proj(header); proj = pj_init_plus(projDef->c_str()); delete projDef; } else { proj = pj_init_plus(projDef->c_str()); } write_obj_header(objWriter, osmFile, sw, ne, proj); const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance(); unique_ptr<index_type> index = map_factory.create_map("sparse_mem_array"); location_handler_type location_handler(*index); location_handler.ignore_errors(); Elevation elevation((int)floor(sw.lat()), (int)floor(sw.lon()), (int)floor(ne.lat()), (int)floor(ne.lon()), elevationPath); ObjHandler handler(proj, objWriter, elevation); osmium::apply(reader2, location_handler, collector.handler([&handler](osmium::memory::Buffer&& buffer) { osmium::apply(buffer, handler); })); reader2.close(); } } <commit_msg>Include building:part<commit_after>#include <cstdint> #include <iostream> #include <memory> #include <algorithm> #include <boost/regex.hpp> #include <osmium/area/assembler.hpp> #include <osmium/area/multipolygon_collector.hpp> #include <osmium/index/map/dummy.hpp> #include <osmium/index/map/sparse_mem_array.hpp> #include <osmium/handler/node_locations_for_ways.hpp> #include <osmium/io/any_input.hpp> #include <osmium/handler.hpp> #include <osmium/visitor.hpp> #include <proj_api.h> //#include "earcut.hxx" #include "ObjWriter.hxx" #include "elevation.hxx" using namespace std; using namespace boost; using namespace osmwave; typedef osmium::index::map::Map<osmium::unsigned_object_id_type, osmium::Location> index_type; typedef osmium::handler::NodeLocationsForWays<index_type> location_handler_type; projPJ wgs84 = pj_init_plus("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"); const double METERS_PER_LEVEL = 3.0; class ObjHandler : public osmium::handler::Handler { projPJ proj; ObjWriter writer; vector<double> wayCoords; Elevation& elevation; double defaultBuildingHeight; public: ObjHandler(projPJ p, ObjWriter writer, Elevation& elevation, double defaultBuildingHeight = 8) : proj(p), writer(writer), elevation(elevation), defaultBuildingHeight(defaultBuildingHeight) {} void area(osmium::Area& area) { const osmium::TagList& tags = area.tags(); const char* building = tags.get_value_by_key("building"); const char* buildingPart = tags.get_value_by_key("building:part"); const char* highway = tags.get_value_by_key("highway"); if (!building && !buildingPart /*&& !highway*/) { return; } double height = getBuildingHeight(tags, defaultBuildingHeight, "height", "building:levels"); double baseHeight = getBuildingHeight(tags, 0, "min_height", "building:min_level"); for (auto oit = area.cbegin<osmium::OuterRing>(); oit != area.cend<osmium::OuterRing>(); ++oit) { const osmium::NodeRefList& nodes = *oit; int nNodes = nodes.size(); if (wayCoords.capacity() < nNodes) { wayCoords.reserve(nNodes * 2); } double minElevation = numeric_limits<double>::max(); for (auto& nr : nodes) { double lon = nr.lon(); double lat = nr.lat(); wayCoords.push_back(lon * DEG_TO_RAD); wayCoords.push_back(lat * DEG_TO_RAD); minElevation = min(minElevation, elevation.elevation(lat, lon)); } pj_transform(wgs84, proj, nodes.size(), 2, wayCoords.data(), wayCoords.data() + 1, nullptr); ringWalls(wayCoords, minElevation + baseHeight, height - baseHeight); flatRoof(nNodes); wayCoords.clear(); } } private: void ringWalls(vector<double> wayCoords, double elevation, double height) { int nVerts = wayCoords.size() / 2; int vertexCount = 0; writer.checkpoint(); for (vector<double>::iterator i = wayCoords.begin(); i != wayCoords.end(); i += 2) { writer.vertex(*(i + 1), elevation, *i); writer.vertex(*(i + 1), elevation + height, *i); if (vertexCount) { writer.beginFace(); writer << (vertexCount - 2) << (vertexCount) << (vertexCount + 1) << (vertexCount - 1); writer.endFace(); } vertexCount += 2; } } void flatRoof(int nVerts) { writer.beginFace(); for (int i = 0; i < nVerts; i++) { writer << (i * 2 + 1); } writer.endFace(); } double getBuildingHeight(const osmium::TagList& tags, double defaultHeight, const char* heightTagName, const char* levelTagName) { regex heightexpr("^\\s*([0-9\\.]+)\\s*(\\S*)\\s*$"); const char* heightTag = tags[heightTagName]; double height = defaultHeight; if (heightTag) { string heightStr(heightTag); auto match_begin = sregex_iterator(heightStr.begin(), heightStr.end(), heightexpr); auto match_end = sregex_iterator(); if (match_begin != match_end) { smatch match = *match_begin; height = stod(match[1]); } } else { const char* levelsTag = tags[levelTagName]; if (levelsTag) { string levelsStr(levelsTag); try { double levels = stod(levelsStr); height = levels * METERS_PER_LEVEL; } catch (const invalid_argument& ia) { cerr << "Unparseable value for \"building:levels\" tag: \"" << levelsStr << "\"" << endl; } } } return height; } }; string* get_proj(osmium::io::Header& header) { auto& box = header.boxes()[0]; float clat = (box.bottom_left().lat() + box.top_right().lat()) / 2; float clon = (box.bottom_left().lon() + box.top_right().lon()) / 2; ostringstream stream; stream << "+proj=tmerc +lat_0=" << clat << " +lon_0=" << clon << " +k=1.000000 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs"; return new string(stream.str()); } namespace osmwave { void write_obj_header(ObjWriter& objWriter, const string& osmFile, const osmium::Location& sw, const osmium::Location& ne, projPJ proj) { ostringstream c; c.precision(7); objWriter.comment("Created with OSMWAVE"); objWriter.comment(""); c << "Input file: " << osmFile; objWriter.comment(c.str()); cerr << c.str() << endl; c.str(""); c << "Lat/lng bounds: (" << sw.lat() << ", " << sw.lon() << ") - (" << ne.lat() << ", " << ne.lon() << ")"; objWriter.comment(c.str()); cerr << c.str() << endl; c.str(""); c << "Projection: " << pj_get_def(proj, 0); objWriter.comment(c.str()); cerr << c.str() << endl; double coord[2]; c.str(""); c << "Projected bounds: ("; coord[0] = sw.lon() * DEG_TO_RAD; coord[1] = sw.lat() * DEG_TO_RAD; pj_transform(wgs84, proj, 1, 2, coord, coord + 1, nullptr); c << coord[0] << ", " << coord[1]; c << ") - ("; coord[0] = ne.lon() * DEG_TO_RAD; coord[1] = ne.lat() * DEG_TO_RAD; pj_transform(wgs84, proj, 1, 2, coord, coord + 1, nullptr); c << coord[0] << ", " << coord[1]; c << ")"; objWriter.comment(c.str()); cerr << c.str() << endl; } void osm_to_obj(const std::string& osmFile, const std::string& elevationPath, const std::string* projDef) { ObjWriter objWriter(cout); osmium::io::File infile(osmFile); osmium::area::Assembler::config_type assembler_config; osmium::area::MultipolygonCollector<osmium::area::Assembler> collector(assembler_config); osmium::io::Reader reader1(infile, osmium::osm_entity_bits::relation); collector.read_relations(reader1); reader1.close(); osmium::io::Reader reader2(osmFile); osmium::io::Header header = reader2.header(); projPJ proj; auto& box = header.boxes()[0]; auto& sw = box.bottom_left(); auto& ne = box.top_right(); float clat = (box.bottom_left().lat() + box.top_right().lat()) / 2; float clon = (box.bottom_left().lon() + box.top_right().lon()) / 2; if (!projDef) { projDef = get_proj(header); proj = pj_init_plus(projDef->c_str()); delete projDef; } else { proj = pj_init_plus(projDef->c_str()); } write_obj_header(objWriter, osmFile, sw, ne, proj); const auto& map_factory = osmium::index::MapFactory<osmium::unsigned_object_id_type, osmium::Location>::instance(); unique_ptr<index_type> index = map_factory.create_map("sparse_mem_array"); location_handler_type location_handler(*index); location_handler.ignore_errors(); Elevation elevation((int)floor(sw.lat()), (int)floor(sw.lon()), (int)floor(ne.lat()), (int)floor(ne.lon()), elevationPath); ObjHandler handler(proj, objWriter, elevation); osmium::apply(reader2, location_handler, collector.handler([&handler](osmium::memory::Buffer&& buffer) { osmium::apply(buffer, handler); })); reader2.close(); } } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkBaseDataIOFactory.h> #include <mitkBaseData.h> #include <mitkImageCast.h> #include <mitkImageToItk.h> #include <itkEvaluateDirectionImagesFilter.h> #include <itkTractsToVectorImageFilter.h> #include <usAny.h> #include <itkImageFileWriter.h> #include <mitkIOUtil.h> #include <boost/lexical_cast.hpp> #include <iostream> #include <fstream> #include <itksys/SystemTools.hxx> #include <mitkTestingMacros.h> #include <mitkCompareImageDataFilter.h> #include <mitkFiberBundleXWriter.h> #define _USE_MATH_DEFINES #include <math.h> using namespace std; int mitkLocalFiberPlausibilityTest(int argc, char* argv[]) { MITK_TEST_BEGIN("mitkLocalFiberPlausibilityTest"); MITK_TEST_CONDITION_REQUIRED(argc==8,"check for input data") string fibFile = argv[1]; vector< string > referenceImages; referenceImages.push_back(argv[2]); referenceImages.push_back(argv[3]); string LDFP_ERROR_IMAGE = argv[4]; string LDFP_NUM_DIRECTIONS = argv[5]; string LDFP_VECTOR_FIELD = argv[6]; string LDFP_ERROR_IMAGE_IGNORE = argv[7]; float angularThreshold = 25; try { typedef itk::Image<unsigned char, 3> ItkUcharImgType; typedef itk::Image< itk::Vector< float, 3>, 3 > ItkDirectionImage3DType; typedef itk::VectorContainer< unsigned int, ItkDirectionImage3DType::Pointer > ItkDirectionImageContainerType; typedef itk::EvaluateDirectionImagesFilter< float > EvaluationFilterType; // load fiber bundle mitk::FiberBundleX::Pointer inputTractogram = dynamic_cast<mitk::FiberBundleX*>(mitk::IOUtil::LoadDataNode(fibFile)->GetData()); // load reference directions ItkDirectionImageContainerType::Pointer referenceImageContainer = ItkDirectionImageContainerType::New(); for (unsigned int i=0; i<referenceImages.size(); i++) { try { mitk::Image::Pointer img = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(referenceImages.at(i))->GetData()); typedef mitk::ImageToItk< ItkDirectionImage3DType > CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput(img); caster->Update(); ItkDirectionImage3DType::Pointer itkImg = caster->GetOutput(); referenceImageContainer->InsertElement(referenceImageContainer->Size(),itkImg); } catch(...){ MITK_INFO << "could not load: " << referenceImages.at(i); } } ItkUcharImgType::Pointer itkMaskImage = ItkUcharImgType::New(); ItkDirectionImage3DType::Pointer dirImg = referenceImageContainer->GetElement(0); itkMaskImage->SetSpacing( dirImg->GetSpacing() ); itkMaskImage->SetOrigin( dirImg->GetOrigin() ); itkMaskImage->SetDirection( dirImg->GetDirection() ); itkMaskImage->SetLargestPossibleRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->SetBufferedRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->SetRequestedRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->Allocate(); itkMaskImage->FillBuffer(1); // extract directions from fiber bundle itk::TractsToVectorImageFilter<float>::Pointer fOdfFilter = itk::TractsToVectorImageFilter<float>::New(); fOdfFilter->SetFiberBundle(inputTractogram); fOdfFilter->SetMaskImage(itkMaskImage); fOdfFilter->SetAngularThreshold(cos(angularThreshold*M_PI/180)); fOdfFilter->SetNormalizeVectors(true); fOdfFilter->SetUseWorkingCopy(false); fOdfFilter->SetNumberOfThreads(1); fOdfFilter->Update(); ItkDirectionImageContainerType::Pointer directionImageContainer = fOdfFilter->GetDirectionImageContainer(); // Get directions and num directions image ItkUcharImgType::Pointer numDirImage = fOdfFilter->GetNumDirectionsImage(); mitk::Image::Pointer mitkNumDirImage = mitk::Image::New(); mitkNumDirImage->InitializeByItk( numDirImage.GetPointer() ); mitkNumDirImage->SetVolume( numDirImage->GetBufferPointer() ); mitk::FiberBundleX::Pointer testDirections = fOdfFilter->GetOutputFiberBundle(); // evaluate directions with missing directions EvaluationFilterType::Pointer evaluationFilter = EvaluationFilterType::New(); evaluationFilter->SetImageSet(directionImageContainer); evaluationFilter->SetReferenceImageSet(referenceImageContainer); evaluationFilter->SetMaskImage(itkMaskImage); evaluationFilter->SetIgnoreMissingDirections(false); evaluationFilter->Update(); EvaluationFilterType::OutputImageType::Pointer angularErrorImage = evaluationFilter->GetOutput(0); mitk::Image::Pointer mitkAngularErrorImage = mitk::Image::New(); mitkAngularErrorImage->InitializeByItk( angularErrorImage.GetPointer() ); mitkAngularErrorImage->SetVolume( angularErrorImage->GetBufferPointer() ); // evaluate directions without missing directions evaluationFilter->SetIgnoreMissingDirections(true); evaluationFilter->Update(); EvaluationFilterType::OutputImageType::Pointer angularErrorImageIgnore = evaluationFilter->GetOutput(0); mitk::Image::Pointer mitkAngularErrorImageIgnore = mitk::Image::New(); mitkAngularErrorImageIgnore->InitializeByItk( angularErrorImageIgnore.GetPointer() ); mitkAngularErrorImageIgnore->SetVolume( angularErrorImageIgnore->GetBufferPointer() ); mitk::Image::Pointer gtAngularErrorImageIgnore = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(LDFP_ERROR_IMAGE_IGNORE)->GetData()); mitk::Image::Pointer gtAngularErrorImage = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(LDFP_ERROR_IMAGE)->GetData()); mitk::Image::Pointer gtNumTestDirImage = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(LDFP_NUM_DIRECTIONS)->GetData()); mitk::FiberBundleX::Pointer gtTestDirections = dynamic_cast<mitk::FiberBundleX*>(mitk::IOUtil::LoadDataNode(LDFP_VECTOR_FIELD)->GetData()); if (!testDirections->Equals(gtTestDirections)) { MITK_INFO << "SAVING FILES TO " << mitk::IOUtil::GetTempPath(); std::string out1 = mitk::IOUtil::GetTempPath().append("test.fib"); std::string out2 = mitk::IOUtil::GetTempPath().append("reference.fib"); mitk::FiberBundleXWriter::Pointer fibWriter = mitk::FiberBundleXWriter::New(); fibWriter->SetFileName(out1.c_str()); fibWriter->DoWrite(testDirections.GetPointer()); fibWriter->SetFileName(out2.c_str()); fibWriter->DoWrite(gtTestDirections.GetPointer()); } MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtAngularErrorImageIgnore, mitkAngularErrorImageIgnore, 0.0001, true), "Check if error images are equal (ignored missing directions)."); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtAngularErrorImage, mitkAngularErrorImage, 0.0001, true), "Check if error images are equal."); MITK_TEST_CONDITION_REQUIRED(testDirections->Equals(gtTestDirections), "Check if vector fields are equal."); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtNumTestDirImage, mitkNumDirImage, 0.0001, true), "Check if num direction images are equal."); } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } MITK_TEST_END(); } <commit_msg>increased tolerance for 32 bit machines<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkBaseDataIOFactory.h> #include <mitkBaseData.h> #include <mitkImageCast.h> #include <mitkImageToItk.h> #include <itkEvaluateDirectionImagesFilter.h> #include <itkTractsToVectorImageFilter.h> #include <usAny.h> #include <itkImageFileWriter.h> #include <mitkIOUtil.h> #include <boost/lexical_cast.hpp> #include <iostream> #include <fstream> #include <itksys/SystemTools.hxx> #include <mitkTestingMacros.h> #include <mitkCompareImageDataFilter.h> #include <mitkFiberBundleXWriter.h> #define _USE_MATH_DEFINES #include <math.h> using namespace std; int mitkLocalFiberPlausibilityTest(int argc, char* argv[]) { MITK_TEST_BEGIN("mitkLocalFiberPlausibilityTest"); MITK_TEST_CONDITION_REQUIRED(argc==8,"check for input data") string fibFile = argv[1]; vector< string > referenceImages; referenceImages.push_back(argv[2]); referenceImages.push_back(argv[3]); string LDFP_ERROR_IMAGE = argv[4]; string LDFP_NUM_DIRECTIONS = argv[5]; string LDFP_VECTOR_FIELD = argv[6]; string LDFP_ERROR_IMAGE_IGNORE = argv[7]; float angularThreshold = 25; try { typedef itk::Image<unsigned char, 3> ItkUcharImgType; typedef itk::Image< itk::Vector< float, 3>, 3 > ItkDirectionImage3DType; typedef itk::VectorContainer< unsigned int, ItkDirectionImage3DType::Pointer > ItkDirectionImageContainerType; typedef itk::EvaluateDirectionImagesFilter< float > EvaluationFilterType; // load fiber bundle mitk::FiberBundleX::Pointer inputTractogram = dynamic_cast<mitk::FiberBundleX*>(mitk::IOUtil::LoadDataNode(fibFile)->GetData()); // load reference directions ItkDirectionImageContainerType::Pointer referenceImageContainer = ItkDirectionImageContainerType::New(); for (unsigned int i=0; i<referenceImages.size(); i++) { try { mitk::Image::Pointer img = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(referenceImages.at(i))->GetData()); typedef mitk::ImageToItk< ItkDirectionImage3DType > CasterType; CasterType::Pointer caster = CasterType::New(); caster->SetInput(img); caster->Update(); ItkDirectionImage3DType::Pointer itkImg = caster->GetOutput(); referenceImageContainer->InsertElement(referenceImageContainer->Size(),itkImg); } catch(...){ MITK_INFO << "could not load: " << referenceImages.at(i); } } ItkUcharImgType::Pointer itkMaskImage = ItkUcharImgType::New(); ItkDirectionImage3DType::Pointer dirImg = referenceImageContainer->GetElement(0); itkMaskImage->SetSpacing( dirImg->GetSpacing() ); itkMaskImage->SetOrigin( dirImg->GetOrigin() ); itkMaskImage->SetDirection( dirImg->GetDirection() ); itkMaskImage->SetLargestPossibleRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->SetBufferedRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->SetRequestedRegion( dirImg->GetLargestPossibleRegion() ); itkMaskImage->Allocate(); itkMaskImage->FillBuffer(1); // extract directions from fiber bundle itk::TractsToVectorImageFilter<float>::Pointer fOdfFilter = itk::TractsToVectorImageFilter<float>::New(); fOdfFilter->SetFiberBundle(inputTractogram); fOdfFilter->SetMaskImage(itkMaskImage); fOdfFilter->SetAngularThreshold(cos(angularThreshold*M_PI/180)); fOdfFilter->SetNormalizeVectors(true); fOdfFilter->SetUseWorkingCopy(false); fOdfFilter->SetNumberOfThreads(1); fOdfFilter->Update(); ItkDirectionImageContainerType::Pointer directionImageContainer = fOdfFilter->GetDirectionImageContainer(); // Get directions and num directions image ItkUcharImgType::Pointer numDirImage = fOdfFilter->GetNumDirectionsImage(); mitk::Image::Pointer mitkNumDirImage = mitk::Image::New(); mitkNumDirImage->InitializeByItk( numDirImage.GetPointer() ); mitkNumDirImage->SetVolume( numDirImage->GetBufferPointer() ); mitk::FiberBundleX::Pointer testDirections = fOdfFilter->GetOutputFiberBundle(); // evaluate directions with missing directions EvaluationFilterType::Pointer evaluationFilter = EvaluationFilterType::New(); evaluationFilter->SetImageSet(directionImageContainer); evaluationFilter->SetReferenceImageSet(referenceImageContainer); evaluationFilter->SetMaskImage(itkMaskImage); evaluationFilter->SetIgnoreMissingDirections(false); evaluationFilter->Update(); EvaluationFilterType::OutputImageType::Pointer angularErrorImage = evaluationFilter->GetOutput(0); mitk::Image::Pointer mitkAngularErrorImage = mitk::Image::New(); mitkAngularErrorImage->InitializeByItk( angularErrorImage.GetPointer() ); mitkAngularErrorImage->SetVolume( angularErrorImage->GetBufferPointer() ); // evaluate directions without missing directions evaluationFilter->SetIgnoreMissingDirections(true); evaluationFilter->Update(); EvaluationFilterType::OutputImageType::Pointer angularErrorImageIgnore = evaluationFilter->GetOutput(0); mitk::Image::Pointer mitkAngularErrorImageIgnore = mitk::Image::New(); mitkAngularErrorImageIgnore->InitializeByItk( angularErrorImageIgnore.GetPointer() ); mitkAngularErrorImageIgnore->SetVolume( angularErrorImageIgnore->GetBufferPointer() ); mitk::Image::Pointer gtAngularErrorImageIgnore = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(LDFP_ERROR_IMAGE_IGNORE)->GetData()); mitk::Image::Pointer gtAngularErrorImage = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(LDFP_ERROR_IMAGE)->GetData()); mitk::Image::Pointer gtNumTestDirImage = dynamic_cast<mitk::Image*>(mitk::IOUtil::LoadDataNode(LDFP_NUM_DIRECTIONS)->GetData()); mitk::FiberBundleX::Pointer gtTestDirections = dynamic_cast<mitk::FiberBundleX*>(mitk::IOUtil::LoadDataNode(LDFP_VECTOR_FIELD)->GetData()); if (!testDirections->Equals(gtTestDirections)) { MITK_INFO << "SAVING FILES TO " << mitk::IOUtil::GetTempPath(); std::string out1 = mitk::IOUtil::GetTempPath().append("test.fib"); std::string out2 = mitk::IOUtil::GetTempPath().append("reference.fib"); mitk::FiberBundleXWriter::Pointer fibWriter = mitk::FiberBundleXWriter::New(); fibWriter->SetFileName(out1.c_str()); fibWriter->DoWrite(testDirections.GetPointer()); fibWriter->SetFileName(out2.c_str()); fibWriter->DoWrite(gtTestDirections.GetPointer()); } MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtAngularErrorImageIgnore, mitkAngularErrorImageIgnore, 0.01, true), "Check if error images are equal (ignored missing directions)."); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtAngularErrorImage, mitkAngularErrorImage, 0.01, true), "Check if error images are equal."); MITK_TEST_CONDITION_REQUIRED(testDirections->Equals(gtTestDirections), "Check if vector fields are equal."); MITK_TEST_CONDITION_REQUIRED(mitk::Equal(gtNumTestDirImage, mitkNumDirImage, 0.0001, true), "Check if num direction images are equal."); } catch (itk::ExceptionObject e) { MITK_INFO << e; return EXIT_FAILURE; } catch (std::exception e) { MITK_INFO << e.what(); return EXIT_FAILURE; } catch (...) { MITK_INFO << "ERROR!?!"; return EXIT_FAILURE; } MITK_TEST_END(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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. */ #ifndef otbLabelImageSmallRegionMergingFilter_hxx #define otbLabelImageSmallRegionMergingFilter_hxx #include "otbLabelImageSmallRegionMergingFilter.h" #include "itkImageConstIterator.h" #include "itkConstShapedNeighborhoodIterator.h" #include "itkProgressReporter.h" #include <time.h> namespace otb { template <class TInputLabelImage > PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::PersistentLabelImageSmallRegionMergingFilter() : m_Size(1) { } template <class TInputLabelImage > void PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::Reset() { m_NeighboursMapsTmp.clear(); m_NeighboursMapsTmp.resize( this->GetNumberOfThreads() ); } template <class TInputLabelImage > void PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::Synthetize() { NeigboursMapType neighboursMap; // Merge the neighbours maps from all threads for( unsigned int threadId = 0; threadId < this->GetNumberOfThreads(); threadId++) { for (auto it = m_NeighboursMapsTmp[threadId].begin(); it != m_NeighboursMapsTmp[threadId].end(); it++) { neighboursMap[ it->first ].insert( it->second.begin(), it->second.end() ); } } // For each label of the label map, find the "closest" connected label, according // to the euclidian distance between the corresponding m_labelStatistic elements. for (auto neighbours : neighboursMap) { double proximity = std::numeric_limits<double>::max(); InputLabelType label = neighbours.first; InputLabelType closestNeighbour = label; for (auto neighbour : neighbours.second) { auto statsLabel = m_LabelStatistic[ label ]; auto statsNeighbour = m_LabelStatistic[ neighbour ]; assert( statsLabel.Size() == statsNeighbour.Size() ); double distance = 0; for (unsigned int i = 0 ; i < statsLabel.Size(); i++) { distance += pow( statsLabel[i] - statsNeighbour[i] , 2); } if (distance < proximity) { proximity = distance; closestNeighbour = neighbour; } } auto curLabelLUT = FindCorrespondingLabel(label); auto adjLabelLUT = FindCorrespondingLabel(closestNeighbour); if(curLabelLUT < adjLabelLUT) { m_LUT[adjLabelLUT] = curLabelLUT; } else { m_LUT[m_LUT[curLabelLUT]] = adjLabelLUT; m_LUT[curLabelLUT] = adjLabelLUT; } } // Update the LUT for(InputLabelType label = 0; label < m_LUT.size(); ++label) { InputLabelType can = label; while(m_LUT[can] != can) { can = m_LUT[can]; } m_LUT[label] = can; } // Update Statistics for(InputLabelType label = 0; label < m_LUT.size(); ++label) { InputLabelType correspondingLabel = m_LUT[label]; if((m_LabelPopulation[label]!=0) && (correspondingLabel != label)) { m_LabelStatistic[ correspondingLabel ] = (m_LabelStatistic[correspondingLabel]*m_LabelPopulation[correspondingLabel] + m_LabelStatistic[label]*m_LabelPopulation[label] ) / (m_LabelPopulation[label]+m_LabelPopulation[correspondingLabel]); m_LabelPopulation[ correspondingLabel ] += m_LabelPopulation[ label ] ; m_LabelPopulation[ label ] = 0; } } } template <class TInputLabelImage > typename PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >::InputLabelType PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::FindCorrespondingLabel( typename PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::InputLabelType label) { auto correspondingLabel = m_LUT[label]; while (label != correspondingLabel) { label = correspondingLabel; correspondingLabel = m_LUT[correspondingLabel]; } return correspondingLabel; } template <class TInputLabelImage > void PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::GenerateInputRequestedRegion() { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); // get pointers to the input auto inputPtr = const_cast<TInputLabelImage *>(this->GetInput()); // get a copy of the input requested region auto inputRequestedRegion = inputPtr->GetRequestedRegion(); // pad the input requested region by the operator radius inputRequestedRegion.PadByRadius(1); // crop the input requested region at the input's largest possible region if (inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion())) { inputPtr->SetRequestedRegion(inputRequestedRegion); return; } else { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. // store what we tried to request (prior to trying to crop) inputPtr->SetRequestedRegion(inputRequestedRegion); // build an exception itk::InvalidRequestedRegionError e(__FILE__, __LINE__); e.SetLocation(ITK_LOCATION); e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(inputPtr); throw e; } } template <class TInputLabelImage > void PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::ThreadedGenerateData(const RegionType& outputRegionForThread, itk::ThreadIdType threadId ) { using IteratorType = itk::ImageRegionConstIterator< TInputLabelImage >; using NeighborhoodIteratorType = itk::ConstShapedNeighborhoodIterator< TInputLabelImage >; typename NeighborhoodIteratorType::RadiusType radius; radius.Fill(1); auto labelImage = this->GetInput(); IteratorType it(labelImage, outputRegionForThread); NeighborhoodIteratorType itN(radius, labelImage, outputRegionForThread); // 4 connected Neighborhood (top, bottom, left and right) typename IteratorType::OffsetType top = {{0,-1}}; itN.ActivateOffset(top); typename IteratorType::OffsetType bottom = {{0,1}}; itN.ActivateOffset(bottom); typename IteratorType::OffsetType right = {{1,0}}; itN.ActivateOffset(right); typename IteratorType::OffsetType left = {{-1,0}}; itN.ActivateOffset(left); for (it.GoToBegin(); ! it.IsAtEnd(); ++it, ++itN) { assert( !itN.IsAtEnd() ); int currentLabel = FindCorrespondingLabel(it.Get()); if ( m_LabelPopulation[currentLabel] == m_Size ) { for (auto ci = itN.Begin() ; !ci.IsAtEnd(); ci++) { int neighbourLabel = FindCorrespondingLabel(ci.Get() ); if (neighbourLabel != currentLabel) m_NeighboursMapsTmp[threadId][ currentLabel ].insert( neighbourLabel ); } } } } template <class TInputLabelImage > void PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); } template <class TInputLabelImage > LabelImageSmallRegionMergingFilter< TInputLabelImage > ::LabelImageSmallRegionMergingFilter() : m_MinSize(1) { m_SmallRegionMergingFilter = LabelImageSmallRegionMergingFilterType::New(); } template <class TInputLabelImage > void LabelImageSmallRegionMergingFilter< TInputLabelImage > ::GenerateData() { this->SetProgress(0.0); auto labelImage = this->GetInput(); m_SmallRegionMergingFilter->GetFilter()->SetInput( labelImage ); // Update the filter for all sizes. for (unsigned int size = 1; size < m_MinSize; size++) { m_SmallRegionMergingFilter->GetFilter()->SetSize( size) ; m_SmallRegionMergingFilter->Update(); this->UpdateProgress(static_cast<double>(size+1)/m_MinSize); } } } // end namespace otb #endif <commit_msg>ENH : Code review 1<commit_after>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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. */ #ifndef otbLabelImageSmallRegionMergingFilter_hxx #define otbLabelImageSmallRegionMergingFilter_hxx #include "otbLabelImageSmallRegionMergingFilter.h" #include "itkImageConstIterator.h" #include "itkConstShapedNeighborhoodIterator.h" #include "itkProgressReporter.h" #include <time.h> namespace otb { template <class TInputLabelImage > PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::PersistentLabelImageSmallRegionMergingFilter() : m_Size(1) { } template <class TInputLabelImage > void PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::Reset() { m_NeighboursMapsTmp.clear(); m_NeighboursMapsTmp.resize( this->GetNumberOfThreads() ); } template <class TInputLabelImage > void PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::Synthetize() { NeigboursMapType neighboursMap; // Merge the neighbours maps from all threads for( unsigned int threadId = 0; threadId < this->GetNumberOfThreads(); threadId++) { for (auto it = m_NeighboursMapsTmp[threadId].begin(); it != m_NeighboursMapsTmp[threadId].end(); it++) { neighboursMap[ it->first ].insert( it->second.begin(), it->second.end() ); } } // For each label of the label map, find the "closest" connected label, according // to the euclidian distance between the corresponding m_labelStatistic elements. for (auto const & neighbours : neighboursMap) { double proximity = std::numeric_limits<double>::max(); InputLabelType label = neighbours.first; InputLabelType closestNeighbour = label; for (auto const & neighbour : neighbours.second) { auto statsLabel = m_LabelStatistic[ label ]; auto statsNeighbour = m_LabelStatistic[ neighbour ]; assert( statsLabel.Size() == statsNeighbour.Size() ); double distance = 0; for (unsigned int i = 0 ; i < statsLabel.Size(); i++) { distance += (statsLabel[i] - statsNeighbour[i]) * (statsLabel[i] - statsNeighbour[i]); } if (distance < proximity) { proximity = distance; closestNeighbour = neighbour; } } auto curLabelLUT = FindCorrespondingLabel(label); auto adjLabelLUT = FindCorrespondingLabel(closestNeighbour); if(curLabelLUT < adjLabelLUT) { m_LUT[adjLabelLUT] = curLabelLUT; } else { m_LUT[m_LUT[curLabelLUT]] = adjLabelLUT; m_LUT[curLabelLUT] = adjLabelLUT; } } // Update the LUT for(InputLabelType label = 0; label < m_LUT.size(); ++label) { InputLabelType can = label; while(m_LUT[can] != can) { can = m_LUT[can]; } m_LUT[label] = can; } // Update Statistics for(InputLabelType label = 0; label < m_LUT.size(); ++label) { InputLabelType correspondingLabel = m_LUT[label]; if((m_LabelPopulation[label]!=0) && (correspondingLabel != label)) { m_LabelStatistic[ correspondingLabel ] = (m_LabelStatistic[correspondingLabel]*m_LabelPopulation[correspondingLabel] + m_LabelStatistic[label]*m_LabelPopulation[label] ) / (m_LabelPopulation[label]+m_LabelPopulation[correspondingLabel]); m_LabelPopulation[ correspondingLabel ] += m_LabelPopulation[ label ] ; m_LabelPopulation[ label ] = 0; } } } template <class TInputLabelImage > typename PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage >::InputLabelType PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::FindCorrespondingLabel( typename PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::InputLabelType label) { auto correspondingLabel = m_LUT[label]; while (label != correspondingLabel) { label = correspondingLabel; correspondingLabel = m_LUT[correspondingLabel]; } return correspondingLabel; } template <class TInputLabelImage > void PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::GenerateInputRequestedRegion() { // call the superclass' implementation of this method Superclass::GenerateInputRequestedRegion(); // get pointers to the input auto inputPtr = const_cast<TInputLabelImage *>(this->GetInput()); // get a copy of the input requested region auto inputRequestedRegion = inputPtr->GetRequestedRegion(); // pad the input requested region by the operator radius inputRequestedRegion.PadByRadius(1); // crop the input requested region at the input's largest possible region if (inputRequestedRegion.Crop(inputPtr->GetLargestPossibleRegion())) { inputPtr->SetRequestedRegion(inputRequestedRegion); return; } else { // Couldn't crop the region (requested region is outside the largest // possible region). Throw an exception. // store what we tried to request (prior to trying to crop) inputPtr->SetRequestedRegion(inputRequestedRegion); // build an exception itk::InvalidRequestedRegionError e(__FILE__, __LINE__); e.SetLocation(ITK_LOCATION); e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(inputPtr); throw e; } } template <class TInputLabelImage > void PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::ThreadedGenerateData(const RegionType& outputRegionForThread, itk::ThreadIdType threadId ) { using IteratorType = itk::ImageRegionConstIterator< TInputLabelImage >; using NeighborhoodIteratorType = itk::ConstShapedNeighborhoodIterator< TInputLabelImage >; typename NeighborhoodIteratorType::RadiusType radius; radius.Fill(1); auto labelImage = this->GetInput(); IteratorType it(labelImage, outputRegionForThread); NeighborhoodIteratorType itN(radius, labelImage, outputRegionForThread); // 4 connected Neighborhood (top, bottom, left and right) typename IteratorType::OffsetType top = {{0,-1}}; itN.ActivateOffset(top); typename IteratorType::OffsetType bottom = {{0,1}}; itN.ActivateOffset(bottom); typename IteratorType::OffsetType right = {{1,0}}; itN.ActivateOffset(right); typename IteratorType::OffsetType left = {{-1,0}}; itN.ActivateOffset(left); for (it.GoToBegin(); ! it.IsAtEnd(); ++it, ++itN) { assert( !itN.IsAtEnd() ); int currentLabel = FindCorrespondingLabel(it.Get()); if ( m_LabelPopulation[currentLabel] == m_Size ) { for (auto ci = itN.Begin() ; !ci.IsAtEnd(); ci++) { int neighbourLabel = FindCorrespondingLabel(ci.Get() ); if (neighbourLabel != currentLabel) m_NeighboursMapsTmp[threadId][ currentLabel ].insert( neighbourLabel ); } } } } template <class TInputLabelImage > void PersistentLabelImageSmallRegionMergingFilter< TInputLabelImage > ::PrintSelf(std::ostream& os, itk::Indent indent) const { Superclass::PrintSelf(os, indent); } template <class TInputLabelImage > LabelImageSmallRegionMergingFilter< TInputLabelImage > ::LabelImageSmallRegionMergingFilter() : m_MinSize(1) { m_SmallRegionMergingFilter = LabelImageSmallRegionMergingFilterType::New(); } template <class TInputLabelImage > void LabelImageSmallRegionMergingFilter< TInputLabelImage > ::GenerateData() { this->SetProgress(0.0); auto labelImage = this->GetInput(); m_SmallRegionMergingFilter->GetFilter()->SetInput( labelImage ); // Update the filter for all sizes. for (unsigned int size = 1; size < m_MinSize; size++) { m_SmallRegionMergingFilter->GetFilter()->SetSize( size) ; m_SmallRegionMergingFilter->Update(); this->UpdateProgress(static_cast<double>(size+1)/m_MinSize); } } } // end namespace otb #endif <|endoftext|>
<commit_before>/** * @file IKParameters.cpp * * @author <a href="mailto:[email protected]">Xu, Yuan</a> * Implement of parameters for IK motion */ #include "IKParameters.h" IKParameters::IKParameters() :ParameterList("IKParameters") { PARAMETER_REGISTER(footOffsetY) = 0; // stand parameter PARAMETER_REGISTER(stand.speed) = 0.01; PARAMETER_REGISTER(stand.enableStabilization) = false; PARAMETER_REGISTER(stand.stiffness) = 0.7; PARAMETER_ANGLE_REGISTER(stand.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(stand.hipOffsetX) = 15; // relax PARAMETER_REGISTER(stand.relax.enable) = true; PARAMETER_REGISTER(stand.relax.allowedDeviation) = 5; // [mm] PARAMETER_REGISTER(stand.relax.allowedRotationDeviation) = Math::fromDegrees(5);// [rad] todo: PARAMETER_ANGLE_REGISTER PARAMETER_REGISTER(stand.relax.timeBonusForCorrection) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.enable) = true; PARAMETER_REGISTER(stand.relax.jointOffsetTuning.deadTime) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.currentThreshold) = 0.3; // [A] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.minimalJointStep) = 0.0013962634; // [rad] PARAMETER_REGISTER(stand.relax.stiffnessControl.enable) = true; PARAMETER_REGISTER(stand.relax.stiffnessControl.deadTime) = 100; // [ms] PARAMETER_REGISTER(stand.relax.stiffnessControl.minAngle) = 0.08; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.maxAngle) = 2; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.minStiffness) = 0.3; PARAMETER_REGISTER(stand.relax.stiffnessControl.maxStiffness) = 1.0; // walk parameter: // General PARAMETER_ANGLE_REGISTER(walk.general.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(walk.general.hipOffsetX) = 15; PARAMETER_REGISTER(walk.general.stiffness) = 0.7; PARAMETER_REGISTER(walk.general.useArm) = false; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorLeft) = 0.4; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorRight) = 0.4; // hip trajectory geometry PARAMETER_REGISTER(walk.hip.comHeight) = 260; PARAMETER_REGISTER(walk.hip.comHeightOffset) = 0.18; PARAMETER_REGISTER(walk.hip.comRotationOffsetX) = 0; PARAMETER_REGISTER(walk.hip.ZMPOffsetY) = 5; PARAMETER_REGISTER(walk.hip.ZMPOffsetYByCharacter) = 0; // step geometry PARAMETER_REGISTER(walk.step.duration) = 300; PARAMETER_REGISTER(walk.step.doubleSupportTime) = 40; PARAMETER_REGISTER(walk.step.stepHeight) = 10; // step limits PARAMETER_REGISTER(walk.limits.maxTurnInner) = 10; PARAMETER_REGISTER(walk.limits.maxStepTurn) = 30; PARAMETER_REGISTER(walk.limits.maxStepLength) = 50; PARAMETER_REGISTER(walk.limits.maxStepLengthBack) = 50; PARAMETER_REGISTER(walk.limits.maxStepWidth) = 50; PARAMETER_REGISTER(walk.limits.maxStepChange) = 0.5; // step control PARAMETER_REGISTER(walk.limits.maxCtrlTurn) = 30; PARAMETER_REGISTER(walk.limits.maxCtrlLength) = 80; PARAMETER_REGISTER(walk.limits.maxCtrlWidth) = 50; // Stabilization //PARAMETER_REGISTER(walk.stabilization.enableFSRProtection) = true; //PARAMETER_REGISTER(walk.stabilization.enableWaitLanding) = false; //PARAMETER_REGISTER(walk.stabilization.minFSRProtectionCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxUnsupportedCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxWaitLandingCount) = 20; PARAMETER_REGISTER(walk.stabilization.emergencyStopError) = 500; PARAMETER_REGISTER(walk.stabilization.rotationStabilize) = true; PARAMETER_REGISTER(walk.stabilization.rotationP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.y) = 0; PARAMETER_REGISTER(walk.stabilization.stabilizeFeet) = true; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.x) = 0.04; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.y) = 0.035; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.x) = -0.4; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.y) = -0.3; PARAMETER_REGISTER(walk.stabilization.dynamicStepsize) = true; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeP) = -1; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeD) = 0.5; // rotation stabilize parameter PARAMETER_REGISTER(rotationStabilize.k.x) = -0.5; PARAMETER_REGISTER(rotationStabilize.k.y) = -0.2; PARAMETER_REGISTER(rotationStabilize.threshold.x) = 2; PARAMETER_REGISTER(rotationStabilize.threshold.y) = 3; // arm parameter PARAMETER_REGISTER(arm.shoulderPitchInterialSensorRate) = -10; PARAMETER_REGISTER(arm.shoulderRollInterialSensorRate) = -10; PARAMETER_REGISTER(arm.maxSpeed) = 60; PARAMETER_REGISTER(arm.alwaysEnabled) = false; PARAMETER_REGISTER(arm.kickEnabled) = true; PARAMETER_REGISTER(arm.walkEnabled) = true; PARAMETER_REGISTER(arm.takeBack) = false; PARAMETER_REGISTER(balanceCoM.kP) = 0; PARAMETER_REGISTER(balanceCoM.kI) = 0; PARAMETER_REGISTER(balanceCoM.kD) = 0; PARAMETER_REGISTER(balanceCoM.threshold) = 10; syncWithConfig(); } IKParameters::~IKParameters() { } <commit_msg>redo initial parameters<commit_after>/** * @file IKParameters.cpp * * @author <a href="mailto:[email protected]">Xu, Yuan</a> * Implement of parameters for IK motion */ #include "IKParameters.h" IKParameters::IKParameters() :ParameterList("IKParameters") { PARAMETER_REGISTER(footOffsetY) = 0; // stand parameter PARAMETER_REGISTER(stand.speed) = 0.04; PARAMETER_REGISTER(stand.enableStabilization) = true; PARAMETER_REGISTER(stand.stiffness) = 0.7; PARAMETER_ANGLE_REGISTER(stand.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(stand.hipOffsetX) = 15; // relax PARAMETER_REGISTER(stand.relax.enable) = true; PARAMETER_REGISTER(stand.relax.allowedDeviation) = 5; // [mm] PARAMETER_REGISTER(stand.relax.allowedRotationDeviation) = Math::fromDegrees(5);// [rad] todo: PARAMETER_ANGLE_REGISTER PARAMETER_REGISTER(stand.relax.timeBonusForCorrection) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.enable) = true; PARAMETER_REGISTER(stand.relax.jointOffsetTuning.deadTime) = 1000; // [ms] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.currentThreshold) = 0.3; // [A] PARAMETER_REGISTER(stand.relax.jointOffsetTuning.minimalJointStep) = 0.0013962634; // [rad] PARAMETER_REGISTER(stand.relax.stiffnessControl.enable) = true; PARAMETER_REGISTER(stand.relax.stiffnessControl.deadTime) = 100; // [ms] PARAMETER_REGISTER(stand.relax.stiffnessControl.minAngle) = 0.08; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.maxAngle) = 2; // [°] PARAMETER_REGISTER(stand.relax.stiffnessControl.minStiffness) = 0.3; PARAMETER_REGISTER(stand.relax.stiffnessControl.maxStiffness) = 1.0; // walk parameter: // General PARAMETER_ANGLE_REGISTER(walk.general.bodyPitchOffset) = 0.2; PARAMETER_REGISTER(walk.general.hipOffsetX) = 15; PARAMETER_REGISTER(walk.general.stiffness) = 0.7; PARAMETER_REGISTER(walk.general.useArm) = false; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorLeft) = 0.4; PARAMETER_REGISTER(walk.general.hipRollSingleSupFactorRight) = 0.4; // hip trajectory geometry PARAMETER_REGISTER(walk.hip.comHeight) = 260; PARAMETER_REGISTER(walk.hip.comHeightOffset) = 0.18; PARAMETER_REGISTER(walk.hip.comRotationOffsetX) = 0; PARAMETER_REGISTER(walk.hip.ZMPOffsetY) = 5; PARAMETER_REGISTER(walk.hip.ZMPOffsetYByCharacter) = 0; // step geometry PARAMETER_REGISTER(walk.step.duration) = 300; PARAMETER_REGISTER(walk.step.doubleSupportTime) = 40; PARAMETER_REGISTER(walk.step.stepHeight) = 10; // step limits PARAMETER_REGISTER(walk.limits.maxTurnInner) = 10; PARAMETER_REGISTER(walk.limits.maxStepTurn) = 30; PARAMETER_REGISTER(walk.limits.maxStepLength) = 50; PARAMETER_REGISTER(walk.limits.maxStepLengthBack) = 50; PARAMETER_REGISTER(walk.limits.maxStepWidth) = 50; PARAMETER_REGISTER(walk.limits.maxStepChange) = 0.5; // step control PARAMETER_REGISTER(walk.limits.maxCtrlTurn) = 30; PARAMETER_REGISTER(walk.limits.maxCtrlLength) = 80; PARAMETER_REGISTER(walk.limits.maxCtrlWidth) = 50; // Stabilization //PARAMETER_REGISTER(walk.stabilization.enableFSRProtection) = true; //PARAMETER_REGISTER(walk.stabilization.enableWaitLanding) = false; //PARAMETER_REGISTER(walk.stabilization.minFSRProtectionCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxUnsupportedCount) = 0; //PARAMETER_REGISTER(walk.stabilization.maxWaitLandingCount) = 20; PARAMETER_REGISTER(walk.stabilization.emergencyStopError) = 500; PARAMETER_REGISTER(walk.stabilization.rotationStabilize) = true; PARAMETER_REGISTER(walk.stabilization.rotationP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationVelocityP.y) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.x) = 0; PARAMETER_REGISTER(walk.stabilization.rotationD.y) = 0; PARAMETER_REGISTER(walk.stabilization.stabilizeFeet) = true; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.x) = 0.04; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetP.y) = 0.035; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.x) = -0.4; PARAMETER_REGISTER(walk.stabilization.stabilizeFeetD.y) = -0.3; PARAMETER_REGISTER(walk.stabilization.dynamicStepsize) = true; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeP) = -1; PARAMETER_REGISTER(walk.stabilization.dynamicStepsizeD) = 0.5; // rotation stabilize parameter PARAMETER_REGISTER(rotationStabilize.k.x) = -0.5; PARAMETER_REGISTER(rotationStabilize.k.y) = -0.2; PARAMETER_REGISTER(rotationStabilize.threshold.x) = 2; PARAMETER_REGISTER(rotationStabilize.threshold.y) = 3; // arm parameter PARAMETER_REGISTER(arm.shoulderPitchInterialSensorRate) = -10; PARAMETER_REGISTER(arm.shoulderRollInterialSensorRate) = -10; PARAMETER_REGISTER(arm.maxSpeed) = 60; PARAMETER_REGISTER(arm.alwaysEnabled) = false; PARAMETER_REGISTER(arm.kickEnabled) = true; PARAMETER_REGISTER(arm.walkEnabled) = true; PARAMETER_REGISTER(arm.takeBack) = false; PARAMETER_REGISTER(balanceCoM.kP) = 0; PARAMETER_REGISTER(balanceCoM.kI) = 0; PARAMETER_REGISTER(balanceCoM.kD) = 0; PARAMETER_REGISTER(balanceCoM.threshold) = 10; syncWithConfig(); } IKParameters::~IKParameters() { } <|endoftext|>
<commit_before><commit_msg>Add the initial template of answer to question 5.1<commit_after><|endoftext|>
<commit_before>// // DialogueBoxSystem.cpp // Chilli Source // Created by Ian Copland on 04/03/2014. // // The MIT License (MIT) // // Copyright (c) 2014 Tag Games Limited // // 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. // #ifdef CS_TARGETPLATFORM_ANDROID #include <CSBackend/Platform/Android/Main/JNI/Core/DialogueBox/DialogueBoxSystem.h> #include <CSBackend/Platform/Android/Main/JNI/Core/DialogueBox/DialogueBoxJavaInterface.h> #include <CSBackend/Platform/Android/Main/JNI/Core/Java/JavaInterfaceManager.h> #include <ChilliSource/Core/Base/Application.h> #include <ChilliSource/Core/Base/PlatformSystem.h> namespace CSBackend { namespace Android { CS_DEFINE_NAMEDTYPE(DialogueBoxSystem); //---------------------------------------------------- //---------------------------------------------------- DialogueBoxSystem::DialogueBoxSystem() { m_dialogueBoxJI = JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<DialogueBoxJavaInterface>(); if (m_dialogueBoxJI == nullptr) { m_dialogueBoxJI = std::make_shared<DialogueBoxJavaInterface>(); JavaInterfaceManager::GetSingletonPtr()->AddJavaInterface(m_dialogueBoxJI); } } //---------------------------------------------------- //---------------------------------------------------- bool DialogueBoxSystem::IsA(ChilliSource::InterfaceIDType in_interfaceId) const { return (DialogueBoxSystem::InterfaceID == in_interfaceId || ChilliSource::DialogueBoxSystem::InterfaceID == in_interfaceId); } //----------------------------------------------------- //----------------------------------------------------- void DialogueBoxSystem::ShowSystemDialogue(u32 in_id, const ChilliSource::DialogueBoxSystem::DialogueDelegate& in_delegate, const std::string& in_title, const std::string& in_message, const std::string& in_confirm) { m_dialogueBoxJI->ShowSystemDialogue(in_id, in_title, in_message, in_confirm); m_activeSysConfirmDelegate = in_delegate; } //----------------------------------------------------- //----------------------------------------------------- void DialogueBoxSystem::ShowSystemConfirmDialogue(u32 in_id, const ChilliSource::DialogueBoxSystem::DialogueDelegate& in_delegate, const std::string& in_title, const std::string& in_message, const std::string& in_confirm, const std::string& in_cancel) { m_dialogueBoxJI->ShowSystemConfirmDialogue(in_id, in_title, in_message, in_confirm, in_cancel); m_activeSysConfirmDelegate = in_delegate; } //----------------------------------------------------- //----------------------------------------------------- void DialogueBoxSystem::MakeToast(const std::string& in_text) { m_dialogueBoxJI->MakeToast(in_text); } //------------------------------------------------------ //------------------------------------------------------ void DialogueBoxSystem::OnSystemConfirmDialogueResult(u32 in_id, ChilliSource::DialogueBoxSystem::DialogueResult in_result) { if(m_activeSysConfirmDelegate) { m_activeSysConfirmDelegate(in_id, in_result); m_activeSysConfirmDelegate = nullptr; } } //----------------------------------------------------- //----------------------------------------------------- DialogueBoxSystem::~DialogueBoxSystem() { } } } #endif <commit_msg>Android now uses system thread scheduling for dialogue boxes.<commit_after>// // DialogueBoxSystem.cpp // Chilli Source // Created by Ian Copland on 04/03/2014. // // The MIT License (MIT) // // Copyright (c) 2014 Tag Games Limited // // 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. // #ifdef CS_TARGETPLATFORM_ANDROID #include <CSBackend/Platform/Android/Main/JNI/Core/DialogueBox/DialogueBoxSystem.h> #include <CSBackend/Platform/Android/Main/JNI/Core/DialogueBox/DialogueBoxJavaInterface.h> #include <CSBackend/Platform/Android/Main/JNI/Core/Java/JavaInterfaceManager.h> #include <ChilliSource/Core/Threading.h> #include <ChilliSource/Core/Base/Application.h> #include <ChilliSource/Core/Base/PlatformSystem.h> namespace CSBackend { namespace Android { CS_DEFINE_NAMEDTYPE(DialogueBoxSystem); //---------------------------------------------------- //---------------------------------------------------- DialogueBoxSystem::DialogueBoxSystem() { m_dialogueBoxJI = JavaInterfaceManager::GetSingletonPtr()->GetJavaInterface<DialogueBoxJavaInterface>(); if (m_dialogueBoxJI == nullptr) { m_dialogueBoxJI = std::make_shared<DialogueBoxJavaInterface>(); JavaInterfaceManager::GetSingletonPtr()->AddJavaInterface(m_dialogueBoxJI); } } //---------------------------------------------------- //---------------------------------------------------- bool DialogueBoxSystem::IsA(ChilliSource::InterfaceIDType in_interfaceId) const { return (DialogueBoxSystem::InterfaceID == in_interfaceId || ChilliSource::DialogueBoxSystem::InterfaceID == in_interfaceId); } //----------------------------------------------------- //----------------------------------------------------- void DialogueBoxSystem::ShowSystemDialogue(u32 in_id, const ChilliSource::DialogueBoxSystem::DialogueDelegate& in_delegate, const std::string& in_title, const std::string& in_message, const std::string& in_confirm) { CS::Application::Get()->GetTaskScheduler()->ScheduleTask(CS::TaskType::k_system, [=](const CS::TaskContext& in_taskContext) { m_dialogueBoxJI->ShowSystemDialogue(in_id, in_title, in_message, in_confirm); m_activeSysConfirmDelegate = in_delegate; }); } //----------------------------------------------------- //----------------------------------------------------- void DialogueBoxSystem::ShowSystemConfirmDialogue(u32 in_id, const ChilliSource::DialogueBoxSystem::DialogueDelegate& in_delegate, const std::string& in_title, const std::string& in_message, const std::string& in_confirm, const std::string& in_cancel) { CS::Application::Get()->GetTaskScheduler()->ScheduleTask(CS::TaskType::k_system, [=](const CS::TaskContext& in_taskContext) { m_dialogueBoxJI->ShowSystemConfirmDialogue(in_id, in_title, in_message, in_confirm, in_cancel); m_activeSysConfirmDelegate = in_delegate; }); } //----------------------------------------------------- //----------------------------------------------------- void DialogueBoxSystem::MakeToast(const std::string& in_text) { CS::Application::Get()->GetTaskScheduler()->ScheduleTask(CS::TaskType::k_system, [=](const CS::TaskContext& in_taskContext) { m_dialogueBoxJI->MakeToast(in_text); }); } //------------------------------------------------------ //------------------------------------------------------ void DialogueBoxSystem::OnSystemConfirmDialogueResult(u32 in_id, ChilliSource::DialogueBoxSystem::DialogueResult in_result) { CS::Application::Get()->GetTaskScheduler()->ScheduleTask(CS::TaskType::k_system, [=](const CS::TaskContext& in_taskContext) { if (m_activeSysConfirmDelegate) { m_activeSysConfirmDelegate(in_id, in_result); m_activeSysConfirmDelegate = nullptr; } }); } //----------------------------------------------------- //----------------------------------------------------- DialogueBoxSystem::~DialogueBoxSystem() { } } } #endif <|endoftext|>
<commit_before> #include <random> #include "../../str_util.hpp" #include "../../no_rt_util.h" #include "../../tbl.hpp" #include "../LavaFlow.hpp" enum Slots { GAUSS_IDXVERTS_OUT = 0 //GAUSS_PARAMS_IN = 0, //GAUSS_IDXVERTS_OUT = 1 }; namespace RNG { using rng_t = ::std::mt19937; using urng_t = ::std::unique_ptr<rng_t>; //extern __declspec(thread) rng_t* m_genPtr; // //void Init(int s); //void Destruct(); rng_t gen(0); rng_t* m_genPtr = &gen; //nullptr; void Init(int s) { //if (m_genPtr == nullptr) { // m_genPtr = new rng_t(s); //} } void Destruct() { //if(m_genPtr != nullptr) // delete m_genPtr; } } float randomf(float lo, float hi) { ::std::uniform_real_distribution<float> dis(lo, hi); return dis(*RNG::m_genPtr); } void PrintLavaMem(LavaMem lm) { if(lm.ptr) printf("\n addr: %llu data addr: %llu ref count: %llu size bytes: %llu \n", (u64)(lm.ptr), (u64)(lm.data()), (u64)lm.refCount(), (u64)lm.sizeBytes() ); } void PrintTblMem(tbl const& t) { if( !t.m_mem ){ printf("nullptr\n"); return; } LavaMem lm; lm.ptr = (void*)( (u8*)t.memStart() - 16 ); PrintLavaMem(lm); //assert(lm.refCount() < 1000); // //lm.fromDataAddr( (u64)t.memStart() ); } extern "C" { const char* InTypes[] = {"IdxVerts", nullptr}; // This array contains the type that each slot of the same index will accept as input. const char* InNames[] = {"Gaussian Slot In", nullptr}; // This array contains the names of each input slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing. const char* OutTypes[] = {"IdxVerts", nullptr}; // This array contains the types that are output in each slot of the same index const char* OutNames[] = {"Gaussian Slot Out", nullptr}; // This array contains the names of each output slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing. void GaussConstruct() { RNG::Init(0); } void GaussDestruct() { RNG::Destruct(); } uint64_t Gaussian(LavaParams const* lp, LavaFrame const* in, lava_threadQ* out) noexcept { using namespace std; u32 i=0; while( LavaNxtPckt(in, &i) ) { tbl gParams = LavaTblFromPckt(lp, in, i); //f32 var = gParams("Variance"); //f32 ev = gParams("Expected Value"); //u64 verts = gParams("Vertex Count"); f32 var = randomf(0.01f, 1.f); f32 ev = 0.f; //randomf(0f, 0.2f); u64 verts = 512; tbl gcurve = LavaMakeTbl(lp); gcurve("type") = tbl::StrToInt("IdxVerts"); gcurve("mode") = (u64)0; // GL_POINTS for now // needs to be openGL lines - GL_LINES - 0x01 tbl ind(verts*2 - 1, (u32)0u); tbl px(verts, 0.f); tbl py(verts, 0.f); tbl cg(verts, 1.f); f32 vrecip = 1.f / verts; f32 coeff = 1.f / sqrtf(2*PIf*var); TO(verts,i){ f32 x = ( (f32)i - (verts/2.f) ) * vrecip * 4.f; f32 eExp = -( (x*x)/(2.f*var) ); f32 y = coeff * expf( eExp ); px[i] = x + ev; py[i] = y; } u64 indsz = ind.size(); for(u64 i=0; i < verts-1; ++i){ ind[i*2] = (u32)i; ind[i*2+1] = (u32)(i+1); } gcurve("positions x") = &px; gcurve("positions y") = &py; gcurve("colors green") = &cg; gcurve("colors blue") = &cg; gcurve("indices") = &ind; gcurve.flatten(); out->push( LavaTblToOut(gcurve, GAUSS_IDXVERTS_OUT) ); // this demonstrates how to output a tbl into the first output slot } return 1; } LavaNode LavaNodes[] = { { Gaussian, // function GaussConstruct, // constructor - this can be set to nullptr if not needed GaussDestruct, // destructor - this can also be set to nullptr LavaNode::FLOW, // node_type - this should be eighther LavaNode::MSG (will be run even without input packets) or LavaNode::FLOW (will be run only when at least one packet is available for input) "Gaussian", // name InTypes, // in_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr InNames, // in_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr OutTypes, // out_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr OutNames, // out_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr nullptr, // description 0 // version }, LavaNodeListEnd // This is a constant that has all the members of the LavaNode struct set to 0 or nullptr - it is used as a special value that ends the static list of LavaNodes. This negates the need for a separate static variable that gives the size of the list, which would be have to be kept in sync and therefore be error prone. }; __declspec(dllexport) LavaNode* GetLavaNodes() { return (LavaNode*)LavaNodes; } } // //PrintTblMem(gcurve); //u32 verts = 8; // //tbl pz(verts, 0.f); // //gcurve("positions z") = &pz; //tbl inputTbl( (void*)(in->packets[i].val.value) ); // //for(auto& kv : gaussParams){ // this loop demonstrates how to iterate through non-empty map elements //} <commit_msg>gaussian node packet index changed to be i - 1<commit_after> #include <random> #include "../../str_util.hpp" #include "../../no_rt_util.h" #include "../../tbl.hpp" #include "../LavaFlow.hpp" enum Slots { GAUSS_IDXVERTS_OUT = 0 //GAUSS_PARAMS_IN = 0, //GAUSS_IDXVERTS_OUT = 1 }; namespace RNG { using rng_t = ::std::mt19937; using urng_t = ::std::unique_ptr<rng_t>; //extern __declspec(thread) rng_t* m_genPtr; // //void Init(int s); //void Destruct(); rng_t gen(0); rng_t* m_genPtr = &gen; //nullptr; void Init(int s) { //if (m_genPtr == nullptr) { // m_genPtr = new rng_t(s); //} } void Destruct() { //if(m_genPtr != nullptr) // delete m_genPtr; } } float randomf(float lo, float hi) { ::std::uniform_real_distribution<float> dis(lo, hi); return dis(*RNG::m_genPtr); } void PrintLavaMem(LavaMem lm) { if(lm.ptr) printf("\n addr: %llu data addr: %llu ref count: %llu size bytes: %llu \n", (u64)(lm.ptr), (u64)(lm.data()), (u64)lm.refCount(), (u64)lm.sizeBytes() ); } void PrintTblMem(tbl const& t) { if( !t.m_mem ){ printf("nullptr\n"); return; } LavaMem lm; lm.ptr = (void*)( (u8*)t.memStart() - 16 ); PrintLavaMem(lm); //assert(lm.refCount() < 1000); // //lm.fromDataAddr( (u64)t.memStart() ); } extern "C" { const char* InTypes[] = {"IdxVerts", nullptr}; // This array contains the type that each slot of the same index will accept as input. const char* InNames[] = {"Gaussian Slot In", nullptr}; // This array contains the names of each input slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing. const char* OutTypes[] = {"IdxVerts", nullptr}; // This array contains the types that are output in each slot of the same index const char* OutNames[] = {"Gaussian Slot Out", nullptr}; // This array contains the names of each output slot as a string that can be used by the GUI. It will show up as a label to each slot and be used when visualizing. void GaussConstruct() { RNG::Init(0); } void GaussDestruct() { RNG::Destruct(); } uint64_t Gaussian(LavaParams const* lp, LavaFrame const* in, lava_threadQ* out) noexcept { using namespace std; u32 i=0; while( LavaNxtPckt(in, &i) ) { tbl gParams = LavaTblFromPckt(lp, in, i-1); //f32 var = gParams("Variance"); //f32 ev = gParams("Expected Value"); //u64 verts = gParams("Vertex Count"); f32 var = randomf(0.01f, 1.f); f32 ev = 0.f; //randomf(0f, 0.2f); u64 verts = 512; tbl gcurve = LavaMakeTbl(lp); gcurve("type") = tbl::StrToInt("IdxVerts"); gcurve("mode") = (u64)0; // GL_POINTS for now // needs to be openGL lines - GL_LINES - 0x01 tbl ind(verts*2 - 1, (u32)0u); tbl px(verts, 0.f); tbl py(verts, 0.f); tbl cg(verts, 1.f); f32 vrecip = 1.f / verts; f32 coeff = 1.f / sqrtf(2*PIf*var); TO(verts,i){ f32 x = ( (f32)i - (verts/2.f) ) * vrecip * 4.f; f32 eExp = -( (x*x)/(2.f*var) ); f32 y = coeff * expf( eExp ); px[i] = x + ev; py[i] = y; } u64 indsz = ind.size(); for(u64 i=0; i < verts-1; ++i){ ind[i*2] = (u32)i; ind[i*2+1] = (u32)(i+1); } gcurve("positions x") = &px; gcurve("positions y") = &py; gcurve("colors green") = &cg; gcurve("colors blue") = &cg; gcurve("indices") = &ind; gcurve.flatten(); out->push( LavaTblToOut(gcurve, GAUSS_IDXVERTS_OUT) ); // this demonstrates how to output a tbl into the first output slot } return 1; } LavaNode LavaNodes[] = { { Gaussian, // function GaussConstruct, // constructor - this can be set to nullptr if not needed GaussDestruct, // destructor - this can also be set to nullptr LavaNode::FLOW, // node_type - this should be eighther LavaNode::MSG (will be run even without input packets) or LavaNode::FLOW (will be run only when at least one packet is available for input) "Gaussian", // name InTypes, // in_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr InNames, // in_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr OutTypes, // out_types - this can be set to nullptr instead of pointing to a list that has the first item as nullptr OutNames, // out_names - this can be set to nullptr instead of pointing to a list that has the first item as nullptr nullptr, // description 0 // version }, LavaNodeListEnd // This is a constant that has all the members of the LavaNode struct set to 0 or nullptr - it is used as a special value that ends the static list of LavaNodes. This negates the need for a separate static variable that gives the size of the list, which would be have to be kept in sync and therefore be error prone. }; __declspec(dllexport) LavaNode* GetLavaNodes() { return (LavaNode*)LavaNodes; } } // //PrintTblMem(gcurve); //u32 verts = 8; // //tbl pz(verts, 0.f); // //gcurve("positions z") = &pz; //tbl inputTbl( (void*)(in->packets[i].val.value) ); // //for(auto& kv : gaussParams){ // this loop demonstrates how to iterate through non-empty map elements //} <|endoftext|>
<commit_before>#include "mmd/pmx/mesh.hpp" #include "../stream.hpp" namespace mmd { namespace pmx { Vertex::Vertex() {} void Vertex::load(Fs *fs, Header *header) { Stream *stream = (Stream *)fs; position = stream->readVec3(); normal = stream->readVec3(); uv = stream->readVec2(); for (int i = 0; i < header->additional; ++i) { addition[i] = stream->readVec4(); } boneType = stream->readSByte(); switch (boneType) { case 0: BDEF.bone[0] = stream->readIndex(header->bone); break; case 1: BDEF.bone[0] = stream->readIndex(header->bone); BDEF.bone[1] = stream->readIndex(header->bone); BDEF.weight[0] = stream->readFloat(); BDEF.weight[1] = 1.0f - BDEF.weight[0]; break; case 2: case 4: for (int i = 0; i < 4; ++i) { BDEF.bone[i] = stream->readIndex(header->bone); } for (int i = 0; i < 4; ++i) { BDEF.weight[i] = stream->readFloat(); } break; case 3: SDEF.bone[0] = stream->readIndex(header->bone); SDEF.bone[1] = stream->readIndex(header->bone); SDEF.weight[0] = stream->readFloat(); SDEF.weight[1] = 1.0f - SDEF.weight[0]; SDEF.C = stream->readVec3(); SDEF.R0 = stream->readVec3(); SDEF.R1 = stream->readVec3(); break; default: FAIL << "Invalid bone type!"; } edge = stream->readFloat(); } void Surface::load(Fs *fs, Header *header) { Stream *stream = (Stream *)fs; A = stream->readUIndex(header->vertex); B = stream->readUIndex(header->vertex); C = stream->readUIndex(header->vertex); } void Mesh::load(Fs *fs, Header *header) { LOG << "Load Mesh"; Stream *stream = (Stream *)fs; int n = stream->readInt(); vertex.resize(n); for (int i = 0; i < n; ++i) { vertex[i].load(fs, header); } n = stream->readInt() / 3; surface.resize(n); for (int i = 0; i < n; ++i) { surface[i].load(fs, header); } LOG << "---------------------"; LOG << "Mesh infomation"; LOG << "---------------------"; LOG << "vertices: " << vertex.size(); LOG << "surfaces: " << surface.size(); LOG << "---------------------"; } } /* pmx */ } /* mmd */ <commit_msg>solve a bug<commit_after>#include "mmd/pmx/mesh.hpp" #include "../stream.hpp" namespace mmd { namespace pmx { Vertex::Vertex() {} void Vertex::load(Fs *fs, Header *header) { Stream *stream = (Stream *)fs; position = stream->readVec3(); normal = stream->readVec3(); uv = stream->readVec2(); for (int i = 0; i < header->additional; ++i) { addition[i] = stream->readVec4(); } boneType = stream->readSByte(); memset(&SDEF, 0, sizeof(SDEF)); switch (boneType) { case 0: BDEF.bone[0] = stream->readIndex(header->bone); BDEF.weight[0] = 1.0f; break; case 1: BDEF.bone[0] = stream->readIndex(header->bone); BDEF.bone[1] = stream->readIndex(header->bone); BDEF.weight[0] = stream->readFloat(); BDEF.weight[1] = 1.0f - BDEF.weight[0]; break; case 2: case 4: for (int i = 0; i < 4; ++i) { BDEF.bone[i] = stream->readIndex(header->bone); } for (int i = 0; i < 4; ++i) { BDEF.weight[i] = stream->readFloat(); } break; case 3: SDEF.bone[0] = stream->readIndex(header->bone); SDEF.bone[1] = stream->readIndex(header->bone); SDEF.weight[0] = stream->readFloat(); SDEF.weight[1] = 1.0f - SDEF.weight[0]; SDEF.C = stream->readVec3(); SDEF.R0 = stream->readVec3(); SDEF.R1 = stream->readVec3(); break; default: FAIL << "Invalid bone type!"; } edge = stream->readFloat(); } void Surface::load(Fs *fs, Header *header) { Stream *stream = (Stream *)fs; A = stream->readUIndex(header->vertex); B = stream->readUIndex(header->vertex); C = stream->readUIndex(header->vertex); } void Mesh::load(Fs *fs, Header *header) { LOG << "Load Mesh"; Stream *stream = (Stream *)fs; int n = stream->readInt(); vertex.resize(n); for (int i = 0; i < n; ++i) { vertex[i].load(fs, header); } n = stream->readInt() / 3; surface.resize(n); for (int i = 0; i < n; ++i) { surface[i].load(fs, header); } LOG << "---------------------"; LOG << "Mesh infomation"; LOG << "---------------------"; LOG << "vertices: " << vertex.size(); LOG << "surfaces: " << surface.size(); LOG << "---------------------"; } } /* pmx */ } /* mmd */ <|endoftext|>
<commit_before>/* Copyright (C) 2014 Torbjorn Rognes This program 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. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Contact: Torbjorn Rognes <[email protected]>, Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "vsearch.h" /* Unable to get the Mac gcc compiler v 4.2.1 produce the real popcnt instruction. Therefore resorting to assembly code. */ #define popcnt_asm(x,y) \ __asm__ __volatile__ ("popcnt %1,%0" : "=r"(y) : "r"(x)); unsigned long popcount(unsigned long x) { unsigned long y; popcnt_asm(x,y); return y; } void pprint(__m128i x) { unsigned char * p = (unsigned char *) & x; printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); } void pshow(char * name, __m128i x) { printf("%s: ", name); pprint(x); printf("\n"); } unsigned long popcount_128(__m128i x) { // pshow("x", x); __m128i mask1 = _mm_set_epi8(0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55); __m128i mask2 = _mm_set_epi8(0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33); __m128i mask4 = _mm_set_epi8(0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f); __m128i zero = _mm_setzero_si128(); /* add together 2 bits: 0+1, 2+3, 3+4, ... 126+127 */ __m128i a = _mm_srli_epi64(x, 1); __m128i b = _mm_and_si128(x, mask1); __m128i c = _mm_and_si128(a, mask1); __m128i d = _mm_add_epi64(b, c); // pshow("d", d); /* add together 4 bits: (0+1)+(2+3), ... (124+125)+(126+127) */ __m128i e = _mm_srli_epi64(d, 2); __m128i f = _mm_and_si128(d, mask2); __m128i g = _mm_and_si128(e, mask2); __m128i h = _mm_add_epi64(f, g); // pshow("h", h); /* add together 8 bits: (0..3)+(4..7), ... (120..123)+(124..127) */ __m128i i = _mm_srli_epi64(h, 4); __m128i j = _mm_add_epi64(h, i); __m128i k = _mm_and_si128(j, mask4); // pshow("k", k); /* add together 8 bytes: (0..63) and (64..127) */ __m128i l = _mm_sad_epu8(k, zero); // pshow("l", l); /* add together 64-bit values into final 128 bit value */ __m128i m = _mm_srli_si128(l, 8); __m128i n = _mm_add_epi64(m, l); // pshow("n", n); /* return low 64 bits - return value is always in range 0 to 128 */ unsigned long zz = (unsigned long) _mm_movepi64_pi64(n); // printf("z: %lu\n", zz); return zz; } <commit_msg>Update popcount.cc<commit_after>/* Copyright (C) 2014 Torbjorn Rognes This program 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. 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Contact: Torbjorn Rognes <[email protected]>, Department of Informatics, University of Oslo, PO Box 1080 Blindern, NO-0316 Oslo, Norway */ #include "vsearch.h" /* Unable to get the Mac gcc compiler v 4.2.1 to produce the real popcnt instruction. Therefore resorting to assembly code. */ #define popcnt_asm(x,y) \ __asm__ __volatile__ ("popcnt %1,%0" : "=r"(y) : "r"(x)); unsigned long popcount(unsigned long x) { unsigned long y; popcnt_asm(x,y); return y; } void pprint(__m128i x) { unsigned char * p = (unsigned char *) & x; printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); printf("%02x", *p++); } void pshow(char * name, __m128i x) { printf("%s: ", name); pprint(x); printf("\n"); } unsigned long popcount_128(__m128i x) { // pshow("x", x); __m128i mask1 = _mm_set_epi8(0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55); __m128i mask2 = _mm_set_epi8(0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33); __m128i mask4 = _mm_set_epi8(0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f); __m128i zero = _mm_setzero_si128(); /* add together 2 bits: 0+1, 2+3, 3+4, ... 126+127 */ __m128i a = _mm_srli_epi64(x, 1); __m128i b = _mm_and_si128(x, mask1); __m128i c = _mm_and_si128(a, mask1); __m128i d = _mm_add_epi64(b, c); // pshow("d", d); /* add together 4 bits: (0+1)+(2+3), ... (124+125)+(126+127) */ __m128i e = _mm_srli_epi64(d, 2); __m128i f = _mm_and_si128(d, mask2); __m128i g = _mm_and_si128(e, mask2); __m128i h = _mm_add_epi64(f, g); // pshow("h", h); /* add together 8 bits: (0..3)+(4..7), ... (120..123)+(124..127) */ __m128i i = _mm_srli_epi64(h, 4); __m128i j = _mm_add_epi64(h, i); __m128i k = _mm_and_si128(j, mask4); // pshow("k", k); /* add together 8 bytes: (0..63) and (64..127) */ __m128i l = _mm_sad_epu8(k, zero); // pshow("l", l); /* add together 64-bit values into final 128 bit value */ __m128i m = _mm_srli_si128(l, 8); __m128i n = _mm_add_epi64(m, l); // pshow("n", n); /* return low 64 bits - return value is always in range 0 to 128 */ unsigned long zz = (unsigned long) _mm_movepi64_pi64(n); // printf("z: %lu\n", zz); return zz; } <|endoftext|>
<commit_before>/* Copyright (C) 2007 <SWGEmu> This File is part of Core3. 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Linking Engine3 statically or dynamically with other modules is making a combined work based on Engine3. Thus, the terms and conditions of the GNU Lesser General Public License cover the whole combination. In addition, as a special exception, the copyright holders of Engine3 give you permission to combine Engine3 program with free software programs or libraries that are released under the GNU LGPL and with code included in the standard release of Core3 under the GNU LGPL license (or modified versions of such code, with unchanged license). You may copy and distribute such a system following the terms of the GNU LGPL for Engine3 and the licenses of the other code concerned, provided that you include the source code of that other code when and as the GNU LGPL requires distribution of source code. Note that people who make modified versions of Engine3 are not obligated to grant this special exception for their modified versions; it is their choice whether to do so. The GNU Lesser General Public License gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception. */ #include "server/zone/managers/director/ScreenPlayObserver.h" #include "DirectorManager.h" #include "engine/lua/LuaPanicException.h" int ScreenPlayObserverImplementation::notifyObserverEvent(uint32 eventType, Observable* observable, ManagedObject* arg1, int64 arg2) { int ret = 1; try { Lua* lua = DirectorManager::instance()->getLuaInstance(); LuaFunction startScreenPlay(lua->getLuaState(), play, key, 1); startScreenPlay << observable; startScreenPlay << arg1; startScreenPlay << arg2; startScreenPlay.callFunction(); if (lua_gettop(lua->getLuaState()) == 0) { Logger::console.error("ScreenPlayObserverImplementation::notifyObserverEvent didnt return a value from " + play + ":" + key); assert(0 && "no return value in ScreenPlayObserverImplementation::notifyObserverEvent"); return 1; } assert(lua_isnumber(lua->getLuaState(), -1)); ret = lua->getIntParameter(lua->getLuaState()); } catch (LuaPanicException& panic) { Logger::console.error("Panic exception: " + panic.getMessage() + " while trying to run SceenPlayObserver: " + play + ":" + key); } //1 remove observer, 0 keep observer return ret; } <commit_msg>[added] better error printing on observer assert<commit_after>/* Copyright (C) 2007 <SWGEmu> This File is part of Core3. 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Linking Engine3 statically or dynamically with other modules is making a combined work based on Engine3. Thus, the terms and conditions of the GNU Lesser General Public License cover the whole combination. In addition, as a special exception, the copyright holders of Engine3 give you permission to combine Engine3 program with free software programs or libraries that are released under the GNU LGPL and with code included in the standard release of Core3 under the GNU LGPL license (or modified versions of such code, with unchanged license). You may copy and distribute such a system following the terms of the GNU LGPL for Engine3 and the licenses of the other code concerned, provided that you include the source code of that other code when and as the GNU LGPL requires distribution of source code. Note that people who make modified versions of Engine3 are not obligated to grant this special exception for their modified versions; it is their choice whether to do so. The GNU Lesser General Public License gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception. */ #include "server/zone/managers/director/ScreenPlayObserver.h" #include "DirectorManager.h" #include "engine/lua/LuaPanicException.h" int ScreenPlayObserverImplementation::notifyObserverEvent(uint32 eventType, Observable* observable, ManagedObject* arg1, int64 arg2) { int ret = 1; try { Lua* lua = DirectorManager::instance()->getLuaInstance(); LuaFunction startScreenPlay(lua->getLuaState(), play, key, 1); startScreenPlay << observable; startScreenPlay << arg1; startScreenPlay << arg2; startScreenPlay.callFunction(); if (lua_gettop(lua->getLuaState()) == 0) { Logger::console.error("ScreenPlayObserverImplementation::notifyObserverEvent didnt return a value from " + play + ":" + key); assert(0 && "no return value in ScreenPlayObserverImplementation::notifyObserverEvent"); return 1; } if (!lua_isnumber(lua->getLuaState(), -1)) { assert(printf("ScreenPlayObserver %s:%s didnt return a valid value in an observer handler\n", play.toCharArray(), key.toCharArray()) && 0); } ret = lua->getIntParameter(lua->getLuaState()); } catch (LuaPanicException& panic) { Logger::console.error("Panic exception: " + panic.getMessage() + " while trying to run SceenPlayObserver: " + play + ":" + key); } //1 remove observer, 0 keep observer return ret; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "base/file_util.h" #include "base/scoped_temp_dir.h" #include "base/test/thread_test_helper.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" #include "content/browser/in_process_webkit/dom_storage_context.h" #include "content/browser/in_process_webkit/webkit_context.h" using content::BrowserContext; using content::BrowserThread; typedef InProcessBrowserTest DOMStorageBrowserTest; // In proc browser test is needed here because ClearLocalState indirectly calls // WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin. IN_PROC_BROWSER_TEST_F(DOMStorageBrowserTest, ClearLocalState) { // Create test files. ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath domstorage_dir = temp_dir.path().Append( DOMStorageContext::kLocalStorageDirectory); ASSERT_TRUE(file_util::CreateDirectory(domstorage_dir)); FilePath::StringType file_name_1(FILE_PATH_LITERAL("http_foo_0")); file_name_1.append(DOMStorageContext::kLocalStorageExtension); FilePath::StringType file_name_2(FILE_PATH_LITERAL("chrome-extension_foo_0")); file_name_2.append(DOMStorageContext::kLocalStorageExtension); FilePath temp_file_path_1 = domstorage_dir.Append(file_name_1); FilePath temp_file_path_2 = domstorage_dir.Append(file_name_2); ASSERT_EQ(1, file_util::WriteFile(temp_file_path_1, ".", 1)); ASSERT_EQ(1, file_util::WriteFile(temp_file_path_2, "o", 1)); // Create the scope which will ensure we run the destructor of the webkit // context which should trigger the clean up. { TestingProfile profile; WebKitContext* webkit_context = BrowserContext::GetWebKitContext(&profile); webkit_context->dom_storage_context()-> set_data_path_for_testing(temp_dir.path()); webkit_context->set_clear_local_state_on_exit(true); } // Make sure we wait until the destructor has run. scoped_refptr<base::ThreadTestHelper> helper( new base::ThreadTestHelper( BrowserThread::GetMessageLoopProxyForThread( BrowserThread::WEBKIT_DEPRECATED))); ASSERT_TRUE(helper->Run()); // Because we specified https for scheme to be skipped the second file // should survive and the first go into vanity. ASSERT_FALSE(file_util::PathExists(temp_file_path_1)); ASSERT_TRUE(file_util::PathExists(temp_file_path_2)); } <commit_msg>Mark DOMStorageBrowserTest.ClearLocalState flaky on Mac<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_path.h" #include "base/file_util.h" #include "base/scoped_temp_dir.h" #include "base/test/thread_test_helper.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" #include "content/browser/in_process_webkit/dom_storage_context.h" #include "content/browser/in_process_webkit/webkit_context.h" using content::BrowserContext; using content::BrowserThread; typedef InProcessBrowserTest DOMStorageBrowserTest; #if defined(OS_MACOSX) // http://crbug.com/115150. On Mac, failure rate is about 30% currently. #define MAYBE_ClearLocalState FLAKY_ClearLocalState #else #define MAYBE_ClearLocalState ClearLocalState #endif // In proc browser test is needed here because ClearLocalState indirectly calls // WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin. IN_PROC_BROWSER_TEST_F(DOMStorageBrowserTest, MAYBE_ClearLocalState) { // Create test files. ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath domstorage_dir = temp_dir.path().Append( DOMStorageContext::kLocalStorageDirectory); ASSERT_TRUE(file_util::CreateDirectory(domstorage_dir)); FilePath::StringType file_name_1(FILE_PATH_LITERAL("http_foo_0")); file_name_1.append(DOMStorageContext::kLocalStorageExtension); FilePath::StringType file_name_2(FILE_PATH_LITERAL("chrome-extension_foo_0")); file_name_2.append(DOMStorageContext::kLocalStorageExtension); FilePath temp_file_path_1 = domstorage_dir.Append(file_name_1); FilePath temp_file_path_2 = domstorage_dir.Append(file_name_2); ASSERT_EQ(1, file_util::WriteFile(temp_file_path_1, ".", 1)); ASSERT_EQ(1, file_util::WriteFile(temp_file_path_2, "o", 1)); // Create the scope which will ensure we run the destructor of the webkit // context which should trigger the clean up. { TestingProfile profile; WebKitContext* webkit_context = BrowserContext::GetWebKitContext(&profile); webkit_context->dom_storage_context()-> set_data_path_for_testing(temp_dir.path()); webkit_context->set_clear_local_state_on_exit(true); } // Make sure we wait until the destructor has run. scoped_refptr<base::ThreadTestHelper> helper( new base::ThreadTestHelper( BrowserThread::GetMessageLoopProxyForThread( BrowserThread::WEBKIT_DEPRECATED))); ASSERT_TRUE(helper->Run()); // Because we specified https for scheme to be skipped the second file // should survive and the first go into vanity. ASSERT_FALSE(file_util::PathExists(temp_file_path_1)); ASSERT_TRUE(file_util::PathExists(temp_file_path_2)); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "inc\CircularTorus.h" namespace Geometry { CircularTorus::CircularTorus() : m_topVis(true) , m_bottomVis(true) { } CircularTorus::~CircularTorus() { } void CircularTorus::subDraw() { osg::ref_ptr<osg::Vec3Array> vertexArr = new osg::Vec3Array; osg::ref_ptr<osg::Vec3Array> normalArr = new osg::Vec3Array; setVertexArray(vertexArr); setNormalArray(normalArr, osg::Array::BIND_PER_VERTEX); osg::ref_ptr<osg::Vec4Array> colArr = new osg::Vec4Array(); colArr->push_back(m_color); setColorArray(colArr, osg::Array::BIND_OVERALL); bool isFull = osg::equivalent(m_angle, 2 * M_PI, GetEpsilon()); if (isFull) { m_angle = 2 * M_PI; } int mainCount = (int)ceil(m_angle / (2 * M_PI / getDivision())); double mainIncAngle = m_angle / mainCount; int subCount = (int)getDivision(); double subIncAngle = 2 * M_PI / subCount; osg::Vec3 mainVec = m_startPnt - m_center; osg::Quat mainQuat(mainIncAngle, m_normal); osg::Vec3 torusNormal = mainVec; torusNormal.normalize(); // һȦ osg::Vec3 faceNormal = torusNormal ^ m_normal; osg::Quat torusQuat(subIncAngle, faceNormal); osg::Vec3 subVec = torusNormal; double subRadius = m_startRadius; osg::Vec3 subCenter = m_startPnt; osg::Vec3 tmpSubVec = subVec * subRadius; for (int i = 0; i < subCount; ++i) { vertexArr->push_back(subCenter + tmpSubVec); tmpSubVec = torusQuat * tmpSubVec; } // м osg::DrawElementsUShort *pDrawEle = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLE_STRIP, 0); pDrawEle->push_back(subCount - 1); double factor = (m_endRadius - m_startRadius) / mainCount; for (int i = 1; i < mainCount; ++i) { faceNormal = mainQuat * faceNormal; mainVec = mainQuat * mainVec; subVec = mainQuat * subVec; subCenter = m_center + mainVec; torusQuat.makeRotate(subIncAngle, faceNormal); subRadius += factor; tmpSubVec = subVec * subRadius; osg::Vec3 tangNormal = m_normal; for (int j = 0; j < subCount; ++j) { vertexArr->push_back(subCenter + tmpSubVec); tmpSubVec = torusQuat * tmpSubVec; int size = vertexArr->size(); normalArr->push_back(tangNormal ^ ((*vertexArr)[size - subCount - 1] - vertexArr->back())); normalArr->back().normalize(); tangNormal = torusQuat * tangNormal; pDrawEle->push_back(size - 1); pDrawEle->push_back(size - subCount - 1); } } // һȦ osg::Quat fullQuat(m_angle, m_normal); faceNormal = fullQuat * (torusNormal ^ m_normal); mainVec = fullQuat * (m_startPnt - m_center); subVec = fullQuat * (torusNormal * m_endRadius); subCenter = m_center + mainVec; torusQuat.makeRotate(subIncAngle, faceNormal); tmpSubVec = subVec; osg::Vec3 tangNormal = m_normal; for (int j = 0; j < subCount; ++j) { vertexArr->push_back(subCenter + tmpSubVec); tmpSubVec = torusQuat * tmpSubVec; int size = vertexArr->size(); normalArr->push_back(tangNormal ^ ((*vertexArr)[size - subCount - 1] - vertexArr->back())); normalArr->back().normalize(); tangNormal = torusQuat * tangNormal; pDrawEle->push_back(size - 1); pDrawEle->push_back(size - subCount - 1); } pDrawEle->push_back(vertexArr->size() - subCount); // һȦ for (int i = 0; i < subCount; ++i) normalArr->push_back((*normalArr)[normalArr->size() - subCount]); addPrimitiveSet(pDrawEle); if (m_topVis) { size_t first = vertexArr->size(); size_t base = first - subCount; osg::Vec3 topNormal = -faceNormal; vertexArr->push_back(subCenter); normalArr->push_back(topNormal); for (int i = subCount - 1; i >= 0; --i) { vertexArr->push_back((*vertexArr)[base + i]); normalArr->push_back(topNormal); } vertexArr->push_back((*vertexArr)[vertexArr->size() - subCount]); normalArr->push_back(topNormal); addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLE_FAN, first, vertexArr->size() - first)); } if (m_bottomVis) { size_t first = vertexArr->size(); osg::Vec3 bottomNormal = torusNormal ^ m_normal; vertexArr->push_back(m_startPnt); normalArr->push_back(bottomNormal); for (int i = 0; i < subCount; ++i) { vertexArr->push_back((*vertexArr)[i]); normalArr->push_back(bottomNormal); } vertexArr->push_back((*vertexArr)[vertexArr->size() - subCount]); normalArr->push_back(bottomNormal); addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLE_FAN, first, vertexArr->size() - first)); } } } // namespace Geometry<commit_msg>解决圆环中间带条线的<commit_after>#include "stdafx.h" #include "inc\CircularTorus.h" namespace Geometry { CircularTorus::CircularTorus() : m_topVis(true) , m_bottomVis(true) { } CircularTorus::~CircularTorus() { } void CircularTorus::subDraw() { osg::ref_ptr<osg::Vec3Array> vertexArr = new osg::Vec3Array; osg::ref_ptr<osg::Vec3Array> normalArr = new osg::Vec3Array; setVertexArray(vertexArr); setNormalArray(normalArr, osg::Array::BIND_PER_VERTEX); osg::ref_ptr<osg::Vec4Array> colArr = new osg::Vec4Array(); colArr->push_back(m_color); setColorArray(colArr, osg::Array::BIND_OVERALL); bool isFull = osg::equivalent(m_angle, 2 * M_PI, GetEpsilon()); if (isFull) { m_angle = 2 * M_PI; } int mainCount = (int)ceil(m_angle / (2 * M_PI / getDivision())); double mainIncAngle = m_angle / mainCount; int subCount = (int)getDivision(); double subIncAngle = 2 * M_PI / subCount; osg::Vec3 mainVec = m_startPnt - m_center; osg::Quat mainQuat(mainIncAngle, m_normal); osg::Vec3 torusNormal = mainVec; torusNormal.normalize(); // һȦ osg::Vec3 faceNormal = torusNormal ^ m_normal; osg::Quat torusQuat(subIncAngle, -faceNormal); osg::Vec3 subVec = torusNormal; double subRadius = m_startRadius; osg::Vec3 subCenter = m_startPnt; osg::Vec3 tmpSubVec = subVec * subRadius; for (int i = 0; i < subCount; ++i) { vertexArr->push_back(subCenter + tmpSubVec); tmpSubVec = torusQuat * tmpSubVec; } // м osg::DrawElementsUShort *pDrawEle = new osg::DrawElementsUShort(osg::PrimitiveSet::TRIANGLE_STRIP, 0); pDrawEle->push_back(subCount - 1); double factor = (m_endRadius - m_startRadius) / mainCount; for (int i = 1; i < mainCount; ++i) { faceNormal = mainQuat * faceNormal; mainVec = mainQuat * mainVec; subVec = mainQuat * subVec; subCenter = m_center + mainVec; torusQuat.makeRotate(subIncAngle, -faceNormal); subRadius += factor; tmpSubVec = subVec * subRadius; osg::Vec3 tangNormal = m_normal; for (int j = 0; j < subCount; ++j) { vertexArr->push_back(subCenter + tmpSubVec); tmpSubVec = torusQuat * tmpSubVec; int size = vertexArr->size(); normalArr->push_back(tangNormal ^ ((*vertexArr)[size - subCount - 1] - vertexArr->back())); normalArr->back().normalize(); tangNormal = torusQuat * tangNormal; pDrawEle->push_back(size - subCount - 1); pDrawEle->push_back(size - 1); } } // һȦ osg::Quat fullQuat(m_angle, m_normal); faceNormal = fullQuat * (torusNormal ^ m_normal); mainVec = fullQuat * (m_startPnt - m_center); subVec = fullQuat * (torusNormal * m_endRadius); subCenter = m_center + mainVec; torusQuat.makeRotate(subIncAngle, -faceNormal); tmpSubVec = subVec; osg::Vec3 tangNormal = m_normal; for (int j = 0; j < subCount; ++j) { vertexArr->push_back(subCenter + tmpSubVec); tmpSubVec = torusQuat * tmpSubVec; int size = vertexArr->size(); normalArr->push_back(tangNormal ^ ((*vertexArr)[size - subCount - 1] - vertexArr->back())); normalArr->back().normalize(); tangNormal = torusQuat * tangNormal; pDrawEle->push_back(size - subCount - 1); pDrawEle->push_back(size - 1); } pDrawEle->push_back(vertexArr->size() - subCount); // һȦ for (int i = 0; i < subCount; ++i) normalArr->push_back((*normalArr)[normalArr->size() - subCount]); addPrimitiveSet(pDrawEle); if (m_topVis) { size_t first = vertexArr->size(); size_t base = first - subCount; osg::Vec3 topNormal = -faceNormal; vertexArr->push_back(subCenter); normalArr->push_back(topNormal); for (int i = 0; i < subCount; ++i) { vertexArr->push_back((*vertexArr)[base + i]); normalArr->push_back(topNormal); } vertexArr->push_back((*vertexArr)[vertexArr->size() - subCount]); normalArr->push_back(topNormal); addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLE_FAN, first, vertexArr->size() - first)); } if (m_bottomVis) { size_t first = vertexArr->size(); osg::Vec3 bottomNormal = torusNormal ^ m_normal; vertexArr->push_back(m_startPnt); normalArr->push_back(bottomNormal); for (int i = subCount - 1; i >= 0; --i) { vertexArr->push_back((*vertexArr)[i]); normalArr->push_back(bottomNormal); } vertexArr->push_back((*vertexArr)[vertexArr->size() - subCount]); normalArr->push_back(bottomNormal); addPrimitiveSet(new osg::DrawArrays(osg::PrimitiveSet::TRIANGLE_FAN, first, vertexArr->size() - first)); } } } // namespace Geometry<|endoftext|>
<commit_before>#include "network.h" #include <QDebug> Network::Network(QObject *parent) :QObject(parent) { my_socket = new QUdpSocket(this); my_socket->bind(QHostAddress::LocalHost, 1337); connect(my_socket, SIGNAL(readyRead()), this, SLOT(processPendingDatagram())); } void Network::sendData(QImage image) { QByteArray q; QBuffer buffer(&q); buffer.open(QIODevice::WriteOnly); image.save(&buffer, "PNG"); my_socket->writeDatagram(q, QHostAddress::LocalHost, 1337); std::cerr << QHostAddress::LocalHost <<std::endl; } void Network::processPendingDatagram() { while (my_socket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(my_socket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; my_socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort); //QImage recv_image((uchar*)datagram.data(), 240, 150, QImage::Format_RGB888); QImage recv_image; if (datagram.isNull()) qDebug("Ures a bejovo buzi!!"); else qDebug("datagram nem ures"); recv_image.loadFromData(datagram, "PNG"); if (recv_image.isNull()) // Check if the image was indeed received qDebug("The image is null. Something failed."); image = recv_image; } //image = QImage("debug/images/kep.png").scaledToHeight(240).scaledToHeight(150); } QImage Network::get_image() { return image; } Network::~Network() { delete my_socket; } <commit_msg>remote networking test and it is working<commit_after>#include "network.h" #include <QDebug> Network::Network(QObject *parent) :QObject(parent) { my_socket = new QUdpSocket(this); //my_socket->bind(QHostAddress::LocalHost, 1337); my_socket->bind(QHostAddress("192.168.254.98"), 1337); connect(my_socket, SIGNAL(readyRead()), this, SLOT(processPendingDatagram())); } void Network::sendData(QImage image) { QByteArray q; QBuffer buffer(&q); buffer.open(QIODevice::WriteOnly); image.save(&buffer, "PNG"); //my_socket->writeDatagram(q, QHostAddress::LocalHost, 1337); my_socket->writeDatagram(q, QHostAddress("192.168.254.108"), 1337); std::cerr << QHostAddress::LocalHost <<std::endl; } void Network::processPendingDatagram() { while (my_socket->hasPendingDatagrams()) { QByteArray datagram; datagram.resize(my_socket->pendingDatagramSize()); QHostAddress sender; quint16 senderPort; my_socket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort); //QImage recv_image((uchar*)datagram.data(), 240, 150, QImage::Format_RGB888); QImage recv_image; if (datagram.isNull()) qDebug("Ures a bejovo buzi!!"); else qDebug("datagram nem ures"); recv_image.loadFromData(datagram, "PNG"); if (recv_image.isNull()) // Check if the image was indeed received qDebug("The image is null. Something failed."); image = recv_image; } //image = QImage("debug/images/kep.png").scaledToHeight(240).scaledToHeight(150); } QImage Network::get_image() { return image; } Network::~Network() { delete my_socket; } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: itkImageToImageTranslationMeanSquaresRegistrationTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #include "itkPhysicalImage.h" #include "itkSimpleImageRegionIterator.h" #include "itkImageToImageTranslationMeanSquaresRegistration.h" /** * This test uses two 2D-Gaussians (standard deviation RegionSize/2) * One is shifted by 10 pixels from the other. * therefore the solution of the registration is |-5 0| * This test uses LevenbergMarquart Optimizer but * conjugate gradient optimizer tolerances are also defined * in the itkImageToImageTranslationMeanSquaresRegistration.txx file * (you need to change the type of the optimizer in the header file * ie itkImageToImageTranslationMeanSquaresRegistration.h) */ int main() { /*Allocate Images*/ typedef itk::PhysicalImage<unsigned char,2> ReferenceType; typedef itk::PhysicalImage<unsigned char,2> TargetType; typedef itk::ImageToImageTranslationMeanSquaresRegistration<ReferenceType,TargetType> RegistrationType; ReferenceType::SizeType size = {{100,100}}; ReferenceType::IndexType index = {{0,0}}; ReferenceType::RegionType region; region.SetSize( size ); region.SetIndex( index ); ReferenceType::Pointer imgReference = ReferenceType::New(); imgReference->SetLargestPossibleRegion( region ); imgReference->SetBufferedRegion( region ); imgReference->SetRequestedRegion( region ); imgReference->Allocate(); TargetType::Pointer imgTarget = TargetType::New(); imgTarget->SetLargestPossibleRegion( region ); imgTarget->SetBufferedRegion( region ); imgTarget->SetRequestedRegion( region ); imgTarget->Allocate(); /* Fill images with a 2D gaussian*/ typedef itk::SimpleImageRegionIterator<ReferenceType> ReferenceIteratorType; typedef itk::SimpleImageRegionIterator<TargetType> TargetIteratorType; itk::Point<double,2> center; center[0] = (double)region.GetSize()[0]/2.0; center[1] = (double)region.GetSize()[1]/2.0; const double s = (double)region.GetSize()[0]/2.0; itk::Point<double,2> p; itk::Vector<double,2> d; /* Set the displacement */ itk::Vector<double,2> displacement; displacement[0] = 7; displacement[1] = 3; ReferenceIteratorType ri(imgReference,region); TargetIteratorType ti(imgTarget,region); ri.Begin(); while(!ri.IsAtEnd()) { p[0] = ri.GetIndex()[0]; p[1] = ri.GetIndex()[1]; d = p-center; d += displacement; const double x = d[0]; const double y = d[1]; ri.Set( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ); ++ri; } ti.Begin(); while(!ti.IsAtEnd()) { p[0] = ti.GetIndex()[0]; p[1] = ti.GetIndex()[1]; d = p-center; const double x = d[0]; const double y = d[1]; ti.Set( 200.0 * exp( - ( x*x + y*y )/(s*s) ) ); ++ti; } RegistrationType::Pointer registrationMethod = RegistrationType::New(); registrationMethod->SetReference(imgReference); registrationMethod->SetTarget(imgTarget); registrationMethod->StartRegistration(); std::cout << "The correct answer should be : " << std::endl; std::cout << -displacement << std::endl; return EXIT_SUCCESS; } <commit_msg>ENH: File renamed to include the optimization method name<commit_after><|endoftext|>
<commit_before>#include "./JPetSinogram.h" #include <boost/numeric/ublas/matrix.hpp> #include <vector> #include <utility> #include <cmath> using namespace boost::numeric::ublas; JPetSinogram::JPetSinogram() { } JPetSinogram::~JPetSinogram() { } /*! \brief Function returning vector of vectors with value of sinogram(180/views degree step and emissionMatrix.size1()/scans size) scaled to <min,max> * \param emissionMatrix matrix, need to by NxN * \param views number of views on object, degree step is calculated as (ang2 - ang1) / views * \param scans number of scans on object, step is calculated as emissionMatrix.size(1) / scans * \param fast if true use nearest neighbour interpolation instead linear interpolation in calculation (Optional, default false) * \param min minimum value in returned sinogram (Optional, default 0) * \param max maximum value in returned sinogram (Optional, default 255) * \param ang1 start angle for projection (Optional, default 0) * \param ang2 end angle for projection (Optional, default 180) */ std::vector<std::vector<double>> JPetSinogram::sinogram(matrix<int> emissionMatrix, int views, int scans, bool fast, int min, int max, float ang1, float ang2) { assert(emissionMatrix.size1() == emissionMatrix.size2()); assert(emissionMatrix.size1() > 0); assert(views > 0); assert(scans > 0); assert(min < max); assert(ang1 < ang2); int i = 0; std::vector<std::vector<double>> proj(views, std::vector<double>(scans)); //create vector of size views, initialize it with vector of size scans int x = 0, y = 0, Xcenter = 0, Ycenter = 0; std::unique_ptr<double[]> sintab(new double[views]); std::unique_ptr<double[]> costab(new double[views]); int scanNumber=0; int inputMatrixSize = emissionMatrix.size1(); float phi = 0., stepsize = 0.; stepsize = (ang2 - ang1) / views; for (phi = ang1; phi < ang2; phi = phi + stepsize) { sintab[i] = std::sin((double) phi * M_PI / 180 - M_PI/2); costab[i] = std::cos((double) phi * M_PI / 180 - M_PI/2); i++; } Xcenter = inputMatrixSize / 2; Ycenter = inputMatrixSize / 2; i=0; //if no. scans is greater than the image width, then scale will be <1 double scale = inputMatrixSize*1.42/scans; int N=0; double value = 0.; double weight = 0; double sang = std::sqrt(2)/2; for (phi=ang1;phi<ang2;phi=phi+stepsize){ double a = -costab[i]/sintab[i] ; double aa = 1/a; if (std::abs(sintab[i]) > sang){ for (scanNumber=0;scanNumber<scans;scanNumber++){ N = scanNumber - scans/2; double b = (N - costab[i] - sintab[i]) / sintab[i]; b = b * scale; for (x = -Xcenter; x < Xcenter; x++){ if (fast == true){ //nearest neighbour interpolation y = (int) std::round(a*x + b); if (y >= -Xcenter && y < Xcenter ) value += emissionMatrix((x+Xcenter),(y+Ycenter)); } else { y = (int) std::round(a*x + b); //linear interpolation weight = std::abs((a*x + b) - std::ceil(a*x + b)); if (y >= -Xcenter && y+1 < Xcenter ) value += (1-weight) * emissionMatrix((x+Xcenter),(y+Ycenter)) + weight * emissionMatrix((x+Xcenter), (y+Ycenter+1)); } } proj[i][scanNumber] = value/std::abs(sintab[i]); value=0; } } if (std::abs(sintab[i]) <= sang){ for (scanNumber=0;scanNumber<scans;scanNumber++){ N = scanNumber - scans/2; double bb = (N - costab[i] - sintab[i]) / costab[i]; bb = bb * scale; for (y = -Ycenter; y < Ycenter; y++) { if (fast ==true){ //nearest neighbour interpolation x = (int) std::round(aa*y + bb); if (x >= -Xcenter && x < Xcenter ) value += emissionMatrix(x+Xcenter, y+Ycenter); } else { //linear interpolation x = (int) std::round(aa*y + bb); weight = std::abs((aa*y + bb) - std::ceil(aa*y + bb)); if (x >= -Xcenter && x+1 < Xcenter ) value += (1-weight) * emissionMatrix((x+Xcenter), (y+Ycenter)) + weight * emissionMatrix((x+Xcenter+1), (y+Ycenter)); } } proj[i][scanNumber] = value/std::abs(costab[i]); value=0; } } i++; } i=0; double datamax = proj[0][0]; double datamin = proj[0][0]; for (unsigned int k = 0; k < proj.size(); k++ ) { for (unsigned int j = 0; j < proj[0].size(); j++ ) { if(proj[k][j] < min) proj[k][j] = min; if(proj[k][j] > datamax) datamax = proj[k][j]; if(proj[k][j] < datamin) datamin = proj[k][j]; } } for (unsigned int k = 0; k < proj.size(); k++ ) { for (unsigned int j = 0; j < proj[0].size(); j++ ) { proj[k][j] = (double) ((proj[k][j]-datamin) * max/datamax); } } return proj; }<commit_msg>Add check to datamax and stepsize<commit_after>#include "./JPetSinogram.h" #include <boost/numeric/ublas/matrix.hpp> #include <vector> #include <utility> #include <cmath> using namespace boost::numeric::ublas; JPetSinogram::JPetSinogram() { } JPetSinogram::~JPetSinogram() { } /*! \brief Function returning vector of vectors with value of sinogram(180/views degree step and emissionMatrix.size1()/scans size) scaled to <min,max> * \param emissionMatrix matrix, need to by NxN * \param views number of views on object, degree step is calculated as (ang2 - ang1) / views * \param scans number of scans on object, step is calculated as emissionMatrix.size(1) / scans * \param fast if true use nearest neighbour interpolation instead linear interpolation in calculation (Optional, default false) * \param min minimum value in returned sinogram (Optional, default 0) * \param max maximum value in returned sinogram (Optional, default 255) * \param ang1 start angle for projection (Optional, default 0) * \param ang2 end angle for projection (Optional, default 180) */ std::vector<std::vector<double>> JPetSinogram::sinogram(matrix<int> emissionMatrix, int views, int scans, bool fast, int min, int max, float ang1, float ang2) { assert(emissionMatrix.size1() == emissionMatrix.size2()); assert(emissionMatrix.size1() > 0); assert(views > 0); assert(scans > 0); assert(min < max); assert(ang1 < ang2); int i = 0; std::vector<std::vector<double>> proj(views, std::vector<double>(scans)); //create vector of size views, initialize it with vector of size scans int x = 0, y = 0, Xcenter = 0, Ycenter = 0; std::unique_ptr<double[]> sintab(new double[views]); std::unique_ptr<double[]> costab(new double[views]); int scanNumber=0; int inputMatrixSize = emissionMatrix.size1(); float phi = 0., stepsize = 0.; stepsize = (ang2 - ang1) / views; assert(stepsize > 0); //maybe != 0 ? for (phi = ang1; phi < ang2; phi = phi + stepsize) { sintab[i] = std::sin((double) phi * M_PI / 180 - M_PI/2); costab[i] = std::cos((double) phi * M_PI / 180 - M_PI/2); i++; } Xcenter = inputMatrixSize / 2; Ycenter = inputMatrixSize / 2; i=0; //if no. scans is greater than the image width, then scale will be <1 double scale = inputMatrixSize*1.42/scans; int N=0; double value = 0.; double weight = 0.; double sang = std::sqrt(2)/2; for (phi=ang1;phi<ang2;phi=phi+stepsize){ double a = -costab[i]/sintab[i]; double aa = 1/a; if (std::abs(sintab[i]) > sang){ for (scanNumber=0;scanNumber<scans;scanNumber++){ N = scanNumber - scans/2; double b = (N - costab[i] - sintab[i]) / sintab[i]; b = b * scale; for (x = -Xcenter; x < Xcenter; x++){ if (fast == true){ //nearest neighbour interpolation y = (int) std::round(a*x + b); if (y >= -Xcenter && y < Xcenter ) value += emissionMatrix((x+Xcenter),(y+Ycenter)); } else { y = (int) std::round(a*x + b); //linear interpolation weight = std::abs((a*x + b) - std::ceil(a*x + b)); if (y >= -Xcenter && y+1 < Xcenter ) value += (1-weight) * emissionMatrix((x+Xcenter),(y+Ycenter)) + weight * emissionMatrix((x+Xcenter), (y+Ycenter+1)); } } proj[i][scanNumber] = value/std::abs(sintab[i]); value=0; } } if (std::abs(sintab[i]) <= sang){ for (scanNumber=0;scanNumber<scans;scanNumber++){ N = scanNumber - scans/2; double bb = (N - costab[i] - sintab[i]) / costab[i]; bb = bb * scale; for (y = -Ycenter; y < Ycenter; y++) { if (fast ==true){ //nearest neighbour interpolation x = (int) std::round(aa*y + bb); if (x >= -Xcenter && x < Xcenter ) value += emissionMatrix(x+Xcenter, y+Ycenter); } else { //linear interpolation x = (int) std::round(aa*y + bb); weight = std::abs((aa*y + bb) - std::ceil(aa*y + bb)); if (x >= -Xcenter && x+1 < Xcenter ) value += (1-weight) * emissionMatrix((x+Xcenter), (y+Ycenter)) + weight * emissionMatrix((x+Xcenter+1), (y+Ycenter)); } } proj[i][scanNumber] = value/std::abs(costab[i]); value=0; } } i++; } i=0; double datamax = proj[0][0]; double datamin = proj[0][0]; for (unsigned int k = 0; k < proj.size(); k++ ) { for (unsigned int j = 0; j < proj[0].size(); j++ ) { if(proj[k][j] < min) proj[k][j] = min; if(proj[k][j] > datamax) datamax = proj[k][j]; if(proj[k][j] < datamin) datamin = proj[k][j]; } } if(datamax == 0.) datamax = 1.; for (unsigned int k = 0; k < proj.size(); k++ ) { for (unsigned int j = 0; j < proj[0].size(); j++ ) { proj[k][j] = (double) ((proj[k][j]-datamin) * max/datamax); } } return proj; }<|endoftext|>
<commit_before>/* * Copyright (c) 2003-2009, John Wiegley. 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 New Artisans LLC nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <system.hh> #include "pyinterp.h" #include "account.h" #include "xact.h" #include "post.h" namespace ledger { using namespace python; shared_ptr<python_interpreter_t> python_session; char * argv0; void export_account(); void export_amount(); void export_balance(); void export_commodity(); void export_expr(); void export_format(); void export_item(); void export_journal(); void export_post(); void export_times(); void export_utils(); void export_value(); void export_xact(); void initialize_for_python() { export_account(); export_amount(); export_balance(); export_commodity(); export_expr(); export_format(); export_item(); export_journal(); export_post(); export_times(); export_utils(); export_value(); export_xact(); } struct python_run { object result; python_run(python_interpreter_t * intepreter, const string& str, int input_mode) : result(handle<>(borrowed(PyRun_String(str.c_str(), input_mode, intepreter->main_nspace.ptr(), intepreter->main_nspace.ptr())))) {} operator object() { return result; } }; void python_interpreter_t::initialize() { TRACE_START(python_init, 1, "Initialized Python"); try { DEBUG("python.interp", "Initializing Python"); Py_Initialize(); assert(Py_IsInitialized()); object main_module = python::import("__main__"); if (! main_module) throw_(std::logic_error, _("Python failed to initialize (couldn't find __main__)")); main_nspace = extract<dict>(main_module.attr("__dict__")); if (! main_nspace) throw_(std::logic_error, _("Python failed to initialize (couldn't find __dict__)")); python::detail::init_module("ledger", &initialize_for_python); is_initialized = true; // Hack ledger.__path__ so it points to a real location python::object module_sys = import("sys"); python::object sys_dict = module_sys.attr("__dict__"); python::list paths(sys_dict["path"]); bool path_initialized = false; int n = python::extract<int>(paths.attr("__len__")()); for (int i = 0; i < n; i++) { python::extract<std::string> str(paths[i]); path pathname(str); DEBUG("python.interp", "sys.path = " << pathname); if (exists(pathname / "ledger" / "__init__.py")) { if (python::object module_ledger = import("ledger")) { DEBUG("python.interp", "Setting ledger.__path__ = " << (pathname / "ledger")); python::object ledger_dict = module_ledger.attr("__dict__"); python::list temp_list; temp_list.append((pathname / "ledger").string()); ledger_dict["__path__"] = temp_list; } else { throw_(std::logic_error, _("Python failed to initialize (couldn't find ledger)")); } path_initialized = true; break; } } #if defined(DEBUG_ON) if (! path_initialized) DEBUG("python.init", "Ledger failed to find 'ledger/__init__.py' on the PYTHONPATH"); #endif } catch (const error_already_set&) { PyErr_Print(); throw_(std::logic_error, _("Python failed to initialize")); } TRACE_FINISH(python_init, 1); } object python_interpreter_t::import(const string& str) { if (! is_initialized) initialize(); try { object mod = python::import(str.c_str()); if (! mod) throw_(std::logic_error, _("Failed to import Python module %1") << str); // Import all top-level entries directly into the main namespace main_nspace.update(mod.attr("__dict__")); return mod; } catch (const error_already_set&) { PyErr_Print(); } return object(); } object python_interpreter_t::eval(std::istream& in, py_eval_mode_t mode) { bool first = true; string buffer; buffer.reserve(4096); while (! in.eof()) { char buf[256]; in.getline(buf, 255); if (buf[0] == '!') break; if (first) first = false; else buffer += "\n"; buffer += buf; } if (! is_initialized) initialize(); try { int input_mode = -1; switch (mode) { case PY_EVAL_EXPR: input_mode = Py_eval_input; break; case PY_EVAL_STMT: input_mode = Py_single_input; break; case PY_EVAL_MULTI: input_mode = Py_file_input; break; } return python_run(this, buffer, input_mode); } catch (const error_already_set&) { PyErr_Print(); throw_(std::logic_error, _("Failed to evaluate Python code")); } return object(); } object python_interpreter_t::eval(const string& str, py_eval_mode_t mode) { if (! is_initialized) initialize(); try { int input_mode = -1; switch (mode) { case PY_EVAL_EXPR: input_mode = Py_eval_input; break; case PY_EVAL_STMT: input_mode = Py_single_input; break; case PY_EVAL_MULTI: input_mode = Py_file_input; break; } return python_run(this, str, input_mode); } catch (const error_already_set&) { PyErr_Print(); throw_(std::logic_error, _("Failed to evaluate Python code")); } return object(); } value_t python_interpreter_t::python_command(call_scope_t& args) { if (! is_initialized) initialize(); char ** argv(new char *[args.size() + 1]); argv[0] = new char[std::strlen(argv0) + 1]; std::strcpy(argv[0], argv0); for (std::size_t i = 0; i < args.size(); i++) { string arg = args[i].as_string(); argv[i + 1] = new char[arg.length() + 1]; std::strcpy(argv[i + 1], arg.c_str()); } int status = Py_Main(static_cast<int>(args.size()) + 1, argv); for (std::size_t i = 0; i < args.size() + 1; i++) delete[] argv[i]; delete[] argv; if (status != 0) throw status; return NULL_VALUE; } option_t<python_interpreter_t> * python_interpreter_t::lookup_option(const char * p) { switch (*p) { case 'i': OPT(import_); break; } return NULL; } expr_t::ptr_op_t python_interpreter_t::lookup(const symbol_t::kind_t kind, const string& name) { // Give our superclass first dibs on symbol definitions if (expr_t::ptr_op_t op = session_t::lookup(kind, name)) return op; switch (kind) { case symbol_t::FUNCTION: if (is_initialized && main_nspace.has_key(name.c_str())) { DEBUG("python.interp", "Python lookup: " << name); if (python::object obj = main_nspace.get(name.c_str())) return WRAP_FUNCTOR(functor_t(name, obj)); } break; case symbol_t::OPTION: if (option_t<python_interpreter_t> * handler = lookup_option(name.c_str())) return MAKE_OPT_HANDLER(python_interpreter_t, handler); break; case symbol_t::PRECOMMAND: { const char * p = name.c_str(); switch (*p) { case 'p': if (is_eq(p, "python")) return MAKE_FUNCTOR(python_interpreter_t::python_command); break; } } default: break; } return NULL; } namespace { void append_value(list& lst, const value_t& value) { if (value.is_scope()) { const scope_t * scope = value.as_scope(); if (const post_t * post = dynamic_cast<const post_t *>(scope)) lst.append(ptr(post)); else if (const xact_t * xact = dynamic_cast<const xact_t *>(scope)) lst.append(ptr(xact)); else if (const account_t * account = dynamic_cast<const account_t *>(scope)) lst.append(ptr(account)); else if (const period_xact_t * period_xact = dynamic_cast<const period_xact_t *>(scope)) lst.append(ptr(period_xact)); else if (const auto_xact_t * auto_xact = dynamic_cast<const auto_xact_t *>(scope)) lst.append(ptr(auto_xact)); else throw_(std::runtime_error, _("Cannot downcast scoped object to specific type")); } else { lst.append(value); } } } value_t python_interpreter_t::functor_t::operator()(call_scope_t& args) { try { std::signal(SIGINT, SIG_DFL); if (! PyCallable_Check(func.ptr())) { extract<value_t> val(func); std::signal(SIGINT, sigint_handler); if (val.check()) return val(); #if 1 // jww (2009-02-24): Distinguish between "no return" and values with // unconvertable type return NULL_VALUE; #else throw_(calc_error, _("Could not evaluate Python variable '%1'") << name); #endif } else if (args.size() > 0) { list arglist; // jww (2009-11-05): What about a single argument which is a sequence, // rather than a sequence of arguments? if (args.value().is_sequence()) foreach (const value_t& value, args.value().as_sequence()) append_value(arglist, value); else append_value(arglist, args.value()); if (PyObject * val = PyObject_CallObject(func.ptr(), python::tuple(arglist).ptr())) { extract<value_t> xval(val); value_t result; if (xval.check()) { result = xval(); Py_DECREF(val); } else { Py_DECREF(val); throw_(calc_error, _("Could not evaluate Python variable '%1'") << name); } std::signal(SIGINT, sigint_handler); return result; } else if (PyErr_Occurred()) { PyErr_Print(); throw_(calc_error, _("Failed call to Python function '%1'") << name); } else { assert(false); } } else { std::signal(SIGINT, sigint_handler); return call<value_t>(func.ptr()); } } catch (const error_already_set&) { std::signal(SIGINT, sigint_handler); PyErr_Print(); throw_(calc_error, _("Failed call to Python function '%1'") << name); } catch (...) { std::signal(SIGINT, sigint_handler); } std::signal(SIGINT, sigint_handler); return NULL_VALUE; } } // namespace ledger <commit_msg>Python vars of unconvertable type return NULL_VALUE<commit_after>/* * Copyright (c) 2003-2009, John Wiegley. 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 New Artisans LLC nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <system.hh> #include "pyinterp.h" #include "account.h" #include "xact.h" #include "post.h" namespace ledger { using namespace python; shared_ptr<python_interpreter_t> python_session; char * argv0; void export_account(); void export_amount(); void export_balance(); void export_commodity(); void export_expr(); void export_format(); void export_item(); void export_journal(); void export_post(); void export_times(); void export_utils(); void export_value(); void export_xact(); void initialize_for_python() { export_account(); export_amount(); export_balance(); export_commodity(); export_expr(); export_format(); export_item(); export_journal(); export_post(); export_times(); export_utils(); export_value(); export_xact(); } struct python_run { object result; python_run(python_interpreter_t * intepreter, const string& str, int input_mode) : result(handle<>(borrowed(PyRun_String(str.c_str(), input_mode, intepreter->main_nspace.ptr(), intepreter->main_nspace.ptr())))) {} operator object() { return result; } }; void python_interpreter_t::initialize() { TRACE_START(python_init, 1, "Initialized Python"); try { DEBUG("python.interp", "Initializing Python"); Py_Initialize(); assert(Py_IsInitialized()); object main_module = python::import("__main__"); if (! main_module) throw_(std::logic_error, _("Python failed to initialize (couldn't find __main__)")); main_nspace = extract<dict>(main_module.attr("__dict__")); if (! main_nspace) throw_(std::logic_error, _("Python failed to initialize (couldn't find __dict__)")); python::detail::init_module("ledger", &initialize_for_python); is_initialized = true; // Hack ledger.__path__ so it points to a real location python::object module_sys = import("sys"); python::object sys_dict = module_sys.attr("__dict__"); python::list paths(sys_dict["path"]); bool path_initialized = false; int n = python::extract<int>(paths.attr("__len__")()); for (int i = 0; i < n; i++) { python::extract<std::string> str(paths[i]); path pathname(str); DEBUG("python.interp", "sys.path = " << pathname); if (exists(pathname / "ledger" / "__init__.py")) { if (python::object module_ledger = import("ledger")) { DEBUG("python.interp", "Setting ledger.__path__ = " << (pathname / "ledger")); python::object ledger_dict = module_ledger.attr("__dict__"); python::list temp_list; temp_list.append((pathname / "ledger").string()); ledger_dict["__path__"] = temp_list; } else { throw_(std::logic_error, _("Python failed to initialize (couldn't find ledger)")); } path_initialized = true; break; } } #if defined(DEBUG_ON) if (! path_initialized) DEBUG("python.init", "Ledger failed to find 'ledger/__init__.py' on the PYTHONPATH"); #endif } catch (const error_already_set&) { PyErr_Print(); throw_(std::logic_error, _("Python failed to initialize")); } TRACE_FINISH(python_init, 1); } object python_interpreter_t::import(const string& str) { if (! is_initialized) initialize(); try { object mod = python::import(str.c_str()); if (! mod) throw_(std::logic_error, _("Failed to import Python module %1") << str); // Import all top-level entries directly into the main namespace main_nspace.update(mod.attr("__dict__")); return mod; } catch (const error_already_set&) { PyErr_Print(); } return object(); } object python_interpreter_t::eval(std::istream& in, py_eval_mode_t mode) { bool first = true; string buffer; buffer.reserve(4096); while (! in.eof()) { char buf[256]; in.getline(buf, 255); if (buf[0] == '!') break; if (first) first = false; else buffer += "\n"; buffer += buf; } if (! is_initialized) initialize(); try { int input_mode = -1; switch (mode) { case PY_EVAL_EXPR: input_mode = Py_eval_input; break; case PY_EVAL_STMT: input_mode = Py_single_input; break; case PY_EVAL_MULTI: input_mode = Py_file_input; break; } return python_run(this, buffer, input_mode); } catch (const error_already_set&) { PyErr_Print(); throw_(std::logic_error, _("Failed to evaluate Python code")); } return object(); } object python_interpreter_t::eval(const string& str, py_eval_mode_t mode) { if (! is_initialized) initialize(); try { int input_mode = -1; switch (mode) { case PY_EVAL_EXPR: input_mode = Py_eval_input; break; case PY_EVAL_STMT: input_mode = Py_single_input; break; case PY_EVAL_MULTI: input_mode = Py_file_input; break; } return python_run(this, str, input_mode); } catch (const error_already_set&) { PyErr_Print(); throw_(std::logic_error, _("Failed to evaluate Python code")); } return object(); } value_t python_interpreter_t::python_command(call_scope_t& args) { if (! is_initialized) initialize(); char ** argv(new char *[args.size() + 1]); argv[0] = new char[std::strlen(argv0) + 1]; std::strcpy(argv[0], argv0); for (std::size_t i = 0; i < args.size(); i++) { string arg = args[i].as_string(); argv[i + 1] = new char[arg.length() + 1]; std::strcpy(argv[i + 1], arg.c_str()); } int status = Py_Main(static_cast<int>(args.size()) + 1, argv); for (std::size_t i = 0; i < args.size() + 1; i++) delete[] argv[i]; delete[] argv; if (status != 0) throw status; return NULL_VALUE; } option_t<python_interpreter_t> * python_interpreter_t::lookup_option(const char * p) { switch (*p) { case 'i': OPT(import_); break; } return NULL; } expr_t::ptr_op_t python_interpreter_t::lookup(const symbol_t::kind_t kind, const string& name) { // Give our superclass first dibs on symbol definitions if (expr_t::ptr_op_t op = session_t::lookup(kind, name)) return op; switch (kind) { case symbol_t::FUNCTION: if (is_initialized && main_nspace.has_key(name.c_str())) { DEBUG("python.interp", "Python lookup: " << name); if (python::object obj = main_nspace.get(name.c_str())) return WRAP_FUNCTOR(functor_t(name, obj)); } break; case symbol_t::OPTION: if (option_t<python_interpreter_t> * handler = lookup_option(name.c_str())) return MAKE_OPT_HANDLER(python_interpreter_t, handler); break; case symbol_t::PRECOMMAND: { const char * p = name.c_str(); switch (*p) { case 'p': if (is_eq(p, "python")) return MAKE_FUNCTOR(python_interpreter_t::python_command); break; } } default: break; } return NULL; } namespace { void append_value(list& lst, const value_t& value) { if (value.is_scope()) { const scope_t * scope = value.as_scope(); if (const post_t * post = dynamic_cast<const post_t *>(scope)) lst.append(ptr(post)); else if (const xact_t * xact = dynamic_cast<const xact_t *>(scope)) lst.append(ptr(xact)); else if (const account_t * account = dynamic_cast<const account_t *>(scope)) lst.append(ptr(account)); else if (const period_xact_t * period_xact = dynamic_cast<const period_xact_t *>(scope)) lst.append(ptr(period_xact)); else if (const auto_xact_t * auto_xact = dynamic_cast<const auto_xact_t *>(scope)) lst.append(ptr(auto_xact)); else throw_(std::runtime_error, _("Cannot downcast scoped object to specific type")); } else { lst.append(value); } } } value_t python_interpreter_t::functor_t::operator()(call_scope_t& args) { try { std::signal(SIGINT, SIG_DFL); if (! PyCallable_Check(func.ptr())) { extract<value_t> val(func); std::signal(SIGINT, sigint_handler); if (val.check()) return val(); return NULL_VALUE; } else if (args.size() > 0) { list arglist; // jww (2009-11-05): What about a single argument which is a sequence, // rather than a sequence of arguments? if (args.value().is_sequence()) foreach (const value_t& value, args.value().as_sequence()) append_value(arglist, value); else append_value(arglist, args.value()); if (PyObject * val = PyObject_CallObject(func.ptr(), python::tuple(arglist).ptr())) { extract<value_t> xval(val); value_t result; if (xval.check()) { result = xval(); Py_DECREF(val); } else { Py_DECREF(val); throw_(calc_error, _("Could not evaluate Python variable '%1'") << name); } std::signal(SIGINT, sigint_handler); return result; } else if (PyErr_Occurred()) { PyErr_Print(); throw_(calc_error, _("Failed call to Python function '%1'") << name); } else { assert(false); } } else { std::signal(SIGINT, sigint_handler); return call<value_t>(func.ptr()); } } catch (const error_already_set&) { std::signal(SIGINT, sigint_handler); PyErr_Print(); throw_(calc_error, _("Failed call to Python function '%1'") << name); } catch (...) { std::signal(SIGINT, sigint_handler); } std::signal(SIGINT, sigint_handler); return NULL_VALUE; } } // namespace ledger <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #if SK_SUPPORT_GPU #include "gm.h" #include "SkCanvas.h" #include "SkColorShader.h" #include "SkPaint.h" #include "SkSurface.h" namespace skiagm { /* * This GM exercises SkCanvas::discard() by creating an offscreen SkSurface and repeatedly * discarding it, drawing to it, and then drawing it to the main canvas. */ class DiscardGM : public GM { public: DiscardGM() { } virtual uint32_t onGetFlags() const SK_OVERRIDE { return kGPUOnly_Flag; } protected: virtual SkString onShortName() SK_OVERRIDE { return SkString("discard"); } virtual SkISize onISize() SK_OVERRIDE { return SkISize::Make(100, 100); } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { GrContext* context = canvas->getGrContext(); if (NULL == context) { return; } SkISize size = this->getISize(); size.fWidth /= 10; size.fHeight /= 10; SkImageInfo info = SkImageInfo::MakeN32Premul(size); SkSurface* surface = SkSurface::NewRenderTarget(context, info); if (NULL == surface) { return; } canvas->clear(SK_ColorBLACK); SkRandom rand; for (int x = 0; x < 10; ++x) { for (int y = 0; y < 10; ++y) { surface->getCanvas()->discard(); // Make something that isn't too close to the background color, black. SkColor color = rand.nextU() | 0xFF404040; switch (rand.nextULessThan(3)) { case 0: surface->getCanvas()->drawColor(color); break; case 1: surface->getCanvas()->clear(color); break; case 2: SkColorShader shader(color); SkPaint paint; paint.setShader(&shader); surface->getCanvas()->drawPaint(paint); break; } surface->draw(canvas, 10*x, 10*y, NULL); } } surface->getCanvas()->discard(); surface->unref(); } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM( return SkNEW(DiscardGM); ) } // end namespace #endif <commit_msg>Fix int->scalar warning on windows<commit_after>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #if SK_SUPPORT_GPU #include "gm.h" #include "SkCanvas.h" #include "SkColorShader.h" #include "SkPaint.h" #include "SkSurface.h" namespace skiagm { /* * This GM exercises SkCanvas::discard() by creating an offscreen SkSurface and repeatedly * discarding it, drawing to it, and then drawing it to the main canvas. */ class DiscardGM : public GM { public: DiscardGM() { } virtual uint32_t onGetFlags() const SK_OVERRIDE { return kGPUOnly_Flag; } protected: virtual SkString onShortName() SK_OVERRIDE { return SkString("discard"); } virtual SkISize onISize() SK_OVERRIDE { return SkISize::Make(100, 100); } virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE { GrContext* context = canvas->getGrContext(); if (NULL == context) { return; } SkISize size = this->getISize(); size.fWidth /= 10; size.fHeight /= 10; SkImageInfo info = SkImageInfo::MakeN32Premul(size); SkSurface* surface = SkSurface::NewRenderTarget(context, info); if (NULL == surface) { return; } canvas->clear(SK_ColorBLACK); SkRandom rand; for (int x = 0; x < 10; ++x) { for (int y = 0; y < 10; ++y) { surface->getCanvas()->discard(); // Make something that isn't too close to the background color, black. SkColor color = rand.nextU() | 0xFF404040; switch (rand.nextULessThan(3)) { case 0: surface->getCanvas()->drawColor(color); break; case 1: surface->getCanvas()->clear(color); break; case 2: SkColorShader shader(color); SkPaint paint; paint.setShader(&shader); surface->getCanvas()->drawPaint(paint); break; } surface->draw(canvas, 10.f*x, 10.f*y, NULL); } } surface->getCanvas()->discard(); surface->unref(); } private: typedef GM INHERITED; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM( return SkNEW(DiscardGM); ) } // end namespace #endif <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #include <miopen/rnn.hpp> #include <miopen/errors.hpp> //#include <miopen/logger.hpp> #include <miopen/tensor_ops.hpp> // TODO: Make miopenConvAlgoPerf_t loggable //inline std::ostream& operator<<(std::ostream& os, miopenConvAlgoPerf_t) { return os; } extern "C" miopenStatus_t miopenCreateRNNDescriptor(miopenRNNDescriptor_t* rnnDesc) { MIOPEN_LOG_FUNCTION(rnnDesc); return miopen::try_([&] { miopen::deref(rnnDesc) = new miopen::RNNDescriptor(); }); } extern "C" miopenStatus_t miopenInitRNNDescriptor(miopenRNNDescriptor_t rnnDesc, miopenRNNMode_t mode, int seqLength, int layer, int bidir) { MIOPEN_LOG_FUNCTION(rnnDesc, mode, seqLength, layer, bidir); return miopen::try_([&] { miopen::deref(rnnDesc) = miopen::RNNDescriptor(mode, seqLength, layer, bidir); }); } extern "C" miopenStatus_t miopenGetRNNDescriptor(miopenRNNDescriptor_t rnnDesc, miopenRNNMode_t* mode, int* seqLength, int* layer, int* bidir) { MIOPEN_LOG_FUNCTION(rnnDesc, mode, seqLength, layer, bidir); return miopen::try_([&] { miopen::deref(mode) = miopen::deref(rnnDesc).mode; miopen::deref(seqLength) = miopen::deref(rnnDesc).seqLength; miopen::deref(layer) = miopen::deref(rnnDesc).layer; miopen::deref(bidir) = miopen::deref(rnnDesc).bidir; }); } /* extern "C" miopenStatus_t miopenGetConvolutionForwardOutputDim(miopenRNNDescriptor_t rnnDesc, const miopenTensorDescriptor_t inputTensorDesc, const miopenTensorDescriptor_t filterDesc, int* n, int* c, int* h, int* w) { MIOPEN_LOG_FUNCTION(rnnDesc, inputTensorDesc, filterDesc, n, c, h, w); return miopen::try_([&] { miopen::tie_deref(n, c, h, w) = miopen::deref(rnnDesc).GetForwardOutputDim( miopen::deref(inputTensorDesc), miopen::deref(filterDesc)); }); } */ extern "C" miopenStatus_t miopenDestroyRNNDescriptor(miopenRNNDescriptor_t rnnDesc) { MIOPEN_LOG_FUNCTION(rnnDesc); return miopen::try_([&] { delete rnnDesc; }); } /* extern "C" miopenStatus_t miopenConvolutionForwardGetWorkSpaceSize(miopenHandle_t handle, const miopenTensorDescriptor_t wDesc, const miopenTensorDescriptor_t xDesc, const miopenRNNDescriptor_t rnnDesc, const miopenTensorDescriptor_t yDesc, size_t* workSpaceSize) { MIOPEN_LOG_FUNCTION(wDesc, yDesc, rnnDesc, workSpaceSize); miopen::try_([&] { miopen::deref(workSpaceSize) = miopen::deref(rnnDesc).ForwardGetWorkSpaceSize(miopen::deref(handle), miopen::deref(wDesc), miopen::deref(xDesc), miopen::deref(yDesc)); }); return (miopenStatusSuccess); } extern "C" miopenStatus_t miopenFindConvolutionForwardAlgorithm(miopenHandle_t handle, const miopenTensorDescriptor_t xDesc, const void* x, const miopenTensorDescriptor_t wDesc, const void* w, const miopenRNNDescriptor_t rnnDesc, const miopenTensorDescriptor_t yDesc, void* y, const int requestAlgoCount, int* returnedAlgoCount, miopenConvAlgoPerf_t* perfResults, void* workSpace, size_t workSpaceSize, bool exhaustiveSearch) { MIOPEN_LOG_FUNCTION(xDesc, x, wDesc, w, rnnDesc, yDesc, y, requestAlgoCount, returnedAlgoCount, perfResults, workSpace, workSpaceSize, exhaustiveSearch); return miopen::try_([&] { miopen::deref(rnnDesc).FindConvFwdAlgorithm(miopen::deref(handle), miopen::deref(xDesc), DataCast(x), miopen::deref(wDesc), DataCast(w), miopen::deref(yDesc), DataCast(y), requestAlgoCount, returnedAlgoCount, perfResults, DataCast(workSpace), workSpaceSize, exhaustiveSearch); }); } extern "C" miopenStatus_t miopenConvolutionForward(miopenHandle_t handle, const void* alpha, const miopenTensorDescriptor_t xDesc, const void* x, const miopenTensorDescriptor_t wDesc, const void* w, const miopenRNNDescriptor_t rnnDesc, miopenConvFwdAlgorithm_t algo, const void* beta, const miopenTensorDescriptor_t yDesc, void* y, void* workSpace, size_t workSpaceSize) { MIOPEN_LOG_FUNCTION( alpha, xDesc, x, wDesc, w, rnnDesc, algo, beta, yDesc, y, workSpace, workSpaceSize); return miopen::try_([&] { miopen::deref(rnnDesc).ConvolutionForward(miopen::deref(handle), alpha, miopen::deref(xDesc), DataCast(x), miopen::deref(wDesc), DataCast(w), algo, beta, miopen::deref(yDesc), DataCast(y), DataCast(workSpace), workSpaceSize); }); } extern "C" miopenStatus_t miopenConvolutionForwardBias(miopenHandle_t handle, const void* alpha, const miopenTensorDescriptor_t bDesc, const void* b, const void* beta, const miopenTensorDescriptor_t yDesc, void* y) { MIOPEN_LOG_FUNCTION(alpha, bDesc, b, beta, yDesc, y); return miopen::try_([&] { return OpTensor(miopen::deref(handle), miopenTensorOpAdd, alpha, miopen::deref(yDesc), DataCast(y), alpha, miopen::deref(bDesc), DataCast(b), beta, miopen::deref(yDesc), DataCast(y)); }); } extern "C" miopenStatus_t miopenFindConvolutionBackwardDataAlgorithm(miopenHandle_t handle, const miopenTensorDescriptor_t dyDesc, const void* dy, const miopenTensorDescriptor_t wDesc, const void* w, const miopenRNNDescriptor_t rnnDesc, const miopenTensorDescriptor_t dxDesc, const void* dx, const int requestAlgoCount, int* returnedAlgoCount, miopenConvAlgoPerf_t* perfResults, void* workSpace, size_t workSpaceSize, bool exhaustiveSearch) { MIOPEN_LOG_FUNCTION(dyDesc, dy, wDesc, w, rnnDesc, dxDesc, dx, requestAlgoCount, returnedAlgoCount, perfResults, workSpace, workSpaceSize, exhaustiveSearch); return miopen::try_([&] { miopen::deref(rnnDesc).FindConvBwdDataAlgorithm(miopen::deref(handle), miopen::deref(dyDesc), DataCast(dy), miopen::deref(wDesc), DataCast(w), miopen::deref(dxDesc), DataCast(dx), requestAlgoCount, returnedAlgoCount, perfResults, DataCast(workSpace), workSpaceSize, exhaustiveSearch); }); } extern "C" miopenStatus_t miopenConvolutionBackwardData(miopenHandle_t handle, const void* alpha, const miopenTensorDescriptor_t dyDesc, const void* dy, const miopenTensorDescriptor_t wDesc, const void* w, const miopenRNNDescriptor_t rnnDesc, miopenConvBwdDataAlgorithm_t algo, const void* beta, const miopenTensorDescriptor_t dxDesc, void* dx, void* workSpace, size_t workSpaceSize) { MIOPEN_LOG_FUNCTION( alpha, dyDesc, dy, wDesc, w, rnnDesc, algo, beta, dxDesc, dx, workSpace, workSpaceSize); return miopen::try_([&] { miopen::deref(rnnDesc).ConvolutionBackwardData(miopen::deref(handle), alpha, miopen::deref(dyDesc), DataCast(dy), miopen::deref(wDesc), DataCast(w), algo, beta, miopen::deref(dxDesc), DataCast(dx), DataCast(workSpace), workSpaceSize); }); } extern "C" miopenStatus_t miopenConvolutionBackwardDataGetWorkSpaceSize(miopenHandle_t handle, const miopenTensorDescriptor_t dyDesc, const miopenTensorDescriptor_t wDesc, const miopenRNNDescriptor_t rnnDesc, const miopenTensorDescriptor_t dxDesc, size_t* workSpaceSize) { MIOPEN_LOG_FUNCTION(dyDesc, wDesc, rnnDesc, dxDesc, workSpaceSize); return miopen::try_([&] { miopen::deref(workSpaceSize) = miopen::deref(rnnDesc).BackwardDataGetWorkSpaceSize(miopen::deref(handle), miopen::deref(wDesc), miopen::deref(dyDesc), miopen::deref(dxDesc)); }); } extern "C" miopenStatus_t miopenConvolutionBackwardWeightsGetWorkSpaceSize(miopenHandle_t handle, const miopenTensorDescriptor_t dyDesc, const miopenTensorDescriptor_t xDesc, const miopenRNNDescriptor_t rnnDesc, const miopenTensorDescriptor_t dwDesc, size_t* workSpaceSize) { MIOPEN_LOG_FUNCTION(dyDesc, xDesc, rnnDesc, dwDesc, workSpaceSize); return miopen::try_([&] { miopen::deref(workSpaceSize) = miopen::deref(rnnDesc).ConvolutionBackwardWeightsGetWorkSpaceSize( miopen::deref(handle), miopen::deref(dyDesc), miopen::deref(xDesc), miopen::deref(dwDesc)); }); } extern "C" miopenStatus_t miopenFindConvolutionBackwardWeightsAlgorithm(miopenHandle_t handle, const miopenTensorDescriptor_t dyDesc, const void* dy, const miopenTensorDescriptor_t xDesc, const void* x, const miopenRNNDescriptor_t rnnDesc, const miopenTensorDescriptor_t dwDesc, void* dw, const int requestAlgoCount, int* returnedAlgoCount, miopenConvAlgoPerf_t* perfResults, void* workSpace, size_t workSpaceSize, bool exhaustiveSearch) { MIOPEN_LOG_FUNCTION(dyDesc, dy, xDesc, x, rnnDesc, dwDesc, dw, requestAlgoCount, returnedAlgoCount, perfResults, workSpace, workSpaceSize, exhaustiveSearch); return miopen::try_([&] { miopen::deref(rnnDesc).FindConvBwdWeightsAlgorithm(miopen::deref(handle), miopen::deref(dyDesc), DataCast(dy), miopen::deref(xDesc), DataCast(x), miopen::deref(dwDesc), DataCast(dw), requestAlgoCount, returnedAlgoCount, perfResults, DataCast(workSpace), workSpaceSize, exhaustiveSearch); }); } extern "C" miopenStatus_t miopenConvolutionBackwardWeights(miopenHandle_t handle, const void* alpha, const miopenTensorDescriptor_t dyDesc, const void* dy, const miopenTensorDescriptor_t xDesc, const void* x, const miopenRNNDescriptor_t rnnDesc, miopenConvBwdWeightsAlgorithm_t algo, const void* beta, const miopenTensorDescriptor_t dwDesc, void* dw, void* workSpace, size_t workSpaceSize) { MIOPEN_LOG_FUNCTION( alpha, dyDesc, dy, xDesc, x, rnnDesc, algo, beta, dwDesc, dw, workSpace, workSpaceSize); return miopen::try_([&] { miopen::deref(rnnDesc).ConvolutionBackwardWeights(miopen::deref(handle), alpha, miopen::deref(dyDesc), DataCast(dy), miopen::deref(xDesc), DataCast(x), algo, beta, miopen::deref(dwDesc), DataCast(dw), DataCast(workSpace), workSpaceSize); }); } extern "C" miopenStatus_t miopenConvolutionBackwardBias(miopenHandle_t handle, const void* alpha, const miopenTensorDescriptor_t dyDesc, const void* dy, const void* beta, const miopenTensorDescriptor_t dbDesc, void* db) { return miopen::try_([&] { ConvolutionBackwardBias(miopen::deref(handle), alpha, miopen::deref(dyDesc), DataCast(dy), beta, miopen::deref(dbDesc), DataCast(db)); }); } */<commit_msg>debug ..<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #include <miopen/rnn.hpp> #include <miopen/errors.hpp> #include <miopen/logger.hpp> #include <miopen/tensor_ops.hpp> // TODO: Make miopenConvAlgoPerf_t loggable inline std::ostream& operator<<(std::ostream& os, miopenConvAlgoPerf_t) { return os; } extern "C" miopenStatus_t miopenCreateRNNDescriptor(miopenRNNDescriptor_t* rnnDesc) { MIOPEN_LOG_FUNCTION(rnnDesc); return miopen::try_([&] { miopen::deref(rnnDesc) = new miopen::RNNDescriptor(); }); } extern "C" miopenStatus_t miopenInitRNNDescriptor(miopenRNNDescriptor_t rnnDesc, miopenRNNMode_t mode, int seqLength, int layer, int bidir) { MIOPEN_LOG_FUNCTION(rnnDesc, mode, seqLength, layer, bidir); return miopen::try_([&] { miopen::deref(rnnDesc) = miopen::RNNDescriptor(mode, seqLength, layer, bidir); }); } extern "C" miopenStatus_t miopenGetRNNDescriptor(miopenRNNDescriptor_t rnnDesc, miopenRNNMode_t* mode, int* seqLength, int* layer, int* bidir) { MIOPEN_LOG_FUNCTION(rnnDesc, mode, seqLength, layer, bidir); return miopen::try_([&] { miopen::deref(mode) = miopen::deref(rnnDesc).mode; miopen::deref(seqLength) = miopen::deref(rnnDesc).seqLength; miopen::deref(layer) = miopen::deref(rnnDesc).layer; miopen::deref(bidir) = miopen::deref(rnnDesc).bidir; }); } /* extern "C" miopenStatus_t miopenGetConvolutionForwardOutputDim(miopenRNNDescriptor_t rnnDesc, const miopenTensorDescriptor_t inputTensorDesc, const miopenTensorDescriptor_t filterDesc, int* n, int* c, int* h, int* w) { MIOPEN_LOG_FUNCTION(rnnDesc, inputTensorDesc, filterDesc, n, c, h, w); return miopen::try_([&] { miopen::tie_deref(n, c, h, w) = miopen::deref(rnnDesc).GetForwardOutputDim( miopen::deref(inputTensorDesc), miopen::deref(filterDesc)); }); } */ extern "C" miopenStatus_t miopenDestroyRNNDescriptor(miopenRNNDescriptor_t rnnDesc) { MIOPEN_LOG_FUNCTION(rnnDesc); return miopen::try_([&] { delete rnnDesc; }); } /* extern "C" miopenStatus_t miopenConvolutionForwardGetWorkSpaceSize(miopenHandle_t handle, const miopenTensorDescriptor_t wDesc, const miopenTensorDescriptor_t xDesc, const miopenRNNDescriptor_t rnnDesc, const miopenTensorDescriptor_t yDesc, size_t* workSpaceSize) { MIOPEN_LOG_FUNCTION(wDesc, yDesc, rnnDesc, workSpaceSize); miopen::try_([&] { miopen::deref(workSpaceSize) = miopen::deref(rnnDesc).ForwardGetWorkSpaceSize(miopen::deref(handle), miopen::deref(wDesc), miopen::deref(xDesc), miopen::deref(yDesc)); }); return (miopenStatusSuccess); } extern "C" miopenStatus_t miopenFindConvolutionForwardAlgorithm(miopenHandle_t handle, const miopenTensorDescriptor_t xDesc, const void* x, const miopenTensorDescriptor_t wDesc, const void* w, const miopenRNNDescriptor_t rnnDesc, const miopenTensorDescriptor_t yDesc, void* y, const int requestAlgoCount, int* returnedAlgoCount, miopenConvAlgoPerf_t* perfResults, void* workSpace, size_t workSpaceSize, bool exhaustiveSearch) { MIOPEN_LOG_FUNCTION(xDesc, x, wDesc, w, rnnDesc, yDesc, y, requestAlgoCount, returnedAlgoCount, perfResults, workSpace, workSpaceSize, exhaustiveSearch); return miopen::try_([&] { miopen::deref(rnnDesc).FindConvFwdAlgorithm(miopen::deref(handle), miopen::deref(xDesc), DataCast(x), miopen::deref(wDesc), DataCast(w), miopen::deref(yDesc), DataCast(y), requestAlgoCount, returnedAlgoCount, perfResults, DataCast(workSpace), workSpaceSize, exhaustiveSearch); }); } extern "C" miopenStatus_t miopenConvolutionForward(miopenHandle_t handle, const void* alpha, const miopenTensorDescriptor_t xDesc, const void* x, const miopenTensorDescriptor_t wDesc, const void* w, const miopenRNNDescriptor_t rnnDesc, miopenConvFwdAlgorithm_t algo, const void* beta, const miopenTensorDescriptor_t yDesc, void* y, void* workSpace, size_t workSpaceSize) { MIOPEN_LOG_FUNCTION( alpha, xDesc, x, wDesc, w, rnnDesc, algo, beta, yDesc, y, workSpace, workSpaceSize); return miopen::try_([&] { miopen::deref(rnnDesc).ConvolutionForward(miopen::deref(handle), alpha, miopen::deref(xDesc), DataCast(x), miopen::deref(wDesc), DataCast(w), algo, beta, miopen::deref(yDesc), DataCast(y), DataCast(workSpace), workSpaceSize); }); } extern "C" miopenStatus_t miopenConvolutionForwardBias(miopenHandle_t handle, const void* alpha, const miopenTensorDescriptor_t bDesc, const void* b, const void* beta, const miopenTensorDescriptor_t yDesc, void* y) { MIOPEN_LOG_FUNCTION(alpha, bDesc, b, beta, yDesc, y); return miopen::try_([&] { return OpTensor(miopen::deref(handle), miopenTensorOpAdd, alpha, miopen::deref(yDesc), DataCast(y), alpha, miopen::deref(bDesc), DataCast(b), beta, miopen::deref(yDesc), DataCast(y)); }); } extern "C" miopenStatus_t miopenFindConvolutionBackwardDataAlgorithm(miopenHandle_t handle, const miopenTensorDescriptor_t dyDesc, const void* dy, const miopenTensorDescriptor_t wDesc, const void* w, const miopenRNNDescriptor_t rnnDesc, const miopenTensorDescriptor_t dxDesc, const void* dx, const int requestAlgoCount, int* returnedAlgoCount, miopenConvAlgoPerf_t* perfResults, void* workSpace, size_t workSpaceSize, bool exhaustiveSearch) { MIOPEN_LOG_FUNCTION(dyDesc, dy, wDesc, w, rnnDesc, dxDesc, dx, requestAlgoCount, returnedAlgoCount, perfResults, workSpace, workSpaceSize, exhaustiveSearch); return miopen::try_([&] { miopen::deref(rnnDesc).FindConvBwdDataAlgorithm(miopen::deref(handle), miopen::deref(dyDesc), DataCast(dy), miopen::deref(wDesc), DataCast(w), miopen::deref(dxDesc), DataCast(dx), requestAlgoCount, returnedAlgoCount, perfResults, DataCast(workSpace), workSpaceSize, exhaustiveSearch); }); } extern "C" miopenStatus_t miopenConvolutionBackwardData(miopenHandle_t handle, const void* alpha, const miopenTensorDescriptor_t dyDesc, const void* dy, const miopenTensorDescriptor_t wDesc, const void* w, const miopenRNNDescriptor_t rnnDesc, miopenConvBwdDataAlgorithm_t algo, const void* beta, const miopenTensorDescriptor_t dxDesc, void* dx, void* workSpace, size_t workSpaceSize) { MIOPEN_LOG_FUNCTION( alpha, dyDesc, dy, wDesc, w, rnnDesc, algo, beta, dxDesc, dx, workSpace, workSpaceSize); return miopen::try_([&] { miopen::deref(rnnDesc).ConvolutionBackwardData(miopen::deref(handle), alpha, miopen::deref(dyDesc), DataCast(dy), miopen::deref(wDesc), DataCast(w), algo, beta, miopen::deref(dxDesc), DataCast(dx), DataCast(workSpace), workSpaceSize); }); } extern "C" miopenStatus_t miopenConvolutionBackwardDataGetWorkSpaceSize(miopenHandle_t handle, const miopenTensorDescriptor_t dyDesc, const miopenTensorDescriptor_t wDesc, const miopenRNNDescriptor_t rnnDesc, const miopenTensorDescriptor_t dxDesc, size_t* workSpaceSize) { MIOPEN_LOG_FUNCTION(dyDesc, wDesc, rnnDesc, dxDesc, workSpaceSize); return miopen::try_([&] { miopen::deref(workSpaceSize) = miopen::deref(rnnDesc).BackwardDataGetWorkSpaceSize(miopen::deref(handle), miopen::deref(wDesc), miopen::deref(dyDesc), miopen::deref(dxDesc)); }); } extern "C" miopenStatus_t miopenConvolutionBackwardWeightsGetWorkSpaceSize(miopenHandle_t handle, const miopenTensorDescriptor_t dyDesc, const miopenTensorDescriptor_t xDesc, const miopenRNNDescriptor_t rnnDesc, const miopenTensorDescriptor_t dwDesc, size_t* workSpaceSize) { MIOPEN_LOG_FUNCTION(dyDesc, xDesc, rnnDesc, dwDesc, workSpaceSize); return miopen::try_([&] { miopen::deref(workSpaceSize) = miopen::deref(rnnDesc).ConvolutionBackwardWeightsGetWorkSpaceSize( miopen::deref(handle), miopen::deref(dyDesc), miopen::deref(xDesc), miopen::deref(dwDesc)); }); } extern "C" miopenStatus_t miopenFindConvolutionBackwardWeightsAlgorithm(miopenHandle_t handle, const miopenTensorDescriptor_t dyDesc, const void* dy, const miopenTensorDescriptor_t xDesc, const void* x, const miopenRNNDescriptor_t rnnDesc, const miopenTensorDescriptor_t dwDesc, void* dw, const int requestAlgoCount, int* returnedAlgoCount, miopenConvAlgoPerf_t* perfResults, void* workSpace, size_t workSpaceSize, bool exhaustiveSearch) { MIOPEN_LOG_FUNCTION(dyDesc, dy, xDesc, x, rnnDesc, dwDesc, dw, requestAlgoCount, returnedAlgoCount, perfResults, workSpace, workSpaceSize, exhaustiveSearch); return miopen::try_([&] { miopen::deref(rnnDesc).FindConvBwdWeightsAlgorithm(miopen::deref(handle), miopen::deref(dyDesc), DataCast(dy), miopen::deref(xDesc), DataCast(x), miopen::deref(dwDesc), DataCast(dw), requestAlgoCount, returnedAlgoCount, perfResults, DataCast(workSpace), workSpaceSize, exhaustiveSearch); }); } extern "C" miopenStatus_t miopenConvolutionBackwardWeights(miopenHandle_t handle, const void* alpha, const miopenTensorDescriptor_t dyDesc, const void* dy, const miopenTensorDescriptor_t xDesc, const void* x, const miopenRNNDescriptor_t rnnDesc, miopenConvBwdWeightsAlgorithm_t algo, const void* beta, const miopenTensorDescriptor_t dwDesc, void* dw, void* workSpace, size_t workSpaceSize) { MIOPEN_LOG_FUNCTION( alpha, dyDesc, dy, xDesc, x, rnnDesc, algo, beta, dwDesc, dw, workSpace, workSpaceSize); return miopen::try_([&] { miopen::deref(rnnDesc).ConvolutionBackwardWeights(miopen::deref(handle), alpha, miopen::deref(dyDesc), DataCast(dy), miopen::deref(xDesc), DataCast(x), algo, beta, miopen::deref(dwDesc), DataCast(dw), DataCast(workSpace), workSpaceSize); }); } extern "C" miopenStatus_t miopenConvolutionBackwardBias(miopenHandle_t handle, const void* alpha, const miopenTensorDescriptor_t dyDesc, const void* dy, const void* beta, const miopenTensorDescriptor_t dbDesc, void* db) { return miopen::try_([&] { ConvolutionBackwardBias(miopen::deref(handle), alpha, miopen::deref(dyDesc), DataCast(dy), beta, miopen::deref(dbDesc), DataCast(db)); }); } */<|endoftext|>
<commit_before>/* * Session management. * * author: Max Kellermann <[email protected]> */ #include "session.hxx" #include "cookie_jar.hxx" #include "shm/dpool.hxx" #include "shm/dbuffer.hxx" #include "expiry.h" #include "crash.hxx" #include "expiry.h" #include <daemon/log.h> #include <assert.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <event.h> #define SESSION_TTL_NEW 120 inline Session::Session(struct dpool *_pool) :pool(_pool), expires(expiry_touch(SESSION_TTL_NEW)), counter(1), is_new(true), cookie_sent(false), cookie_received(false), realm(nullptr), translate(nullptr), user(nullptr), user_expires(0), language(nullptr), cookies(cookie_jar_new(*_pool)) { lock_init(&lock); } inline Session::Session(struct dpool *_pool, const Session &src) :pool(_pool), id(src.id), expires(src.expires), counter(1), is_new(src.is_new), cookie_sent(src.cookie_sent), cookie_received(src.cookie_received), realm(d_strdup_checked(pool, src.realm)), translate(DupBuffer(pool, src.translate)), user(d_strdup_checked(pool, src.user)), user_expires(0), language(d_strdup_checked(pool, src.language)), cookies(src.cookies->Dup(*pool)) { lock_init(&lock); } inline Session::~Session() { lock_destroy(&lock); } Session * session_allocate(struct dpool *pool) { return NewFromPool<Session>(pool, pool); } void session_destroy(Session *session) { DeleteDestroyPool(*session->pool, session); } /** * Calculates the score for purging the session: higher score means * more likely to be purged. */ unsigned session_purge_score(const Session *session) { if (session->is_new) return 1000; if (!session->cookie_received) return 50; if (session->user == nullptr) return 20; return 1; } void session_clear_translate(Session *session) { assert(crash_in_unsafe()); assert(session != nullptr); if (!session->translate.IsEmpty()) { d_free(session->pool, session->translate.data); session->translate = nullptr; } } void session_clear_user(Session *session) { assert(crash_in_unsafe()); assert(session != nullptr); if (session->user != nullptr) { d_free(session->pool, session->user); session->user = nullptr; } } void session_clear_language(Session *session) { assert(crash_in_unsafe()); assert(session != nullptr); if (session->language != nullptr) { d_free(session->pool, session->language); session->language = nullptr; } } bool session_set_translate(Session *session, ConstBuffer<void> translate) { assert(crash_in_unsafe()); assert(session != nullptr); assert(!translate.IsNull()); if (!session->translate.IsNull() && session->translate.size == translate.size && memcmp(session->translate.data, translate.data, translate.size) == 0) /* same value as before: no-op */ return true; session_clear_translate(session); session->translate = DupBuffer(session->pool, translate); return !session->translate.IsNull(); } bool session_set_user(Session *session, const char *user, unsigned max_age) { assert(crash_in_unsafe()); assert(session != nullptr); assert(user != nullptr); if (session->user == nullptr || strcmp(session->user, user) != 0) { session_clear_user(session); session->user = d_strdup(session->pool, user); if (session->user == nullptr) return false; } if (max_age == (unsigned)-1) /* never expires */ session->user_expires = 0; else if (max_age == 0) /* expires immediately, use only once */ session->user_expires = 1; else session->user_expires = expiry_touch(max_age); return true; } bool session_set_language(Session *session, const char *language) { assert(crash_in_unsafe()); assert(session != nullptr); assert(language != nullptr); if (session->language != nullptr && strcmp(session->language, language) == 0) /* same value as before: no-op */ return true; session_clear_language(session); session->language = d_strdup(session->pool, language); return session->language != nullptr; } static WidgetSession::Set widget_session_map_dup(struct dpool *pool, const WidgetSession::Set &src, Session *session, WidgetSession *parent); gcc_malloc static WidgetSession * widget_session_dup(struct dpool *pool, const WidgetSession *src, Session *session) { assert(crash_in_unsafe()); assert(src != nullptr); assert(src->id != nullptr); auto *dest = NewFromPool<WidgetSession>(pool); if (dest == nullptr) return nullptr; dest->id = d_strdup(pool, src->id); if (dest->id == nullptr) return nullptr; dest->children = widget_session_map_dup(pool, src->children, session, dest); if (src->path_info != nullptr) { dest->path_info = d_strdup(pool, src->path_info); if (dest->path_info == nullptr) return nullptr; } else dest->path_info = nullptr; if (src->query_string != nullptr) { dest->query_string = d_strdup(pool, src->query_string); if (dest->query_string == nullptr) return nullptr; } else dest->query_string = nullptr; return dest; } static WidgetSession::Set widget_session_map_dup(struct dpool *pool, const WidgetSession::Set &src, Session *session, WidgetSession *parent) { assert(crash_in_unsafe()); WidgetSession::Set dest; for (const auto &src_ws : src) { WidgetSession *dest_ws = widget_session_dup(pool, &src_ws, session); if (dest_ws == nullptr) break; dest_ws->parent = parent; dest_ws->session = session; dest.insert(*dest_ws); } return std::move(dest); } Session * session_dup(struct dpool *pool, const Session *src) { assert(crash_in_unsafe()); auto *dest = NewFromPool<Session>(pool, pool, *src); if (dest == nullptr) return nullptr; dest->widgets = widget_session_map_dup(pool, src->widgets, dest, nullptr); return dest; } WidgetSession * widget_session_allocate(Session *session) { auto *ws = NewFromPool<WidgetSession>(session->pool); if (ws == nullptr) return nullptr; ws->session = session; return ws; } static WidgetSession * hashmap_r_get_widget_session(Session *session, WidgetSession::Set &set, const char *id, bool create) { assert(crash_in_unsafe()); assert(session != nullptr); assert(lock_is_locked(&session->lock)); assert(id != nullptr); auto i = set.find(id, WidgetSession::Compare()); if (i != set.end()) return &*i; if (!create) return nullptr; auto *ws = widget_session_allocate(session); if (ws == nullptr) return nullptr; ws->parent = nullptr; ws->id = d_strdup(session->pool, id); if (ws->id == nullptr) { DeleteFromPool(session->pool, ws); return nullptr; } ws->path_info = nullptr; ws->query_string = nullptr; set.insert(*ws); return ws; } WidgetSession * session_get_widget(Session *session, const char *id, bool create) { assert(crash_in_unsafe()); assert(session != nullptr); assert(id != nullptr); return hashmap_r_get_widget_session(session, session->widgets, id, create); } WidgetSession * widget_session_get_child(WidgetSession *parent, const char *id, bool create) { assert(crash_in_unsafe()); assert(parent != nullptr); assert(parent->session != nullptr); assert(id != nullptr); return hashmap_r_get_widget_session(parent->session, parent->children, id, create); } static void widget_session_free(struct dpool *pool, WidgetSession *ws) { assert(crash_in_unsafe()); d_free(pool, ws->id); if (ws->path_info != nullptr) d_free(pool, ws->path_info); if (ws->query_string != nullptr) d_free(pool, ws->query_string); DeleteFromPool(pool, ws); } static void widget_session_clear_map(struct dpool *pool, WidgetSession::Set &set) { assert(crash_in_unsafe()); assert(pool != nullptr); set.clear_and_dispose([pool](WidgetSession *ws){ widget_session_delete(pool, ws); }); } void widget_session_delete(struct dpool *pool, WidgetSession *ws) { assert(crash_in_unsafe()); assert(pool != nullptr); assert(ws != nullptr); widget_session_clear_map(pool, ws->children); widget_session_free(pool, ws); } void session_delete_widgets(Session *session) { assert(crash_in_unsafe()); assert(session != nullptr); widget_session_clear_map(session->pool, session->widgets); } <commit_msg>session: use unchecked version of d_strdup() to copy realm name<commit_after>/* * Session management. * * author: Max Kellermann <[email protected]> */ #include "session.hxx" #include "cookie_jar.hxx" #include "shm/dpool.hxx" #include "shm/dbuffer.hxx" #include "expiry.h" #include "crash.hxx" #include "expiry.h" #include <daemon/log.h> #include <assert.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <event.h> #define SESSION_TTL_NEW 120 inline Session::Session(struct dpool *_pool) :pool(_pool), expires(expiry_touch(SESSION_TTL_NEW)), counter(1), is_new(true), cookie_sent(false), cookie_received(false), realm(nullptr), translate(nullptr), user(nullptr), user_expires(0), language(nullptr), cookies(cookie_jar_new(*_pool)) { lock_init(&lock); } inline Session::Session(struct dpool *_pool, const Session &src) :pool(_pool), id(src.id), expires(src.expires), counter(1), is_new(src.is_new), cookie_sent(src.cookie_sent), cookie_received(src.cookie_received), realm(d_strdup(pool, src.realm)), translate(DupBuffer(pool, src.translate)), user(d_strdup_checked(pool, src.user)), user_expires(0), language(d_strdup_checked(pool, src.language)), cookies(src.cookies->Dup(*pool)) { lock_init(&lock); } inline Session::~Session() { lock_destroy(&lock); } Session * session_allocate(struct dpool *pool) { return NewFromPool<Session>(pool, pool); } void session_destroy(Session *session) { DeleteDestroyPool(*session->pool, session); } /** * Calculates the score for purging the session: higher score means * more likely to be purged. */ unsigned session_purge_score(const Session *session) { if (session->is_new) return 1000; if (!session->cookie_received) return 50; if (session->user == nullptr) return 20; return 1; } void session_clear_translate(Session *session) { assert(crash_in_unsafe()); assert(session != nullptr); if (!session->translate.IsEmpty()) { d_free(session->pool, session->translate.data); session->translate = nullptr; } } void session_clear_user(Session *session) { assert(crash_in_unsafe()); assert(session != nullptr); if (session->user != nullptr) { d_free(session->pool, session->user); session->user = nullptr; } } void session_clear_language(Session *session) { assert(crash_in_unsafe()); assert(session != nullptr); if (session->language != nullptr) { d_free(session->pool, session->language); session->language = nullptr; } } bool session_set_translate(Session *session, ConstBuffer<void> translate) { assert(crash_in_unsafe()); assert(session != nullptr); assert(!translate.IsNull()); if (!session->translate.IsNull() && session->translate.size == translate.size && memcmp(session->translate.data, translate.data, translate.size) == 0) /* same value as before: no-op */ return true; session_clear_translate(session); session->translate = DupBuffer(session->pool, translate); return !session->translate.IsNull(); } bool session_set_user(Session *session, const char *user, unsigned max_age) { assert(crash_in_unsafe()); assert(session != nullptr); assert(user != nullptr); if (session->user == nullptr || strcmp(session->user, user) != 0) { session_clear_user(session); session->user = d_strdup(session->pool, user); if (session->user == nullptr) return false; } if (max_age == (unsigned)-1) /* never expires */ session->user_expires = 0; else if (max_age == 0) /* expires immediately, use only once */ session->user_expires = 1; else session->user_expires = expiry_touch(max_age); return true; } bool session_set_language(Session *session, const char *language) { assert(crash_in_unsafe()); assert(session != nullptr); assert(language != nullptr); if (session->language != nullptr && strcmp(session->language, language) == 0) /* same value as before: no-op */ return true; session_clear_language(session); session->language = d_strdup(session->pool, language); return session->language != nullptr; } static WidgetSession::Set widget_session_map_dup(struct dpool *pool, const WidgetSession::Set &src, Session *session, WidgetSession *parent); gcc_malloc static WidgetSession * widget_session_dup(struct dpool *pool, const WidgetSession *src, Session *session) { assert(crash_in_unsafe()); assert(src != nullptr); assert(src->id != nullptr); auto *dest = NewFromPool<WidgetSession>(pool); if (dest == nullptr) return nullptr; dest->id = d_strdup(pool, src->id); if (dest->id == nullptr) return nullptr; dest->children = widget_session_map_dup(pool, src->children, session, dest); if (src->path_info != nullptr) { dest->path_info = d_strdup(pool, src->path_info); if (dest->path_info == nullptr) return nullptr; } else dest->path_info = nullptr; if (src->query_string != nullptr) { dest->query_string = d_strdup(pool, src->query_string); if (dest->query_string == nullptr) return nullptr; } else dest->query_string = nullptr; return dest; } static WidgetSession::Set widget_session_map_dup(struct dpool *pool, const WidgetSession::Set &src, Session *session, WidgetSession *parent) { assert(crash_in_unsafe()); WidgetSession::Set dest; for (const auto &src_ws : src) { WidgetSession *dest_ws = widget_session_dup(pool, &src_ws, session); if (dest_ws == nullptr) break; dest_ws->parent = parent; dest_ws->session = session; dest.insert(*dest_ws); } return std::move(dest); } Session * session_dup(struct dpool *pool, const Session *src) { assert(crash_in_unsafe()); auto *dest = NewFromPool<Session>(pool, pool, *src); if (dest == nullptr) return nullptr; dest->widgets = widget_session_map_dup(pool, src->widgets, dest, nullptr); return dest; } WidgetSession * widget_session_allocate(Session *session) { auto *ws = NewFromPool<WidgetSession>(session->pool); if (ws == nullptr) return nullptr; ws->session = session; return ws; } static WidgetSession * hashmap_r_get_widget_session(Session *session, WidgetSession::Set &set, const char *id, bool create) { assert(crash_in_unsafe()); assert(session != nullptr); assert(lock_is_locked(&session->lock)); assert(id != nullptr); auto i = set.find(id, WidgetSession::Compare()); if (i != set.end()) return &*i; if (!create) return nullptr; auto *ws = widget_session_allocate(session); if (ws == nullptr) return nullptr; ws->parent = nullptr; ws->id = d_strdup(session->pool, id); if (ws->id == nullptr) { DeleteFromPool(session->pool, ws); return nullptr; } ws->path_info = nullptr; ws->query_string = nullptr; set.insert(*ws); return ws; } WidgetSession * session_get_widget(Session *session, const char *id, bool create) { assert(crash_in_unsafe()); assert(session != nullptr); assert(id != nullptr); return hashmap_r_get_widget_session(session, session->widgets, id, create); } WidgetSession * widget_session_get_child(WidgetSession *parent, const char *id, bool create) { assert(crash_in_unsafe()); assert(parent != nullptr); assert(parent->session != nullptr); assert(id != nullptr); return hashmap_r_get_widget_session(parent->session, parent->children, id, create); } static void widget_session_free(struct dpool *pool, WidgetSession *ws) { assert(crash_in_unsafe()); d_free(pool, ws->id); if (ws->path_info != nullptr) d_free(pool, ws->path_info); if (ws->query_string != nullptr) d_free(pool, ws->query_string); DeleteFromPool(pool, ws); } static void widget_session_clear_map(struct dpool *pool, WidgetSession::Set &set) { assert(crash_in_unsafe()); assert(pool != nullptr); set.clear_and_dispose([pool](WidgetSession *ws){ widget_session_delete(pool, ws); }); } void widget_session_delete(struct dpool *pool, WidgetSession *ws) { assert(crash_in_unsafe()); assert(pool != nullptr); assert(ws != nullptr); widget_session_clear_map(pool, ws->children); widget_session_free(pool, ws); } void session_delete_widgets(Session *session) { assert(crash_in_unsafe()); assert(session != nullptr); widget_session_clear_map(session->pool, session->widgets); } <|endoftext|>
<commit_before>#include <faunus/species.h> #include <faunus/inputfile.h> #include <faunus/textio.h> #include <faunus/physconst.h> #include <faunus/json.h> #include <stdlib.h> namespace Faunus { AtomData::AtomData() { activity=0; charge=0; dp=0; dprot=0; eps=0; hydrophobic=0; mean=0; muscalar=0; mw=1.0; name="UNK"; patchtype=0; radius=0; sigma=0; variance=0; len=0; half_len=0; pswitch=0; pdis=0; pangl=0; panglsw=0; //rcutwca=0; //rcut=0; //pcangl=0; //pcanglsw=0; //pcoshalfi=0; //psinhalfi=0; chiral_angle=0; mu.clear(); theta.clear(); alpha.clear(); } AtomMap::AtomMap() { AtomData a; a.id=list.size(); a.name="UNK"; list.push_back(a); } AtomData & AtomMap::operator[] (AtomData::Tid i) { return list.at(i); } AtomData & AtomMap::operator[] (string s) { for (auto &l_i : list) if (s==l_i.name) return l_i; return list.at(0); } /** * This will look for the keyword `atomlist` in the InputMap and * use value as the filename.fs */ bool AtomMap::includefile(InputMap &in) { return includefile( in.get<string>("atomlist",filename) ); } bool AtomMap::includeJSON(const string& file) { int n=0; filename=file; std::vector<double> test1 (3,0); auto j=json::open(file); for (auto &atom : json::object("atomlist", j)) { n++; AtomData a; //Tensor<double> fallback; //fallback.clear(); a.name = atom.first; a.activity = json::value<double>(atom.second, "activity", 0); a.alpha << json::value<std::string>(atom.second, "alpha", ""); a.alpha *= 4*pc::pi*pc::e0*(1e-10)*pc::kT()/(pc::e*pc::e); a.theta << json::value<std::string>(atom.second, "theta", ""); a.theta *= 0.20819434; // Debye Å -> e Å^2 a.dp = json::value<double>(atom.second, "dp", 0); a.dprot = json::value<double>(atom.second, "dprot", 0) * pc::pi / 180.; // deg->rads a.eps = json::value<double>(atom.second, "eps", 0); a.hydrophobic = json::value<bool>(atom.second, "hydrophobic", false); a.mu << json::value<std::string>(atom.second, "mu", "0 0 0"); a.muscalar = a.mu.len()*pc::D2eA(); if (a.mu.len()>1e-6) a.mu = a.mu/a.mu.len(); a.mw = json::value<double>(atom.second, "Mw", 1.); a.charge = json::value<double>(atom.second, "q", 0); a.radius = json::value<double>(atom.second, "r", 0); a.sigma = 2*a.radius; a.sigma = json::value<double>(atom.second, "sigma", a.sigma); a.radius = a.sigma/2; a.id=AtomData::Tid( list.size() ); a.half_len = 0.5 * json::value<double>(atom.second, "len", 0); a.patchtype = json::value<double>(atom.second, "patchtype", 0); a.pswitch = json::value<double>(atom.second, "patchswitch", 0); a.pdis = json::value<double>(atom.second, "patchdistance", 0); a.pangl = json::value<double>(atom.second, "patchangle", 0)/180.0*pc::pi; a.panglsw = json::value<double>(atom.second, "patchangleswitch", 0)/180.0*pc::pi; a.chiral_angle = json::value<double>(atom.second, "patchchiralangle", 0)/180.0*pc::pi; // add to particle list bool insert=true; for (auto &i : list) if (i.name==a.name) { i=a; // override existing insert=false; break; } if (insert) list.push_back(a); } return (n>0) ? true : false; } /** * This will automatically detect if the file is a JSON * file and call includeJSON(). If not, the old restricted * file format is used. */ bool AtomMap::includefile(string file) { // is it a JSON file? if (file.substr(file.find_last_of(".") + 1) == "json") return includeJSON(file); AtomData a; string t; filename=file; std::ifstream f(filename.c_str()); cout << "Reading atom data from '" << filename << "'. "; if (f) { cout << "OK!\n"; while (!f.eof()) { f >> t; if (t=="Atom") { f >> a.name >> a.charge >> a.radius >> a.eps >> a.mw >> t; a.sigma=2*a.radius; a.hydrophobic = (t=="yes") ? true : false; a.id=list.size(); list.push_back(a); } } return true; } cout << "FAILED!\n"; filename+=" (n/a)"; return false; } string AtomMap::info() { using namespace textio; char w=25; if (filename.empty()) filename="(undefined)"; std::ostringstream o; o << header("Atomic Species") << pad(SUB,w,"Number of species") << list.size() << endl << pad(SUB,w,"Parameter file") << filename << endl << indent(SUB) << "Species:"; for (size_t i=0; i<list.size(); i++) { if (i%10==0) o << endl << indent(SUBSUB); o << setw(SUBSUB+1) << std::left << list[i].name; } o << endl; return o.str(); } AtomMap atom; // Instantiate global copy }//namespace <commit_msg>Fixed a bug for duplicate species<commit_after>#include <faunus/species.h> #include <faunus/inputfile.h> #include <faunus/textio.h> #include <faunus/physconst.h> #include <faunus/json.h> #include <stdlib.h> namespace Faunus { AtomData::AtomData() { activity=0; charge=0; dp=0; dprot=0; eps=0; hydrophobic=0; mean=0; muscalar=0; mw=1.0; name="UNK"; patchtype=0; radius=0; sigma=0; variance=0; len=0; half_len=0; pswitch=0; pdis=0; pangl=0; panglsw=0; //rcutwca=0; //rcut=0; //pcangl=0; //pcanglsw=0; //pcoshalfi=0; //psinhalfi=0; chiral_angle=0; mu.clear(); theta.clear(); alpha.clear(); } AtomMap::AtomMap() { AtomData a; a.id=list.size(); a.name="UNK"; list.push_back(a); } AtomData & AtomMap::operator[] (AtomData::Tid i) { assert(i>=0 && i<list.size() && "Particle id not found!"); return list.at(i); } AtomData & AtomMap::operator[] (string s) { for (auto &l_i : list) if (s==l_i.name) return l_i; return list.at(0); } /** * This will look for the keyword `atomlist` in the InputMap and * use value as the filename.fs */ bool AtomMap::includefile(InputMap &in) { return includefile( in.get<string>("atomlist",filename) ); } bool AtomMap::includeJSON(const string& file) { int n=0; filename=file; auto j=json::open(file); for (auto &atom : json::object("atomlist", j)) { n++; AtomData a; //Tensor<double> fallback; //fallback.clear(); a.name = atom.first; a.activity = json::value<double>(atom.second, "activity", 0); a.alpha << json::value<std::string>(atom.second, "alpha", ""); a.alpha *= 4*pc::pi*pc::e0*(1e-10)*pc::kT()/(pc::e*pc::e); a.theta << json::value<std::string>(atom.second, "theta", ""); a.theta *= 0.20819434; // Debye Å -> e Å^2 a.dp = json::value<double>(atom.second, "dp", 0); a.dprot = json::value<double>(atom.second, "dprot", 0) * pc::pi / 180.; // deg->rads a.eps = json::value<double>(atom.second, "eps", 0); a.hydrophobic = json::value<bool>(atom.second, "hydrophobic", false); a.mu << json::value<std::string>(atom.second, "mu", "0 0 0"); a.muscalar = a.mu.len()*pc::D2eA(); if (a.mu.len()>1e-6) a.mu = a.mu/a.mu.len(); a.mw = json::value<double>(atom.second, "Mw", 1.); a.charge = json::value<double>(atom.second, "q", 0); a.radius = json::value<double>(atom.second, "r", 0); a.sigma = 2*a.radius; a.sigma = json::value<double>(atom.second, "sigma", a.sigma); a.radius = a.sigma/2; a.id=AtomData::Tid( list.size() ); a.half_len = 0.5 * json::value<double>(atom.second, "len", 0); a.patchtype = json::value<double>(atom.second, "patchtype", 0); a.pswitch = json::value<double>(atom.second, "patchswitch", 0); a.pdis = json::value<double>(atom.second, "patchdistance", 0); a.pangl = json::value<double>(atom.second, "patchangle", 0)/180.0*pc::pi; a.panglsw = json::value<double>(atom.second, "patchangleswitch", 0)/180.0*pc::pi; a.chiral_angle = json::value<double>(atom.second, "patchchiralangle", 0)/180.0*pc::pi; // add to particle list bool insert=true; for (auto &i : list) if (i.name==a.name) { a.id=i.id; // keep old id and i=a; // override existing insert=false; break; } if (insert) list.push_back(a); } return (n>0) ? true : false; } /** * This will automatically detect if the file is a JSON * file and call includeJSON(). If not, the old restricted * file format is used. */ bool AtomMap::includefile(string file) { // is it a JSON file? if (file.substr(file.find_last_of(".") + 1) == "json") return includeJSON(file); AtomData a; string t; filename=file; std::ifstream f(filename.c_str()); cout << "Reading atom data from '" << filename << "'. "; if (f) { cout << "OK!\n"; while (!f.eof()) { f >> t; if (t=="Atom") { f >> a.name >> a.charge >> a.radius >> a.eps >> a.mw >> t; a.sigma=2*a.radius; a.hydrophobic = (t=="yes") ? true : false; a.id=list.size(); list.push_back(a); } } return true; } cout << "FAILED!\n"; filename+=" (n/a)"; return false; } string AtomMap::info() { using namespace textio; char w=25; if (filename.empty()) filename="(undefined)"; std::ostringstream o; o << header("Atomic Species") << pad(SUB,w,"Number of species") << list.size() << endl << pad(SUB,w,"Parameter file") << filename << endl << indent(SUB) << "Species:"; for (size_t i=0; i<list.size(); i++) { if (i%10==0) o << endl << indent(SUBSUB); o << setw(SUBSUB+1) << std::left << list[i].name; } o << endl; return o.str(); } AtomMap atom; // Instantiate global copy }//namespace <|endoftext|>
<commit_before>#include "openmc/summary.h" #include <fmt/core.h> #include "openmc/capi.h" #include "openmc/cell.h" #include "openmc/file_utils.h" #include "openmc/hdf5_interface.h" #include "openmc/lattice.h" #include "openmc/material.h" #include "openmc/mgxs_interface.h" #include "openmc/nuclide.h" #include "openmc/output.h" #include "openmc/surface.h" #include "openmc/settings.h" namespace openmc { void write_summary() { // Display output message write_message("Writing summary.h5 file...", 5); // Create a new file using default properties. hid_t file = file_open("summary.h5", 'w'); write_header(file); write_nuclides(file); write_geometry(file); write_materials(file); // Terminate access to the file. file_close(file); } void write_header(hid_t file) { // Write filetype and version info write_attribute(file, "filetype", "summary"); write_attribute(file, "version", VERSION_SUMMARY); write_attribute(file, "openmc_version", VERSION); #ifdef GIT_SHA1 write_attribute(file, "git_sha1", GIT_SHA1); #endif // Write current date and time write_attribute(file, "date_and_time", time_stamp()); } void write_nuclides(hid_t file) { // Build vectors of nuclide names and awrs while only sorting nuclides from // macroscopics vector<std::string> nuc_names; vector<std::string> macro_names; vector<double> awrs; for (int i = 0; i < data::nuclides.size(); ++i) { if (settings::run_CE) { const auto& nuc {data::nuclides[i]}; nuc_names.push_back(nuc->name_); awrs.push_back(nuc->awr_); } else { const auto& nuc {data::mg.nuclides_[i]}; if (nuc.awr != MACROSCOPIC_AWR) { nuc_names.push_back(nuc.name); awrs.push_back(nuc.awr); } else { macro_names.push_back(nuc.name); } } } hid_t nuclide_group = create_group(file, "nuclides"); write_attribute(nuclide_group, "n_nuclides", nuc_names.size()); hid_t macro_group = create_group(file, "macroscopics"); write_attribute(macro_group, "n_macroscopics", macro_names.size()); // Write nuclide names and awrs if (!nuc_names.empty()) { // Write useful data from nuclide objects write_dataset(nuclide_group, "names", nuc_names); write_dataset(nuclide_group, "awrs", awrs); } if (!macro_names.empty()) { // Write useful data from macroscopic objects write_dataset(macro_group, "names", macro_names); } close_group(nuclide_group); close_group(macro_group); } void write_geometry(hid_t file) { auto geom_group = create_group(file, "geometry"); #ifdef DAGMC if (settings::dagmc) { write_attribute(geom_group, "dagmc", 1); close_group(geom_group); return; } #endif write_attribute(geom_group, "n_cells", model::cells.size()); write_attribute(geom_group, "n_surfaces", model::surfaces.size()); write_attribute(geom_group, "n_universes", model::universes.size()); write_attribute(geom_group, "n_lattices", model::lattices.size()); auto cells_group = create_group(geom_group, "cells"); for (const auto& c : model::cells) c->to_hdf5(cells_group); close_group(cells_group); auto surfaces_group = create_group(geom_group, "surfaces"); for (const auto& surf : model::surfaces) surf->to_hdf5(surfaces_group); close_group(surfaces_group); auto universes_group = create_group(geom_group, "universes"); for (const auto& u : model::universes) u->to_hdf5(universes_group); close_group(universes_group); auto lattices_group = create_group(geom_group, "lattices"); for (const auto& lat : model::lattices) lat->to_hdf5(lattices_group); close_group(lattices_group); close_group(geom_group); } void write_materials(hid_t file) { // write number of materials write_dataset(file, "n_materials", model::materials.size()); hid_t materials_group = create_group(file, "materials"); for (const auto& mat : model::materials) { mat->to_hdf5(materials_group); } close_group(materials_group); } //============================================================================== // C API //============================================================================== extern "C" int openmc_properties_export(const char* filename) { // Set a default filename if none was passed std::string name = filename ? filename : "properties.h5"; // Display output message auto msg = fmt::format("Exporting properties to {}...", name); write_message(msg, 5); // Create a new file using default properties. hid_t file = file_open(name, 'w'); // Write metadata write_attribute(file, "filetype", "properties"); write_attribute(file, "version", VERSION_STATEPOINT); write_attribute(file, "openmc_version", VERSION); #ifdef GIT_SHA1 write_attribute(file, "git_sha1", GIT_SHA1); #endif write_attribute(file, "date_and_time", time_stamp()); write_attribute(file, "path", settings::path_input); // Write cell properties auto geom_group = create_group(file, "geometry"); write_attribute(geom_group, "n_cells", model::cells.size()); auto cells_group = create_group(geom_group, "cells"); for (const auto& c : model::cells) { c->export_properties_hdf5(cells_group); } close_group(cells_group); close_group(geom_group); // Write material properties hid_t materials_group = create_group(file, "materials"); write_attribute(materials_group, "n_materials", model::materials.size()); for (const auto& mat : model::materials) { mat->export_properties_hdf5(materials_group); } close_group(materials_group); // Terminate access to the file. file_close(file); return 0; } extern "C" int openmc_properties_import(const char* filename) { // Display output message auto msg = fmt::format("Importing properties from {}...", filename); write_message(msg, 5); // Create a new file using default properties. if (!file_exists(filename)) { set_errmsg(fmt::format("File '{}' does not exist.", filename)); return OPENMC_E_INVALID_ARGUMENT; } hid_t file = file_open(filename, 'r'); // Ensure the filetype is correct std::string filetype; read_attribute(file, "filetype", filetype); if (filetype != "properties") { set_errmsg(fmt::format("File '{}' is not a properties file.", filename)); return OPENMC_E_INVALID_ARGUMENT; } // Make sure number of cells matches auto geom_group = open_group(file, "geometry"); int32_t n; read_attribute(geom_group, "n_cells", n); if (n != openmc::model::cells.size()) { set_errmsg(fmt::format("Number of cells in {} doesn't match current model.", filename)); return OPENMC_E_GEOMETRY; } // Read cell properties auto cells_group = open_group(geom_group, "cells"); for (const auto& c : model::cells) { c->import_properties_hdf5(cells_group); } close_group(cells_group); close_group(geom_group); // Make sure number of cells matches auto materials_group = open_group(file, "materials"); read_attribute(materials_group, "n_materials", n); if (n != openmc::model::materials.size()) { set_errmsg(fmt::format("Number of materials in {} doesn't match current model.", filename)); return OPENMC_E_GEOMETRY; } // Read material properties for (const auto& mat : model::materials) { mat->import_properties_hdf5(materials_group); } close_group(materials_group); // Terminate access to the file. file_close(file); return 0; } } // namespace openmc <commit_msg>Make sure properties.h5 gets closed properly upon error<commit_after>#include "openmc/summary.h" #include <fmt/core.h> #include "openmc/capi.h" #include "openmc/cell.h" #include "openmc/file_utils.h" #include "openmc/hdf5_interface.h" #include "openmc/lattice.h" #include "openmc/material.h" #include "openmc/mgxs_interface.h" #include "openmc/nuclide.h" #include "openmc/output.h" #include "openmc/surface.h" #include "openmc/settings.h" namespace openmc { void write_summary() { // Display output message write_message("Writing summary.h5 file...", 5); // Create a new file using default properties. hid_t file = file_open("summary.h5", 'w'); write_header(file); write_nuclides(file); write_geometry(file); write_materials(file); // Terminate access to the file. file_close(file); } void write_header(hid_t file) { // Write filetype and version info write_attribute(file, "filetype", "summary"); write_attribute(file, "version", VERSION_SUMMARY); write_attribute(file, "openmc_version", VERSION); #ifdef GIT_SHA1 write_attribute(file, "git_sha1", GIT_SHA1); #endif // Write current date and time write_attribute(file, "date_and_time", time_stamp()); } void write_nuclides(hid_t file) { // Build vectors of nuclide names and awrs while only sorting nuclides from // macroscopics vector<std::string> nuc_names; vector<std::string> macro_names; vector<double> awrs; for (int i = 0; i < data::nuclides.size(); ++i) { if (settings::run_CE) { const auto& nuc {data::nuclides[i]}; nuc_names.push_back(nuc->name_); awrs.push_back(nuc->awr_); } else { const auto& nuc {data::mg.nuclides_[i]}; if (nuc.awr != MACROSCOPIC_AWR) { nuc_names.push_back(nuc.name); awrs.push_back(nuc.awr); } else { macro_names.push_back(nuc.name); } } } hid_t nuclide_group = create_group(file, "nuclides"); write_attribute(nuclide_group, "n_nuclides", nuc_names.size()); hid_t macro_group = create_group(file, "macroscopics"); write_attribute(macro_group, "n_macroscopics", macro_names.size()); // Write nuclide names and awrs if (!nuc_names.empty()) { // Write useful data from nuclide objects write_dataset(nuclide_group, "names", nuc_names); write_dataset(nuclide_group, "awrs", awrs); } if (!macro_names.empty()) { // Write useful data from macroscopic objects write_dataset(macro_group, "names", macro_names); } close_group(nuclide_group); close_group(macro_group); } void write_geometry(hid_t file) { auto geom_group = create_group(file, "geometry"); #ifdef DAGMC if (settings::dagmc) { write_attribute(geom_group, "dagmc", 1); close_group(geom_group); return; } #endif write_attribute(geom_group, "n_cells", model::cells.size()); write_attribute(geom_group, "n_surfaces", model::surfaces.size()); write_attribute(geom_group, "n_universes", model::universes.size()); write_attribute(geom_group, "n_lattices", model::lattices.size()); auto cells_group = create_group(geom_group, "cells"); for (const auto& c : model::cells) c->to_hdf5(cells_group); close_group(cells_group); auto surfaces_group = create_group(geom_group, "surfaces"); for (const auto& surf : model::surfaces) surf->to_hdf5(surfaces_group); close_group(surfaces_group); auto universes_group = create_group(geom_group, "universes"); for (const auto& u : model::universes) u->to_hdf5(universes_group); close_group(universes_group); auto lattices_group = create_group(geom_group, "lattices"); for (const auto& lat : model::lattices) lat->to_hdf5(lattices_group); close_group(lattices_group); close_group(geom_group); } void write_materials(hid_t file) { // write number of materials write_dataset(file, "n_materials", model::materials.size()); hid_t materials_group = create_group(file, "materials"); for (const auto& mat : model::materials) { mat->to_hdf5(materials_group); } close_group(materials_group); } //============================================================================== // C API //============================================================================== extern "C" int openmc_properties_export(const char* filename) { // Set a default filename if none was passed std::string name = filename ? filename : "properties.h5"; // Display output message auto msg = fmt::format("Exporting properties to {}...", name); write_message(msg, 5); // Create a new file using default properties. hid_t file = file_open(name, 'w'); // Write metadata write_attribute(file, "filetype", "properties"); write_attribute(file, "version", VERSION_STATEPOINT); write_attribute(file, "openmc_version", VERSION); #ifdef GIT_SHA1 write_attribute(file, "git_sha1", GIT_SHA1); #endif write_attribute(file, "date_and_time", time_stamp()); write_attribute(file, "path", settings::path_input); // Write cell properties auto geom_group = create_group(file, "geometry"); write_attribute(geom_group, "n_cells", model::cells.size()); auto cells_group = create_group(geom_group, "cells"); for (const auto& c : model::cells) { c->export_properties_hdf5(cells_group); } close_group(cells_group); close_group(geom_group); // Write material properties hid_t materials_group = create_group(file, "materials"); write_attribute(materials_group, "n_materials", model::materials.size()); for (const auto& mat : model::materials) { mat->export_properties_hdf5(materials_group); } close_group(materials_group); // Terminate access to the file. file_close(file); return 0; } extern "C" int openmc_properties_import(const char* filename) { // Display output message auto msg = fmt::format("Importing properties from {}...", filename); write_message(msg, 5); // Create a new file using default properties. if (!file_exists(filename)) { set_errmsg(fmt::format("File '{}' does not exist.", filename)); return OPENMC_E_INVALID_ARGUMENT; } hid_t file = file_open(filename, 'r'); // Ensure the filetype is correct std::string filetype; read_attribute(file, "filetype", filetype); if (filetype != "properties") { file_close(file); set_errmsg(fmt::format("File '{}' is not a properties file.", filename)); return OPENMC_E_INVALID_ARGUMENT; } // Make sure number of cells matches auto geom_group = open_group(file, "geometry"); int32_t n; read_attribute(geom_group, "n_cells", n); if (n != openmc::model::cells.size()) { close_group(geom_group); file_close(file); set_errmsg(fmt::format("Number of cells in {} doesn't match current model.", filename)); return OPENMC_E_GEOMETRY; } // Read cell properties auto cells_group = open_group(geom_group, "cells"); for (const auto& c : model::cells) { c->import_properties_hdf5(cells_group); } close_group(cells_group); close_group(geom_group); // Make sure number of cells matches auto materials_group = open_group(file, "materials"); read_attribute(materials_group, "n_materials", n); if (n != openmc::model::materials.size()) { close_group(materials_group); file_close(file); set_errmsg(fmt::format("Number of materials in {} doesn't match current model.", filename)); return OPENMC_E_GEOMETRY; } // Read material properties for (const auto& mat : model::materials) { mat->import_properties_hdf5(materials_group); } close_group(materials_group); // Terminate access to the file. file_close(file); return 0; } } // namespace openmc <|endoftext|>
<commit_before>#include "systems.h" #include "compiler.h" #include "mswin.h" #include "resources.h" #include "vector.h" #include "make_system.h" #include "cramer.h" #include "graphics.h" #include "memory.h" #include <cstdint> struct triangle_t { float xyz [3] [4]; // Co-ordinates for a single triangle XYZ of the Moebius tiling. float abc [8] [4]; // Coefficients A, B, C for the generator T = AX + BY + CZ. }; // The fundamental triangle of the tiling has angles // A = pi/p, B = pi/q, C = pi/r and sides a, b, c. // By the spherical cosine rule, // cosa = (cosA + cosB * cosC) / (sinB * sinC), // cosb = (cosB + cosC * cosA) / (sinC * sinA), // cosc = (cosC + cosA * cosB) / (sinA * sinB). // We assume p = 2; thus cosA = 0 and sinA = 1. Therefore, // cosa = (cosB * cosC) / (sinB * sinC), // cosb = cosB / sinC, // cosc = cosC / sinB. // Any triple (alpha, beta, gamma) identifies a point T relative to // the spherical triangle XYZ, by the formula // T = alpha * X + beta * Y + gamma * Z. // For certain triples, replicating the point T in each triangle // of the tiling gives the vertices of a uniform polyhedron: // { 1, 0, 0, }, Point X. // { 0, 1, 0, }, Point Y. // { 0, 0, 1, }, Point Z. // { 0, sinb, sinc, }, Intersection of YZ with the angular bisector of corner X. // { sina, 0, sinc, }, Intersection of ZX with the angular bisector of corner Y. // { sina, sinb, 0, }, Intersection of YZ with the angular bisector of corner Z. // { sinA, sinB, sinC, }, Incentre (intersection of the three bisectors). // { alpha, beta, gamma, }, Snub generator. // X1 // / \ Part of the tiling of the sphere, showing // Z0--Y0 the triangle X0-Y0-Z0 and the adjacent triangles. // |\ /| // | X0 | // |/ \| // Y1 Z1 // For the snub generator, the three points // TX = alpha * X1 + beta * Y0 + gamma * Z0 // TY = alpha * X0 + beta * Y1 + gamma * Z0 // TZ = alpha * X0 + beta * Y0 + gamma * Z1 // (see diagram) are the vertices of an equilateral spherical triangle. triangle_t triangles [3] ALIGNED16 = { // Tetrahedral, <2, 3, 3>. { { { +0x1.000000P+0f, +0x0.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x1.279a74P-1f, +0x1.a20bd8P-1f, +0x0.000000P+0f, 0.0f, }, { +0x1.279a74P-1f, +0x0.000000P+0f, +0x1.a20bd8P-1f, 0.0f, }, }, { { +0x1.000000P+0f, +0x0.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x1.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x0.000000P+0f, +0x1.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x1.3988e2P-1f, +0x1.3988e2P-1f, 0.0f, }, { +0x1.34bf64P-1f, +0x0.000000P+0f, +0x1.0b621eP-1f, 0.0f, }, { +0x1.34bf64P-1f, +0x1.0b621eP-1f, +0x0.000000P+0f, 0.0f, }, { +0x1.c9f25cP-2f, +0x1.8c97f0P-2f, +0x1.8c97f0P-2f, 0.0f, }, { +0x1.4cb7c0P-2f, +0x1.d2393eP-2f, +0x1.d2393eP-2f, 0.0f, }, }, }, // Octahedral, <2, 4, 3>. // Aligned so that two octahedral triangles cover one tetrahedral triangle. { { { +0x1.6a09e6P-1f, +0x1.000000P-1f, +0x1.000000P-1f, 0.0f, }, { +0x1.000000P+0f, +0x0.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x1.279a74P-1f, +0x1.a20bd8P-1f, +0x0.000000P+0f, 0.0f, }, }, { { +0x1.000000P+0f, +0x0.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x1.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x0.000000P+0f, +0x1.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x1.02ca46P-1f, +0x1.3cf3aeP-1f, 0.0f, }, { +0x1.1fd4a6P-1f, +0x0.000000P+0f, +0x1.f28990P-2f, 0.0f, }, { +0x1.43d136P-1f, +0x1.c9f25cP-2f, +0x0.000000P+0f, 0.0f, }, { +0x1.b9d594P-2f, +0x1.386c8eP-2f, +0x1.7ea3c6P-2f, 0.0f, }, { +0x1.31816eP-2f, +0x1.8d5502P-2f, +0x1.bdd092P-2f, 0.0f, }, }, }, // Icosahedral, <2, 5, 3>. { { { +0x1.000000P+0f, +0x0.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x1.b38880P-1f, +0x1.0d2ca0P-1f, +0x0.000000P+0f, 0.0f, }, { +0x1.de4bd6P-1f, +0x0.0000000P+0, +0x1.6d62c6P-2f, 0.0f, }, }, { { +0x1.000000P+0f, +0x0.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x1.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x0.000000P+0f, +0x1.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x1.b4242aP-2f, +0x1.414c80P-1f, 0.0f, }, { +0x1.16fc4eP-1f, +0x0.000000P+0f, +0x1.e33798P-2f, 0.0f, }, { +0x1.4e5014P-1f, +0x1.890220P-2f, +0x0.000000P+0f, 0.0f, }, { +0x1.b3be36P-2f, +0x1.001f92P-2f, +0x1.795d50P-2f, 0.0f, }, { +0x1.287f1eP-2f, +0x1.52a52eP-2f, +0x1.b882c6P-2f, 0.0f, }, }, } }; // Turn a PQR triangle into a PRQ triangle. void reflect (triangle_t & t) { v4f x = load4f (t.xyz [0]); v4f y = load4f (t.xyz [1]); v4f z = load4f (t.xyz [2]); v4f n = normalize (cross (x, y)); v4f d = dot (n, z) * n; store4f (t.xyz [1], z - (d + d)); store4f (t.xyz [2], y); for (unsigned k = 0; k != 8; ++ k) { v4f a = load4f (t.abc [k]); store4f (t.abc [k], _mm_shuffle_ps (a, a, SHUFFLE (0, 2, 1, 3))); } } template <unsigned K> ALWAYS_INLINE inline void copy (const float (* from) [4], float (& to) [K] [4]) { for (unsigned k = 0; k != K; ++ k) { store4f (to [k], load4f (from [k])); } } void initialize_systems (float (& abc) [system_count] [8] [4], float (& xyz) [system_count] [3] [4], float (& xyzinvt) [system_count] [3] [4], unsigned (& primitive_count) [system_count], unsigned (& vao_ids) [system_count]) { auto init = [&] (const triangle_t & t, system_select_t select, unsigned q, unsigned r) -> void { copy (t.xyz, xyz [select]); copy (t.abc, abc [select]); cramer::inverse_transpose (xyz [select], xyzinvt [select]); unsigned p = 2, N = 2 * p * q * r / (q * r + r * p + p * q - p * q * r); unsigned indices [60] [6]; ALIGNED16 float nodes [62] [4]; make_system (q, r, t.xyz, nodes, indices); vao_ids [select] = make_vao (N, nodes, indices); primitive_count [select] = N; }; for (unsigned n = 0; n != 3; ++ n) { triangle_t & triangle = triangles [n]; init (triangle, system_select_t (2 * n + 0), 3 + n, 3); reflect (triangle); init (triangle, system_select_t (2 * n + 1), 3, 3 + n); } } <commit_msg>systems.cpp: co-ordinates for the great icosahedron as a snubified tetrahedron.<commit_after>#include "systems.h" #include "compiler.h" #include "mswin.h" #include "resources.h" #include "vector.h" #include "make_system.h" #include "cramer.h" #include "graphics.h" #include "memory.h" #include <cstdint> struct triangle_t { float xyz [3] [4]; // Co-ordinates for a single triangle XYZ of the Moebius tiling. float abc [8] [4]; // Coefficients A, B, C for the generator T = AX + BY + CZ. }; // The fundamental triangle of the tiling has angles // A = pi/p, B = pi/q, C = pi/r and sides a, b, c. // By the spherical cosine rule, // cosa = (cosA + cosB * cosC) / (sinB * sinC), // cosb = (cosB + cosC * cosA) / (sinC * sinA), // cosc = (cosC + cosA * cosB) / (sinA * sinB). // We assume p = 2; thus cosA = 0 and sinA = 1. Therefore, // cosa = (cosB * cosC) / (sinB * sinC), // cosb = cosB / sinC, // cosc = cosC / sinB. // Any triple (alpha, beta, gamma) identifies a point T relative to // the spherical triangle XYZ, by the formula // T = alpha * X + beta * Y + gamma * Z. // For certain triples, replicating the point T in each triangle // of the tiling gives the vertices of a uniform polyhedron: // { 1, 0, 0, }, Point X. // { 0, 1, 0, }, Point Y. // { 0, 0, 1, }, Point Z. // { 0, sinb, sinc, }, Intersection of YZ with the angular bisector of corner X. // { sina, 0, sinc, }, Intersection of ZX with the angular bisector of corner Y. // { sina, sinb, 0, }, Intersection of YZ with the angular bisector of corner Z. // { sinA, sinB, sinC, }, Incentre (intersection of the three bisectors). // { alpha, beta, gamma, }, Snub generator. // X1 // / \ Part of the tiling of the sphere, showing // Z0--Y0 the triangle X0-Y0-Z0 and the adjacent triangles. // |\ /| // | X0 | // |/ \| // Y1 Z1 // For the snub generator, the three points // TX = alpha * X1 + beta * Y0 + gamma * Z0 // TY = alpha * X0 + beta * Y1 + gamma * Z0 // TZ = alpha * X0 + beta * Y0 + gamma * Z1 // (see diagram) are the vertices of an equilateral spherical triangle. triangle_t triangles [3] ALIGNED16 = { // Tetrahedral, <2, 3, 3>. { { { +0x1.000000P+0f, +0x0.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x1.279a74P-1f, +0x1.a20bd8P-1f, +0x0.000000P+0f, 0.0f, }, { +0x1.279a74P-1f, +0x0.000000P+0f, +0x1.a20bd8P-1f, 0.0f, }, }, { { +0x1.000000P+0f, +0x0.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x1.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x0.000000P+0f, +0x1.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x1.3988e2P-1f, +0x1.3988e2P-1f, 0.0f, }, { +0x1.34bf64P-1f, +0x0.000000P+0f, +0x1.0b621eP-1f, 0.0f, }, { +0x1.34bf64P-1f, +0x1.0b621eP-1f, +0x0.000000P+0f, 0.0f, }, { +0x1.c9f25cP-2f, +0x1.8c97f0P-2f, +0x1.8c97f0P-2f, 0.0f, }, { +0x1.4cb7c0P-2f, +0x1.d2393eP-2f, +0x1.d2393eP-2f, 0.0f, }, // Icosahedron //{ -0x1.605a90P+0f, +0x1.792eceP-1f, +0x1.792eceP-1f, 0.0f, }, // Great icosahedron }, }, // Octahedral, <2, 4, 3>. // Aligned so that two octahedral triangles cover one tetrahedral triangle. { { { +0x1.6a09e6P-1f, +0x1.000000P-1f, +0x1.000000P-1f, 0.0f, }, { +0x1.000000P+0f, +0x0.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x1.279a74P-1f, +0x1.a20bd8P-1f, +0x0.000000P+0f, 0.0f, }, }, { { +0x1.000000P+0f, +0x0.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x1.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x0.000000P+0f, +0x1.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x1.02ca46P-1f, +0x1.3cf3aeP-1f, 0.0f, }, { +0x1.1fd4a6P-1f, +0x0.000000P+0f, +0x1.f28990P-2f, 0.0f, }, { +0x1.43d136P-1f, +0x1.c9f25cP-2f, +0x0.000000P+0f, 0.0f, }, { +0x1.b9d594P-2f, +0x1.386c8eP-2f, +0x1.7ea3c6P-2f, 0.0f, }, { +0x1.31816eP-2f, +0x1.8d5502P-2f, +0x1.bdd092P-2f, 0.0f, }, }, }, // Icosahedral, <2, 5, 3>. { { { +0x1.000000P+0f, +0x0.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x1.b38880P-1f, +0x1.0d2ca0P-1f, +0x0.000000P+0f, 0.0f, }, { +0x1.de4bd6P-1f, +0x0.0000000P+0, +0x1.6d62c6P-2f, 0.0f, }, }, { { +0x1.000000P+0f, +0x0.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x1.000000P+0f, +0x0.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x0.000000P+0f, +0x1.000000P+0f, 0.0f, }, { +0x0.000000P+0f, +0x1.b4242aP-2f, +0x1.414c80P-1f, 0.0f, }, { +0x1.16fc4eP-1f, +0x0.000000P+0f, +0x1.e33798P-2f, 0.0f, }, { +0x1.4e5014P-1f, +0x1.890220P-2f, +0x0.000000P+0f, 0.0f, }, { +0x1.b3be36P-2f, +0x1.001f92P-2f, +0x1.795d50P-2f, 0.0f, }, { +0x1.287f1eP-2f, +0x1.52a52eP-2f, +0x1.b882c6P-2f, 0.0f, }, }, } }; // Turn a PQR triangle into a PRQ triangle. void reflect (triangle_t & t) { v4f x = load4f (t.xyz [0]); v4f y = load4f (t.xyz [1]); v4f z = load4f (t.xyz [2]); v4f n = normalize (cross (x, y)); v4f d = dot (n, z) * n; store4f (t.xyz [1], z - (d + d)); store4f (t.xyz [2], y); for (unsigned k = 0; k != 8; ++ k) { v4f a = load4f (t.abc [k]); store4f (t.abc [k], _mm_shuffle_ps (a, a, SHUFFLE (0, 2, 1, 3))); } } template <unsigned K> ALWAYS_INLINE inline void copy (const float (* from) [4], float (& to) [K] [4]) { for (unsigned k = 0; k != K; ++ k) { store4f (to [k], load4f (from [k])); } } void initialize_systems (float (& abc) [system_count] [8] [4], float (& xyz) [system_count] [3] [4], float (& xyzinvt) [system_count] [3] [4], unsigned (& primitive_count) [system_count], unsigned (& vao_ids) [system_count]) { auto init = [&] (const triangle_t & t, system_select_t select, unsigned q, unsigned r) -> void { copy (t.xyz, xyz [select]); copy (t.abc, abc [select]); cramer::inverse_transpose (xyz [select], xyzinvt [select]); unsigned p = 2, N = 2 * p * q * r / (q * r + r * p + p * q - p * q * r); unsigned indices [60] [6]; ALIGNED16 float nodes [62] [4]; make_system (q, r, t.xyz, nodes, indices); vao_ids [select] = make_vao (N, nodes, indices); primitive_count [select] = N; }; for (unsigned n = 0; n != 3; ++ n) { triangle_t & triangle = triangles [n]; init (triangle, system_select_t (2 * n + 0), 3 + n, 3); reflect (triangle); init (triangle, system_select_t (2 * n + 1), 3, 3 + n); } } <|endoftext|>
<commit_before>#include "Navigation.h" #include <iostream> #include <assert.h> using namespace std; void testInputNodes(const char* file); void testReconstructPath(const char* file); void testFindPath(const char* file); void testTravelFromSourceToSink(const char* file); int main(int argc, char const *argv[]) { if(argc != 2) { cout << "usage:\n\t./a.out inputFileName" << endl; return 0; } system("clear"); cout << "Running test on Navigation::inputNodes" << endl; testInputNodes(argv[1]); cout << "[PASS] Navigation::inputNodes" << endl << endl; cout << "Running test on Navigation::reconstructPath" << endl; testReconstructPath(argv[1]); cout << "[PASS] Navigation::reconstructPath" << endl << endl; testFindPath(argv[1]); cout << "Running test on Navigation::findPath" << endl; cout << "[PASS] Navigation::findPath" << endl << endl; testTravelFromSourceToSink(argv[1]); cout << "Running test on Navigation::travelFromSourceToSink" << endl; cout << "[PASS] Navigation::travelFromSourceToSink" << endl << endl; return 0; } void testInputNodes(const char* file) { Navigation defaultNav; defaultNav.inputNodes(file); assert(defaultNav.getNode(0)->name=="node0"); assert(defaultNav.getNode(0)->neighbors[0]->name=="node1"); assert(defaultNav.getNode(0)->neighbors[1]->name=="node3"); assert(defaultNav.getNode(0)->weights[0]==10); assert(defaultNav.getNode(0)->weights[1]==25); assert(defaultNav.getNode(1)->name=="node1"); assert(defaultNav.getNode(1)->neighbors[0]->name=="node0"); assert(defaultNav.getNode(1)->neighbors[1]->name=="node2"); assert(defaultNav.getNode(1)->weights[0]==10); assert(defaultNav.getNode(1)->weights[1]==5); assert(defaultNav.getNode(2)->name=="node2"); assert(defaultNav.getNode(2)->neighbors[0]->name=="node1"); assert(defaultNav.getNode(2)->neighbors[1]->name=="node3"); assert(defaultNav.getNode(2)->neighbors[2]->name=="node4"); assert(defaultNav.getNode(2)->weights[0]==5); assert(defaultNav.getNode(2)->weights[1]==5); assert(defaultNav.getNode(2)->weights[2]==20); assert(defaultNav.getNode(3)->name=="node3"); assert(defaultNav.getNode(3)->neighbors[0]->name=="node0"); assert(defaultNav.getNode(3)->neighbors[1]->name=="node2"); assert(defaultNav.getNode(3)->neighbors[2]->name=="node4"); assert(defaultNav.getNode(3)->weights[0]==25); assert(defaultNav.getNode(3)->weights[1]==5); assert(defaultNav.getNode(3)->weights[2]==5); assert(defaultNav.getNode(4)->name=="node4"); assert(defaultNav.getNode(4)->neighbors[0]->name=="node2"); assert(defaultNav.getNode(4)->neighbors[1]->name=="node3"); assert(defaultNav.getNode(4)->weights[0]==20); assert(defaultNav.getNode(4)->weights[1]==5); } void testReconstructPath(const char* file) { Navigation defaultNav; vector<Node*> path; defaultNav.inputNodes(file); defaultNav.getNode(4)->parent = defaultNav.getNode(3); defaultNav.getNode(3)->parent = defaultNav.getNode(2); defaultNav.getNode(2)->parent = defaultNav.getNode(1); defaultNav.getNode(1)->parent = defaultNav.getNode(0); defaultNav.getNode(0)->parent = NULL; path = defaultNav.dbgReconstructPath(defaultNav.getNode(4)); assert(!path.empty()); assert(path[0] == defaultNav.getNode(1)); assert(path[1] == defaultNav.getNode(2)); assert(path[2] == defaultNav.getNode(3)); assert(path[3] == defaultNav.getNode(4)); } void testFindPath(const char* file) { Navigation defaultNav; vector<Node*> path; defaultNav.inputNodes(file); path = defaultNav.dbgFindPath(defaultNav.getNode(0), defaultNav.getNode(4)); assert(!path.empty()); assert(path[0] == defaultNav.getNode(1)); assert(path[1] == defaultNav.getNode(2)); assert(path[2] == defaultNav.getNode(3)); assert(path[3] == defaultNav.getNode(4)); } void testTravelFromSourceToSink(const char* file) { Navigation defaultNav; bool arrived; defaultNav.inputNodes(file); arrived = defaultNav.travelFromSourceToSink(defaultNav.getNode(0), defaultNav.getNode(4)); assert(arrived); }<commit_msg>fuck your bracketing<commit_after>#include "Navigation.h" #include <iostream> #include <assert.h> using namespace std; void testInputNodes(const char* file); void testReconstructPath(const char* file); void testFindPath(const char* file); void testTravelFromSourceToSink(const char* file); int main(int argc, char const *argv[]) { if(argc != 2) { cout << "usage:\n\t./a.out inputFileName" << endl; return 0; } system("clear"); cout << "Running test on Navigation::inputNodes" << endl; testInputNodes(argv[1]); cout << "[PASS] Navigation::inputNodes" << endl << endl; cout << "Running test on Navigation::reconstructPath" << endl; testReconstructPath(argv[1]); cout << "[PASS] Navigation::reconstructPath" << endl << endl; testFindPath(argv[1]); cout << "Running test on Navigation::findPath" << endl; cout << "[PASS] Navigation::findPath" << endl << endl; testTravelFromSourceToSink(argv[1]); cout << "Running test on Navigation::travelFromSourceToSink" << endl; cout << "[PASS] Navigation::travelFromSourceToSink" << endl << endl; return 0; } void testInputNodes(const char* file) { Navigation defaultNav; defaultNav.inputNodes(file); assert(defaultNav.getNode(0)->name=="node0"); assert(defaultNav.getNode(0)->neighbors[0]->name=="node1"); assert(defaultNav.getNode(0)->neighbors[1]->name=="node3"); assert(defaultNav.getNode(0)->weights[0]==10); assert(defaultNav.getNode(0)->weights[1]==25); assert(defaultNav.getNode(1)->name=="node1"); assert(defaultNav.getNode(1)->neighbors[0]->name=="node0"); assert(defaultNav.getNode(1)->neighbors[1]->name=="node2"); assert(defaultNav.getNode(1)->weights[0]==10); assert(defaultNav.getNode(1)->weights[1]==5); assert(defaultNav.getNode(2)->name=="node2"); assert(defaultNav.getNode(2)->neighbors[0]->name=="node1"); assert(defaultNav.getNode(2)->neighbors[1]->name=="node3"); assert(defaultNav.getNode(2)->neighbors[2]->name=="node4"); assert(defaultNav.getNode(2)->weights[0]==5); assert(defaultNav.getNode(2)->weights[1]==5); assert(defaultNav.getNode(2)->weights[2]==20); assert(defaultNav.getNode(3)->name=="node3"); assert(defaultNav.getNode(3)->neighbors[0]->name=="node0"); assert(defaultNav.getNode(3)->neighbors[1]->name=="node2"); assert(defaultNav.getNode(3)->neighbors[2]->name=="node4"); assert(defaultNav.getNode(3)->weights[0]==25); assert(defaultNav.getNode(3)->weights[1]==5); assert(defaultNav.getNode(3)->weights[2]==5); assert(defaultNav.getNode(4)->name=="node4"); assert(defaultNav.getNode(4)->neighbors[0]->name=="node2"); assert(defaultNav.getNode(4)->neighbors[1]->name=="node3"); assert(defaultNav.getNode(4)->weights[0]==20); assert(defaultNav.getNode(4)->weights[1]==5); } void testReconstructPath(const char* file) { Navigation defaultNav; vector<Node*> path; defaultNav.inputNodes(file); defaultNav.getNode(4)->parent = defaultNav.getNode(3); defaultNav.getNode(3)->parent = defaultNav.getNode(2); defaultNav.getNode(2)->parent = defaultNav.getNode(1); defaultNav.getNode(1)->parent = defaultNav.getNode(0); defaultNav.getNode(0)->parent = NULL; path = defaultNav.dbgReconstructPath(defaultNav.getNode(4)); assert(!path.empty()); assert(path[0] == defaultNav.getNode(1)); assert(path[1] == defaultNav.getNode(2)); assert(path[2] == defaultNav.getNode(3)); assert(path[3] == defaultNav.getNode(4)); } void testFindPath(const char* file) { Navigation defaultNav; vector<Node*> path; defaultNav.inputNodes(file); path = defaultNav.dbgFindPath(defaultNav.getNode(0), defaultNav.getNode(4)); assert(!path.empty()); assert(path[0] == defaultNav.getNode(1)); assert(path[1] == defaultNav.getNode(2)); assert(path[2] == defaultNav.getNode(3)); assert(path[3] == defaultNav.getNode(4)); } void testTravelFromSourceToSink(const char* file) { Navigation defaultNav; bool arrived; defaultNav.inputNodes(file); arrived = defaultNav.travelFromSourceToSink(defaultNav.getNode(0), defaultNav.getNode(4)); assert(arrived); }<|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: RootSolver.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2012 Stanford University and the Authors * * Author(s): Frank C. Anderson * * * * 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. * * -------------------------------------------------------------------------- */ /* * Author: Frank C. Anderson */ // INCLUDES #include <iostream> #include <string> #include <float.h> #include <math.h> #include "RootSolver.h" using namespace OpenSim; using namespace std; //============================================================================= // DESTRUCTOR AND CONSTRUCTORS //============================================================================= //_____________________________________________________________________________ /** * Destructor. */ RootSolver::~RootSolver() { } //_____________________________________________________________________________ /** * Default constructor. */ RootSolver:: RootSolver(VectorFunctionUncoupledNxN *aFunc) { setNull(); _function = aFunc; } //----------------------------------------------------------------------------- // CONSTRUCTION METHODS //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Set all member variables to NULL values. */ void RootSolver:: setNull() { _function = NULL; } //============================================================================= // SOLVE //============================================================================= //_____________________________________________________________________________ /** * Solve for the roots. * * */ Array<double> RootSolver:: solve(const SimTK::State& s, const Array<double> &ax,const Array<double> &bx, const Array<double> &tol) { int i; int N = _function->getNX(); Array<double> a(0.0,N),b(0.0,N),c(0.0,N); Array<double> fa(0.0,N),fb(0.0,N),fc(0.0,N); Array<double> prev_step(0.0,N); Array<double> tol_act(0.0,N); Array<double> p(0.0,N); Array<double> q(0.0,N); Array<double> new_step(0.0,N); bool finished = false; Array<int> converged(0,N); // INITIALIZATIONS a = ax; b = bx; _function->evaluate(s,a,fa); _function->evaluate(s,b,fb); c = a; fc = fa; // ITERATION LOOP int iter; for(iter=0;!finished;iter++) { // ABSCISSAE MANIPULATION LOOP for(i=0;i<N;i++) { // Continue? // If a function is already converged no need to do any manipulation. if(converged[i]) continue; // Make c on opposite side of b. // (was down at very bottom) if( (fb[i]>0.0 && fc[i]>0.0) || (fb[i]<0.0 && fc[i]<0.0) ) { c[i] = a[i]; fc[i] = fa[i]; } // Record previous step prev_step[i] = b[i] - a[i]; // Swap data for b to be the best approximation. if( fabs(fc[i]) < fabs(fb[i]) ) { a[i] = b[i]; b[i] = c[i]; c[i] = a[i]; fa[i]= fb[i]; fb[i]= fc[i]; fc[i]= fa[i]; } tol_act[i] = 2.0*DBL_EPSILON*fabs(b[i]) + 0.5*tol[i]; new_step[i] = 0.5 * (c[i]-b[i]); // Converged? // Original convergence test: if(fabs(new_step[i])<=tol_act[i] || fb[i]==(double)0.0 ) { converged[i] = iter; continue; } // Interpolate if prev_step was large enough and in true direction if( fabs(prev_step[i])>=tol_act[i] && fabs(fa[i])>fabs(fb[i]) ) { register double t1,cb,t2; cb = c[i]-b[i]; // Only two distinct roots, must use linear interpolation. if(a[i]==c[i]) { t1 = fb[i]/fa[i]; p[i] = cb*t1; q[i] = 1.0 - t1; // Quadratic interpolation } else { q[i] = fa[i]/fc[i]; t1 = fb[i]/fc[i]; t2 = fb[i]/fa[i]; p[i] = t2 * ( cb*q[i]*(q[i]-t1) - (b[i]-a[i])*(t1-1.0) ); q[i] = (q[i]-1.0) * (t1-1.0) * (t2-1.0); } // Change sign of q or p? if( p[i]>(double)0.0 ) { q[i] = -q[i]; } else { p[i] = -p[i]; } // If the interpolate is bad, use bissection. if( p[i]<(0.75*cb*q[i] - 0.5*fabs(tol_act[i]*q[i])) && p[i]<fabs(0.5*prev_step[i]*q[i]) ) new_step[i] = p[i]/q[i]; } // Adjust step to be not less than tolerance. if( fabs(new_step[i]) < tol_act[i] ) if( new_step[i] > (double)0.0 ) new_step[i] = tol_act[i]; else new_step[i] = -tol_act[i]; // Save previous approximation. a[i] = b[i]; fa[i] = fb[i]; b[i] += new_step[i]; } // END ABSCISSAE LOOP // NEW FUNCTION EVALUATION _function->evaluate(s, b,fb); // FINISHED? for(i=0;i<N;i++) { finished = true; if(!converged[i]) { finished = false; break; } } } // PRINT //cout<<"\n\nRootSolver: found solution in "<<iter<<" iterations.\n"; //cout<<"converged array:\n"; //cout<<converged<<endl<<endl; //cout<<"roots:\n"; //cout<<b<<endl<<endl; //cout<<"errors:\n"; //cout<<fb<<endl; return(b); } <commit_msg>Address Clang warning about ambiguous nested 'else' clause.<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: RootSolver.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2012 Stanford University and the Authors * * Author(s): Frank C. Anderson * * * * 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. * * -------------------------------------------------------------------------- */ /* * Author: Frank C. Anderson */ // INCLUDES #include <iostream> #include <string> #include <float.h> #include <math.h> #include "RootSolver.h" using namespace OpenSim; using namespace std; //============================================================================= // DESTRUCTOR AND CONSTRUCTORS //============================================================================= //_____________________________________________________________________________ /** * Destructor. */ RootSolver::~RootSolver() { } //_____________________________________________________________________________ /** * Default constructor. */ RootSolver:: RootSolver(VectorFunctionUncoupledNxN *aFunc) { setNull(); _function = aFunc; } //----------------------------------------------------------------------------- // CONSTRUCTION METHODS //----------------------------------------------------------------------------- //_____________________________________________________________________________ /** * Set all member variables to NULL values. */ void RootSolver:: setNull() { _function = NULL; } //============================================================================= // SOLVE //============================================================================= //_____________________________________________________________________________ /** * Solve for the roots. * * */ Array<double> RootSolver:: solve(const SimTK::State& s, const Array<double> &ax,const Array<double> &bx, const Array<double> &tol) { int i; int N = _function->getNX(); Array<double> a(0.0,N),b(0.0,N),c(0.0,N); Array<double> fa(0.0,N),fb(0.0,N),fc(0.0,N); Array<double> prev_step(0.0,N); Array<double> tol_act(0.0,N); Array<double> p(0.0,N); Array<double> q(0.0,N); Array<double> new_step(0.0,N); bool finished = false; Array<int> converged(0,N); // INITIALIZATIONS a = ax; b = bx; _function->evaluate(s,a,fa); _function->evaluate(s,b,fb); c = a; fc = fa; // ITERATION LOOP int iter; for(iter=0;!finished;iter++) { // ABSCISSAE MANIPULATION LOOP for(i=0;i<N;i++) { // Continue? // If a function is already converged no need to do any manipulation. if(converged[i]) continue; // Make c on opposite side of b. // (was down at very bottom) if( (fb[i]>0.0 && fc[i]>0.0) || (fb[i]<0.0 && fc[i]<0.0) ) { c[i] = a[i]; fc[i] = fa[i]; } // Record previous step prev_step[i] = b[i] - a[i]; // Swap data for b to be the best approximation. if( fabs(fc[i]) < fabs(fb[i]) ) { a[i] = b[i]; b[i] = c[i]; c[i] = a[i]; fa[i]= fb[i]; fb[i]= fc[i]; fc[i]= fa[i]; } tol_act[i] = 2.0*DBL_EPSILON*fabs(b[i]) + 0.5*tol[i]; new_step[i] = 0.5 * (c[i]-b[i]); // Converged? // Original convergence test: if(fabs(new_step[i])<=tol_act[i] || fb[i]==(double)0.0 ) { converged[i] = iter; continue; } // Interpolate if prev_step was large enough and in true direction if( fabs(prev_step[i])>=tol_act[i] && fabs(fa[i])>fabs(fb[i]) ) { register double t1,cb,t2; cb = c[i]-b[i]; // Only two distinct roots, must use linear interpolation. if(a[i]==c[i]) { t1 = fb[i]/fa[i]; p[i] = cb*t1; q[i] = 1.0 - t1; // Quadratic interpolation } else { q[i] = fa[i]/fc[i]; t1 = fb[i]/fc[i]; t2 = fb[i]/fa[i]; p[i] = t2 * ( cb*q[i]*(q[i]-t1) - (b[i]-a[i])*(t1-1.0) ); q[i] = (q[i]-1.0) * (t1-1.0) * (t2-1.0); } // Change sign of q or p? if( p[i]>(double)0.0 ) { q[i] = -q[i]; } else { p[i] = -p[i]; } // If the interpolate is bad, use bissection. if( p[i]<(0.75*cb*q[i] - 0.5*fabs(tol_act[i]*q[i])) && p[i]<fabs(0.5*prev_step[i]*q[i]) ) new_step[i] = p[i]/q[i]; } // Adjust step to be not less than tolerance. if( fabs(new_step[i]) < tol_act[i] ) { if( new_step[i] > (double)0.0 ) { new_step[i] = tol_act[i]; } else { new_step[i] = -tol_act[i]; } } // Save previous approximation. a[i] = b[i]; fa[i] = fb[i]; b[i] += new_step[i]; } // END ABSCISSAE LOOP // NEW FUNCTION EVALUATION _function->evaluate(s, b,fb); // FINISHED? for(i=0;i<N;i++) { finished = true; if(!converged[i]) { finished = false; break; } } } // PRINT //cout<<"\n\nRootSolver: found solution in "<<iter<<" iterations.\n"; //cout<<"converged array:\n"; //cout<<converged<<endl<<endl; //cout<<"roots:\n"; //cout<<b<<endl<<endl; //cout<<"errors:\n"; //cout<<fb<<endl; return(b); } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <Context.h> #include <Msg.h> #include <test.h> Context context; //////////////////////////////////////////////////////////////////////////////// int main (int argc, char** argv) { UnitTest t (12); Msg m; t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\n\n\n", "Msg::serialize '' --> '\\n\\n'"); m.set ("name", "value"); t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\nname: value\n\n\n", "Msg::serialize 1 var"); m.set ("foo", "bar"); t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\nfoo: bar\nname: value\n\n\n", "Msg::serialize 2 vars"); m.setPayload ("payload"); t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\nfoo: bar\nname: value\n\npayload\n", "Msg::serialize 2 vars + payload"); Msg m2; t.ok (m2.parse ("foo: bar\nname: value\n\npayload\n"), "Msg::parse ok"); t.is (m2.get ("foo"), "bar", "Msg::get"); t.is (m2.get ("name"), "value", "Msg::get"); t.is (m2.getPayload (), "payload\n", "Msg::getPayload"); Msg m3; t.ok (m3.parse ("foo:bar\nname: value\n\npayload\n"), "Msg::parse ok"); t.is (m3.get ("foo"), "bar", "Msg::get"); t.is (m3.get ("name"), "value", "Msg::get"); t.is (m3.getPayload (), "payload\n", "Msg::getPayload"); return 0; } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Test: Added test for Msg::all<commit_after>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <Context.h> #include <Msg.h> #include <test.h> Context context; //////////////////////////////////////////////////////////////////////////////// int main (int argc, char** argv) { UnitTest t (13); Msg m; t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\n\n\n", "Msg::serialize '' --> '\\n\\n'"); m.set ("name", "value"); t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\nname: value\n\n\n", "Msg::serialize 1 var"); m.set ("foo", "bar"); t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\nfoo: bar\nname: value\n\n\n", "Msg::serialize 2 vars"); m.setPayload ("payload"); t.is (m.serialize (), std::string ("client: ") + PACKAGE_STRING + "\nfoo: bar\nname: value\n\npayload\n", "Msg::serialize 2 vars + payload"); Msg m2; t.ok (m2.parse ("foo: bar\nname: value\n\npayload\n"), "Msg::parse ok"); t.is (m2.get ("foo"), "bar", "Msg::get"); t.is (m2.get ("name"), "value", "Msg::get"); t.is (m2.getPayload (), "payload\n", "Msg::getPayload"); Msg m3; t.ok (m3.parse ("foo:bar\nname: value\n\npayload\n"), "Msg::parse ok"); t.is (m3.get ("foo"), "bar", "Msg::get"); t.is (m3.get ("name"), "value", "Msg::get"); t.is (m3.getPayload (), "payload\n", "Msg::getPayload"); std::vector <std::string> vars; m3.all (vars); t.ok (vars.size () == 2, "Msg::all --> 2 vars"); return 0; } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Benoit Jacob <[email protected]> // // Eigen 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. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" template<typename MatrixType> void matrixRedux(const MatrixType& m) { typedef typename MatrixType::Scalar Scalar; int rows = m.rows(); int cols = m.cols(); MatrixType m1 = MatrixType::Random(rows, cols); VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows, cols).sum(), Scalar(1)); VERIFY_IS_APPROX(MatrixType::Ones(rows, cols).sum(), Scalar(float(rows*cols))); // the float() here to shut up excessive MSVC warning about int->complex conversion being lossy Scalar s(0), p(1), minc(ei_real(m1.coeff(0))), maxc(ei_real(m1.coeff(0))); for(int j = 0; j < cols; j++) for(int i = 0; i < rows; i++) { s += m1(i,j); p *= m1(i,j); minc = std::min(ei_real(minc), ei_real(m1(i,j))); maxc = std::max(ei_real(maxc), ei_real(m1(i,j))); } const Scalar mean = s/Scalar(rows*cols); const Scalar other_mean = m1.mean(); VERIFY_IS_APPROX(m1.sum(), s); VERIFY_IS_APPROX(m1.mean(), mean); VERIFY_IS_APPROX(m1.prod(), p); VERIFY_IS_APPROX(m1.real().minCoeff(), ei_real(minc)); VERIFY_IS_APPROX(m1.real().maxCoeff(), ei_real(maxc)); } template<typename VectorType> void vectorRedux(const VectorType& w) { typedef typename VectorType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; int size = w.size(); VectorType v = VectorType::Random(size); for(int i = 1; i < size; i++) { Scalar s(0), p(1); RealScalar minc(ei_real(v.coeff(0))), maxc(ei_real(v.coeff(0))); for(int j = 0; j < i; j++) { s += v[j]; p *= v[j]; minc = std::min(minc, ei_real(v[j])); maxc = std::max(maxc, ei_real(v[j])); } VERIFY_IS_APPROX(s, v.head(i).sum()); VERIFY_IS_APPROX(p, v.head(i).prod()); VERIFY_IS_APPROX(minc, v.real().head(i).minCoeff()); VERIFY_IS_APPROX(maxc, v.real().head(i).maxCoeff()); } for(int i = 0; i < size-1; i++) { Scalar s(0), p(1); RealScalar minc(ei_real(v.coeff(i))), maxc(ei_real(v.coeff(i))); for(int j = i; j < size; j++) { s += v[j]; p *= v[j]; minc = std::min(minc, ei_real(v[j])); maxc = std::max(maxc, ei_real(v[j])); } VERIFY_IS_APPROX(s, v.tail(size-i).sum()); VERIFY_IS_APPROX(p, v.tail(size-i).prod()); VERIFY_IS_APPROX(minc, v.real().tail(size-i).minCoeff()); VERIFY_IS_APPROX(maxc, v.real().tail(size-i).maxCoeff()); } for(int i = 0; i < size/2; i++) { Scalar s(0), p(1); RealScalar minc(ei_real(v.coeff(i))), maxc(ei_real(v.coeff(i))); for(int j = i; j < size-i; j++) { s += v[j]; p *= v[j]; minc = std::min(minc, ei_real(v[j])); maxc = std::max(maxc, ei_real(v[j])); } VERIFY_IS_APPROX(s, v.segment(i, size-2*i).sum()); VERIFY_IS_APPROX(p, v.segment(i, size-2*i).prod()); VERIFY_IS_APPROX(minc, v.real().segment(i, size-2*i).minCoeff()); VERIFY_IS_APPROX(maxc, v.real().segment(i, size-2*i).maxCoeff()); } } void test_redux() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( matrixRedux(Matrix<float, 1, 1>()) ); CALL_SUBTEST_1( matrixRedux(Array<float, 1, 1>()) ); CALL_SUBTEST_2( matrixRedux(Matrix2f()) ); CALL_SUBTEST_2( matrixRedux(Array2f()) ); CALL_SUBTEST_3( matrixRedux(Matrix4d()) ); CALL_SUBTEST_3( matrixRedux(Array4d()) ); CALL_SUBTEST_4( matrixRedux(MatrixXcf(3, 3)) ); CALL_SUBTEST_4( matrixRedux(ArrayXXcf(3, 3)) ); CALL_SUBTEST_5( matrixRedux(MatrixXd(8, 12)) ); CALL_SUBTEST_5( matrixRedux(ArrayXXd(8, 12)) ); CALL_SUBTEST_6( matrixRedux(MatrixXi(8, 12)) ); CALL_SUBTEST_6( matrixRedux(ArrayXXi(8, 12)) ); } for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_7( vectorRedux(Vector4f()) ); CALL_SUBTEST_7( vectorRedux(Array4f()) ); CALL_SUBTEST_5( vectorRedux(VectorXd(10)) ); CALL_SUBTEST_5( vectorRedux(ArrayXd(10)) ); CALL_SUBTEST_8( vectorRedux(VectorXf(33)) ); CALL_SUBTEST_8( vectorRedux(ArrayXf(33)) ); } } <commit_msg>One warning less...<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008 Benoit Jacob <[email protected]> // // Eigen 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. // // Alternatively, 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. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" template<typename MatrixType> void matrixRedux(const MatrixType& m) { typedef typename MatrixType::Scalar Scalar; int rows = m.rows(); int cols = m.cols(); MatrixType m1 = MatrixType::Random(rows, cols); VERIFY_IS_MUCH_SMALLER_THAN(MatrixType::Zero(rows, cols).sum(), Scalar(1)); VERIFY_IS_APPROX(MatrixType::Ones(rows, cols).sum(), Scalar(float(rows*cols))); // the float() here to shut up excessive MSVC warning about int->complex conversion being lossy Scalar s(0), p(1), minc(ei_real(m1.coeff(0))), maxc(ei_real(m1.coeff(0))); for(int j = 0; j < cols; j++) for(int i = 0; i < rows; i++) { s += m1(i,j); p *= m1(i,j); minc = std::min(ei_real(minc), ei_real(m1(i,j))); maxc = std::max(ei_real(maxc), ei_real(m1(i,j))); } const Scalar mean = s/Scalar(rows*cols); VERIFY_IS_APPROX(m1.sum(), s); VERIFY_IS_APPROX(m1.mean(), mean); VERIFY_IS_APPROX(m1.prod(), p); VERIFY_IS_APPROX(m1.real().minCoeff(), ei_real(minc)); VERIFY_IS_APPROX(m1.real().maxCoeff(), ei_real(maxc)); } template<typename VectorType> void vectorRedux(const VectorType& w) { typedef typename VectorType::Scalar Scalar; typedef typename NumTraits<Scalar>::Real RealScalar; int size = w.size(); VectorType v = VectorType::Random(size); for(int i = 1; i < size; i++) { Scalar s(0), p(1); RealScalar minc(ei_real(v.coeff(0))), maxc(ei_real(v.coeff(0))); for(int j = 0; j < i; j++) { s += v[j]; p *= v[j]; minc = std::min(minc, ei_real(v[j])); maxc = std::max(maxc, ei_real(v[j])); } VERIFY_IS_APPROX(s, v.head(i).sum()); VERIFY_IS_APPROX(p, v.head(i).prod()); VERIFY_IS_APPROX(minc, v.real().head(i).minCoeff()); VERIFY_IS_APPROX(maxc, v.real().head(i).maxCoeff()); } for(int i = 0; i < size-1; i++) { Scalar s(0), p(1); RealScalar minc(ei_real(v.coeff(i))), maxc(ei_real(v.coeff(i))); for(int j = i; j < size; j++) { s += v[j]; p *= v[j]; minc = std::min(minc, ei_real(v[j])); maxc = std::max(maxc, ei_real(v[j])); } VERIFY_IS_APPROX(s, v.tail(size-i).sum()); VERIFY_IS_APPROX(p, v.tail(size-i).prod()); VERIFY_IS_APPROX(minc, v.real().tail(size-i).minCoeff()); VERIFY_IS_APPROX(maxc, v.real().tail(size-i).maxCoeff()); } for(int i = 0; i < size/2; i++) { Scalar s(0), p(1); RealScalar minc(ei_real(v.coeff(i))), maxc(ei_real(v.coeff(i))); for(int j = i; j < size-i; j++) { s += v[j]; p *= v[j]; minc = std::min(minc, ei_real(v[j])); maxc = std::max(maxc, ei_real(v[j])); } VERIFY_IS_APPROX(s, v.segment(i, size-2*i).sum()); VERIFY_IS_APPROX(p, v.segment(i, size-2*i).prod()); VERIFY_IS_APPROX(minc, v.real().segment(i, size-2*i).minCoeff()); VERIFY_IS_APPROX(maxc, v.real().segment(i, size-2*i).maxCoeff()); } } void test_redux() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( matrixRedux(Matrix<float, 1, 1>()) ); CALL_SUBTEST_1( matrixRedux(Array<float, 1, 1>()) ); CALL_SUBTEST_2( matrixRedux(Matrix2f()) ); CALL_SUBTEST_2( matrixRedux(Array2f()) ); CALL_SUBTEST_3( matrixRedux(Matrix4d()) ); CALL_SUBTEST_3( matrixRedux(Array4d()) ); CALL_SUBTEST_4( matrixRedux(MatrixXcf(3, 3)) ); CALL_SUBTEST_4( matrixRedux(ArrayXXcf(3, 3)) ); CALL_SUBTEST_5( matrixRedux(MatrixXd(8, 12)) ); CALL_SUBTEST_5( matrixRedux(ArrayXXd(8, 12)) ); CALL_SUBTEST_6( matrixRedux(MatrixXi(8, 12)) ); CALL_SUBTEST_6( matrixRedux(ArrayXXi(8, 12)) ); } for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_7( vectorRedux(Vector4f()) ); CALL_SUBTEST_7( vectorRedux(Array4f()) ); CALL_SUBTEST_5( vectorRedux(VectorXd(10)) ); CALL_SUBTEST_5( vectorRedux(ArrayXd(10)) ); CALL_SUBTEST_8( vectorRedux(VectorXf(33)) ); CALL_SUBTEST_8( vectorRedux(ArrayXf(33)) ); } } <|endoftext|>
<commit_before>#include "trainer.hpp" //trainer class void Trainer::SetLife(float life) //setlife function { //write process memory with the new value int stat = WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_LIFE, &life, (DWORD)sizeof(life), NULL); if (stat > 0){ //if it success it says this std::clog << "Sucesso ao escrever na memoria com valor: " << life << std::endl; } else { //if not it says another thing std::cerr << "Ocorreu algo inesperado, tente novamente." << std::endl; } } //same thing as life void Trainer::SetMoney(int money) { int stat = WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_MONEY, &money, (DWORD)sizeof(money), NULL); if (stat > 0){ std::clog << "Sucesso ao escrever na memoria com valor: " << money << std::endl; } else { std::cerr << "Ocorreu algo inesperado, tente novamente." << std::endl; } } //Entries: Red, Green, Blue, Alpha. //Changes the color of health bar void Trainer::SetHealthBarColor(int R, int G, int B, int A) { if (WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_RED, &R, sizeof(R), NULL)) if (WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_GREEN, &G, sizeof(G), NULL)) if (WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_BLUE, &B, sizeof(B), NULL)) if (WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_ALPHA, &A, sizeof(A), NULL)) //it will write all the memories, if the previously won't return an error value. } //this one is diferent it has dynamic address, i did this way but i will probably use another way so i don't have to create //multiple variables to declare each dynamic addres void Trainer::SetArmor(float armor) { unsigned long pointer = 0xB6F5F0; //CPed address unsigned long offset = 0x548; //armor address unsigned long address = pointer + offset; //the address's combined togther //same thing as the life, it writes a new value to the memory int stat = WriteProcessMemory(Trainer::memory.hProc, (LPVOID)address, &armor, (DWORD)sizeof(armor), NULL); if (stat > 0){ std::clog << "Sucesso ao escrever na memoria com valor: " << armor << std::endl; } else { std::cerr << "Ocorreu algo inesperado, tente novamente." << std::endl; } } void Trainer::SetWantedLevel(int level) { int stat = WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_WANTED, &level, (DWORD)sizeof(level), NULL); if (stat > 0){ std::clog << "Sucesso ao escrever na memoria com valor: " << level << std::endl; } else { std::cerr << "Ocorreu algo inesperado, tente novamente." << std::endl; } } /* Future functions void Trainer::SetX(double pos) { int stat = WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_X, &pos, (DWORD)sizeof(pos), NULL); if (stat > 0){ std::clog << "Sucesso ao escrever na memoria com valor: " << pos << std::endl; } else { std::cerr << "Ocorreu algo inesperado, tente novamente." << std::endl; } } void Trainer::SetY(double pos) { int stat = WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_Y, &pos, (DWORD)sizeof(pos), NULL); if (stat > 0){ std::clog << "Sucesso ao escrever na memoria com valor: " << pos << std::endl; } else { std::cerr << "Ocorreu algo inesperado, tente novamente." << std::endl; } } void Trainer::SetZ(double pos) { int stat = WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_Z, &pos, (DWORD)sizeof(pos), NULL); if (stat > 0){ std::clog << "Sucesso ao escrever na memoria com valor: " << pos << std::endl; } else { std::cerr << "Ocorreu algo inesperado, tente novamente." << std::endl; } } void Trainer::SetPos(double x,double y, double z) { Trainer::SetX(x); Trainer::SetY(y); Trainer::SetZ(z); }*/ <commit_msg>Removed useless instructions<commit_after>#include "trainer.hpp" //trainer class void Trainer::SetLife(float life) //setlife function { //write process memory with the new value int stat = WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_LIFE, &life, (DWORD)sizeof(life), NULL); if (stat <= 0){ //if it success it says this std::cerr << "Ocorreu algo inesperado, tente novamente." << std::endl; return; } std::clog << "Sucesso ao escrever na memoria com valor: " << life << std::endl; } //same thing as life void Trainer::SetMoney(int money) { int stat = WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_MONEY, &money, (DWORD)sizeof(money), NULL); if (stat <= 0){ std::cerr << "Ocorreu algo inesperado, tente novamente." << std::endl; return; } std::clog << "Sucesso ao escrever na memoria com valor: " << money << std::endl; } //Entries: Red, Green, Blue, Alpha. //Changes the color of health bar void Trainer::SetHealthBarColor(int R, int G, int B, int A) { if (WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_RED, &R, sizeof(R), NULL)) if (WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_GREEN, &G, sizeof(G), NULL)) if (WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_BLUE, &B, sizeof(B), NULL)) if (WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_ALPHA, &A, sizeof(A), NULL)) //it will write all the memories, if the previously won't return an error value. } //this one is diferent it has dynamic address, i did this way but i will probably use another way so i don't have to create //multiple variables to declare each dynamic addres void Trainer::SetArmor(float armor) { unsigned long pointer = 0xB6F5F0; //CPed address unsigned long offset = 0x548; //armor address unsigned long address = pointer + offset; //the address's combined togther //same thing as the life, it writes a new value to the memory int stat = WriteProcessMemory(Trainer::memory.hProc, (LPVOID)address, &armor, (DWORD)sizeof(armor), NULL); if (stat <= 0){ std::cerr << "Ocorreu algo inesperado, tente novamente." << std::endl; return; } std::clog << "Sucesso ao escrever na memoria com valor: " << armor << std::endl; } void Trainer::SetWantedLevel(int level) { int stat = WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_WANTED, &level, (DWORD)sizeof(level), NULL); if (stat <= 0){ std::cerr << "Ocorreu algo inesperado, tente novamente." << std::endl; return; } std::clog << "Sucesso ao escrever na memoria com valor: " << level << std::endl; } /* Future functions void Trainer::SetX(double pos) { int stat = WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_X, &pos, (DWORD)sizeof(pos), NULL); if (stat > 0){ std::clog << "Sucesso ao escrever na memoria com valor: " << pos << std::endl; } else { std::cerr << "Ocorreu algo inesperado, tente novamente." << std::endl; } } void Trainer::SetY(double pos) { int stat = WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_Y, &pos, (DWORD)sizeof(pos), NULL); if (stat > 0){ std::clog << "Sucesso ao escrever na memoria com valor: " << pos << std::endl; } else { std::cerr << "Ocorreu algo inesperado, tente novamente." << std::endl; } } void Trainer::SetZ(double pos) { int stat = WriteProcessMemory(Trainer::memory.hProc, (LPVOID)Trainer::TRAINER_Z, &pos, (DWORD)sizeof(pos), NULL); if (stat > 0){ std::clog << "Sucesso ao escrever na memoria com valor: " << pos << std::endl; } else { std::cerr << "Ocorreu algo inesperado, tente novamente." << std::endl; } } void Trainer::SetPos(double x,double y, double z) { Trainer::SetX(x); Trainer::SetY(y); Trainer::SetZ(z); }*/ <|endoftext|>
<commit_before>#include "../googletest/include/gtest/gtest.h" #include "../include/easylogging++.h" #include "../include/llg.hpp" #include "../include/integrators.hpp" #include "../include/io.hpp" #include "../include/simulation.hpp" INITIALIZE_EASYLOGGINGPP TEST(llg, drift) { double deriv[3]; const double state[3] = {2, 3, 4}; const double field[3] = {1, 2, 3}; const double time=0, damping=3; llg::drift( deriv, state, time, damping, field ); EXPECT_EQ( -34, deriv[0] ); EXPECT_EQ( -4, deriv[1] ); EXPECT_EQ( 20, deriv[2] ); } TEST(llg, diffusion) { double deriv[3*3]; const double state[3] = { 2, 3, 4 }; const double time=0, sr=2, alpha=3; llg::diffusion( deriv, state, time, sr, alpha ); EXPECT_EQ( 150, deriv[0] ); EXPECT_EQ( -28, deriv[1] ); EXPECT_EQ ( -54, deriv[2] ); EXPECT_EQ ( -44, deriv[3] ); EXPECT_EQ ( 120, deriv[4] ); EXPECT_EQ ( -68, deriv[5] ); EXPECT_EQ ( -42, deriv[6] ); EXPECT_EQ ( -76, deriv[7] ); EXPECT_EQ ( 78, deriv[8] ); } TEST(heun, 2d_wiener) { double next_state[2]; double drift_arr[2]; double trial_drift_arr[2]; double diffusion_matrix[4]; double trial_diffusion_matrix[4]; const double current_state[2] = { 0, 0 }; const double wiener_steps[2] = { 0.1, 0.01 }; const std::function<void(double*,const double*,const double)> drift = [](double *out, const double *in, const double t) { out[0]=0;out[1]=0; }; const std::function<void(double*,const double*,const double)> diffusion = [](double *out, const double *in, const double t) { out[0]=1;out[1]=0;out[2]=0;out[3]=1; }; const size_t n_dims=2, wiener_dims=2; const double t=0, step_size=1.44; integrator::heun( next_state, drift_arr, trial_drift_arr, diffusion_matrix, trial_diffusion_matrix, current_state, wiener_steps, drift, diffusion, n_dims, wiener_dims, t, step_size ); EXPECT_FLOAT_EQ( 0.1, next_state[0] ); EXPECT_FLOAT_EQ( 0.01, next_state[1] ); } TEST(io, write_array) { double arr[3] = {1, 2, 3}, arrback[3]; int fail, nread; fail = io::write_array( "test.out", arr, 3 ); ASSERT_EQ( 0, fail ); // Read back the data FILE *in; in = fopen( "test.out", "rb" ); nread = fread( arrback, sizeof(double), 3, in ); fclose( in ); ASSERT_EQ( 3, nread ); ASSERT_FLOAT_EQ( 1, arrback[0] ); ASSERT_FLOAT_EQ( 2, arrback[1] ); ASSERT_FLOAT_EQ( 3, arrback[2] ); } TEST( simulation, save_results ) { simulation::results res( 2 ); res.magnetisation[0] = 2; res.magnetisation[1] = 3; res.field[0] = 4; res.field[1] = 5; res.time[0] = 6; res.time[1] = 7; simulation::save_results( "test.out", res ); int nread; double arr[2]; FILE *in; in=fopen( "test.out.mag", "rb" ); nread = fread( arr, sizeof(double), 2, in ); ASSERT_EQ( 2, nread ); ASSERT_FLOAT_EQ( 2, arr[0] ); ASSERT_FLOAT_EQ( 3, arr[1] ); in=fopen( "test.out.field", "rb" ); nread = fread( arr, sizeof(double), 2, in ); ASSERT_EQ( 2, nread ); ASSERT_FLOAT_EQ( 4, arr[0] ); ASSERT_FLOAT_EQ( 5, arr[1] ); in=fopen( "test.out.time", "rb" ); nread = fread( arr, sizeof(double), 2, in ); ASSERT_EQ( 2, nread ); ASSERT_FLOAT_EQ( 6, arr[0] ); ASSERT_FLOAT_EQ( 7, arr[1] ); } <commit_msg>improve heun test and add driver test<commit_after>#include "../googletest/include/gtest/gtest.h" #include "../include/easylogging++.h" #include "../include/llg.hpp" #include "../include/integrators.hpp" #include "../include/io.hpp" #include "../include/simulation.hpp" #include <cmath> #include <random> INITIALIZE_EASYLOGGINGPP TEST(llg, drift) { double deriv[3]; const double state[3] = {2, 3, 4}; const double field[3] = {1, 2, 3}; const double time=0, damping=3; llg::drift( deriv, state, time, damping, field ); EXPECT_EQ( -34, deriv[0] ); EXPECT_EQ( -4, deriv[1] ); EXPECT_EQ( 20, deriv[2] ); } TEST(llg, diffusion) { double deriv[3*3]; const double state[3] = { 2, 3, 4 }; const double time=0, sr=2, alpha=3; llg::diffusion( deriv, state, time, sr, alpha ); EXPECT_EQ( 150, deriv[0] ); EXPECT_EQ( -28, deriv[1] ); EXPECT_EQ ( -54, deriv[2] ); EXPECT_EQ ( -44, deriv[3] ); EXPECT_EQ ( 120, deriv[4] ); EXPECT_EQ ( -68, deriv[5] ); EXPECT_EQ ( -42, deriv[6] ); EXPECT_EQ ( -76, deriv[7] ); EXPECT_EQ ( 78, deriv[8] ); } TEST(heun, multiplicative ) { double next_state[2]; double drift_arr[2]; double trial_drift_arr[2]; double diffusion_matrix[6]; double trial_diffusion_matrix[6]; const double current_state[2] = { 1, 2 }; const double wiener_steps[3] = { 0.1, 0.01, 0.001 }; const std::function<void(double*,const double*,const double)> drift = [](double *out, const double *in, const double t) { out[0]=in[0]*in[1]*t; out[1]=3*in[0]; }; const std::function<void(double*,const double*,const double)> diffusion = [](double *out, const double *in, const double t) { out[0]=t; out[1]=in[0]; out[2]=in[1]; out[3]=in[1]; out[4]=4.0; out[5]=in[0]*in[1]; }; const size_t n_dims=2, wiener_dims=3; const double t=0, step_size=0.1;; integrator::heun( next_state, drift_arr, trial_drift_arr, diffusion_matrix, trial_diffusion_matrix, current_state, wiener_steps, drift, diffusion, n_dims, wiener_dims, t, step_size ); EXPECT_FLOAT_EQ( 1.03019352, next_state[0] ); EXPECT_FLOAT_EQ( 2.57118625, next_state[1] ); } TEST(io, write_array) { double arr[3] = {1, 2, 3}, arrback[3]; int fail, nread; fail = io::write_array( "test.out", arr, 3 ); ASSERT_EQ( 0, fail ); // Read back the data FILE *in; in = fopen( "test.out", "rb" ); nread = fread( arrback, sizeof(double), 3, in ); fclose( in ); ASSERT_EQ( 3, nread ); ASSERT_DOUBLE_EQ( 1, arrback[0] ); ASSERT_DOUBLE_EQ( 2, arrback[1] ); ASSERT_DOUBLE_EQ( 3, arrback[2] ); } TEST( simulation, save_results ) { simulation::results res( 2 ); res.magnetisation[0] = 2; res.magnetisation[1] = 3; res.field[0] = 4; res.field[1] = 5; res.time[0] = 6; res.time[1] = 7; simulation::save_results( "test.out", res ); int nread; double arr[2]; FILE *in; in=fopen( "test.out.mag", "rb" ); nread = fread( arr, sizeof(double), 2, in ); ASSERT_EQ( 2, nread ); ASSERT_DOUBLE_EQ( 2, arr[0] ); ASSERT_DOUBLE_EQ( 3, arr[1] ); in=fopen( "test.out.field", "rb" ); nread = fread( arr, sizeof(double), 2, in ); ASSERT_EQ( 2, nread ); ASSERT_DOUBLE_EQ( 4, arr[0] ); ASSERT_DOUBLE_EQ( 5, arr[1] ); in=fopen( "test.out.time", "rb" ); nread = fread( arr, sizeof(double), 2, in ); ASSERT_EQ( 2, nread ); ASSERT_DOUBLE_EQ( 6, arr[0] ); ASSERT_DOUBLE_EQ( 7, arr[1] ); } TEST( heun_driver, ou ) { const size_t n_steps = 5000; const size_t n_dims = 1; const size_t n_wiener = 1; const double step_size = 1e-5; const double initial_state[1]={-3}; // define the Ornstein-Uhlenbeck process const double ou_theta = 10; const double ou_mu = -1; const double ou_sigma = 0.8; const std::function<void(double*,const double*,const double)> drift = [ou_theta,ou_mu](double *out, const double *in, const double t) { out[0]=ou_theta*(ou_mu - in[0]); }; const std::function<void(double*,const double*,const double)> diffusion = [ou_sigma](double *out, const double *in, const double t) { out[0]=ou_sigma; }; // Create a wiener path double wiener_process[n_steps]; std::normal_distribution<double> dist( 0, std::sqrt( step_size ) ); std::mt19937_64 rng; for( unsigned int i=0; i<n_steps; i++ ) wiener_process[i] = dist( rng ); // Generate the states double states[n_steps]; driver::heun( states, initial_state, wiener_process, drift, diffusion, n_steps, n_dims, n_wiener, step_size ); // Compute the analytic solution and compare pathwise similarity double truesol = initial_state[0]; for( unsigned int i=1; i<n_steps; i++ ) { truesol = truesol*std::exp( -ou_theta*step_size ) + ou_mu*( 1-std::exp( -ou_theta*step_size ) ) + ou_sigma*std::sqrt( ( 1- std::exp( -2*ou_theta*step_size ) )/( 2*ou_theta ) ) * wiener_process[i-1]/std::sqrt( step_size ); ASSERT_NEAR( truesol, states[i], 1e-8 ); } } <|endoftext|>
<commit_before>// Copyright 2022 Michael Fisher <[email protected]> // SPDX-License-Identifier: ISC #include <algorithm> #include "lvtk/ui/input.hpp" #include "lvtk/ui/main.hpp" #include "lvtk/ui/view.hpp" #include "lvtk/ui/widget.hpp" #define PUGL_DISABLE_DEPRECATED #include <pugl/pugl.h> // flip these for verbose logging // #define VIEW_DBG(x) std::clog << x << std::endl; #define VIEW_DBG(x) namespace lvtk { namespace detail { template <typename Tp, class Ev> static inline Point<Tp> point (const Ev& ev) { return { static_cast<Tp> (ev.x), static_cast<Tp> (ev.y) }; } template <typename Tp, class Ev> static inline Rectangle<Tp> rect (const Ev& ev) { return { static_cast<Tp> (ev.x), static_cast<Tp> (ev.y), static_cast<Tp> (ev.width), static_cast<Tp> (ev.height) }; } template <typename Rect> static inline PuglRect frame (const Rect& r) { return { static_cast<PuglCoord> (r.x), static_cast<PuglCoord> (r.y), static_cast<PuglSpan> (r.width), static_cast<PuglSpan> (r.height) }; } inline static void erase (std::vector<View*>& views, View* view) { auto it = std::find (views.begin(), views.end(), view); if (it != views.end()) views.erase (it); } } // namespace detail struct View::EventHandler { static PuglStatus configure (View& view, const PuglConfigureEvent& ev) { if (ev.flags & PUGL_IS_HINT) { VIEW_DBG ("configure: hint"); return PUGL_SUCCESS; } auto& w = view._widget; w.set_bounds (w.x(), w.y(), ev.width / view.scale_factor(), ev.height / view.scale_factor()); VIEW_DBG ("pugl: configure: " << w.bounds().str()); return PUGL_SUCCESS; } static PuglStatus expose (View& view, const PuglExposeEvent& ev) { if (ev.flags & PUGL_IS_HINT) { VIEW_DBG ("expose: hint"); return PUGL_SUCCESS; } auto x = (float) ev.x / view.scale_factor(); auto y = (float) ev.y / view.scale_factor(); auto w = (float) ev.width / view.scale_factor(); auto h = (float) ev.height / view.scale_factor(); view.expose (Rectangle<float> { x, y, w, h }.as<int>()); return PUGL_SUCCESS; } static PuglStatus create (View& view, const PuglCreateEvent& ev) { view.created(); return PUGL_SUCCESS; } static PuglStatus destroy (View& view, const PuglDestroyEvent& ev) { view.destroyed(); return PUGL_SUCCESS; } static PuglStatus map (View& view, const PuglMapEvent& ev) { return PUGL_SUCCESS; } static PuglStatus unmap (View& view, const PuglUnmapEvent& ev) { return PUGL_SUCCESS; } static PuglStatus update (View& view, const PuglUpdateEvent& ev) { return PUGL_SUCCESS; } static PuglStatus close (View& view, const PuglCloseEvent& ev) { // dirty setup so the demo can at least quit... if (view._main.mode() == Mode::PROGRAM) view._main.quit(); return PUGL_SUCCESS; } static PuglStatus focus_in (View& view, const PuglFocusEvent& ev) { return PUGL_SUCCESS; } static PuglStatus focus_out (View& view, const PuglFocusEvent& ev) { return PUGL_SUCCESS; } static PuglStatus key_press (View& view, const PuglKeyEvent& ev) { return PUGL_SUCCESS; } static PuglStatus key_release (View& view, const PuglKeyEvent& ev) { return PUGL_SUCCESS; } static PuglStatus text (View& view, const PuglTextEvent& ev) { return PUGL_SUCCESS; } static PuglStatus pointer_in (View& view, const PuglCrossingEvent& ev) { VIEW_DBG ("pointer in") return PUGL_SUCCESS; } static PuglStatus pointer_out (View& view, const PuglCrossingEvent& ev) { VIEW_DBG ("pointer out") return PUGL_SUCCESS; } static PuglStatus motion (View& view, const PuglMotionEvent& ev) { auto pos = detail::point<float> (ev) / view.scale_factor(); WidgetRef ref = view._widget.widget_at (pos); InputEvent event; if (ref.valid()) { event.pos = ref->convert (&view._widget, pos); if (view._hovered != ref) { VIEW_DBG ("hovered changed: " << ref->__name); ref->pointer_in (event); view._hovered = ref; } ref->motion (event); } else if (view._hovered) { VIEW_DBG ("hovered cleared"); if (auto h = view._hovered.lock()) { event.pos = h->convert (&view._widget, pos); h->pointer_out (event); } view._hovered = nullptr; } return PUGL_SUCCESS; } static PuglStatus button_press (View& view, const PuglButtonEvent& ev) { InputEvent event; event.pos = detail::point<float> (ev) / view.scale_factor(); if (auto w = view._hovered.lock()) { event.pos = w->convert (&view._widget, event.pos); // VIEW_DBG("widget:" << w->__name << " bounds: " << w->bounds().str()); // VIEW_DBG("ev pos: " << event.pos.str()); if (w->contains (event.pos)) w->pressed (event); } return PUGL_SUCCESS; } static PuglStatus button_release (View& view, const PuglButtonEvent& ev) { InputEvent event; event.pos = detail::point<float> (ev) / view.scale_factor(); auto hovered = view._hovered; if (auto w = hovered.lock()) { event.pos = hovered->convert (&view._widget, event.pos); if (w->contains (event.pos)) w->released (event); } return PUGL_SUCCESS; } static PuglStatus scroll (View& view, const PuglScrollEvent& ev) { return PUGL_SUCCESS; } static PuglStatus client (View& view, const PuglClientEvent& ev) { return PUGL_SUCCESS; } static PuglStatus timer (View& view, const PuglTimerEvent& ev) { return PUGL_SUCCESS; } static PuglStatus loop_enter (View& view, const PuglLoopEnterEvent& ev) { return PUGL_SUCCESS; } static PuglStatus loop_leave (View& view, const PuglLoopLeaveEvent& ev) { return PUGL_SUCCESS; } static PuglStatus data_offer (View& view, const PuglDataOfferEvent& ev) { return PUGL_SUCCESS; } static PuglStatus data (View& view, const PuglDataEvent& ev) { return PUGL_SUCCESS; } static PuglStatus nothing (View&, const PuglAnyEvent&) { return PUGL_SUCCESS; } static inline PuglStatus dispatch (PuglView* v, const PuglEvent* ev) { auto view = static_cast<View*> (puglGetHandle (v)); PuglStatus status = PUGL_SUCCESS; #define CASE3(t, fn, arg) \ case t: \ status = fn (*view, arg); \ break; #define CASE2(t, fn) CASE3 (t, fn, ev->fn) #define CASEA(t, fn) CASE3 (t, fn, ev->any) switch (ev->type) { CASE2 (PUGL_CONFIGURE, configure) //< View moved/resized, a #PuglConfigureEvent CASEA (PUGL_UPDATE, update) //< View ready to draw, a #PuglUpdateEvent CASE2 (PUGL_EXPOSE, expose) //< View must be drawn, a #PuglExposeEvent CASEA (PUGL_CREATE, create) //< View created, a #PuglCreateEvent CASEA (PUGL_DESTROY, destroy) ///< View destroyed, a #PuglDestroyEvent CASEA (PUGL_MAP, map) ///< View made visible, a #PuglMapEvent CASEA (PUGL_UNMAP, unmap) ///< View made invisible, a #PuglUnmapEvent CASEA (PUGL_CLOSE, close) ///< View will be closed, a #PuglCloseEvent CASE3 (PUGL_FOCUS_IN, focus_in, ev->focus) ///< Keyboard focus entered view, a #PuglFocusEvent CASE3 (PUGL_FOCUS_OUT, focus_out, ev->focus) ///< Keyboard focus left view, a #PuglFocusEvent CASE3 (PUGL_KEY_PRESS, key_press, ev->key) ///< Key pressed, a #PuglKeyEvent CASE3 (PUGL_KEY_RELEASE, key_release, ev->key) ///< Key released, a #PuglKeyEvent CASE2 (PUGL_TEXT, text) ///< Character entered, a #PuglTextEvent CASE3 (PUGL_POINTER_IN, pointer_in, ev->crossing) ///< Pointer entered view, a #PuglCrossingEvent CASE3 (PUGL_POINTER_OUT, pointer_out, ev->crossing) ///< Pointer left view, a #PuglCrossingEvent CASE3 (PUGL_BUTTON_PRESS, button_press, ev->button) ///< Mouse button pressed, a #PuglButtonEvent CASE3 (PUGL_BUTTON_RELEASE, button_release, ev->button) ///< Mouse button released, a #PuglButtonEvent CASE2 (PUGL_MOTION, motion) ///< Pointer moved, a #PuglMotionEvent CASE2 (PUGL_SCROLL, scroll) ///< Scrolled, a #PuglScrollEvent CASE2 (PUGL_CLIENT, client) ///< Custom client message, a #PuglClientEvent CASE2 (PUGL_TIMER, timer) ///< Timer triggered, a #PuglTimerEvent CASEA (PUGL_LOOP_ENTER, loop_enter) ///< Recursive loop entered, a #PuglLoopEnterEvent CASEA (PUGL_LOOP_LEAVE, loop_leave) ///< Recursive loop left, a #PuglLoopLeaveEvent CASE3 (PUGL_DATA_OFFER, data_offer, ev->offer) ///< Data offered from clipboard, a #PuglDataOfferEvent CASE2 (PUGL_DATA, data) ///< Data available from clipboard, a #PuglDataEvent CASE3 (PUGL_NOTHING, nothing, ev->any) ///< No event default: break; } #undef CASE2 #undef CASE3 #undef CASEA return status; } }; View::View (Main& m, Widget& w) : _main (m), _widget (w) { _view = (uintptr_t) puglNewView ((PuglWorld*) m.world()); auto v = (PuglView*) _view; puglSetHandle (v, this); puglSetEventFunc (v, EventHandler::dispatch); _weak_status.reset (this); _main._views.push_back (this); } View::~View() { detail::erase (_main._views, this); _weak_status.reset(); puglFreeView ((PuglView*) _view); _view = (uintptr_t) nullptr; } void View::set_backend (uintptr_t b) { puglSetBackend ((PuglView*) _view, (PuglBackend*) b); } void View::set_view_hint (int hint, int value) { puglSetViewHint ((PuglView*) _view, static_cast<PuglViewHint> (hint), value); } uintptr_t View::handle() { return puglGetNativeView ((PuglView*) _view); } float View::scale_factor() const noexcept { return static_cast<float> (puglGetScaleFactor ((PuglView*) _view)); } void View::set_visible (bool visible) { if (visible) puglShow ((PuglView*) _view); else puglHide ((PuglView*) _view); } bool View::visible() const { return puglGetVisible ((PuglView*) _view); } void View::set_size (int width, int height) { puglSetSize ((PuglView*) _view, width * scale_factor(), height * scale_factor()); } Rectangle<int> View::bounds() const { auto f = puglGetFrame ((PuglView*) _view); return { static_cast<int> ((float) f.x / scale_factor()), static_cast<int> ((float) f.y / scale_factor()), static_cast<int> ((float) f.width / scale_factor()), static_cast<int> ((float) f.height / scale_factor()) }; } void View::set_bounds (Bounds b) { b *= scale_factor(); puglSetFrame ((PuglView*) _view, detail::frame (b)); } void View::realize() { puglRealize ((PuglView*) _view); } Style& View::style() noexcept { return _main.style(); } const Style& View::style() const noexcept { return _main.style(); } void View::elevate (Widget& widget, ViewFlags flags) { _main.elevate (widget, flags, *this); } //== void View::render (Surface& ctx) { Graphics g (ctx); _widget.render (g); } void View::set_parent (uintptr_t parent, bool transient) { if (! parent) return; if (transient) puglSetTransientParent ((PuglView*) _view, parent); else puglSetParentWindow ((PuglView*) _view, parent); } void View::__pugl_post_redisplay() { puglPostRedisplay ((PuglView*) _view); } } // namespace lvtk <commit_msg>limit pointer_out coords to widget local bounds<commit_after>// Copyright 2022 Michael Fisher <[email protected]> // SPDX-License-Identifier: ISC #include <algorithm> #include "lvtk/ui/input.hpp" #include "lvtk/ui/main.hpp" #include "lvtk/ui/view.hpp" #include "lvtk/ui/widget.hpp" #define PUGL_DISABLE_DEPRECATED #include <pugl/pugl.h> // flip these for verbose logging // #define VIEW_DBG(x) std::clog << x << std::endl; #define VIEW_DBG(x) namespace lvtk { namespace detail { template <typename Tp, class Ev> static inline Point<Tp> point (const Ev& ev) { return { static_cast<Tp> (ev.x), static_cast<Tp> (ev.y) }; } template <typename Tp, class Ev> static inline Rectangle<Tp> rect (const Ev& ev) { return { static_cast<Tp> (ev.x), static_cast<Tp> (ev.y), static_cast<Tp> (ev.width), static_cast<Tp> (ev.height) }; } template <typename Rect> static inline PuglRect frame (const Rect& r) { return { static_cast<PuglCoord> (r.x), static_cast<PuglCoord> (r.y), static_cast<PuglSpan> (r.width), static_cast<PuglSpan> (r.height) }; } inline static void erase (std::vector<View*>& views, View* view) { auto it = std::find (views.begin(), views.end(), view); if (it != views.end()) views.erase (it); } } // namespace detail struct View::EventHandler { static PuglStatus configure (View& view, const PuglConfigureEvent& ev) { if (ev.flags & PUGL_IS_HINT) { VIEW_DBG ("configure: hint"); return PUGL_SUCCESS; } auto& w = view._widget; w.set_bounds (w.x(), w.y(), ev.width / view.scale_factor(), ev.height / view.scale_factor()); VIEW_DBG ("pugl: configure: " << w.bounds().str()); return PUGL_SUCCESS; } static PuglStatus expose (View& view, const PuglExposeEvent& ev) { if (ev.flags & PUGL_IS_HINT) { VIEW_DBG ("expose: hint"); return PUGL_SUCCESS; } auto x = (float) ev.x / view.scale_factor(); auto y = (float) ev.y / view.scale_factor(); auto w = (float) ev.width / view.scale_factor(); auto h = (float) ev.height / view.scale_factor(); view.expose (Rectangle<float> { x, y, w, h }.as<int>()); return PUGL_SUCCESS; } static PuglStatus create (View& view, const PuglCreateEvent& ev) { view.created(); return PUGL_SUCCESS; } static PuglStatus destroy (View& view, const PuglDestroyEvent& ev) { view.destroyed(); return PUGL_SUCCESS; } static PuglStatus map (View& view, const PuglMapEvent& ev) { return PUGL_SUCCESS; } static PuglStatus unmap (View& view, const PuglUnmapEvent& ev) { return PUGL_SUCCESS; } static PuglStatus update (View& view, const PuglUpdateEvent& ev) { return PUGL_SUCCESS; } static PuglStatus close (View& view, const PuglCloseEvent& ev) { // dirty setup so the demo can at least quit... if (view._main.mode() == Mode::PROGRAM) view._main.quit(); return PUGL_SUCCESS; } static PuglStatus focus_in (View& view, const PuglFocusEvent& ev) { return PUGL_SUCCESS; } static PuglStatus focus_out (View& view, const PuglFocusEvent& ev) { return PUGL_SUCCESS; } static PuglStatus key_press (View& view, const PuglKeyEvent& ev) { return PUGL_SUCCESS; } static PuglStatus key_release (View& view, const PuglKeyEvent& ev) { return PUGL_SUCCESS; } static PuglStatus text (View& view, const PuglTextEvent& ev) { return PUGL_SUCCESS; } static PuglStatus pointer_in (View& view, const PuglCrossingEvent& ev) { VIEW_DBG ("pointer in") return PUGL_SUCCESS; } static PuglStatus pointer_out (View& view, const PuglCrossingEvent& ev) { VIEW_DBG ("pointer out") return PUGL_SUCCESS; } static PuglStatus motion (View& view, const PuglMotionEvent& ev) { auto pos = detail::point<float> (ev) / view.scale_factor(); WidgetRef ref = view._widget.widget_at (pos); InputEvent event; if (ref.valid()) { event.pos = ref->convert (&view._widget, pos); if (view._hovered != ref) { VIEW_DBG ("hovered changed: " << ref->__name); ref->pointer_in (event); view._hovered = ref; } ref->motion (event); } else if (view._hovered) { VIEW_DBG ("hovered cleared"); if (auto h = view._hovered.lock()) { event.pos = h->convert (&view._widget, pos); event.pos.x = std::min (std::max (0.f, event.pos.x), (float)h->width()); event.pos.y = std::min (std::max (0.f, event.pos.y), (float)h->height()); h->pointer_out (event); } view._hovered = nullptr; } return PUGL_SUCCESS; } static PuglStatus button_press (View& view, const PuglButtonEvent& ev) { InputEvent event; event.pos = detail::point<float> (ev) / view.scale_factor(); if (auto w = view._hovered.lock()) { event.pos = w->convert (&view._widget, event.pos); // VIEW_DBG("widget:" << w->__name << " bounds: " << w->bounds().str()); // VIEW_DBG("ev pos: " << event.pos.str()); if (w->contains (event.pos)) w->pressed (event); } return PUGL_SUCCESS; } static PuglStatus button_release (View& view, const PuglButtonEvent& ev) { InputEvent event; event.pos = detail::point<float> (ev) / view.scale_factor(); auto hovered = view._hovered; if (auto w = hovered.lock()) { event.pos = hovered->convert (&view._widget, event.pos); if (w->contains (event.pos)) w->released (event); } return PUGL_SUCCESS; } static PuglStatus scroll (View& view, const PuglScrollEvent& ev) { return PUGL_SUCCESS; } static PuglStatus client (View& view, const PuglClientEvent& ev) { return PUGL_SUCCESS; } static PuglStatus timer (View& view, const PuglTimerEvent& ev) { return PUGL_SUCCESS; } static PuglStatus loop_enter (View& view, const PuglLoopEnterEvent& ev) { return PUGL_SUCCESS; } static PuglStatus loop_leave (View& view, const PuglLoopLeaveEvent& ev) { return PUGL_SUCCESS; } static PuglStatus data_offer (View& view, const PuglDataOfferEvent& ev) { return PUGL_SUCCESS; } static PuglStatus data (View& view, const PuglDataEvent& ev) { return PUGL_SUCCESS; } static PuglStatus nothing (View&, const PuglAnyEvent&) { return PUGL_SUCCESS; } static inline PuglStatus dispatch (PuglView* v, const PuglEvent* ev) { auto view = static_cast<View*> (puglGetHandle (v)); PuglStatus status = PUGL_SUCCESS; #define CASE3(t, fn, arg) \ case t: \ status = fn (*view, arg); \ break; #define CASE2(t, fn) CASE3 (t, fn, ev->fn) #define CASEA(t, fn) CASE3 (t, fn, ev->any) switch (ev->type) { CASE2 (PUGL_CONFIGURE, configure) //< View moved/resized, a #PuglConfigureEvent CASEA (PUGL_UPDATE, update) //< View ready to draw, a #PuglUpdateEvent CASE2 (PUGL_EXPOSE, expose) //< View must be drawn, a #PuglExposeEvent CASEA (PUGL_CREATE, create) //< View created, a #PuglCreateEvent CASEA (PUGL_DESTROY, destroy) ///< View destroyed, a #PuglDestroyEvent CASEA (PUGL_MAP, map) ///< View made visible, a #PuglMapEvent CASEA (PUGL_UNMAP, unmap) ///< View made invisible, a #PuglUnmapEvent CASEA (PUGL_CLOSE, close) ///< View will be closed, a #PuglCloseEvent CASE3 (PUGL_FOCUS_IN, focus_in, ev->focus) ///< Keyboard focus entered view, a #PuglFocusEvent CASE3 (PUGL_FOCUS_OUT, focus_out, ev->focus) ///< Keyboard focus left view, a #PuglFocusEvent CASE3 (PUGL_KEY_PRESS, key_press, ev->key) ///< Key pressed, a #PuglKeyEvent CASE3 (PUGL_KEY_RELEASE, key_release, ev->key) ///< Key released, a #PuglKeyEvent CASE2 (PUGL_TEXT, text) ///< Character entered, a #PuglTextEvent CASE3 (PUGL_POINTER_IN, pointer_in, ev->crossing) ///< Pointer entered view, a #PuglCrossingEvent CASE3 (PUGL_POINTER_OUT, pointer_out, ev->crossing) ///< Pointer left view, a #PuglCrossingEvent CASE3 (PUGL_BUTTON_PRESS, button_press, ev->button) ///< Mouse button pressed, a #PuglButtonEvent CASE3 (PUGL_BUTTON_RELEASE, button_release, ev->button) ///< Mouse button released, a #PuglButtonEvent CASE2 (PUGL_MOTION, motion) ///< Pointer moved, a #PuglMotionEvent CASE2 (PUGL_SCROLL, scroll) ///< Scrolled, a #PuglScrollEvent CASE2 (PUGL_CLIENT, client) ///< Custom client message, a #PuglClientEvent CASE2 (PUGL_TIMER, timer) ///< Timer triggered, a #PuglTimerEvent CASEA (PUGL_LOOP_ENTER, loop_enter) ///< Recursive loop entered, a #PuglLoopEnterEvent CASEA (PUGL_LOOP_LEAVE, loop_leave) ///< Recursive loop left, a #PuglLoopLeaveEvent CASE3 (PUGL_DATA_OFFER, data_offer, ev->offer) ///< Data offered from clipboard, a #PuglDataOfferEvent CASE2 (PUGL_DATA, data) ///< Data available from clipboard, a #PuglDataEvent CASE3 (PUGL_NOTHING, nothing, ev->any) ///< No event default: break; } #undef CASE2 #undef CASE3 #undef CASEA return status; } }; View::View (Main& m, Widget& w) : _main (m), _widget (w) { _view = (uintptr_t) puglNewView ((PuglWorld*) m.world()); auto v = (PuglView*) _view; puglSetHandle (v, this); puglSetEventFunc (v, EventHandler::dispatch); _weak_status.reset (this); _main._views.push_back (this); } View::~View() { detail::erase (_main._views, this); _weak_status.reset(); puglFreeView ((PuglView*) _view); _view = (uintptr_t) nullptr; } void View::set_backend (uintptr_t b) { puglSetBackend ((PuglView*) _view, (PuglBackend*) b); } void View::set_view_hint (int hint, int value) { puglSetViewHint ((PuglView*) _view, static_cast<PuglViewHint> (hint), value); } uintptr_t View::handle() { return puglGetNativeView ((PuglView*) _view); } float View::scale_factor() const noexcept { return static_cast<float> (puglGetScaleFactor ((PuglView*) _view)); } void View::set_visible (bool visible) { if (visible) puglShow ((PuglView*) _view); else puglHide ((PuglView*) _view); } bool View::visible() const { return puglGetVisible ((PuglView*) _view); } void View::set_size (int width, int height) { puglSetSize ((PuglView*) _view, width * scale_factor(), height * scale_factor()); } Rectangle<int> View::bounds() const { auto f = puglGetFrame ((PuglView*) _view); return { static_cast<int> ((float) f.x / scale_factor()), static_cast<int> ((float) f.y / scale_factor()), static_cast<int> ((float) f.width / scale_factor()), static_cast<int> ((float) f.height / scale_factor()) }; } void View::set_bounds (Bounds b) { b *= scale_factor(); puglSetFrame ((PuglView*) _view, detail::frame (b)); } void View::realize() { puglRealize ((PuglView*) _view); } Style& View::style() noexcept { return _main.style(); } const Style& View::style() const noexcept { return _main.style(); } void View::elevate (Widget& widget, ViewFlags flags) { _main.elevate (widget, flags, *this); } //== void View::render (Surface& ctx) { Graphics g (ctx); _widget.render (g); } void View::set_parent (uintptr_t parent, bool transient) { if (! parent) return; if (transient) puglSetTransientParent ((PuglView*) _view, parent); else puglSetParentWindow ((PuglView*) _view, parent); } void View::__pugl_post_redisplay() { puglPostRedisplay ((PuglView*) _view); } } // namespace lvtk <|endoftext|>
<commit_before>#include "../mtl.hpp" #include "../src/debug.hpp" #include <iostream> using A = std::tuple<int, int>; using B = std::tuple<long, char>; // Has type // ================================================================================ static_assert(mtl::has_type<char, B>::value, ""); static_assert(mtl::has_type<long, B>::value, ""); static_assert(!mtl::has_type<int, B>::value, ""); // Concat // ================================================================================ using C = mtl::concat<A, B>; using D = mtl::concat<A>; using E = mtl::concat<A, B, C, D>; static_assert(std::tuple_size<C>::value == 4, "C should be size of 4"); static_assert(std::tuple_size<D>::value == 2, "D should be size of 2"); static_assert(std::tuple_size<E>::value == 10, "E should be size of 10"); // Head // ================================================================================ static_assert(std::is_same<long, mtl::head<B>>::value, ""); // Index of type // Select // ================================================================================ static_assert(std::is_same<std::tuple<char, int>, mtl::select<C, 3, 1>>::value, ""); // Tail // ================================================================================ static_assert(std::is_same<std::tuple<int, long, char>, mtl::tail<C>>::value, ""); // Transform // ================================================================================ static_assert(std::is_same<std::tuple<int, int>, mtl::transform<B, mtl::transform_to<int>::value>>::value, ""); static_assert(std::is_same<std::tuple<long, char>, mtl::transform<B, mtl::identity>>::value, ""); // Filter // ================================================================================ template<typename T> struct no_ints { static constexpr auto value = !std::is_same<T, int>::value; }; static_assert(std::is_same<std::tuple<char, float>, mtl::filter<no_ints, std::tuple<int, char, int, float>>>::value, ""); // Unique // ================================================================================ static_assert(std::is_same<std::tuple<int, char, float, long>, mtl::unique<std::tuple<int, char, int, float, char, long>>>::value, ""); // Without // ================================================================================ static_assert(std::is_same<std::tuple<char, float, char, long>, mtl::without<int, std::tuple<int, char, int, float, char, long>>>::value, ""); // Interleave // ================================================================================ static_assert(std::is_same<std::tuple<int, long, char, long, int, long>, mtl::interleave<std::tuple<int, char, int>, std::tuple<long, long, long>>>::value, ""); static_assert(std::is_same<std::tuple<int, char, char>, mtl::interleave<std::tuple<int>, std::tuple<char, char>>>::value, ""); // Merge // ================================================================================ using MA = std::tuple<float, int, float>; using MB = std::tuple<int, char, char>; using MVec = std::tuple<float, int, char>; using MC = mtl::merge<MA, MB, MVec>; static_assert(std::tuple_size<MC>::value == 6, ""); static_assert(std::is_same<std::tuple<float, int, float, int, char, char>, MC>::value, ""); // Sort // ================================================================================ using ST = std::tuple<int, char, int, int, float, char, float, int>; using SV = std::tuple<char, int, float>; using SC = mtl::sort<ST, SV>; static_assert(std::is_same<std::tuple<char, char, int, int, int, int, float, float>, SC>::value, ""); int main() { return 0; } <commit_msg>Cleanup<commit_after>#include "../mtl.hpp" #include "../src/debug.hpp" #include <iostream> using A = std::tuple<int, int>; using B = std::tuple<long, char>; // Has type // ================================================================================ static_assert(mtl::has_type<char, B>::value, ""); static_assert(mtl::has_type<long, B>::value, ""); static_assert(!mtl::has_type<int, B>::value, ""); // Concat // ================================================================================ using C = mtl::concat<A, B>; using D = mtl::concat<A>; using E = mtl::concat<A, B, C, D>; static_assert(std::tuple_size<C>::value == 4, "C should be size of 4"); static_assert(std::tuple_size<D>::value == 2, "D should be size of 2"); static_assert(std::tuple_size<E>::value == 10, "E should be size of 10"); // Head // ================================================================================ static_assert(std::is_same<long, mtl::head<B>>::value, ""); // Index of type // Select // ================================================================================ static_assert(std::is_same<std::tuple<char, int>, mtl::select<C, 3, 1>>::value, ""); // Tail // ================================================================================ static_assert(std::is_same<std::tuple<int, long, char>, mtl::tail<C>>::value, ""); // Transform // ================================================================================ static_assert(std::is_same<std::tuple<int, int>, mtl::transform<B, mtl::transform_to<int>::value>>::value, ""); static_assert(std::is_same<std::tuple<long, char>, mtl::transform<B, mtl::identity>>::value, ""); // Filter // ================================================================================ template<typename T> struct no_ints { static constexpr auto value = !std::is_same<T, int>::value; }; static_assert(std::is_same<std::tuple<char, float>, mtl::filter<no_ints, std::tuple<int, char, int, float>>>::value, ""); // Unique // ================================================================================ static_assert(std::is_same<std::tuple<int, char, float, long>, mtl::unique<std::tuple<int, char, int, float, char, long>>>::value, ""); // Without // ================================================================================ static_assert(std::is_same<std::tuple<char, float, char, long>, mtl::without<int, std::tuple<int, char, int, float, char, long>>>::value, ""); // Interleave // ================================================================================ static_assert(std::is_same<std::tuple<int, long, char, long, int, long>, mtl::interleave<std::tuple<int, char, int>, std::tuple<long, long, long>>>::value, ""); static_assert(std::is_same<std::tuple<int, char, char>, mtl::interleave<std::tuple<int>, std::tuple<char, char>>>::value, ""); // Merge // ================================================================================ using MA = std::tuple<float, int, float>; using MB = std::tuple<int, char, char>; using MC = mtl::merge<MA, MB, std::tuple<float, int, char>>; static_assert(std::is_same<std::tuple<float, int, float, int, char, char>, MC>::value, ""); // Sort // ================================================================================ using ST = std::tuple<int, char, int, int, float, char, float, int>; using SC = mtl::sort<ST, std::tuple<char, int, float>>; static_assert(std::is_same<std::tuple<char, char, int, int, int, int, float, float>, SC>::value, ""); int main() { return 0; } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <iostream> #define MAXSTRLEN 255 // 用户可在255以内定义最大串长 typedef unsigned char SString[MAXSTRLEN+1]; // 0号单元存放串的长度 void get_next(SString T,int next[]){ int i=1,j; next[1]=0; j=0; while(i<T[0]){ if(j == 0 || T[i]==T[j]){ ++i; ++j; if(T[i]!=T[j]){ next[i]=j; }else{ next[i]=next[j]; } } else j=next[j]; } } int Index_KMP(SString S,SString T,int pos){ // 算法4.6 // 利用模式串T的next函数求T在主串S中第pos个字符之后的位置 // KMP算法。请补全代码 int i=pos,j=1; int next[T[0]]; get_next(T,next); while(i<=S[0] &&j<=T[0]){ if(j==0 || S[i] == T[i]){ ++i; ++j; }else{ j=next[j]; } } if(j>T[0]) return i-T[0]; return 0 } void main() { SString T,S; int i,j,n; char ch; int pos; scanf(“%d”,&n); // 指定n对需进行模式匹配的字符串 ch=getchar(); for(j=1;j<=n;j++) { ch=getchar(); for( i=1;i<=MAXSTRLEN&&(ch!='\n');i++) // 录入主串 { S[i]=ch; ch=getchar(); } S[0]=i-1; // S[0]用于存储主串中字符个数 ch=getchar(); for( i=1;i<=MAXSTRLEN&&(ch!='\n');i++) // 录入模式串 { T[i]=ch; ch=getchar(); } T[0]=i-1; // T[0]用于存储模式串中字符个数 pos=Index_KMP(S,T,1); // 请填空 printf("%d\n",pos); } }<commit_msg>update uoj8592<commit_after>#include <cstdio> #include <cstdlib> #include <iostream> #define MAXSTRLEN 255 // 用户可在255以内定义最大串长 typedef unsigned char SString[MAXSTRLEN+1]; // 0号单元存放串的长度 void get_next(SString T,int next[]){ int i=1,j; next[1]=0; j=0; while(i<T[0]){ if(j == 0 || T[i]==T[j]){ ++i; ++j; if(T[i]!=T[j]){ next[i]=j; }else{ next[i]=next[j]; } } else j=next[j]; } } int Index_KMP(SString S,SString T,int pos){ // 算法4.6 // 利用模式串T的next函数求T在主串S中第pos个字符之后的位置 // KMP算法。请补全代码 int i=pos,j=1; int next[T[0]]; get_next(T,next); while(i<=S[0] &&j<=T[0]){ if(j==0 || S[i] == T[i]){ ++i; ++j; }else{ j=next[j]; } } if(j>T[0]) return i-T[0]; return 0; } int main() { SString T,S; int i,j,n; char ch; int pos; scanf("%d",&n); // 指定n对需进行模式匹配的字符串 ch=getchar(); for(j=1;j<=n;j++) { ch=getchar(); for( i=1;i<=MAXSTRLEN&&(ch!='\n');i++) // 录入主串 { S[i]=ch; ch=getchar(); } S[0]=i-1; // S[0]用于存储主串中字符个数 ch=getchar(); for( i=1;i<=MAXSTRLEN&&(ch!='\n');i++) // 录入模式串 { T[i]=ch; ch=getchar(); } T[0]=i-1; // T[0]用于存储模式串中字符个数 pos=Index_KMP(S,T,1); // 请填空 printf("%d\n",pos); } }<|endoftext|>
<commit_before>#pragma once #include "util.hh" #include "queue.hh" #include <avr/interrupt.h> #include <util/delay.h> #include <util/twi.h> // See http://www.chrisherring.net/all/tutorial-interrupt-driven-twi-interface-for-avr-part1/ /* enum TWIMode { TWIMaster, TWISlave }; */ class I2C { public: enum TransferMode { kNoStop, // Used to send repeated start in the subsequent transfer kSendStop }; }; template<class I2CPeriph, byte address> class I2CDevice { public: static void send(byte *const data, byte nBytes, I2C::TransferMode mode = I2C::kSendStop) { I2CPeriph::write(address, data, nBytes, mode); } static void receive(byte * data, byte nBytes, I2C::TransferMode mode = I2C::kSendStop) { I2CPeriph::read(address, data, nBytes, mode); } }; class TWIMaster : public I2C { public: static void setup(uint32_t clockFrequency = 100000ul) { _state = kReady; _errorCode = 0xFF; _repStart = 0; // Set prescaler (no prescaling) (TODO: set correct prescaler) // Note that no prescaler is necessary for 100kHz clock TWSR = 0; // Set bit rate TWBR = ((F_CPU / clockFrequency) - 16) / 2; // Enable TWI and interrupt TWCR = (1 << TWIE) | (1 << TWEN); } static byte write(byte address, byte *const data, byte nBytes, TransferMode mode = kSendStop) { if (!isTWIReady()) return 0; _sla = (address << 1) | TW_WRITE; _mode = mode; _data = data; _dataLength = nBytes; TWISendStart(); } static byte read(byte address, byte *data, byte nBytes, TransferMode mode = kSendStop) { _sla = (address << 1) | TW_READ; _mode = mode; _data = data; _dataLength = nBytes; TWISendStart(); } static bool isReady(void) { return (_state == kReady) || (_state == kRepeatedStartSent); } static bool onTWIInterrupt() { interruptImpl(); } private: enum State { kReady, kInitializing, kRepeatedStartSent, kTransmit, kReceive }; static byte _sla; static State _state; static byte _errorCode; static TransmitMode _mode; static byte * _data; static byte _dataLength; // The total number of bytes to transmit /************************ Helper methods ************************/ // Send the START signal, enable interrupts and TWI, clear TWINT flag to resume transfer. static void TWISendStart() { TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN)|(1<<TWIE); } // Send the STOP signal, enable interrupts and TWI, clear TWINT flag. static void TWISendStop() { TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN)|(1<<TWIE); } // Used to resume a transfer, clear TWINT and ensure that TWI and interrupts are enabled. static void TWISendTransmit() { TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWIE); } // FOR MR mode. Resume a transfer, ensure that TWI and interrupts are enabled // and respond with an ACK if the device is addressed as a slave or after it receives a byte. static void TWISendACK() { TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWIE)|(1<<TWEA); } // FOR MR mode. Resume a transfer, ensure that TWI and interrupts are enabled // but DO NOT respond with an ACK if the device is addressed as a slave or after // it receives a byte. static void TWISendNACK() { TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWIE); } /********************* TWI state machine *********************/ static void interruptImpl() { switch (TW_STATUS) { // ----\/ ---- START CONDITION ----\/ ---- // case TW_START: // Start condition has been transmitted TWDR = _sla; // Transmit either SLA+W or SLA+R TWISendTransmit(); break; // ----\/ ---- MASTER TRANSMITTER ----\/ ---- // case TW_MT_SLA_ACK: // SLA+W transmitted and ACK received case TW_MT_DATA_ACK: // Data byte has been transmitted, ACK received if (_dataLength > 0) // If there is more data to send { TWDR = *_data++; // Load data to transmit buffer _dataLength--; _errorCode = TW_NO_INFO; TWISendTransmit(); // Send the data } // All transmissions are complete, exit else { _state = kReady; _errorCode = 0xFF; if (_mode == kSendStop) { TWISendStop(); } } break; // ----\/ ---- MASTER RECEIVER ----\/ ---- // case TW_MR_SLA_ACK: // SLA+R has been transmitted, ACK has been received // Switch to Master Receiver mode _state = kReceive; _errorCode = TW_NO_INFO; // If there is more than one byte to be read, receive data byte and return an ACK if (_dataLength > 1) { TWISendACK(); } // Otherwise when a data byte (the only data byte) is received, return NACK else { TWISendNACK(); } break; case TW_MR_DATA_ACK: // Data has been received, ACK has been transmitted. /// -- HANDLE DATA BYTE --- /// *_data++ = TWDR; _dataLength--; _errorCode = TW_NO_INFO; // If there is more than one byte to be read, receive data byte and return an ACK if (_dataLength > 1) { TWISendACK(); } // Otherwise when a data byte (the only data byte) is received, return NACK else { TWISendNACK(); } break; case TW_MR_DATA_NACK: // Data byte has been received, NACK has been transmitted. End of transmission. /// -- HANDLE DATA BYTE --- /// *_data+++ = TWDR; _dataLength--; // All transmissions are complete, exit _state = kReady; _errorCode = 0xFF; if (_mode == kSendStop) { TWISendStop(); } break; // ----\/ ---- MT and MR common ----\/ ---- // case TW_MR_SLA_NACK: // SLA+R transmitted, NACK received case TW_MT_SLA_NACK: // SLA+W transmitted, NACK received case TW_MT_DATA_NACK: // Data byte has been transmitted, NACK received case TW_MT_ARB_LOST: // Arbitration has been lost _state = kReady; _errorCode = TW_STATUS; TWISendStop(); break; case TW_REP_START: // Repeated start has been transmitted // Set the mode but DO NOT clear TWINT as the next data is not yet ready _state = kRepeatedStartSent; break; // ----\/ ---- SLAVE RECEIVER ----\/ ---- // // TODO IMPLEMENT SLAVE RECEIVER FUNCTIONALITY // ----\/ ---- SLAVE TRANSMITTER ----\/ ---- // // TODO IMPLEMENT SLAVE TRANSMITTER FUNCTIONALITY // ----\/ ---- MISCELLANEOUS STATES ----\/ ---- // case TW_NO_INFO: // It is not really possible to get into this ISR on this condition // Rather, it is there to be manually set between operations break; case TW_BUS_ERROR: // Illegal START/STOP, abort and return error _errorCode = TW_STATUS; _state = kReady; TWISendStop(); break; } } }; <commit_msg>Syntax error fix<commit_after>#pragma once #include "util.hh" #include "queue.hh" #include <avr/interrupt.h> #include <util/delay.h> #include <util/twi.h> // See http://www.chrisherring.net/all/tutorial-interrupt-driven-twi-interface-for-avr-part1/ /* enum TWIMode { TWIMaster, TWISlave }; */ class I2C { public: enum TransferMode { kNoStop, // Used to send repeated start in the subsequent transfer kSendStop }; }; template<class I2CPeriph, byte address> class I2CDevice { public: static void send(byte *const data, byte nBytes, I2C::TransferMode mode = I2C::kSendStop) { I2CPeriph::write(address, data, nBytes, mode); } static void receive(byte * data, byte nBytes, I2C::TransferMode mode = I2C::kSendStop) { I2CPeriph::read(address, data, nBytes, mode); } }; class TWIMaster : public I2C { public: static void setup(uint32_t clockFrequency = 100000ul) { _state = kReady; _errorCode = 0xFF; // Set prescaler (no prescaling) (TODO: set correct prescaler) // Note that no prescaler is necessary for 100kHz clock TWSR = 0; // Set bit rate TWBR = ((F_CPU / clockFrequency) - 16) / 2; // Enable TWI and interrupt TWCR = (1 << TWIE) | (1 << TWEN); } static byte write(byte address, byte *const data, byte nBytes, TransferMode mode = kSendStop) { if (!isReady()) return 0; _sla = (address << 1) | TW_WRITE; _mode = mode; _data = data; _dataLength = nBytes; TWISendStart(); } static byte read(byte address, byte *data, byte nBytes, TransferMode mode = kSendStop) { _sla = (address << 1) | TW_READ; _mode = mode; _data = data; _dataLength = nBytes; TWISendStart(); } static bool isReady(void) { return (_state == kReady) || (_state == kRepeatedStartSent); } static bool onTWIInterrupt() { interruptImpl(); } private: enum State { kReady, kInitializing, kRepeatedStartSent, kTransmit, kReceive }; static byte _sla; static State _state; static byte _errorCode; static TransferMode _mode; static byte * _data; static byte _dataLength; // The total number of bytes to transmit /************************ Helper methods ************************/ // Send the START signal, enable interrupts and TWI, clear TWINT flag to resume transfer. static void TWISendStart() { TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN)|(1<<TWIE); } // Send the STOP signal, enable interrupts and TWI, clear TWINT flag. static void TWISendStop() { TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN)|(1<<TWIE); } // Used to resume a transfer, clear TWINT and ensure that TWI and interrupts are enabled. static void TWISendTransmit() { TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWIE); } // FOR MR mode. Resume a transfer, ensure that TWI and interrupts are enabled // and respond with an ACK if the device is addressed as a slave or after it receives a byte. static void TWISendACK() { TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWIE)|(1<<TWEA); } // FOR MR mode. Resume a transfer, ensure that TWI and interrupts are enabled // but DO NOT respond with an ACK if the device is addressed as a slave or after // it receives a byte. static void TWISendNACK() { TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWIE); } /********************* TWI state machine *********************/ static void interruptImpl() { switch (TW_STATUS) { // ----\/ ---- START CONDITION ----\/ ---- // case TW_START: // Start condition has been transmitted TWDR = _sla; // Transmit either SLA+W or SLA+R TWISendTransmit(); break; // ----\/ ---- MASTER TRANSMITTER ----\/ ---- // case TW_MT_SLA_ACK: // SLA+W transmitted and ACK received case TW_MT_DATA_ACK: // Data byte has been transmitted, ACK received if (_dataLength > 0) // If there is more data to send { TWDR = *_data++; // Load data to transmit buffer _dataLength--; _errorCode = TW_NO_INFO; TWISendTransmit(); // Send the data } // All transmissions are complete, exit else { _state = kReady; _errorCode = 0xFF; if (_mode == kSendStop) { TWISendStop(); } } break; // ----\/ ---- MASTER RECEIVER ----\/ ---- // case TW_MR_SLA_ACK: // SLA+R has been transmitted, ACK has been received // Switch to Master Receiver mode _state = kReceive; _errorCode = TW_NO_INFO; // If there is more than one byte to be read, receive data byte and return an ACK if (_dataLength > 1) { TWISendACK(); } // Otherwise when a data byte (the only data byte) is received, return NACK else { TWISendNACK(); } break; case TW_MR_DATA_ACK: // Data has been received, ACK has been transmitted. /// -- HANDLE DATA BYTE --- /// *_data++ = TWDR; _dataLength--; _errorCode = TW_NO_INFO; // If there is more than one byte to be read, receive data byte and return an ACK if (_dataLength > 1) { TWISendACK(); } // Otherwise when a data byte (the only data byte) is received, return NACK else { TWISendNACK(); } break; case TW_MR_DATA_NACK: // Data byte has been received, NACK has been transmitted. End of transmission. /// -- HANDLE DATA BYTE --- /// *_data++ = TWDR; _dataLength--; // All transmissions are complete, exit _state = kReady; _errorCode = 0xFF; if (_mode == kSendStop) { TWISendStop(); } break; // ----\/ ---- MT and MR common ----\/ ---- // case TW_MR_SLA_NACK: // SLA+R transmitted, NACK received case TW_MT_SLA_NACK: // SLA+W transmitted, NACK received case TW_MT_DATA_NACK: // Data byte has been transmitted, NACK received case TW_MT_ARB_LOST: // Arbitration has been lost _state = kReady; _errorCode = TW_STATUS; TWISendStop(); break; case TW_REP_START: // Repeated start has been transmitted // Set the mode but DO NOT clear TWINT as the next data is not yet ready _state = kRepeatedStartSent; break; // ----\/ ---- SLAVE RECEIVER ----\/ ---- // // TODO IMPLEMENT SLAVE RECEIVER FUNCTIONALITY // ----\/ ---- SLAVE TRANSMITTER ----\/ ---- // // TODO IMPLEMENT SLAVE TRANSMITTER FUNCTIONALITY // ----\/ ---- MISCELLANEOUS STATES ----\/ ---- // case TW_NO_INFO: // It is not really possible to get into this ISR on this condition // Rather, it is there to be manually set between operations break; case TW_BUS_ERROR: // Illegal START/STOP, abort and return error _errorCode = TW_STATUS; _state = kReady; TWISendStop(); break; } } }; <|endoftext|>
<commit_before>/* * Copyright 2014–2015 The SmartSqlite contributors (see NOTICE.txt) * * 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 "smartsqlite/version.h" #include <cstring> #include "smartsqlite/sqlite3.h" namespace SmartSqlite { namespace { const auto SMARTSQLITE_VERSION_CODE = int{4}; const auto SMARTSQLITE_VERSION_STRING = std::string{"v4"}; } std::string version() { return SMARTSQLITE_VERSION_STRING; } int versionCode() { return SMARTSQLITE_VERSION_CODE; } std::string sqliteVersion() { return sqlite3_libversion(); } bool checkSqliteVersion() { return (sqlite3_libversion_number() == SQLITE_VERSION_NUMBER) && (std::strcmp(sqlite3_sourceid(), SQLITE_SOURCE_ID) == 0) && (std::strcmp(sqlite3_libversion(), SQLITE_VERSION) == 0); } } <commit_msg>Make failing version check more verbose<commit_after>/* * Copyright 2014–2015 The SmartSqlite contributors (see NOTICE.txt) * * 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 "smartsqlite/version.h" #include <cstring> #include <iostream> #include "smartsqlite/sqlite3.h" namespace SmartSqlite { namespace { const auto SMARTSQLITE_VERSION_CODE = int{4}; const auto SMARTSQLITE_VERSION_STRING = std::string{"v4"}; } std::string version() { return SMARTSQLITE_VERSION_STRING; } int versionCode() { return SMARTSQLITE_VERSION_CODE; } std::string sqliteVersion() { return sqlite3_libversion(); } bool checkSqliteVersion() { auto logPrefix = "SmartSqlite version check failed: "; bool success = true; if (sqlite3_libversion_number() != SQLITE_VERSION_NUMBER) { success = false; std::cerr << logPrefix << "sqlite3_libversion_number()==" << sqlite3_libversion_number() << ", SQLITE_VERSION_NUMBER==" << SQLITE_VERSION_NUMBER << std::endl; } if (std::strcmp(sqlite3_sourceid(), SQLITE_SOURCE_ID)) { success = false; std::cerr << logPrefix << "sqlite3_sourceid()==" << sqlite3_sourceid() << ", SQLITE_SOURCE_ID==" << SQLITE_SOURCE_ID << std::endl; } if (std::strcmp(sqlite3_libversion(), SQLITE_VERSION)) { success = false; std::cerr << logPrefix << "sqlite3_libversion()==" << sqlite3_libversion() << ", SQLITE_VERSION==" << SQLITE_VERSION << std::endl; } return success; } } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "version.h" // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("MintCoin"); // Client version number #define CLIENT_VERSION_SUFFIX "" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. #define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "" # define GIT_COMMIT_DATE "$Format:%cD" #endif #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "" #ifndef BUILD_DESC # ifdef GIT_COMMIT_ID # define BUILD_DESC BUILD_DESC_FROM_COMMIT(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(DISPLAY_VERSION_MAJOR, DISPLAY_VERSION_MINOR, DISPLAY_VERSION_REVISION, DISPLAY_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <commit_msg>Better version string formatting<commit_after>// Copyright (c) 2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "version.h" #include <string> // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. const std::string CLIENT_NAME("MintCoin"); // Client version number #define CLIENT_VERSION_SUFFIX "" // The following part of the code determines the CLIENT_BUILD variable. // Several mechanisms are used for this: // * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is // generated by the build environment, possibly containing the output // of git-describe in a macro called BUILD_DESC // * secondly, if this is an exported version of the code, GIT_ARCHIVE will // be defined (automatically using the export-subst git attribute), and // GIT_COMMIT will contain the commit id. // * then, three options exist for determining CLIENT_BUILD: // * if BUILD_DESC is defined, use that literally (output of git-describe) // * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] // * otherwise, use v[maj].[min].[rev].[build]-unk // finally CLIENT_VERSION_SUFFIX is added // First, include build.h if requested #ifdef HAVE_BUILD_INFO # include "build.h" #endif // git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$ #ifdef GIT_ARCHIVE # define GIT_COMMIT_ID "$Format:%h$" # define GIT_COMMIT_DATE "$Format:%cD$" #endif #define BUILD_DESC_WITH_SUFFIX(maj,min,rev,build,suffix) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix) #define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC # ifdef BUILD_SUFFIX # define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX) # elif defined(GIT_COMMIT_ID) # define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) # else # define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) # endif #endif #ifndef BUILD_DATE # ifdef GIT_COMMIT_DATE # define BUILD_DATE GIT_COMMIT_DATE # else # define BUILD_DATE __DATE__ ", " __TIME__ # endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); <|endoftext|>
<commit_before>#include <BinaryTree.hpp> #include <catch.hpp> SCENARIO ("init", "[init]") { BinaryTree<int> obj; REQUIRE(obj.root_() == nullptr); } SCENARIO("insert", "[insert]") { BinaryTree<int> obj; obj.insert_node(3); REQUIRE(obj.find_node(3, obj.root_())->data == 3); } SCENARIO("find_node", "[find_node]") { BinaryTree<int> obj; obj.insert_node(2); REQUIRE(obj.find_node(2, obj.root_()) != nullptr); REQUIRE(obj.find_node(2, obj.root_())->data == 2); } SCENARIO("get root", "[get root]") { BinaryTree<int> obj; obj.insert_node(4); REQUIRE(obj.root_() != 0); } SCENARIO ("reading", "[reading]") { BinaryTree<int> obj; obj.reading("file1.txt"); REQUIRE(obj.search_result(1) == 1); } <commit_msg>Update init.cpp<commit_after>#include <BinaryTree.hpp> #include <catch.hpp> SCENARIO ("init", "[init]") { BinaryTree<int> obj; REQUIRE(obj.root_() == nullptr); } SCENARIO("insert", "[insert]") { BinaryTree<int> obj; obj.insert_node(3); REQUIRE(obj.find_node(3, obj.root_())->data == 3); } SCENARIO("find_node", "[find_node]") { BinaryTree<int> obj; obj.insert_node(2); REQUIRE(obj.find_node(2, obj.root_()) != nullptr); REQUIRE(obj.find_node(2, obj.root_())->data == 2); } SCENARIO("get root", "[get root]") { BinaryTree<int> obj; obj.insert_node(4); REQUIRE(obj.root_() != 0); } SCENARIO ("reading", "[init]") { BinaryTree<int> obj; obj.reading("file2.txt"); REQUIRE(obj.search_result(1) == 1)) } <|endoftext|>
<commit_before>#include <binary_search_tree.hpp> #include <catch.hpp> SCENARIO("default constructor") { BinarySearchTree<int> bst; REQUIRE(bst.root() == nullptr); REQUIRE(bst.count() == 0); } SCENARIO("insertElement") { BinarySearchTree<int> bst; bst.insert(7); REQUIRE(bst.findElement() == 7); REQUIRE(bst.count() == 1); } <commit_msg>Update init.cpp<commit_after>#include <binary_search_tree.hpp> #include <catch.hpp> SCENARIO("default constructor") { BinarySearchTree<int> bst; REQUIRE(bst.root() == nullptr); REQUIRE(bst.count() == 0); } SCENARIO("insertElement") { BinarySearchTree<int> bst; bst.insertElement(7); REQUIRE(bst.findElement() == 7); REQUIRE(bst.count() == 1); } <|endoftext|>
<commit_before>#include <matrix.hpp> #include <catch.hpp> SCENARIO("matrix init without parametrs", "[init wp]") { Matrix matrix; REQUIRE(matrix.rows() == 4); REQUIRE(matrix.columns() == 4); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.Element(i,j) == 0); } } } SCENARIO("matrix init with parametrs", "[init withp]") { Matrix matrix(6,6); REQUIRE(matrix.rows() == 6); REQUIRE(matrix.columns() == 6); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.Element(i,j) == 0); } } } SCENARIO("matrix init copy", "[init copy]") { Matrix matrix(6,6); Matrix matrix1(matrix); REQUIRE(matrix1.rows() == matrix.rows()); REQUIRE(matrix1.columns() == matrix.columns()); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j)); } } } SCENARIO("matrix fill", "[fill]") { Matrix matrix(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); matrix.fill("test1.txt"); REQUIRE(matrix.Element(0,0) == 1); REQUIRE(matrix.Element(0,1) == 2); REQUIRE(matrix.Element(1,0) == 3); REQUIRE(matrix.Element(1,1) == 4); } SCENARIO("matrix sum", "[sum]") { Matrix matrix(2,2); Matrix matrix1(2,2); Matrix sum(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); matrix.fill("test1.txt"); matrix1.fill("test1.txt"); //ofstream sumfile("sumfile.txt"); //sumfile << "2 4 6 8"; //sum.fill("sumfile.txt"); //sumfile.close(); REQUIRE(matrix.Element(0,0) + matrix1.Element(0,0) == 2); REQUIRE(matrix.Element(0,1) + matrix1.Element(0,1) == 4); REQUIRE(matrix.Element(1,0) + matrix1.Element(1,0) == 6); REQUIRE(matrix.Element(1,1) + matrix1.Element(1,1) == 8); } <commit_msg>Update init.cpp<commit_after>#include <matrix.hpp> #include <catch.hpp> SCENARIO("matrix init without parametrs", "[init wp]") { Matrix matrix; REQUIRE(matrix.rows() == 4); REQUIRE(matrix.columns() == 4); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.Element(i,j) == 0); } } } SCENARIO("matrix init with parametrs", "[init withp]") { Matrix matrix(6,6); REQUIRE(matrix.rows() == 6); REQUIRE(matrix.columns() == 6); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.Element(i,j) == 0); } } } SCENARIO("matrix init copy", "[init copy]") { Matrix matrix(6,6); Matrix matrix1(matrix); REQUIRE(matrix1.rows() == matrix.rows()); REQUIRE(matrix1.columns() == matrix.columns()); for (int i=0;i<matrix.rows(); i++) { for (int j = 0; j<matrix.columns();j++) { REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j)); } } } SCENARIO("matrix fill", "[fill]") { Matrix matrix(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); matrix.fill("test1.txt"); REQUIRE(matrix.Element(0,0) == 1); REQUIRE(matrix.Element(0,1) == 2); REQUIRE(matrix.Element(1,0) == 3); REQUIRE(matrix.Element(1,1) == 4); } SCENARIO("matrix sum", "[sum]") { Matrix matrix(2,2); Matrix matrix1(2,2); Matrix sum(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); matrix.fill("test1.txt"); matrix1.fill("test1.txt"); //ofstream sumfile("sumfile.txt"); //sumfile << "2 4 6 8"; //sum.fill("sumfile.txt"); //sumfile.close(); REQUIRE(matrix.Element(0,0) + matrix1.Element(0,0) == 2); REQUIRE(matrix.Element(0,1) + matrix1.Element(0,1) == 4); REQUIRE(matrix.Element(1,0) + matrix1.Element(1,0) == 6); REQUIRE(matrix.Element(1,1) + matrix1.Element(1,1) == 8); } SCENARIO("matrix Proizv", "[Pro]") { Matrix matrix(2,2); Matrix matrix1(2,2); Matrix Pro(2,2); ofstream test1("test1.txt"); test1 << "1 2 3 4"; test1.close(); matrix.fill("test1.txt"); matrix1.fill("test1.txt"); //ofstream sumfile("sumfile.txt"); //sumfile << "2 4 6 8"; //sum.fill("sumfile.txt"); //sumfile.close(); REQUIRE(matrix[0][0] * matrix1[0][0] + matrix[0][1] * matrix[1][0] == 7); REQUIRE(matrix[0][0] * matrix1[1][0] + matrix[0][1] * matrix[1][1] == 10); REQUIRE(matrix[0][1] * matrix1[0][0] + matrix[1][1] * matrix[0][1] == 15); REQUIRE(matrix[0][1] * matrix1[1][0] + matrix[1][1] * matrix[1][1] == 22); } <|endoftext|>
<commit_before>#define CATCH_CONFIG_RUNNER #include <catch.hpp> #include "sphere.cpp" #include "box.hpp" #include <glm/vec3.hpp> TEST_CASE("get volume of sphere", "[volume]") { Sphere sphere; REQUIRE(sphere.volume() == Approx(4.1888)); } TEST_CASE("get area of sphere", "[area]") { Sphere sphere; REQUIRE(sphere.area() == Approx(12.5664)); } TEST_CASE("get radius of sphere", "[radius]") { Sphere sphere; REQUIRE(sphere.radius() == 1); } TEST_CASE("get center of sphere", "[center]") { Sphere sphere; glm::vec3 tmp{0,0,0}; REQUIRE(sphere.center() == tmp); } TEST_CASE("constructors of sphere", "[constructors]") { Sphere s1; Sphere s2{{0,0,0},1}; REQUIRE(s1.center() == s2.center()); REQUIRE(s1.radius() == s2.radius()); REQUIRE(s1.area() == s2.area()); REQUIRE(s1.volume() == s2.volume()); } TEST_CASE("constructors for box", "[constructors]") { Box b1; glm::vec3 tmp{0,0,0}; REQUIRE(b1.min() == tmp); tmp = {1,1,1}; REQUIRE(b1.max() == tmp); Box b2{{1,1,3},{3,2,2}}; tmp = {1,1,2}; REQUIRE(b2.min() == tmp); tmp = {3,2,3}; REQUIRE(b2.max() == tmp); } int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); } <commit_msg>Add mehtod tests for box<commit_after>#define CATCH_CONFIG_RUNNER #include <catch.hpp> #include "sphere.cpp" #include "box.hpp" #include <glm/vec3.hpp> TEST_CASE("get volume of sphere", "[volume]") { Sphere sphere; REQUIRE(sphere.volume() == Approx(4.1888)); } TEST_CASE("get area of sphere", "[area]") { Sphere sphere; REQUIRE(sphere.area() == Approx(12.5664)); } TEST_CASE("get radius of sphere", "[radius]") { Sphere sphere; REQUIRE(sphere.radius() == 1); } TEST_CASE("get center of sphere", "[center]") { Sphere sphere; glm::vec3 tmp{0,0,0}; REQUIRE(sphere.center() == tmp); } TEST_CASE("constructors of sphere", "[constructors]") { Sphere s1; Sphere s2{{0,0,0},1}; REQUIRE(s1.center() == s2.center()); REQUIRE(s1.radius() == s2.radius()); REQUIRE(s1.area() == s2.area()); REQUIRE(s1.volume() == s2.volume()); } TEST_CASE("constructors for box", "[constructors]") { Box b1; glm::vec3 tmp{0,0,0}; REQUIRE(b1.min() == tmp); tmp = {1,1,1}; REQUIRE(b1.max() == tmp); Box b2{{1,1,3},{3,2,2}}; tmp = {1,1,2}; REQUIRE(b2.min() == tmp); tmp = {3,2,3}; REQUIRE(b2.max() == tmp); } TEST_CASE("get area of box", "[area]") { Box box; REQUIRE(box.area() == 6); } TEST_CASE("get volume of box", "[area]") { Box box; REQUIRE(box.volume() == 1); } int main(int argc, char *argv[]) { return Catch::Session().run(argc, argv); } //Tests for Box<|endoftext|>
<commit_before>#include <gtest\gtest.h> #include <BufferedReader.h> TEST(BufferedReader, OpenClose) { BufferedReader reader(1024); EXPECT_FALSE(reader.Close()); EXPECT_FALSE(reader.Open(nullptr)); EXPECT_FALSE(reader.Open(L"C:/temp/cwd/zbot")); EXPECT_TRUE(reader.Open(L"file")); EXPECT_TRUE(reader.Close()); EXPECT_FALSE(reader.Close()); EXPECT_FALSE(reader.Open(nullptr)); } TEST(BufferedReader, InvalidRead) { BufferedReader reader(256); BYTE buffer[8192] = {}; EXPECT_EQ(0, reader.Read(nullptr, 0)); EXPECT_EQ(0, reader.Read(buffer, 0)); EXPECT_EQ(0, reader.Read(nullptr, 128)); EXPECT_EQ(0, reader.Read(buffer, 128)); EXPECT_EQ(0, reader.Read(nullptr, 512)); EXPECT_EQ(0, reader.Read(buffer, 512)); } TEST(BufferedReader, Read) { BufferedReader reader(256); HANDLE hFile; DWORD readSize1, readSize2; BYTE buffer1[8192] = {}, buffer2[8192] = {}; hFile = CreateFile(L"file", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile == INVALID_HANDLE_VALUE) return; EXPECT_TRUE(reader.Open(L"file")); EXPECT_EQ(0, reader.Read(buffer1, 0)); readSize1 = reader.Read(buffer1, 128); ReadFile(hFile, buffer2, 128, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); readSize1 = reader.Read(buffer1, 512); ReadFile(hFile, buffer2, 512, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); readSize1 = reader.Read(buffer1, 2048); ReadFile(hFile, buffer2, 2048, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); SetFilePointer(hFile, 0, nullptr, SEEK_SET); readSize1 = reader.Read(0, buffer1, 128); ReadFile(hFile, buffer2, 128, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); SetFilePointer(hFile, 0, nullptr, SEEK_SET); readSize1 = reader.Read(0, buffer1, 256); ReadFile(hFile, buffer2, 256, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); SetFilePointer(hFile, 0, nullptr, SEEK_SET); readSize1 = reader.Read(0, buffer1, 2048); ReadFile(hFile, buffer2, 2048, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); SetFilePointer(hFile, 0x100, nullptr, SEEK_SET); readSize1 = reader.Read(0x100, buffer1, 2048); ReadFile(hFile, buffer2, 2048, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); } int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<commit_msg>add test<commit_after>#include <gtest\gtest.h> #include <BufferedReader.h> TEST(BufferedReader, OpenClose) { BufferedReader reader(1024); EXPECT_FALSE(reader.Close()); EXPECT_FALSE(reader.Open(nullptr)); EXPECT_FALSE(reader.Open(L"C:/temp/cwd/zbot")); EXPECT_TRUE(reader.Open(L"file")); EXPECT_TRUE(reader.Close()); EXPECT_FALSE(reader.Close()); EXPECT_FALSE(reader.Open(nullptr)); } TEST(BufferedReader, InvalidRead) { BufferedReader reader(256); BYTE buffer[8192] = {}; EXPECT_EQ(0, reader.Read(nullptr, 0)); EXPECT_EQ(0, reader.Read(buffer, 0)); EXPECT_EQ(0, reader.Read(nullptr, 128)); EXPECT_EQ(0, reader.Read(buffer, 128)); EXPECT_EQ(0, reader.Read(nullptr, 512)); EXPECT_EQ(0, reader.Read(buffer, 512)); } TEST(BufferedReader, Read) { BufferedReader reader(256); HANDLE hFile; DWORD readSize1, readSize2; BYTE buffer1[8192] = {}, buffer2[8192] = {}; hFile = CreateFile(L"file", GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile == INVALID_HANDLE_VALUE) return; EXPECT_TRUE(reader.Open(L"file")); EXPECT_EQ(0, reader.Read(buffer1, 0)); readSize1 = reader.Read(buffer1, 128); ReadFile(hFile, buffer2, 128, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); readSize1 = reader.Read(buffer1, 512); ReadFile(hFile, buffer2, 512, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); readSize1 = reader.Read(buffer1, 2048); ReadFile(hFile, buffer2, 2048, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); SetFilePointer(hFile, 0, nullptr, SEEK_SET); readSize1 = reader.Read(0, buffer1, 128); ReadFile(hFile, buffer2, 128, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); SetFilePointer(hFile, 0, nullptr, SEEK_SET); readSize1 = reader.Read(0, buffer1, 256); ReadFile(hFile, buffer2, 256, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); SetFilePointer(hFile, 0, nullptr, SEEK_SET); readSize1 = reader.Read(0, buffer1, 2048); ReadFile(hFile, buffer2, 2048, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); SetFilePointer(hFile, 0x100, nullptr, SEEK_SET); readSize1 = reader.Read(0x100, buffer1, 2048); ReadFile(hFile, buffer2, 2048, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); for (DWORD i = 0; i < 256; ++i) { SetFilePointer(hFile, i, nullptr, SEEK_SET); readSize1 = reader.Read(i, buffer1, 128); ReadFile(hFile, buffer2, 128, &readSize2, nullptr); EXPECT_EQ(readSize2, readSize1); EXPECT_EQ(0, memcmp(buffer1, buffer2, readSize1)); } } int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }<|endoftext|>
<commit_before>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2020 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #define CATCH_CONFIG_RUNNER #include "catch2/catch.hpp" #include <openspace/engine/configuration.h> #include <openspace/engine/globals.h> #include <openspace/engine/openspaceengine.h> #include <openspace/engine/windowdelegate.h> #include <openspace/util/factorymanager.h> #include <openspace/util/spicemanager.h> #include <openspace/util/time.h> #include <ghoul/filesystem/file.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/logging/logmanager.h> #include <ghoul/lua/ghoul_lua.h> #include <ghoul/misc/dictionary.h> #include <ghoul/ghoul.h> #include <iostream> int main(int argc, char** argv) { using namespace openspace; ghoul::initialize(); // Register the path of the executable, // to make it possible to find other files in the same directory. FileSys.registerPathToken( "${BIN}", ghoul::filesystem::File(absPath(argv[0])).directoryName(), ghoul::filesystem::FileSystem::Override::Yes ); std::string configFile = configuration::findConfiguration(); *global::configuration = configuration::loadConfigurationFromFile(configFile); global::openSpaceEngine->registerPathTokens(); global::openSpaceEngine->initialize(); FileSys.registerPathToken("${TESTDIR}", "${BASE}/tests"); // All of the relevant tests initialize the SpiceManager openspace::SpiceManager::deinitialize(); int result = Catch::Session().run(argc, argv); // And the deinitialization needs the SpiceManager to be initialized openspace::SpiceManager::initialize(); global::openSpaceEngine->deinitialize(); return result; } <commit_msg>Restored missing global::create call to tests app<commit_after>/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2020 * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #define CATCH_CONFIG_RUNNER #include "catch2/catch.hpp" #include <openspace/engine/configuration.h> #include <openspace/engine/globals.h> #include <openspace/engine/openspaceengine.h> #include <openspace/engine/windowdelegate.h> #include <openspace/util/factorymanager.h> #include <openspace/util/spicemanager.h> #include <openspace/util/time.h> #include <ghoul/filesystem/file.h> #include <ghoul/filesystem/filesystem.h> #include <ghoul/logging/logmanager.h> #include <ghoul/lua/ghoul_lua.h> #include <ghoul/misc/dictionary.h> #include <ghoul/ghoul.h> #include <iostream> int main(int argc, char** argv) { using namespace openspace; ghoul::initialize(); global::create(); // Register the path of the executable, // to make it possible to find other files in the same directory. FileSys.registerPathToken( "${BIN}", ghoul::filesystem::File(absPath(argv[0])).directoryName(), ghoul::filesystem::FileSystem::Override::Yes ); std::string configFile = configuration::findConfiguration(); *global::configuration = configuration::loadConfigurationFromFile(configFile); global::openSpaceEngine->registerPathTokens(); global::openSpaceEngine->initialize(); FileSys.registerPathToken("${TESTDIR}", "${BASE}/tests"); // All of the relevant tests initialize the SpiceManager openspace::SpiceManager::deinitialize(); int result = Catch::Session().run(argc, argv); // And the deinitialization needs the SpiceManager to be initialized openspace::SpiceManager::initialize(); global::openSpaceEngine->deinitialize(); return result; } <|endoftext|>
<commit_before>/* code_completion_service.cpp */ #include "code_completion_service.h" #include "io/resource_loader.h" #include "globals.h" #ifdef GDSCRIPT_ENABLED #include "modules/gdscript/gd_script.h" #endif static bool _is_symbol(CharType c) { return c!='_' && ((c>='!' && c<='/') || (c>=':' && c<='@') || (c>='[' && c<='`') || (c>='{' && c<='~') || c=='\t'); } static bool _is_completable(CharType c) { return !_is_symbol(c) || c=='"' || c=='\''; } CodeCompletionService::Result CodeCompletionService::obtain_suggestions(const Request& p_request) { #ifdef GDSCRIPT_ENABLED Result result(true); String path = Globals::get_singleton()->localize_path(p_request.script_path); if (path == "res://" || !path.begins_with("res://")) return Result(); Ref<Script> script = ResourceLoader::load(path); if (!script.is_valid() || !script->cast_to<GDScript>()) return Result(); String script_text = p_request.script_text; if (script_text.empty()) { ERR_FAIL_COND_V(!script->has_source_code(), result); script_text = script->get_source_code(); } Node *base = get_tree()->get_edited_scene_root(); if (base) { base = _find_node_for_script(base,base,script); } String current_line = _get_text_for_completion(p_request, script_text); List<String> options; script->get_language()->complete_code(script_text, script->get_path().get_base_dir(), base, &options, result.hint); if (options.size() > 0) { result.prefix = _filter_completion_candidates(p_request.column, current_line, options, result.suggestions); } return result; #else return Result(); #endif } String CodeCompletionService::_get_text_for_completion(const Request& p_request, String& r_text) { Vector<String> substrings = r_text.replace("\r","").split("\n"); r_text.clear(); int len = substrings.size(); for (int i=0;i<len;i++) { if (i==p_request.row) { r_text+=substrings[i].substr(0,p_request.column); r_text+=String::chr(0xFFFF); //not unicode, represents the cursor r_text+=substrings[i].substr(p_request.column,substrings[i].size()); } else { r_text+=substrings[i]; } if (i!=len-1) r_text+="\n"; } return substrings[p_request.row]; } Node* CodeCompletionService::_find_node_for_script(Node* p_base, Node* p_current, const Ref<Script>& p_script) { if (p_current->get_owner()!=p_base && p_base!=p_current) return NULL; Ref<Script> c = p_current->get_script(); if (c==p_script) return p_current; for(int i=0;i<p_current->get_child_count();i++) { Node *found = _find_node_for_script(p_base,p_current->get_child(i),p_script); if (found) return found; } return NULL; } String CodeCompletionService::_filter_completion_candidates(int p_col, const String& p_line, const List<String>& p_options, Vector<String> &r_suggestions) { int cofs = CLAMP(p_col,0,p_line.length()); //look for keywords first bool inquote=false; int first_quote=-1; int c=cofs-1; while(c>=0) { if (p_line[c]=='"' || p_line[c]=='\'') { inquote=!inquote; if (first_quote==-1) first_quote=c; } c--; } String prefix; bool pre_keyword=false; bool cancel=false; if (!inquote && first_quote==cofs-1) { cancel=true; } if (inquote && first_quote!=-1) { prefix=p_line.substr(first_quote,cofs-first_quote); } else if (cofs>0 && p_line[cofs-1]==' ') { int kofs=cofs-1; String kw; while (kofs>=0 && p_line[kofs]==' ') kofs--; while(kofs>=0 && p_line[kofs]>32 && _is_completable(p_line[kofs])) { kw=String::chr(p_line[kofs])+kw; kofs--; } pre_keyword=type_keywords.find(kw) || language_keywords.find(kw); } else { while(cofs>0 && p_line[cofs-1]>32 && _is_completable(p_line[cofs-1])) { prefix=String::chr(p_line[cofs-1])+prefix; if (p_line[cofs-1]=='\'' || p_line[cofs-1]=='"') break; cofs--; } } if (cancel || (!pre_keyword && prefix=="" && (cofs==0 || !completion_prefixes.has(String::chr(p_line[cofs-1]))))) return String(); for (const List<String>::Element *E=p_options.front();E;E=E->next()) { if (E->get().begins_with(prefix)) { r_suggestions.push_back(E->get()); } } return prefix; } CodeCompletionService::CodeCompletionService() { completion_prefixes.insert("."); completion_prefixes.insert(","); completion_prefixes.insert("("); type_keywords.push_back("Vector2"); type_keywords.push_back("Vector3"); type_keywords.push_back("Plane"); type_keywords.push_back("Quat"); type_keywords.push_back("AABB"); type_keywords.push_back("Matrix3"); type_keywords.push_back("Transform"); type_keywords.push_back("Color"); type_keywords.push_back("Image"); type_keywords.push_back("InputEvent"); ObjectTypeDB::get_type_list(&type_keywords); #ifdef GDSCRIPT_ENABLED GDScriptLanguage::get_singleton()->get_reserved_words(&language_keywords); #endif } CodeCompletionService::~CodeCompletionService() { } <commit_msg>Fix wrong return<commit_after>/* code_completion_service.cpp */ #include "code_completion_service.h" #include "io/resource_loader.h" #include "globals.h" #ifdef GDSCRIPT_ENABLED #include "modules/gdscript/gd_script.h" #endif static bool _is_symbol(CharType c) { return c!='_' && ((c>='!' && c<='/') || (c>=':' && c<='@') || (c>='[' && c<='`') || (c>='{' && c<='~') || c=='\t'); } static bool _is_completable(CharType c) { return !_is_symbol(c) || c=='"' || c=='\''; } CodeCompletionService::Result CodeCompletionService::obtain_suggestions(const Request& p_request) { #ifdef GDSCRIPT_ENABLED Result result(true); String path = Globals::get_singleton()->localize_path(p_request.script_path); if (path == "res://" || !path.begins_with("res://")) return Result(); Ref<Script> script = ResourceLoader::load(path); if (!script.is_valid() || !script->cast_to<GDScript>()) return Result(); String script_text = p_request.script_text; if (script_text.empty()) { ERR_FAIL_COND_V(!script->has_source_code(), Result()); script_text = script->get_source_code(); } Node *base = get_tree()->get_edited_scene_root(); if (base) { base = _find_node_for_script(base,base,script); } String current_line = _get_text_for_completion(p_request, script_text); List<String> options; script->get_language()->complete_code(script_text, script->get_path().get_base_dir(), base, &options, result.hint); if (options.size() > 0) { result.prefix = _filter_completion_candidates(p_request.column, current_line, options, result.suggestions); } return result; #else return Result(); #endif } String CodeCompletionService::_get_text_for_completion(const Request& p_request, String& r_text) { Vector<String> substrings = r_text.replace("\r","").split("\n"); r_text.clear(); int len = substrings.size(); for (int i=0;i<len;i++) { if (i==p_request.row) { r_text+=substrings[i].substr(0,p_request.column); r_text+=String::chr(0xFFFF); //not unicode, represents the cursor r_text+=substrings[i].substr(p_request.column,substrings[i].size()); } else { r_text+=substrings[i]; } if (i!=len-1) r_text+="\n"; } return substrings[p_request.row]; } Node* CodeCompletionService::_find_node_for_script(Node* p_base, Node* p_current, const Ref<Script>& p_script) { if (p_current->get_owner()!=p_base && p_base!=p_current) return NULL; Ref<Script> c = p_current->get_script(); if (c==p_script) return p_current; for(int i=0;i<p_current->get_child_count();i++) { Node *found = _find_node_for_script(p_base,p_current->get_child(i),p_script); if (found) return found; } return NULL; } String CodeCompletionService::_filter_completion_candidates(int p_col, const String& p_line, const List<String>& p_options, Vector<String> &r_suggestions) { int cofs = CLAMP(p_col,0,p_line.length()); //look for keywords first bool inquote=false; int first_quote=-1; int c=cofs-1; while(c>=0) { if (p_line[c]=='"' || p_line[c]=='\'') { inquote=!inquote; if (first_quote==-1) first_quote=c; } c--; } String prefix; bool pre_keyword=false; bool cancel=false; if (!inquote && first_quote==cofs-1) { cancel=true; } if (inquote && first_quote!=-1) { prefix=p_line.substr(first_quote,cofs-first_quote); } else if (cofs>0 && p_line[cofs-1]==' ') { int kofs=cofs-1; String kw; while (kofs>=0 && p_line[kofs]==' ') kofs--; while(kofs>=0 && p_line[kofs]>32 && _is_completable(p_line[kofs])) { kw=String::chr(p_line[kofs])+kw; kofs--; } pre_keyword=type_keywords.find(kw) || language_keywords.find(kw); } else { while(cofs>0 && p_line[cofs-1]>32 && _is_completable(p_line[cofs-1])) { prefix=String::chr(p_line[cofs-1])+prefix; if (p_line[cofs-1]=='\'' || p_line[cofs-1]=='"') break; cofs--; } } if (cancel || (!pre_keyword && prefix=="" && (cofs==0 || !completion_prefixes.has(String::chr(p_line[cofs-1]))))) return String(); for (const List<String>::Element *E=p_options.front();E;E=E->next()) { if (E->get().begins_with(prefix)) { r_suggestions.push_back(E->get()); } } return prefix; } CodeCompletionService::CodeCompletionService() { completion_prefixes.insert("."); completion_prefixes.insert(","); completion_prefixes.insert("("); type_keywords.push_back("Vector2"); type_keywords.push_back("Vector3"); type_keywords.push_back("Plane"); type_keywords.push_back("Quat"); type_keywords.push_back("AABB"); type_keywords.push_back("Matrix3"); type_keywords.push_back("Transform"); type_keywords.push_back("Color"); type_keywords.push_back("Image"); type_keywords.push_back("InputEvent"); ObjectTypeDB::get_type_list(&type_keywords); #ifdef GDSCRIPT_ENABLED GDScriptLanguage::get_singleton()->get_reserved_words(&language_keywords); #endif } CodeCompletionService::~CodeCompletionService() { } <|endoftext|>
<commit_before>// you can use includes, for example: #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; int findMin(vector<int> &P) { int minP(P[0]); for(unsigned int i=0; i<P.size(); ++i) { if( P[i]<minP ) minP = P[i]; } return minP; } int findMax(vector<int> &Q) { int maxQ(Q[0]); for(unsigned int i=0; i<Q.size(); ++i) { if( Q[i]>maxQ ) maxQ = Q[i]; } return maxQ; } bool isPrime(int number) { int a = floor(sqrt(number)); for(unsigned int i=a; i>1; --i) { if( number%i==0 ) return false; } return true; } vector<int> findPrimes(int first, int last) { vector<int> primes; for(unsigned int i=first; i<=last; ++i) { if( isPrime(i) ) { primes.push_back(i); // cout << i << endl; } } return primes; } vector<int> findSemiPrimes(vector<int> &primes, int first, int last) { vector<int> semiPrimes; for(unsigned int i=0; i<primes.size(); ++i) { for(unsigned int j=0; j<primes.size(); ++j) { if( primes[i]<=primes[j] ) { int semiPrime = primes[i]*primes[j]; if( semiPrime>=first && semiPrime<=last ) { semiPrimes.push_back( semiPrime ); // cout << semiPrime << endl; } } } } return semiPrimes; } int countSemiPrimes(vector<int> &semiPrimes, int first, int last) { int count(0); for(unsigned int i=0; i<semiPrimes.size(); ++i) { // cout << semiPrimes[i] << endl; if( semiPrimes[i]>=first && semiPrimes[i]<=last ) count++; } return count; } vector<int> solution(int N, vector<int> &P, vector<int> &Q) { // write your code in C++11 int minP = findMin(P); int maxQ = findMax(Q); // cout << minP << " " << maxQ << endl; vector<int> primes = findPrimes(2,maxQ); // cout << endl; vector<int> semiPrimes = findSemiPrimes(primes,minP,maxQ); vector<int> counts(P.size(),0); for(unsigned int i=0; i<P.size(); ++i) { counts[i] = countSemiPrimes(semiPrimes,P[i],Q[i]); } return counts; } <commit_msg>Update solution.cpp<commit_after>// you can use includes, for example: #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; // Correctness 100% // Performance 20% // Task score 55% // Detected time complexity: // O(M * N ** (3/2)) or O(N * log(log(N)) + M * N) or O(M * N**3) int findMin(vector<int> &P) { int minP(P[0]); for(unsigned int i=0; i<P.size(); ++i) { if( P[i]<minP ) minP = P[i]; } return minP; } int findMax(vector<int> &Q) { int maxQ(Q[0]); for(unsigned int i=0; i<Q.size(); ++i) { if( Q[i]>maxQ ) maxQ = Q[i]; } return maxQ; } bool isPrime(int number) { int a = floor(sqrt(number)); for(unsigned int i=a; i>1; --i) { if( number%i==0 ) return false; } return true; } vector<int> findPrimes(int first, int last) { vector<int> primes; for(unsigned int i=first; i<=last; ++i) { if( isPrime(i) ) { primes.push_back(i); // cout << i << endl; } } return primes; } vector<int> findSemiPrimes(vector<int> &primes, int first, int last) { vector<int> semiPrimes; for(unsigned int i=0; i<primes.size(); ++i) { for(unsigned int j=0; j<primes.size(); ++j) { if( primes[i]<=primes[j] ) { int semiPrime = primes[i]*primes[j]; if( semiPrime>=first && semiPrime<=last ) { semiPrimes.push_back( semiPrime ); // cout << semiPrime << endl; } } } } return semiPrimes; } int countSemiPrimes(vector<int> &semiPrimes, int first, int last) { int count(0); for(unsigned int i=0; i<semiPrimes.size(); ++i) { // cout << semiPrimes[i] << endl; if( semiPrimes[i]>=first && semiPrimes[i]<=last ) count++; } return count; } vector<int> solution(int N, vector<int> &P, vector<int> &Q) { // write your code in C++11 int minP = findMin(P); int maxQ = findMax(Q); // cout << minP << " " << maxQ << endl; vector<int> primes = findPrimes(2,maxQ); // cout << endl; vector<int> semiPrimes = findSemiPrimes(primes,minP,maxQ); vector<int> counts(P.size(),0); for(unsigned int i=0; i<P.size(); ++i) { counts[i] = countSemiPrimes(semiPrimes,P[i],Q[i]); } return counts; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #ifndef _Stroika_Foundation_Streams_OutputStream_inl_ #define _Stroika_Foundation_Streams_OutputStream_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include <mutex> #include "../Debug/Assertions.h" #include "../Memory/BLOB.h" namespace Stroika { namespace Foundation { namespace Streams { /* ******************************************************************************** **************************** OutputStream<ELEMENT_TYPE> ************************ ******************************************************************************** */ template <typename ELEMENT_TYPE> inline OutputStream<ELEMENT_TYPE>::OutputStream (const _SharedIRep& rep) : inherited (rep) { } template <typename ELEMENT_TYPE> inline OutputStream<ELEMENT_TYPE>::OutputStream (nullptr_t) : inherited (nullptr) { } template <typename ELEMENT_TYPE> inline auto OutputStream<ELEMENT_TYPE>::_GetRep () const -> _SharedIRep { return dynamic_pointer_cast<_IRep> (inherited::_GetRep ()); } template <typename ELEMENT_TYPE> inline OutputStream<ELEMENT_TYPE> OutputStream<ELEMENT_TYPE>::Synchronized () const { struct SyncRep_ : public OutputStream<ELEMENT_TYPE>::_IRep { public: SyncRep_ (const OutputStream<ELEMENT_TYPE>& realIn) : OutputStream<ELEMENT_TYPE>::_IRep () , fCriticalSection_ () , fRealIn_ (realIn) { } virtual bool IsSeekable () const override { using Execution::make_unique_lock; // @todo implement 'offset' support #if qCompilerAndStdLib_make_unique_lock_IsSlow MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_); #else auto critSec { make_unique_lock (fCriticalSection_) }; #endif return fRealIn_.IsSeekable (); } virtual SeekOffsetType GetWriteOffset () const override { using Execution::make_unique_lock; // @todo implement 'offset' support #if qCompilerAndStdLib_make_unique_lock_IsSlow MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_); #else auto critSec { make_unique_lock (fCriticalSection_) }; #endif return fRealIn_.GetWriteOffset (); } virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override { using Execution::make_unique_lock; // @todo implement 'offset' support #if qCompilerAndStdLib_make_unique_lock_IsSlow MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_); #else auto critSec { make_unique_lock (fCriticalSection_) }; #endif return fRealIn_.SeekWrite (whence, offset); } virtual size_t Write (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override { using Execution::make_unique_lock; // @todo implement 'offset' support #if qCompilerAndStdLib_make_unique_lock_IsSlow MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_); #else auto critSec { make_unique_lock (fCriticalSection_) }; #endif return fRealIn_.Write (intoStart, intoEnd); } private: mutable mutex fCriticalSection_; OutputStream<ELEMENT_TYPE> fRealIn_; }; return OutputStream<ELEMENT_TYPE> (make_shared<SyncRep_> (*this)); } template <typename ELEMENT_TYPE> inline SeekOffsetType OutputStream<ELEMENT_TYPE>::GetOffset () const { return _GetRep ()->GetWriteOffset (); } template <typename ELEMENT_TYPE> SeekOffsetType OutputStream<ELEMENT_TYPE>::GetOffsetToEndOfStream () const { SeekOffsetType savedReadFrom = GetOffset (); SeekOffsetType size = Seek (Whence::eFromEnd, 0); Seek (Whence::eFromStart, savedReadFrom); Assert (size >= savedReadFrom); size -= savedReadFrom; return size; } template <typename ELEMENT_TYPE> inline SeekOffsetType OutputStream<ELEMENT_TYPE>::Seek (SignedSeekOffsetType offset) const { return _GetRep ()->SeekWrite (Whence::eFromStart, offset); } template <typename ELEMENT_TYPE> inline SeekOffsetType OutputStream<ELEMENT_TYPE>::Seek (Whence whence, SignedSeekOffsetType offset) const { return _GetRep ()->SeekWrite (whence, offset); } template <typename ELEMENT_TYPE> inline void OutputStream<ELEMENT_TYPE>::Write (const ElementType* start, const ElementType* end) const { Require (start <= end); Require (start != nullptr or start == end); Require (end != nullptr or start == end); if (start != end) { _GetRep ()->Write (start, end); } } template <typename ELEMENT_TYPE> template <typename TEST_TYPE, typename ENABLE_IF_TEST> inline void OutputStream<ELEMENT_TYPE>::Write (const Memory::BLOB& blob) const { Write (blob.begin (), blob.end ()); } template <typename ELEMENT_TYPE> template <typename TEST_TYPE, typename ENABLE_IF_TEST> inline void OutputStream<ELEMENT_TYPE>::Write (const wchar_t* cStr) const { Write (cStr, cStr + ::wcslen (cStr)); } template <typename ELEMENT_TYPE> inline void OutputStream<ELEMENT_TYPE>::Flush () const { _GetRep ()->Flush (); } template <> template <> inline const OutputStream<Characters::Character>& OutputStream<Characters::Character>::operator<< (const Characters::String& write2TextStream) const { Write (write2TextStream); return *this; } template <> template <> inline const OutputStream<Characters::Character>& OutputStream<Characters::Character>::operator<< (const wchar_t* write2TextStream) const { Write (write2TextStream); return *this; } } } } #endif /*_Stroika_Foundation_Streams_OutputStream_inl_*/ <commit_msg>#include String.h in Streams/OutputStream.inl to avoid gcc compile failure. Would be nice to detangle these dependencies more<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #ifndef _Stroika_Foundation_Streams_OutputStream_inl_ #define _Stroika_Foundation_Streams_OutputStream_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include <mutex> #include "../Characters/String.h" #include "../Debug/Assertions.h" #include "../Memory/BLOB.h" namespace Stroika { namespace Foundation { namespace Streams { /* ******************************************************************************** **************************** OutputStream<ELEMENT_TYPE> ************************ ******************************************************************************** */ template <typename ELEMENT_TYPE> inline OutputStream<ELEMENT_TYPE>::OutputStream (const _SharedIRep& rep) : inherited (rep) { } template <typename ELEMENT_TYPE> inline OutputStream<ELEMENT_TYPE>::OutputStream (nullptr_t) : inherited (nullptr) { } template <typename ELEMENT_TYPE> inline auto OutputStream<ELEMENT_TYPE>::_GetRep () const -> _SharedIRep { return dynamic_pointer_cast<_IRep> (inherited::_GetRep ()); } template <typename ELEMENT_TYPE> inline OutputStream<ELEMENT_TYPE> OutputStream<ELEMENT_TYPE>::Synchronized () const { struct SyncRep_ : public OutputStream<ELEMENT_TYPE>::_IRep { public: SyncRep_ (const OutputStream<ELEMENT_TYPE>& realIn) : OutputStream<ELEMENT_TYPE>::_IRep () , fCriticalSection_ () , fRealIn_ (realIn) { } virtual bool IsSeekable () const override { using Execution::make_unique_lock; // @todo implement 'offset' support #if qCompilerAndStdLib_make_unique_lock_IsSlow MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_); #else auto critSec { make_unique_lock (fCriticalSection_) }; #endif return fRealIn_.IsSeekable (); } virtual SeekOffsetType GetWriteOffset () const override { using Execution::make_unique_lock; // @todo implement 'offset' support #if qCompilerAndStdLib_make_unique_lock_IsSlow MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_); #else auto critSec { make_unique_lock (fCriticalSection_) }; #endif return fRealIn_.GetWriteOffset (); } virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override { using Execution::make_unique_lock; // @todo implement 'offset' support #if qCompilerAndStdLib_make_unique_lock_IsSlow MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_); #else auto critSec { make_unique_lock (fCriticalSection_) }; #endif return fRealIn_.SeekWrite (whence, offset); } virtual size_t Write (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override { using Execution::make_unique_lock; // @todo implement 'offset' support #if qCompilerAndStdLib_make_unique_lock_IsSlow MACRO_LOCK_GUARD_CONTEXT (fCriticalSection_); #else auto critSec { make_unique_lock (fCriticalSection_) }; #endif return fRealIn_.Write (intoStart, intoEnd); } private: mutable mutex fCriticalSection_; OutputStream<ELEMENT_TYPE> fRealIn_; }; return OutputStream<ELEMENT_TYPE> (make_shared<SyncRep_> (*this)); } template <typename ELEMENT_TYPE> inline SeekOffsetType OutputStream<ELEMENT_TYPE>::GetOffset () const { return _GetRep ()->GetWriteOffset (); } template <typename ELEMENT_TYPE> SeekOffsetType OutputStream<ELEMENT_TYPE>::GetOffsetToEndOfStream () const { SeekOffsetType savedReadFrom = GetOffset (); SeekOffsetType size = Seek (Whence::eFromEnd, 0); Seek (Whence::eFromStart, savedReadFrom); Assert (size >= savedReadFrom); size -= savedReadFrom; return size; } template <typename ELEMENT_TYPE> inline SeekOffsetType OutputStream<ELEMENT_TYPE>::Seek (SignedSeekOffsetType offset) const { return _GetRep ()->SeekWrite (Whence::eFromStart, offset); } template <typename ELEMENT_TYPE> inline SeekOffsetType OutputStream<ELEMENT_TYPE>::Seek (Whence whence, SignedSeekOffsetType offset) const { return _GetRep ()->SeekWrite (whence, offset); } template <typename ELEMENT_TYPE> inline void OutputStream<ELEMENT_TYPE>::Write (const ElementType* start, const ElementType* end) const { Require (start <= end); Require (start != nullptr or start == end); Require (end != nullptr or start == end); if (start != end) { _GetRep ()->Write (start, end); } } template <typename ELEMENT_TYPE> template <typename TEST_TYPE, typename ENABLE_IF_TEST> inline void OutputStream<ELEMENT_TYPE>::Write (const Memory::BLOB& blob) const { Write (blob.begin (), blob.end ()); } template <typename ELEMENT_TYPE> template <typename TEST_TYPE, typename ENABLE_IF_TEST> inline void OutputStream<ELEMENT_TYPE>::Write (const wchar_t* cStr) const { Write (cStr, cStr + ::wcslen (cStr)); } template <typename ELEMENT_TYPE> inline void OutputStream<ELEMENT_TYPE>::Flush () const { _GetRep ()->Flush (); } template <> template <> inline const OutputStream<Characters::Character>& OutputStream<Characters::Character>::operator<< (const Characters::String& write2TextStream) const { Write (write2TextStream); return *this; } template <> template <> inline const OutputStream<Characters::Character>& OutputStream<Characters::Character>::operator<< (const wchar_t* write2TextStream) const { Write (write2TextStream); return *this; } } } } #endif /*_Stroika_Foundation_Streams_OutputStream_inl_*/ <|endoftext|>
<commit_before>#include <tiramisu/tiramisu.h> #include <string.h> #include "baryon_wrapper.h" using namespace tiramisu; /* Implementation log: - Sum: 7h 35mn. */ /* * The goal is to generate code that implements the reference. * baryon_ref.cpp */ void generate_function(std::string name) { tiramisu::init(name); var n("n", 0, Nsrc), iCprime("iCprime", 0, Nc), iSprime("iSprime", 0, Ns), jCprime("jCprime", 0, Nc), jSprime("jSprime", 0, Ns), kCprime("kCprime", 0, Nc), kSprime("kSprime", 0, Ns), lCprime("lCprime", 0, Nc), lSprime("lSprime", 0, Ns), x("x", 0, Vsnk), x2("x2", 0, Vsnk), t("t", 0, Lt), wnum("wnum", 0, Nw), y("y", 0, Vsrc), tri("tri", 0, Nq); input Blocal_r("Blocal_r", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, p_float64); input Blocal_i("Blocal_i", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, p_float64); input prop_r("prop_r", {tri, iCprime, iSprime, jCprime, jSprime, x, t, y}, p_float64); input prop_i("prop_i", {tri, iCprime, iSprime, jCprime, jSprime, x, t, y}, p_float64); input weights("weights", {wnum}, p_float64); input psi_r("psi_r", {n, y}, p_float64); input psi_i("psi_i", {n, y}, p_float64); input color_weights("color_weights", {wnum, tri}, p_int32); input spin_weights("spin_weights", {wnum, tri}, p_int32); computation Blocal_r_init("Blocal_r_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, expr((double) 0)); computation Blocal_i_init("Blocal_i_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, expr((double) 0)); computation iC("iC", {wnum}, color_weights(wnum, 0)); computation iS("iS", {wnum}, spin_weights(wnum, 0)); computation jC("jC", {wnum}, color_weights(wnum, 1)); computation jS("jS", {wnum}, spin_weights(wnum, 1)); computation kC("kC", {wnum}, color_weights(wnum, 2)); computation kS("kS", {wnum}, spin_weights(wnum, 2)); computation Blocal_r_update("Blocal_r_update", {wnum, n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t, y}, p_float64); Blocal_r_update.set_expression(Blocal_r_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t) + weights(wnum) * psi_r(n, y) * (prop_r(0, iCprime, iSprime, iC(wnum), iS(wnum), x, t, y) * prop_r(2, kCprime, kSprime, kC(wnum), kS(wnum), x, t, y) - prop_r(0, kCprime, kSprime, iC(wnum), iS(wnum), x, t, y) * prop_r(2, iCprime, iSprime, kC(wnum), kS(wnum), x, t, y)) * prop_r(1, jCprime, jSprime, jC(wnum), jS(wnum), x, t, y)); computation Blocal_i_update("Blocal_i_update", {wnum, n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t, y}, p_float64); Blocal_i_update.set_expression(Blocal_i_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t) + weights(wnum) * psi_i(n, y) * (prop_i(0, iCprime, iSprime, iC(wnum), iS(wnum), x, t, y) * prop_i(2, kCprime, kSprime, kC(wnum), kS(wnum), x, t, y) - prop_i(0, kCprime, kSprime, iC(wnum), iS(wnum), x, t, y) * prop_i(2, iCprime, iSprime, kC(wnum), kS(wnum), x, t, y)) * prop_i(1, jCprime, jSprime, jC(wnum), jS(wnum), x, t, y)); computation Q_r_init("Q_r_init", {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}, expr((double) 0)); computation Q_i_init("Q_i_init", {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}, expr((double) 0)); computation Bsingle_r_init("Bsingle_r_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t}, expr((double) 0)); computation Bsingle_i_init("Bsingle_i_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t}, expr((double) 0)); computation iC2("iC2", {wnum}, color_weights(wnum, 0)); computation iS2("iS2", {wnum}, spin_weights(wnum, 0)); computation jC2("jC2", {wnum}, color_weights(wnum, 1)); computation jS2("jS2", {wnum}, spin_weights(wnum, 1)); computation kC2("kC2", {wnum}, color_weights(wnum, 2)); computation kS2("kS2", {wnum}, spin_weights(wnum, 2)); computation Q_r_update("Q_r_update", {wnum, n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}, Q_r_init(n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y) + weights(wnum)); //* psi_r(n, y) * (prop_r(0, iCprime, iSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_r(2, kCprime, kSprime, kC2(wnum), kS2(wnum), x, t, y) - prop_r(0, kCprime, kSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_r(2, iCprime, iSprime, kC2(wnum), kS2(wnum), x, t, y)))); Q_r_update.add_predicate((jCprime == jC2(wnum)) && (jSprime == jS2(wnum))); computation Q_i_update("Q_i_update", {wnum, n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}, Q_i_init(n, iCprime, iSprime, kCprime, kSprime, jC2(wnum), jS2(wnum), x, t, y) + weights(wnum)); //* psi_i(n, y) * (prop_i(0, iCprime, iSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_i(2, kCprime, kSprime, kC2(wnum), kS2(wnum), x, t, y) - prop_i(0, kCprime, kSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_i(2, iCprime, iSprime, kC2(wnum), kS2(wnum), x, t, y))); computation Bsingle_r_update("Bsingle_r_update", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, lCprime, lSprime, x, x2, t, y}, Bsingle_r_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t) + Q_r_update(0, n, iCprime, iSprime, kCprime, kSprime, lCprime, lSprime, x, t, y)); // * prop_r(1, jCprime, jSprime, lCprime, lSprime, x2, t, y)); computation Bsingle_i_update("Bsingle_i_update", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, lCprime, lSprime, x, x2, t, y}, Bsingle_i_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t) + Q_i_update(0, n, iCprime, iSprime, kCprime, kSprime, lCprime, lSprime, x, t, y)); // * prop_i(1, jCprime, jSprime, lCprime, lSprime, x2, t, y)); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- Blocal_r_init.then(Blocal_i_init, t) .then(Q_r_init, computation::root) .then(Q_i_init, y) .then(Bsingle_r_init, computation::root) .then(Bsingle_i_init, t) .then(iC, computation::root) .then(iS, wnum) .then(jC, wnum) .then(jS, wnum) .then(kC, wnum) .then(kS, wnum) .then(Blocal_r_update, wnum) .then(Blocal_i_update, y) .then(iC2, computation::root) .then(iS2, wnum) .then(jC2, wnum) .then(jS2, wnum) .then(kC2, wnum) .then(kS2, wnum) .then(Q_r_update, wnum) .then(Q_i_update, y) .then(Bsingle_r_update, computation::root) .then(Bsingle_i_update, y); //Blocal_r_update.tag_parallel_level(n); Blocal_r_update.vectorize(t, Lt); //Blocal_r_update.unroll(y, Vsrc); //Blocal_r_update.unroll(x, Vsnk); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer buf_Blocal_r("buf_Blocal_r", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt}, p_float64, a_output); buffer buf_Blocal_i("buf_Blocal_i", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt}, p_float64, a_output); buffer buf_Q_r("buf_Q_r", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt, Vsnk}, p_float64, a_temporary); buffer buf_Q_i("buf_Q_i", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt, Vsnk}, p_float64, a_temporary); buffer buf_Bsingle_r("buf_Bsingle_r", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Vsnk, Lt}, p_float64, a_output); buffer buf_Bsingle_i("buf_Bsingle_i", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Vsnk, Lt}, p_float64, a_output); Blocal_r.store_in(&buf_Blocal_r); Blocal_i.store_in(&buf_Blocal_i); Blocal_r_init.store_in(&buf_Blocal_r); Blocal_i_init.store_in(&buf_Blocal_i); Blocal_r_update.store_in(&buf_Blocal_r, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}); Blocal_i_update.store_in(&buf_Blocal_i, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}); Q_r_init.store_in(&buf_Q_r); Q_i_init.store_in(&buf_Q_i); Q_r_update.store_in(&buf_Q_r, {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}); Q_i_update.store_in(&buf_Q_i, {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}); Bsingle_r_init.store_in(&buf_Bsingle_r); Bsingle_i_init.store_in(&buf_Bsingle_i); Bsingle_r_update.store_in(&buf_Bsingle_r, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t}); Bsingle_i_update.store_in(&buf_Bsingle_i, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t}); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- tiramisu::codegen({&buf_Blocal_r, &buf_Blocal_i, prop_r.get_buffer(), prop_i.get_buffer(), weights.get_buffer(), psi_r.get_buffer(), psi_i.get_buffer(), color_weights.get_buffer(), spin_weights.get_buffer(), Bsingle_r_update.get_buffer(), Bsingle_i_update.get_buffer()}, "generated_baryon.o"); } int main(int argc, char **argv) { generate_function("tiramisu_generated_code"); return 0; } <commit_msg>dibaryon: add optimizations<commit_after>#include <tiramisu/tiramisu.h> #include <string.h> #include "baryon_wrapper.h" using namespace tiramisu; /* * The goal is to generate code that implements the reference. * baryon_ref.cpp */ void generate_function(std::string name) { tiramisu::init(name); var n("n", 0, Nsrc), iCprime("iCprime", 0, Nc), iSprime("iSprime", 0, Ns), jCprime("jCprime", 0, Nc), jSprime("jSprime", 0, Ns), kCprime("kCprime", 0, Nc), kSprime("kSprime", 0, Ns), lCprime("lCprime", 0, Nc), lSprime("lSprime", 0, Ns), x("x", 0, Vsnk), x2("x2", 0, Vsnk), t("t", 0, Lt), wnum("wnum", 0, Nw), y("y", 0, Vsrc), tri("tri", 0, Nq); input Blocal_r("Blocal_r", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, p_float64); input Blocal_i("Blocal_i", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, p_float64); input prop_r("prop_r", {tri, iCprime, iSprime, jCprime, jSprime, x, t, y}, p_float64); input prop_i("prop_i", {tri, iCprime, iSprime, jCprime, jSprime, x, t, y}, p_float64); input weights("weights", {wnum}, p_float64); input psi_r("psi_r", {n, y}, p_float64); input psi_i("psi_i", {n, y}, p_float64); input color_weights("color_weights", {wnum, tri}, p_int32); input spin_weights("spin_weights", {wnum, tri}, p_int32); computation Blocal_r_init("Blocal_r_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, expr((double) 0)); computation Blocal_i_init("Blocal_i_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}, expr((double) 0)); computation iC("iC", {wnum}, color_weights(wnum, 0)); computation iS("iS", {wnum}, spin_weights(wnum, 0)); computation jC("jC", {wnum}, color_weights(wnum, 1)); computation jS("jS", {wnum}, spin_weights(wnum, 1)); computation kC("kC", {wnum}, color_weights(wnum, 2)); computation kS("kS", {wnum}, spin_weights(wnum, 2)); computation Blocal_r_update("Blocal_r_update", {wnum, n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t, y}, p_float64); Blocal_r_update.set_expression(Blocal_r_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t) + weights(wnum) * psi_r(n, y) * (prop_r(0, iCprime, iSprime, iC(wnum), iS(wnum), x, t, y) * prop_r(2, kCprime, kSprime, kC(wnum), kS(wnum), x, t, y) - prop_r(0, kCprime, kSprime, iC(wnum), iS(wnum), x, t, y) * prop_r(2, iCprime, iSprime, kC(wnum), kS(wnum), x, t, y)) * prop_r(1, jCprime, jSprime, jC(wnum), jS(wnum), x, t, y)); computation Blocal_i_update("Blocal_i_update", {wnum, n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t, y}, p_float64); Blocal_i_update.set_expression(Blocal_i_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t) + weights(wnum) * psi_i(n, y) * (prop_i(0, iCprime, iSprime, iC(wnum), iS(wnum), x, t, y) * prop_i(2, kCprime, kSprime, kC(wnum), kS(wnum), x, t, y) - prop_i(0, kCprime, kSprime, iC(wnum), iS(wnum), x, t, y) * prop_i(2, iCprime, iSprime, kC(wnum), kS(wnum), x, t, y)) * prop_i(1, jCprime, jSprime, jC(wnum), jS(wnum), x, t, y)); computation Q_r_init("Q_r_init", {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}, expr((double) 0)); computation Q_i_init("Q_i_init", {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}, expr((double) 0)); computation Bsingle_r_init("Bsingle_r_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t}, expr((double) 0)); computation Bsingle_i_init("Bsingle_i_init", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t}, expr((double) 0)); computation iC2("iC2", {wnum}, color_weights(wnum, 0)); computation iS2("iS2", {wnum}, spin_weights(wnum, 0)); computation jC2("jC2", {wnum}, color_weights(wnum, 1)); computation jS2("jS2", {wnum}, spin_weights(wnum, 1)); computation kC2("kC2", {wnum}, color_weights(wnum, 2)); computation kS2("kS2", {wnum}, spin_weights(wnum, 2)); computation Q_r_update("Q_r_update", {wnum, n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}, Q_r_init(n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y) + weights(wnum)); //* psi_r(n, y) * (prop_r(0, iCprime, iSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_r(2, kCprime, kSprime, kC2(wnum), kS2(wnum), x, t, y) - prop_r(0, kCprime, kSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_r(2, iCprime, iSprime, kC2(wnum), kS2(wnum), x, t, y)))); Q_r_update.add_predicate((jCprime == jC2(wnum)) && (jSprime == jS2(wnum))); computation Q_i_update("Q_i_update", {wnum, n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}, Q_i_init(n, iCprime, iSprime, kCprime, kSprime, jC2(wnum), jS2(wnum), x, t, y) + weights(wnum)); //* psi_i(n, y) * (prop_i(0, iCprime, iSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_i(2, kCprime, kSprime, kC2(wnum), kS2(wnum), x, t, y) - prop_i(0, kCprime, kSprime, iC2(wnum), iS2(wnum), x, t, y) * prop_i(2, iCprime, iSprime, kC2(wnum), kS2(wnum), x, t, y))); Q_i_update.add_predicate((jCprime == jC2(wnum)) && (jSprime == jS2(wnum))); computation Bsingle_r_update("Bsingle_r_update", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, lCprime, lSprime, x, x2, t, y}, Bsingle_r_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t) + Q_r_update(0, n, iCprime, iSprime, kCprime, kSprime, lCprime, lSprime, x, t, y)); // * prop_r(1, jCprime, jSprime, lCprime, lSprime, x2, t, y)); computation Bsingle_i_update("Bsingle_i_update", {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, lCprime, lSprime, x, x2, t, y}, Bsingle_i_init(n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t) + Q_i_update(0, n, iCprime, iSprime, kCprime, kSprime, lCprime, lSprime, x, t, y)); // * prop_i(1, jCprime, jSprime, lCprime, lSprime, x2, t, y)); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- Blocal_r_init.then(Blocal_i_init, t) .then(Q_r_init, computation::root) .then(Q_i_init, y) .then(Bsingle_r_init, computation::root) .then(Bsingle_i_init, t) .then(iC, computation::root) .then(iS, wnum) .then(jC, wnum) .then(jS, wnum) .then(kC, wnum) .then(kS, wnum) .then(Blocal_r_update, wnum) .then(Blocal_i_update, y) .then(iC2, computation::root) .then(iS2, wnum) .then(jC2, wnum) .then(jS2, wnum) .then(kC2, wnum) .then(kS2, wnum) .then(Q_r_update, wnum) .then(Q_i_update, y) .then(Bsingle_r_update, computation::root) .then(Bsingle_i_update, y); //Blocal_r_update.tag_parallel_level(n); Blocal_r_init.vectorize(t, Lt); Blocal_r_update.vectorize(t, Lt); //Blocal_r_update.unroll(y, Vsrc); //Blocal_r_update.unroll(x, Vsnk); Q_r_init.vectorize(y, Vsrc); Bsingle_r_init.vectorize(t, Lt); Q_r_update.vectorize(y, Vsrc); //Bsingle_r_update.tag_parallel_level(n); Bsingle_r_update.vectorize(t, Lt); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer buf_Blocal_r("buf_Blocal_r", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt}, p_float64, a_output); buffer buf_Blocal_i("buf_Blocal_i", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt}, p_float64, a_output); buffer buf_Q_r("buf_Q_r", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt, Vsnk}, p_float64, a_temporary); buffer buf_Q_i("buf_Q_i", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Lt, Vsnk}, p_float64, a_temporary); buffer buf_Bsingle_r("buf_Bsingle_r", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Vsnk, Lt}, p_float64, a_output); buffer buf_Bsingle_i("buf_Bsingle_i", {Nsrc, Nc, Ns, Nc, Ns, Nc, Ns, Vsnk, Vsnk, Lt}, p_float64, a_output); Blocal_r.store_in(&buf_Blocal_r); Blocal_i.store_in(&buf_Blocal_i); Blocal_r_init.store_in(&buf_Blocal_r); Blocal_i_init.store_in(&buf_Blocal_i); Blocal_r_update.store_in(&buf_Blocal_r, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}); Blocal_i_update.store_in(&buf_Blocal_i, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, t}); Q_r_init.store_in(&buf_Q_r); Q_i_init.store_in(&buf_Q_i); Q_r_update.store_in(&buf_Q_r, {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}); Q_i_update.store_in(&buf_Q_i, {n, iCprime, iSprime, kCprime, kSprime, jCprime, jSprime, x, t, y}); Bsingle_r_init.store_in(&buf_Bsingle_r); Bsingle_i_init.store_in(&buf_Bsingle_i); Bsingle_r_update.store_in(&buf_Bsingle_r, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t}); Bsingle_i_update.store_in(&buf_Bsingle_i, {n, iCprime, iSprime, jCprime, jSprime, kCprime, kSprime, x, x2, t}); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- tiramisu::codegen({&buf_Blocal_r, &buf_Blocal_i, prop_r.get_buffer(), prop_i.get_buffer(), weights.get_buffer(), psi_r.get_buffer(), psi_i.get_buffer(), color_weights.get_buffer(), spin_weights.get_buffer(), Bsingle_r_update.get_buffer(), Bsingle_i_update.get_buffer()}, "generated_baryon.o"); } int main(int argc, char **argv) { generate_function("tiramisu_generated_code"); return 0; } <|endoftext|>
<commit_before>#include "catch.hpp" #include <type_traits> #include <compile_time.hpp> #include <string> namespace myspace { REGISTER_TYPE_BEGIN() REGISTER_TYPE(int) REGISTER_TYPE(float) REGISTER_TYPE(double) REGISTER_TYPE_END() } TEST_CASE("", "") { } <commit_msg>Add unit tests for the case of registering no types. modified: tests/test_compile_time1.cpp<commit_after>#include "catch.hpp" #include <type_traits> #include <compile_time.hpp> #include <string> namespace refl_space_1 { REGISTER_TYPE_BEGIN() REGISTER_TYPE_END() } TEST_CASE("No types registered", "[REGISTER_TYPE]") { constexpr auto range_len = metamusil::int_seq::length_v<refl_space_1::type_line_range>; constexpr auto compile_time_infos_len = metamusil::t_list::length_v< refl_space_1::instantiated_compile_time_infos>; constexpr auto type_len = metamusil::t_list::length_v<refl_space_1::type_universe>; REQUIRE(range_len == 0); REQUIRE(compile_time_infos_len == 0); REQUIRE(refl_space_1::type_name_array_holder::value == nullptr); REQUIRE(refl_space_1::type_info_array_holder::value == nullptr); REQUIRE(type_len == 0); } <|endoftext|>
<commit_before>#include "SDLApplication.h" #ifdef HX_MACOS #include <CoreFoundation/CoreFoundation.h> #endif namespace lime { AutoGCRoot* Application::callback = 0; double Application::GetTicks () { return SDL_GetTicks (); } SDLApplication::SDLApplication () { SDL_Init (SDL_INIT_VIDEO | SDL_INIT_TIMER); currentUpdate = 0; lastUpdate = 0; nextUpdate = 0; KeyEvent keyEvent; MouseEvent mouseEvent; RenderEvent renderEvent; TouchEvent touchEvent; UpdateEvent updateEvent; WindowEvent windowEvent; #ifdef HX_MACOS CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL (CFBundleGetMainBundle ()); char path[PATH_MAX]; if (CFURLGetFileSystemRepresentation (resourcesURL, TRUE, (UInt8 *)path, PATH_MAX)) { chdir (path); } CFRelease (resourcesURL); #endif } SDLApplication::~SDLApplication () { } int SDLApplication::Exec () { Init (); while (active) { Update (); } return Quit (); } void SDLApplication::HandleEvent (SDL_Event* event) { switch (event->type) { case SDL_USEREVENT: currentUpdate = SDL_GetTicks (); updateEvent.deltaTime = currentUpdate - lastUpdate; lastUpdate = currentUpdate; while (nextUpdate <= currentUpdate) { nextUpdate += framePeriod; } UpdateEvent::Dispatch (&updateEvent); RenderEvent::Dispatch (&renderEvent); break; case SDL_JOYAXISMOTION: case SDL_JOYBALLMOTION: case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: case SDL_JOYHATMOTION: case SDL_JOYDEVICEADDED: case SDL_JOYDEVICEREMOVED: //joy break; case SDL_KEYDOWN: case SDL_KEYUP: ProcessKeyEvent (event); break; case SDL_MOUSEMOTION: case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: case SDL_MOUSEWHEEL: ProcessMouseEvent (event); break; case SDL_WINDOWEVENT: switch (event->window.event) { case SDL_WINDOWEVENT_SHOWN: case SDL_WINDOWEVENT_HIDDEN: case SDL_WINDOWEVENT_FOCUS_GAINED: case SDL_WINDOWEVENT_FOCUS_LOST: case SDL_WINDOWEVENT_MOVED: ProcessWindowEvent (event); break; case SDL_WINDOWEVENT_EXPOSED: RenderEvent::Dispatch (&renderEvent); break; case SDL_WINDOWEVENT_SIZE_CHANGED: ProcessWindowEvent (event); RenderEvent::Dispatch (&renderEvent); break; case SDL_WINDOWEVENT_CLOSE: ProcessWindowEvent (event); active = false; break; } break; case SDL_QUIT: //quit active = false; break; } } void SDLApplication::Init() { framePeriod = 1000.0 / 60.0; active = true; lastUpdate = SDL_GetTicks (); nextUpdate = lastUpdate; } void SDLApplication::ProcessKeyEvent (SDL_Event* event) { if (KeyEvent::callback) { switch (event->type) { case SDL_KEYDOWN: keyEvent.type = KEY_DOWN; break; case SDL_KEYUP: keyEvent.type = KEY_UP; break; } keyEvent.keyCode = event->key.keysym.sym; KeyEvent::Dispatch (&keyEvent); } } void SDLApplication::ProcessMouseEvent (SDL_Event* event) { if (MouseEvent::callback) { switch (event->type) { case SDL_MOUSEMOTION: mouseEvent.type = MOUSE_MOVE; break; case SDL_MOUSEBUTTONDOWN: mouseEvent.type = MOUSE_DOWN; break; case SDL_MOUSEBUTTONUP: mouseEvent.type = MOUSE_UP; break; case SDL_MOUSEWHEEL: mouseEvent.type = MOUSE_WHEEL; break; } if (event->type != SDL_MOUSEWHEEL) { mouseEvent.button = event->button.button - 1; mouseEvent.x = event->button.x; mouseEvent.y = event->button.y; } else { mouseEvent.x = event->wheel.x; mouseEvent.y = event->wheel.y; } MouseEvent::Dispatch (&mouseEvent); } } void SDLApplication::ProcessTouchEvent (SDL_Event* event) { } void SDLApplication::ProcessWindowEvent (SDL_Event* event) { if (WindowEvent::callback) { switch (event->window.event) { case SDL_WINDOWEVENT_SHOWN: windowEvent.type = WINDOW_ACTIVATE; break; case SDL_WINDOWEVENT_CLOSE: windowEvent.type = WINDOW_CLOSE; break; case SDL_WINDOWEVENT_HIDDEN: windowEvent.type = WINDOW_DEACTIVATE; break; case SDL_WINDOWEVENT_FOCUS_GAINED: windowEvent.type = WINDOW_FOCUS_IN; break; case SDL_WINDOWEVENT_FOCUS_LOST: windowEvent.type = WINDOW_FOCUS_OUT; break; case SDL_WINDOWEVENT_MOVED: windowEvent.type = WINDOW_MOVE; windowEvent.x = event->window.data1; windowEvent.y = event->window.data2; break; case SDL_WINDOWEVENT_SIZE_CHANGED: windowEvent.type = WINDOW_RESIZE; windowEvent.width = event->window.data1; windowEvent.height = event->window.data2; break; } WindowEvent::Dispatch (&windowEvent); } } int SDLApplication::Quit () { windowEvent.type = WINDOW_DEACTIVATE; WindowEvent::Dispatch (&windowEvent); SDL_Quit (); return 0; } static SDL_TimerID timerID = 0; bool timerActive = false; bool firstTime = true; Uint32 OnTimer (Uint32 interval, void *) { SDL_Event event; SDL_UserEvent userevent; userevent.type = SDL_USEREVENT; userevent.code = 0; userevent.data1 = NULL; userevent.data2 = NULL; event.type = SDL_USEREVENT; event.user = userevent; timerActive = false; timerID = 0; SDL_PushEvent (&event); return 0; } bool SDLApplication::Update () { SDL_Event event; event.type = -1; if (active && (firstTime || SDL_WaitEvent (&event))) { firstTime = false; HandleEvent (&event); event.type = -1; if (!active) return active; if (SDL_PollEvent (&event)) { HandleEvent (&event); event.type = -1; } currentUpdate = SDL_GetTicks (); if (currentUpdate >= nextUpdate) { SDL_RemoveTimer (timerID); OnTimer (0, 0); } else if (!timerActive) { timerActive = true; timerID = SDL_AddTimer (nextUpdate - currentUpdate, OnTimer, 0); } } return active; } Application* CreateApplication () { return new SDLApplication (); } } #ifdef ANDROID int SDL_main (int argc, char *argv[]) { return 0; } #endif<commit_msg>Setting key modifier value in SDL key event<commit_after>#include "SDLApplication.h" #ifdef HX_MACOS #include <CoreFoundation/CoreFoundation.h> #endif namespace lime { AutoGCRoot* Application::callback = 0; double Application::GetTicks () { return SDL_GetTicks (); } SDLApplication::SDLApplication () { SDL_Init (SDL_INIT_VIDEO | SDL_INIT_TIMER); currentUpdate = 0; lastUpdate = 0; nextUpdate = 0; KeyEvent keyEvent; MouseEvent mouseEvent; RenderEvent renderEvent; TouchEvent touchEvent; UpdateEvent updateEvent; WindowEvent windowEvent; #ifdef HX_MACOS CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL (CFBundleGetMainBundle ()); char path[PATH_MAX]; if (CFURLGetFileSystemRepresentation (resourcesURL, TRUE, (UInt8 *)path, PATH_MAX)) { chdir (path); } CFRelease (resourcesURL); #endif } SDLApplication::~SDLApplication () { } int SDLApplication::Exec () { Init (); while (active) { Update (); } return Quit (); } void SDLApplication::HandleEvent (SDL_Event* event) { switch (event->type) { case SDL_USEREVENT: currentUpdate = SDL_GetTicks (); updateEvent.deltaTime = currentUpdate - lastUpdate; lastUpdate = currentUpdate; while (nextUpdate <= currentUpdate) { nextUpdate += framePeriod; } UpdateEvent::Dispatch (&updateEvent); RenderEvent::Dispatch (&renderEvent); break; case SDL_JOYAXISMOTION: case SDL_JOYBALLMOTION: case SDL_JOYBUTTONDOWN: case SDL_JOYBUTTONUP: case SDL_JOYHATMOTION: case SDL_JOYDEVICEADDED: case SDL_JOYDEVICEREMOVED: //joy break; case SDL_KEYDOWN: case SDL_KEYUP: ProcessKeyEvent (event); break; case SDL_MOUSEMOTION: case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: case SDL_MOUSEWHEEL: ProcessMouseEvent (event); break; case SDL_WINDOWEVENT: switch (event->window.event) { case SDL_WINDOWEVENT_SHOWN: case SDL_WINDOWEVENT_HIDDEN: case SDL_WINDOWEVENT_FOCUS_GAINED: case SDL_WINDOWEVENT_FOCUS_LOST: case SDL_WINDOWEVENT_MOVED: ProcessWindowEvent (event); break; case SDL_WINDOWEVENT_EXPOSED: RenderEvent::Dispatch (&renderEvent); break; case SDL_WINDOWEVENT_SIZE_CHANGED: ProcessWindowEvent (event); RenderEvent::Dispatch (&renderEvent); break; case SDL_WINDOWEVENT_CLOSE: ProcessWindowEvent (event); active = false; break; } break; case SDL_QUIT: //quit active = false; break; } } void SDLApplication::Init() { framePeriod = 1000.0 / 60.0; active = true; lastUpdate = SDL_GetTicks (); nextUpdate = lastUpdate; } void SDLApplication::ProcessKeyEvent (SDL_Event* event) { if (KeyEvent::callback) { switch (event->type) { case SDL_KEYDOWN: keyEvent.type = KEY_DOWN; break; case SDL_KEYUP: keyEvent.type = KEY_UP; break; } keyEvent.keyCode = event->key.keysym.sym; keyEvent.modifier = event->key.keysym.mod; KeyEvent::Dispatch (&keyEvent); } } void SDLApplication::ProcessMouseEvent (SDL_Event* event) { if (MouseEvent::callback) { switch (event->type) { case SDL_MOUSEMOTION: mouseEvent.type = MOUSE_MOVE; break; case SDL_MOUSEBUTTONDOWN: mouseEvent.type = MOUSE_DOWN; break; case SDL_MOUSEBUTTONUP: mouseEvent.type = MOUSE_UP; break; case SDL_MOUSEWHEEL: mouseEvent.type = MOUSE_WHEEL; break; } if (event->type != SDL_MOUSEWHEEL) { mouseEvent.button = event->button.button - 1; mouseEvent.x = event->button.x; mouseEvent.y = event->button.y; } else { mouseEvent.x = event->wheel.x; mouseEvent.y = event->wheel.y; } MouseEvent::Dispatch (&mouseEvent); } } void SDLApplication::ProcessTouchEvent (SDL_Event* event) { } void SDLApplication::ProcessWindowEvent (SDL_Event* event) { if (WindowEvent::callback) { switch (event->window.event) { case SDL_WINDOWEVENT_SHOWN: windowEvent.type = WINDOW_ACTIVATE; break; case SDL_WINDOWEVENT_CLOSE: windowEvent.type = WINDOW_CLOSE; break; case SDL_WINDOWEVENT_HIDDEN: windowEvent.type = WINDOW_DEACTIVATE; break; case SDL_WINDOWEVENT_FOCUS_GAINED: windowEvent.type = WINDOW_FOCUS_IN; break; case SDL_WINDOWEVENT_FOCUS_LOST: windowEvent.type = WINDOW_FOCUS_OUT; break; case SDL_WINDOWEVENT_MOVED: windowEvent.type = WINDOW_MOVE; windowEvent.x = event->window.data1; windowEvent.y = event->window.data2; break; case SDL_WINDOWEVENT_SIZE_CHANGED: windowEvent.type = WINDOW_RESIZE; windowEvent.width = event->window.data1; windowEvent.height = event->window.data2; break; } WindowEvent::Dispatch (&windowEvent); } } int SDLApplication::Quit () { windowEvent.type = WINDOW_DEACTIVATE; WindowEvent::Dispatch (&windowEvent); SDL_Quit (); return 0; } static SDL_TimerID timerID = 0; bool timerActive = false; bool firstTime = true; Uint32 OnTimer (Uint32 interval, void *) { SDL_Event event; SDL_UserEvent userevent; userevent.type = SDL_USEREVENT; userevent.code = 0; userevent.data1 = NULL; userevent.data2 = NULL; event.type = SDL_USEREVENT; event.user = userevent; timerActive = false; timerID = 0; SDL_PushEvent (&event); return 0; } bool SDLApplication::Update () { SDL_Event event; event.type = -1; if (active && (firstTime || SDL_WaitEvent (&event))) { firstTime = false; HandleEvent (&event); event.type = -1; if (!active) return active; if (SDL_PollEvent (&event)) { HandleEvent (&event); event.type = -1; } currentUpdate = SDL_GetTicks (); if (currentUpdate >= nextUpdate) { SDL_RemoveTimer (timerID); OnTimer (0, 0); } else if (!timerActive) { timerActive = true; timerID = SDL_AddTimer (nextUpdate - currentUpdate, OnTimer, 0); } } return active; } Application* CreateApplication () { return new SDLApplication (); } } #ifdef ANDROID int SDL_main (int argc, char *argv[]) { return 0; } #endif<|endoftext|>
<commit_before>#include <ros/ros.h> //#include <gazebo_msgs/ApplyJointEffort.h> #include <urdf/model.h> #include <urdf_interface/joint.h> #include <cstdlib> #include <sys/time.h> #include <time.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/Twist.h> #include <atlas_gazebo_msgs/RobotState.h> #include <lcm/lcm-cpp.hpp> #include <lcmtypes/drc_lcmtypes.hpp> #include <atlas_gazebo_msgs/ActuatorCmd.h> #include <std_msgs/Float64.h> double getTime_now() { struct timeval tv; gettimeofday (&tv,NULL); return (int64_t) tv.tv_sec*1000000+tv.tv_usec; } class ActuatorCmdHandler{ private: ros::Publisher actuator_cmd_pub; ros::Publisher body_twist_cmd_pub; ros::Publisher rot_scan_cmd_pub; ros::NodeHandle actuator_cmd_node; public: ActuatorCmdHandler(ros::NodeHandle &node): actuator_cmd_node(node) { actuator_cmd_pub = actuator_cmd_node.advertise<atlas_gazebo_msgs::ActuatorCmd>("actuator_cmd",10); body_twist_cmd_pub = actuator_cmd_node.advertise<geometry_msgs::Twist>("cmd_vel",10); rot_scan_cmd_pub = actuator_cmd_node.advertise<std_msgs::Float64>("/multisense_sl/set_spindle_speed",10); } ~ActuatorCmdHandler() {} void actuator_cmd_Callback(const lcm::ReceiveBuffer* rbuf,const std::string &channel,const drc::actuator_cmd_t* msg)//what is rbuf and channel here? { atlas_gazebo_msgs::ActuatorCmd actuator_cmd_msg; long t = msg->utime*1000; // from usec to nsec actuator_cmd_msg.header.stamp.fromNSec(t); actuator_cmd_msg.robot_name = msg->robot_name; for(std::vector<int>::size_type i=0;i!=msg->actuator_name.size();i++){//So varaibles in lcm message are all in vector type actuator_cmd_msg.actuator_name.push_back(msg->actuator_name.at(i)); actuator_cmd_msg.actuator_effort.push_back(msg->actuator_effort.at(i)); actuator_cmd_msg.effort_duration.push_back(msg->effort_duration.at(i)); } if(ros::ok()) { actuator_cmd_pub.publish(actuator_cmd_msg); //ros::spinOnce(); // required? } } void body_twist_cmd_Callback(const lcm::ReceiveBuffer* rbuf,const std::string &channel,const drc::twist_t* msg)//what is rbuf and channel here? { geometry_msgs::Twist body_twist_cmd_msg; //long t = msg->utime*1000; // from usec to nsec body_twist_cmd_msg.linear.x = msg->linear_velocity.x; body_twist_cmd_msg.linear.y = msg->linear_velocity.y; body_twist_cmd_msg.linear.z = msg->linear_velocity.z; body_twist_cmd_msg.angular.x = msg->angular_velocity.x; body_twist_cmd_msg.angular.y = msg->angular_velocity.y; body_twist_cmd_msg.angular.z = msg->angular_velocity.z; if(ros::ok()) { body_twist_cmd_pub.publish(body_twist_cmd_msg); //ros::spinOnce(); // required? } } void rot_scan_rate_cmd_Callback(const lcm::ReceiveBuffer* rbuf,const std::string &channel,const drc::twist_timed_t* msg) { std_msgs::Float64 rot_scan_cmd_msg; rot_scan_cmd_msg.data = msg->angular_velocity.x; if(ros::ok()) { rot_scan_cmd_pub.publish(rot_scan_cmd_msg); //ros::spinOnce(); // required? } } }; int main(int argc,char** argv) { ros::init(argc,argv,"actuator_cmd_publisher",ros::init_options::NoSigintHandler); ros::NodeHandle actuator_cmd_node; lcm::LCM listener; if(!listener.good()) return 1; ActuatorCmdHandler handlerObject(actuator_cmd_node); //LCM subscription listener.subscribe("ACTUATOR_CMDS",&ActuatorCmdHandler::actuator_cmd_Callback,&handlerObject); listener.subscribe("NAV_CMDS",&ActuatorCmdHandler::body_twist_cmd_Callback,&handlerObject); listener.subscribe("ROTATING_SCAN_RATE_CMD",&ActuatorCmdHandler::rot_scan_rate_cmd_Callback,&handlerObject); while(0 == listener.handle()); return 0; } // lcm::LCM talker; // if(!talker.good()) // return 1; // drc::actuator_cmd_t actuator_cmd; // actuator_cmd.timestamp = 0; // actuator_cmd.robot_name = "wheeled_atlas"; // actuator_cmd.num_joints = 2; // actuator_cmd.joint_name.push_back("LShoulderRoll"); // actuator_cmd.joint_name.push_back("RShoulderRoll"); // actuator_cmd.joint_effort.push_back(12.0); // actuator_cmd.joint_effort.push_back(-12.0); // actuator_cmd.duration.push_back(0.1); // actuator_cmd.duration.push_back(0.1); // // lcm::LCM listener; // if(!listener.good()) // return 1; // ActuatorCmdHandler handler; // listener.subscribe("ACTUATOR_CMDS",&ActuatorCmdHandler::actuator_cmd_Callback,&handler); // while(true) // { // talker.publish("ACTUATOR_CMDS",&actuator_cmd); // listener.handle(); // } // return 0; <commit_msg>minor changes for estop<commit_after>#include <ros/ros.h> //#include <gazebo_msgs/ApplyJointEffort.h> #include <urdf/model.h> #include <urdf_interface/joint.h> #include <cstdlib> #include <sys/time.h> #include <time.h> #include <geometry_msgs/Pose.h> #include <geometry_msgs/Twist.h> #include <atlas_gazebo_msgs/RobotState.h> #include <lcm/lcm-cpp.hpp> #include <lcmtypes/drc_lcmtypes.hpp> #include <atlas_gazebo_msgs/ActuatorCmd.h> #include <std_msgs/Float64.h> double getTime_now() { struct timeval tv; gettimeofday (&tv,NULL); return (int64_t) tv.tv_sec*1000000+tv.tv_usec; } class ActuatorCmdHandler{ private: ros::Publisher actuator_cmd_pub; ros::Publisher body_twist_cmd_pub; ros::Publisher rot_scan_cmd_pub; ros::Publisher gas_pedal_pub; ros::Publisher brake_pedal_pub; ros::NodeHandle actuator_cmd_node; public: ActuatorCmdHandler(ros::NodeHandle &node): actuator_cmd_node(node) { actuator_cmd_pub = actuator_cmd_node.advertise<atlas_gazebo_msgs::ActuatorCmd>("actuator_cmd",10); body_twist_cmd_pub = actuator_cmd_node.advertise<geometry_msgs::Twist>("cmd_vel",10); rot_scan_cmd_pub = actuator_cmd_node.advertise<std_msgs::Float64>("/multisense_sl/set_spindle_speed",10); gas_pedal_pub = actuator_cmd_node.advertise<std_msgs::Float64>("mit_golf_cart/gas_pedal/cmd", 1000); brake_pedal_pub = actuator_cmd_node.advertise<std_msgs::Float64>("mit_golf_cart/brake_pedal/cmd", 1000); } ~ActuatorCmdHandler() {} void actuator_cmd_Callback(const lcm::ReceiveBuffer* rbuf,const std::string &channel,const drc::actuator_cmd_t* msg)//what is rbuf and channel here? { atlas_gazebo_msgs::ActuatorCmd actuator_cmd_msg; long t = msg->utime*1000; // from usec to nsec actuator_cmd_msg.header.stamp.fromNSec(t); actuator_cmd_msg.robot_name = msg->robot_name; for(std::vector<int>::size_type i=0;i!=msg->actuator_name.size();i++){//So varaibles in lcm message are all in vector type actuator_cmd_msg.actuator_name.push_back(msg->actuator_name.at(i)); actuator_cmd_msg.actuator_effort.push_back(msg->actuator_effort.at(i)); actuator_cmd_msg.effort_duration.push_back(msg->effort_duration.at(i)); } if(ros::ok()) { actuator_cmd_pub.publish(actuator_cmd_msg); //ros::spinOnce(); // required? } } void body_twist_cmd_Callback(const lcm::ReceiveBuffer* rbuf,const std::string &channel,const drc::twist_t* msg)//what is rbuf and channel here? { geometry_msgs::Twist body_twist_cmd_msg; //long t = msg->utime*1000; // from usec to nsec body_twist_cmd_msg.linear.x = msg->linear_velocity.x; body_twist_cmd_msg.linear.y = msg->linear_velocity.y; body_twist_cmd_msg.linear.z = msg->linear_velocity.z; body_twist_cmd_msg.angular.x = msg->angular_velocity.x; body_twist_cmd_msg.angular.y = msg->angular_velocity.y; body_twist_cmd_msg.angular.z = msg->angular_velocity.z; if(ros::ok()) { body_twist_cmd_pub.publish(body_twist_cmd_msg); //ros::spinOnce(); // required? } } void estop_Callback(const lcm::ReceiveBuffer* rbuf,const std::string &channel,const drc::nav_goal_timed_t* msg)//what is rbuf and channel here? { if(ros::ok()){ std_msgs::Float64 msg; msg.data = 1.0; brake_pedal_pub.publish(msg); std_msgs::Float64 gasmsg; gasmsg.data = 0.0; gas_pedal_pub.publish(gasmsg); } } // Only here to Demo Estop: void rot_scan_rate_cmd_Callback(const lcm::ReceiveBuffer* rbuf,const std::string &channel,const drc::twist_timed_t* msg) { std_msgs::Float64 rot_scan_cmd_msg; rot_scan_cmd_msg.data = msg->angular_velocity.x; if(ros::ok()){ rot_scan_cmd_pub.publish(rot_scan_cmd_msg); } } }; int main(int argc,char** argv) { ros::init(argc,argv,"actuator_cmd_publisher",ros::init_options::NoSigintHandler); ros::NodeHandle actuator_cmd_node; lcm::LCM listener; if(!listener.good()) return 1; ActuatorCmdHandler handlerObject(actuator_cmd_node); //LCM subscription listener.subscribe("ACTUATOR_CMDS",&ActuatorCmdHandler::actuator_cmd_Callback,&handlerObject); listener.subscribe("NAV_CMDS",&ActuatorCmdHandler::body_twist_cmd_Callback,&handlerObject); listener.subscribe("ROTATING_SCAN_RATE_CMD",&ActuatorCmdHandler::rot_scan_rate_cmd_Callback,&handlerObject); // Only here to Demo Estop: listener.subscribe("NAV_GOAL_ESTOP",&ActuatorCmdHandler::estop_Callback,&handlerObject); while(0 == listener.handle()); return 0; } // lcm::LCM talker; // if(!talker.good()) // return 1; // drc::actuator_cmd_t actuator_cmd; // actuator_cmd.timestamp = 0; // actuator_cmd.robot_name = "wheeled_atlas"; // actuator_cmd.num_joints = 2; // actuator_cmd.joint_name.push_back("LShoulderRoll"); // actuator_cmd.joint_name.push_back("RShoulderRoll"); // actuator_cmd.joint_effort.push_back(12.0); // actuator_cmd.joint_effort.push_back(-12.0); // actuator_cmd.duration.push_back(0.1); // actuator_cmd.duration.push_back(0.1); // // lcm::LCM listener; // if(!listener.good()) // return 1; // ActuatorCmdHandler handler; // listener.subscribe("ACTUATOR_CMDS",&ActuatorCmdHandler::actuator_cmd_Callback,&handler); // while(true) // { // talker.publish("ACTUATOR_CMDS",&actuator_cmd); // listener.handle(); // } // return 0; <|endoftext|>
<commit_before>#include "../TestCase.hpp" #include <ctime> WRD_TEST_START(MemRobustTest) class A : public Object { public: virtual const Class& getClass() const { static TClass<A> in; return in; } int age; }; class B : public A { public: virtual const Class& getClass() const { static TClass<B> in; return in; } float grade; }; class PInstance : public Thing { Id _id; virtual Res& release() { return wasgood; } }; class PNode : public PInstance {}; class PObject : public PNode {}; class PA : public PObject { public: virtual const Class& getClass() const { static TClass<PA> in; return in; } int age; }; class PB : public PA { public: virtual const Class& getClass() const { static TClass<PB> in; return in; } float grade; }; class Sprint { public: static void run(int n) { PA* parr[100000] = {0, }; time_t start = clock(); int crc = 0; for(int i=0; i < n ;i++) { parr[i] = new PB(); crc += (int) parr[i]; } for(int i=0; i < n ;i++) delete parr[i]; WRD_WARN("%d times new/delete : %f ms elapsed. crc=%d", n, ((float) clock() - start) / CLOCKS_PER_SEC*1000.0f, crc); crc = 0; A* arr[100000] = {0, }; start = clock(); for(int i=0; i < n ;i++) { arr[i] = new B(); crc += (int) arr[i]; } for(int i=0; i < n ;i++) delete arr[i]; WRD_WARN("%d times mempool : %f ms elapsed. crc=%d", n, ((float) clock() - start) / CLOCKS_PER_SEC*1000.0f, crc); } }; Sprint::run(10); Sprint::run(100); Sprint::run(1000); Sprint::run(10000); Sprint::run(50000); return ""; WRD_TEST_END(MemRobustTest) <commit_msg>- [ut] permissive error on linux.<commit_after>#include "../TestCase.hpp" #include <ctime> WRD_TEST_START(MemRobustTest) class A : public Object { public: virtual const Class& getClass() const { static TClass<A> in; return in; } int age; }; class B : public A { public: virtual const Class& getClass() const { static TClass<B> in; return in; } float grade; }; class PInstance : public Thing { Id _id; virtual Res& release() { return wasgood; } }; class PNode : public PInstance {}; class PObject : public PNode {}; class PA : public PObject { public: virtual const Class& getClass() const { static TClass<PA> in; return in; } int age; }; class PB : public PA { public: virtual const Class& getClass() const { static TClass<PB> in; return in; } float grade; }; class Sprint { public: static void run(int n) { PA* parr[100000] = {0, }; time_t start = clock(); int crc = 0; for(int i=0; i < n ;i++) { parr[i] = new PB(); crc += *(int*) parr[i]; } for(int i=0; i < n ;i++) delete parr[i]; WRD_WARN("%d times new/delete : %f ms elapsed. crc=%d", n, ((float) clock() - start) / CLOCKS_PER_SEC*1000.0f, crc); crc = 0; A* arr[100000] = {0, }; start = clock(); for(int i=0; i < n ;i++) { arr[i] = new B(); crc += *(int*) arr[i]; } for(int i=0; i < n ;i++) delete arr[i]; WRD_WARN("%d times mempool : %f ms elapsed. crc=%d", n, ((float) clock() - start) / CLOCKS_PER_SEC*1000.0f, crc); } }; Sprint::run(10); Sprint::run(100); Sprint::run(1000); Sprint::run(10000); Sprint::run(50000); return ""; WRD_TEST_END(MemRobustTest) <|endoftext|>
<commit_before>// Copyright 2019 The TCMalloc 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 // // https://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 "tcmalloc/experiment.h" #include <string.h> #include "absl/base/macros.h" #include "absl/strings/str_cat.h" #include "tcmalloc/internal/environment.h" #include "tcmalloc/internal/logging.h" using tcmalloc::internal::kNumExperiments; using tcmalloc::tcmalloc_internal::thread_safe_getenv; namespace tcmalloc { namespace { const char kDelimiter = ','; const char kExperiments[] = "BORG_EXPERIMENTS"; const char kEnableAll[] = "enable-all-known-experiments"; const char kDisableExperiments[] = "BORG_DISABLE_EXPERIMENTS"; const char kDisableAll[] = "all"; bool LookupExperimentID(absl::string_view label, Experiment* exp) { for (auto config : experiments) { if (config.name == label) { *exp = config.id; return true; } } return false; } const bool* GetSelectedExperiments() { static bool by_id[kNumExperiments]; static const char* active_experiments = thread_safe_getenv(kExperiments); static const char* disabled_experiments = thread_safe_getenv(kDisableExperiments); static const bool* status = internal::SelectExperiments( by_id, active_experiments ? active_experiments : "", disabled_experiments ? disabled_experiments : ""); return status; } template <typename F> void ParseExperiments(absl::string_view labels, F f) { absl::string_view::size_type pos = 0; do { absl::string_view token; auto end = labels.find(kDelimiter, pos); if (end == absl::string_view::npos) { token = labels.substr(pos); pos = end; } else { token = labels.substr(pos, end - pos); pos = end + 1; } f(token); } while (pos != absl::string_view::npos); } } // namespace namespace internal { const bool* SelectExperiments(bool* buffer, absl::string_view active, absl::string_view disabled) { memset(buffer, 0, sizeof(*buffer) * kNumExperiments); if (active == kEnableAll) { std::fill(buffer, buffer + kNumExperiments, true); } ParseExperiments(active, [buffer](absl::string_view token) { Experiment id; if (LookupExperimentID(token, &id)) { buffer[static_cast<int>(id)] = true; } }); if (disabled == kDisableAll) { memset(buffer, 0, sizeof(*buffer) * kNumExperiments); } ParseExperiments(disabled, [buffer](absl::string_view token) { Experiment id; if (LookupExperimentID(token, &id)) { buffer[static_cast<int>(id)] = false; } }); return buffer; } } // namespace internal bool IsExperimentActive(Experiment exp) { ASSERT(static_cast<int>(exp) >= 0); ASSERT(exp < Experiment::kMaxExperimentID); return GetSelectedExperiments()[static_cast<int>(exp)]; } void FillExperimentProperties( std::map<std::string, MallocExtension::Property>* result) { for (const auto& config : experiments) { (*result)[absl::StrCat("tcmalloc.experiment.", config.name)].value = IsExperimentActive(config.id) ? 1 : 0; } } absl::optional<Experiment> FindExperimentByName(absl::string_view name) { for (const auto& config : experiments) { if (name == config.name) { return config.id; } } return absl::nullopt; } void PrintExperiments(TCMalloc_Printer* printer) { // Index experiments by their positions in the experiments array, rather than // by experiment ID. static bool active[ABSL_ARRAYSIZE(experiments)]; static const bool* status = []() { memset(active, 0, sizeof(active)); const bool* by_id = GetSelectedExperiments(); for (int i = 0; i < ABSL_ARRAYSIZE(experiments); i++) { const auto& config = experiments[i]; active[i] = by_id[static_cast<int>(config.id)]; } return active; }(); printer->printf("MALLOC EXPERIMENTS:"); for (int i = 0; i < ABSL_ARRAYSIZE(experiments); i++) { const char* value = status[i] ? "1" : "0"; printer->printf(" %s=%s", experiments[i].name, value); } printer->printf("\n"); } } // namespace tcmalloc <commit_msg>Use absl::string_view for constants compared to another string_view.<commit_after>// Copyright 2019 The TCMalloc 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 // // https://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 "tcmalloc/experiment.h" #include <string.h> #include "absl/base/macros.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "tcmalloc/internal/environment.h" #include "tcmalloc/internal/logging.h" using tcmalloc::internal::kNumExperiments; using tcmalloc::tcmalloc_internal::thread_safe_getenv; namespace tcmalloc { namespace { const char kDelimiter = ','; const char kExperiments[] = "BORG_EXPERIMENTS"; const char kDisableExperiments[] = "BORG_DISABLE_EXPERIMENTS"; constexpr absl::string_view kEnableAll = "enable-all-known-experiments"; constexpr absl::string_view kDisableAll = "all"; bool LookupExperimentID(absl::string_view label, Experiment* exp) { for (auto config : experiments) { if (config.name == label) { *exp = config.id; return true; } } return false; } const bool* GetSelectedExperiments() { static bool by_id[kNumExperiments]; static const char* active_experiments = thread_safe_getenv(kExperiments); static const char* disabled_experiments = thread_safe_getenv(kDisableExperiments); static const bool* status = internal::SelectExperiments( by_id, active_experiments ? active_experiments : "", disabled_experiments ? disabled_experiments : ""); return status; } template <typename F> void ParseExperiments(absl::string_view labels, F f) { absl::string_view::size_type pos = 0; do { absl::string_view token; auto end = labels.find(kDelimiter, pos); if (end == absl::string_view::npos) { token = labels.substr(pos); pos = end; } else { token = labels.substr(pos, end - pos); pos = end + 1; } f(token); } while (pos != absl::string_view::npos); } } // namespace namespace internal { const bool* SelectExperiments(bool* buffer, absl::string_view active, absl::string_view disabled) { memset(buffer, 0, sizeof(*buffer) * kNumExperiments); if (active == kEnableAll) { std::fill(buffer, buffer + kNumExperiments, true); } ParseExperiments(active, [buffer](absl::string_view token) { Experiment id; if (LookupExperimentID(token, &id)) { buffer[static_cast<int>(id)] = true; } }); if (disabled == kDisableAll) { memset(buffer, 0, sizeof(*buffer) * kNumExperiments); } ParseExperiments(disabled, [buffer](absl::string_view token) { Experiment id; if (LookupExperimentID(token, &id)) { buffer[static_cast<int>(id)] = false; } }); return buffer; } } // namespace internal bool IsExperimentActive(Experiment exp) { ASSERT(static_cast<int>(exp) >= 0); ASSERT(exp < Experiment::kMaxExperimentID); return GetSelectedExperiments()[static_cast<int>(exp)]; } void FillExperimentProperties( std::map<std::string, MallocExtension::Property>* result) { for (const auto& config : experiments) { (*result)[absl::StrCat("tcmalloc.experiment.", config.name)].value = IsExperimentActive(config.id) ? 1 : 0; } } absl::optional<Experiment> FindExperimentByName(absl::string_view name) { for (const auto& config : experiments) { if (name == config.name) { return config.id; } } return absl::nullopt; } void PrintExperiments(TCMalloc_Printer* printer) { // Index experiments by their positions in the experiments array, rather than // by experiment ID. static bool active[ABSL_ARRAYSIZE(experiments)]; static const bool* status = []() { memset(active, 0, sizeof(active)); const bool* by_id = GetSelectedExperiments(); for (int i = 0; i < ABSL_ARRAYSIZE(experiments); i++) { const auto& config = experiments[i]; active[i] = by_id[static_cast<int>(config.id)]; } return active; }(); printer->printf("MALLOC EXPERIMENTS:"); for (int i = 0; i < ABSL_ARRAYSIZE(experiments); i++) { const char* value = status[i] ? "1" : "0"; printer->printf(" %s=%s", experiments[i].name, value); } printer->printf("\n"); } } // namespace tcmalloc <|endoftext|>
<commit_before>// Copyright 2019 The TCMalloc 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 // // https://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 "tcmalloc/experiment.h" #include <string.h> #include <algorithm> #include <string> #include "absl/base/macros.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "tcmalloc/internal/environment.h" #include "tcmalloc/internal/logging.h" GOOGLE_MALLOC_SECTION_BEGIN namespace tcmalloc { namespace tcmalloc_internal { namespace { const char kDelimiter = ','; const char kExperiments[] = "BORG_EXPERIMENTS"; const char kDisableExperiments[] = "BORG_DISABLE_EXPERIMENTS"; constexpr absl::string_view kEnableAll = "enable-all-known-experiments"; constexpr absl::string_view kDisableAll = "all"; bool LookupExperimentID(absl::string_view label, Experiment* exp) { for (auto config : experiments) { if (config.name == label) { *exp = config.id; return true; } } return false; } const bool* GetSelectedExperiments() { static bool by_id[kNumExperiments]; static const bool* status = [&]() { const char* active_experiments = thread_safe_getenv(kExperiments); const char* disabled_experiments = thread_safe_getenv(kDisableExperiments); return SelectExperiments(by_id, active_experiments ? active_experiments : "", disabled_experiments ? disabled_experiments : ""); }(); return status; } template <typename F> void ParseExperiments(absl::string_view labels, F f) { absl::string_view::size_type pos = 0; do { absl::string_view token; auto end = labels.find(kDelimiter, pos); if (end == absl::string_view::npos) { token = labels.substr(pos); pos = end; } else { token = labels.substr(pos, end - pos); pos = end + 1; } f(token); } while (pos != absl::string_view::npos); } } // namespace const bool* SelectExperiments(bool* buffer, absl::string_view active, absl::string_view disabled) { memset(buffer, 0, sizeof(*buffer) * kNumExperiments); if (active == kEnableAll) { std::fill(buffer, buffer + kNumExperiments, true); } ParseExperiments(active, [buffer](absl::string_view token) { Experiment id; if (LookupExperimentID(token, &id)) { buffer[static_cast<int>(id)] = true; } }); if (disabled == kDisableAll) { memset(buffer, 0, sizeof(*buffer) * kNumExperiments); } ParseExperiments(disabled, [buffer](absl::string_view token) { Experiment id; if (LookupExperimentID(token, &id)) { buffer[static_cast<int>(id)] = false; } }); return buffer; } } // namespace tcmalloc_internal bool IsExperimentActive(Experiment exp) { ASSERT(static_cast<int>(exp) >= 0); ASSERT(exp < Experiment::kMaxExperimentID); return tcmalloc_internal::GetSelectedExperiments()[static_cast<int>(exp)]; } absl::optional<Experiment> FindExperimentByName(absl::string_view name) { for (const auto& config : experiments) { if (name == config.name) { return config.id; } } return absl::nullopt; } void WalkExperiments( absl::FunctionRef<void(absl::string_view name, bool active)> callback) { for (const auto& config : experiments) { callback(config.name, IsExperimentActive(config.id)); } } } // namespace tcmalloc GOOGLE_MALLOC_SECTION_END <commit_msg>Internal change<commit_after>// Copyright 2019 The TCMalloc 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 // // https://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 "tcmalloc/experiment.h" #include <string.h> #include <algorithm> #include <string> #include "absl/base/macros.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "tcmalloc/internal/environment.h" #include "tcmalloc/internal/logging.h" GOOGLE_MALLOC_SECTION_BEGIN namespace tcmalloc { namespace tcmalloc_internal { namespace { const char kDelimiter = ','; const char kExperiments[] = "BORG_EXPERIMENTS"; const char kDisableExperiments[] = "BORG_DISABLE_EXPERIMENTS"; constexpr absl::string_view kEnableAll = "enable-all-known-experiments"; constexpr absl::string_view kDisableAll = "all"; bool LookupExperimentID(absl::string_view label, Experiment* exp) { for (auto config : experiments) { if (config.name == label) { *exp = config.id; return true; } } return false; } const bool* GetSelectedExperiments() { static bool by_id[kNumExperiments]; static const bool* status = [&]() { const char* active_experiments = thread_safe_getenv(kExperiments); const char* disabled_experiments = thread_safe_getenv(kDisableExperiments); return SelectExperiments(by_id, active_experiments ? active_experiments : "", disabled_experiments ? disabled_experiments : ""); }(); return status; } template <typename F> void ParseExperiments(absl::string_view labels, F f) { absl::string_view::size_type pos = 0; do { absl::string_view token; auto end = labels.find(kDelimiter, pos); if (end == absl::string_view::npos) { token = labels.substr(pos); pos = end; } else { token = labels.substr(pos, end - pos); pos = end + 1; } f(token); } while (pos != absl::string_view::npos); } } // namespace const bool* SelectExperiments(bool* buffer, absl::string_view active, absl::string_view disabled) { memset(buffer, 0, sizeof(*buffer) * kNumExperiments); if (active == kEnableAll) { std::fill(buffer, buffer + kNumExperiments, true); } ParseExperiments(active, [buffer](absl::string_view token) { Experiment id; if (LookupExperimentID(token, &id)) { buffer[static_cast<int>(id)] = true; } }); if (disabled == kDisableAll) { memset(buffer, 0, sizeof(*buffer) * kNumExperiments); } ParseExperiments(disabled, [buffer](absl::string_view token) { Experiment id; if (LookupExperimentID(token, &id)) { buffer[static_cast<int>(id)] = false; } }); return buffer; } } // namespace tcmalloc_internal bool IsExperimentActive(Experiment exp) { ASSERT(static_cast<int>(exp) >= 0); ASSERT(exp < Experiment::kMaxExperimentID); return tcmalloc_internal::GetSelectedExperiments()[static_cast<int>(exp)]; } absl::optional<Experiment> FindExperimentByName(absl::string_view name) { for (const auto& config : experiments) { if (name == config.name) { return config.id; } } return absl::nullopt; } void WalkExperiments( absl::FunctionRef<void(absl::string_view name, bool active)> callback) { for (const auto& config : experiments) { callback(config.name, IsExperimentActive(config.id)); } } } // namespace tcmalloc GOOGLE_MALLOC_SECTION_END <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertyanimationnode.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2006-12-13 15:34:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_slideshow.hxx" // must be first #include "canvas/debug.hxx" #include "canvas/verbosetrace.hxx" #include "propertyanimationnode.hxx" #include "animationfactory.hxx" using namespace com::sun::star; namespace slideshow { namespace internal { AnimationActivitySharedPtr PropertyAnimationNode::createActivity() const { // Create AnimationActivity from common XAnimate parameters: ActivitiesFactory::CommonParameters aParms( fillCommonParameters() ); uno::Reference<animations::XAnimate> const& xAnimateNode =getXAnimateNode(); rtl::OUString const attrName( xAnimateNode->getAttributeName() ); AttributableShapeSharedPtr const pShape( getShape() ); switch (AnimationFactory::classifyAttributeName( attrName )) { default: case AnimationFactory::CLASS_UNKNOWN_PROPERTY: ENSURE_AND_THROW( false, "Unexpected attribute class (unknown or empty attribute name)" ); break; case AnimationFactory::CLASS_NUMBER_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createNumberPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); case AnimationFactory::CLASS_ENUM_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createEnumPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); case AnimationFactory::CLASS_COLOR_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createColorPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); case AnimationFactory::CLASS_STRING_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createStringPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); case AnimationFactory::CLASS_BOOL_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createBoolPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); } return AnimationActivitySharedPtr(); } } // namespace internal } // namespace slideshow <commit_msg>INTEGRATION: CWS presfixes12 (1.6.12); FILE MERGED 2007/02/06 17:18:08 thb 1.6.12.2: #i37778# Moved clear() method from View to ViewLayer (also sprites need to be cleared); fixed a few more cases of local code style violations; removed redundant inline keywords; finished Layer/LayerManager rework (Layer now represents ViewLayers, shapes and rendering are fully under LayerManager control); made shape comparator reusable 2007/01/29 14:02:02 thb 1.6.12.1: Issue number: #i37778#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertyanimationnode.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2007-07-17 14:50:16 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_slideshow.hxx" // must be first #include <canvas/debug.hxx> #include <canvas/verbosetrace.hxx> #include "propertyanimationnode.hxx" #include "animationfactory.hxx" using namespace com::sun::star; namespace slideshow { namespace internal { AnimationActivitySharedPtr PropertyAnimationNode::createActivity() const { // Create AnimationActivity from common XAnimate parameters: ActivitiesFactory::CommonParameters aParms( fillCommonParameters() ); uno::Reference<animations::XAnimate> const& xAnimateNode =getXAnimateNode(); rtl::OUString const attrName( xAnimateNode->getAttributeName() ); AttributableShapeSharedPtr const pShape( getShape() ); switch (AnimationFactory::classifyAttributeName( attrName )) { default: case AnimationFactory::CLASS_UNKNOWN_PROPERTY: ENSURE_AND_THROW( false, "Unexpected attribute class (unknown or empty attribute name)" ); break; case AnimationFactory::CLASS_NUMBER_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createNumberPropertyAnimation( attrName, pShape, getContext().mpSubsettableShapeManager, getSlideSize() ), xAnimateNode ); case AnimationFactory::CLASS_ENUM_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createEnumPropertyAnimation( attrName, pShape, getContext().mpSubsettableShapeManager, getSlideSize() ), xAnimateNode ); case AnimationFactory::CLASS_COLOR_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createColorPropertyAnimation( attrName, pShape, getContext().mpSubsettableShapeManager, getSlideSize() ), xAnimateNode ); case AnimationFactory::CLASS_STRING_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createStringPropertyAnimation( attrName, pShape, getContext().mpSubsettableShapeManager, getSlideSize() ), xAnimateNode ); case AnimationFactory::CLASS_BOOL_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createBoolPropertyAnimation( attrName, pShape, getContext().mpSubsettableShapeManager, getSlideSize() ), xAnimateNode ); } return AnimationActivitySharedPtr(); } } // namespace internal } // namespace slideshow <|endoftext|>
<commit_before>// Copyright (c) 2019 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 <iostream> #include <memory> #include <string> #include <utility> #include "net/third_party/quiche/src/quic/core/quic_types.h" #include "net/third_party/quiche/src/quic/core/quic_versions.h" #include "net/third_party/quiche/src/quic/platform/api/quic_epoll.h" #include "net/third_party/quiche/src/quic/platform/api/quic_system_event_loop.h" #include "net/quic/platform/impl/quic_epoll_clock.h" #include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h" #include "net/third_party/quiche/src/quic/test_tools/quic_session_peer.h" #include "net/third_party/quiche/src/quic/test_tools/simple_session_cache.h" #include "net/third_party/quiche/src/quic/tools/fake_proof_verifier.h" #include "net/third_party/quiche/src/quic/tools/quic_client.h" #include "net/third_party/quiche/src/quic/tools/quic_url.h" #include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h" DEFINE_QUIC_COMMAND_LINE_FLAG(std::string, host, "", "The IP or hostname to connect to."); DEFINE_QUIC_COMMAND_LINE_FLAG(int32_t, port, 0, "The port to connect to."); namespace quic { enum class Feature { // First row of features ("table stakes") // A version negotiation response is elicited and acted on. kVersionNegotiation, // The handshake completes successfully. kHandshake, // Stream data is being exchanged and ACK'ed. kStreamData, // The connection close procedcure completes with a zero error code. kConnectionClose, // The connection was established using TLS resumption. kResumption, // A RETRY packet was successfully processed. kRetry, // Second row of features (anything else protocol-related) // We switched to a different port and the server migrated to it. kRebinding, // Third row of features (H3 tests) // An H3 transaction succeeded. kHttp3, // One or both endpoints insert entries into dynamic table and subsequenly // reference them from header blocks. kDynamicEntryReferenced, }; char MatrixLetter(Feature f) { switch (f) { case Feature::kVersionNegotiation: return 'V'; case Feature::kHandshake: return 'H'; case Feature::kStreamData: return 'D'; case Feature::kConnectionClose: return 'C'; case Feature::kResumption: return 'R'; case Feature::kRetry: return 'S'; case Feature::kRebinding: return 'B'; case Feature::kHttp3: return '3'; case Feature::kDynamicEntryReferenced: return 'd'; } } class QuicClientInteropRunner : QuicConnectionDebugVisitor { public: QuicClientInteropRunner() {} void InsertFeature(Feature feature) { features_.insert(feature); } std::set<Feature> features() const { return features_; } // Attempts a resumption using |client| by disconnecting and reconnecting. If // resumption is successful, |features_| is modified to add // Feature::kResumption to it, otherwise it is left unmodified. void AttemptResumption(QuicClient* client); void AttemptRequest(QuicSocketAddress addr, std::string authority, QuicServerId server_id, ParsedQuicVersion version, bool test_version_negotiation, bool attempt_rebind); void OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override { switch (frame.close_type) { case GOOGLE_QUIC_CONNECTION_CLOSE: QUIC_LOG(ERROR) << "Received unexpected GoogleQUIC connection close"; break; case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE: if (frame.wire_error_code == NO_IETF_QUIC_ERROR) { InsertFeature(Feature::kConnectionClose); } else { QUIC_LOG(ERROR) << "Received transport connection close " << QuicIetfTransportErrorCodeString( static_cast<QuicIetfTransportErrorCodes>( frame.wire_error_code)); } break; case IETF_QUIC_APPLICATION_CONNECTION_CLOSE: if (frame.wire_error_code == 0) { InsertFeature(Feature::kConnectionClose); } else { QUIC_LOG(ERROR) << "Received application connection close " << frame.wire_error_code; } break; } } void OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& /*packet*/) override { InsertFeature(Feature::kVersionNegotiation); } private: std::set<Feature> features_; }; void QuicClientInteropRunner::AttemptResumption(QuicClient* client) { client->Disconnect(); if (!client->Initialize()) { QUIC_LOG(ERROR) << "Failed to reinitialize client"; return; } if (!client->Connect() || !client->session()->OneRttKeysAvailable()) { return; } if (static_cast<QuicCryptoClientStream*>( test::QuicSessionPeer::GetMutableCryptoStream(client->session())) ->IsResumption()) { InsertFeature(Feature::kResumption); } } void QuicClientInteropRunner::AttemptRequest(QuicSocketAddress addr, std::string authority, QuicServerId server_id, ParsedQuicVersion version, bool test_version_negotiation, bool attempt_rebind) { ParsedQuicVersionVector versions = {version}; if (test_version_negotiation) { versions.insert(versions.begin(), QuicVersionReservedForNegotiation()); } auto proof_verifier = std::make_unique<FakeProofVerifier>(); auto session_cache = std::make_unique<test::SimpleSessionCache>(); QuicEpollServer epoll_server; QuicEpollClock epoll_clock(&epoll_server); QuicConfig config; QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(20); config.SetIdleNetworkTimeout(timeout); auto client = std::make_unique<QuicClient>( addr, server_id, versions, config, &epoll_server, std::move(proof_verifier), std::move(session_cache)); client->set_connection_debug_visitor(this); if (!client->Initialize()) { QUIC_LOG(ERROR) << "Failed to initialize client"; return; } const bool connect_result = client->Connect(); QuicConnection* connection = client->session()->connection(); if (connection == nullptr) { QUIC_LOG(ERROR) << "No QuicConnection object"; return; } QuicConnectionStats client_stats = connection->GetStats(); if (client_stats.retry_packet_processed) { InsertFeature(Feature::kRetry); } if (test_version_negotiation && connection->version() == version) { InsertFeature(Feature::kVersionNegotiation); } if (test_version_negotiation && !connect_result) { // Failed to negotiate version, retry without version negotiation. AttemptRequest(addr, authority, server_id, version, /*test_version_negotiation=*/false, attempt_rebind); return; } if (!client->session()->OneRttKeysAvailable()) { return; } InsertFeature(Feature::kHandshake); // Construct and send a request. spdy::SpdyHeaderBlock header_block; header_block[":method"] = "GET"; header_block[":scheme"] = "https"; header_block[":authority"] = authority; header_block[":path"] = "/"; client->set_store_response(true); client->SendRequestAndWaitForResponse(header_block, "", /*fin=*/true); client_stats = connection->GetStats(); QuicSentPacketManager* sent_packet_manager = test::QuicConnectionPeer::GetSentPacketManager(connection); const bool received_forward_secure_ack = sent_packet_manager != nullptr && sent_packet_manager->GetLargestAckedPacket(ENCRYPTION_FORWARD_SECURE) .IsInitialized(); if (client_stats.stream_bytes_received > 0 && received_forward_secure_ack) { InsertFeature(Feature::kStreamData); } if (!client->connected()) { return; } if (client->latest_response_code() != -1) { InsertFeature(Feature::kHttp3); if (client->client_session()->dynamic_table_entry_referenced()) { InsertFeature(Feature::kDynamicEntryReferenced); } if (attempt_rebind) { // Now make a second request after switching to a different client port. if (client->ChangeEphemeralPort()) { client->SendRequestAndWaitForResponse(header_block, "", /*fin=*/true); if (!client->connected()) { // Rebinding does not work, retry without attempting it. AttemptRequest(addr, authority, server_id, version, test_version_negotiation, /*attempt_rebind=*/false); return; } InsertFeature(Feature::kRebinding); if (client->client_session()->dynamic_table_entry_referenced()) { InsertFeature(Feature::kDynamicEntryReferenced); } } else { QUIC_LOG(ERROR) << "Failed to change ephemeral port"; } } } if (connection->connected()) { connection->CloseConnection( QUIC_NO_ERROR, "Graceful close", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); InsertFeature(Feature::kConnectionClose); } AttemptResumption(client.get()); } std::set<Feature> ServerSupport(std::string host, int port) { // Enable IETF version support. QuicVersionInitializeSupportForIetfDraft(); ParsedQuicVersion version = UnsupportedQuicVersion(); for (const ParsedQuicVersion& vers : AllSupportedVersions()) { // Find the first version that supports IETF QUIC. if (vers.HasIetfQuicFrames() && vers.handshake_protocol == quic::PROTOCOL_TLS1_3) { version = vers; break; } } CHECK_NE(version.transport_version, QUIC_VERSION_UNSUPPORTED); QuicEnableVersion(version); // Build the client, and try to connect. QuicSocketAddress addr = tools::LookupAddress(host, quiche::QuicheStrCat(port)); if (!addr.IsInitialized()) { QUIC_LOG(ERROR) << "Failed to resolve " << host; return std::set<Feature>(); } QuicServerId server_id(host, port, false); std::string authority = quiche::QuicheStrCat(host, ":", port); QuicClientInteropRunner runner; runner.AttemptRequest(addr, authority, server_id, version, /*test_version_negotiation=*/true, /*attempt_rebind=*/true); return runner.features(); } } // namespace quic int main(int argc, char* argv[]) { QuicSystemEventLoop event_loop("quic_client"); const char* usage = "Usage: quic_client_interop_test [options] [url]"; std::vector<std::string> args = quic::QuicParseCommandLineFlags(usage, argc, argv); if (args.size() > 1) { quic::QuicPrintCommandLineFlagHelp(usage); exit(1); } std::string host = GetQuicFlag(FLAGS_host); int port = GetQuicFlag(FLAGS_port); if (!args.empty()) { quic::QuicUrl url(args[0], "https"); if (host.empty()) { host = url.host(); } if (port == 0) { port = url.port(); } } if (port == 0) { port = 443; } if (host.empty()) { quic::QuicPrintCommandLineFlagHelp(usage); exit(1); } auto supported_features = quic::ServerSupport(host, port); std::cout << "Results for " << host << ":" << port << std::endl; int current_row = 1; for (auto feature : supported_features) { if (current_row < 2 && feature >= quic::Feature::kRebinding) { std::cout << std::endl; current_row = 2; } if (current_row < 3 && feature >= quic::Feature::kHttp3) { std::cout << std::endl; current_row = 3; } std::cout << MatrixLetter(feature); } std::cout << std::endl; } <commit_msg>Allow --host and url to refer to different hosts in quic_client_interop_test_bin<commit_after>// Copyright (c) 2019 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 <iostream> #include <memory> #include <string> #include <utility> #include "net/third_party/quiche/src/quic/core/quic_types.h" #include "net/third_party/quiche/src/quic/core/quic_versions.h" #include "net/third_party/quiche/src/quic/platform/api/quic_epoll.h" #include "net/third_party/quiche/src/quic/platform/api/quic_system_event_loop.h" #include "net/quic/platform/impl/quic_epoll_clock.h" #include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h" #include "net/third_party/quiche/src/quic/test_tools/quic_session_peer.h" #include "net/third_party/quiche/src/quic/test_tools/simple_session_cache.h" #include "net/third_party/quiche/src/quic/tools/fake_proof_verifier.h" #include "net/third_party/quiche/src/quic/tools/quic_client.h" #include "net/third_party/quiche/src/quic/tools/quic_url.h" #include "net/third_party/quiche/src/common/platform/api/quiche_str_cat.h" DEFINE_QUIC_COMMAND_LINE_FLAG(std::string, host, "", "The IP or hostname to connect to."); DEFINE_QUIC_COMMAND_LINE_FLAG(int32_t, port, 0, "The port to connect to."); namespace quic { enum class Feature { // First row of features ("table stakes") // A version negotiation response is elicited and acted on. kVersionNegotiation, // The handshake completes successfully. kHandshake, // Stream data is being exchanged and ACK'ed. kStreamData, // The connection close procedcure completes with a zero error code. kConnectionClose, // The connection was established using TLS resumption. kResumption, // A RETRY packet was successfully processed. kRetry, // Second row of features (anything else protocol-related) // We switched to a different port and the server migrated to it. kRebinding, // Third row of features (H3 tests) // An H3 transaction succeeded. kHttp3, // One or both endpoints insert entries into dynamic table and subsequenly // reference them from header blocks. kDynamicEntryReferenced, }; char MatrixLetter(Feature f) { switch (f) { case Feature::kVersionNegotiation: return 'V'; case Feature::kHandshake: return 'H'; case Feature::kStreamData: return 'D'; case Feature::kConnectionClose: return 'C'; case Feature::kResumption: return 'R'; case Feature::kRetry: return 'S'; case Feature::kRebinding: return 'B'; case Feature::kHttp3: return '3'; case Feature::kDynamicEntryReferenced: return 'd'; } } class QuicClientInteropRunner : QuicConnectionDebugVisitor { public: QuicClientInteropRunner() {} void InsertFeature(Feature feature) { features_.insert(feature); } std::set<Feature> features() const { return features_; } // Attempts a resumption using |client| by disconnecting and reconnecting. If // resumption is successful, |features_| is modified to add // Feature::kResumption to it, otherwise it is left unmodified. void AttemptResumption(QuicClient* client); void AttemptRequest(QuicSocketAddress addr, std::string authority, QuicServerId server_id, ParsedQuicVersion version, bool test_version_negotiation, bool attempt_rebind); void OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override { switch (frame.close_type) { case GOOGLE_QUIC_CONNECTION_CLOSE: QUIC_LOG(ERROR) << "Received unexpected GoogleQUIC connection close"; break; case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE: if (frame.wire_error_code == NO_IETF_QUIC_ERROR) { InsertFeature(Feature::kConnectionClose); } else { QUIC_LOG(ERROR) << "Received transport connection close " << QuicIetfTransportErrorCodeString( static_cast<QuicIetfTransportErrorCodes>( frame.wire_error_code)); } break; case IETF_QUIC_APPLICATION_CONNECTION_CLOSE: if (frame.wire_error_code == 0) { InsertFeature(Feature::kConnectionClose); } else { QUIC_LOG(ERROR) << "Received application connection close " << frame.wire_error_code; } break; } } void OnVersionNegotiationPacket( const QuicVersionNegotiationPacket& /*packet*/) override { InsertFeature(Feature::kVersionNegotiation); } private: std::set<Feature> features_; }; void QuicClientInteropRunner::AttemptResumption(QuicClient* client) { client->Disconnect(); if (!client->Initialize()) { QUIC_LOG(ERROR) << "Failed to reinitialize client"; return; } if (!client->Connect() || !client->session()->OneRttKeysAvailable()) { return; } if (static_cast<QuicCryptoClientStream*>( test::QuicSessionPeer::GetMutableCryptoStream(client->session())) ->IsResumption()) { InsertFeature(Feature::kResumption); } } void QuicClientInteropRunner::AttemptRequest(QuicSocketAddress addr, std::string authority, QuicServerId server_id, ParsedQuicVersion version, bool test_version_negotiation, bool attempt_rebind) { ParsedQuicVersionVector versions = {version}; if (test_version_negotiation) { versions.insert(versions.begin(), QuicVersionReservedForNegotiation()); } auto proof_verifier = std::make_unique<FakeProofVerifier>(); auto session_cache = std::make_unique<test::SimpleSessionCache>(); QuicEpollServer epoll_server; QuicEpollClock epoll_clock(&epoll_server); QuicConfig config; QuicTime::Delta timeout = QuicTime::Delta::FromSeconds(20); config.SetIdleNetworkTimeout(timeout); auto client = std::make_unique<QuicClient>( addr, server_id, versions, config, &epoll_server, std::move(proof_verifier), std::move(session_cache)); client->set_connection_debug_visitor(this); if (!client->Initialize()) { QUIC_LOG(ERROR) << "Failed to initialize client"; return; } const bool connect_result = client->Connect(); QuicConnection* connection = client->session()->connection(); if (connection == nullptr) { QUIC_LOG(ERROR) << "No QuicConnection object"; return; } QuicConnectionStats client_stats = connection->GetStats(); if (client_stats.retry_packet_processed) { InsertFeature(Feature::kRetry); } if (test_version_negotiation && connection->version() == version) { InsertFeature(Feature::kVersionNegotiation); } if (test_version_negotiation && !connect_result) { // Failed to negotiate version, retry without version negotiation. AttemptRequest(addr, authority, server_id, version, /*test_version_negotiation=*/false, attempt_rebind); return; } if (!client->session()->OneRttKeysAvailable()) { return; } InsertFeature(Feature::kHandshake); // Construct and send a request. spdy::SpdyHeaderBlock header_block; header_block[":method"] = "GET"; header_block[":scheme"] = "https"; header_block[":authority"] = authority; header_block[":path"] = "/"; client->set_store_response(true); client->SendRequestAndWaitForResponse(header_block, "", /*fin=*/true); client_stats = connection->GetStats(); QuicSentPacketManager* sent_packet_manager = test::QuicConnectionPeer::GetSentPacketManager(connection); const bool received_forward_secure_ack = sent_packet_manager != nullptr && sent_packet_manager->GetLargestAckedPacket(ENCRYPTION_FORWARD_SECURE) .IsInitialized(); if (client_stats.stream_bytes_received > 0 && received_forward_secure_ack) { InsertFeature(Feature::kStreamData); } if (!client->connected()) { return; } if (client->latest_response_code() != -1) { InsertFeature(Feature::kHttp3); if (client->client_session()->dynamic_table_entry_referenced()) { InsertFeature(Feature::kDynamicEntryReferenced); } if (attempt_rebind) { // Now make a second request after switching to a different client port. if (client->ChangeEphemeralPort()) { client->SendRequestAndWaitForResponse(header_block, "", /*fin=*/true); if (!client->connected()) { // Rebinding does not work, retry without attempting it. AttemptRequest(addr, authority, server_id, version, test_version_negotiation, /*attempt_rebind=*/false); return; } InsertFeature(Feature::kRebinding); if (client->client_session()->dynamic_table_entry_referenced()) { InsertFeature(Feature::kDynamicEntryReferenced); } } else { QUIC_LOG(ERROR) << "Failed to change ephemeral port"; } } } if (connection->connected()) { connection->CloseConnection( QUIC_NO_ERROR, "Graceful close", ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET); InsertFeature(Feature::kConnectionClose); } AttemptResumption(client.get()); } std::set<Feature> ServerSupport(std::string dns_host, std::string url_host, int port) { // Enable IETF version support. QuicVersionInitializeSupportForIetfDraft(); ParsedQuicVersion version = UnsupportedQuicVersion(); for (const ParsedQuicVersion& vers : AllSupportedVersions()) { // Find the first version that supports IETF QUIC. if (vers.HasIetfQuicFrames() && vers.handshake_protocol == quic::PROTOCOL_TLS1_3) { version = vers; break; } } CHECK_NE(version.transport_version, QUIC_VERSION_UNSUPPORTED); QuicEnableVersion(version); // Build the client, and try to connect. QuicSocketAddress addr = tools::LookupAddress(dns_host, quiche::QuicheStrCat(port)); if (!addr.IsInitialized()) { QUIC_LOG(ERROR) << "Failed to resolve " << dns_host; return std::set<Feature>(); } QuicServerId server_id(url_host, port, false); std::string authority = quiche::QuicheStrCat(url_host, ":", port); QuicClientInteropRunner runner; runner.AttemptRequest(addr, authority, server_id, version, /*test_version_negotiation=*/true, /*attempt_rebind=*/true); return runner.features(); } } // namespace quic int main(int argc, char* argv[]) { QuicSystemEventLoop event_loop("quic_client"); const char* usage = "Usage: quic_client_interop_test [options] [url]"; std::vector<std::string> args = quic::QuicParseCommandLineFlags(usage, argc, argv); if (args.size() > 1) { quic::QuicPrintCommandLineFlagHelp(usage); exit(1); } std::string dns_host = GetQuicFlag(FLAGS_host); std::string url_host = ""; int port = GetQuicFlag(FLAGS_port); if (!args.empty()) { quic::QuicUrl url(args[0], "https"); url_host = url.host(); if (dns_host.empty()) { dns_host = url_host; } if (port == 0) { port = url.port(); } } if (port == 0) { port = 443; } if (dns_host.empty()) { quic::QuicPrintCommandLineFlagHelp(usage); exit(1); } if (url_host.empty()) { url_host = dns_host; } auto supported_features = quic::ServerSupport(dns_host, url_host, port); std::cout << "Results for " << url_host << ":" << port << std::endl; int current_row = 1; for (auto feature : supported_features) { if (current_row < 2 && feature >= quic::Feature::kRebinding) { std::cout << std::endl; current_row = 2; } if (current_row < 3 && feature >= quic::Feature::kHttp3) { std::cout << std::endl; current_row = 3; } std::cout << MatrixLetter(feature); } std::cout << std::endl; } <|endoftext|>
<commit_before>#define _IRR_STATIC_LIB_ #include <irrlicht.h> #include <iostream> #include <cstdio> #include "../source/Irrlicht/COpenGLExtensionHandler.h" using namespace irr; using namespace core; /** We do cool stuff here, like make an event receiver to process input **/ class MyEventReceiver : public IEventReceiver { public: MyEventReceiver() { } bool OnEvent(const SEvent& event) { if (event.EventType == irr::EET_KEY_INPUT_EVENT && !event.KeyInput.PressedDown) { switch (event.KeyInput.Key) { case irr::KEY_KEY_Q: // switch wire frame mode exit(0); return true; default: break; } } return false; } private: }; class SimpleCallBack : public video::IShaderConstantSetCallBack { int32_t mvpUniformLocation; video::E_SHADER_CONSTANT_TYPE mvpUniformType; public: SimpleCallBack() : mvpUniformLocation(-1), mvpUniformType(video::ESCT_FLOAT_VEC3) {} virtual void PostLink(video::IMaterialRendererServices* services, const video::E_MATERIAL_TYPE& materialType, const core::vector<video::SConstantLocationNamePair>& constants) { //! Normally we'd iterate through the array and check our actual constant names before mapping them to locations but oh well mvpUniformLocation = constants[0].location; mvpUniformType = constants[0].type; } virtual void OnSetConstants(video::IMaterialRendererServices* services, int32_t userData) { services->setShaderConstant(services->getVideoDriver()->getTransform(video::EPTS_PROJ_VIEW_WORLD).pointer(),mvpUniformLocation,mvpUniformType,1); } virtual void OnUnsetMaterial() {} }; #include "irr/irrpack.h" struct VertexStruct { /// every member needs to be at location aligned to its type size for GLSL float Pos[3]; /// uses float hence need 4 byte alignment uint8_t Col[2]; /// same logic needs 1 byte alignment uint8_t uselessPadding[2]; /// so if there is a member with 4 byte alignment then whole struct needs 4 byte align, so pad it } PACK_STRUCT; #include "irr/irrunpack.h" int main() { printf("Please select the background:\n"); printf(" (0 : default) Use SkyDome\n"); printf(" (1) Use SkyBox\n"); uint8_t c = 0; std::cin >> c; // create device with full flexibility over creation parameters // you can add more parameters if desired, check irr::SIrrlichtCreationParameters irr::SIrrlichtCreationParameters params; params.Bits = 24; //may have to set to 32bit for some platforms params.ZBufferBits = 24; //we'd like 32bit here params.DriverType = video::EDT_OPENGL; //! Only Well functioning driver, software renderer left for sake of 2D image drawing params.WindowSize = dimension2d<uint32_t>(1280, 720); params.Fullscreen = false; params.Vsync = true; //! If supported by target platform params.Doublebuffer = true; params.Stencilbuffer = false; //! This will not even be a choice soon IrrlichtDevice* device = createDeviceEx(params); if (device == 0) return 1; // could not create selected driver. video::IVideoDriver* driver = device->getVideoDriver(); SimpleCallBack* callBack = new SimpleCallBack(); //! First need to make a material other than default to be able to draw with custom shader video::SMaterial material; material.BackfaceCulling = false; //! Triangles will be visible from both sides material.MaterialType = (video::E_MATERIAL_TYPE)driver->getGPUProgrammingServices()->addHighLevelShaderMaterialFromFiles("../mesh.vert", "","","", //! No Geometry or Tessellation Shaders "../mesh.frag", 3,video::EMT_SOLID, //! 3 vertices per primitive (this is tessellation shader relevant only callBack, 0); //! No custom user data callBack->drop(); scene::ISceneManager* smgr = device->getSceneManager(); driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true); driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false); // create skybox and skydome switch (c) { case '1': smgr->addSkyBoxSceneNode( driver->getTexture("../../media/irrlicht2_up.jpg"), driver->getTexture("../../media/irrlicht2_dn.jpg"), driver->getTexture("../../media/irrlicht2_lf.jpg"), driver->getTexture("../../media/irrlicht2_rt.jpg"), driver->getTexture("../../media/irrlicht2_ft.jpg"), driver->getTexture("../../media/irrlicht2_bk.jpg")); break; default: smgr->addSkyDomeSceneNode(driver->getTexture("../../media/skydome.jpg"),16,8,0.95f,2.0f,10.f); break; } driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, true); //! we want to move around the scene and view it from different angles scene::ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS(0,100.0f,0.001f); camera->setPosition(core::vector3df(-4,0,0)); camera->setTarget(core::vector3df(0,0,0)); camera->setNearValue(0.01f); camera->setFarValue(10.0f); smgr->setActiveCamera(camera); //! disable mouse cursor, since camera will force it to the middle //! and we don't want a jittery cursor in the middle distracting us device->getCursorControl()->setVisible(false); //! Since our cursor will be enslaved, there will be no way to close the window //! So we listen for the "Q" key being pressed and exit the application MyEventReceiver receiver; device->setEventReceiver(&receiver); uint64_t lastFPSTime = 0; while(device->run()) //if (device->isWindowActive()) { driver->beginScene(true, true, video::SColor(255,255,255,255) ); //! This animates (moves) the camera and sets the transforms //! Also draws the meshbuffer smgr->drawAll(); //! Stress test for memleaks aside from demo how to create meshes that live on the GPU RAM { VertexStruct vertices[8]; vertices[0] = VertexStruct{{-1.f,-1.f,-1.f},{ 0, 0}}; vertices[1] = VertexStruct{{ 1.f,-1.f,-1.f},{127, 0}}; vertices[2] = VertexStruct{{-1.f, 1.f,-1.f},{255, 0}}; vertices[3] = VertexStruct{{ 1.f, 1.f,-1.f},{ 0,127}}; vertices[4] = VertexStruct{{-1.f,-1.f, 1.f},{127,127}}; vertices[5] = VertexStruct{{ 1.f,-1.f, 1.f},{255,127}}; vertices[6] = VertexStruct{{-1.f, 1.f, 1.f},{ 0,255}}; vertices[7] = VertexStruct{{ 1.f, 1.f, 1.f},{127,255}}; uint16_t indices_indexed16[] = { 0,1,2,1,2,3, 4,5,6,5,6,7, 0,1,4,1,4,5, 2,3,6,3,6,7, 0,2,4,2,4,6, 1,3,5,3,5,7 }; auto upStreamBuff = driver->getDefaultUpStreamingBuffer(); const void* dataToPlace[2] = {vertices,indices_indexed16}; uint32_t offsets[2] = {video::StreamingTransientDataBufferMT<>::invalid_address,video::StreamingTransientDataBufferMT<>::invalid_address}; uint32_t alignments[2] = {sizeof(decltype(vertices[0u])),sizeof(decltype(indices_indexed16[0u]))}; uint32_t sizes[2] = {sizeof(vertices),sizeof(indices_indexed16)}; upStreamBuff->multi_place(2u,(const void* const*)dataToPlace,(uint32_t*)&offsets,(uint32_t*)&sizes,(uint32_t*)&alignments); if (upStreamBuff->needsManualFlushOrInvalidate()) { auto upStreamMem = upStreamBuff->getBuffer()->getBoundMemory(); driver->flushMappedMemoryRanges({video::IDriverMemoryAllocation::MappedMemoryRange(upStreamMem,offsets[0],sizes[0]),video::IDriverMemoryAllocation::MappedMemoryRange(upStreamMem,offsets[1],sizes[1])}); } auto buff = upStreamBuff->getBuffer(); scene::IGPUMeshDataFormatDesc* desc = driver->createGPUMeshDataFormatDesc(); desc->mapVertexAttrBuffer(buff,scene::EVAI_ATTR0,scene::ECPA_THREE,scene::ECT_FLOAT,sizeof(VertexStruct),offsetof(VertexStruct,Pos[0])+offsets[0]); desc->mapVertexAttrBuffer(buff,scene::EVAI_ATTR1,scene::ECPA_TWO,scene::ECT_NORMALIZED_UNSIGNED_BYTE,sizeof(VertexStruct),offsetof(VertexStruct,Col[0])+offsets[0]); desc->mapIndexBuffer(buff); scene::IGPUMeshBuffer* mb = new scene::IGPUMeshBuffer(); mb->setMeshDataAndFormat(desc); mb->setIndexBufferOffset(offsets[1]); mb->setIndexType(scene::EIT_16BIT); mb->setIndexCount(2*3*6); desc->drop(); driver->setTransform(video::E4X3TS_WORLD,core::matrix4x3()); driver->setMaterial(material); driver->drawMeshBuffer(mb); mb->drop(); upStreamBuff->multi_free(1u,(uint32_t*)&offsets,(uint32_t*)&sizes,driver->placeFence()); } driver->endScene(); // display frames per second in window title uint64_t time = device->getTimer()->getRealTime(); if (time-lastFPSTime > 1000) { std::wostringstream str; str << L"GPU Mesh Demo - Irrlicht Engine [" << driver->getName() << "] FPS:" << driver->getFPS() << " PrimitvesDrawn:" << driver->getPrimitiveCountDrawn(); device->setWindowCaption(str.str().c_str()); lastFPSTime = time; } } //create a screenshot video::IImage* screenshot = driver->createImage(video::ECF_A8R8G8B8,params.WindowSize); glReadPixels(0,0, params.WindowSize.Width,params.WindowSize.Height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, screenshot->getData()); { // images are horizontally flipped, so we have to fix that here. uint8_t* pixels = (uint8_t*)screenshot->getData(); const int32_t pitch=screenshot->getPitch(); uint8_t* p2 = pixels + (params.WindowSize.Height - 1) * pitch; uint8_t* tmpBuffer = new uint8_t[pitch]; for (uint32_t i=0; i < params.WindowSize.Height; i += 2) { memcpy(tmpBuffer, pixels, pitch); memcpy(pixels, p2, pitch); memcpy(p2, tmpBuffer, pitch); pixels += pitch; p2 -= pitch; } delete [] tmpBuffer; } driver->writeImageToFile(screenshot,"./screenshot.png"); screenshot->drop(); device->sleep(3000); device->drop(); return 0; } <commit_msg>Fix #170<commit_after>#define _IRR_STATIC_LIB_ #include <irrlicht.h> #include <iostream> #include <cstdio> #include "../source/Irrlicht/COpenGLExtensionHandler.h" using namespace irr; using namespace core; /** We do cool stuff here, like make an event receiver to process input **/ class MyEventReceiver : public IEventReceiver { public: MyEventReceiver() { } bool OnEvent(const SEvent& event) { if (event.EventType == irr::EET_KEY_INPUT_EVENT && !event.KeyInput.PressedDown) { switch (event.KeyInput.Key) { case irr::KEY_KEY_Q: // switch wire frame mode exit(0); return true; default: break; } } return false; } private: }; class SimpleCallBack : public video::IShaderConstantSetCallBack { int32_t mvpUniformLocation; video::E_SHADER_CONSTANT_TYPE mvpUniformType; public: SimpleCallBack() : mvpUniformLocation(-1), mvpUniformType(video::ESCT_FLOAT_VEC3) {} virtual void PostLink(video::IMaterialRendererServices* services, const video::E_MATERIAL_TYPE& materialType, const core::vector<video::SConstantLocationNamePair>& constants) { //! Normally we'd iterate through the array and check our actual constant names before mapping them to locations but oh well mvpUniformLocation = constants[0].location; mvpUniformType = constants[0].type; } virtual void OnSetConstants(video::IMaterialRendererServices* services, int32_t userData) { services->setShaderConstant(services->getVideoDriver()->getTransform(video::EPTS_PROJ_VIEW_WORLD).pointer(),mvpUniformLocation,mvpUniformType,1); } virtual void OnUnsetMaterial() {} }; #include "irr/irrpack.h" struct VertexStruct { /// every member needs to be at location aligned to its type size for GLSL float Pos[3]; /// uses float hence need 4 byte alignment uint8_t Col[2]; /// same logic needs 1 byte alignment uint8_t uselessPadding[2]; /// so if there is a member with 4 byte alignment then whole struct needs 4 byte align, so pad it } PACK_STRUCT; #include "irr/irrunpack.h" int main() { printf("Please select the background:\n"); printf(" (0 : default) Use SkyDome\n"); printf(" (1) Use SkyBox\n"); uint8_t c = 0; std::cin >> c; // create device with full flexibility over creation parameters // you can add more parameters if desired, check irr::SIrrlichtCreationParameters irr::SIrrlichtCreationParameters params; params.Bits = 24; //may have to set to 32bit for some platforms params.ZBufferBits = 24; //we'd like 32bit here params.DriverType = video::EDT_OPENGL; //! Only Well functioning driver, software renderer left for sake of 2D image drawing params.WindowSize = dimension2d<uint32_t>(1280, 720); params.Fullscreen = false; params.Vsync = true; //! If supported by target platform params.Doublebuffer = true; params.Stencilbuffer = false; //! This will not even be a choice soon IrrlichtDevice* device = createDeviceEx(params); if (device == 0) return 1; // could not create selected driver. video::IVideoDriver* driver = device->getVideoDriver(); SimpleCallBack* callBack = new SimpleCallBack(); //! First need to make a material other than default to be able to draw with custom shader video::SMaterial material; material.BackfaceCulling = false; //! Triangles will be visible from both sides material.MaterialType = (video::E_MATERIAL_TYPE)driver->getGPUProgrammingServices()->addHighLevelShaderMaterialFromFiles("../mesh.vert", "","","", //! No Geometry or Tessellation Shaders "../mesh.frag", 3,video::EMT_SOLID, //! 3 vertices per primitive (this is tessellation shader relevant only callBack, 0); //! No custom user data callBack->drop(); scene::ISceneManager* smgr = device->getSceneManager(); driver->setTextureCreationFlag(video::ETCF_ALWAYS_32_BIT, true); driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, false); // create skybox and skydome switch (c) { case '1': smgr->addSkyBoxSceneNode( driver->getTexture("../../media/irrlicht2_up.jpg"), driver->getTexture("../../media/irrlicht2_dn.jpg"), driver->getTexture("../../media/irrlicht2_lf.jpg"), driver->getTexture("../../media/irrlicht2_rt.jpg"), driver->getTexture("../../media/irrlicht2_ft.jpg"), driver->getTexture("../../media/irrlicht2_bk.jpg")); break; default: smgr->addSkyDomeSceneNode(driver->getTexture("../../media/skydome.jpg"),16,8,0.95f,2.0f,10.f); break; } driver->setTextureCreationFlag(video::ETCF_CREATE_MIP_MAPS, true); //! we want to move around the scene and view it from different angles scene::ICameraSceneNode* camera = smgr->addCameraSceneNodeFPS(0,100.0f,0.001f); camera->setPosition(core::vector3df(-4,0,0)); camera->setTarget(core::vector3df(0,0,0)); camera->setNearValue(0.01f); camera->setFarValue(10.0f); smgr->setActiveCamera(camera); //! disable mouse cursor, since camera will force it to the middle //! and we don't want a jittery cursor in the middle distracting us device->getCursorControl()->setVisible(false); //! Since our cursor will be enslaved, there will be no way to close the window //! So we listen for the "Q" key being pressed and exit the application MyEventReceiver receiver; device->setEventReceiver(&receiver); uint64_t lastFPSTime = 0; while(device->run()) //if (device->isWindowActive()) { driver->beginScene(true, true, video::SColor(255,255,255,255) ); //! This animates (moves) the camera and sets the transforms //! Also draws the meshbuffer smgr->drawAll(); //! Stress test for memleaks aside from demo how to create meshes that live on the GPU RAM { VertexStruct vertices[8]; vertices[0] = VertexStruct{{-1.f,-1.f,-1.f},{ 0, 0}}; vertices[1] = VertexStruct{{ 1.f,-1.f,-1.f},{127, 0}}; vertices[2] = VertexStruct{{-1.f, 1.f,-1.f},{255, 0}}; vertices[3] = VertexStruct{{ 1.f, 1.f,-1.f},{ 0,127}}; vertices[4] = VertexStruct{{-1.f,-1.f, 1.f},{127,127}}; vertices[5] = VertexStruct{{ 1.f,-1.f, 1.f},{255,127}}; vertices[6] = VertexStruct{{-1.f, 1.f, 1.f},{ 0,255}}; vertices[7] = VertexStruct{{ 1.f, 1.f, 1.f},{127,255}}; uint16_t indices_indexed16[] = { 0,1,2,1,2,3, 4,5,6,5,6,7, 0,1,4,1,4,5, 2,3,6,3,6,7, 0,2,4,2,4,6, 1,3,5,3,5,7 }; auto upStreamBuff = driver->getDefaultUpStreamingBuffer(); const void* dataToPlace[2] = {vertices,indices_indexed16}; uint32_t offsets[2] = {video::StreamingTransientDataBufferMT<>::invalid_address,video::StreamingTransientDataBufferMT<>::invalid_address}; uint32_t alignments[2] = {sizeof(decltype(vertices[0u])),sizeof(decltype(indices_indexed16[0u]))}; uint32_t sizes[2] = {sizeof(vertices),sizeof(indices_indexed16)}; upStreamBuff->multi_place(2u,(const void* const*)dataToPlace,(uint32_t*)&offsets,(uint32_t*)&sizes,(uint32_t*)&alignments); if (upStreamBuff->needsManualFlushOrInvalidate()) { auto upStreamMem = upStreamBuff->getBuffer()->getBoundMemory(); driver->flushMappedMemoryRanges({video::IDriverMemoryAllocation::MappedMemoryRange(upStreamMem,offsets[0],sizes[0]),video::IDriverMemoryAllocation::MappedMemoryRange(upStreamMem,offsets[1],sizes[1])}); } auto buff = upStreamBuff->getBuffer(); scene::IGPUMeshDataFormatDesc* desc = driver->createGPUMeshDataFormatDesc(); desc->mapVertexAttrBuffer(buff,scene::EVAI_ATTR0,scene::ECPA_THREE,scene::ECT_FLOAT,sizeof(VertexStruct),offsetof(VertexStruct,Pos[0])+offsets[0]); desc->mapVertexAttrBuffer(buff,scene::EVAI_ATTR1,scene::ECPA_TWO,scene::ECT_NORMALIZED_UNSIGNED_BYTE,sizeof(VertexStruct),offsetof(VertexStruct,Col[0])+offsets[0]); desc->mapIndexBuffer(buff); scene::IGPUMeshBuffer* mb = new scene::IGPUMeshBuffer(); mb->setMeshDataAndFormat(desc); mb->setIndexBufferOffset(offsets[1]); mb->setIndexType(scene::EIT_16BIT); mb->setIndexCount(2*3*6); desc->drop(); driver->setTransform(video::E4X3TS_WORLD,core::matrix4x3()); driver->setMaterial(material); driver->drawMeshBuffer(mb); mb->drop(); upStreamBuff->multi_free(2u,(uint32_t*)&offsets,(uint32_t*)&sizes,driver->placeFence()); } driver->endScene(); // display frames per second in window title uint64_t time = device->getTimer()->getRealTime(); if (time-lastFPSTime > 1000) { std::wostringstream str; str << L"GPU Mesh Demo - Irrlicht Engine [" << driver->getName() << "] FPS:" << driver->getFPS() << " PrimitvesDrawn:" << driver->getPrimitiveCountDrawn(); device->setWindowCaption(str.str().c_str()); lastFPSTime = time; } } //create a screenshot video::IImage* screenshot = driver->createImage(video::ECF_A8R8G8B8,params.WindowSize); glReadPixels(0,0, params.WindowSize.Width,params.WindowSize.Height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, screenshot->getData()); { // images are horizontally flipped, so we have to fix that here. uint8_t* pixels = (uint8_t*)screenshot->getData(); const int32_t pitch=screenshot->getPitch(); uint8_t* p2 = pixels + (params.WindowSize.Height - 1) * pitch; uint8_t* tmpBuffer = new uint8_t[pitch]; for (uint32_t i=0; i < params.WindowSize.Height; i += 2) { memcpy(tmpBuffer, pixels, pitch); memcpy(pixels, p2, pitch); memcpy(p2, tmpBuffer, pitch); pixels += pitch; p2 -= pitch; } delete [] tmpBuffer; } driver->writeImageToFile(screenshot,"./screenshot.png"); screenshot->drop(); device->sleep(3000); device->drop(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2019 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 <iostream> #include <memory> #include <string> #include <utility> #include "net/third_party/quiche/src/quic/core/quic_types.h" #include "net/third_party/quiche/src/quic/core/quic_versions.h" #include "net/third_party/quiche/src/quic/platform/api/quic_epoll.h" #include "net/third_party/quiche/src/quic/platform/api/quic_system_event_loop.h" #include "net/quic/platform/impl/quic_epoll_clock.h" #include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h" #include "net/third_party/quiche/src/quic/tools/fake_proof_verifier.h" #include "net/third_party/quiche/src/quic/tools/quic_client.h" #include "net/third_party/quiche/src/quic/tools/quic_url.h" DEFINE_QUIC_COMMAND_LINE_FLAG(std::string, host, "", "The IP or hostname to connect to."); DEFINE_QUIC_COMMAND_LINE_FLAG(int32_t, port, 0, "The port to connect to."); namespace quic { enum class Feature { // A version negotiation response is elicited and acted on. kVersionNegotiation, // The handshake completes successfully. kHandshake, // Stream data is being exchanged and ACK'ed. kStreamData, // The connection close procedcure completes with a zero error code. kConnectionClose, // A RETRY packet was successfully processed. kRetry, // An H3 transaction succeeded. kHttp3, }; char MatrixLetter(Feature f) { switch (f) { case Feature::kVersionNegotiation: return 'V'; case Feature::kHandshake: return 'H'; case Feature::kStreamData: return 'D'; case Feature::kConnectionClose: return 'C'; case Feature::kHttp3: return '3'; case Feature::kRetry: return 'S'; } } std::set<Feature> AttemptRequest(QuicSocketAddress addr, std::string authority, QuicServerId server_id, ParsedQuicVersionVector versions) { std::set<Feature> features; auto proof_verifier = std::make_unique<FakeProofVerifier>(); QuicEpollServer epoll_server; QuicEpollClock epoll_clock(&epoll_server); auto client = std::make_unique<QuicClient>( addr, server_id, versions, &epoll_server, std::move(proof_verifier)); if (!client->Initialize()) { return features; } if (!client->Connect()) { QuicErrorCode error = client->session()->error(); if (error == QUIC_INVALID_VERSION) { // QuicFramer::ProcessPacket returns RaiseError(QUIC_INVALID_VERSION) if // it receives a packet containing a version in the header that is not our // version. It might be possible that we didn't actually process a VN // packet here. features.insert(Feature::kVersionNegotiation); return features; } return features; } if (!client->session()->IsCryptoHandshakeConfirmed()) { return features; } features.insert(Feature::kHandshake); // Construct and send a request. spdy::SpdyHeaderBlock header_block; header_block[":method"] = "GET"; header_block[":scheme"] = "https"; header_block[":authority"] = authority; header_block[":path"] = "/"; client->set_store_response(true); client->SendRequest(header_block, "", /*fin=*/true); const QuicTime request_start_time = epoll_clock.Now(); static const auto request_timeout = QuicTime::Delta::FromSeconds(20); while (client->WaitForEvents()) { if (epoll_clock.Now() - request_start_time >= request_timeout) { QUIC_LOG(ERROR) << "Timed out waiting for HTTP response"; return features; } } QuicConnection* connection = client->session()->connection(); if (connection != nullptr) { QuicConnectionStats client_stats = connection->GetStats(); if (client_stats.retry_packet_processed) { features.insert(Feature::kRetry); } QuicSentPacketManager* sent_packet_manager = test::QuicConnectionPeer::GetSentPacketManager(connection); const bool received_forward_secure_ack = sent_packet_manager != nullptr && sent_packet_manager->GetLargestAckedPacket(ENCRYPTION_FORWARD_SECURE) .IsInitialized(); if (client_stats.stream_bytes_received > 0 && received_forward_secure_ack) { features.insert(Feature::kStreamData); } } if (!client->connected()) { return features; } if (client->latest_response_code() != -1) { features.insert(Feature::kHttp3); } if (connection != nullptr && connection->connected()) { test::QuicConnectionPeer::SendConnectionClosePacket( connection, QUIC_NO_ERROR, "Graceful close"); const QuicTime close_start_time = epoll_clock.Now(); static const auto close_timeout = QuicTime::Delta::FromSeconds(10); while (client->connected()) { client->epoll_network_helper()->RunEventLoop(); if (epoll_clock.Now() - close_start_time >= close_timeout) { QUIC_LOG(ERROR) << "Timed out waiting for connection close"; return features; } } const QuicErrorCode received_error = client->session()->error(); if (received_error == QUIC_NO_ERROR || received_error == QUIC_PUBLIC_RESET) { features.insert(Feature::kConnectionClose); } else { QUIC_LOG(ERROR) << "Received error " << client->session()->error() << " " << client->session()->error_details(); } } return features; } std::set<Feature> ServerSupport(std::string host, int port) { // Configure version list. QuicVersionInitializeSupportForIetfDraft(); ParsedQuicVersion version = ParsedQuicVersion(PROTOCOL_TLS1_3, QUIC_VERSION_99); ParsedQuicVersionVector versions = {version}; QuicEnableVersion(version); // Build the client, and try to connect. QuicSocketAddress addr = tools::LookupAddress(host, QuicStrCat(port)); QuicServerId server_id(host, port, false); std::string authority = QuicStrCat(host, ":", port); ParsedQuicVersionVector versions_with_negotiation = versions; versions_with_negotiation.insert(versions_with_negotiation.begin(), QuicVersionReservedForNegotiation()); auto supported_features = AttemptRequest(addr, authority, server_id, versions_with_negotiation); if (!supported_features.empty()) { supported_features.insert(Feature::kVersionNegotiation); } else { supported_features = AttemptRequest(addr, authority, server_id, versions); } return supported_features; } } // namespace quic int main(int argc, char* argv[]) { QuicSystemEventLoop event_loop("quic_client"); const char* usage = "Usage: quic_client_interop_test [options] [url]"; std::vector<std::string> args = quic::QuicParseCommandLineFlags(usage, argc, argv); if (args.size() > 1) { quic::QuicPrintCommandLineFlagHelp(usage); exit(1); } std::string host = GetQuicFlag(FLAGS_host); int port = GetQuicFlag(FLAGS_port); if (!args.empty()) { quic::QuicUrl url(args[0], "https"); if (host.empty()) { host = url.host(); } if (port == 0) { port = url.port(); } } if (port == 0) { port = 443; } if (host.empty()) { quic::QuicPrintCommandLineFlagHelp(usage); exit(1); } auto supported_features = quic::ServerSupport(host, port); std::cout << host << ":" << port << " = "; for (auto feature : supported_features) { std::cout << MatrixLetter(feature); } std::cout << std::endl; } <commit_msg>Add rebinding support to quic_client_interop<commit_after>// Copyright (c) 2019 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 <iostream> #include <memory> #include <string> #include <utility> #include "net/third_party/quiche/src/quic/core/quic_types.h" #include "net/third_party/quiche/src/quic/core/quic_versions.h" #include "net/third_party/quiche/src/quic/platform/api/quic_epoll.h" #include "net/third_party/quiche/src/quic/platform/api/quic_system_event_loop.h" #include "net/quic/platform/impl/quic_epoll_clock.h" #include "net/third_party/quiche/src/quic/test_tools/quic_connection_peer.h" #include "net/third_party/quiche/src/quic/tools/fake_proof_verifier.h" #include "net/third_party/quiche/src/quic/tools/quic_client.h" #include "net/third_party/quiche/src/quic/tools/quic_url.h" DEFINE_QUIC_COMMAND_LINE_FLAG(std::string, host, "", "The IP or hostname to connect to."); DEFINE_QUIC_COMMAND_LINE_FLAG(int32_t, port, 0, "The port to connect to."); namespace quic { enum class Feature { // A version negotiation response is elicited and acted on. kVersionNegotiation, // The handshake completes successfully. kHandshake, // Stream data is being exchanged and ACK'ed. kStreamData, // The connection close procedcure completes with a zero error code. kConnectionClose, // A RETRY packet was successfully processed. kRetry, // An H3 transaction succeeded. kHttp3, // We switched to a different port and the server migrated to it. kRebinding, }; char MatrixLetter(Feature f) { switch (f) { case Feature::kVersionNegotiation: return 'V'; case Feature::kHandshake: return 'H'; case Feature::kStreamData: return 'D'; case Feature::kConnectionClose: return 'C'; case Feature::kHttp3: return '3'; case Feature::kRetry: return 'S'; case Feature::kRebinding: return 'B'; } } std::set<Feature> AttemptRequest(QuicSocketAddress addr, std::string authority, QuicServerId server_id, ParsedQuicVersionVector versions, bool attempt_rebind) { std::set<Feature> features; auto proof_verifier = std::make_unique<FakeProofVerifier>(); QuicEpollServer epoll_server; QuicEpollClock epoll_clock(&epoll_server); auto client = std::make_unique<QuicClient>( addr, server_id, versions, &epoll_server, std::move(proof_verifier)); if (!client->Initialize()) { return features; } if (!client->Connect()) { QuicErrorCode error = client->session()->error(); if (error == QUIC_INVALID_VERSION) { // QuicFramer::ProcessPacket returns RaiseError(QUIC_INVALID_VERSION) if // it receives a packet containing a version in the header that is not our // version. It might be possible that we didn't actually process a VN // packet here. features.insert(Feature::kVersionNegotiation); return features; } return features; } if (!client->session()->IsCryptoHandshakeConfirmed()) { return features; } features.insert(Feature::kHandshake); // Construct and send a request. spdy::SpdyHeaderBlock header_block; header_block[":method"] = "GET"; header_block[":scheme"] = "https"; header_block[":authority"] = authority; header_block[":path"] = "/"; client->set_store_response(true); client->SendRequest(header_block, "", /*fin=*/true); const QuicTime request_start_time = epoll_clock.Now(); static const auto request_timeout = QuicTime::Delta::FromSeconds(20); while (client->WaitForEvents()) { if (epoll_clock.Now() - request_start_time >= request_timeout) { QUIC_LOG(ERROR) << "Timed out waiting for HTTP response"; return features; } } QuicConnection* connection = client->session()->connection(); if (connection != nullptr) { QuicConnectionStats client_stats = connection->GetStats(); if (client_stats.retry_packet_processed) { features.insert(Feature::kRetry); } QuicSentPacketManager* sent_packet_manager = test::QuicConnectionPeer::GetSentPacketManager(connection); const bool received_forward_secure_ack = sent_packet_manager != nullptr && sent_packet_manager->GetLargestAckedPacket(ENCRYPTION_FORWARD_SECURE) .IsInitialized(); if (client_stats.stream_bytes_received > 0 && received_forward_secure_ack) { features.insert(Feature::kStreamData); } } if (!client->connected()) { return features; } if (client->latest_response_code() != -1) { features.insert(Feature::kHttp3); if (attempt_rebind) { // Now make a second request after switching to a different client port. if (client->ChangeEphemeralPort()) { client->SendRequest(header_block, "", /*fin=*/true); const QuicTime second_request_start_time = epoll_clock.Now(); while (client->WaitForEvents()) { if (epoll_clock.Now() - second_request_start_time >= request_timeout) { // Rebinding does not work, retry without attempting it. return AttemptRequest(addr, authority, server_id, versions, /*attempt_rebind=*/false); } } features.insert(Feature::kRebinding); } else { QUIC_LOG(ERROR) << "Failed to change ephemeral port"; } } } if (connection != nullptr && connection->connected()) { test::QuicConnectionPeer::SendConnectionClosePacket( connection, QUIC_NO_ERROR, "Graceful close"); const QuicTime close_start_time = epoll_clock.Now(); static const auto close_timeout = QuicTime::Delta::FromSeconds(10); while (client->connected()) { client->epoll_network_helper()->RunEventLoop(); if (epoll_clock.Now() - close_start_time >= close_timeout) { QUIC_LOG(ERROR) << "Timed out waiting for connection close"; return features; } } const QuicErrorCode received_error = client->session()->error(); if (received_error == QUIC_NO_ERROR || received_error == QUIC_PUBLIC_RESET) { features.insert(Feature::kConnectionClose); } else { QUIC_LOG(ERROR) << "Received error " << client->session()->error() << " " << client->session()->error_details(); } } return features; } std::set<Feature> ServerSupport(std::string host, int port) { // Configure version list. QuicVersionInitializeSupportForIetfDraft(); ParsedQuicVersion version = ParsedQuicVersion(PROTOCOL_TLS1_3, QUIC_VERSION_99); ParsedQuicVersionVector versions = {version}; QuicEnableVersion(version); // Build the client, and try to connect. QuicSocketAddress addr = tools::LookupAddress(host, QuicStrCat(port)); QuicServerId server_id(host, port, false); std::string authority = QuicStrCat(host, ":", port); ParsedQuicVersionVector versions_with_negotiation = versions; versions_with_negotiation.insert(versions_with_negotiation.begin(), QuicVersionReservedForNegotiation()); auto supported_features = AttemptRequest(addr, authority, server_id, versions_with_negotiation, /*attempt_rebind=*/true); if (!supported_features.empty()) { supported_features.insert(Feature::kVersionNegotiation); } else { supported_features = AttemptRequest(addr, authority, server_id, versions, /*attempt_rebind=*/true); } return supported_features; } } // namespace quic int main(int argc, char* argv[]) { QuicSystemEventLoop event_loop("quic_client"); const char* usage = "Usage: quic_client_interop_test [options] [url]"; std::vector<std::string> args = quic::QuicParseCommandLineFlags(usage, argc, argv); if (args.size() > 1) { quic::QuicPrintCommandLineFlagHelp(usage); exit(1); } std::string host = GetQuicFlag(FLAGS_host); int port = GetQuicFlag(FLAGS_port); if (!args.empty()) { quic::QuicUrl url(args[0], "https"); if (host.empty()) { host = url.host(); } if (port == 0) { port = url.port(); } } if (port == 0) { port = 443; } if (host.empty()) { quic::QuicPrintCommandLineFlagHelp(usage); exit(1); } auto supported_features = quic::ServerSupport(host, port); std::cout << host << ":" << port << " = "; for (auto feature : supported_features) { std::cout << MatrixLetter(feature); } std::cout << std::endl; } <|endoftext|>
<commit_before>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include "Node.h" #include "Engine.h" #include "SceneManager.h" #include "Layer.h" #include "Animator.h" #include "Camera.h" #include "Utils.h" #include "MathUtils.h" #include "Drawable.h" namespace ouzel { namespace scene { Node::Node() { } Node::~Node() { } void Node::visit(const Matrix4& newTransformMatrix, bool parentTransformDirty) { if (parentTransformDirty) { updateTransform(newTransformMatrix); } if (visible) { if (transformDirty) { calculateTransform(); } LayerPtr currentLayer = layer.lock(); // check if parent is layer bool isRoot = !parent.owner_before(layer) && !layer.owner_before(parent); if (children.empty()) { if (currentLayer && (globalOrder || isRoot) && checkVisibility()) { currentLayer->addToDrawQueue(std::static_pointer_cast<Node>(shared_from_this())); } } else { lock(); std::stable_sort(children.begin(), children.end(), [](const NodePtr& a, const NodePtr& b) { return a->getZ() > b->getZ(); }); auto i = children.begin(); NodePtr node; for (; i != children.end(); ++i) { node = *i; if (!node->remove) { if (node->getZ() < 0.0f) { node->visit(transform, updateChildrenTransform); } else { break; } } } if (currentLayer && (globalOrder || isRoot) && checkVisibility()) { currentLayer->addToDrawQueue(std::static_pointer_cast<Node>(shared_from_this())); } for (; i != children.end(); ++i) { if (!node->remove) { node = *i; node->visit(transform, updateChildrenTransform); } } unlock(); } updateChildrenTransform = false; } } void Node::process() { if (children.empty()) { draw(); } else { lock(); auto i = children.begin(); NodePtr node; for (; i != children.end(); ++i) { node = *i; if (node->getZ() < 0.0f) { if (!node->isGlobalOrder() && node->isVisible() && node->checkVisibility()) { node->draw(); } } else { break; } } draw(); for (; i != children.end(); ++i) { node = *i; if (!node->isGlobalOrder() && node->isVisible() && node->checkVisibility()) { node->draw(); } } unlock(); } } void Node::draw() { if (transformDirty) { calculateTransform(); } if (LayerPtr currentLayer = layer.lock()) { if (currentLayer->getCamera()) { graphics::Color drawColor(color.r, color.g, color.b, static_cast<uint8_t>(color.a * opacity)); for (const DrawablePtr& drawable : drawables) { if (drawable->isVisible()) { drawable->draw(currentLayer->getCamera()->getViewProjection(), transform, drawColor); } } } } } bool Node::addChild(const NodePtr& node) { if (NodeContainer::addChild(node)) { node->addToLayer(layer); node->updateTransform(getTransform()); return true; } else { return false; } } bool Node::removeFromParent() { if (NodeContainerPtr currentParent = parent.lock()) { currentParent->removeChild(std::static_pointer_cast<Node>(shared_from_this())); return true; } return false; } void Node::setZ(float newZ) { z = newZ; // Currently z does not affect transformation //localTransformDirty = transformDirty = inverseTransformDirty = true; } void Node::setGlobalOrder(bool newGlobalOrder) { globalOrder = newGlobalOrder; } void Node::setPosition(const Vector2& newPosition) { position = newPosition; localTransformDirty = transformDirty = inverseTransformDirty = true; } void Node::setRotation(float newRotation) { rotation = newRotation; localTransformDirty = transformDirty = inverseTransformDirty = true; } void Node::setScale(const Vector2& newScale) { scale = newScale; localTransformDirty = transformDirty = inverseTransformDirty = true; } void Node::setColor(const graphics::Color& newColor) { color = newColor; } void Node::setOpacity(float newOpacity) { opacity = clamp(newOpacity, 0.0f, 1.0f); } void Node::setFlipX(bool newFlipX) { flipX = newFlipX; localTransformDirty = transformDirty = inverseTransformDirty = true; } void Node::setFlipY(bool newFlipY) { flipY = newFlipY; localTransformDirty = transformDirty = inverseTransformDirty = true; } void Node::setVisible(bool newVisible) { visible = newVisible; } void Node::addToLayer(const LayerWeakPtr& newLayer) { layer = newLayer; if (!layer.expired()) { for (const NodePtr& child : children) { child->addToLayer(layer); } } } void Node::removeFromLayer() { for (const NodePtr& child : children) { child->removeFromLayer(); } layer.reset(); } bool Node::pointOn(const Vector2& worldPosition) const { Vector2 localPosition = convertWorldToLocal(worldPosition); for (const DrawablePtr& drawable : drawables) { if (drawable->pointOn(localPosition)) { return true; } } return false; } bool Node::shapeOverlaps(const std::vector<Vector2>& edges) const { Matrix4 inverse = getInverseTransform(); std::vector<Vector2> transformedEdges; for (const Vector2& edge : edges) { Vector3 transformedEdge = edge; inverse.transformPoint(transformedEdge); transformedEdges.push_back(Vector2(transformedEdge.x, transformedEdge.y)); } for (const DrawablePtr& drawable : drawables) { if (drawable->shapeOverlaps(transformedEdges)) { return true; } } return false; } const Matrix4& Node::getTransform() const { if (transformDirty) { calculateTransform(); } return transform; } const Matrix4& Node::getInverseTransform() const { if (transformDirty) { calculateTransform(); } if (inverseTransformDirty) { calculateInverseTransform(); } return inverseTransform; } void Node::updateTransform(const Matrix4& newParentTransform) { parentTransform = newParentTransform; transformDirty = inverseTransformDirty = true; } Vector2 Node::convertWorldToLocal(const Vector2& worldPosition) const { Vector3 localPosition = worldPosition; const Matrix4& currentInverseTransform = getInverseTransform(); currentInverseTransform.transformPoint(localPosition); return Vector2(localPosition.x, localPosition.y); } Vector2 Node::convertLocalToWorld(const Vector2& localPosition) const { Vector3 worldPosition = localPosition; const Matrix4& currentTransform = getTransform(); currentTransform.transformPoint(worldPosition); return Vector2(worldPosition.x, worldPosition.y); } bool Node::checkVisibility() const { if (LayerPtr currentLayer = layer.lock()) { for (const DrawablePtr& drawable : drawables) { if (drawable->isVisible() && (drawable->getBoundingBox().isEmpty() || sharedEngine->getRenderer()->checkVisibility(getTransform(), drawable->getBoundingBox(), currentLayer->getCamera()))) { return true; } } } return false; } void Node::animate(const AnimatorPtr& animator) { stopAnimation(); currentAnimator = animator; if (currentAnimator) { currentAnimator->start(std::static_pointer_cast<Node>(shared_from_this())); } } void Node::stopAnimation() { if (currentAnimator) { currentAnimator->stop(); removeAnimation(); } } void Node::removeAnimation() { currentAnimator.reset(); } void Node::calculateLocalTransform() const { localTransform = Matrix4::IDENTITY; localTransform.translate(Vector3(position.x, position.y, 0.0f)); localTransform.rotateZ(TAU - rotation); Vector3 realScale = Vector3(scale.x * (flipX ? -1.0f : 1.0f), scale.y * (flipY ? -1.0f : 1.0f), 1.0f); localTransform.scale(realScale); localTransformDirty = false; } void Node::calculateTransform() const { if (localTransformDirty) { calculateLocalTransform(); } transform = parentTransform * localTransform; transformDirty = false; updateChildrenTransform = true; } void Node::calculateInverseTransform() const { if (transformDirty) { calculateTransform(); } inverseTransform = transform; inverseTransform.invert(); inverseTransformDirty = false; } void Node::addDrawable(DrawablePtr drawable) { drawables.push_back(drawable); drawable->setParentNode(std::static_pointer_cast<Node>(shared_from_this())); } void Node::removeDrawable(uint32_t index) { if (index >= drawables.size()) { return; } drawables.erase(drawables.begin() + index); } void Node::removeDrawable(DrawablePtr drawable) { for (auto i = drawables.begin(); i != drawables.end();) { if (*i == drawable) { i = drawables.erase(i); } else { ++i; } } } void Node::removeAllDrawables() { drawables.clear(); } } // namespace scene } // namespace ouzel <commit_msg>Add node to draw queue if it has children<commit_after>// Copyright (C) 2016 Elviss Strazdins // This file is part of the Ouzel engine. #include <algorithm> #include "Node.h" #include "Engine.h" #include "SceneManager.h" #include "Layer.h" #include "Animator.h" #include "Camera.h" #include "Utils.h" #include "MathUtils.h" #include "Drawable.h" namespace ouzel { namespace scene { Node::Node() { } Node::~Node() { } void Node::visit(const Matrix4& newTransformMatrix, bool parentTransformDirty) { if (parentTransformDirty) { updateTransform(newTransformMatrix); } if (visible) { if (transformDirty) { calculateTransform(); } LayerPtr currentLayer = layer.lock(); // check if parent is layer bool isRoot = !parent.owner_before(layer) && !layer.owner_before(parent); if (children.empty()) { if (currentLayer && (globalOrder || isRoot) && checkVisibility()) { currentLayer->addToDrawQueue(std::static_pointer_cast<Node>(shared_from_this())); } } else { lock(); std::stable_sort(children.begin(), children.end(), [](const NodePtr& a, const NodePtr& b) { return a->getZ() > b->getZ(); }); auto i = children.begin(); NodePtr node; for (; i != children.end(); ++i) { node = *i; if (!node->remove) { if (node->getZ() < 0.0f) { node->visit(transform, updateChildrenTransform); } else { break; } } } if (currentLayer && (globalOrder || isRoot) && checkVisibility()) { currentLayer->addToDrawQueue(std::static_pointer_cast<Node>(shared_from_this())); } for (; i != children.end(); ++i) { if (!node->remove) { node = *i; node->visit(transform, updateChildrenTransform); } } unlock(); } updateChildrenTransform = false; } } void Node::process() { if (children.empty()) { draw(); } else { lock(); auto i = children.begin(); NodePtr node; for (; i != children.end(); ++i) { node = *i; if (node->getZ() < 0.0f) { if (!node->isGlobalOrder() && node->isVisible() && node->checkVisibility()) { node->draw(); } } else { break; } } draw(); for (; i != children.end(); ++i) { node = *i; if (!node->isGlobalOrder() && node->isVisible() && node->checkVisibility()) { node->draw(); } } unlock(); } } void Node::draw() { if (transformDirty) { calculateTransform(); } if (LayerPtr currentLayer = layer.lock()) { if (currentLayer->getCamera()) { graphics::Color drawColor(color.r, color.g, color.b, static_cast<uint8_t>(color.a * opacity)); for (const DrawablePtr& drawable : drawables) { if (drawable->isVisible()) { drawable->draw(currentLayer->getCamera()->getViewProjection(), transform, drawColor); } } } } } bool Node::addChild(const NodePtr& node) { if (NodeContainer::addChild(node)) { node->addToLayer(layer); node->updateTransform(getTransform()); return true; } else { return false; } } bool Node::removeFromParent() { if (NodeContainerPtr currentParent = parent.lock()) { currentParent->removeChild(std::static_pointer_cast<Node>(shared_from_this())); return true; } return false; } void Node::setZ(float newZ) { z = newZ; // Currently z does not affect transformation //localTransformDirty = transformDirty = inverseTransformDirty = true; } void Node::setGlobalOrder(bool newGlobalOrder) { globalOrder = newGlobalOrder; } void Node::setPosition(const Vector2& newPosition) { position = newPosition; localTransformDirty = transformDirty = inverseTransformDirty = true; } void Node::setRotation(float newRotation) { rotation = newRotation; localTransformDirty = transformDirty = inverseTransformDirty = true; } void Node::setScale(const Vector2& newScale) { scale = newScale; localTransformDirty = transformDirty = inverseTransformDirty = true; } void Node::setColor(const graphics::Color& newColor) { color = newColor; } void Node::setOpacity(float newOpacity) { opacity = clamp(newOpacity, 0.0f, 1.0f); } void Node::setFlipX(bool newFlipX) { flipX = newFlipX; localTransformDirty = transformDirty = inverseTransformDirty = true; } void Node::setFlipY(bool newFlipY) { flipY = newFlipY; localTransformDirty = transformDirty = inverseTransformDirty = true; } void Node::setVisible(bool newVisible) { visible = newVisible; } void Node::addToLayer(const LayerWeakPtr& newLayer) { layer = newLayer; if (!layer.expired()) { for (const NodePtr& child : children) { child->addToLayer(layer); } } } void Node::removeFromLayer() { for (const NodePtr& child : children) { child->removeFromLayer(); } layer.reset(); } bool Node::pointOn(const Vector2& worldPosition) const { Vector2 localPosition = convertWorldToLocal(worldPosition); for (const DrawablePtr& drawable : drawables) { if (drawable->pointOn(localPosition)) { return true; } } return false; } bool Node::shapeOverlaps(const std::vector<Vector2>& edges) const { Matrix4 inverse = getInverseTransform(); std::vector<Vector2> transformedEdges; for (const Vector2& edge : edges) { Vector3 transformedEdge = edge; inverse.transformPoint(transformedEdge); transformedEdges.push_back(Vector2(transformedEdge.x, transformedEdge.y)); } for (const DrawablePtr& drawable : drawables) { if (drawable->shapeOverlaps(transformedEdges)) { return true; } } return false; } const Matrix4& Node::getTransform() const { if (transformDirty) { calculateTransform(); } return transform; } const Matrix4& Node::getInverseTransform() const { if (transformDirty) { calculateTransform(); } if (inverseTransformDirty) { calculateInverseTransform(); } return inverseTransform; } void Node::updateTransform(const Matrix4& newParentTransform) { parentTransform = newParentTransform; transformDirty = inverseTransformDirty = true; } Vector2 Node::convertWorldToLocal(const Vector2& worldPosition) const { Vector3 localPosition = worldPosition; const Matrix4& currentInverseTransform = getInverseTransform(); currentInverseTransform.transformPoint(localPosition); return Vector2(localPosition.x, localPosition.y); } Vector2 Node::convertLocalToWorld(const Vector2& localPosition) const { Vector3 worldPosition = localPosition; const Matrix4& currentTransform = getTransform(); currentTransform.transformPoint(worldPosition); return Vector2(worldPosition.x, worldPosition.y); } bool Node::checkVisibility() const { // we must add this node to draw queue if it has children if (!children.empty()) { return true; } if (LayerPtr currentLayer = layer.lock()) { for (const DrawablePtr& drawable : drawables) { if (drawable->isVisible() && (drawable->getBoundingBox().isEmpty() || sharedEngine->getRenderer()->checkVisibility(getTransform(), drawable->getBoundingBox(), currentLayer->getCamera()))) { return true; } } } return false; } void Node::animate(const AnimatorPtr& animator) { stopAnimation(); currentAnimator = animator; if (currentAnimator) { currentAnimator->start(std::static_pointer_cast<Node>(shared_from_this())); } } void Node::stopAnimation() { if (currentAnimator) { currentAnimator->stop(); removeAnimation(); } } void Node::removeAnimation() { currentAnimator.reset(); } void Node::calculateLocalTransform() const { localTransform = Matrix4::IDENTITY; localTransform.translate(Vector3(position.x, position.y, 0.0f)); localTransform.rotateZ(TAU - rotation); Vector3 realScale = Vector3(scale.x * (flipX ? -1.0f : 1.0f), scale.y * (flipY ? -1.0f : 1.0f), 1.0f); localTransform.scale(realScale); localTransformDirty = false; } void Node::calculateTransform() const { if (localTransformDirty) { calculateLocalTransform(); } transform = parentTransform * localTransform; transformDirty = false; updateChildrenTransform = true; } void Node::calculateInverseTransform() const { if (transformDirty) { calculateTransform(); } inverseTransform = transform; inverseTransform.invert(); inverseTransformDirty = false; } void Node::addDrawable(DrawablePtr drawable) { drawables.push_back(drawable); drawable->setParentNode(std::static_pointer_cast<Node>(shared_from_this())); } void Node::removeDrawable(uint32_t index) { if (index >= drawables.size()) { return; } drawables.erase(drawables.begin() + index); } void Node::removeDrawable(DrawablePtr drawable) { for (auto i = drawables.begin(); i != drawables.end();) { if (*i == drawable) { i = drawables.erase(i); } else { ++i; } } } void Node::removeAllDrawables() { drawables.clear(); } } // namespace scene } // namespace ouzel <|endoftext|>
<commit_before>/* * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* Author: Ioan Sucan */ #include <moveit/rviz_plugin_render_tools/render_shapes.h> #include <moveit/rviz_plugin_render_tools/octomap_render.h> #include <OGRE/OgreSceneNode.h> #include <OGRE/OgreSceneManager.h> #include <OGRE/OgreManualObject.h> #include <OGRE/OgreMaterialManager.h> #include <rviz/ogre_helpers/shape.h> #include <rviz/display_context.h> #include <rviz/robot/robot.h> #include <boost/lexical_cast.hpp> #include <boost/math/constants/constants.hpp> namespace moveit_rviz_plugin { RenderShapes::RenderShapes(rviz::DisplayContext *context) : context_(context) { } RenderShapes::~RenderShapes() { clear(); } void RenderShapes::clear() { scene_shapes_.clear(); for (std::size_t i = 0 ; i < movable_objects_.size() ; ++i) context_->getSceneManager()->destroyMovableObject(movable_objects_[i]); movable_objects_.clear(); for (std::size_t i = 0; i < materials_.size(); ++i) { materials_[i]->unload(); Ogre::MaterialManager::getSingleton().remove(materials_[i]->getName()); } materials_.clear(); octree_voxel_grids_.clear(); } void RenderShapes::renderShape(Ogre::SceneNode *node, const shapes::Shape *s, const Eigen::Affine3d &p, OctreeVoxelRenderMode octree_voxel_rendering, OctreeVoxelColorMode octree_color_mode, const rviz::Color &color, float alpha) { rviz::Shape* ogre_shape = NULL; switch (s->type) { case shapes::SPHERE: { ogre_shape = new rviz::Shape(rviz::Shape::Sphere, context_->getSceneManager(), node); double d = 2.0 * static_cast<const shapes::Sphere*>(s)->radius; ogre_shape->setScale(Ogre::Vector3(d, d, d)); } break; case shapes::BOX: { ogre_shape = new rviz::Shape(rviz::Shape::Cube, context_->getSceneManager(), node); const double* sz = static_cast<const shapes::Box*>(s)->size; ogre_shape->setScale(Ogre::Vector3(sz[0], sz[1], sz[2])); } break; case shapes::CYLINDER: { ogre_shape = new rviz::Shape(rviz::Shape::Cylinder, context_->getSceneManager(), node); double d = 2.0 * static_cast<const shapes::Cylinder*>(s)->radius; double z = static_cast<const shapes::Cylinder*>(s)->length; ogre_shape->setScale(Ogre::Vector3(d, z, d)); // the shape has z as major axis, but the rendered cylinder has y as major axis (assuming z is upright); } break; case shapes::MESH: { const shapes::Mesh *mesh = static_cast<const shapes::Mesh*>(s); if (mesh->triangle_count > 0) { //construct the material std::string mname = "Planning Scene Display Mesh Material " + boost::lexical_cast<std::string>(materials_.size()) + " @" + boost::lexical_cast<std::string>(this); Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create(mname, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); mat->setReceiveShadows(true); mat->getTechnique(0)->setLightingEnabled(true); mat->setCullingMode(Ogre::CULL_NONE); mat->getTechnique(0)->setAmbient(color.r_ * 0.2f, color.g_ * 0.2f, color.b_ * 0.2f); mat->getTechnique(0)->setDiffuse(color.r_, color.g_, color.b_, alpha); if (alpha < 0.9998) { mat->getTechnique(0)->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA ); mat->getTechnique(0)->setDepthWriteEnabled( false ); } else { mat->getTechnique(0)->setSceneBlending( Ogre::SBT_REPLACE ); mat->getTechnique(0)->setDepthWriteEnabled( true ); } materials_.push_back(mat); std::string name = "Planning Scene Display Mesh " + boost::lexical_cast<std::string>(movable_objects_.size()) + " @" + boost::lexical_cast<std::string>(this); Ogre::ManualObject *manual_object = context_->getSceneManager()->createManualObject(name); manual_object->estimateVertexCount(mesh->triangle_count * 3); manual_object->begin(materials_.back()->getName(), Ogre::RenderOperation::OT_TRIANGLE_LIST); Eigen::Vector3d normal(0.0, 0.0, 0.0); Eigen::Matrix3d rot = p.rotation(); for (unsigned int i = 0 ; i < mesh->triangle_count ; ++i) { unsigned int i3 = i * 3; if (mesh->triangle_normals && !mesh->vertex_normals) normal = rot * Eigen::Vector3d(mesh->triangle_normals[i3], mesh->triangle_normals[i3 + 1], mesh->triangle_normals[i3 + 2]); for (int k = 0 ; k < 3 ; ++k) { unsigned int vi = 3 * mesh->triangles[i3 + k]; Eigen::Vector3d v = p * Eigen::Vector3d(mesh->vertices[vi], mesh->vertices[vi + 1], mesh->vertices[vi + 2]); manual_object->position(v.x(), v.y(), v.z()); if (mesh->vertex_normals) { normal = rot * Eigen::Vector3d(mesh->vertex_normals[vi], mesh->vertex_normals[vi + 1], mesh->vertex_normals[vi + 2]); manual_object->normal(normal.x(), normal.y(), normal.z()); } else if (mesh->triangle_normals) manual_object->normal(normal.x(), normal.y(), normal.z()); } } manual_object->end(); node->attachObject(manual_object); movable_objects_.push_back(manual_object); } } break; case shapes::OCTREE: { boost::shared_ptr<OcTreeRender> octree(new OcTreeRender(static_cast<const shapes::OcTree*>(s)->octree, octree_voxel_rendering, octree_color_mode, 0u, context_->getSceneManager(), node)); octree_voxel_grids_.push_back(octree); } break; default: break; } if (ogre_shape) { ogre_shape->setColor(color.r_, color.g_, color.b_, alpha); Ogre::Vector3 position(p.translation().x(), p.translation().y(), p.translation().z()); Eigen::Quaterniond q(p.rotation()); Ogre::Quaternion orientation(q.w(), q.x(), q.y(), q.z()); if (s->type == shapes::CYLINDER) { // in geometric shapes, the z axis of the cylinder is it height; // for the rviz shape, the y axis is the height; we add a transform to fix this static Ogre::Quaternion fix(Ogre::Radian(boost::math::constants::pi<double>()/2.0), Ogre::Vector3(1.0, 0.0, 0.0)); orientation = orientation * fix; } ogre_shape->setPosition(position); ogre_shape->setOrientation(orientation); scene_shapes_.push_back(boost::shared_ptr<rviz::Shape>(ogre_shape)); } } } <commit_msg>add ability to render cones<commit_after>/* * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* Author: Ioan Sucan */ #include <moveit/rviz_plugin_render_tools/render_shapes.h> #include <moveit/rviz_plugin_render_tools/octomap_render.h> #include <geometric_shapes/mesh_operations.h> #include <OGRE/OgreSceneNode.h> #include <OGRE/OgreSceneManager.h> #include <OGRE/OgreManualObject.h> #include <OGRE/OgreMaterialManager.h> #include <rviz/ogre_helpers/shape.h> #include <rviz/display_context.h> #include <rviz/robot/robot.h> #include <boost/lexical_cast.hpp> #include <boost/math/constants/constants.hpp> #include <boost/scoped_ptr.hpp> namespace moveit_rviz_plugin { RenderShapes::RenderShapes(rviz::DisplayContext *context) : context_(context) { } RenderShapes::~RenderShapes() { clear(); } void RenderShapes::clear() { scene_shapes_.clear(); for (std::size_t i = 0 ; i < movable_objects_.size() ; ++i) context_->getSceneManager()->destroyMovableObject(movable_objects_[i]); movable_objects_.clear(); for (std::size_t i = 0; i < materials_.size(); ++i) { materials_[i]->unload(); Ogre::MaterialManager::getSingleton().remove(materials_[i]->getName()); } materials_.clear(); octree_voxel_grids_.clear(); } void RenderShapes::renderShape(Ogre::SceneNode *node, const shapes::Shape *s, const Eigen::Affine3d &p, OctreeVoxelRenderMode octree_voxel_rendering, OctreeVoxelColorMode octree_color_mode, const rviz::Color &color, float alpha) { rviz::Shape* ogre_shape = NULL; // we don't know how to render cones directly, but we can convert them to a mesh if (s->type == shapes::CONE) { boost::scoped_ptr<shapes::Mesh> m(shapes::createMeshFromShape(static_cast<const shapes::Cone&>(*s))); if (m) renderShape(node, m.get(), p, octree_voxel_rendering, octree_color_mode, color, alpha); return; } switch (s->type) { case shapes::SPHERE: { ogre_shape = new rviz::Shape(rviz::Shape::Sphere, context_->getSceneManager(), node); double d = 2.0 * static_cast<const shapes::Sphere*>(s)->radius; ogre_shape->setScale(Ogre::Vector3(d, d, d)); } break; case shapes::BOX: { ogre_shape = new rviz::Shape(rviz::Shape::Cube, context_->getSceneManager(), node); const double* sz = static_cast<const shapes::Box*>(s)->size; ogre_shape->setScale(Ogre::Vector3(sz[0], sz[1], sz[2])); } break; case shapes::CYLINDER: { ogre_shape = new rviz::Shape(rviz::Shape::Cylinder, context_->getSceneManager(), node); double d = 2.0 * static_cast<const shapes::Cylinder*>(s)->radius; double z = static_cast<const shapes::Cylinder*>(s)->length; ogre_shape->setScale(Ogre::Vector3(d, z, d)); // the shape has z as major axis, but the rendered cylinder has y as major axis (assuming z is upright); } break; case shapes::MESH: { const shapes::Mesh *mesh = static_cast<const shapes::Mesh*>(s); if (mesh->triangle_count > 0) { //construct the material std::string mname = "Planning Scene Display Mesh Material " + boost::lexical_cast<std::string>(materials_.size()) + " @" + boost::lexical_cast<std::string>(this); Ogre::MaterialPtr mat = Ogre::MaterialManager::getSingleton().create(mname, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); mat->setReceiveShadows(true); mat->getTechnique(0)->setLightingEnabled(true); mat->setCullingMode(Ogre::CULL_NONE); mat->getTechnique(0)->setAmbient(color.r_ * 0.2f, color.g_ * 0.2f, color.b_ * 0.2f); mat->getTechnique(0)->setDiffuse(color.r_, color.g_, color.b_, alpha); if (alpha < 0.9998) { mat->getTechnique(0)->setSceneBlending( Ogre::SBT_TRANSPARENT_ALPHA ); mat->getTechnique(0)->setDepthWriteEnabled( false ); } else { mat->getTechnique(0)->setSceneBlending( Ogre::SBT_REPLACE ); mat->getTechnique(0)->setDepthWriteEnabled( true ); } materials_.push_back(mat); std::string name = "Planning Scene Display Mesh " + boost::lexical_cast<std::string>(movable_objects_.size()) + " @" + boost::lexical_cast<std::string>(this); Ogre::ManualObject *manual_object = context_->getSceneManager()->createManualObject(name); manual_object->estimateVertexCount(mesh->triangle_count * 3); manual_object->begin(materials_.back()->getName(), Ogre::RenderOperation::OT_TRIANGLE_LIST); Eigen::Vector3d normal(0.0, 0.0, 0.0); Eigen::Matrix3d rot = p.rotation(); for (unsigned int i = 0 ; i < mesh->triangle_count ; ++i) { unsigned int i3 = i * 3; if (mesh->triangle_normals && !mesh->vertex_normals) normal = rot * Eigen::Vector3d(mesh->triangle_normals[i3], mesh->triangle_normals[i3 + 1], mesh->triangle_normals[i3 + 2]); for (int k = 0 ; k < 3 ; ++k) { unsigned int vi = 3 * mesh->triangles[i3 + k]; Eigen::Vector3d v = p * Eigen::Vector3d(mesh->vertices[vi], mesh->vertices[vi + 1], mesh->vertices[vi + 2]); manual_object->position(v.x(), v.y(), v.z()); if (mesh->vertex_normals) { normal = rot * Eigen::Vector3d(mesh->vertex_normals[vi], mesh->vertex_normals[vi + 1], mesh->vertex_normals[vi + 2]); manual_object->normal(normal.x(), normal.y(), normal.z()); } else if (mesh->triangle_normals) manual_object->normal(normal.x(), normal.y(), normal.z()); } } manual_object->end(); node->attachObject(manual_object); movable_objects_.push_back(manual_object); } } break; case shapes::OCTREE: { boost::shared_ptr<OcTreeRender> octree(new OcTreeRender(static_cast<const shapes::OcTree*>(s)->octree, octree_voxel_rendering, octree_color_mode, 0u, context_->getSceneManager(), node)); octree_voxel_grids_.push_back(octree); } break; default: break; } if (ogre_shape) { ogre_shape->setColor(color.r_, color.g_, color.b_, alpha); Ogre::Vector3 position(p.translation().x(), p.translation().y(), p.translation().z()); Eigen::Quaterniond q(p.rotation()); Ogre::Quaternion orientation(q.w(), q.x(), q.y(), q.z()); if (s->type == shapes::CYLINDER) { // in geometric shapes, the z axis of the cylinder is it height; // for the rviz shape, the y axis is the height; we add a transform to fix this static Ogre::Quaternion fix(Ogre::Radian(boost::math::constants::pi<double>()/2.0), Ogre::Vector3(1.0, 0.0, 0.0)); orientation = orientation * fix; } ogre_shape->setPosition(position); ogre_shape->setOrientation(orientation); scene_shapes_.push_back(boost::shared_ptr<rviz::Shape>(ogre_shape)); } } } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/core/p9_hcd_core_stopclocks.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2017 */ /* [+] 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_hcd_core_stopclocks.C /// @brief Core Clock Stop /// /// Procedure Summary: // *HWP HWP Owner : David Du <[email protected]> // *HWP Backup HWP Owner : Greg Still <[email protected]> // *HWP FW Owner : Sangeetha T S <[email protected]> // *HWP Team : PM // *HWP Consumed by : HB:PREV // *HWP Level : 2 //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p9_misc_scom_addresses.H> #include <p9_quad_scom_addresses.H> #include <p9_hcd_common.H> #include <p9_common_clk_ctrl_state.H> #include "p9_hcd_core_stopclocks.H" //------------------------------------------------------------------------------ // Constant Definitions //------------------------------------------------------------------------------ enum P9_HCD_CORE_STOPCLOCKS_CONSTANTS { CORE_PCB_MUX_POLLING_HW_NS_DELAY = 10000, CORE_PCB_MUX_POLLING_SIM_CYCLE_DELAY = 320000, CORE_CLK_SYNC_POLLING_HW_NS_DELAY = 10000, CORE_CLK_SYNC_POLLING_SIM_CYCLE_DELAY = 320000, CORE_CLK_STOP_POLLING_HW_NS_DELAY = 10000, CORE_CLK_STOP_POLLING_SIM_CYCLE_DELAY = 320000 }; //------------------------------------------------------------------------------ // Procedure: Core Clock Stop //------------------------------------------------------------------------------ fapi2::ReturnCode p9_hcd_core_stopclocks( const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target) { FAPI_INF(">>p9_hcd_core_stopclocks"); fapi2::ReturnCode l_rc; fapi2::buffer<uint64_t> l_ccsr; fapi2::buffer<uint64_t> l_data64; fapi2::buffer<uint64_t> l_temp64; uint32_t l_loops1ms; uint8_t l_attr_chip_unit_pos; uint8_t l_attr_vdm_enable; uint8_t l_attr_sdisn_setup; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_sys; auto l_quad = i_target.getParent<fapi2::TARGET_TYPE_EQ>(); auto l_perv = i_target.getParent<fapi2::TARGET_TYPE_PERV>(); auto l_chip = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_SDISN_SETUP, l_chip, l_attr_sdisn_setup)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_VDM_ENABLE, l_sys, l_attr_vdm_enable)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_perv, l_attr_chip_unit_pos)); l_attr_chip_unit_pos = (l_attr_chip_unit_pos - p9hcd::PERV_TO_CORE_POS_OFFSET) % 4; // ---------------------------- // Prepare to stop core clocks // ---------------------------- FAPI_DBG("Check PM_RESET_STATE_INDICATOR via GPMMR[15]"); FAPI_TRY(getScom(i_target, C_PPM_GPMMR_SCOM, l_data64)); if (!l_data64.getBit<15>()) { FAPI_DBG("Gracefully turn off power management, continue anyways if fail"); /// @todo RTC158181 suspend_pm() } FAPI_DBG("Check core clock controller status"); l_rc = p9_common_clk_ctrl_state<fapi2::TARGET_TYPE_CORE>(i_target); if (l_rc) { FAPI_INF("Clock controller of this core chiplet is inaccessible, return"); goto fapi_try_exit; } FAPI_DBG("Check cache clock controller status"); l_rc = p9_common_clk_ctrl_state<fapi2::TARGET_TYPE_EQ>(l_quad); if (l_rc) { FAPI_INF("WARNING: core is enabled while cache is not, continue anyways"); } else { FAPI_DBG("Check PERV clock status for access to CME via CLOCK_STAT[4]"); FAPI_TRY(getScom(l_quad, EQ_CLOCK_STAT_SL, l_data64)); FAPI_DBG("Check PERV fence status for access to CME via CPLT_CTRL1[4]"); FAPI_TRY(getScom(l_quad, EQ_CPLT_CTRL1, l_temp64)); if (l_data64.getBit<4>() == 0 && l_temp64.getBit<4>() == 0) { //halt cme(poll for halted, if timeout, print warnning keep going). FAPI_DBG("Assert Core-L2/CC Quiesces via CME_SCOM_SICR[6,8]/[7,9]"); FAPI_TRY(putScom(l_quad, (l_attr_chip_unit_pos < 2) ? EX_0_CME_SCOM_SICR_OR : EX_1_CME_SCOM_SICR_OR, (BIT64(6 + (l_attr_chip_unit_pos % 2)) | BIT64(8 + (l_attr_chip_unit_pos % 2))))); } } FAPI_DBG("Assert pm_mux_disable to get PCB Mux from CME via SLAVE_CONFIG[7]"); FAPI_TRY(getScom(i_target, C_SLAVE_CONFIG_REG, l_data64)); FAPI_TRY(putScom(i_target, C_SLAVE_CONFIG_REG, DATA_SET(7))); FAPI_DBG("Override possible PPM write protection to CME via CPPM_CPMMR[1]"); FAPI_TRY(putScom(i_target, C_CPPM_CPMMR_OR, MASK_SET(1))); FAPI_DBG("Assert chiplet fence via NET_CTRL0[18]"); FAPI_TRY(putScom(i_target, C_NET_CTRL0_WOR, MASK_SET(18))); // ------------------------------- // Stop core clocks // ------------------------------- FAPI_DBG("Clear all SCAN_REGION_TYPE bits"); FAPI_TRY(putScom(i_target, C_SCAN_REGION_TYPE, MASK_ZERO)); FAPI_DBG("Stop core clocks(all but pll) via CLK_REGION"); l_data64 = (p9hcd::CLK_STOP_CMD | p9hcd::CLK_REGION_ALL_BUT_PLL | p9hcd::CLK_THOLD_ALL); FAPI_TRY(putScom(i_target, C_CLK_REGION, l_data64)); FAPI_DBG("Poll for core clocks stopped via CPLT_STAT0[8]"); l_loops1ms = 1E6 / CORE_CLK_STOP_POLLING_HW_NS_DELAY; do { fapi2::delay(CORE_CLK_STOP_POLLING_HW_NS_DELAY, CORE_CLK_STOP_POLLING_SIM_CYCLE_DELAY); FAPI_TRY(getScom(i_target, C_CPLT_STAT0, l_data64)); } while((l_data64.getBit<8>() != 1) && ((--l_loops1ms) != 0)); FAPI_ASSERT((l_loops1ms != 0), fapi2::PMPROC_CORECLKSTOP_TIMEOUT().set_CORECPLTSTAT(l_data64), "Core Clock Stop Timeout"); FAPI_DBG("Check core clocks stopped via CLOCK_STAT_SL[4-13]"); FAPI_TRY(getScom(i_target, C_CLOCK_STAT_SL, l_data64)); FAPI_ASSERT((((~l_data64) & p9hcd::CLK_REGION_ALL_BUT_PLL) == 0), fapi2::PMPROC_CORECLKSTOP_FAILED().set_CORECLKSTAT(l_data64), "Core Clock Stop Failed"); FAPI_DBG("Core clocks stopped now"); // ------------------------------- // Disable core clock sync // ------------------------------- FAPI_DBG("Drop core clock sync enable via CPPM_CACCR[15]"); FAPI_TRY(putScom(i_target, C_CPPM_CACCR_CLEAR, MASK_SET(15))); FAPI_DBG("Poll for core clock sync done to drop via CPPM_CACSR[13]"); l_loops1ms = 1E6 / CORE_CLK_SYNC_POLLING_HW_NS_DELAY; do { fapi2::delay(CORE_CLK_SYNC_POLLING_HW_NS_DELAY, CORE_CLK_SYNC_POLLING_SIM_CYCLE_DELAY); FAPI_TRY(getScom(i_target, C_CPPM_CACSR, l_data64)); } while((l_data64.getBit<13>() == 1) && ((--l_loops1ms) != 0)); FAPI_ASSERT((l_loops1ms != 0), fapi2::PMPROC_CORECLKSYNCDROP_TIMEOUT().set_COREPPMCACSR(l_data64), "Core Clock Sync Drop Timeout"); FAPI_DBG("Core clock sync done dropped"); // ------------------------------- // Fence up // ------------------------------- FAPI_DBG("Assert skew sense to skew adjust fence via NET_CTRL0[22]"); FAPI_TRY(putScom(i_target, C_NET_CTRL0_WOR, MASK_SET(22))); FAPI_DBG("Assert vital fence via CPLT_CTRL1[3]"); FAPI_TRY(putScom(i_target, C_CPLT_CTRL1_OR, MASK_SET(3))); FAPI_DBG("Assert regional fences via CPLT_CTRL1[4-14]"); FAPI_TRY(putScom(i_target, C_CPLT_CTRL1_OR, p9hcd::CLK_REGION_ALL)); if (l_attr_sdisn_setup) { FAPI_DBG("DD1 Only: Drop sdis_n(flushing LCBES condition) vai CPLT_CONF0[34]"); FAPI_TRY(putScom(i_target, C_CPLT_CONF0_CLEAR, MASK_SET(34))); } // ------------------------------- // Disable VDM // ------------------------------- if (l_attr_vdm_enable == fapi2::ENUM_ATTR_VDM_ENABLE_ON) { FAPI_DBG("Drop vdm enable via CPPM_VDMCR[0]"); FAPI_TRY(putScom(i_target, C_PPM_VDMCR_CLEAR, MASK_SET(0))); } // ------------------------------- // Update stop history // ------------------------------- FAPI_DBG("Set core as stopped in STOP history register"); FAPI_TRY(putScom(i_target, C_PPM_SSHSRC, BIT64(0))); // ------------------------------- // Clean up // ------------------------------- FAPI_DBG("Return possible PPM write protection to CME via CPPM_CPMMR[1]"); FAPI_TRY(putScom(i_target, C_CPPM_CPMMR_CLEAR, MASK_SET(1))); FAPI_DBG("Drop pm_mux_disable to release PCB Mux via SLAVE_CONFIG[7]"); FAPI_TRY(getScom(i_target, C_SLAVE_CONFIG_REG, l_data64)); FAPI_TRY(putScom(i_target, C_SLAVE_CONFIG_REG, DATA_UNSET(7))); fapi_try_exit: FAPI_INF("<<p9_hcd_core_stopclocks"); return fapi2::current_err; } <commit_msg>IPL/Stop: Assert ABIST_SRAM_MODE_DC to support ABIST Recovery<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/core/p9_hcd_core_stopclocks.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2017 */ /* [+] 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_hcd_core_stopclocks.C /// @brief Core Clock Stop /// /// Procedure Summary: // *HWP HWP Owner : David Du <[email protected]> // *HWP Backup HWP Owner : Greg Still <[email protected]> // *HWP FW Owner : Sangeetha T S <[email protected]> // *HWP Team : PM // *HWP Consumed by : HB:PREV // *HWP Level : 2 //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p9_misc_scom_addresses.H> #include <p9_quad_scom_addresses.H> #include <p9_hcd_common.H> #include <p9_common_clk_ctrl_state.H> #include "p9_hcd_core_stopclocks.H" //------------------------------------------------------------------------------ // Constant Definitions //------------------------------------------------------------------------------ enum P9_HCD_CORE_STOPCLOCKS_CONSTANTS { CORE_PCB_MUX_POLLING_HW_NS_DELAY = 10000, CORE_PCB_MUX_POLLING_SIM_CYCLE_DELAY = 320000, CORE_CLK_SYNC_POLLING_HW_NS_DELAY = 10000, CORE_CLK_SYNC_POLLING_SIM_CYCLE_DELAY = 320000, CORE_CLK_STOP_POLLING_HW_NS_DELAY = 10000, CORE_CLK_STOP_POLLING_SIM_CYCLE_DELAY = 320000 }; //------------------------------------------------------------------------------ // Procedure: Core Clock Stop //------------------------------------------------------------------------------ fapi2::ReturnCode p9_hcd_core_stopclocks( const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target) { FAPI_INF(">>p9_hcd_core_stopclocks"); fapi2::ReturnCode l_rc; fapi2::buffer<uint64_t> l_ccsr; fapi2::buffer<uint64_t> l_data64; fapi2::buffer<uint64_t> l_temp64; uint32_t l_loops1ms; uint8_t l_attr_chip_unit_pos; uint8_t l_attr_vdm_enable; uint8_t l_attr_sdisn_setup; const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_sys; auto l_quad = i_target.getParent<fapi2::TARGET_TYPE_EQ>(); auto l_perv = i_target.getParent<fapi2::TARGET_TYPE_PERV>(); auto l_chip = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_SDISN_SETUP, l_chip, l_attr_sdisn_setup)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_VDM_ENABLE, l_sys, l_attr_vdm_enable)); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_perv, l_attr_chip_unit_pos)); l_attr_chip_unit_pos = (l_attr_chip_unit_pos - p9hcd::PERV_TO_CORE_POS_OFFSET) % 4; // ---------------------------- // Prepare to stop core clocks // ---------------------------- FAPI_DBG("Check PM_RESET_STATE_INDICATOR via GPMMR[15]"); FAPI_TRY(getScom(i_target, C_PPM_GPMMR_SCOM, l_data64)); if (!l_data64.getBit<15>()) { FAPI_DBG("Gracefully turn off power management, continue anyways if fail"); /// @todo RTC158181 suspend_pm() } FAPI_DBG("Check core clock controller status"); l_rc = p9_common_clk_ctrl_state<fapi2::TARGET_TYPE_CORE>(i_target); if (l_rc) { FAPI_INF("Clock controller of this core chiplet is inaccessible, return"); goto fapi_try_exit; } FAPI_DBG("Check cache clock controller status"); l_rc = p9_common_clk_ctrl_state<fapi2::TARGET_TYPE_EQ>(l_quad); if (l_rc) { FAPI_INF("WARNING: core is enabled while cache is not, continue anyways"); } else { FAPI_DBG("Check PERV clock status for access to CME via CLOCK_STAT[4]"); FAPI_TRY(getScom(l_quad, EQ_CLOCK_STAT_SL, l_data64)); FAPI_DBG("Check PERV fence status for access to CME via CPLT_CTRL1[4]"); FAPI_TRY(getScom(l_quad, EQ_CPLT_CTRL1, l_temp64)); if (l_data64.getBit<4>() == 0 && l_temp64.getBit<4>() == 0) { //halt cme(poll for halted, if timeout, print warnning keep going). FAPI_DBG("Assert Core-L2/CC Quiesces via CME_SCOM_SICR[6,8]/[7,9]"); FAPI_TRY(putScom(l_quad, (l_attr_chip_unit_pos < 2) ? EX_0_CME_SCOM_SICR_OR : EX_1_CME_SCOM_SICR_OR, (BIT64(6 + (l_attr_chip_unit_pos % 2)) | BIT64(8 + (l_attr_chip_unit_pos % 2))))); } } FAPI_DBG("Assert pm_mux_disable to get PCB Mux from CME via SLAVE_CONFIG[7]"); FAPI_TRY(getScom(i_target, C_SLAVE_CONFIG_REG, l_data64)); FAPI_TRY(putScom(i_target, C_SLAVE_CONFIG_REG, DATA_SET(7))); FAPI_DBG("Override possible PPM write protection to CME via CPPM_CPMMR[1]"); FAPI_TRY(putScom(i_target, C_CPPM_CPMMR_OR, MASK_SET(1))); FAPI_DBG("Assert chiplet fence via NET_CTRL0[18]"); FAPI_TRY(putScom(i_target, C_NET_CTRL0_WOR, MASK_SET(18))); // ------------------------------- // Stop core clocks // ------------------------------- FAPI_DBG("Clear all SCAN_REGION_TYPE bits"); FAPI_TRY(putScom(i_target, C_SCAN_REGION_TYPE, MASK_ZERO)); FAPI_DBG("Stop core clocks(all but pll) via CLK_REGION"); l_data64 = (p9hcd::CLK_STOP_CMD | p9hcd::CLK_REGION_ALL_BUT_PLL | p9hcd::CLK_THOLD_ALL); FAPI_TRY(putScom(i_target, C_CLK_REGION, l_data64)); FAPI_DBG("Poll for core clocks stopped via CPLT_STAT0[8]"); l_loops1ms = 1E6 / CORE_CLK_STOP_POLLING_HW_NS_DELAY; do { fapi2::delay(CORE_CLK_STOP_POLLING_HW_NS_DELAY, CORE_CLK_STOP_POLLING_SIM_CYCLE_DELAY); FAPI_TRY(getScom(i_target, C_CPLT_STAT0, l_data64)); } while((l_data64.getBit<8>() != 1) && ((--l_loops1ms) != 0)); FAPI_ASSERT((l_loops1ms != 0), fapi2::PMPROC_CORECLKSTOP_TIMEOUT().set_CORECPLTSTAT(l_data64), "Core Clock Stop Timeout"); FAPI_DBG("Check core clocks stopped via CLOCK_STAT_SL[4-13]"); FAPI_TRY(getScom(i_target, C_CLOCK_STAT_SL, l_data64)); FAPI_ASSERT((((~l_data64) & p9hcd::CLK_REGION_ALL_BUT_PLL) == 0), fapi2::PMPROC_CORECLKSTOP_FAILED().set_CORECLKSTAT(l_data64), "Core Clock Stop Failed"); FAPI_DBG("Core clocks stopped now"); // ------------------------------- // Disable core clock sync // ------------------------------- FAPI_DBG("Drop core clock sync enable via CPPM_CACCR[15]"); FAPI_TRY(putScom(i_target, C_CPPM_CACCR_CLEAR, MASK_SET(15))); FAPI_DBG("Poll for core clock sync done to drop via CPPM_CACSR[13]"); l_loops1ms = 1E6 / CORE_CLK_SYNC_POLLING_HW_NS_DELAY; do { fapi2::delay(CORE_CLK_SYNC_POLLING_HW_NS_DELAY, CORE_CLK_SYNC_POLLING_SIM_CYCLE_DELAY); FAPI_TRY(getScom(i_target, C_CPPM_CACSR, l_data64)); } while((l_data64.getBit<13>() == 1) && ((--l_loops1ms) != 0)); FAPI_ASSERT((l_loops1ms != 0), fapi2::PMPROC_CORECLKSYNCDROP_TIMEOUT().set_COREPPMCACSR(l_data64), "Core Clock Sync Drop Timeout"); FAPI_DBG("Core clock sync done dropped"); // ------------------------------- // Fence up // ------------------------------- FAPI_DBG("Assert skew sense to skew adjust fence via NET_CTRL0[22]"); FAPI_TRY(putScom(i_target, C_NET_CTRL0_WOR, MASK_SET(22))); FAPI_DBG("Drop ABIST_SRAM_MODE_DC to support ABIST Recovery via BIST[1]"); FAPI_TRY(getScom(i_target, C_BIST, l_data64)); FAPI_TRY(putScom(i_target, C_BIST, DATA_UNSET(1))); FAPI_DBG("Assert vital fence via CPLT_CTRL1[3]"); FAPI_TRY(putScom(i_target, C_CPLT_CTRL1_OR, MASK_SET(3))); FAPI_DBG("Assert regional fences via CPLT_CTRL1[4-14]"); FAPI_TRY(putScom(i_target, C_CPLT_CTRL1_OR, p9hcd::CLK_REGION_ALL)); if (l_attr_sdisn_setup) { FAPI_DBG("DD1 Only: Drop sdis_n(flushing LCBES condition) vai CPLT_CONF0[34]"); FAPI_TRY(putScom(i_target, C_CPLT_CONF0_CLEAR, MASK_SET(34))); } // ------------------------------- // Disable VDM // ------------------------------- if (l_attr_vdm_enable == fapi2::ENUM_ATTR_VDM_ENABLE_ON) { FAPI_DBG("Drop vdm enable via CPPM_VDMCR[0]"); FAPI_TRY(putScom(i_target, C_PPM_VDMCR_CLEAR, MASK_SET(0))); } // ------------------------------- // Update stop history // ------------------------------- FAPI_DBG("Set core as stopped in STOP history register"); FAPI_TRY(putScom(i_target, C_PPM_SSHSRC, BIT64(0))); // ------------------------------- // Clean up // ------------------------------- FAPI_DBG("Return possible PPM write protection to CME via CPPM_CPMMR[1]"); FAPI_TRY(putScom(i_target, C_CPPM_CPMMR_CLEAR, MASK_SET(1))); FAPI_DBG("Drop pm_mux_disable to release PCB Mux via SLAVE_CONFIG[7]"); FAPI_TRY(getScom(i_target, C_SLAVE_CONFIG_REG, l_data64)); FAPI_TRY(putScom(i_target, C_SLAVE_CONFIG_REG, DATA_UNSET(7))); fapi_try_exit: FAPI_INF("<<p9_hcd_core_stopclocks"); return fapi2::current_err; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_post_trainadv.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_io_xbus_post_trainadv.H /// @brief Post-Training PHY Status Function. /// ///----------------------------------------------------------------------------- /// *HWP HWP Owner : Chris Steffen <[email protected]> /// *HWP HWP Backup Owner : Gary Peterson <[email protected]> /// *HWP FW Owner : Jamie Knight <[email protected]> /// *HWP Team : IO /// *HWP Level : 2 /// *HWP Consumed by : FSP:HB ///----------------------------------------------------------------------------- /// /// @verbatim /// High-level procedure flow: /// /// Post-Training PHY Status Function. /// /// Procedure Prereq: /// - System clocks are running. /// - Scominit Procedure is completed. /// - IO DCCAL Procedure is completed. /// - IO Run Training Procedure is completed. /// @endverbatim ///---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------------- #include "p9_io_xbus_post_trainadv.H" #include <p9_io_scom.H> #include <p9_io_regs.H> // ---------------------------------------------------------------------------- // Procedure Function // ---------------------------------------------------------------------------- fapi2::ReturnCode getDebugInfo( const fapi2::Target<fapi2::TARGET_TYPE_XBUS> i_tgt, const uint8_t i_grp ) { FAPI_IMP("Entering..."); FAPI_IMP("Exiting..."); return fapi2::current_err; } fapi2::ReturnCode checkEyeWidth( const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_tgt, const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_ctgt, const uint8_t i_grp ) { FAPI_IMP("Entering..."); const uint32_t ONE_MS = 1000000; // 1,000,000ns = 1ms const uint32_t DELAY_NS = 100 * ONE_MS; // Delay for 100ms const uint32_t DELAY_CYCLES = 1; // We won't be using this feature in sim. const uint8_t LN0 = 0; uint64_t data64 = 0; uint8_t minMfgEyeWidth = 0; char tgt_str[fapi2::MAX_ECMD_STRING_LEN]; fapi2::toString(i_tgt, tgt_str, fapi2::MAX_ECMD_STRING_LEN); // Get the minimum manufacturing eye width FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_IO_X_MFG_MIN_EYE_WIDTH, i_tgt, minMfgEyeWidth ) ); // We need to wait for each lane to get through recal before the historical eye // width values will be valid. At 2ms per lane * 17 lanes = 34ms. To be safe // we want this number to get through a few times. We will wait 100ms FAPI_TRY(fapi2::delay(DELAY_NS, DELAY_CYCLES)); // Read the historical minimum eye width FAPI_TRY( io::read( EDIP_RX_CTL_CNTL13_EO_PG, i_tgt, i_grp, LN0, data64 ), "Reading EDI+ RX CTL CNTL13 EO PG Failed" ); FAPI_DBG( "tgt(%s:g%d) Min Eye Width(%d) Lane(%d) Valid(%d) :: MinMfgEyeWidth(%d)", tgt_str, i_grp, io::get( EDIP_RX_HIST_MIN_EYE_WIDTH , data64 ), io::get( EDIP_RX_HIST_MIN_EYE_WIDTH_LANE , data64 ), io::get( EDIP_RX_HIST_MIN_EYE_WIDTH_VALID, data64 ), minMfgEyeWidth ); // Check if the historical eye width is less then the manufacturing minimum eye width FAPI_ASSERT( ( io::get( EDIP_RX_HIST_MIN_EYE_WIDTH, data64 ) >= minMfgEyeWidth ), fapi2::IO_XBUS_MFG_RX_EYE_WIDTH_FAILURE().set_RXTARGET(i_tgt) .set_TXTARGET(i_ctgt).set_GROUP(i_grp) .set_EYE_WIDTH( io::get( EDIP_RX_HIST_MIN_EYE_WIDTH, data64 ) ) .set_EYE_WIDTH_LANE( io::get( EDIP_RX_HIST_MIN_EYE_WIDTH_LANE, data64 ) ) .set_EYE_WIDTH_VALID( io::get( EDIP_RX_HIST_MIN_EYE_WIDTH_VALID, data64 ) ) .set_MIN_EYE_WIDTH( minMfgEyeWidth ), "I/O EDI+ Xbus Manufacturing Eye Width Failure." ); fapi_try_exit: FAPI_IMP("Exiting..."); return fapi2::current_err; } /** * @brief A simple HWP that runs after io_run_trainig. * This function is called on every Xbus. * @param[in] i_target Fapi2 Target * @param[in] i_group Clock Group * @param[in] i_ctarget Fapi2 Connected Target * @param[in] i_cgroup Connected Clock Group * @retval ReturnCode */ fapi2::ReturnCode p9_io_xbus_post_trainadv( const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_tgt, const uint8_t& i_grp, const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_ctgt, const uint8_t& i_cgrp) { FAPI_IMP("Entering..."); uint8_t l_status = 0x0; char tgt_str[fapi2::MAX_ECMD_STRING_LEN]; fapi2::toString(i_tgt, tgt_str, fapi2::MAX_ECMD_STRING_LEN); FAPI_INF("Checking %s:g%d Post Link Training.", tgt_str, i_grp); // Get Debug Info FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IO_X_DEBUG, i_tgt, l_status)); if(l_status == fapi2::ENUM_ATTR_IO_X_DEBUG_TRUE) { FAPI_TRY( getDebugInfo( i_tgt, i_grp ) ); FAPI_TRY( getDebugInfo( i_ctgt, i_cgrp ) ); } // Run Manufacturing Eye Width Check FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IO_X_MFG_CHK, i_tgt, l_status)); if(l_status == fapi2::ENUM_ATTR_IO_X_MFG_CHK_TRUE) { FAPI_TRY( checkEyeWidth( i_tgt, i_ctgt, i_grp ) ); FAPI_TRY( checkEyeWidth( i_ctgt, i_tgt, i_cgrp ) ); } fapi_try_exit: FAPI_IMP("Exiting..."); return fapi2::current_err; } <commit_msg>I/O Metadata Cleanup<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_xbus_post_trainadv.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_io_xbus_post_trainadv.H /// @brief Post-Training PHY Status Function. /// ///----------------------------------------------------------------------------- /// *HWP HWP Owner : Chris Steffen <[email protected]> /// *HWP HWP Backup Owner : Gary Peterson <[email protected]> /// *HWP FW Owner : Jamie Knight <[email protected]> /// *HWP Team : IO /// *HWP Level : 3 /// *HWP Consumed by : FSP:HB ///----------------------------------------------------------------------------- /// /// @verbatim /// High-level procedure flow: /// /// Post-Training PHY Status Function. /// /// Procedure Prereq: /// - System clocks are running. /// - Scominit Procedure is completed. /// - IO DCCAL Procedure is completed. /// - IO Run Training Procedure is completed. /// @endverbatim ///---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Includes // ---------------------------------------------------------------------------- #include "p9_io_xbus_post_trainadv.H" #include <p9_io_scom.H> #include <p9_io_regs.H> // ---------------------------------------------------------------------------- // Procedure Function // ---------------------------------------------------------------------------- fapi2::ReturnCode getDebugInfo( const fapi2::Target<fapi2::TARGET_TYPE_XBUS> i_tgt, const uint8_t i_grp ) { FAPI_IMP("Entering..."); FAPI_IMP("Exiting..."); return fapi2::current_err; } fapi2::ReturnCode checkEyeWidth( const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_tgt, const fapi2::Target<fapi2::TARGET_TYPE_XBUS>& i_ctgt, const uint8_t i_grp ) { FAPI_IMP("Entering..."); const uint32_t ONE_MS = 1000000; // 1,000,000ns = 1ms const uint32_t DELAY_NS = 100 * ONE_MS; // Delay for 100ms const uint32_t DELAY_CYCLES = 1; // We won't be using this feature in sim. const uint8_t LN0 = 0; uint64_t data64 = 0; uint8_t minMfgEyeWidth = 0; char tgt_str[fapi2::MAX_ECMD_STRING_LEN]; fapi2::toString(i_tgt, tgt_str, fapi2::MAX_ECMD_STRING_LEN); // Get the minimum manufacturing eye width FAPI_TRY( FAPI_ATTR_GET( fapi2::ATTR_IO_X_MFG_MIN_EYE_WIDTH, i_tgt, minMfgEyeWidth ) ); // We need to wait for each lane to get through recal before the historical eye // width values will be valid. At 2ms per lane * 17 lanes = 34ms. To be safe // we want this number to get through a few times. We will wait 100ms FAPI_TRY(fapi2::delay(DELAY_NS, DELAY_CYCLES)); // Read the historical minimum eye width FAPI_TRY( io::read( EDIP_RX_CTL_CNTL13_EO_PG, i_tgt, i_grp, LN0, data64 ), "Reading EDI+ RX CTL CNTL13 EO PG Failed" ); FAPI_DBG( "tgt(%s:g%d) Min Eye Width(%d) Lane(%d) Valid(%d) :: MinMfgEyeWidth(%d)", tgt_str, i_grp, io::get( EDIP_RX_HIST_MIN_EYE_WIDTH , data64 ), io::get( EDIP_RX_HIST_MIN_EYE_WIDTH_LANE , data64 ), io::get( EDIP_RX_HIST_MIN_EYE_WIDTH_VALID, data64 ), minMfgEyeWidth ); // Check if the historical eye width is less then the manufacturing minimum eye width FAPI_ASSERT( ( io::get( EDIP_RX_HIST_MIN_EYE_WIDTH, data64 ) >= minMfgEyeWidth ), fapi2::IO_XBUS_MFG_RX_EYE_WIDTH_FAILURE().set_RXTARGET(i_tgt) .set_TXTARGET(i_ctgt).set_GROUP(i_grp) .set_EYE_WIDTH( io::get( EDIP_RX_HIST_MIN_EYE_WIDTH, data64 ) ) .set_EYE_WIDTH_LANE( io::get( EDIP_RX_HIST_MIN_EYE_WIDTH_LANE, data64 ) ) .set_EYE_WIDTH_VALID( io::get( EDIP_RX_HIST_MIN_EYE_WIDTH_VALID, data64 ) ) .set_MIN_EYE_WIDTH( minMfgEyeWidth ), "I/O EDI+ Xbus Manufacturing Eye Width Failure." ); fapi_try_exit: FAPI_IMP("Exiting..."); return fapi2::current_err; } /** * @brief A simple HWP that runs after io_run_trainig. * This function is called on every Xbus. * @param[in] i_target Fapi2 Target * @param[in] i_group Clock Group * @param[in] i_ctarget Fapi2 Connected Target * @param[in] i_cgroup Connected Clock Group * @retval ReturnCode */ fapi2::ReturnCode p9_io_xbus_post_trainadv( const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_tgt, const uint8_t& i_grp, const fapi2::Target < fapi2::TARGET_TYPE_XBUS >& i_ctgt, const uint8_t& i_cgrp) { FAPI_IMP("Entering..."); uint8_t l_status = 0x0; char tgt_str[fapi2::MAX_ECMD_STRING_LEN]; fapi2::toString(i_tgt, tgt_str, fapi2::MAX_ECMD_STRING_LEN); FAPI_INF("Checking %s:g%d Post Link Training.", tgt_str, i_grp); // Get Debug Info FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IO_X_DEBUG, i_tgt, l_status)); if(l_status == fapi2::ENUM_ATTR_IO_X_DEBUG_TRUE) { FAPI_TRY( getDebugInfo( i_tgt, i_grp ) ); FAPI_TRY( getDebugInfo( i_ctgt, i_cgrp ) ); } // Run Manufacturing Eye Width Check FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IO_X_MFG_CHK, i_tgt, l_status)); if(l_status == fapi2::ENUM_ATTR_IO_X_MFG_CHK_TRUE) { FAPI_TRY( checkEyeWidth( i_tgt, i_ctgt, i_grp ) ); FAPI_TRY( checkEyeWidth( i_ctgt, i_tgt, i_cgrp ) ); } fapi_try_exit: FAPI_IMP("Exiting..."); return fapi2::current_err; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_pgpe.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 */ // *INDENT-OFF* /// /// @file p9_pm_recovery_ffdc_pgpe.C /// @brief Models PGPE platform for the FFDC collection of PM complex /// /// *HWP HWP Owner: Greg Still <[email protected]> /// *HWP FW Owner: Prem S Jha <[email protected]> /// *HWP Team: PM /// *HWP Level: 2 /// *HWP Consumed by: Hostboot // // *INDENT-OFF* //-------------------------------------------------------------------------- // Includes //-------------------------------------------------------------------------- #include <p9_pm_recovery_ffdc_pgpe.H> #include <p9_hcd_memmap_occ_sram.H> #include <p9_ppe_defs.H> #include <stddef.h> #include <endian.h> namespace p9_stop_recov_ffdc { PlatPgpe::PlatPgpe( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt ) : PlatPmComplex( i_procChipTgt, OCC_SRAM_PGPE_HEADER_ADDR, OCC_SRAM_PGPE_TRACE_START, OCC_SRAM_PGPE_DASHBOARD_START, PLAT_PGPE ) { } //---------------------------------------------------------------------- fapi2::ReturnCode PlatPgpe::collectFfdc( void * i_pHomerBuf ) { FAPI_DBG(">> PlatPgpe::collectFfdc"); fapi2::current_err = fapi2::FAPI2_RC_SUCCESS; fapi2::ReturnCode l_retCode = fapi2::FAPI2_RC_SUCCESS; uint8_t l_ffdcValdityVect = PPE_FFDC_ALL_VALID; uint8_t l_haltState = PPE_HALT_COND_UNKNOWN; uint8_t *l_pFfdcLoc = NULL; HomerFfdcRegion * l_pHomerFfdc = ( HomerFfdcRegion *)( (uint8_t *)i_pHomerBuf + FFDC_REGION_HOMER_BASE_OFFSET ); l_pFfdcLoc = (uint8_t *)(&l_pHomerFfdc->iv_pgpeFfdcRegion); //In case of error , invalidate FFDC in header. l_retCode = collectPpeState ( PGPE_BASE_ADDRESS, l_pFfdcLoc ); if ( l_retCode != fapi2::FAPI2_RC_SUCCESS ) { FAPI_ERR ( "Error collecting PGPE State" ); l_ffdcValdityVect &= ~PPE_STATE_VALID; } l_retCode = collectTrace( l_pFfdcLoc ); if( l_retCode ) { FAPI_ERR("Error in collecting PGPE Trace " ); l_ffdcValdityVect &= ~PPE_TRACE_VALID; } l_retCode = collectGlobals( l_pFfdcLoc ); if( l_retCode ) { FAPI_ERR("Error in collecting PGPE Globals" ); l_ffdcValdityVect &= ~PPE_DASHBOARD_VALID; } l_retCode = collectImageHeader( l_pFfdcLoc ); if( l_retCode ) { FAPI_ERR("Error in collecting PGPE Image header" ); l_ffdcValdityVect &= ~PPE_IMAGE_HEADER_VALID; } FAPI_TRY( updatePgpeFfdcHeader( l_pFfdcLoc, l_ffdcValdityVect, l_haltState ), "Failed To Update PGPE FFDC Header for PGPE " ); fapi_try_exit: FAPI_DBG("<< PlatPgpe::collectFfdc"); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatPgpe::collectTrace( uint8_t * i_pTraceBuf ) { FAPI_DBG(">> PlatPgpe::collectTrace" ); PpeFfdcLayout * l_pPgpeFfdc = ( PpeFfdcLayout *) ( i_pTraceBuf ); uint8_t * l_pTraceLoc = &l_pPgpeFfdc->iv_ppeTraces[0]; FAPI_TRY( PlatPmComplex::collectSramInfo ( PlatPmComplex::getProcChip(), l_pTraceLoc, TRACES, FFDC_PPE_TRACES_SIZE ), "Trace Collection Failed" ); fapi_try_exit: FAPI_DBG("<< PlatPgpe::collectTrace" ); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatPgpe::collectGlobals( uint8_t * i_pPgpeGlobals ) { FAPI_DBG(">> PlatPgpe::collectGlobals" ); PpeFfdcLayout * l_pPgpeFfdc = ( PpeFfdcLayout *) ( i_pPgpeGlobals ); uint8_t * l_pTraceLoc = &l_pPgpeFfdc->iv_ppeGlobals[0]; FAPI_TRY( PlatPmComplex::collectSramInfo ( PlatPmComplex::getProcChip(), l_pTraceLoc, DASH_BOARD_VAR, OCC_SRAM_PGPE_DASHBOARD_SIZE ), "Failed To Collect PGPE Global Variables" ); fapi_try_exit: FAPI_DBG("<< PlatPgpe::collectGlobals" ); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatPgpe::collectInternalReg( uint8_t * i_pPgpeIntReg ) { return fapi2::FAPI2_RC_SUCCESS; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatPgpe::collectImageHeader( uint8_t * i_pPgpeImgHdr ) { FAPI_DBG(">> PlatPgpe::collectImageHeader" ); PpeFfdcLayout *l_pPgpeFfdc = ( PpeFfdcLayout *) ( i_pPgpeImgHdr ); uint8_t * l_pTraceLoc = &l_pPgpeFfdc->iv_ppeImageHeader[0]; FAPI_TRY( PlatPmComplex::collectSramInfo ( PlatPmComplex::getProcChip(), l_pTraceLoc, IMAGE_HEADER, FFDC_PPE_IMG_HDR_SIZE ), "Failed To Collect PGPE Image Header" ); fapi_try_exit: FAPI_DBG("<< PlatPgpe::collectImageHeader" ); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatPgpe::updatePgpeFfdcHeader( uint8_t * i_pHomerBuf, bool i_ffdcValid, uint8_t i_haltState ) { FAPI_DBG(">> updatePgpeFfdcHeader" ); PpeFfdcHeader * l_pPgpeFfdcHdr = ( (PpeFfdcHeader *)(( PpeFfdcHdrRegion * ) i_pHomerBuf )); l_pPgpeFfdcHdr->iv_ppeMagicNumber = htobe32( FFDC_PGPE_MAGIC_NUM ); l_pPgpeFfdcHdr->iv_ppeNumber = 0; PlatPmComplex::updatePpeFfdcHeader( l_pPgpeFfdcHdr, i_ffdcValid, i_haltState ); FAPI_DBG("<< updatePgpeFfdcHeader" ); return fapi2::FAPI2_RC_SUCCESS; } //----------------------------------------------------------------------- extern "C" { fapi2::ReturnCode p9_pm_recovery_ffdc_pgpe( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP >& i_procChip, void * i_pFfdcBuf ) { FAPI_IMP(">> p9_pm_recovery_pgpe" ); PlatPgpe l_pgpeFfdc( i_procChip ); FAPI_TRY( l_pgpeFfdc.collectFfdc( i_pFfdcBuf ), "Failed To Collect PGPE FFDC" ); fapi_try_exit: FAPI_IMP("<< p9_pm_recovery_pgpe" ); return fapi2::current_err; } } }//namespace p9_stop_recov_ffdc ends <commit_msg>STOP Recovery: Misc infra. updates to enable PM FFDC in HOMER<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_pgpe.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 */ // *INDENT-OFF* /// /// @file p9_pm_recovery_ffdc_pgpe.C /// @brief Models PGPE platform for the FFDC collection of PM complex /// /// *HWP HWP Owner: Greg Still <[email protected]> /// *HWP FW Owner: Prem S Jha <[email protected]> /// *HWP Team: PM /// *HWP Level: 2 /// *HWP Consumed by: Hostboot // // *INDENT-OFF* //-------------------------------------------------------------------------- // Includes //-------------------------------------------------------------------------- #include <p9_pm_recovery_ffdc_pgpe.H> #include <p9_hcd_memmap_occ_sram.H> #include <p9_ppe_defs.H> #include <stddef.h> #include <endian.h> namespace p9_stop_recov_ffdc { PlatPgpe::PlatPgpe( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt ) : PlatPmComplex( i_procChipTgt, PLAT_PGPE, OCC_SRAM_PGPE_HEADER_ADDR, OCC_SRAM_PGPE_TRACE_START, OCC_SRAM_PGPE_DASHBOARD_START ) { } //---------------------------------------------------------------------- fapi2::ReturnCode PlatPgpe::init ( void* i_pHomerBuf ) { FAPI_DBG (">> PlatPgpe::init" ); FAPI_TRY ( collectFfdc( i_pHomerBuf, INIT), "Failed To init PGPE FFDC" ); fapi_try_exit: FAPI_DBG ("<< PlatPgpe::init" ); return fapi2::current_err; } //---------------------------------------------------------------------- fapi2::ReturnCode PlatPgpe::collectFfdc( void * i_pHomerBuf, uint8_t i_ffdcType ) { FAPI_DBG(">> PlatPgpe::collectFfdc: 0x%02X", i_ffdcType); fapi2::ReturnCode l_retCode = fapi2::FAPI2_RC_SUCCESS; HomerFfdcRegion * l_pHomerFfdc = ( HomerFfdcRegion *)( (uint8_t *)i_pHomerBuf + FFDC_REGION_HOMER_BASE_OFFSET ); uint8_t* l_pFfdcLoc = (uint8_t *)(&l_pHomerFfdc->iv_pgpeFfdcRegion); PpeFfdcHeader* l_pPgpeFfdcHdr = (PpeFfdcHeader*) l_pFfdcLoc; uint16_t l_ffdcValdityVect = l_pPgpeFfdcHdr->iv_sectionsValid; if ( i_ffdcType & INIT ) { // overwrite on init l_ffdcValdityVect = PPE_FFDC_INVALID; } //In case of error , invalidate FFDC in header. if ( i_ffdcType & PPE_HALT_STATE ) { l_ffdcValdityVect |= PPE_HALT_STATE_VALID; l_retCode = readPpeHaltState ( PGPE_BASE_ADDRESS, l_pFfdcLoc); if ( l_retCode != fapi2::FAPI2_RC_SUCCESS ) { FAPI_ERR ( "Error collecting PGPE Halt State" ); l_ffdcValdityVect &= ~PPE_HALT_STATE_VALID; } } if (i_ffdcType & PPE_STATE ) { l_ffdcValdityVect |= PPE_STATE_VALID; l_retCode = collectPpeState ( PGPE_BASE_ADDRESS, l_pFfdcLoc ); if ( l_retCode != fapi2::FAPI2_RC_SUCCESS ) { FAPI_ERR ( "Error collecting PGPE State" ); l_ffdcValdityVect &= ~PPE_STATE_VALID; } } if ( i_ffdcType & TRACES ) { l_ffdcValdityVect |= PPE_TRACE_VALID; l_retCode = collectTrace( l_pFfdcLoc ); if( l_retCode ) { FAPI_ERR("Error in collecting PGPE Trace " ); l_ffdcValdityVect &= ~PPE_TRACE_VALID; } } if ( i_ffdcType & DASH_BOARD_VAR ) { l_ffdcValdityVect |= PPE_DASHBOARD_VALID; l_retCode = collectGlobals( l_pFfdcLoc ); if( l_retCode ) { FAPI_ERR("Error in collecting PGPE Globals" ); l_ffdcValdityVect &= ~PPE_DASHBOARD_VALID; } } if ( i_ffdcType & IMAGE_HEADER ) { l_ffdcValdityVect |= PPE_IMAGE_HEADER_VALID; l_retCode = collectImageHeader( l_pFfdcLoc ); if( l_retCode ) { FAPI_ERR("Error in collecting PGPE Image header" ); l_ffdcValdityVect &= ~PPE_IMAGE_HEADER_VALID; } } FAPI_TRY( updatePgpeFfdcHeader( l_pFfdcLoc, l_ffdcValdityVect ), "Failed To Update PGPE FFDC Header for PGPE " ); if (l_ffdcValdityVect == PPE_FFDC_INVALID) setPmFfdcSectionValid ( i_pHomerBuf, PM_FFDC_PGPE_VALID, false ); else setPmFfdcSectionValid ( i_pHomerBuf, PM_FFDC_PGPE_VALID ); fapi_try_exit: FAPI_DBG("<< PlatPgpe::collectFfdc"); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatPgpe::collectTrace( uint8_t * i_pTraceBuf ) { FAPI_DBG(">> PlatPgpe::collectTrace" ); PpeFfdcLayout * l_pPgpeFfdc = ( PpeFfdcLayout *) ( i_pTraceBuf ); uint8_t * l_pTraceLoc = &l_pPgpeFfdc->iv_ppeTraces[0]; FAPI_TRY( PlatPmComplex::collectSramInfo ( PlatPmComplex::getProcChip(), l_pTraceLoc, TRACES, FFDC_PPE_TRACES_SIZE ), "Trace Collection Failed" ); fapi_try_exit: FAPI_DBG("<< PlatPgpe::collectTrace" ); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatPgpe::collectGlobals( uint8_t * i_pPgpeGlobals ) { FAPI_DBG(">> PlatPgpe::collectGlobals" ); PpeFfdcLayout * l_pPgpeFfdc = ( PpeFfdcLayout *) ( i_pPgpeGlobals ); uint8_t * l_pTraceLoc = &l_pPgpeFfdc->iv_ppeGlobals[0]; FAPI_TRY( PlatPmComplex::collectSramInfo ( PlatPmComplex::getProcChip(), l_pTraceLoc, DASH_BOARD_VAR, OCC_SRAM_PGPE_DASHBOARD_SIZE ), "Failed To Collect PGPE Global Variables" ); fapi_try_exit: FAPI_DBG("<< PlatPgpe::collectGlobals" ); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatPgpe::collectInternalReg( uint8_t * i_pPgpeIntReg ) { return fapi2::FAPI2_RC_SUCCESS; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatPgpe::collectImageHeader( uint8_t * i_pPgpeImgHdr ) { FAPI_DBG(">> PlatPgpe::collectImageHeader" ); PpeFfdcLayout *l_pPgpeFfdc = ( PpeFfdcLayout *) ( i_pPgpeImgHdr ); uint8_t * l_pTraceLoc = &l_pPgpeFfdc->iv_ppeImageHeader[0]; FAPI_TRY( PlatPmComplex::collectSramInfo ( PlatPmComplex::getProcChip(), l_pTraceLoc, IMAGE_HEADER, FFDC_PPE_IMG_HDR_SIZE ), "Failed To Collect PGPE Image Header" ); fapi_try_exit: FAPI_DBG("<< PlatPgpe::collectImageHeader" ); return fapi2::current_err; } //----------------------------------------------------------------------- fapi2::ReturnCode PlatPgpe::updatePgpeFfdcHeader( uint8_t* i_pHomerBuf, uint16_t i_sectionsValid ) { FAPI_DBG(">> updatePgpeFfdcHeader" ); PpeFfdcHeader * l_pPgpeFfdcHdr = ( (PpeFfdcHeader *)(( PpeFfdcHdrRegion * ) i_pHomerBuf )); l_pPgpeFfdcHdr->iv_ppeMagicNumber = htobe32( FFDC_PGPE_MAGIC_NUM ); l_pPgpeFfdcHdr->iv_ppeNumber = 0; updatePpeFfdcHeader ( l_pPgpeFfdcHdr, i_sectionsValid ); FAPI_DBG("<< updatePgpeFfdcHeader" ); return fapi2::FAPI2_RC_SUCCESS; } //----------------------------------------------------------------------- extern "C" { fapi2::ReturnCode p9_pm_recovery_ffdc_pgpe( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP >& i_procChip, void * i_pFfdcBuf ) { FAPI_IMP(">> p9_pm_recovery_pgpe" ); PlatPgpe l_pgpeFfdc( i_procChip ); FAPI_TRY( l_pgpeFfdc.collectFfdc( i_pFfdcBuf, (ALL & ~PPE_HALT_STATE) ), "Failed To Collect PGPE FFDC" ); fapi_try_exit: FAPI_IMP("<< p9_pm_recovery_pgpe" ); return fapi2::current_err; } } }//namespace p9_stop_recov_ffdc ends <|endoftext|>
<commit_before>#include "analogjoystick.hpp" void setupJoystick() { pinMode(joystickXADC, INPUT); pinMode(joystickXADC, INPUT); pinMode(joystickEnable, INPUT); digitalWrite(joystickEnable, HIGH); } /* void disableJoystick() { digitalWrite(joystickEnable, LOW); } */ void getJoystickReading(int* X, int* Y) { *X = analogRead(joystickXADC); *Y = analogRead(joystickYADC); } int sign(int n) { if(n > 0) { return 1; } return -1; } /* Get joystick position and turn it into motor velocities */ // // +y // -x +x // -y // void joystickSetMotors() { int xAxis = 0; int yAxis = 0; const int XMiddle = 1023 / 2; const int YMiddle = 1023 / 2; getJoystickReading(&xAxis, &yAxis); //shift 0 xAxis -= XMiddle; yAxis -= YMiddle; //make x go the right dir //xAxis *= -1; /* Apply deadzones */ if (abs(xAxis) < DEAD_ZONE) { xAxis = 0; } if (abs(yAxis) < DEAD_ZONE) { yAxis = 0; } /* Calculate drive outputs -- magic*/ //int leftVelocity = .5*float(yAxis) + 2 * sign(xAxis) * sqrt(abs(xAxis)); //int rightVelocity = .5*float(yAxis) - 2 * sign(xAxis) * sqrt(abs(xAxis)); int leftVelocity = yAxis + 3 * sign(xAxis) * sqrt(abs(xAxis)); int rightVelocity = yAxis - 3 * sign(xAxis) * sqrt(abs(xAxis)); /* Limit drive velcocities to vaild values and convert them to drive speeds and directions */ byte leftSpeed = min(abs(leftVelocity), 255); byte leftDir = (leftVelocity < 0) ? MC_MOTOR_REVERSE : MC_MOTOR_FORWARD; byte rightSpeed = min(abs(rightVelocity), 255); byte rightDir = (rightVelocity < 0) ? MC_MOTOR_REVERSE : MC_MOTOR_FORWARD; setLeftMotorDutyCycle(leftDir, leftSpeed); setRightMotorDutyCycle(rightDir, rightSpeed); } <commit_msg>John's joystick code<commit_after>#include "analogjoystick.hpp" void setupJoystick() { pinMode(joystickXADC, INPUT); pinMode(joystickXADC, INPUT); pinMode(joystickEnable, INPUT); digitalWrite(joystickEnable, HIGH); } /* void disableJoystick() { digitalWrite(joystickEnable, LOW); } */ void getJoystickReading(int* X, int* Y) { *X = analogRead(joystickXADC); *Y = analogRead(joystickYADC); } int sign(int n) { if(n > 0) { return 1; } return -1; } /* Get joystick position and turn it into motor velocities */ // // +y // -x +x // -y // void joystickSetMotors() { int xAxis = 0; int yAxis = 0; const int XMiddle = 1023 / 2; const int YMiddle = 1023 / 2; getJoystickReading(&xAxis, &yAxis); //shift 0 xAxis -= XMiddle; yAxis -= YMiddle; //make x go the right dir //xAxis *= -1; /* Apply deadzones */ if (abs(xAxis) < DEAD_ZONE) { xAxis = 0; } if (abs(yAxis) < DEAD_ZONE) { yAxis = 0; } /* Calculate drive outputs -- magic*/ //int leftVelocity = .5*float(yAxis) + 2 * sign(xAxis) * sqrt(abs(xAxis)); //int rightVelocity = .5*float(yAxis) - 2 * sign(xAxis) * sqrt(abs(xAxis)); //int leftVelocity = yAxis + 3 * sign(xAxis) * sqrt(abs(xAxis)); //int rightVelocity = yAxis - 3 * sign(xAxis) * sqrt(abs(xAxis)); int leftVelocity; int rightVelocity; if ((yAxis > xAxis)&&(xAxis >= 0)) { leftVelocity = 512; rightVelocity = 512 - xAxis/2; } else if ((yAxis <= xAxis)&&(yAxis > 0)) { leftVelocity = 256 + yAxis/2; rightVelocity = yAxis - 256; } else if ((-yAxis < xAxis)&&(yAxis <= 0)) { leftVelocity = 256 - yAxis; rightVelocity = -256 - yAxis/2; } else if ((-yAxis >= xAxis)&&(xAxis > 0)) { leftVelocity = -512 + xAxis/2; rightVelocity = -512; } else if ((yAxis < xAxis)&&(xAxis <= 0)) { leftVelocity = -512; rightVelocity = -512 - xAxis/2; } else if ((yAxis >= xAxis)&&(yAxis < 0)) { leftVelocity = -256 + yAxis/2; rightVelocity = -256 + yAxis; } else if ((-yAxis < xAxis)&&(yAxis >= 0)) { leftVelocity = -256 + yAxis; rightVelocity = 256 + yAxis/2; } else if ((-yAxis >= xAxis)&&(xAxis < 0)) { leftVelocity = 512 + xAxis/2; rightVelocity = 512; } leftVelocity = float(leftVelocity/2)*abs(float(xAxis + yAxis)/float(1023 - abs(xAxis - yAxis))); rightVelocity = float(rightVelocity/2)*abs(float(xAxis + yAxis)/float(1023 - abs(xAxis - yAxis))); /* Limit drive velcocities to vaild values and convert them to drive speeds and directions */ Serial.print("L/Rev: "); Serial.println(leftVelocity, DEC); Serial.print("R/Rev: "); Serial.println(rightVelocity, DEC); byte leftSpeed = min(abs(leftVelocity), 255); byte leftDir = (leftVelocity < 0) ? MC_MOTOR_REVERSE : MC_MOTOR_FORWARD; byte rightSpeed = min(abs(rightVelocity), 255); byte rightDir = (rightVelocity < 0) ? MC_MOTOR_REVERSE : MC_MOTOR_FORWARD; setLeftMotorDutyCycle(leftDir, leftSpeed); setRightMotorDutyCycle(rightDir, rightSpeed); } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #ifndef itkTestingStretchIntensityImageFilter_hxx #define itkTestingStretchIntensityImageFilter_hxx #include "itkTestingStretchIntensityImageFilter.h" #include "itkImageRegionIterator.h" #include "itkImageRegionConstIterator.h" #include "itkMath.h" namespace itk { namespace Testing { template <typename TInputImage, typename TOutputImage> StretchIntensityImageFilter<TInputImage, TOutputImage>::StretchIntensityImageFilter() : m_Scale(1.0) , m_Shift(0.0) , m_InputMinimum(NumericTraits<InputPixelType>::max()) , m_InputMaximum(NumericTraits<InputPixelType>::ZeroValue()) , m_OutputMinimum(NumericTraits<OutputPixelType>::NonpositiveMin()) , m_OutputMaximum(NumericTraits<OutputPixelType>::max()) { this->DynamicMultiThreadingOn(); } template <typename TInputImage, typename TOutputImage> void StretchIntensityImageFilter<TInputImage, TOutputImage>::BeforeThreadedGenerateData() { if (m_OutputMinimum > m_OutputMaximum) { itkExceptionMacro(<< "Minimum output value cannot be greater than Maximum output value."); return; } const TInputImage * inputImage = this->GetInput(); ImageRegionConstIteratorWithIndex<TInputImage> it(inputImage, inputImage->GetBufferedRegion()); m_InputMaximum = NumericTraits<InputPixelType>::NonpositiveMin(); m_InputMinimum = NumericTraits<InputPixelType>::max(); while (!it.IsAtEnd()) { const InputPixelType value = it.Get(); if (value > m_InputMaximum) { m_InputMaximum = value; } if (value < m_InputMinimum) { m_InputMinimum = value; } ++it; } if (itk::Math::abs(m_InputMaximum - m_InputMinimum) > itk::Math::abs(NumericTraits<InputPixelType>::epsilon())) { m_Scale = (static_cast<RealType>(m_OutputMaximum) - static_cast<RealType>(m_OutputMinimum)) / (static_cast<RealType>(m_InputMaximum) - static_cast<RealType>(m_InputMinimum)); } else if (m_InputMaximum > NumericTraits<InputPixelType>::epsilon()) { m_Scale = (static_cast<RealType>(m_OutputMaximum) - static_cast<RealType>(m_OutputMinimum)) / static_cast<RealType>(m_InputMaximum); } else { m_Scale = 0.0; } m_Shift = static_cast<RealType>(m_OutputMinimum) - static_cast<RealType>(m_InputMinimum) * m_Scale; } template <typename TInputImage, typename TOutputImage> void StretchIntensityImageFilter<TInputImage, TOutputImage>::DynamicThreadedGenerateData( const OutputImageRegionType & outputRegionForThread) { const TInputImage * inputPtr = this->GetInput(); TOutputImage * outputPtr = this->GetOutput(0); InputImageRegionType inputRegionForThread = outputRegionForThread; ImageRegionConstIterator<TInputImage> inputIt(inputPtr, inputRegionForThread); ImageRegionIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); inputIt.GoToBegin(); outputIt.GoToBegin(); while (!inputIt.IsAtEnd()) { const InputPixelType x = inputIt.Get(); const RealType value = static_cast<RealType>(x) * m_Scale + m_Shift; auto result = Math::Round<OutputPixelType>(value); result = (result > m_OutputMaximum) ? m_OutputMaximum : result; result = (result < m_OutputMinimum) ? m_OutputMinimum : result; outputIt.Set(result); ++inputIt; ++outputIt; } } template <typename TInputImage, typename TOutputImage> void StretchIntensityImageFilter<TInputImage, TOutputImage>::SetInput(const TInputImage * input) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast<TInputImage *>(input)); } template <typename TInputImage, typename TOutputImage> const TInputImage * StretchIntensityImageFilter<TInputImage, TOutputImage>::GetInput() const { return itkDynamicCastInDebugMode<const TInputImage *>(this->GetPrimaryInput()); } template <typename TInputImage, typename TOutputImage> void StretchIntensityImageFilter<TInputImage, TOutputImage>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Scale: " << static_cast<typename NumericTraits<RealType>::PrintType>(m_Scale) << std::endl; os << indent << "Shift: " << static_cast<typename NumericTraits<RealType>::PrintType>(m_Shift) << std::endl; os << indent << "Input Minimum: " << static_cast<typename NumericTraits<InputPixelType>::PrintType>(m_InputMinimum) << std::endl; os << indent << "Input Maximum: " << static_cast<typename NumericTraits<InputPixelType>::PrintType>(m_InputMaximum) << std::endl; os << indent << "Output Minimum: " << static_cast<typename NumericTraits<OutputPixelType>::PrintType>(m_OutputMinimum) << std::endl; os << indent << "Output Maximum: " << static_cast<typename NumericTraits<OutputPixelType>::PrintType>(m_OutputMaximum) << std::endl; } } // end namespace Testing } // end namespace itk #endif <commit_msg>PERF: Use ImageBufferRange in Testing::StretchIntensityImageFilter<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #ifndef itkTestingStretchIntensityImageFilter_hxx #define itkTestingStretchIntensityImageFilter_hxx #include "itkTestingStretchIntensityImageFilter.h" #include "itkImageBufferRange.h" #include "itkImageRegionIterator.h" #include "itkImageRegionConstIterator.h" #include "itkMath.h" namespace itk { namespace Testing { template <typename TInputImage, typename TOutputImage> StretchIntensityImageFilter<TInputImage, TOutputImage>::StretchIntensityImageFilter() : m_Scale(1.0) , m_Shift(0.0) , m_InputMinimum(NumericTraits<InputPixelType>::max()) , m_InputMaximum(NumericTraits<InputPixelType>::ZeroValue()) , m_OutputMinimum(NumericTraits<OutputPixelType>::NonpositiveMin()) , m_OutputMaximum(NumericTraits<OutputPixelType>::max()) { this->DynamicMultiThreadingOn(); } template <typename TInputImage, typename TOutputImage> void StretchIntensityImageFilter<TInputImage, TOutputImage>::BeforeThreadedGenerateData() { if (m_OutputMinimum > m_OutputMaximum) { itkExceptionMacro(<< "Minimum output value cannot be greater than Maximum output value."); return; } const TInputImage * inputImage = this->GetInput(); m_InputMaximum = NumericTraits<InputPixelType>::NonpositiveMin(); m_InputMinimum = NumericTraits<InputPixelType>::max(); for (const InputPixelType value : Experimental::MakeImageBufferRange(inputImage)) { if (value > m_InputMaximum) { m_InputMaximum = value; } if (value < m_InputMinimum) { m_InputMinimum = value; } } if (itk::Math::abs(m_InputMaximum - m_InputMinimum) > itk::Math::abs(NumericTraits<InputPixelType>::epsilon())) { m_Scale = (static_cast<RealType>(m_OutputMaximum) - static_cast<RealType>(m_OutputMinimum)) / (static_cast<RealType>(m_InputMaximum) - static_cast<RealType>(m_InputMinimum)); } else if (m_InputMaximum > NumericTraits<InputPixelType>::epsilon()) { m_Scale = (static_cast<RealType>(m_OutputMaximum) - static_cast<RealType>(m_OutputMinimum)) / static_cast<RealType>(m_InputMaximum); } else { m_Scale = 0.0; } m_Shift = static_cast<RealType>(m_OutputMinimum) - static_cast<RealType>(m_InputMinimum) * m_Scale; } template <typename TInputImage, typename TOutputImage> void StretchIntensityImageFilter<TInputImage, TOutputImage>::DynamicThreadedGenerateData( const OutputImageRegionType & outputRegionForThread) { const TInputImage * inputPtr = this->GetInput(); TOutputImage * outputPtr = this->GetOutput(0); InputImageRegionType inputRegionForThread = outputRegionForThread; ImageRegionConstIterator<TInputImage> inputIt(inputPtr, inputRegionForThread); ImageRegionIterator<TOutputImage> outputIt(outputPtr, outputRegionForThread); inputIt.GoToBegin(); outputIt.GoToBegin(); while (!inputIt.IsAtEnd()) { const InputPixelType x = inputIt.Get(); const RealType value = static_cast<RealType>(x) * m_Scale + m_Shift; auto result = Math::Round<OutputPixelType>(value); result = (result > m_OutputMaximum) ? m_OutputMaximum : result; result = (result < m_OutputMinimum) ? m_OutputMinimum : result; outputIt.Set(result); ++inputIt; ++outputIt; } } template <typename TInputImage, typename TOutputImage> void StretchIntensityImageFilter<TInputImage, TOutputImage>::SetInput(const TInputImage * input) { // Process object is not const-correct so the const_cast is required here this->ProcessObject::SetNthInput(0, const_cast<TInputImage *>(input)); } template <typename TInputImage, typename TOutputImage> const TInputImage * StretchIntensityImageFilter<TInputImage, TOutputImage>::GetInput() const { return itkDynamicCastInDebugMode<const TInputImage *>(this->GetPrimaryInput()); } template <typename TInputImage, typename TOutputImage> void StretchIntensityImageFilter<TInputImage, TOutputImage>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Scale: " << static_cast<typename NumericTraits<RealType>::PrintType>(m_Scale) << std::endl; os << indent << "Shift: " << static_cast<typename NumericTraits<RealType>::PrintType>(m_Shift) << std::endl; os << indent << "Input Minimum: " << static_cast<typename NumericTraits<InputPixelType>::PrintType>(m_InputMinimum) << std::endl; os << indent << "Input Maximum: " << static_cast<typename NumericTraits<InputPixelType>::PrintType>(m_InputMaximum) << std::endl; os << indent << "Output Minimum: " << static_cast<typename NumericTraits<OutputPixelType>::PrintType>(m_OutputMinimum) << std::endl; os << indent << "Output Maximum: " << static_cast<typename NumericTraits<OutputPixelType>::PrintType>(m_OutputMaximum) << std::endl; } } // end namespace Testing } // end namespace itk #endif <|endoftext|>
<commit_before>AliAnalysisTaskJetHBOM *AddTaskJetHBOM(char* bRec = "AOD",char* bGen = "",UInt_t filterMask = 272, UInt_t iPhysicsSelectionFlag = AliVEvent::kAny,Char_t *jf = "KT", Float_t radius = 0.4,Int_t kWriteAOD = kFALSE,char* deltaFile = "",Float_t ptTrackCut = 0.15, Float_t etaTrackWindow = 0.9,Float_t vertexWindow = 10.,TString effLoc = "$ALICE_ROOT/OADB/PWGJE/HBOM/fastMCInput_LHC10h_110719a.root",Int_t fNHBOM = 0); Int_t kBackgroundModeCl = 0; Float_t kPtTrackCutCl = 0.15; Float_t kTrackEtaWindowCl = 0.8; Float_t kVertexWindowCl = 10; AliAnalysisTaskJetHBOM *AddTaskJetHBOM(char* bRec,char* bGen ,UInt_t filterMask,UInt_t iPhysicsSelectionFlag,Char_t *jf,Float_t radius,Int_t kWriteAOD,char *deltaFile,Float_t ptTrackCut,Float_t etaTrackWindow,Float_t vertexWindow,TString effLoc,Int_t fNHBOM) { // Creates a jet fider task, configures it and adds it to the analysis manager. kPtTrackCutCl = ptTrackCut; kTrackEtaWindowCl = etaTrackWindow; kVertexWindowCl = vertexWindow; TString outputFile(deltaFile); // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskJetHBOM", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskJetHBOM", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); TString typeRec(bRec); TString typeGen(bGen); if(!typeRec.Contains("AODextra")) { typeGen.ToUpper(); typeRec.ToUpper(); } cout << "typeRec: " << typeRec << endl; // Create the task and configure it. //=========================================================================== TString cAdd = ""; cAdd += Form("%02d_",(int)((radius+0.01)*10.)); cAdd += Form("B%d",(int)kBackgroundModeCl); cAdd += Form("_Filter%05d",filterMask); cAdd += Form("_Cut%05d",(int)(1000.*kPtTrackCutCl)); cAdd += Form("_hbom%02d",fNHBOM); Printf("%s %E",cAdd.Data(),kPtTrackCutCl); AliAnalysisTaskJetHBOM* hbom = new AliAnalysisTaskJetHBOM(Form("JetHBOM%s_%s%s",bRec,jf,cAdd.Data())); hbom->SetFilterMask(filterMask); // hbom->SetUseGlobalSelection(kTRUE); hbom->SetVtxCuts(kVertexWindowCl,1);//sets fVtxZCut and fVtxR2Cut if(type == "AOD"){ // Assume all jet are produced already hbom->SetAODTrackInput(kTRUE); hbom->SetAODMCInput(kTRUE); } if(typeRec.Contains("AODMC2b")){// work down from the top AODMC2b -> AODMC2 -> AODMC -> AOD hbom->SetTrackTypeRec(AliAnalysisTaskJetHBOM::kTrackAODMCChargedAcceptance); hbom->SetTrackPtCut(kPtTrackCutCl); hbom->SetTrackEtaWindow(kTrackEtaWindowCl); } else if (typeRec.Contains("AODMC2")){ hbom->SetTrackTypeRec(AliAnalysisTaskJetHBOM::kTrackAODMCCharged); hbom->SetTrackPtCut(kPtTrackCutCl); hbom->SetTrackEtaWindow(5); } else if (typeRec.Contains("AODMC")){ hbom->SetTrackTypeRec(AliAnalysisTaskJetHBOM::kTrackAODMCAll); hbom->SetTrackPtCut(kPtTrackCutCl); hbom->SetTrackEtaWindow(5); } else if (typeRec.Contains("AODextraonly")) { hbom->SetTrackTypeRec(AliAnalysisTaskJetHBOM::kTrackAODextraonly); hbom->SetTrackPtCut(kPtTrackCutCl); hbom->SetTrackEtaWindow(kTrackEtaWindowCl); } else if (typeRec.Contains("AODextra")) { cout << "AliAnalysisTaskJetHBOM::kTrackAODextra: " << AliAnalysisTaskJetHBOM::kTrackAODextra << endl; hbom->SetTrackTypeRec(AliAnalysisTaskJetHBOM::kTrackAODextra); hbom->SetTrackPtCut(kPtTrackCutCl); hbom->SetTrackEtaWindow(kTrackEtaWindowCl); } else if (typeRec.Contains("AOD")) { hbom->SetTrackTypeRec(AliAnalysisTaskJetHBOM::kTrackAOD); hbom->SetTrackPtCut(kPtTrackCutCl); hbom->SetTrackEtaWindow(kTrackEtaWindowCl); } hbom->SetRparam(radius); hbom->SetGhostArea(0.005); hbom->SetGhostEtamax(kTrackEtaWindowCl); switch (jf) { case "ANTIKT": hbom->SetAlgorithm(2); // antikt from fastjet/JetDefinition.hh break; case "CA": hbom->SetAlgorithm(1); // CA from fastjet/JetDefinition.hh break; case "KT": hbom->SetAlgorithm(0); // kt from fastjet/JetDefinition.hh break; default: ::Error("AddTaskJetHBOM", "Wrong jet finder selected\n"); return 0; } if(kWriteAOD){ if(outputFile.Length())hbom->SetJetOutputFile(outputFile); hbom->SetJetOutputBranch(Form("hbom%s_%s%s",bRec,jf,cAdd.Data())); hbom->SetJetOutputMinPt(0); // store only jets above a certain threshold } //sets number of detector hits hbom->SetfNHBOM(fNHBOM); //physics Selection if(iPhysicsSelectionFlag)hbom->SelectCollisionCandidates(iPhysicsSelectionFlag); mgr->AddTask(hbom); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== AliAnalysisDataContainer *coutput1_Spec = mgr->CreateContainer(Form("hbom_%s_%s_%s%s",bRec,bGen,jf,cAdd.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s:PWGJE_hbom_%s_%s_%s%s",AliAnalysisManager::GetCommonFileName(),bRec,bGen,jf,cAdd.Data())); mgr->ConnectInput (hbom, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (hbom, 0, mgr->GetCommonOutputContainer()); mgr->ConnectOutput (hbom, 1, coutput1_Spec ); //loads efficiencies hbom->SetEfficiencyPt(GetEfficiencyPt(effLoc)); hbom->SetEfficiencyPhi(GetEfficiencyPhi(effLoc)); return hbom; } //loads single track pT efficiency from root file TH1F *GetEfficiencyPt(TString effLoc){ static TFile *fIn = 0; static TH1F *hEffPt = 0; if(!fIn)fIn = TFile::Open(effLoc.Data()); if(!hEffPt)hEffPt = (TH1F*)fIn->Get("hSingleTrackEffPt"); if(!hEffPt) cout<<"Could not load hSingleTrackEffPt"<<endl; if(hEffPt){return hEffPt;} return 0; } //loads phi-pT efficiency from root file TH2D *GetEfficiencyPhi(TString effLoc){ static TFile *fIn = 0; static TH2D *hPhiPt = 0; if(!fIn)fIn = TFile::Open(effLoc.Data()); if(!hPhiPt)hPhiPt = (TH2D*)fIn->Get("h2TrackPtPhiNorm"); if(!hPhiPt) cout<<"Could not load h2TrackPtPhiNorm"<<endl; if(hPhiPt){return hPhiPt;} return 0; } <commit_msg>Fix name of output container (M. Zimmermann)<commit_after>AliAnalysisTaskJetHBOM *AddTaskJetHBOM(char* bRec = "AOD",char* bGen = "",UInt_t filterMask = 272, UInt_t iPhysicsSelectionFlag = AliVEvent::kAny,Char_t *jf = "KT", Float_t radius = 0.4,Int_t kWriteAOD = kFALSE,char* deltaFile = "",Float_t ptTrackCut = 0.15, Float_t etaTrackWindow = 0.9,Float_t vertexWindow = 10.,TString effLoc = "$ALICE_ROOT/OADB/PWGJE/HBOM/fastMCInput_LHC10h_110719a.root",Int_t fNHBOM = 0, Int_t constCone = kFALSE, Float_t constConePhi = 0, Float_t constConeEta = 0); Int_t kBackgroundModeCl = 0; Float_t kPtTrackCutCl = 0.15; Float_t kTrackEtaWindowCl = 0.8; Float_t kVertexWindowCl = 10; AliAnalysisTaskJetHBOM *AddTaskJetHBOM(char* bRec,char* bGen ,UInt_t filterMask,UInt_t iPhysicsSelectionFlag,Char_t *jf,Float_t radius,Int_t kWriteAOD,char *deltaFile,Float_t ptTrackCut,Float_t etaTrackWindow,Float_t vertexWindow,TString effLoc,Int_t fNHBOM, Int_t constCone, Float_t constConePhi,Float_t constConeEta) { //if constCone is true, the random Cone positon is set to constConePhi and constConeEta. Else the cone is random set and the parameters constConePhi and constConeEta are irrelevant // Creates a jet fider task, configures it and adds it to the analysis manager. kPtTrackCutCl = ptTrackCut; kTrackEtaWindowCl = etaTrackWindow; kVertexWindowCl = vertexWindow; TString outputFile(deltaFile); // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskJetHBOM", "No analysis manager to connect to."); return NULL; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { ::Error("AddTaskJetHBOM", "This task requires an input event handler"); return NULL; } TString type = mgr->GetInputEventHandler()->GetDataType(); TString typeRec(bRec); TString typeGen(bGen); if(!typeRec.Contains("AODextra")) { typeGen.ToUpper(); typeRec.ToUpper(); } cout << "typeRec: " << typeRec << endl; // Create the task and configure it. //=========================================================================== TString cAdd = ""; cAdd += Form("%02d_",(int)((radius+0.01)*10.)); cAdd += Form("B%d",(int)kBackgroundModeCl); cAdd += Form("_Filter%05d",filterMask); cAdd += Form("_Cut%05d",(int)(1000.*kPtTrackCutCl)); cAdd += Form("_hbom%02d",fNHBOM); if(constCone){ cAdd += Form("_constConePhi%02dEta%02d",constConePhi,constConeEta); } Printf("%s %E",cAdd.Data(),kPtTrackCutCl); AliAnalysisTaskJetHBOM* hbom = new AliAnalysisTaskJetHBOM(Form("JetHBOM%s_%s%s",bRec,jf,cAdd.Data())); hbom->SetFilterMask(filterMask); // hbom->SetUseGlobalSelection(kTRUE); hbom->SetVtxCuts(kVertexWindowCl,1);//sets fVtxZCut and fVtxR2Cut if(type == "AOD"){ // Assume all jet are produced already hbom->SetAODTrackInput(kTRUE); hbom->SetAODMCInput(kTRUE); } if(typeRec.Contains("AODMC2b")){// work down from the top AODMC2b -> AODMC2 -> AODMC -> AOD hbom->SetTrackTypeRec(AliAnalysisTaskJetHBOM::kTrackAODMCChargedAcceptance); hbom->SetTrackPtCut(kPtTrackCutCl); hbom->SetTrackEtaWindow(kTrackEtaWindowCl); } else if (typeRec.Contains("AODMC2")){ hbom->SetTrackTypeRec(AliAnalysisTaskJetHBOM::kTrackAODMCCharged); hbom->SetTrackPtCut(kPtTrackCutCl); hbom->SetTrackEtaWindow(5); } else if (typeRec.Contains("AODMC")){ hbom->SetTrackTypeRec(AliAnalysisTaskJetHBOM::kTrackAODMCAll); hbom->SetTrackPtCut(kPtTrackCutCl); hbom->SetTrackEtaWindow(5); } else if (typeRec.Contains("AODextraonly")) { hbom->SetTrackTypeRec(AliAnalysisTaskJetHBOM::kTrackAODextraonly); hbom->SetTrackPtCut(kPtTrackCutCl); hbom->SetTrackEtaWindow(kTrackEtaWindowCl); } else if (typeRec.Contains("AODextra")) { cout << "AliAnalysisTaskJetHBOM::kTrackAODextra: " << AliAnalysisTaskJetHBOM::kTrackAODextra << endl; hbom->SetTrackTypeRec(AliAnalysisTaskJetHBOM::kTrackAODextra); hbom->SetTrackPtCut(kPtTrackCutCl); hbom->SetTrackEtaWindow(kTrackEtaWindowCl); } else if (typeRec.Contains("AOD")) { hbom->SetTrackTypeRec(AliAnalysisTaskJetHBOM::kTrackAOD); hbom->SetTrackPtCut(kPtTrackCutCl); hbom->SetTrackEtaWindow(kTrackEtaWindowCl); } hbom->SetRparam(radius); hbom->SetGhostArea(0.005); hbom->SetGhostEtamax(kTrackEtaWindowCl); switch (jf) { case "ANTIKT": hbom->SetAlgorithm(2); // antikt from fastjet/JetDefinition.hh break; case "CA": hbom->SetAlgorithm(1); // CA from fastjet/JetDefinition.hh break; case "KT": hbom->SetAlgorithm(0); // kt from fastjet/JetDefinition.hh break; default: ::Error("AddTaskJetHBOM", "Wrong jet finder selected\n"); return 0; } //Constant Cone analysis if(constCone){ hbom->SetRandConePos(constConeEta,constConePhi); } if(kWriteAOD){ if(outputFile.Length())hbom->SetJetOutputFile(outputFile); hbom->SetJetOutputBranch(Form("hbom%s_%s%s",bRec,jf,cAdd.Data())); hbom->SetJetOutputMinPt(0); // store only jets above a certain threshold } //sets number of detector hits hbom->SetfNHBOM(fNHBOM); //physics Selection if(iPhysicsSelectionFlag)hbom->SelectCollisionCandidates(iPhysicsSelectionFlag); mgr->AddTask(hbom); // Create ONLY the output containers for the data produced by the task. // Get and connect other common input/output containers via the manager as below //============================================================================== AliAnalysisDataContainer *coutput1_Spec = mgr->CreateContainer(Form("hbom_%s_%s_%s%s",bRec,bGen,jf,cAdd.Data()), TList::Class(),AliAnalysisManager::kOutputContainer,Form("%s:PWGJE_hbom_%s_%s_%s%s",AliAnalysisManager::GetCommonFileName(),bRec,bGen,jf,cAdd.Data())); mgr->ConnectInput (hbom, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput (hbom, 0, mgr->GetCommonOutputContainer()); mgr->ConnectOutput (hbom, 1, coutput1_Spec ); //loads efficiencies hbom->SetEfficiencyPt(GetEfficiencyPt(effLoc)); hbom->SetEfficiencyPhi(GetEfficiencyPhi(effLoc)); return hbom; } //loads single track pT efficiency from root file TH1F *GetEfficiencyPt(TString effLoc){ static TFile *fIn = 0; static TH1F *hEffPt = 0; if(!fIn)fIn = TFile::Open(effLoc.Data()); if(!hEffPt)hEffPt = (TH1F*)fIn->Get("hSingleTrackEffPt"); if(!hEffPt) cout<<"Could not load hSingleTrackEffPt"<<endl; if(hEffPt){return hEffPt;} return 0; } //loads phi-pT efficiency from root file TH2D *GetEfficiencyPhi(TString effLoc){ static TFile *fIn = 0; static TH2D *hPhiPt = 0; if(!fIn)fIn = TFile::Open(effLoc.Data()); if(!hPhiPt)hPhiPt = (TH2D*)fIn->Get("h2TrackPtPhiNorm"); if(!hPhiPt) cout<<"Could not load h2TrackPtPhiNorm"<<endl; if(hPhiPt){return hPhiPt;} return 0; } <|endoftext|>
<commit_before>/** * @file PathPlanner.cpp * * @author <a href="mailto:[email protected]">Yigit Can Akcay</a> * Implementation of class PathPlanner */ #include "PathPlanner.h" PathPlanner::PathPlanner() : step_buffer({}), foot_to_use(Foot::RIGHT), last_stepRequestID(getMotionStatus().stepControl.stepRequestID + 1), // WalkRequest stepRequestID starts at 0, we have to start at 1 kick_planned(false) { DEBUG_REQUEST_REGISTER("PathPlanner:walk_to_ball", "Walks to the ball from far.", false); getDebugParameterList().add(&params); } PathPlanner::~PathPlanner() { getDebugParameterList().remove(&params); } void PathPlanner::execute() { // --- DEBUG REQUESTS --- DEBUG_REQUEST("PathPlanner:walk_to_ball", if (getBallModel().positionPreview.x > 250) { walk_to_ball(Foot::NONE); } ); // --- DEBUG REQUESTS --- getPathModel().kick_executed = false; STOPWATCH_START("PathPlanner"); // Always executed first manage_step_buffer(); // The kick has been executed // Tells XABSL to jump into next state if (kick_planned && step_buffer.empty()) { getPathModel().kick_executed = true; } switch (getPathModel().path_routine) { case PathModel::PathRoutine::NONE: // There is no kick planned, since the kick has been executed // and XABSL is in a different state now if (kick_planned) { kick_planned = false; } if (step_buffer.empty()) { return; } break; case PathModel::PathRoutine::GO_TO_BALL_FAST: walk_to_ball(Foot::NONE , true); break; case PathModel::PathRoutine::GO_TO_BALL_SLOW: walk_to_ball(Foot::NONE); break; case PathModel::PathRoutine::MOVE_AROUND_BALL: move_around_ball(getPathModel().direction, getPathModel().radius); break; case PathModel::PathRoutine::APPROACH_BALL_LEFT: approach_ball(Foot::LEFT); break; case PathModel::PathRoutine::APPROACH_BALL_RIGHT: approach_ball(Foot::RIGHT); break; case PathModel::PathRoutine::SHORT_KICK_LEFT: short_kick(Foot::LEFT); break; case PathModel::PathRoutine::SHORT_KICK_RIGHT: short_kick(Foot::RIGHT); break; case PathModel::PathRoutine::LONG_KICK_LEFT: long_kick(Foot::LEFT); break; case PathModel::PathRoutine::LONG_KICK_RIGHT: long_kick(Foot::RIGHT); break; case PathModel::PathRoutine::SIDEKICK_LEFT: sidekick(Foot::LEFT); break; case PathModel::PathRoutine::SIDEKICK_RIGHT: sidekick(Foot::RIGHT); break; } // Always executed last execute_step_buffer(); STOPWATCH_STOP("PathPlanner"); } void PathPlanner::walk_to_ball(const Foot foot, const bool go_fast) { Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; break; case Foot::NONE: ballPos = getBallModel().positionPreview; coordinate = WalkRequest::Hip; break; } double ballRotation = ballPos.angle(); Pose2D pose = { ballRotation, 0.7*(ballPos.x - getPathModel().distance), ballPos.y }; if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double scale = 1.0; double speed_direction = 0.0; if (go_fast) { double character = 1.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } else { double character = 0.3; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } } else { update_step(pose); } } void PathPlanner::move_around_ball(const double direction, const double radius) { Vector2d ballPos = getBallModel().positionPreview; double ballRotation = ballPos.angle(); double ballDistance = ballPos.abs(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; double min1; double min2; double max1; double max2; if (direction <= 0) { min1 = 0.0; min2 = 0.0; max1 = 45.0; max2 = 100.0; } else { min1 = -45; min2 = -100; max1 = 0; max2 = 0; } double stepX = (ballDistance - radius) * std::cos(ballRotation); double stepY = Math::clamp(radius * std::tan(Math::clamp(Math::toDegrees(-direction), min1, max1)), min2, max2) * std::cos(ballRotation); Pose2D pose = { ballRotation, stepX, stepY }; if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double character = 0.7; Foot foot = Foot::NONE; double scale = 1.0; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } else { update_step(pose); } } void PathPlanner::approach_ball(const Foot foot) { Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; double stepX = 0.0; double stepY = 0.0; double ballRadius = getFieldInfo().ballRadius; double stepRotation = ballPos.abs() > 250 ? ballPos.angle() : 0; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; stepX = ballPos.x - std::abs(ballPos.y - getPathModel().yOffset) - getPathModel().distance - ballRadius; stepY = ballPos.y - getPathModel().yOffset; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; stepX = ballPos.x - std::abs(ballPos.y + getPathModel().yOffset) - getPathModel().distance - ballRadius; stepY = ballPos.y + getPathModel().yOffset; break; case Foot::NONE: ASSERT(false); } Pose2D pose; if ( params.approach_ball_adapt_control && Pose2D(0.7*stepX, 0.7*stepY).translation.abs() < params.approach_ball_adapt_threshold) { pose = { stepRotation, stepX, stepY }; } else { pose = { stepRotation, 0.7 * stepX, 0.7 * stepY }; } if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double character = 0.7; double scale = 1.0; double speed_direction = 0.0; add_step(pose, type, coordinate, character, Foot::NONE, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } else { update_step(pose); } } void PathPlanner::short_kick(const Foot foot) { if (!kick_planned) { WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: coordinate = WalkRequest::RFoot; break; case Foot::RIGHT: coordinate = WalkRequest::LFoot; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, 500 , 0.0 }; StepType type = StepType::KICKSTEP; double character = 1.0; double scale = 0.7; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true); kick_planned = true; } } } void PathPlanner::long_kick(const Foot foot) { if (!kick_planned) { WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: coordinate = WalkRequest::RFoot; break; case Foot::RIGHT: coordinate = WalkRequest::LFoot; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, 500, 0.0 }; StepType type = StepType::KICKSTEP; double character = 1.0; double scale = 0.7; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true); kick_planned = true; } } } void PathPlanner::sidekick(const Foot foot) { if (!kick_planned) { double speed_direction = 0.0; double stepY = 0.0; WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: coordinate = WalkRequest::LFoot; speed_direction = 90; stepY = 100; break; case Foot::RIGHT: coordinate = WalkRequest::RFoot; speed_direction = -90; stepY = -100; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, 500, stepY }; StepType type = StepType::KICKSTEP; double character = 1.0; Foot step_foot = foot == Foot::RIGHT ? Foot::LEFT : Foot::RIGHT; double scale = params.sidekick_scale; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true); kick_planned = true; } } } // Stepcontrol void PathPlanner::add_step(Pose2D &pose, const StepType &type, const WalkRequest::Coordinate &coordinate, const double character, const Foot foot, const double scale, const double speedDirection, const WalkRequest::StepControlRequest::RestrictionMode restriction, bool isProtected) { step_buffer.push_back(Step_Buffer_Element({ pose, speedDirection, type, type == StepType::KICKSTEP ? params.kick_time : 250, character, scale, foot, coordinate, restriction, isProtected})); } void PathPlanner::update_step(Pose2D &pose) { ASSERT(step_buffer.size() > 0); step_buffer.front().pose = pose; } void PathPlanner::manage_step_buffer() { if (step_buffer.empty()) { return; } // requested step has been accepted if (last_stepRequestID == getMotionStatus().stepControl.stepRequestID) { step_buffer.erase(step_buffer.begin()); last_stepRequestID = getMotionStatus().stepControl.stepRequestID + 1; } } void PathPlanner::execute_step_buffer() { STOPWATCH_START("PathPlanner:execute_steplist"); if (step_buffer.empty()) { return; } getMotionRequest().id = motion::walk; getMotionRequest().walkRequest.coordinate = step_buffer.front().coordinate; getMotionRequest().walkRequest.character = step_buffer.front().character; getMotionRequest().walkRequest.stepControl.scale = step_buffer.front().scale; getMotionRequest().walkRequest.stepControl.stepID = getMotionStatus().stepControl.stepID; getMotionRequest().walkRequest.stepControl.type = step_buffer.front().type; getMotionRequest().walkRequest.stepControl.time = step_buffer.front().time; getMotionRequest().walkRequest.stepControl.speedDirection = step_buffer.front().speedDirection; getMotionRequest().walkRequest.stepControl.target = step_buffer.front().pose; getMotionRequest().walkRequest.stepControl.restriction = step_buffer.front().restriction; getMotionRequest().walkRequest.stepControl.isProtected = step_buffer.front().isProtected; getMotionRequest().walkRequest.stepControl.stepRequestID = last_stepRequestID; // normal walking WALKSTEPs use Foot::NONE, for KICKSTEPs the foot to use has to be specified if (step_buffer.front().foot == Foot::NONE) { switch (getMotionStatus().stepControl.moveableFoot) { case MotionStatus::StepControlStatus::LEFT: foot_to_use = Foot::LEFT; break; case MotionStatus::StepControlStatus::RIGHT: foot_to_use = Foot::RIGHT; break; case MotionStatus::StepControlStatus::BOTH: if (step_buffer.front().pose.translation.y > 0.0f || step_buffer.front().pose.rotation > 0.0f) { foot_to_use = Foot::LEFT; } else { foot_to_use = Foot::RIGHT; } break; case MotionStatus::StepControlStatus::NONE: foot_to_use = Foot::RIGHT; break; } } else { foot_to_use = step_buffer.front().foot; } // false means right foot getMotionRequest().walkRequest.stepControl.moveLeftFoot = (foot_to_use != Foot::RIGHT); STOPWATCH_STOP("PathPlanner:execute_steplist"); } <commit_msg>more clear implementation<commit_after>/** * @file PathPlanner.cpp * * @author <a href="mailto:[email protected]">Yigit Can Akcay</a> * Implementation of class PathPlanner */ #include "PathPlanner.h" PathPlanner::PathPlanner() : step_buffer({}), foot_to_use(Foot::RIGHT), last_stepRequestID(getMotionStatus().stepControl.stepRequestID + 1), // WalkRequest stepRequestID starts at 0, we have to start at 1 kick_planned(false) { DEBUG_REQUEST_REGISTER("PathPlanner:walk_to_ball", "Walks to the ball from far.", false); getDebugParameterList().add(&params); } PathPlanner::~PathPlanner() { getDebugParameterList().remove(&params); } void PathPlanner::execute() { // --- DEBUG REQUESTS --- DEBUG_REQUEST("PathPlanner:walk_to_ball", if (getBallModel().positionPreview.x > 250) { walk_to_ball(Foot::NONE); } ); // --- DEBUG REQUESTS --- getPathModel().kick_executed = false; STOPWATCH_START("PathPlanner"); // Always executed first manage_step_buffer(); // The kick has been executed // Tells XABSL to jump into next state if (kick_planned && step_buffer.empty()) { getPathModel().kick_executed = true; } switch (getPathModel().path_routine) { case PathModel::PathRoutine::NONE: // There is no kick planned, since the kick has been executed // and XABSL is in a different state now if (kick_planned) { kick_planned = false; } if (step_buffer.empty()) { return; } break; case PathModel::PathRoutine::GO_TO_BALL_FAST: walk_to_ball(Foot::NONE , true); break; case PathModel::PathRoutine::GO_TO_BALL_SLOW: walk_to_ball(Foot::NONE); break; case PathModel::PathRoutine::MOVE_AROUND_BALL: move_around_ball(getPathModel().direction, getPathModel().radius); break; case PathModel::PathRoutine::APPROACH_BALL_LEFT: approach_ball(Foot::LEFT); break; case PathModel::PathRoutine::APPROACH_BALL_RIGHT: approach_ball(Foot::RIGHT); break; case PathModel::PathRoutine::SHORT_KICK_LEFT: short_kick(Foot::LEFT); break; case PathModel::PathRoutine::SHORT_KICK_RIGHT: short_kick(Foot::RIGHT); break; case PathModel::PathRoutine::LONG_KICK_LEFT: long_kick(Foot::LEFT); break; case PathModel::PathRoutine::LONG_KICK_RIGHT: long_kick(Foot::RIGHT); break; case PathModel::PathRoutine::SIDEKICK_LEFT: sidekick(Foot::LEFT); break; case PathModel::PathRoutine::SIDEKICK_RIGHT: sidekick(Foot::RIGHT); break; } // Always executed last execute_step_buffer(); STOPWATCH_STOP("PathPlanner"); } void PathPlanner::walk_to_ball(const Foot foot, const bool go_fast) { Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; break; case Foot::NONE: ballPos = getBallModel().positionPreview; coordinate = WalkRequest::Hip; break; } double ballRotation = ballPos.angle(); Pose2D pose = { ballRotation, 0.7*(ballPos.x - getPathModel().distance), ballPos.y }; if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double scale = 1.0; double speed_direction = 0.0; if (go_fast) { double character = 1.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } else { double character = 0.3; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } } else { update_step(pose); } } void PathPlanner::move_around_ball(const double direction, const double radius) { Vector2d ballPos = getBallModel().positionPreview; double ballRotation = ballPos.angle(); double ballDistance = ballPos.abs(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; double min1; double min2; double max1; double max2; if (direction <= 0) { min1 = 0.0; min2 = 0.0; max1 = 45.0; max2 = 100.0; } else { min1 = -45; min2 = -100; max1 = 0; max2 = 0; } double stepX = (ballDistance - radius) * std::cos(ballRotation); double stepY = Math::clamp(radius * std::tan(Math::clamp(Math::toDegrees(-direction), min1, max1)), min2, max2) * std::cos(ballRotation); Pose2D pose = { ballRotation, stepX, stepY }; if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double character = 0.7; Foot foot = Foot::NONE; double scale = 1.0; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } else { update_step(pose); } } void PathPlanner::approach_ball(const Foot foot) { Vector2d ballPos = Vector2d(); WalkRequest::Coordinate coordinate = WalkRequest::Hip; double stepX = 0.0; double stepY = 0.0; double ballRadius = getFieldInfo().ballRadius; double stepRotation = ballPos.abs() > 250 ? ballPos.angle() : 0; switch (foot) { case Foot::LEFT: ballPos = getBallModel().positionPreviewInLFoot; coordinate = WalkRequest::LFoot; stepX = ballPos.x - std::abs(ballPos.y - getPathModel().yOffset) - getPathModel().distance - ballRadius; stepY = ballPos.y - getPathModel().yOffset; break; case Foot::RIGHT: ballPos = getBallModel().positionPreviewInRFoot; coordinate = WalkRequest::RFoot; stepX = ballPos.x - std::abs(ballPos.y + getPathModel().yOffset) - getPathModel().distance - ballRadius; stepY = ballPos.y + getPathModel().yOffset; break; case Foot::NONE: ASSERT(false); } const double slow_down_factor = 0.7; Pose2D pose; if ( params.approach_ball_adapt_control && Vector2d(stepX, stepY).abs() < params.approach_ball_adapt_threshold) { pose = { stepRotation, stepX, stepY }; } else { pose = { stepRotation, slow_down_factor * stepX, slow_down_factor * stepY }; } if (step_buffer.empty()) { StepType type = StepType::WALKSTEP; double character = 0.7; double scale = 1.0; double speed_direction = 0.0; add_step(pose, type, coordinate, character, Foot::NONE, scale, speed_direction, WalkRequest::StepControlRequest::HARD, false); } else { update_step(pose); } } void PathPlanner::short_kick(const Foot foot) { if (!kick_planned) { WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: coordinate = WalkRequest::RFoot; break; case Foot::RIGHT: coordinate = WalkRequest::LFoot; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, 500 , 0.0 }; StepType type = StepType::KICKSTEP; double character = 1.0; double scale = 0.7; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true); kick_planned = true; } } } void PathPlanner::long_kick(const Foot foot) { if (!kick_planned) { WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: coordinate = WalkRequest::RFoot; break; case Foot::RIGHT: coordinate = WalkRequest::LFoot; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, 500, 0.0 }; StepType type = StepType::KICKSTEP; double character = 1.0; double scale = 0.7; double speed_direction = 0.0; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true); kick_planned = true; } } } void PathPlanner::sidekick(const Foot foot) { if (!kick_planned) { double speed_direction = 0.0; double stepY = 0.0; WalkRequest::Coordinate coordinate = WalkRequest::Hip; switch (foot) { case Foot::LEFT: coordinate = WalkRequest::LFoot; speed_direction = 90; stepY = 100; break; case Foot::RIGHT: coordinate = WalkRequest::RFoot; speed_direction = -90; stepY = -100; break; case Foot::NONE: ASSERT(false); } if (step_buffer.empty()) { Pose2D pose = { 0.0, 500, stepY }; StepType type = StepType::KICKSTEP; double character = 1.0; Foot step_foot = foot == Foot::RIGHT ? Foot::LEFT : Foot::RIGHT; double scale = params.sidekick_scale; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); type = StepType::ZEROSTEP; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::SOFT, true); pose = { 0.0, 0.0, 0.0 }; type = StepType::WALKSTEP; add_step(pose, type, coordinate, character, step_foot, scale, speed_direction, WalkRequest::StepControlRequest::HARD, true); kick_planned = true; } } } // Stepcontrol void PathPlanner::add_step(Pose2D &pose, const StepType &type, const WalkRequest::Coordinate &coordinate, const double character, const Foot foot, const double scale, const double speedDirection, const WalkRequest::StepControlRequest::RestrictionMode restriction, bool isProtected) { step_buffer.push_back(Step_Buffer_Element({ pose, speedDirection, type, type == StepType::KICKSTEP ? params.kick_time : 250, character, scale, foot, coordinate, restriction, isProtected})); } void PathPlanner::update_step(Pose2D &pose) { ASSERT(step_buffer.size() > 0); step_buffer.front().pose = pose; } void PathPlanner::manage_step_buffer() { if (step_buffer.empty()) { return; } // requested step has been accepted if (last_stepRequestID == getMotionStatus().stepControl.stepRequestID) { step_buffer.erase(step_buffer.begin()); last_stepRequestID = getMotionStatus().stepControl.stepRequestID + 1; } } void PathPlanner::execute_step_buffer() { STOPWATCH_START("PathPlanner:execute_steplist"); if (step_buffer.empty()) { return; } getMotionRequest().id = motion::walk; getMotionRequest().walkRequest.coordinate = step_buffer.front().coordinate; getMotionRequest().walkRequest.character = step_buffer.front().character; getMotionRequest().walkRequest.stepControl.scale = step_buffer.front().scale; getMotionRequest().walkRequest.stepControl.stepID = getMotionStatus().stepControl.stepID; getMotionRequest().walkRequest.stepControl.type = step_buffer.front().type; getMotionRequest().walkRequest.stepControl.time = step_buffer.front().time; getMotionRequest().walkRequest.stepControl.speedDirection = step_buffer.front().speedDirection; getMotionRequest().walkRequest.stepControl.target = step_buffer.front().pose; getMotionRequest().walkRequest.stepControl.restriction = step_buffer.front().restriction; getMotionRequest().walkRequest.stepControl.isProtected = step_buffer.front().isProtected; getMotionRequest().walkRequest.stepControl.stepRequestID = last_stepRequestID; // normal walking WALKSTEPs use Foot::NONE, for KICKSTEPs the foot to use has to be specified if (step_buffer.front().foot == Foot::NONE) { switch (getMotionStatus().stepControl.moveableFoot) { case MotionStatus::StepControlStatus::LEFT: foot_to_use = Foot::LEFT; break; case MotionStatus::StepControlStatus::RIGHT: foot_to_use = Foot::RIGHT; break; case MotionStatus::StepControlStatus::BOTH: if (step_buffer.front().pose.translation.y > 0.0f || step_buffer.front().pose.rotation > 0.0f) { foot_to_use = Foot::LEFT; } else { foot_to_use = Foot::RIGHT; } break; case MotionStatus::StepControlStatus::NONE: foot_to_use = Foot::RIGHT; break; } } else { foot_to_use = step_buffer.front().foot; } // false means right foot getMotionRequest().walkRequest.stepControl.moveLeftFoot = (foot_to_use != Foot::RIGHT); STOPWATCH_STOP("PathPlanner:execute_steplist"); } <|endoftext|>