text
stringlengths
54
60.6k
<commit_before>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /**\file examples/valence.C \brief Valence of sparse matrix over Z or Zp. \ingroup examples */ //#include "linbox-config.h" #include <iostream> #include "linbox/field/modular-double.h" #include "linbox/field/gmp-integers.h" #include "linbox/blackbox/transpose.h" #include "linbox/blackbox/compose.h" #include "linbox/blackbox/sparse.h" #include "linbox/solutions/valence.h" #include "linbox/util/matrix-stream.h" using namespace LinBox; int main (int argc, char **argv) { if (argc < 2 || argc > 3) { std::cerr << "Usage: valence <matrix-file-in-supported-format> [-ata|-aat]" << std::endl; return -1; } std::ifstream input (argv[1]); if (!input) { std::cerr << "Error opening matrix file " << argv[1] << std::endl; return -1; } PID_integer ZZ; MatrixStream< PID_integer > ms( ZZ, input ); typedef SparseMatrix<PID_integer> Blackbox; Blackbox A (ms); std::cout << "A is " << A.rowdim() << " by " << A.coldim() << std::endl; PID_integer::Element val_A; if (argc == 3) { Transpose<Blackbox> T(&A); if (argv[2] == "-ata") { Compose< Transpose<Blackbox>, Blackbox > C (&T, &A); std::cout << "A^T A is " << C.rowdim() << " by " << C.coldim() << std::endl; valence(val_A, C); } else { Compose< Blackbox, Transpose<Blackbox> > C (&A, &T); std::cout << "A A^T is " << C.rowdim() << " by " << C.coldim() << std::endl; valence(val_A, C); } } else { if (A.rowdim() != A.coldim()) { std::cerr << "Valence works only on square matrices, try either to change the dimension in the matrix file, or to compute the valence of A A^T or A^T A, via the -aat or -ata options." << std::endl; exit(0); } else valence (val_A, A); } std::cout << "Valence is " << val_A << std::endl; return 0; } <commit_msg>corrected strcmp<commit_after>/* -*- mode: C++; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ /**\file examples/valence.C \brief Valence of sparse matrix over Z or Zp. \ingroup examples */ //#include "linbox-config.h" #include <iostream> #include "linbox/field/modular-double.h" #include "linbox/field/gmp-integers.h" #include "linbox/blackbox/transpose.h" #include "linbox/blackbox/compose.h" #include "linbox/blackbox/sparse.h" #include "linbox/solutions/valence.h" #include "linbox/util/matrix-stream.h" using namespace LinBox; int main (int argc, char **argv) { if (argc < 2 || argc > 3) { std::cerr << "Usage: valence <matrix-file-in-supported-format> [-ata|-aat]" << std::endl; return -1; } std::ifstream input (argv[1]); if (!input) { std::cerr << "Error opening matrix file " << argv[1] << std::endl; return -1; } PID_integer ZZ; MatrixStream< PID_integer > ms( ZZ, input ); typedef SparseMatrix<PID_integer> Blackbox; Blackbox A (ms); std::cout << "A is " << A.rowdim() << " by " << A.coldim() << std::endl; PID_integer::Element val_A; if (argc == 3) { Transpose<Blackbox> T(&A); if (strcmp(argv[2],"-aat")) { Compose< Transpose<Blackbox>, Blackbox > C (&T, &A); std::cout << "A^T A is " << C.rowdim() << " by " << C.coldim() << std::endl; valence(val_A, C); } else { Compose< Blackbox, Transpose<Blackbox> > C (&A, &T); std::cout << "A A^T is " << C.rowdim() << " by " << C.coldim() << std::endl; valence(val_A, C); } } else { if (A.rowdim() != A.coldim()) { std::cerr << "Valence works only on square matrices, try either to change the dimension in the matrix file, or to compute the valence of A A^T or A^T A, via the -aat or -ata options." << std::endl; exit(0); } else valence (val_A, A); } std::cout << "Valence is " << val_A << std::endl; return 0; } <|endoftext|>
<commit_before>/** * @file * @copyright defined in eos/LICENSE */ #include <fc/io/raw.hpp> #include <fc/bitutil.hpp> #include <fc/smart_ref_impl.hpp> #include <algorithm> #include <mutex> #include <boost/range/adaptor/transformed.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/sequenced_index.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/member.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/device/back_inserter.hpp> #include <boost/iostreams/filter/zlib.hpp> #include <eosio/chain/config.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/chain/transaction.hpp> namespace eosio { namespace chain { using namespace boost::multi_index; struct cached_pub_key { transaction_id_type trx_id; public_key_type pub_key; signature_type sig; fc::microseconds cpu_usage; cached_pub_key(const cached_pub_key&) = delete; cached_pub_key() = delete; cached_pub_key& operator=(const cached_pub_key&) = delete; cached_pub_key(cached_pub_key&&) = default; }; struct by_sig{}; typedef multi_index_container< cached_pub_key, indexed_by< sequenced<>, hashed_unique< tag<by_sig>, member<cached_pub_key, signature_type, &cached_pub_key::sig> > > > recovery_cache_type; void transaction_header::set_reference_block( const block_id_type& reference_block ) { ref_block_num = fc::endian_reverse_u32(reference_block._hash[0]); ref_block_prefix = reference_block._hash[1]; } bool transaction_header::verify_reference_block( const block_id_type& reference_block )const { return ref_block_num == (decltype(ref_block_num))fc::endian_reverse_u32(reference_block._hash[0]) && ref_block_prefix == (decltype(ref_block_prefix))reference_block._hash[1]; } void transaction_header::validate()const { EOS_ASSERT( max_net_usage_words.value < UINT32_MAX / 8UL, transaction_exception, "declared max_net_usage_words overflows when expanded to max net usage" ); } transaction_id_type transaction::id() const { digest_type::encoder enc; fc::raw::pack( enc, *this ); return enc.result(); } digest_type transaction::sig_digest( const chain_id_type& chain_id, const vector<bytes>& cfd )const { digest_type::encoder enc; fc::raw::pack( enc, chain_id ); fc::raw::pack( enc, *this ); if( cfd.size() ) { fc::raw::pack( enc, digest_type::hash(cfd) ); } else { fc::raw::pack( enc, digest_type() ); } return enc.result(); } fc::microseconds transaction::get_signature_keys( const vector<signature_type>& signatures, const chain_id_type& chain_id, fc::time_point deadline, const vector<bytes>& cfd, flat_set<public_key_type>& recovered_pub_keys, bool allow_duplicate_keys)const { try { using boost::adaptors::transformed; constexpr size_t recovery_cache_size = 10000; static recovery_cache_type recovery_cache; static std::mutex cache_mtx; auto start = fc::time_point::now(); recovered_pub_keys.clear(); const digest_type digest = sig_digest(chain_id, cfd); std::unique_lock<std::mutex> lock(cache_mtx, std::defer_lock); fc::microseconds sig_cpu_usage; for(const signature_type& sig : signatures) { auto now = fc::time_point::now(); EOS_ASSERT( now < deadline, tx_cpu_usage_exceeded, "transaction signature verification executed for too long", ("now", now)("deadline", deadline)("start", start) ); public_key_type recov; const auto& tid = id(); lock.lock(); recovery_cache_type::index<by_sig>::type::iterator it = recovery_cache.get<by_sig>().find( sig ); if( it == recovery_cache.get<by_sig>().end() || it->trx_id != tid ) { lock.unlock(); recov = public_key_type( sig, digest ); fc::microseconds cpu_usage = fc::time_point::now() - start; lock.lock(); recovery_cache.emplace_back( cached_pub_key{tid, recov, sig, cpu_usage} ); //could fail on dup signatures; not a problem sig_cpu_usage += cpu_usage; } else { recov = it->pub_key; sig_cpu_usage += it->cpu_usage; } lock.unlock(); bool successful_insertion = false; std::tie(std::ignore, successful_insertion) = recovered_pub_keys.insert(recov); EOS_ASSERT( allow_duplicate_keys || successful_insertion, tx_duplicate_sig, "transaction includes more than one signature signed using the same key associated with public key: ${key}", ("key", recov) ); } lock.lock(); while ( recovery_cache.size() > recovery_cache_size ) recovery_cache.erase( recovery_cache.begin()); lock.unlock(); return sig_cpu_usage; } FC_CAPTURE_AND_RETHROW() } const signature_type& signed_transaction::sign(const private_key_type& key, const chain_id_type& chain_id) { signatures.push_back(key.sign(sig_digest(chain_id, context_free_data))); return signatures.back(); } signature_type signed_transaction::sign(const private_key_type& key, const chain_id_type& chain_id)const { return key.sign(sig_digest(chain_id, context_free_data)); } fc::microseconds signed_transaction::get_signature_keys( const chain_id_type& chain_id, fc::time_point deadline, flat_set<public_key_type>& recovered_pub_keys, bool allow_duplicate_keys)const { return transaction::get_signature_keys(signatures, chain_id, deadline, context_free_data, recovered_pub_keys, allow_duplicate_keys); } uint32_t packed_transaction::get_unprunable_size()const { uint64_t size = config::fixed_net_overhead_of_packed_trx; size += packed_trx.size(); EOS_ASSERT( size <= std::numeric_limits<uint32_t>::max(), tx_too_big, "packed_transaction is too big" ); return static_cast<uint32_t>(size); } uint32_t packed_transaction::get_prunable_size()const { uint64_t size = fc::raw::pack_size(signatures); size += packed_context_free_data.size(); EOS_ASSERT( size <= std::numeric_limits<uint32_t>::max(), tx_too_big, "packed_transaction is too big" ); return static_cast<uint32_t>(size); } digest_type packed_transaction::packed_digest()const { digest_type::encoder prunable; fc::raw::pack( prunable, signatures ); fc::raw::pack( prunable, packed_context_free_data ); digest_type::encoder enc; fc::raw::pack( enc, compression ); fc::raw::pack( enc, packed_trx ); fc::raw::pack( enc, prunable.result() ); return enc.result(); } namespace bio = boost::iostreams; template<size_t Limit> struct read_limiter { using char_type = char; using category = bio::multichar_output_filter_tag; template<typename Sink> size_t write(Sink &sink, const char* s, size_t count) { EOS_ASSERT(_total + count <= Limit, tx_decompression_error, "Exceeded maximum decompressed transaction size"); _total += count; return bio::write(sink, s, count); } size_t _total = 0; }; static vector<bytes> unpack_context_free_data(const bytes& data) { if( data.size() == 0 ) return vector<bytes>(); return fc::raw::unpack< vector<bytes> >(data); } static transaction unpack_transaction(const bytes& data) { return fc::raw::unpack<transaction>(data); } static bytes zlib_decompress(const bytes& data) { try { bytes out; bio::filtering_ostream decomp; decomp.push(bio::zlib_decompressor()); decomp.push(read_limiter<1*1024*1024>()); // limit to 10 megs decompressed for zip bomb protections decomp.push(bio::back_inserter(out)); bio::write(decomp, data.data(), data.size()); bio::close(decomp); return out; } catch( fc::exception& er ) { throw; } catch( ... ) { fc::unhandled_exception er( FC_LOG_MESSAGE( warn, "internal decompression error"), std::current_exception() ); throw er; } } static vector<bytes> zlib_decompress_context_free_data(const bytes& data) { if( data.size() == 0 ) return vector<bytes>(); bytes out = zlib_decompress(data); return unpack_context_free_data(out); } static transaction zlib_decompress_transaction(const bytes& data) { bytes out = zlib_decompress(data); return unpack_transaction(out); } static bytes pack_transaction(const transaction& t) { return fc::raw::pack(t); } static bytes pack_context_free_data(const vector<bytes>& cfd ) { if( cfd.size() == 0 ) return bytes(); return fc::raw::pack(cfd); } static bytes zlib_compress_context_free_data(const vector<bytes>& cfd ) { if( cfd.size() == 0 ) return bytes(); bytes in = pack_context_free_data(cfd); bytes out; bio::filtering_ostream comp; comp.push(bio::zlib_compressor(bio::zlib::best_compression)); comp.push(bio::back_inserter(out)); bio::write(comp, in.data(), in.size()); bio::close(comp); return out; } static bytes zlib_compress_transaction(const transaction& t) { bytes in = pack_transaction(t); bytes out; bio::filtering_ostream comp; comp.push(bio::zlib_compressor(bio::zlib::best_compression)); comp.push(bio::back_inserter(out)); bio::write(comp, in.data(), in.size()); bio::close(comp); return out; } bytes packed_transaction::get_raw_transaction() const { try { switch(compression) { case none: return packed_trx; case zlib: return zlib_decompress(packed_trx); default: EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm"); } } FC_CAPTURE_AND_RETHROW((compression)(packed_trx)) } packed_transaction::packed_transaction( bytes&& packed_txn, vector<signature_type>&& sigs, bytes&& packed_cfd, compression_type _compression ) :signatures(std::move(sigs)) ,compression(_compression) ,packed_context_free_data(std::move(packed_cfd)) ,packed_trx(std::move(packed_txn)) { local_unpack_transaction({}); if( !packed_context_free_data.empty() ) { local_unpack_context_free_data(); } } packed_transaction::packed_transaction( bytes&& packed_txn, vector<signature_type>&& sigs, vector<bytes>&& cfd, compression_type _compression ) :signatures(std::move(sigs)) ,compression(_compression) ,packed_trx(std::move(packed_txn)) { local_unpack_transaction( std::move( cfd ) ); if( !unpacked_trx.context_free_data.empty() ) { local_pack_context_free_data(); } } packed_transaction::packed_transaction( transaction&& t, vector<signature_type>&& sigs, bytes&& packed_cfd, compression_type _compression ) :signatures(std::move(sigs)) ,compression(_compression) ,packed_context_free_data(std::move(packed_cfd)) ,unpacked_trx(std::move(t), signatures, {}) { local_pack_transaction(); if( !packed_context_free_data.empty() ) { local_unpack_context_free_data(); } } void packed_transaction::reflector_init() { // called after construction, but always on the same thread and before packed_transaction passed to any other threads static_assert(&fc::reflector_init_visitor<packed_transaction>::reflector_init, "FC with reflector_init required"); static_assert(fc::raw::has_feature_reflector_init_on_unpacked_reflected_types, "FC unpack needs to call reflector_init otherwise unpacked_trx will not be initialized"); EOS_ASSERT( unpacked_trx.expiration == time_point_sec(), tx_decompression_error, "packed_transaction already unpacked" ); local_unpack_transaction({}); local_unpack_context_free_data(); } void packed_transaction::local_unpack_transaction(vector<bytes>&& context_free_data) { try { switch( compression ) { case none: unpacked_trx = signed_transaction( unpack_transaction( packed_trx ), signatures, std::move(context_free_data) ); break; case zlib: unpacked_trx = signed_transaction( zlib_decompress_transaction( packed_trx ), signatures, std::move(context_free_data) ); break; default: EOS_THROW( unknown_transaction_compression, "Unknown transaction compression algorithm" ); } } FC_CAPTURE_AND_RETHROW( (compression) ) } void packed_transaction::local_unpack_context_free_data() { try { EOS_ASSERT(unpacked_trx.context_free_data.empty(), tx_decompression_error, "packed_transaction.context_free_data not empty"); switch( compression ) { case none: unpacked_trx.context_free_data = unpack_context_free_data( packed_context_free_data ); break; case zlib: unpacked_trx.context_free_data = zlib_decompress_context_free_data( packed_context_free_data ); break; default: EOS_THROW( unknown_transaction_compression, "Unknown transaction compression algorithm" ); } } FC_CAPTURE_AND_RETHROW( (compression) ) } void packed_transaction::local_pack_transaction() { try { switch(compression) { case none: packed_trx = pack_transaction(unpacked_trx); break; case zlib: packed_trx = zlib_compress_transaction(unpacked_trx); break; default: EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm"); } } FC_CAPTURE_AND_RETHROW((compression)) } void packed_transaction::local_pack_context_free_data() { try { switch(compression) { case none: packed_context_free_data = pack_context_free_data(unpacked_trx.context_free_data); break; case zlib: packed_context_free_data = zlib_compress_context_free_data(unpacked_trx.context_free_data); break; default: EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm"); } } FC_CAPTURE_AND_RETHROW((compression)) } } } // eosio::chain <commit_msg>Fix comment on max trx decompressed size<commit_after>/** * @file * @copyright defined in eos/LICENSE */ #include <fc/io/raw.hpp> #include <fc/bitutil.hpp> #include <fc/smart_ref_impl.hpp> #include <algorithm> #include <mutex> #include <boost/range/adaptor/transformed.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/sequenced_index.hpp> #include <boost/multi_index/hashed_index.hpp> #include <boost/multi_index/member.hpp> #include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/device/back_inserter.hpp> #include <boost/iostreams/filter/zlib.hpp> #include <eosio/chain/config.hpp> #include <eosio/chain/exceptions.hpp> #include <eosio/chain/transaction.hpp> namespace eosio { namespace chain { using namespace boost::multi_index; struct cached_pub_key { transaction_id_type trx_id; public_key_type pub_key; signature_type sig; fc::microseconds cpu_usage; cached_pub_key(const cached_pub_key&) = delete; cached_pub_key() = delete; cached_pub_key& operator=(const cached_pub_key&) = delete; cached_pub_key(cached_pub_key&&) = default; }; struct by_sig{}; typedef multi_index_container< cached_pub_key, indexed_by< sequenced<>, hashed_unique< tag<by_sig>, member<cached_pub_key, signature_type, &cached_pub_key::sig> > > > recovery_cache_type; void transaction_header::set_reference_block( const block_id_type& reference_block ) { ref_block_num = fc::endian_reverse_u32(reference_block._hash[0]); ref_block_prefix = reference_block._hash[1]; } bool transaction_header::verify_reference_block( const block_id_type& reference_block )const { return ref_block_num == (decltype(ref_block_num))fc::endian_reverse_u32(reference_block._hash[0]) && ref_block_prefix == (decltype(ref_block_prefix))reference_block._hash[1]; } void transaction_header::validate()const { EOS_ASSERT( max_net_usage_words.value < UINT32_MAX / 8UL, transaction_exception, "declared max_net_usage_words overflows when expanded to max net usage" ); } transaction_id_type transaction::id() const { digest_type::encoder enc; fc::raw::pack( enc, *this ); return enc.result(); } digest_type transaction::sig_digest( const chain_id_type& chain_id, const vector<bytes>& cfd )const { digest_type::encoder enc; fc::raw::pack( enc, chain_id ); fc::raw::pack( enc, *this ); if( cfd.size() ) { fc::raw::pack( enc, digest_type::hash(cfd) ); } else { fc::raw::pack( enc, digest_type() ); } return enc.result(); } fc::microseconds transaction::get_signature_keys( const vector<signature_type>& signatures, const chain_id_type& chain_id, fc::time_point deadline, const vector<bytes>& cfd, flat_set<public_key_type>& recovered_pub_keys, bool allow_duplicate_keys)const { try { using boost::adaptors::transformed; constexpr size_t recovery_cache_size = 10000; static recovery_cache_type recovery_cache; static std::mutex cache_mtx; auto start = fc::time_point::now(); recovered_pub_keys.clear(); const digest_type digest = sig_digest(chain_id, cfd); std::unique_lock<std::mutex> lock(cache_mtx, std::defer_lock); fc::microseconds sig_cpu_usage; for(const signature_type& sig : signatures) { auto now = fc::time_point::now(); EOS_ASSERT( now < deadline, tx_cpu_usage_exceeded, "transaction signature verification executed for too long", ("now", now)("deadline", deadline)("start", start) ); public_key_type recov; const auto& tid = id(); lock.lock(); recovery_cache_type::index<by_sig>::type::iterator it = recovery_cache.get<by_sig>().find( sig ); if( it == recovery_cache.get<by_sig>().end() || it->trx_id != tid ) { lock.unlock(); recov = public_key_type( sig, digest ); fc::microseconds cpu_usage = fc::time_point::now() - start; lock.lock(); recovery_cache.emplace_back( cached_pub_key{tid, recov, sig, cpu_usage} ); //could fail on dup signatures; not a problem sig_cpu_usage += cpu_usage; } else { recov = it->pub_key; sig_cpu_usage += it->cpu_usage; } lock.unlock(); bool successful_insertion = false; std::tie(std::ignore, successful_insertion) = recovered_pub_keys.insert(recov); EOS_ASSERT( allow_duplicate_keys || successful_insertion, tx_duplicate_sig, "transaction includes more than one signature signed using the same key associated with public key: ${key}", ("key", recov) ); } lock.lock(); while ( recovery_cache.size() > recovery_cache_size ) recovery_cache.erase( recovery_cache.begin()); lock.unlock(); return sig_cpu_usage; } FC_CAPTURE_AND_RETHROW() } const signature_type& signed_transaction::sign(const private_key_type& key, const chain_id_type& chain_id) { signatures.push_back(key.sign(sig_digest(chain_id, context_free_data))); return signatures.back(); } signature_type signed_transaction::sign(const private_key_type& key, const chain_id_type& chain_id)const { return key.sign(sig_digest(chain_id, context_free_data)); } fc::microseconds signed_transaction::get_signature_keys( const chain_id_type& chain_id, fc::time_point deadline, flat_set<public_key_type>& recovered_pub_keys, bool allow_duplicate_keys)const { return transaction::get_signature_keys(signatures, chain_id, deadline, context_free_data, recovered_pub_keys, allow_duplicate_keys); } uint32_t packed_transaction::get_unprunable_size()const { uint64_t size = config::fixed_net_overhead_of_packed_trx; size += packed_trx.size(); EOS_ASSERT( size <= std::numeric_limits<uint32_t>::max(), tx_too_big, "packed_transaction is too big" ); return static_cast<uint32_t>(size); } uint32_t packed_transaction::get_prunable_size()const { uint64_t size = fc::raw::pack_size(signatures); size += packed_context_free_data.size(); EOS_ASSERT( size <= std::numeric_limits<uint32_t>::max(), tx_too_big, "packed_transaction is too big" ); return static_cast<uint32_t>(size); } digest_type packed_transaction::packed_digest()const { digest_type::encoder prunable; fc::raw::pack( prunable, signatures ); fc::raw::pack( prunable, packed_context_free_data ); digest_type::encoder enc; fc::raw::pack( enc, compression ); fc::raw::pack( enc, packed_trx ); fc::raw::pack( enc, prunable.result() ); return enc.result(); } namespace bio = boost::iostreams; template<size_t Limit> struct read_limiter { using char_type = char; using category = bio::multichar_output_filter_tag; template<typename Sink> size_t write(Sink &sink, const char* s, size_t count) { EOS_ASSERT(_total + count <= Limit, tx_decompression_error, "Exceeded maximum decompressed transaction size"); _total += count; return bio::write(sink, s, count); } size_t _total = 0; }; static vector<bytes> unpack_context_free_data(const bytes& data) { if( data.size() == 0 ) return vector<bytes>(); return fc::raw::unpack< vector<bytes> >(data); } static transaction unpack_transaction(const bytes& data) { return fc::raw::unpack<transaction>(data); } static bytes zlib_decompress(const bytes& data) { try { bytes out; bio::filtering_ostream decomp; decomp.push(bio::zlib_decompressor()); decomp.push(read_limiter<1*1024*1024>()); // limit to 1 meg decompressed for zip bomb protections decomp.push(bio::back_inserter(out)); bio::write(decomp, data.data(), data.size()); bio::close(decomp); return out; } catch( fc::exception& er ) { throw; } catch( ... ) { fc::unhandled_exception er( FC_LOG_MESSAGE( warn, "internal decompression error"), std::current_exception() ); throw er; } } static vector<bytes> zlib_decompress_context_free_data(const bytes& data) { if( data.size() == 0 ) return vector<bytes>(); bytes out = zlib_decompress(data); return unpack_context_free_data(out); } static transaction zlib_decompress_transaction(const bytes& data) { bytes out = zlib_decompress(data); return unpack_transaction(out); } static bytes pack_transaction(const transaction& t) { return fc::raw::pack(t); } static bytes pack_context_free_data(const vector<bytes>& cfd ) { if( cfd.size() == 0 ) return bytes(); return fc::raw::pack(cfd); } static bytes zlib_compress_context_free_data(const vector<bytes>& cfd ) { if( cfd.size() == 0 ) return bytes(); bytes in = pack_context_free_data(cfd); bytes out; bio::filtering_ostream comp; comp.push(bio::zlib_compressor(bio::zlib::best_compression)); comp.push(bio::back_inserter(out)); bio::write(comp, in.data(), in.size()); bio::close(comp); return out; } static bytes zlib_compress_transaction(const transaction& t) { bytes in = pack_transaction(t); bytes out; bio::filtering_ostream comp; comp.push(bio::zlib_compressor(bio::zlib::best_compression)); comp.push(bio::back_inserter(out)); bio::write(comp, in.data(), in.size()); bio::close(comp); return out; } bytes packed_transaction::get_raw_transaction() const { try { switch(compression) { case none: return packed_trx; case zlib: return zlib_decompress(packed_trx); default: EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm"); } } FC_CAPTURE_AND_RETHROW((compression)(packed_trx)) } packed_transaction::packed_transaction( bytes&& packed_txn, vector<signature_type>&& sigs, bytes&& packed_cfd, compression_type _compression ) :signatures(std::move(sigs)) ,compression(_compression) ,packed_context_free_data(std::move(packed_cfd)) ,packed_trx(std::move(packed_txn)) { local_unpack_transaction({}); if( !packed_context_free_data.empty() ) { local_unpack_context_free_data(); } } packed_transaction::packed_transaction( bytes&& packed_txn, vector<signature_type>&& sigs, vector<bytes>&& cfd, compression_type _compression ) :signatures(std::move(sigs)) ,compression(_compression) ,packed_trx(std::move(packed_txn)) { local_unpack_transaction( std::move( cfd ) ); if( !unpacked_trx.context_free_data.empty() ) { local_pack_context_free_data(); } } packed_transaction::packed_transaction( transaction&& t, vector<signature_type>&& sigs, bytes&& packed_cfd, compression_type _compression ) :signatures(std::move(sigs)) ,compression(_compression) ,packed_context_free_data(std::move(packed_cfd)) ,unpacked_trx(std::move(t), signatures, {}) { local_pack_transaction(); if( !packed_context_free_data.empty() ) { local_unpack_context_free_data(); } } void packed_transaction::reflector_init() { // called after construction, but always on the same thread and before packed_transaction passed to any other threads static_assert(&fc::reflector_init_visitor<packed_transaction>::reflector_init, "FC with reflector_init required"); static_assert(fc::raw::has_feature_reflector_init_on_unpacked_reflected_types, "FC unpack needs to call reflector_init otherwise unpacked_trx will not be initialized"); EOS_ASSERT( unpacked_trx.expiration == time_point_sec(), tx_decompression_error, "packed_transaction already unpacked" ); local_unpack_transaction({}); local_unpack_context_free_data(); } void packed_transaction::local_unpack_transaction(vector<bytes>&& context_free_data) { try { switch( compression ) { case none: unpacked_trx = signed_transaction( unpack_transaction( packed_trx ), signatures, std::move(context_free_data) ); break; case zlib: unpacked_trx = signed_transaction( zlib_decompress_transaction( packed_trx ), signatures, std::move(context_free_data) ); break; default: EOS_THROW( unknown_transaction_compression, "Unknown transaction compression algorithm" ); } } FC_CAPTURE_AND_RETHROW( (compression) ) } void packed_transaction::local_unpack_context_free_data() { try { EOS_ASSERT(unpacked_trx.context_free_data.empty(), tx_decompression_error, "packed_transaction.context_free_data not empty"); switch( compression ) { case none: unpacked_trx.context_free_data = unpack_context_free_data( packed_context_free_data ); break; case zlib: unpacked_trx.context_free_data = zlib_decompress_context_free_data( packed_context_free_data ); break; default: EOS_THROW( unknown_transaction_compression, "Unknown transaction compression algorithm" ); } } FC_CAPTURE_AND_RETHROW( (compression) ) } void packed_transaction::local_pack_transaction() { try { switch(compression) { case none: packed_trx = pack_transaction(unpacked_trx); break; case zlib: packed_trx = zlib_compress_transaction(unpacked_trx); break; default: EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm"); } } FC_CAPTURE_AND_RETHROW((compression)) } void packed_transaction::local_pack_context_free_data() { try { switch(compression) { case none: packed_context_free_data = pack_context_free_data(unpacked_trx.context_free_data); break; case zlib: packed_context_free_data = zlib_compress_context_free_data(unpacked_trx.context_free_data); break; default: EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm"); } } FC_CAPTURE_AND_RETHROW((compression)) } } } // eosio::chain <|endoftext|>
<commit_before>#include <Element.h> #include <FWPlatform.h> #include <HeadingText.h> #include <TextLabel.h> #include <LinearLayout.h> #include <FWApplication.h> #include <cassert> using namespace std; atomic<int> Element::nextInternalId(1); Element::~Element() { // the platform itself cannot be unregistered at this point if (platform && this != platform) { platform->unregisterElement(this); } } void Element::initialize(FWPlatform * _platform) { assert(_platform); if (_platform) { platform = _platform; platform->registerElement(this); create(); for (auto & c : pendingCommands) { sendCommand(c); } pendingCommands.clear(); } assert(isInitialized()); } void Element::initializeChildren() { assert(isInitialized()); if (isInitialized()) { for (auto & c : getChildren()) { c->initialize(platform); c->initializeChildren(); } } } void Element::setError(bool t) { if ((t && !has_error) || (!t && has_error)) { has_error = t; cerr << "setting error to " << has_error << endl; Command c(Command::SET_ERROR, getInternalId()); c.setValue(t ? 1 : 0); if (t) c.setTextValue("Arvo ei kelpaa!"); sendCommand(c); } } void Element::setEnabled(bool _is_enabled) { is_enabled = _is_enabled; Command c(Command::SET_ENABLED, getInternalId()); c.setValue(is_enabled ? 1 : 0); sendCommand(c); } void Element::show() { is_visible = true; Command c(Command::SET_VISIBILITY, getInternalId()); c.setValue(1); sendCommand(c); } void Element::hide() { is_visible = false; Command c(Command::SET_VISIBILITY, getInternalId()); c.setValue(0); sendCommand(c); } void Element::style(const std::string & key, const std::string & value) { Command c(Command::SET_STYLE, getInternalId()); c.setTextValue(key); c.setTextValue2(value); sendCommand(c); } void Element::sendCommand(const Command & command) { if (platform) { platform->sendCommand2(command); } else { pendingCommands.push_back(command); } } Element & Element::addHeading(const std::string & text) { return addChild(make_shared<HeadingText>(text)); } Element & Element::addText(const std::string & text) { return addChild(make_shared<TextLabel>(text)); } Element & Element::addHorizontalLayout(int _id) { return addChild(make_shared<LinearLayout>(FW_HORIZONTAL, _id)); } Element & Element::addVerticalLayout(int _id) { return addChild(make_shared<LinearLayout>(FW_VERTICAL, _id)); } void Element::onEvent(Event & ev) { if (!ev.isHandled()) { if (ev.isBroadcast()) { for (auto & c : getChildren()){ ev.dispatch(*c); } } else if (parent) { ev.dispatch(*parent); } } } void Element::showMessageDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); } std::string Element::showInputDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); return platform->getModalResultText(); } void Element::showToast(const std::string & message, int duration) { Command c(Command::CREATE_TOAST, getParentInternalId(), getInternalId()); c.setTextValue(message); c.setValue(duration); sendCommand(c); } FWApplication & Element::getApplication() { auto p = getPlatform().getFirstChild(); return dynamic_cast<FWApplication&>(*p); } const FWApplication & Element::getApplication() const { auto p = getPlatform().getFirstChild(); return dynamic_cast<const FWApplication&>(*p); } void Element::removeChild(Element * child) { for (auto it = children.begin(); it != children.end(); it++) { if (it->get() == child) { sendCommand(Command(Command::DELETE_ELEMENT, getInternalId(), child->getInternalId())); children.erase(it); return; } } } int Element::createTimer(int timeout_ms) { int timer_id = getNextInternalId(); sendCommand(Command(Command::CREATE_TIMER, getInternalId(), timer_id)); return timer_id; } <commit_msg>Add timeout to createTimer<commit_after>#include <Element.h> #include <FWPlatform.h> #include <HeadingText.h> #include <TextLabel.h> #include <LinearLayout.h> #include <FWApplication.h> #include <cassert> using namespace std; atomic<int> Element::nextInternalId(1); Element::~Element() { // the platform itself cannot be unregistered at this point if (platform && this != platform) { platform->unregisterElement(this); } } void Element::initialize(FWPlatform * _platform) { assert(_platform); if (_platform) { platform = _platform; platform->registerElement(this); create(); for (auto & c : pendingCommands) { sendCommand(c); } pendingCommands.clear(); } assert(isInitialized()); } void Element::initializeChildren() { assert(isInitialized()); if (isInitialized()) { for (auto & c : getChildren()) { c->initialize(platform); c->initializeChildren(); } } } void Element::setError(bool t) { if ((t && !has_error) || (!t && has_error)) { has_error = t; cerr << "setting error to " << has_error << endl; Command c(Command::SET_ERROR, getInternalId()); c.setValue(t ? 1 : 0); if (t) c.setTextValue("Arvo ei kelpaa!"); sendCommand(c); } } void Element::setEnabled(bool _is_enabled) { is_enabled = _is_enabled; Command c(Command::SET_ENABLED, getInternalId()); c.setValue(is_enabled ? 1 : 0); sendCommand(c); } void Element::show() { is_visible = true; Command c(Command::SET_VISIBILITY, getInternalId()); c.setValue(1); sendCommand(c); } void Element::hide() { is_visible = false; Command c(Command::SET_VISIBILITY, getInternalId()); c.setValue(0); sendCommand(c); } void Element::style(const std::string & key, const std::string & value) { Command c(Command::SET_STYLE, getInternalId()); c.setTextValue(key); c.setTextValue2(value); sendCommand(c); } void Element::sendCommand(const Command & command) { if (platform) { platform->sendCommand2(command); } else { pendingCommands.push_back(command); } } Element & Element::addHeading(const std::string & text) { return addChild(make_shared<HeadingText>(text)); } Element & Element::addText(const std::string & text) { return addChild(make_shared<TextLabel>(text)); } Element & Element::addHorizontalLayout(int _id) { return addChild(make_shared<LinearLayout>(FW_HORIZONTAL, _id)); } Element & Element::addVerticalLayout(int _id) { return addChild(make_shared<LinearLayout>(FW_VERTICAL, _id)); } void Element::onEvent(Event & ev) { if (!ev.isHandled()) { if (ev.isBroadcast()) { for (auto & c : getChildren()){ ev.dispatch(*c); } } else if (parent) { ev.dispatch(*parent); } } } void Element::showMessageDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_MESSAGE_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); } std::string Element::showInputDialog(const std::string & title, const std::string & text) { Command c(Command::SHOW_INPUT_DIALOG, getParentInternalId(), getInternalId()); c.setTextValue(title); c.setTextValue2(text); sendCommand(c); return platform->getModalResultText(); } void Element::showToast(const std::string & message, int duration) { Command c(Command::CREATE_TOAST, getParentInternalId(), getInternalId()); c.setTextValue(message); c.setValue(duration); sendCommand(c); } FWApplication & Element::getApplication() { auto p = getPlatform().getFirstChild(); return dynamic_cast<FWApplication&>(*p); } const FWApplication & Element::getApplication() const { auto p = getPlatform().getFirstChild(); return dynamic_cast<const FWApplication&>(*p); } void Element::removeChild(Element * child) { for (auto it = children.begin(); it != children.end(); it++) { if (it->get() == child) { sendCommand(Command(Command::DELETE_ELEMENT, getInternalId(), child->getInternalId())); children.erase(it); return; } } } int Element::createTimer(int timeout_ms) { int timer_id = getNextInternalId(); Command c(Command::CREATE_TIMER, getInternalId(), timer_id); c.setValue(timeout_ms); sendCommand(c); return timer_id; } <|endoftext|>
<commit_before>/** * \file FFTPlot.cpp * \brief Contains the FFTPlot class */ #include "FFTPlot.h" // class constructor FFTPlot::FFTPlot(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : ChaosPlot(parent, id, pos, size, style, name) { side_gutter_size = 0; bottom_gutter_size = 20; graph_title = wxT("Fast Fourier transform"); graph_subtitle = wxT("Power Spectral Density vs. Frequency (Hz)"); } // class destructor FFTPlot::~FFTPlot() { // insert your code here } void FFTPlot::drawPlot() { const int points_to_graph = 400; const int N = 8192; int x_axis_max = (int)(float(points_to_graph)/(N*1/float(LIBCHAOS_SAMPLE_FREQUENCY))); startDraw(); drawXAxis(0.0,x_axis_max,1200); float a; float a_old=0; float x_scale = float(graph_width)/points_to_graph; float y_scale = graph_height/15.0; libchaos_getFFTPlotPoint(&a_old, 1); a_old = graph_height + top_gutter_size - (a_old*y_scale); for(int i = 0; i < points_to_graph; i++) { libchaos_getFFTPlotPoint(&a, i+2); a = graph_height + top_gutter_size - (a*y_scale); if ( a > graph_height + top_gutter_size ) { a = graph_height + top_gutter_size; } //Use blue pen wxPen bPen(*wxBLUE, 2); // blue pen of width 2 buffer->SetPen(bPen); buffer->DrawLine((int)((i*x_scale)+side_gutter_size), (int)(a_old), (int)(((i+1)*x_scale)+side_gutter_size), (int)(a)); a_old = a; } endDraw(); } <commit_msg>- added additional comments for the FFT<commit_after>/** * \file FFTPlot.cpp * \brief Contains the FFTPlot class */ #include "FFTPlot.h" FFTPlot::FFTPlot(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : ChaosPlot(parent, id, pos, size, style, name) { /** * Constructor for the FFTPlot class. * * This class inherits basic plot functionality from ChaosPlot */ side_gutter_size = 0; bottom_gutter_size = 20; graph_title = wxT("Fast Fourier transform"); graph_subtitle = wxT("Power Spectral Density vs. Frequency (Hz)"); } FFTPlot::~FFTPlot() { /** * Destructor for the FFTPlot */ } void FFTPlot::drawPlot() { /** * Draw the FFT Plot * * The FFT data is not collected by this function but is simply * draw by it. The main timer call to libchaos_readPlot() handles * the data collection and FFT calculation and then stores that * data. Calls to libchaos_getFFTPlotPoint() pull in the data from * libchaos. From here, it's just plotting the points where we want * them. */ // number of points to use in the graph const int points_to_graph = 400; // number of data points used for FFT const int N = 8192; int x_axis_max = (int)(float(points_to_graph)/(N*1/float(LIBCHAOS_SAMPLE_FREQUENCY))); startDraw(); drawXAxis(0.0,x_axis_max,1200); float a; float a_old=0; float x_scale = float(graph_width)/points_to_graph; float y_scale = graph_height/15.0; libchaos_getFFTPlotPoint(&a_old, 1); a_old = graph_height + top_gutter_size - (a_old*y_scale); for(int i = 0; i < points_to_graph; i++) { libchaos_getFFTPlotPoint(&a, i+2); a = graph_height + top_gutter_size - (a*y_scale); if ( a > graph_height + top_gutter_size ) { a = graph_height + top_gutter_size; } //Use blue pen wxPen bPen(*wxBLUE, 2); // blue pen of width 2 buffer->SetPen(bPen); buffer->DrawLine((int)((i*x_scale)+side_gutter_size), (int)(a_old), (int)(((i+1)*x_scale)+side_gutter_size), (int)(a)); a_old = a; } endDraw(); } <|endoftext|>
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome_frame/turndown_prompt/turndown_prompt.h" #include <atlbase.h> #include <shlguid.h> #include "base/bind.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/win/scoped_bstr.h" #include "base/win/scoped_comptr.h" #include "base/win/win_util.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/google_update_settings.h" #include "chrome/installer/util/install_util.h" #include "chrome/installer/util/installation_state.h" #include "chrome/installer/util/util_constants.h" #include "chrome_frame/infobars/infobar_manager.h" #include "chrome_frame/policy_settings.h" #include "chrome_frame/ready_mode/internal/ready_mode_web_browser_adapter.h" #include "chrome_frame/ready_mode/internal/url_launcher.h" #include "chrome_frame/simple_resource_loader.h" #include "chrome_frame/turndown_prompt/reshow_state.h" #include "chrome_frame/turndown_prompt/turndown_prompt_content.h" #include "chrome_frame/utils.h" #include "grit/chromium_strings.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" namespace { // Time between showings of the turndown prompt. const int kTurndownPromptReshowDeltaMinutes = 60 * 24 * 7; void OnUninstallClicked(UrlLauncher* url_launcher); // Manages the Turndown UI in response to browsing ChromeFrame-rendered // pages. class BrowserObserver : public ReadyModeWebBrowserAdapter::Observer { public: BrowserObserver(IWebBrowser2* web_browser, ReadyModeWebBrowserAdapter* adapter); // ReadyModeWebBrowserAdapter::Observer implementation virtual void OnNavigateTo(const string16& url); virtual void OnRenderInChromeFrame(const string16& url); virtual void OnRenderInHost(const string16& url); private: // Shows the turndown prompt if it hasn't been seen since // kTurndownPromptReshowDeltaMinutes. void ShowPrompt(); void Hide(); // Returns a self-managed pointer that is not guaranteed to survive handling // of Windows events. For safety's sake, retrieve this pointer for each use // and do not store it for use outside of scope. InfobarManager* GetInfobarManager(); GURL rendered_url_; base::win::ScopedComPtr<IWebBrowser2> web_browser_; ReadyModeWebBrowserAdapter* adapter_; DISALLOW_COPY_AND_ASSIGN(BrowserObserver); }; // Implements launching of a URL in an instance of IWebBrowser2. class UrlLauncherImpl : public UrlLauncher { public: explicit UrlLauncherImpl(IWebBrowser2* web_browser); // UrlLauncher implementation void LaunchUrl(const string16& url); private: base::win::ScopedComPtr<IWebBrowser2> web_browser_; }; UrlLauncherImpl::UrlLauncherImpl(IWebBrowser2* web_browser) { DCHECK(web_browser); web_browser_ = web_browser; } void UrlLauncherImpl::LaunchUrl(const string16& url) { VARIANT flags = { VT_I4 }; V_I4(&flags) = navOpenInNewWindow; base::win::ScopedBstr location(url.c_str()); HRESULT hr = web_browser_->Navigate(location, &flags, NULL, NULL, NULL); DLOG_IF(ERROR, FAILED(hr)) << "Failed to invoke Navigate on IWebBrowser2. " << "Error: " << hr; } BrowserObserver::BrowserObserver(IWebBrowser2* web_browser, ReadyModeWebBrowserAdapter* adapter) : web_browser_(web_browser), adapter_(adapter) { } void BrowserObserver::OnNavigateTo(const string16& url) { if (!net::registry_controlled_domains::SameDomainOrHost( GURL(url), rendered_url_, net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES)) { rendered_url_ = GURL(); Hide(); } } void BrowserObserver::OnRenderInChromeFrame(const string16& url) { ShowPrompt(); rendered_url_ = GURL(url); } void BrowserObserver::OnRenderInHost(const string16& url) { Hide(); rendered_url_ = GURL(url); } void BrowserObserver::ShowPrompt() { turndown_prompt::ReshowState reshow_state( base::TimeDelta::FromMinutes(kTurndownPromptReshowDeltaMinutes)); // Short-circuit if the prompt shouldn't be shown again yet. if (!reshow_state.HasReshowDeltaExpired(base::Time::Now())) return; // This pointer is self-managed and not guaranteed to survive handling of // Windows events. For safety's sake, retrieve this pointer for each use and // do not store it for use outside of scope. InfobarManager* infobar_manager = GetInfobarManager(); if (infobar_manager) { // Owned by infobar_content scoped_ptr<UrlLauncher> url_launcher(new UrlLauncherImpl(web_browser_)); // Owned by infobar_manager scoped_ptr<InfobarContent> infobar_content(new TurndownPromptContent( url_launcher.release(), base::Bind(&OnUninstallClicked, base::Owned(new UrlLauncherImpl(web_browser_))))); if (infobar_manager->Show(infobar_content.release(), TOP_INFOBAR)) { // Update state in the registry that the prompt was shown. reshow_state.MarkShown(base::Time::Now()); } } } void BrowserObserver::Hide() { InfobarManager* infobar_manager = GetInfobarManager(); if (infobar_manager) infobar_manager->HideAll(); } InfobarManager* BrowserObserver::GetInfobarManager() { HRESULT hr = NOERROR; base::win::ScopedComPtr<IOleWindow> ole_window; hr = DoQueryService(SID_SShellBrowser, web_browser_, ole_window.Receive()); if (FAILED(hr) || ole_window == NULL) { DLOG(ERROR) << "Failed to query SID_SShellBrowser from IWebBrowser2. " << "Error: " << hr; return NULL; } HWND web_browser_hwnd = NULL; hr = ole_window->GetWindow(&web_browser_hwnd); if (FAILED(hr) || web_browser_hwnd == NULL) { DLOG(ERROR) << "Failed to query HWND from IOleWindow. " << "Error: " << hr; return NULL; } return InfobarManager::Get(web_browser_hwnd); } // Returns true if the module into which this code is linked is installed at // system-level. bool IsCurrentModuleSystemLevel() { base::FilePath dll_path; if (PathService::Get(base::DIR_MODULE, &dll_path)) return !InstallUtil::IsPerUserInstall(dll_path.value().c_str()); return false; } // Attempts to create a ReadyModeWebBrowserAdapter instance. bool CreateWebBrowserAdapter(ReadyModeWebBrowserAdapter** adapter) { *adapter = NULL; CComObject<ReadyModeWebBrowserAdapter>* com_object; HRESULT hr = CComObject<ReadyModeWebBrowserAdapter>::CreateInstance(&com_object); if (FAILED(hr)) { DLOG(ERROR) << "Failed to create instance of ReadyModeWebBrowserAdapter. " << "Error: " << hr; return false; } com_object->AddRef(); *adapter = com_object; return true; } // Attempts to install Turndown prompts in the provided web browser. bool InstallPrompts(IWebBrowser2* web_browser) { base::win::ScopedComPtr<ReadyModeWebBrowserAdapter, NULL> adapter; if (!CreateWebBrowserAdapter(adapter.Receive())) return false; // Pass ownership of our delegate to the BrowserObserver scoped_ptr<ReadyModeWebBrowserAdapter::Observer> browser_observer( new BrowserObserver(web_browser, adapter)); // Owns the BrowserObserver return adapter->Initialize(web_browser, browser_observer.release()); } // Launches the Chrome Frame uninstaller in response to user action. This // implementation should not be used to uninstall MSI-based versions of GCF, // since those must be removed by way of Windows Installer machinery. void LaunchChromeFrameUninstaller() { BrowserDistribution* dist = BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_FRAME); const bool system_level = IsCurrentModuleSystemLevel(); installer::ProductState product_state; if (!product_state.Initialize(system_level, dist)) { DLOG(ERROR) << "Chrome frame isn't installed at " << (system_level ? "system" : "user") << " level."; return; } CommandLine uninstall_command(product_state.uninstall_command()); if (uninstall_command.GetProgram().empty()) { DLOG(ERROR) << "No uninstall command found in registry."; return; } // Force Uninstall silences the prompt to reboot to complete uninstall. uninstall_command.AppendSwitch(installer::switches::kForceUninstall); VLOG(1) << "Uninstalling Chrome Frame with command: " << uninstall_command.GetCommandLineString(); base::LaunchProcess(uninstall_command, base::LaunchOptions(), NULL); } void LaunchLearnMoreURL(UrlLauncher* url_launcher) { url_launcher->LaunchUrl(SimpleResourceLoader::Get( IDS_CHROME_FRAME_TURNDOWN_LEARN_MORE_URL)); } void OnUninstallClicked(UrlLauncher* url_launcher) { LaunchChromeFrameUninstaller(); LaunchLearnMoreURL(url_launcher); } } // namespace namespace turndown_prompt { bool IsPromptSuppressed() { // See if this is an MSI install of GCF or if updates have been disabled. BrowserDistribution* dist = BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_FRAME); const bool system_level = IsCurrentModuleSystemLevel(); bool multi_install = false; installer::ProductState product_state; if (product_state.Initialize(system_level, dist)) { if (product_state.is_msi()) return true; multi_install = product_state.is_multi_install(); } if (multi_install) { dist = BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_BINARIES); } if (GoogleUpdateSettings::GetAppUpdatePolicy(dist->GetAppGuid(), NULL) == GoogleUpdateSettings::UPDATES_DISABLED) { return true; } // See if the prompt is explicitly suppressed via GP. return PolicySettings::GetInstance()->suppress_turndown_prompt(); } void Configure(IWebBrowser2* web_browser) { if (!IsPromptSuppressed()) InstallPrompts(web_browser); } } // namespace turndown_prompt <commit_msg>Show the Chrome Frame turndown prompt daily.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome_frame/turndown_prompt/turndown_prompt.h" #include <atlbase.h> #include <shlguid.h> #include "base/bind.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/win/scoped_bstr.h" #include "base/win/scoped_comptr.h" #include "base/win/win_util.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/google_update_settings.h" #include "chrome/installer/util/install_util.h" #include "chrome/installer/util/installation_state.h" #include "chrome/installer/util/util_constants.h" #include "chrome_frame/infobars/infobar_manager.h" #include "chrome_frame/policy_settings.h" #include "chrome_frame/ready_mode/internal/ready_mode_web_browser_adapter.h" #include "chrome_frame/ready_mode/internal/url_launcher.h" #include "chrome_frame/simple_resource_loader.h" #include "chrome_frame/turndown_prompt/reshow_state.h" #include "chrome_frame/turndown_prompt/turndown_prompt_content.h" #include "chrome_frame/utils.h" #include "grit/chromium_strings.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" namespace { // Time between showings of the turndown prompt. const int kTurndownPromptReshowDeltaMinutes = 60 * 24 * 1; void OnUninstallClicked(UrlLauncher* url_launcher); // Manages the Turndown UI in response to browsing ChromeFrame-rendered // pages. class BrowserObserver : public ReadyModeWebBrowserAdapter::Observer { public: BrowserObserver(IWebBrowser2* web_browser, ReadyModeWebBrowserAdapter* adapter); // ReadyModeWebBrowserAdapter::Observer implementation virtual void OnNavigateTo(const string16& url); virtual void OnRenderInChromeFrame(const string16& url); virtual void OnRenderInHost(const string16& url); private: // Shows the turndown prompt if it hasn't been seen since // kTurndownPromptReshowDeltaMinutes. void ShowPrompt(); void Hide(); // Returns a self-managed pointer that is not guaranteed to survive handling // of Windows events. For safety's sake, retrieve this pointer for each use // and do not store it for use outside of scope. InfobarManager* GetInfobarManager(); GURL rendered_url_; base::win::ScopedComPtr<IWebBrowser2> web_browser_; ReadyModeWebBrowserAdapter* adapter_; DISALLOW_COPY_AND_ASSIGN(BrowserObserver); }; // Implements launching of a URL in an instance of IWebBrowser2. class UrlLauncherImpl : public UrlLauncher { public: explicit UrlLauncherImpl(IWebBrowser2* web_browser); // UrlLauncher implementation void LaunchUrl(const string16& url); private: base::win::ScopedComPtr<IWebBrowser2> web_browser_; }; UrlLauncherImpl::UrlLauncherImpl(IWebBrowser2* web_browser) { DCHECK(web_browser); web_browser_ = web_browser; } void UrlLauncherImpl::LaunchUrl(const string16& url) { VARIANT flags = { VT_I4 }; V_I4(&flags) = navOpenInNewWindow; base::win::ScopedBstr location(url.c_str()); HRESULT hr = web_browser_->Navigate(location, &flags, NULL, NULL, NULL); DLOG_IF(ERROR, FAILED(hr)) << "Failed to invoke Navigate on IWebBrowser2. " << "Error: " << hr; } BrowserObserver::BrowserObserver(IWebBrowser2* web_browser, ReadyModeWebBrowserAdapter* adapter) : web_browser_(web_browser), adapter_(adapter) { } void BrowserObserver::OnNavigateTo(const string16& url) { if (!net::registry_controlled_domains::SameDomainOrHost( GURL(url), rendered_url_, net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES)) { rendered_url_ = GURL(); Hide(); } } void BrowserObserver::OnRenderInChromeFrame(const string16& url) { ShowPrompt(); rendered_url_ = GURL(url); } void BrowserObserver::OnRenderInHost(const string16& url) { Hide(); rendered_url_ = GURL(url); } void BrowserObserver::ShowPrompt() { turndown_prompt::ReshowState reshow_state( base::TimeDelta::FromMinutes(kTurndownPromptReshowDeltaMinutes)); // Short-circuit if the prompt shouldn't be shown again yet. if (!reshow_state.HasReshowDeltaExpired(base::Time::Now())) return; // This pointer is self-managed and not guaranteed to survive handling of // Windows events. For safety's sake, retrieve this pointer for each use and // do not store it for use outside of scope. InfobarManager* infobar_manager = GetInfobarManager(); if (infobar_manager) { // Owned by infobar_content scoped_ptr<UrlLauncher> url_launcher(new UrlLauncherImpl(web_browser_)); // Owned by infobar_manager scoped_ptr<InfobarContent> infobar_content(new TurndownPromptContent( url_launcher.release(), base::Bind(&OnUninstallClicked, base::Owned(new UrlLauncherImpl(web_browser_))))); if (infobar_manager->Show(infobar_content.release(), TOP_INFOBAR)) { // Update state in the registry that the prompt was shown. reshow_state.MarkShown(base::Time::Now()); } } } void BrowserObserver::Hide() { InfobarManager* infobar_manager = GetInfobarManager(); if (infobar_manager) infobar_manager->HideAll(); } InfobarManager* BrowserObserver::GetInfobarManager() { HRESULT hr = NOERROR; base::win::ScopedComPtr<IOleWindow> ole_window; hr = DoQueryService(SID_SShellBrowser, web_browser_, ole_window.Receive()); if (FAILED(hr) || ole_window == NULL) { DLOG(ERROR) << "Failed to query SID_SShellBrowser from IWebBrowser2. " << "Error: " << hr; return NULL; } HWND web_browser_hwnd = NULL; hr = ole_window->GetWindow(&web_browser_hwnd); if (FAILED(hr) || web_browser_hwnd == NULL) { DLOG(ERROR) << "Failed to query HWND from IOleWindow. " << "Error: " << hr; return NULL; } return InfobarManager::Get(web_browser_hwnd); } // Returns true if the module into which this code is linked is installed at // system-level. bool IsCurrentModuleSystemLevel() { base::FilePath dll_path; if (PathService::Get(base::DIR_MODULE, &dll_path)) return !InstallUtil::IsPerUserInstall(dll_path.value().c_str()); return false; } // Attempts to create a ReadyModeWebBrowserAdapter instance. bool CreateWebBrowserAdapter(ReadyModeWebBrowserAdapter** adapter) { *adapter = NULL; CComObject<ReadyModeWebBrowserAdapter>* com_object; HRESULT hr = CComObject<ReadyModeWebBrowserAdapter>::CreateInstance(&com_object); if (FAILED(hr)) { DLOG(ERROR) << "Failed to create instance of ReadyModeWebBrowserAdapter. " << "Error: " << hr; return false; } com_object->AddRef(); *adapter = com_object; return true; } // Attempts to install Turndown prompts in the provided web browser. bool InstallPrompts(IWebBrowser2* web_browser) { base::win::ScopedComPtr<ReadyModeWebBrowserAdapter, NULL> adapter; if (!CreateWebBrowserAdapter(adapter.Receive())) return false; // Pass ownership of our delegate to the BrowserObserver scoped_ptr<ReadyModeWebBrowserAdapter::Observer> browser_observer( new BrowserObserver(web_browser, adapter)); // Owns the BrowserObserver return adapter->Initialize(web_browser, browser_observer.release()); } // Launches the Chrome Frame uninstaller in response to user action. This // implementation should not be used to uninstall MSI-based versions of GCF, // since those must be removed by way of Windows Installer machinery. void LaunchChromeFrameUninstaller() { BrowserDistribution* dist = BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_FRAME); const bool system_level = IsCurrentModuleSystemLevel(); installer::ProductState product_state; if (!product_state.Initialize(system_level, dist)) { DLOG(ERROR) << "Chrome frame isn't installed at " << (system_level ? "system" : "user") << " level."; return; } CommandLine uninstall_command(product_state.uninstall_command()); if (uninstall_command.GetProgram().empty()) { DLOG(ERROR) << "No uninstall command found in registry."; return; } // Force Uninstall silences the prompt to reboot to complete uninstall. uninstall_command.AppendSwitch(installer::switches::kForceUninstall); VLOG(1) << "Uninstalling Chrome Frame with command: " << uninstall_command.GetCommandLineString(); base::LaunchProcess(uninstall_command, base::LaunchOptions(), NULL); } void LaunchLearnMoreURL(UrlLauncher* url_launcher) { url_launcher->LaunchUrl(SimpleResourceLoader::Get( IDS_CHROME_FRAME_TURNDOWN_LEARN_MORE_URL)); } void OnUninstallClicked(UrlLauncher* url_launcher) { LaunchChromeFrameUninstaller(); LaunchLearnMoreURL(url_launcher); } } // namespace namespace turndown_prompt { bool IsPromptSuppressed() { // See if this is an MSI install of GCF or if updates have been disabled. BrowserDistribution* dist = BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_FRAME); const bool system_level = IsCurrentModuleSystemLevel(); bool multi_install = false; installer::ProductState product_state; if (product_state.Initialize(system_level, dist)) { if (product_state.is_msi()) return true; multi_install = product_state.is_multi_install(); } if (multi_install) { dist = BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_BINARIES); } if (GoogleUpdateSettings::GetAppUpdatePolicy(dist->GetAppGuid(), NULL) == GoogleUpdateSettings::UPDATES_DISABLED) { return true; } // See if the prompt is explicitly suppressed via GP. return PolicySettings::GetInstance()->suppress_turndown_prompt(); } void Configure(IWebBrowser2* web_browser) { if (!IsPromptSuppressed()) InstallPrompts(web_browser); } } // namespace turndown_prompt <|endoftext|>
<commit_before>#include "loadedinstance.hpp" #include <map> #include <string> #if defined(_MSC_VER) || defined(__BORLANDC__) #define WIN32_LEAN_AND_MEAN #include <windows.h> inline void *getMethod(void *handle, const char *methodName) { return static_cast<void*>(GetProcAddress(static_cast<HMODULE>(handle), methodName)); } inline void *loadSharedObject(const char *fileName) { return static_cast<void*>(LoadLibrary(fileName)); } inline bool freeSharedObject(void *handle) { FreeLibrary(static_cast<HMODULE>(handle)); } #endif namespace loader { using namespace std; class LoadedInstancePrivate { public: LoadedInstancePrivate() {} ~LoadedInstancePrivate() { m_methods.clear(); } void *m_sharedFileHandle; map<string, void*> m_methods; }; LoadedInstance::LoadedInstance() : m_private{ new LoadedInstancePrivate } {} LoadedInstance::~LoadedInstance() { unload(); } bool LoadedInstance::load(const char * fileName) { m_private->m_sharedFileHandle = loadSharedObject(fileName); return loaded(); } void *LoadedInstance::loadMethod(const char *methodName) { if (loaded()) { auto node(m_private->m_methods.find(methodName)); if (node == m_private->m_methods.end()) { auto methodAddress(getMethod(m_private->m_sharedFileHandle, methodName)); // Add the result of getMethod even if is nullptr to avoid // trying to load it more times m_private->m_methods[methodName] = methodAddress; return methodAddress; } else { // The method is already on the map, return it return node->second; } } return nullptr; } bool LoadedInstance::loaded() const { return m_private->m_sharedFileHandle != nullptr; } bool LoadedInstance::unload() { if (loaded()) { freeSharedObject(m_private->m_sharedFileHandle); m_private->m_sharedFileHandle = nullptr; m_private->m_methods.clear(); return true; } return false; } void *LoadedInstance::loadedData() const { return m_private->m_sharedFileHandle; } } <commit_msg>Take care of result conversion in FreeLibrary<commit_after>#include "loadedinstance.hpp" #include <map> #include <string> #if defined(_MSC_VER) || defined(__BORLANDC__) #define WIN32_LEAN_AND_MEAN #include <windows.h> inline void *getMethod(void *handle, const char *methodName) { return static_cast<void*>(GetProcAddress(static_cast<HMODULE>(handle), methodName)); } inline void *loadSharedObject(const char *fileName) { return static_cast<void*>(LoadLibrary(fileName)); } inline bool freeSharedObject(void *handle) { return (FreeLibrary(static_cast<HMODULE>(handle)) != 0); } #endif namespace loader { using namespace std; class LoadedInstancePrivate { public: LoadedInstancePrivate() {} ~LoadedInstancePrivate() { m_methods.clear(); } void *m_sharedFileHandle; map<string, void*> m_methods; }; LoadedInstance::LoadedInstance() : m_private{ new LoadedInstancePrivate } {} LoadedInstance::~LoadedInstance() { unload(); } bool LoadedInstance::load(const char * fileName) { m_private->m_sharedFileHandle = loadSharedObject(fileName); return loaded(); } void *LoadedInstance::loadMethod(const char *methodName) { if (loaded()) { auto node(m_private->m_methods.find(methodName)); if (node == m_private->m_methods.end()) { auto methodAddress(getMethod(m_private->m_sharedFileHandle, methodName)); // Add the result of getMethod even if is nullptr to avoid // trying to load it more times m_private->m_methods[methodName] = methodAddress; return methodAddress; } else { // The method is already on the map, return it return node->second; } } return nullptr; } bool LoadedInstance::loaded() const { return m_private->m_sharedFileHandle != nullptr; } bool LoadedInstance::unload() { if (loaded()) { bool result(freeSharedObject(m_private->m_sharedFileHandle)); m_private->m_sharedFileHandle = nullptr; m_private->m_methods.clear(); return result; } return false; } void *LoadedInstance::loadedData() const { return m_private->m_sharedFileHandle; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkPolyDataSilhouette.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .SECTION Thanks // Contribution by Thierry Carrard <br> // CEA/DIF - Commissariat a l'Energie Atomique, Centre DAM Ile-De-France <br> // BP12, F-91297 Arpajon, France. <br> #include "vtkPolyDataSilhouette.h" #include "vtkCamera.h" #include "vtkCellData.h" #include "vtkGenericCell.h" #include "vtkMath.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkProp3D.h" #include "vtkTransform.h" #include "vtkUnsignedIntArray.h" #include "vtkIdTypeArray.h" #include "vtkPoints.h" #include "vtkCellArray.h" #include "vtkPolygon.h" #include <vtkstd/map> vtkStandardNewMacro(vtkPolyDataSilhouette); vtkCxxSetObjectMacro(vtkPolyDataSilhouette,Camera,vtkCamera); struct vtkOrderedEdge { inline vtkOrderedEdge(vtkIdType a, vtkIdType b) { if(a<=b) { p1=a; p2=b; } else { p1=b; p2=a; } } inline bool operator < (const vtkOrderedEdge& oe) const { return (p1<oe.p1) || ( (p1==oe.p1) && (p2<oe.p2) ) ; } vtkIdType p1,p2; }; struct vtkTwoNormals { double leftNormal[3]; // normal of the left polygon double rightNormal[3]; // normal of the right polygon inline vtkTwoNormals() { leftNormal[0] = 0.0; leftNormal[1] = 0.0; leftNormal[2] = 0.0; rightNormal[0] = 0.0; rightNormal[1] = 0.0; rightNormal[2] = 0.0; } }; class vtkPolyDataEdges { public: vtkTimeStamp mtime; double vec[3]; vtkstd::map<vtkOrderedEdge,vtkTwoNormals> edges; bool * edgeFlag; vtkCellArray* lines; inline vtkPolyDataEdges() : edgeFlag(0), lines(0) { vec[0]=vec[1]=vec[2]=0.0; } }; vtkPolyDataSilhouette::vtkPolyDataSilhouette() { this->Camera = NULL; this->Prop3D = NULL; this->Direction = VTK_DIRECTION_CAMERA_ORIGIN; this->Vector[0] = this->Vector[1] = this->Vector[2] = 0.0; this->Origin[0] = this->Origin[1] = this->Origin[2] = 0.0; this->Transform = vtkTransform::New(); this->EnableFeatureAngle = 1; this->FeatureAngle = 60; this->BorderEdges = 0; this->PieceInvariant = 1; this->PreComp = new vtkPolyDataEdges(); } vtkPolyDataSilhouette::~vtkPolyDataSilhouette() { this->Transform->Delete(); if ( this->Camera ) { this->Camera->Delete(); } delete this->PreComp; //Note: vtkProp3D is not deleted to avoid reference count cycle } // Don't reference count to avoid nasty cycle void vtkPolyDataSilhouette::SetProp3D(vtkProp3D *prop3d) { if ( this->Prop3D != prop3d ) { this->Prop3D = prop3d; this->Modified(); } } vtkProp3D *vtkPolyDataSilhouette::GetProp3D() { return this->Prop3D; } int vtkPolyDataSilhouette::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the input and ouptut vtkPolyData *input = vtkPolyData::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); if(input==0 || output==0) { vtkErrorMacro(<<"Need correct connections"); return 0; } vtkDebugMacro(<<"RequestData\n"); const double featureAngleCos = cos( vtkMath::RadiansFromDegrees( this->FeatureAngle ) ); bool vectorMode = true; double vector[3]; double origin[3]; // Compute the sort vector switch( this->Direction ) { case VTK_DIRECTION_SPECIFIED_VECTOR : vector[0] = this->Vector[0]; vector[1] = this->Vector[1]; vector[2] = this->Vector[2]; break; case VTK_DIRECTION_SPECIFIED_ORIGIN : origin[0] = this->Origin[0]; origin[1] = this->Origin[1]; origin[2] = this->Origin[2]; vectorMode = false; break; case VTK_DIRECTION_CAMERA_ORIGIN : vectorMode = false; case VTK_DIRECTION_CAMERA_VECTOR : if ( this->Camera == NULL) { vtkErrorMacro(<<"Need a camera when direction is set to VTK_DIRECTION_CAMERA_*"); return 0; } this->ComputeProjectionVector(vector, origin); break; } vtkIdType nPolys = input->GetNumberOfPolys(); vtkIdTypeArray* polysArray = input->GetPolys()->GetData(); vtkPoints* inPoints = input->GetPoints(); if( input->GetMTime() > this->PreComp->mtime.GetMTime() ) { vtkDebugMacro(<<"Compute edge-face connectivity and face normals\n"); this->PreComp->mtime.Modified(); this->PreComp->edges.clear(); vtkIdType* polys = polysArray->GetPointer(0); for(vtkIdType i=0;i<nPolys;i++) { int np = *(polys); ++polys; double normal[3]; vtkPolygon::ComputeNormal(inPoints, np, polys, normal); for(int j=0;j<np;j++) { vtkIdType p1=j, p2=(j+1)%np; vtkOrderedEdge oe( polys[p1], polys[p2] ); vtkTwoNormals& tn = this->PreComp->edges[oe]; if( polys[p1] < polys[p2] ) { #ifdef DEBUG if( vtkMath::Dot(tn.leftNormal,tn.leftNormal) > 0 ) { vtkDebugMacro(<<"Warning: vtkPolyDataSilhouette: non-manifold mesh: edge-L ("<<polys[p1]<<","<<polys[p2]<<") counted more than once\n"); } #endif tn.leftNormal[0] = normal[0]; tn.leftNormal[1] = normal[1]; tn.leftNormal[2] = normal[2]; } else { #ifdef DEBUG if( vtkMath::Dot(tn.rightNormal,tn.rightNormal) > 0 ) { vtkDebugMacro(<<"Warning: vtkPolyDataSilhouette: non-manifold mesh: edge-R ("<<polys[p1]<<","<<polys[p2]<<") counted more than once\n"); } #endif tn.rightNormal[0] = normal[0]; tn.rightNormal[1] = normal[1]; tn.rightNormal[2] = normal[2]; } } polys += np; } if( this->PreComp->edgeFlag != 0 ) delete [] this->PreComp->edgeFlag; this->PreComp->edgeFlag = new bool[ this->PreComp->edges.size() ]; } bool vecChanged = false; for(int d=0;d<3;d++) { vecChanged = vecChanged || this->PreComp->vec[d]!=vector[d] ; } if( ( this->PreComp->mtime.GetMTime() > output->GetMTime() ) || ( this->Camera->GetMTime() > output->GetMTime() ) || ( this->Prop3D!=0 && this->Prop3D->GetMTime() > output->GetMTime() ) || vecChanged ) { vtkDebugMacro(<<"Extract edges\n"); vtkIdType i=0, silhouetteEdges=0; for(vtkstd::map<vtkOrderedEdge,vtkTwoNormals>::iterator it=this->PreComp->edges.begin(); it!=this->PreComp->edges.end(); ++it) { double d1,d2; // does this edge have two co-faces ? bool winged = vtkMath::Norm(it->second.leftNormal)>0.5 && vtkMath::Norm(it->second.rightNormal)>0.5 ; // cosine of feature angle, to be compared with scalar product of two co-faces normals double edgeAngleCos = vtkMath::Dot( it->second.leftNormal, it->second.rightNormal ); if( vectorMode ) // uniform direction { d1 = vtkMath::Dot( vector, it->second.leftNormal ); d2 = vtkMath::Dot( vector, it->second.rightNormal ); } else // origin to edge's center direction { double p1[3]; double p2[3]; double vec[3]; inPoints->GetPoint( it->first.p1 , p1 ); inPoints->GetPoint( it->first.p2 , p2 ); vec[0] = origin[0] - ( (p1[0]+p2[0])*0.5 ); vec[1] = origin[1] - ( (p1[1]+p2[1])*0.5 ); vec[2] = origin[2] - ( (p1[2]+p2[2])*0.5 ); d1 = vtkMath::Dot( vec, it->second.leftNormal ); d2 = vtkMath::Dot( vec, it->second.rightNormal ); } // shall we output this edge ? bool outputEdge = ( winged && (d1*d2)<0 ) || ( this->EnableFeatureAngle && edgeAngleCos<featureAngleCos ) || ( this->BorderEdges && !winged ); if( outputEdge ) // add this edge { this->PreComp->edgeFlag[i] = true ; ++silhouetteEdges; } else // skip this edge { this->PreComp->edgeFlag[i] = false ; } ++i; } // build output data set (lines) vtkIdTypeArray* la = vtkIdTypeArray::New(); la->SetNumberOfValues( 3*silhouetteEdges ); vtkIdType* laPtr = la->WritePointer(0,3*silhouetteEdges); i=0; silhouetteEdges=0; for(vtkstd::map<vtkOrderedEdge,vtkTwoNormals>::iterator it=this->PreComp->edges.begin(); it!=this->PreComp->edges.end(); ++it) { if( this->PreComp->edgeFlag[i] ) { laPtr[ silhouetteEdges*3+0 ] = 2 ; laPtr[ silhouetteEdges*3+1 ] = it->first.p1 ; laPtr[ silhouetteEdges*3+2 ] = it->first.p2 ; ++silhouetteEdges; } ++i; } if( this->PreComp->lines == 0 ) { this->PreComp->lines = vtkCellArray::New(); } this->PreComp->lines->SetCells( silhouetteEdges, la ); la->Delete(); } output->Initialize(); output->SetPoints(inPoints); output->SetLines(this->PreComp->lines); return 1; } void vtkPolyDataSilhouette::ComputeProjectionVector(double vector[3], double origin[3]) { double *focalPoint = this->Camera->GetFocalPoint(); double *position = this->Camera->GetPosition(); // If a camera is present, use it if ( !this->Prop3D ) { for(int i=0; i<3; i++) { vector[i] = focalPoint[i] - position[i]; origin[i] = position[i]; } } else //Otherwise, use Prop3D { double focalPt[4], pos[4]; int i; this->Transform->SetMatrix(this->Prop3D->GetMatrix()); this->Transform->Push(); this->Transform->Inverse(); for(i=0; i<4; i++) { focalPt[i] = focalPoint[i]; pos[i] = position[i]; } this->Transform->TransformPoint(focalPt,focalPt); this->Transform->TransformPoint(pos,pos); for (i=0; i<3; i++) { vector[i] = focalPt[i] - pos[i]; origin[i] = pos[i]; } this->Transform->Pop(); } } unsigned long int vtkPolyDataSilhouette::GetMTime() { unsigned long mTime=this->Superclass::GetMTime(); if ( this->Direction != VTK_DIRECTION_SPECIFIED_VECTOR ) { unsigned long time; if ( this->Camera != NULL ) { time = this->Camera->GetMTime(); mTime = ( time > mTime ? time : mTime ); } if ( this->Prop3D != NULL ) { time = this->Prop3D->GetMTime(); mTime = ( time > mTime ? time : mTime ); } } return mTime; } void vtkPolyDataSilhouette::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if ( this->Camera ) { os << indent << "Camera:\n"; this->Camera->PrintSelf(os,indent.GetNextIndent()); } else { os << indent << "Camera: (none)\n"; } if ( this->Prop3D ) { os << indent << "Prop3D:\n"; this->Prop3D->PrintSelf(os,indent.GetNextIndent()); } else { os << indent << "Prop3D: (none)\n"; } os << indent << "Direction: "; #define DIRECTION_CASE(name) case VTK_DIRECTION_##name :os << "VTK_DIRECTION_" << #name <<"\n"; break switch(this->Direction) { DIRECTION_CASE( SPECIFIED_ORIGIN ); DIRECTION_CASE( SPECIFIED_VECTOR ); DIRECTION_CASE( CAMERA_ORIGIN ); DIRECTION_CASE( CAMERA_VECTOR ); } #undef DIRECTION_CASE if( this->Direction == VTK_DIRECTION_SPECIFIED_VECTOR ) { os << "Specified Vector: (" << this->Vector[0] << ", " << this->Vector[1] << ", " << this->Vector[2] << ")\n"; } if( this->Direction == VTK_DIRECTION_SPECIFIED_ORIGIN ) { os << "Specified Origin: (" << this->Origin[0] << ", " << this->Origin[1] << ", " << this->Origin[2] << ")\n"; } os << indent << "PieceInvariant: " << this->PieceInvariant << "\n"; os << indent << "FeatureAngle: " << this->FeatureAngle << "\n"; os << indent << "EnableFeatureAngle: " << this->EnableFeatureAngle << "\n"; os << indent << "BorderEdges: " << this->BorderEdges << "\n"; } <commit_msg>BUG: memory leak.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkPolyDataSilhouette.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .SECTION Thanks // Contribution by Thierry Carrard <br> // CEA/DIF - Commissariat a l'Energie Atomique, Centre DAM Ile-De-France <br> // BP12, F-91297 Arpajon, France. <br> #include "vtkPolyDataSilhouette.h" #include "vtkCamera.h" #include "vtkCellData.h" #include "vtkGenericCell.h" #include "vtkMath.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkProp3D.h" #include "vtkTransform.h" #include "vtkUnsignedIntArray.h" #include "vtkIdTypeArray.h" #include "vtkPoints.h" #include "vtkCellArray.h" #include "vtkPolygon.h" #include <vtkstd/map> vtkStandardNewMacro(vtkPolyDataSilhouette); vtkCxxSetObjectMacro(vtkPolyDataSilhouette,Camera,vtkCamera); struct vtkOrderedEdge { inline vtkOrderedEdge(vtkIdType a, vtkIdType b) { if(a<=b) { p1=a; p2=b; } else { p1=b; p2=a; } } inline bool operator < (const vtkOrderedEdge& oe) const { return (p1<oe.p1) || ( (p1==oe.p1) && (p2<oe.p2) ) ; } vtkIdType p1,p2; }; struct vtkTwoNormals { double leftNormal[3]; // normal of the left polygon double rightNormal[3]; // normal of the right polygon inline vtkTwoNormals() { leftNormal[0] = 0.0; leftNormal[1] = 0.0; leftNormal[2] = 0.0; rightNormal[0] = 0.0; rightNormal[1] = 0.0; rightNormal[2] = 0.0; } }; class vtkPolyDataEdges { public: vtkTimeStamp mtime; double vec[3]; vtkstd::map<vtkOrderedEdge,vtkTwoNormals> edges; bool * edgeFlag; vtkCellArray* lines; inline vtkPolyDataEdges() : edgeFlag(0), lines(0) { vec[0]=vec[1]=vec[2]=0.0; } }; vtkPolyDataSilhouette::vtkPolyDataSilhouette() { this->Camera = NULL; this->Prop3D = NULL; this->Direction = VTK_DIRECTION_CAMERA_ORIGIN; this->Vector[0] = this->Vector[1] = this->Vector[2] = 0.0; this->Origin[0] = this->Origin[1] = this->Origin[2] = 0.0; this->Transform = vtkTransform::New(); this->EnableFeatureAngle = 1; this->FeatureAngle = 60; this->BorderEdges = 0; this->PieceInvariant = 1; this->PreComp = new vtkPolyDataEdges(); } vtkPolyDataSilhouette::~vtkPolyDataSilhouette() { this->Transform->Delete(); if ( this->Camera ) { this->Camera->Delete(); } if (this->PreComp->edgeFlag) { delete [] this->PreComp->edgeFlag; } if (this->PreComp->lines) { this->PreComp->lines->Delete(); } delete this->PreComp; //Note: vtkProp3D is not deleted to avoid reference count cycle } // Don't reference count to avoid nasty cycle void vtkPolyDataSilhouette::SetProp3D(vtkProp3D *prop3d) { if ( this->Prop3D != prop3d ) { this->Prop3D = prop3d; this->Modified(); } } vtkProp3D *vtkPolyDataSilhouette::GetProp3D() { return this->Prop3D; } int vtkPolyDataSilhouette::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the input and ouptut vtkPolyData *input = vtkPolyData::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPolyData *output = vtkPolyData::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); if(input==0 || output==0) { vtkErrorMacro(<<"Need correct connections"); return 0; } vtkDebugMacro(<<"RequestData\n"); const double featureAngleCos = cos( vtkMath::RadiansFromDegrees( this->FeatureAngle ) ); bool vectorMode = true; double vector[3]; double origin[3]; // Compute the sort vector switch( this->Direction ) { case VTK_DIRECTION_SPECIFIED_VECTOR : vector[0] = this->Vector[0]; vector[1] = this->Vector[1]; vector[2] = this->Vector[2]; break; case VTK_DIRECTION_SPECIFIED_ORIGIN : origin[0] = this->Origin[0]; origin[1] = this->Origin[1]; origin[2] = this->Origin[2]; vectorMode = false; break; case VTK_DIRECTION_CAMERA_ORIGIN : vectorMode = false; case VTK_DIRECTION_CAMERA_VECTOR : if ( this->Camera == NULL) { vtkErrorMacro(<<"Need a camera when direction is set to VTK_DIRECTION_CAMERA_*"); return 0; } this->ComputeProjectionVector(vector, origin); break; } vtkIdType nPolys = input->GetNumberOfPolys(); vtkIdTypeArray* polysArray = input->GetPolys()->GetData(); vtkPoints* inPoints = input->GetPoints(); if( input->GetMTime() > this->PreComp->mtime.GetMTime() ) { vtkDebugMacro(<<"Compute edge-face connectivity and face normals\n"); this->PreComp->mtime.Modified(); this->PreComp->edges.clear(); vtkIdType* polys = polysArray->GetPointer(0); for(vtkIdType i=0;i<nPolys;i++) { int np = *(polys); ++polys; double normal[3]; vtkPolygon::ComputeNormal(inPoints, np, polys, normal); for(int j=0;j<np;j++) { vtkIdType p1=j, p2=(j+1)%np; vtkOrderedEdge oe( polys[p1], polys[p2] ); vtkTwoNormals& tn = this->PreComp->edges[oe]; if( polys[p1] < polys[p2] ) { #ifdef DEBUG if( vtkMath::Dot(tn.leftNormal,tn.leftNormal) > 0 ) { vtkDebugMacro(<<"Warning: vtkPolyDataSilhouette: non-manifold mesh: edge-L ("<<polys[p1]<<","<<polys[p2]<<") counted more than once\n"); } #endif tn.leftNormal[0] = normal[0]; tn.leftNormal[1] = normal[1]; tn.leftNormal[2] = normal[2]; } else { #ifdef DEBUG if( vtkMath::Dot(tn.rightNormal,tn.rightNormal) > 0 ) { vtkDebugMacro(<<"Warning: vtkPolyDataSilhouette: non-manifold mesh: edge-R ("<<polys[p1]<<","<<polys[p2]<<") counted more than once\n"); } #endif tn.rightNormal[0] = normal[0]; tn.rightNormal[1] = normal[1]; tn.rightNormal[2] = normal[2]; } } polys += np; } if( this->PreComp->edgeFlag != 0 ) delete [] this->PreComp->edgeFlag; this->PreComp->edgeFlag = new bool[ this->PreComp->edges.size() ]; } bool vecChanged = false; for(int d=0;d<3;d++) { vecChanged = vecChanged || this->PreComp->vec[d]!=vector[d] ; } if( ( this->PreComp->mtime.GetMTime() > output->GetMTime() ) || ( this->Camera->GetMTime() > output->GetMTime() ) || ( this->Prop3D!=0 && this->Prop3D->GetMTime() > output->GetMTime() ) || vecChanged ) { vtkDebugMacro(<<"Extract edges\n"); vtkIdType i=0, silhouetteEdges=0; for(vtkstd::map<vtkOrderedEdge,vtkTwoNormals>::iterator it=this->PreComp->edges.begin(); it!=this->PreComp->edges.end(); ++it) { double d1,d2; // does this edge have two co-faces ? bool winged = vtkMath::Norm(it->second.leftNormal)>0.5 && vtkMath::Norm(it->second.rightNormal)>0.5 ; // cosine of feature angle, to be compared with scalar product of two co-faces normals double edgeAngleCos = vtkMath::Dot( it->second.leftNormal, it->second.rightNormal ); if( vectorMode ) // uniform direction { d1 = vtkMath::Dot( vector, it->second.leftNormal ); d2 = vtkMath::Dot( vector, it->second.rightNormal ); } else // origin to edge's center direction { double p1[3]; double p2[3]; double vec[3]; inPoints->GetPoint( it->first.p1 , p1 ); inPoints->GetPoint( it->first.p2 , p2 ); vec[0] = origin[0] - ( (p1[0]+p2[0])*0.5 ); vec[1] = origin[1] - ( (p1[1]+p2[1])*0.5 ); vec[2] = origin[2] - ( (p1[2]+p2[2])*0.5 ); d1 = vtkMath::Dot( vec, it->second.leftNormal ); d2 = vtkMath::Dot( vec, it->second.rightNormal ); } // shall we output this edge ? bool outputEdge = ( winged && (d1*d2)<0 ) || ( this->EnableFeatureAngle && edgeAngleCos<featureAngleCos ) || ( this->BorderEdges && !winged ); if( outputEdge ) // add this edge { this->PreComp->edgeFlag[i] = true ; ++silhouetteEdges; } else // skip this edge { this->PreComp->edgeFlag[i] = false ; } ++i; } // build output data set (lines) vtkIdTypeArray* la = vtkIdTypeArray::New(); la->SetNumberOfValues( 3*silhouetteEdges ); vtkIdType* laPtr = la->WritePointer(0,3*silhouetteEdges); i=0; silhouetteEdges=0; for(vtkstd::map<vtkOrderedEdge,vtkTwoNormals>::iterator it=this->PreComp->edges.begin(); it!=this->PreComp->edges.end(); ++it) { if( this->PreComp->edgeFlag[i] ) { laPtr[ silhouetteEdges*3+0 ] = 2 ; laPtr[ silhouetteEdges*3+1 ] = it->first.p1 ; laPtr[ silhouetteEdges*3+2 ] = it->first.p2 ; ++silhouetteEdges; } ++i; } if( this->PreComp->lines == 0 ) { this->PreComp->lines = vtkCellArray::New(); } this->PreComp->lines->SetCells( silhouetteEdges, la ); la->Delete(); } output->Initialize(); output->SetPoints(inPoints); output->SetLines(this->PreComp->lines); return 1; } void vtkPolyDataSilhouette::ComputeProjectionVector(double vector[3], double origin[3]) { double *focalPoint = this->Camera->GetFocalPoint(); double *position = this->Camera->GetPosition(); // If a camera is present, use it if ( !this->Prop3D ) { for(int i=0; i<3; i++) { vector[i] = focalPoint[i] - position[i]; origin[i] = position[i]; } } else //Otherwise, use Prop3D { double focalPt[4], pos[4]; int i; this->Transform->SetMatrix(this->Prop3D->GetMatrix()); this->Transform->Push(); this->Transform->Inverse(); for(i=0; i<4; i++) { focalPt[i] = focalPoint[i]; pos[i] = position[i]; } this->Transform->TransformPoint(focalPt,focalPt); this->Transform->TransformPoint(pos,pos); for (i=0; i<3; i++) { vector[i] = focalPt[i] - pos[i]; origin[i] = pos[i]; } this->Transform->Pop(); } } unsigned long int vtkPolyDataSilhouette::GetMTime() { unsigned long mTime=this->Superclass::GetMTime(); if ( this->Direction != VTK_DIRECTION_SPECIFIED_VECTOR ) { unsigned long time; if ( this->Camera != NULL ) { time = this->Camera->GetMTime(); mTime = ( time > mTime ? time : mTime ); } if ( this->Prop3D != NULL ) { time = this->Prop3D->GetMTime(); mTime = ( time > mTime ? time : mTime ); } } return mTime; } void vtkPolyDataSilhouette::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if ( this->Camera ) { os << indent << "Camera:\n"; this->Camera->PrintSelf(os,indent.GetNextIndent()); } else { os << indent << "Camera: (none)\n"; } if ( this->Prop3D ) { os << indent << "Prop3D:\n"; this->Prop3D->PrintSelf(os,indent.GetNextIndent()); } else { os << indent << "Prop3D: (none)\n"; } os << indent << "Direction: "; #define DIRECTION_CASE(name) case VTK_DIRECTION_##name :os << "VTK_DIRECTION_" << #name <<"\n"; break switch(this->Direction) { DIRECTION_CASE( SPECIFIED_ORIGIN ); DIRECTION_CASE( SPECIFIED_VECTOR ); DIRECTION_CASE( CAMERA_ORIGIN ); DIRECTION_CASE( CAMERA_VECTOR ); } #undef DIRECTION_CASE if( this->Direction == VTK_DIRECTION_SPECIFIED_VECTOR ) { os << "Specified Vector: (" << this->Vector[0] << ", " << this->Vector[1] << ", " << this->Vector[2] << ")\n"; } if( this->Direction == VTK_DIRECTION_SPECIFIED_ORIGIN ) { os << "Specified Origin: (" << this->Origin[0] << ", " << this->Origin[1] << ", " << this->Origin[2] << ")\n"; } os << indent << "PieceInvariant: " << this->PieceInvariant << "\n"; os << indent << "FeatureAngle: " << this->FeatureAngle << "\n"; os << indent << "EnableFeatureAngle: " << this->EnableFeatureAngle << "\n"; os << indent << "BorderEdges: " << this->BorderEdges << "\n"; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkMedicalImageProperties.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMedicalImageProperties.h" #include "vtkObjectFactory.h" #include <vtksys/stl/string> #include <vtksys/stl/vector> //---------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkMedicalImageProperties, "1.10"); vtkStandardNewMacro(vtkMedicalImageProperties); //---------------------------------------------------------------------------- class vtkMedicalImagePropertiesInternals { public: class WindowLevelPreset { public: double Window; double Level; vtksys_stl::string Comment; }; typedef vtkstd::vector<WindowLevelPreset> WindowLevelPresetPoolType; typedef vtkstd::vector<WindowLevelPreset>::iterator WindowLevelPresetPoolIterator; WindowLevelPresetPoolType WindowLevelPresetPool; }; //---------------------------------------------------------------------------- vtkMedicalImageProperties::vtkMedicalImageProperties() { this->Internals = new vtkMedicalImagePropertiesInternals; this->AcquisitionDate = NULL; this->AcquisitionTime = NULL; this->ConvolutionKernel = NULL; this->Exposure = NULL; this->ExposureTime = NULL; this->GantryTilt = NULL; this->ImageDate = NULL; this->ImageNumber = NULL; this->ImageTime = NULL; this->InstitutionName = NULL; this->KVP = NULL; this->ManufacturerModelName = NULL; this->Modality = NULL; this->PatientAge = NULL; this->PatientBirthDate = NULL; this->PatientID = NULL; this->PatientName = NULL; this->PatientSex = NULL; this->SeriesNumber = NULL; this->SliceThickness = NULL; this->StationName = NULL; this->StudyDescription = NULL; this->StudyID = NULL; this->XRayTubeCurrent = NULL; } //---------------------------------------------------------------------------- vtkMedicalImageProperties::~vtkMedicalImageProperties() { if (this->Internals) { delete this->Internals; this->Internals = NULL; } this->Clear(); } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::Clear() { this->SetAcquisitionDate(NULL); this->SetAcquisitionTime(NULL); this->SetConvolutionKernel(NULL); this->SetExposure(NULL); this->SetExposureTime(NULL); this->SetGantryTilt(NULL); this->SetImageDate(NULL); this->SetImageNumber(NULL); this->SetImageTime(NULL); this->SetInstitutionName(NULL); this->SetKVP(NULL); this->SetManufacturerModelName(NULL); this->SetModality(NULL); this->SetPatientAge(NULL); this->SetPatientBirthDate(NULL); this->SetPatientID(NULL); this->SetPatientName(NULL); this->SetPatientSex(NULL); this->SetSeriesNumber(NULL); this->SetSliceThickness(NULL); this->SetStationName(NULL); this->SetStudyDescription(NULL); this->SetStudyID(NULL); this->SetXRayTubeCurrent(NULL); this->RemoveAllWindowLevelPresets(); } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::DeepCopy(vtkMedicalImageProperties *p) { if (p == NULL) { return; } this->Clear(); this->SetAcquisitionDate(p->GetAcquisitionDate()); this->SetAcquisitionTime(p->GetAcquisitionTime()); this->SetConvolutionKernel(p->GetConvolutionKernel()); this->SetExposure(p->GetExposure()); this->SetExposureTime(p->GetExposureTime()); this->SetGantryTilt(p->GetGantryTilt()); this->SetImageDate(p->GetImageDate()); this->SetImageNumber(p->GetImageNumber()); this->SetImageTime(p->GetImageTime()); this->SetInstitutionName(p->GetInstitutionName()); this->SetKVP(p->GetKVP()); this->SetManufacturerModelName(p->GetManufacturerModelName()); this->SetModality(p->GetModality()); this->SetPatientAge(p->GetPatientAge()); this->SetPatientBirthDate(p->GetPatientBirthDate()); this->SetPatientID(p->GetPatientID()); this->SetPatientName(p->GetPatientName()); this->SetPatientSex(p->GetPatientSex()); this->SetSeriesNumber(p->GetSeriesNumber()); this->SetSliceThickness(p->GetSliceThickness()); this->SetStationName(p->GetStationName()); this->SetStudyDescription(p->GetStudyDescription()); this->SetStudyID(p->GetStudyID()); this->SetXRayTubeCurrent(p->GetXRayTubeCurrent()); int nb_presets = p->GetNumberOfWindowLevelPresets(); for (int i = 0; i < nb_presets; i++) { double w, l; p->GetNthWindowLevelPreset(i, &w, &l); this->AddWindowLevelPreset(w, l); this->SetNthWindowLevelPresetComment( this->GetNumberOfWindowLevelPresets() - 1, p->GetNthWindowLevelPresetComment(i)); } } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::AddWindowLevelPreset( double w, double l) { if (!this->Internals || this->HasWindowLevelPreset(w, l)) { return; } vtkMedicalImagePropertiesInternals::WindowLevelPreset preset; preset.Window = w; preset.Level = l; this->Internals->WindowLevelPresetPool.push_back(preset); } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::HasWindowLevelPreset(double w, double l) { if (this->Internals) { vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator it = this->Internals->WindowLevelPresetPool.begin(); vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator end = this->Internals->WindowLevelPresetPool.end(); for (; it != end; ++it) { if ((*it).Window == w && (*it).Level == l) { return 1; } } } return 0; } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::RemoveWindowLevelPreset(double w, double l) { if (this->Internals) { vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator it = this->Internals->WindowLevelPresetPool.begin(); vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator end = this->Internals->WindowLevelPresetPool.end(); for (; it != end; ++it) { if ((*it).Window == w && (*it).Level == l) { this->Internals->WindowLevelPresetPool.erase(it); break; } } } } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::RemoveAllWindowLevelPresets() { if (this->Internals) { this->Internals->WindowLevelPresetPool.clear(); } } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetNumberOfWindowLevelPresets() { return this->Internals ? this->Internals->WindowLevelPresetPool.size() : 0; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetNthWindowLevelPreset( int idx, double *w, double *l) { if (this->Internals && idx >= 0 && idx < this->GetNumberOfWindowLevelPresets()) { *w = this->Internals->WindowLevelPresetPool[idx].Window; *l = this->Internals->WindowLevelPresetPool[idx].Level; return 1; } return 0; } //---------------------------------------------------------------------------- double* vtkMedicalImageProperties::GetNthWindowLevelPreset(int idx) { static double wl[2]; if (this->GetNthWindowLevelPreset(idx, wl, wl + 1)) { return wl; } return NULL; } //---------------------------------------------------------------------------- const char* vtkMedicalImageProperties::GetNthWindowLevelPresetComment( int idx) { if (this->Internals && idx >= 0 && idx < this->GetNumberOfWindowLevelPresets()) { return this->Internals->WindowLevelPresetPool[idx].Comment.c_str(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::SetNthWindowLevelPresetComment( int idx, const char *comment) { if (this->Internals && idx >= 0 && idx < this->GetNumberOfWindowLevelPresets()) { this->Internals->WindowLevelPresetPool[idx].Comment = (comment ? comment : ""); } } //---------------------------------------------------------------------------- double vtkMedicalImageProperties::GetSliceThicknessAsDouble() { if (this->SliceThickness) { return atof(this->SliceThickness); } return 0; } //---------------------------------------------------------------------------- double vtkMedicalImageProperties::GetGantryTiltAsDouble() { if (this->GantryTilt) { return atof(this->GantryTilt); } return 0; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetDateAsFields(const char *date, int &year, int &month, int &day) { if( !date ) { return 0; } size_t len = strlen(date); if( len != 10 ) { return 0; } // DICOM V3 if( sscanf(date, "%d%d%d", &year, &month, &day) != 3 ) { // Some *very* old ACR-NEMA if( sscanf(date, "%d.%d.%d", &year, &month, &day) != 3 ) { return 0; } } return 1; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetPatientBirthDateYear() { const char *date = this->GetPatientBirthDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return year; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetPatientBirthDateMonth() { const char *date = this->GetPatientBirthDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return month; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetPatientBirthDateDay() { const char *date = this->GetPatientBirthDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return day; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetAcquisitionDateYear() { const char *date = this->GetAcquisitionDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return year; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetAcquisitionDateMonth() { const char *date = this->GetAcquisitionDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return month; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetAcquisitionDateDay() { const char *date = this->GetAcquisitionDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return day; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetImageDateYear() { const char *date = this->GetImageDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return year; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetImageDateMonth() { const char *date = this->GetImageDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return month; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetImageDateDay() { const char *date = this->GetImageDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return day; } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << "\n" << indent << "PatientName: "; if (this->PatientName) { os << this->PatientName; } os << "\n" << indent << "PatientID: "; if (this->PatientID) { os << this->PatientID; } os << "\n" << indent << "PatientAge: "; if (this->PatientAge) { os << this->PatientAge; } os << "\n" << indent << "PatientSex: "; if (this->PatientSex) { os << this->PatientSex; } os << "\n" << indent << "PatientBirthDate: "; if (this->PatientBirthDate) { os << this->PatientBirthDate; } os << "\n" << indent << "ImageDate: "; if (this->ImageDate) { os << this->ImageDate; } os << "\n" << indent << "ImageTime: "; if (this->ImageTime) { os << this->ImageTime; } os << "\n" << indent << "ImageNumber: "; if (this->ImageNumber) { os << this->ImageNumber; } os << "\n" << indent << "AcquisitionDate: "; if (this->AcquisitionDate) { os << this->AcquisitionDate; } os << "\n" << indent << "AcquisitionTime: "; if (this->AcquisitionTime) { os << this->AcquisitionTime; } os << "\n" << indent << "SeriesNumber: "; if (this->SeriesNumber) { os << this->SeriesNumber; } os << "\n" << indent << "StudyDescription: "; if (this->StudyDescription) { os << this->StudyDescription; } os << "\n" << indent << "StudyID: "; if (this->StudyID) { os << this->StudyID; } os << "\n" << indent << "Modality: "; if (this->Modality) { os << this->Modality; } os << "\n" << indent << "ManufacturerModelName: "; if (this->ManufacturerModelName) { os << this->ManufacturerModelName; } os << "\n" << indent << "StationName: "; if (this->StationName) { os << this->StationName; } os << "\n" << indent << "InstitutionName: "; if (this->InstitutionName) { os << this->InstitutionName; } os << "\n" << indent << "ConvolutionKernel: "; if (this->ConvolutionKernel) { os << this->ConvolutionKernel; } os << "\n" << indent << "SliceThickness: "; if (this->SliceThickness) { os << this->SliceThickness; } os << "\n" << indent << "KVP: "; if (this->KVP) { os << this->KVP; } os << "\n" << indent << "GantryTilt: "; if (this->GantryTilt) { os << this->GantryTilt; } os << "\n" << indent << "ExposureTime: "; if (this->ExposureTime) { os << this->ExposureTime; } os << "\n" << indent << "XRayTubeCurrent: "; if (this->XRayTubeCurrent) { os << this->XRayTubeCurrent; } os << "\n" << indent << "Exposure: "; if (this->Exposure) { os << this->Exposure; } } <commit_msg>BUG: Did not read date properly<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkMedicalImageProperties.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMedicalImageProperties.h" #include "vtkObjectFactory.h" #include <vtksys/stl/string> #include <vtksys/stl/vector> //---------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkMedicalImageProperties, "1.11"); vtkStandardNewMacro(vtkMedicalImageProperties); //---------------------------------------------------------------------------- class vtkMedicalImagePropertiesInternals { public: class WindowLevelPreset { public: double Window; double Level; vtksys_stl::string Comment; }; typedef vtkstd::vector<WindowLevelPreset> WindowLevelPresetPoolType; typedef vtkstd::vector<WindowLevelPreset>::iterator WindowLevelPresetPoolIterator; WindowLevelPresetPoolType WindowLevelPresetPool; }; //---------------------------------------------------------------------------- vtkMedicalImageProperties::vtkMedicalImageProperties() { this->Internals = new vtkMedicalImagePropertiesInternals; this->AcquisitionDate = NULL; this->AcquisitionTime = NULL; this->ConvolutionKernel = NULL; this->Exposure = NULL; this->ExposureTime = NULL; this->GantryTilt = NULL; this->ImageDate = NULL; this->ImageNumber = NULL; this->ImageTime = NULL; this->InstitutionName = NULL; this->KVP = NULL; this->ManufacturerModelName = NULL; this->Modality = NULL; this->PatientAge = NULL; this->PatientBirthDate = NULL; this->PatientID = NULL; this->PatientName = NULL; this->PatientSex = NULL; this->SeriesNumber = NULL; this->SliceThickness = NULL; this->StationName = NULL; this->StudyDescription = NULL; this->StudyID = NULL; this->XRayTubeCurrent = NULL; } //---------------------------------------------------------------------------- vtkMedicalImageProperties::~vtkMedicalImageProperties() { if (this->Internals) { delete this->Internals; this->Internals = NULL; } this->Clear(); } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::Clear() { this->SetAcquisitionDate(NULL); this->SetAcquisitionTime(NULL); this->SetConvolutionKernel(NULL); this->SetExposure(NULL); this->SetExposureTime(NULL); this->SetGantryTilt(NULL); this->SetImageDate(NULL); this->SetImageNumber(NULL); this->SetImageTime(NULL); this->SetInstitutionName(NULL); this->SetKVP(NULL); this->SetManufacturerModelName(NULL); this->SetModality(NULL); this->SetPatientAge(NULL); this->SetPatientBirthDate(NULL); this->SetPatientID(NULL); this->SetPatientName(NULL); this->SetPatientSex(NULL); this->SetSeriesNumber(NULL); this->SetSliceThickness(NULL); this->SetStationName(NULL); this->SetStudyDescription(NULL); this->SetStudyID(NULL); this->SetXRayTubeCurrent(NULL); this->RemoveAllWindowLevelPresets(); } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::DeepCopy(vtkMedicalImageProperties *p) { if (p == NULL) { return; } this->Clear(); this->SetAcquisitionDate(p->GetAcquisitionDate()); this->SetAcquisitionTime(p->GetAcquisitionTime()); this->SetConvolutionKernel(p->GetConvolutionKernel()); this->SetExposure(p->GetExposure()); this->SetExposureTime(p->GetExposureTime()); this->SetGantryTilt(p->GetGantryTilt()); this->SetImageDate(p->GetImageDate()); this->SetImageNumber(p->GetImageNumber()); this->SetImageTime(p->GetImageTime()); this->SetInstitutionName(p->GetInstitutionName()); this->SetKVP(p->GetKVP()); this->SetManufacturerModelName(p->GetManufacturerModelName()); this->SetModality(p->GetModality()); this->SetPatientAge(p->GetPatientAge()); this->SetPatientBirthDate(p->GetPatientBirthDate()); this->SetPatientID(p->GetPatientID()); this->SetPatientName(p->GetPatientName()); this->SetPatientSex(p->GetPatientSex()); this->SetSeriesNumber(p->GetSeriesNumber()); this->SetSliceThickness(p->GetSliceThickness()); this->SetStationName(p->GetStationName()); this->SetStudyDescription(p->GetStudyDescription()); this->SetStudyID(p->GetStudyID()); this->SetXRayTubeCurrent(p->GetXRayTubeCurrent()); int nb_presets = p->GetNumberOfWindowLevelPresets(); for (int i = 0; i < nb_presets; i++) { double w, l; p->GetNthWindowLevelPreset(i, &w, &l); this->AddWindowLevelPreset(w, l); this->SetNthWindowLevelPresetComment( this->GetNumberOfWindowLevelPresets() - 1, p->GetNthWindowLevelPresetComment(i)); } } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::AddWindowLevelPreset( double w, double l) { if (!this->Internals || this->HasWindowLevelPreset(w, l)) { return; } vtkMedicalImagePropertiesInternals::WindowLevelPreset preset; preset.Window = w; preset.Level = l; this->Internals->WindowLevelPresetPool.push_back(preset); } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::HasWindowLevelPreset(double w, double l) { if (this->Internals) { vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator it = this->Internals->WindowLevelPresetPool.begin(); vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator end = this->Internals->WindowLevelPresetPool.end(); for (; it != end; ++it) { if ((*it).Window == w && (*it).Level == l) { return 1; } } } return 0; } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::RemoveWindowLevelPreset(double w, double l) { if (this->Internals) { vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator it = this->Internals->WindowLevelPresetPool.begin(); vtkMedicalImagePropertiesInternals::WindowLevelPresetPoolIterator end = this->Internals->WindowLevelPresetPool.end(); for (; it != end; ++it) { if ((*it).Window == w && (*it).Level == l) { this->Internals->WindowLevelPresetPool.erase(it); break; } } } } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::RemoveAllWindowLevelPresets() { if (this->Internals) { this->Internals->WindowLevelPresetPool.clear(); } } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetNumberOfWindowLevelPresets() { return this->Internals ? this->Internals->WindowLevelPresetPool.size() : 0; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetNthWindowLevelPreset( int idx, double *w, double *l) { if (this->Internals && idx >= 0 && idx < this->GetNumberOfWindowLevelPresets()) { *w = this->Internals->WindowLevelPresetPool[idx].Window; *l = this->Internals->WindowLevelPresetPool[idx].Level; return 1; } return 0; } //---------------------------------------------------------------------------- double* vtkMedicalImageProperties::GetNthWindowLevelPreset(int idx) { static double wl[2]; if (this->GetNthWindowLevelPreset(idx, wl, wl + 1)) { return wl; } return NULL; } //---------------------------------------------------------------------------- const char* vtkMedicalImageProperties::GetNthWindowLevelPresetComment( int idx) { if (this->Internals && idx >= 0 && idx < this->GetNumberOfWindowLevelPresets()) { return this->Internals->WindowLevelPresetPool[idx].Comment.c_str(); } return NULL; } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::SetNthWindowLevelPresetComment( int idx, const char *comment) { if (this->Internals && idx >= 0 && idx < this->GetNumberOfWindowLevelPresets()) { this->Internals->WindowLevelPresetPool[idx].Comment = (comment ? comment : ""); } } //---------------------------------------------------------------------------- double vtkMedicalImageProperties::GetSliceThicknessAsDouble() { if (this->SliceThickness) { return atof(this->SliceThickness); } return 0; } //---------------------------------------------------------------------------- double vtkMedicalImageProperties::GetGantryTiltAsDouble() { if (this->GantryTilt) { return atof(this->GantryTilt); } return 0; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetDateAsFields(const char *date, int &year, int &month, int &day) { if( !date ) { return 0; } size_t len = strlen(date); if( len == 8 ) { // DICOM V3 if( sscanf(date, "%04d%02d%02d", &year, &month, &day) != 3 ) { return 0; } } if( len == 10 ) { // Some *very* old ACR-NEMA if( sscanf(date, "%04d.%02d.%02d", &year, &month, &day) != 3 ) { return 0; } } return 1; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetPatientBirthDateYear() { const char *date = this->GetPatientBirthDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return year; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetPatientBirthDateMonth() { const char *date = this->GetPatientBirthDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return month; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetPatientBirthDateDay() { const char *date = this->GetPatientBirthDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return day; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetAcquisitionDateYear() { const char *date = this->GetAcquisitionDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return year; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetAcquisitionDateMonth() { const char *date = this->GetAcquisitionDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return month; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetAcquisitionDateDay() { const char *date = this->GetAcquisitionDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return day; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetImageDateYear() { const char *date = this->GetImageDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return year; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetImageDateMonth() { const char *date = this->GetImageDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return month; } //---------------------------------------------------------------------------- int vtkMedicalImageProperties::GetImageDateDay() { const char *date = this->GetImageDate(); int year, month, day; vtkMedicalImageProperties::GetDateAsFields(date, year, month, day); return day; } //---------------------------------------------------------------------------- void vtkMedicalImageProperties::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << "\n" << indent << "PatientName: "; if (this->PatientName) { os << this->PatientName; } os << "\n" << indent << "PatientID: "; if (this->PatientID) { os << this->PatientID; } os << "\n" << indent << "PatientAge: "; if (this->PatientAge) { os << this->PatientAge; } os << "\n" << indent << "PatientSex: "; if (this->PatientSex) { os << this->PatientSex; } os << "\n" << indent << "PatientBirthDate: "; if (this->PatientBirthDate) { os << this->PatientBirthDate; } os << "\n" << indent << "ImageDate: "; if (this->ImageDate) { os << this->ImageDate; } os << "\n" << indent << "ImageTime: "; if (this->ImageTime) { os << this->ImageTime; } os << "\n" << indent << "ImageNumber: "; if (this->ImageNumber) { os << this->ImageNumber; } os << "\n" << indent << "AcquisitionDate: "; if (this->AcquisitionDate) { os << this->AcquisitionDate; } os << "\n" << indent << "AcquisitionTime: "; if (this->AcquisitionTime) { os << this->AcquisitionTime; } os << "\n" << indent << "SeriesNumber: "; if (this->SeriesNumber) { os << this->SeriesNumber; } os << "\n" << indent << "StudyDescription: "; if (this->StudyDescription) { os << this->StudyDescription; } os << "\n" << indent << "StudyID: "; if (this->StudyID) { os << this->StudyID; } os << "\n" << indent << "Modality: "; if (this->Modality) { os << this->Modality; } os << "\n" << indent << "ManufacturerModelName: "; if (this->ManufacturerModelName) { os << this->ManufacturerModelName; } os << "\n" << indent << "StationName: "; if (this->StationName) { os << this->StationName; } os << "\n" << indent << "InstitutionName: "; if (this->InstitutionName) { os << this->InstitutionName; } os << "\n" << indent << "ConvolutionKernel: "; if (this->ConvolutionKernel) { os << this->ConvolutionKernel; } os << "\n" << indent << "SliceThickness: "; if (this->SliceThickness) { os << this->SliceThickness; } os << "\n" << indent << "KVP: "; if (this->KVP) { os << this->KVP; } os << "\n" << indent << "GantryTilt: "; if (this->GantryTilt) { os << this->GantryTilt; } os << "\n" << indent << "ExposureTime: "; if (this->ExposureTime) { os << this->ExposureTime; } os << "\n" << indent << "XRayTubeCurrent: "; if (this->XRayTubeCurrent) { os << this->XRayTubeCurrent; } os << "\n" << indent << "Exposure: "; if (this->Exposure) { os << this->Exposure; } } <|endoftext|>
<commit_before>/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2022, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "opengl-precomp.h" // Precompiled header // #include <Eigen/Dense> // First! to avoid conflicts with X.h // #include <mrpt/opengl/CSetOfObjects.h> #include <mrpt/opengl/CText.h> #include <mrpt/opengl/RenderQueue.h> #include <mrpt/opengl/opengl_api.h> #include <mrpt/system/os.h> #include <map> using namespace std; using namespace mrpt; using namespace mrpt::math; using namespace mrpt::poses; using namespace mrpt::system; using namespace mrpt::opengl; // (U,V) normalized screen coordinates: // // +----------------------+ // |(-1,+1) (+1,+1)| // | | // | | // | | // |(-1,-1) (+1,-1)| // +----------------------+ // static std::tuple<mrpt::math::TPoint2Df, float> projectToScreenCoordsAndDepth( const mrpt::math::TPoint3Df& localPt, const mrpt::opengl::TRenderMatrices& objState) { const Eigen::Vector4f lrp_hm(localPt.x, localPt.y, localPt.z, 1.0f); const auto lrp_proj = (objState.pmv_matrix.asEigen() * lrp_hm).eval(); const float depth = (lrp_proj(3) != 0) ? lrp_proj(2) / std::abs(lrp_proj(3)) : .001f; const auto uv = (lrp_proj(3) != 0) ? mrpt::math::TPoint2Df( lrp_proj(0) / lrp_proj(3), lrp_proj(1) / lrp_proj(3)) : mrpt::math::TPoint2Df(.001f, .001f); return {uv, depth}; } std::tuple<double, bool> mrpt::opengl::depthAndVisibleInView( const CRenderizable* obj, const mrpt::opengl::TRenderMatrices& objState) { // This profiler has a too-high impact. Only for very ^low-level debugging. /*#ifdef MRPT_OPENGL_PROFILER mrpt::system::CTimeLoggerEntry tle( opengl_profiler(), "depthAndVisibleInView"); #endif*/ // Get a representative depth for this object (to sort objects from // eye-distance): const mrpt::math::TPoint3Df lrp = obj->getLocalRepresentativePoint(); const auto [lrpUV, depth] = projectToScreenCoordsAndDepth(lrp, objState); // If the object is outside of the camera frustrum, do not even send // it for rendering: // bbox is in local object frame of reference. /*#ifdef MRPT_OPENGL_PROFILER mrpt::system::CTimeLoggerEntry tle2( opengl_profiler(), "depthAndVisibleInView.bbox"); #endif*/ const auto bbox = obj->getBoundingBoxLocalf(); /*#ifdef MRPT_OPENGL_PROFILER tle2.stop(); #endif*/ const mrpt::math::TPoint3Df ends[2] = {bbox.min, bbox.max}; // for each of the 8 corners: bool visible = false; bool anyNorth = false, anySouth = false, anyEast = false, anyWest = false; for (int ix = 0; !visible && ix < 2; ix++) { const float x = ends[ix].x; for (int iy = 0; !visible && iy < 2; iy++) { const float y = ends[iy].y; for (int iz = 0; !visible && iz < 2; iz++) { const float z = ends[iz].z; const auto [uv, bboxDepth] = projectToScreenCoordsAndDepth({x, y, z}, objState); const bool inside = uv.x >= -1 && uv.x <= 1 && uv.y >= -1 && uv.y < 1; if (inside) { visible = true; break; } if (uv.x < -1) anyWest = true; if (uv.x > +1) anyEast = true; if (uv.y < -1) anySouth = true; if (uv.y > +1) anyNorth = true; } } } // if we already had *any* bbox corner inside the frustrum, it's visible. // if not, *but* the corners are in opposed sides of the frustrum, then the // (central part of the) object may be still visible: if (!visible) { // This is still a bit conservative, but easy to check: if ((anyWest && anyEast) || (anyNorth && anySouth)) visible = true; } return {depth, visible}; } // Render a set of objects void mrpt::opengl::enqueForRendering( const mrpt::opengl::CListOpenGLObjects& objs, const mrpt::opengl::TRenderMatrices& state, RenderQueue& rq, RenderQueueStats* stats) { #if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL using mrpt::math::CMatrixDouble44; #ifdef MRPT_OPENGL_PROFILER mrpt::system::CTimeLoggerEntry tle(opengl_profiler(), "enqueForRendering"); #endif const char* curClassName = nullptr; try { for (const auto& objPtr : objs) { if (!objPtr) continue; #ifdef MRPT_OPENGL_PROFILER if (stats) stats->numObjTotal++; #endif // Use plain pointers, faster than smart pointers: const CRenderizable* obj = objPtr.get(); // Save class name: just in case we have an exception, for error // reporting: curClassName = obj->GetRuntimeClass()->className; // Regenerate opengl vertex buffers? if (obj->hasToUpdateBuffers()) obj->updateBuffers(); if (!obj->isVisible()) continue; const CPose3D& thisPose = obj->getPoseRef(); CMatrixFloat44 HM = thisPose.getHomogeneousMatrixVal<CMatrixDouble44>() .cast_float(); // Scaling: if (obj->getScaleX() != 1 || obj->getScaleY() != 1 || obj->getScaleZ() != 1) { auto scale = CMatrixFloat44::Identity(); scale(0, 0) = obj->getScaleX(); scale(1, 1) = obj->getScaleY(); scale(2, 2) = obj->getScaleZ(); HM.asEigen() = HM.asEigen() * scale.asEigen(); } // Make a copy of rendering state, so we always have the // original version of my parent intact. auto _ = state; // Compose relative to my parent pose: _.mv_matrix.asEigen() = _.mv_matrix.asEigen() * HM.asEigen(); // Precompute pmv_matrix to be used in shaders: _.pmv_matrix.asEigen() = _.p_matrix.asEigen() * _.mv_matrix.asEigen(); const auto [depth, withinView] = depthAndVisibleInView(obj, _); if (withinView) { #ifdef MRPT_OPENGL_PROFILER if (stats) stats->numObjRendered++; #endif // Enqeue this object... const auto lst_shaders = obj->requiredShaders(); for (const auto shader_id : lst_shaders) { // eye-to-object depth: rq[shader_id].emplace(depth, RenderQueueElement(obj, _)); } if (obj->isShowNameEnabled()) { CText& label = obj->labelObject(); // Update the label, only if it changed: if (label.getString() != obj->getName()) label.setString(obj->getName()); // Regenerate opengl vertex buffers, if first time or // label changed: if (label.hasToUpdateBuffers()) label.updateBuffers(); rq[DefaultShaderID::TEXT].emplace( depth, RenderQueueElement(&label, _)); } } // ...and its children: obj->enqueForRenderRecursive(_, rq); } // end foreach object } catch (const exception& e) { THROW_EXCEPTION_FMT( "Exception while rendering class '%s':\n%s", curClassName ? curClassName : "(undefined)", e.what()); } #endif } void mrpt::opengl::processRenderQueue( const RenderQueue& rq, std::map<shader_id_t, mrpt::opengl::Program::Ptr>& shaders, const mrpt::opengl::TLightParameters& lights) { #if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL #ifdef MRPT_OPENGL_PROFILER mrpt::system::CTimeLoggerEntry tle(opengl_profiler(), "processRenderQueue"); #endif for (const auto& rqSet : rq) { // bind the shader for this sequence of objects: mrpt::opengl::Program& shader = *shaders.at(rqSet.first); glUseProgram(shader.programId()); CHECK_OPENGL_ERROR(); CRenderizable::RenderContext rc; rc.shader = &shader; rc.shader_id = rqSet.first; rc.lights = &lights; // Process all objects using this shader: const auto& rqMap = rqSet.second; // Render in reverse depth order: for (auto it = rqMap.rbegin(); it != rqMap.rend(); ++it) { const RenderQueueElement& rqe = it->second; // Load matrices in shader: const auto IS_TRANSPOSED = GL_TRUE; if (shader.hasUniform("p_matrix")) glUniformMatrix4fv( shader.uniformId("p_matrix"), 1, IS_TRANSPOSED, rqe.renderState.p_matrix.data()); if (shader.hasUniform("mv_matrix")) glUniformMatrix4fv( shader.uniformId("mv_matrix"), 1, IS_TRANSPOSED, rqe.renderState.mv_matrix.data()); if (shader.hasUniform("pmv_matrix")) glUniformMatrix4fv( shader.uniformId("pmv_matrix"), 1, IS_TRANSPOSED, rqe.renderState.pmv_matrix.data()); rc.state = &rqe.renderState; // Render object: ASSERT_(rqe.object != nullptr); rqe.object->render(rc); } } #endif } #if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL void mrpt::opengl::checkOpenGLErr_impl( unsigned int glErrorCode, const char* filename, int lineno) { if (glErrorCode == GL_NO_ERROR) return; #if MRPT_HAS_OPENGL_GLUT const std::string sErr = mrpt::format( "[%s:%i] OpenGL error: %s", filename, lineno, reinterpret_cast<const char*>(gluErrorString(glErrorCode))); #else // w/o glu: const std::string sErr = mrpt::format("[%s:%i] OpenGL error: %u", filename, lineno, glErrorCode); #endif std::cerr << "[gl_utils::checkOpenGLError] " << sErr << std::endl; THROW_EXCEPTION(sErr); } #endif <commit_msg>finer opengl culling (#1260)<commit_after>/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | https://www.mrpt.org/ | | | | Copyright (c) 2005-2022, Individual contributors, see AUTHORS file | | See: https://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See: https://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include "opengl-precomp.h" // Precompiled header // #include <Eigen/Dense> // First! to avoid conflicts with X.h // #include <mrpt/opengl/CSetOfObjects.h> #include <mrpt/opengl/CText.h> #include <mrpt/opengl/RenderQueue.h> #include <mrpt/opengl/opengl_api.h> #include <mrpt/system/os.h> #include <map> using namespace std; using namespace mrpt; using namespace mrpt::math; using namespace mrpt::poses; using namespace mrpt::system; using namespace mrpt::opengl; // (U,V) normalized screen coordinates: // // +----------------------+ // |(-1,+1) (+1,+1)| // | | // | | // | | // |(-1,-1) (+1,-1)| // +----------------------+ // static std::tuple<mrpt::math::TPoint2Df, float> projectToScreenCoordsAndDepth( const mrpt::math::TPoint3Df& localPt, const mrpt::opengl::TRenderMatrices& objState) { const Eigen::Vector4f lrp_hm(localPt.x, localPt.y, localPt.z, 1.0f); const auto lrp_proj = (objState.pmv_matrix.asEigen() * lrp_hm).eval(); const float depth = (lrp_proj(3) != 0) ? lrp_proj(2) / lrp_proj(3) : .001f; const auto uv = (lrp_proj(3) != 0) ? mrpt::math::TPoint2Df( lrp_proj(0) / lrp_proj(3), lrp_proj(1) / lrp_proj(3)) : mrpt::math::TPoint2Df(.001f, .001f); return {uv, depth}; } std::tuple<double, bool> mrpt::opengl::depthAndVisibleInView( const CRenderizable* obj, const mrpt::opengl::TRenderMatrices& objState) { // This profiler has a too-high impact. Only for very ^low-level debugging. /*#ifdef MRPT_OPENGL_PROFILER mrpt::system::CTimeLoggerEntry tle( opengl_profiler(), "depthAndVisibleInView"); #endif*/ // Get a representative depth for this object (to sort objects from // eye-distance): const mrpt::math::TPoint3Df lrp = obj->getLocalRepresentativePoint(); const auto [lrpUV, depth] = projectToScreenCoordsAndDepth(lrp, objState); // If the object is outside of the camera frustrum, do not even send // it for rendering: // bbox is in local object frame of reference. /*#ifdef MRPT_OPENGL_PROFILER mrpt::system::CTimeLoggerEntry tle2( opengl_profiler(), "depthAndVisibleInView.bbox"); #endif*/ const auto bbox = obj->getBoundingBoxLocalf(); /*#ifdef MRPT_OPENGL_PROFILER tle2.stop(); #endif*/ const mrpt::math::TPoint3Df ends[2] = {bbox.min, bbox.max}; // for each of the 8 corners: bool visible = false; bool quadrants[9] = {false, false, false, false, false, false, false, false, false}; // dont go thru the (min,max) dimensions of one axis if it's negligible: const auto diag = bbox.max - bbox.min; const float maxLen = mrpt::max3(diag.x, diag.y, diag.z); int numLayersX = 1, numLayersY = 1, numLayersZ = 1; bool anyGoodDepth = false; if (maxLen > 0) { numLayersX = (diag.x / maxLen) > 1e-3f ? 2 : 1; numLayersY = (diag.y / maxLen) > 1e-3f ? 2 : 1; numLayersZ = (diag.z / maxLen) > 1e-3f ? 2 : 1; } for (int ix = 0; !visible && ix < numLayersX; ix++) { const float x = ends[ix].x; for (int iy = 0; !visible && iy < numLayersY; iy++) { const float y = ends[iy].y; for (int iz = 0; !visible && iz < numLayersZ; iz++) { const float z = ends[iz].z; auto [uv, bboxDepth] = projectToScreenCoordsAndDepth({x, y, z}, objState); const bool goodDepth = bboxDepth > -1.0f && bboxDepth < 1.0f; anyGoodDepth = anyGoodDepth | goodDepth; if (!goodDepth) // continue; uv *= -1.0; const bool inside = uv.x >= -1 && uv.x <= 1 && uv.y >= -1 && uv.y < 1; if (inside) { visible = true; break; } // quadrants: int qx = uv.x < -1 ? 0 : (uv.x > 1 ? 2 : 1); int qy = uv.y < -1 ? 0 : (uv.y > 1 ? 2 : 1); quadrants[qx + 3 * qy] = true; } } } // if we already had *any* bbox corner inside the frustrum, it's visible. // if not, *but* the corners are in opposed sides of the frustrum, then the // (central part of the) object may be still visible: if (!visible) { using Bools3x3_bits = uint32_t; constexpr Bools3x3_bits quadPairs[9] = { // clang-format off // 0: (0b011 << 6) | (0b011 << 3) | (0b000 << 0), // 1: (0b111 << 6) | (0b111 << 3) | (0b000 << 0), // 2: (0b110 << 6) | (0b110 << 3) | (0b000 << 0), // 3: (0b011 << 6) | (0b011 << 3) | (0b011 << 0), // 4: (0b111 << 6) | (0b101 << 3) | (0b111 << 0), // 5: (0b110 << 6) | (0b110 << 3) | (0b110 << 0), // 6: (0b000 << 6) | (0b011 << 3) | (0b011 << 0), // 7: (0b000 << 6) | (0b111 << 3) | (0b111 << 0), // 8: (0b000 << 6) | (0b110 << 3) | (0b110 << 0), // clang-format on }; uint32_t q = 0; for (int i = 0; i < 9; i++) { if (quadrants[i]) q = q | (1 << i); } for (int i = 0; i < 9 && !visible; i++) { if (!quadrants[i]) continue; if ((q & quadPairs[i]) != 0) { // at least one match for a potential edge crossing the visible // area of the frustum: visible = true; } } } if (!anyGoodDepth) visible = false; return {depth, visible}; } // Render a set of objects void mrpt::opengl::enqueForRendering( const mrpt::opengl::CListOpenGLObjects& objs, const mrpt::opengl::TRenderMatrices& state, RenderQueue& rq, RenderQueueStats* stats) { #if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL using mrpt::math::CMatrixDouble44; #ifdef MRPT_OPENGL_PROFILER mrpt::system::CTimeLoggerEntry tle(opengl_profiler(), "enqueForRendering"); #endif const char* curClassName = nullptr; try { for (const auto& objPtr : objs) { if (!objPtr) continue; #ifdef MRPT_OPENGL_PROFILER if (stats) stats->numObjTotal++; #endif // Use plain pointers, faster than smart pointers: const CRenderizable* obj = objPtr.get(); // Save class name: just in case we have an exception, for error // reporting: curClassName = obj->GetRuntimeClass()->className; // Regenerate opengl vertex buffers? if (obj->hasToUpdateBuffers()) obj->updateBuffers(); if (!obj->isVisible()) continue; const CPose3D& thisPose = obj->getPoseRef(); CMatrixFloat44 HM = thisPose.getHomogeneousMatrixVal<CMatrixDouble44>() .cast_float(); // Scaling: if (obj->getScaleX() != 1 || obj->getScaleY() != 1 || obj->getScaleZ() != 1) { auto scale = CMatrixFloat44::Identity(); scale(0, 0) = obj->getScaleX(); scale(1, 1) = obj->getScaleY(); scale(2, 2) = obj->getScaleZ(); HM.asEigen() = HM.asEigen() * scale.asEigen(); } // Make a copy of rendering state, so we always have the // original version of my parent intact. auto _ = state; // Compose relative to my parent pose: _.mv_matrix.asEigen() = _.mv_matrix.asEigen() * HM.asEigen(); // Precompute pmv_matrix to be used in shaders: _.pmv_matrix.asEigen() = _.p_matrix.asEigen() * _.mv_matrix.asEigen(); const auto [depth, withinView] = depthAndVisibleInView(obj, _); if (withinView) { #ifdef MRPT_OPENGL_PROFILER if (stats) stats->numObjRendered++; #endif // Enqeue this object... const auto lst_shaders = obj->requiredShaders(); for (const auto shader_id : lst_shaders) { // eye-to-object depth: rq[shader_id].emplace(depth, RenderQueueElement(obj, _)); } if (obj->isShowNameEnabled()) { CText& label = obj->labelObject(); // Update the label, only if it changed: if (label.getString() != obj->getName()) label.setString(obj->getName()); // Regenerate opengl vertex buffers, if first time or // label changed: if (label.hasToUpdateBuffers()) label.updateBuffers(); rq[DefaultShaderID::TEXT].emplace( depth, RenderQueueElement(&label, _)); } } // ...and its children: obj->enqueForRenderRecursive(_, rq); } // end foreach object } catch (const exception& e) { THROW_EXCEPTION_FMT( "Exception while rendering class '%s':\n%s", curClassName ? curClassName : "(undefined)", e.what()); } #endif } void mrpt::opengl::processRenderQueue( const RenderQueue& rq, std::map<shader_id_t, mrpt::opengl::Program::Ptr>& shaders, const mrpt::opengl::TLightParameters& lights) { #if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL #ifdef MRPT_OPENGL_PROFILER mrpt::system::CTimeLoggerEntry tle(opengl_profiler(), "processRenderQueue"); #endif for (const auto& rqSet : rq) { // bind the shader for this sequence of objects: mrpt::opengl::Program& shader = *shaders.at(rqSet.first); glUseProgram(shader.programId()); CHECK_OPENGL_ERROR(); CRenderizable::RenderContext rc; rc.shader = &shader; rc.shader_id = rqSet.first; rc.lights = &lights; // Process all objects using this shader: const auto& rqMap = rqSet.second; // Render in reverse depth order: for (auto it = rqMap.rbegin(); it != rqMap.rend(); ++it) { const RenderQueueElement& rqe = it->second; // Load matrices in shader: const auto IS_TRANSPOSED = GL_TRUE; if (shader.hasUniform("p_matrix")) glUniformMatrix4fv( shader.uniformId("p_matrix"), 1, IS_TRANSPOSED, rqe.renderState.p_matrix.data()); if (shader.hasUniform("mv_matrix")) glUniformMatrix4fv( shader.uniformId("mv_matrix"), 1, IS_TRANSPOSED, rqe.renderState.mv_matrix.data()); if (shader.hasUniform("pmv_matrix")) glUniformMatrix4fv( shader.uniformId("pmv_matrix"), 1, IS_TRANSPOSED, rqe.renderState.pmv_matrix.data()); rc.state = &rqe.renderState; // Render object: ASSERT_(rqe.object != nullptr); rqe.object->render(rc); } } #endif } #if MRPT_HAS_OPENGL_GLUT || MRPT_HAS_EGL void mrpt::opengl::checkOpenGLErr_impl( unsigned int glErrorCode, const char* filename, int lineno) { if (glErrorCode == GL_NO_ERROR) return; #if MRPT_HAS_OPENGL_GLUT const std::string sErr = mrpt::format( "[%s:%i] OpenGL error: %s", filename, lineno, reinterpret_cast<const char*>(gluErrorString(glErrorCode))); #else // w/o glu: const std::string sErr = mrpt::format("[%s:%i] OpenGL error: %u", filename, lineno, glErrorCode); #endif std::cerr << "[gl_utils::checkOpenGLError] " << sErr << std::endl; THROW_EXCEPTION(sErr); } #endif <|endoftext|>
<commit_before>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University 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 Stanford University 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. */ /*vc.cpp * *this class describes a virtual channel in a router *it includes buffers and virtual channel state and controls * *This class calls the routing functions */ #include <limits> #include "globals.hpp" #include "booksim.hpp" #include "vc.hpp" int VC::total_cycles = 0; const char * const VC::VCSTATE[] = {"idle", "routing", "vc_alloc", "active", "vc_spec", "vc_spec_grant"}; VC::state_info_t VC::state_info[] = {{0}, {0}, {0}, {0}, {0}, {0}}; int VC::occupancy = 0; VC::VC( const Configuration& config, int outputs, Module *parent, const string& name ) : Module( parent, name ), _state(idle), _state_time(0), _out_port(-1), _out_vc(-1), _total_cycles(0), _vc_alloc_cycles(0), _active_cycles(0), _idle_cycles(0), _routing_cycles(0), _pri(0), _watched(false), _expected_pid(-1) { _size = config.GetInt( "vc_buf_size" ) + config.GetInt( "shared_buf_size" ); _route_set = new OutputSet( ); string priority; config.GetStr( "priority", priority ); if ( priority == "local_age" ) { _pri_type = local_age_based; } else if ( priority == "queue_length" ) { _pri_type = queue_length_based; } else if ( priority == "hop_count" ) { _pri_type = hop_count_based; } else if ( priority == "none" ) { _pri_type = none; } else { _pri_type = other; } _priority_donation = config.GetInt("vc_priority_donation"); } VC::~VC() { delete _route_set; } bool VC::AddFlit( Flit *f ) { assert(f); if(_expected_pid >= 0) { if(f->pid != _expected_pid) { Error("Received flit with unexpected packet ID."); return false; } else if(f->tail) { _expected_pid = -1; } } else if(!f->tail) { _expected_pid = f->pid; } if((int)_buffer.size() >= _size) { Error("Flit buffer overflow."); return false; } // update flit priority before adding to VC buffer if(_pri_type == local_age_based) { f->pri = numeric_limits<int>::max() - GetSimTime(); assert(f->pri >= 0); } else if(_pri_type == hop_count_based) { f->pri = f->hops; assert(f->pri >= 0); } _buffer.push_back(f); UpdatePriority(); return true; } Flit *VC::FrontFlit( ) { return _buffer.empty() ? NULL : _buffer.front(); } Flit *VC::RemoveFlit( ) { Flit *f = NULL; if ( !_buffer.empty( ) ) { f = _buffer.front( ); _buffer.pop_front( ); UpdatePriority(); } else { Error("Trying to remove flit from empty buffer."); } return f; } void VC::SetState( eVCState s ) { Flit * f = FrontFlit(); if(f && f->watch) *gWatchOut << GetSimTime() << " | " << FullName() << " | " << "Changing state from " << VC::VCSTATE[_state] << " to " << VC::VCSTATE[s] << "." << endl; // do not reset state time for speculation-related pseudo state transitions if(((_state == vc_alloc) && (s == vc_spec)) || ((_state == vc_spec) && (s == vc_spec_grant))) { assert(f); if(f->watch) *gWatchOut << GetSimTime() << " | " << FullName() << " | " << "Keeping state time at " << _state_time << "." << endl; } else { if(f && f->watch) *gWatchOut << GetSimTime() << " | " << FullName() << " | " << "Resetting state time." << endl; _state_time = 0; } _state = s; } const OutputSet *VC::GetRouteSet( ) const { return _route_set; } void VC::SetOutput( int port, int vc ) { _out_port = port; _out_vc = vc; } void VC::UpdatePriority() { if(_buffer.empty()) return; if(_pri_type == queue_length_based) { _pri = _buffer.size(); } else if(_pri_type != none) { Flit * f = _buffer.front(); if((_pri_type != local_age_based) && _priority_donation) { Flit * df = f; for(size_t i = 1; i < _buffer.size(); ++i) { Flit * bf = _buffer[i]; if(bf->pri > df->pri) df = bf; } if((df != f) && (df->watch || f->watch)) { *gWatchOut << GetSimTime() << " | " << FullName() << " | " << "Flit " << df->id << " donates priority to flit " << f->id << "." << endl; } f = df; } if(f->watch) *gWatchOut << GetSimTime() << " | " << FullName() << " | " << "Flit " << f->id << " sets priority to " << f->pri << "." << endl; _pri = f->pri; } } void VC::Route( tRoutingFunction rf, const Router* router, const Flit* f, int in_channel ) { rf( router, f, in_channel, _route_set, false ); } void VC::AdvanceTime( ) { if(!Empty()) { _state_time++; } total_cycles++; switch( _state ) { case idle : _idle_cycles++; break; case active : _active_cycles++; break; case vc_spec_grant : _active_cycles++; break; case vc_alloc : _vc_alloc_cycles++; break; case vc_spec : _vc_alloc_cycles++; break; case routing : _routing_cycles++; break; } state_info[_state].cycles++; occupancy += _buffer.size(); } // ==== Debug functions ==== void VC::SetWatch( bool watch ) { _watched = watch; } bool VC::IsWatched( ) const { return _watched; } void VC::Display( ) const { if ( _state != VC::idle ) { cout << FullName() << ": " << " state: " << VCSTATE[_state] << " out_port: " << _out_port << " out_vc: " << _out_vc << " fill: " << _buffer.size() << endl ; } } void VC::DisplayStats( bool print_csv ) { if(print_csv) { for(eVCState state = state_min; state <= state_max; state = eVCState(state+1)) { cout << (float)state_info[state].cycles/(float)total_cycles << ","; } cout << (float)occupancy/(float)total_cycles << endl; } cout << "VC state breakdown:" << endl; for(eVCState state = state_min; state <= state_max; state = eVCState(state+1)) { cout << " " << VCSTATE[state] << ": " << (float)state_info[state].cycles/(float)total_cycles << endl; } cout << " occupancy: " << (float)occupancy/(float)total_cycles << endl; } <commit_msg>update VC::Display()<commit_after>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University 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 Stanford University 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. */ /*vc.cpp * *this class describes a virtual channel in a router *it includes buffers and virtual channel state and controls * *This class calls the routing functions */ #include <limits> #include "globals.hpp" #include "booksim.hpp" #include "vc.hpp" int VC::total_cycles = 0; const char * const VC::VCSTATE[] = {"idle", "routing", "vc_alloc", "active", "vc_spec", "vc_spec_grant"}; VC::state_info_t VC::state_info[] = {{0}, {0}, {0}, {0}, {0}, {0}}; int VC::occupancy = 0; VC::VC( const Configuration& config, int outputs, Module *parent, const string& name ) : Module( parent, name ), _state(idle), _state_time(0), _out_port(-1), _out_vc(-1), _total_cycles(0), _vc_alloc_cycles(0), _active_cycles(0), _idle_cycles(0), _routing_cycles(0), _pri(0), _watched(false), _expected_pid(-1) { _size = config.GetInt( "vc_buf_size" ) + config.GetInt( "shared_buf_size" ); _route_set = new OutputSet( ); string priority; config.GetStr( "priority", priority ); if ( priority == "local_age" ) { _pri_type = local_age_based; } else if ( priority == "queue_length" ) { _pri_type = queue_length_based; } else if ( priority == "hop_count" ) { _pri_type = hop_count_based; } else if ( priority == "none" ) { _pri_type = none; } else { _pri_type = other; } _priority_donation = config.GetInt("vc_priority_donation"); } VC::~VC() { delete _route_set; } bool VC::AddFlit( Flit *f ) { assert(f); if(_expected_pid >= 0) { if(f->pid != _expected_pid) { Error("Received flit with unexpected packet ID."); return false; } else if(f->tail) { _expected_pid = -1; } } else if(!f->tail) { _expected_pid = f->pid; } if((int)_buffer.size() >= _size) { Error("Flit buffer overflow."); return false; } // update flit priority before adding to VC buffer if(_pri_type == local_age_based) { f->pri = numeric_limits<int>::max() - GetSimTime(); assert(f->pri >= 0); } else if(_pri_type == hop_count_based) { f->pri = f->hops; assert(f->pri >= 0); } _buffer.push_back(f); UpdatePriority(); return true; } Flit *VC::FrontFlit( ) { return _buffer.empty() ? NULL : _buffer.front(); } Flit *VC::RemoveFlit( ) { Flit *f = NULL; if ( !_buffer.empty( ) ) { f = _buffer.front( ); _buffer.pop_front( ); UpdatePriority(); } else { Error("Trying to remove flit from empty buffer."); } return f; } void VC::SetState( eVCState s ) { Flit * f = FrontFlit(); if(f && f->watch) *gWatchOut << GetSimTime() << " | " << FullName() << " | " << "Changing state from " << VC::VCSTATE[_state] << " to " << VC::VCSTATE[s] << "." << endl; // do not reset state time for speculation-related pseudo state transitions if(((_state == vc_alloc) && (s == vc_spec)) || ((_state == vc_spec) && (s == vc_spec_grant))) { assert(f); if(f->watch) *gWatchOut << GetSimTime() << " | " << FullName() << " | " << "Keeping state time at " << _state_time << "." << endl; } else { if(f && f->watch) *gWatchOut << GetSimTime() << " | " << FullName() << " | " << "Resetting state time." << endl; _state_time = 0; } _state = s; } const OutputSet *VC::GetRouteSet( ) const { return _route_set; } void VC::SetOutput( int port, int vc ) { _out_port = port; _out_vc = vc; } void VC::UpdatePriority() { if(_buffer.empty()) return; if(_pri_type == queue_length_based) { _pri = _buffer.size(); } else if(_pri_type != none) { Flit * f = _buffer.front(); if((_pri_type != local_age_based) && _priority_donation) { Flit * df = f; for(size_t i = 1; i < _buffer.size(); ++i) { Flit * bf = _buffer[i]; if(bf->pri > df->pri) df = bf; } if((df != f) && (df->watch || f->watch)) { *gWatchOut << GetSimTime() << " | " << FullName() << " | " << "Flit " << df->id << " donates priority to flit " << f->id << "." << endl; } f = df; } if(f->watch) *gWatchOut << GetSimTime() << " | " << FullName() << " | " << "Flit " << f->id << " sets priority to " << f->pri << "." << endl; _pri = f->pri; } } void VC::Route( tRoutingFunction rf, const Router* router, const Flit* f, int in_channel ) { rf( router, f, in_channel, _route_set, false ); } void VC::AdvanceTime( ) { if(!Empty()) { _state_time++; } total_cycles++; switch( _state ) { case idle : _idle_cycles++; break; case active : _active_cycles++; break; case vc_spec_grant : _active_cycles++; break; case vc_alloc : _vc_alloc_cycles++; break; case vc_spec : _vc_alloc_cycles++; break; case routing : _routing_cycles++; break; } state_info[_state].cycles++; occupancy += _buffer.size(); } // ==== Debug functions ==== void VC::SetWatch( bool watch ) { _watched = watch; } bool VC::IsWatched( ) const { return _watched; } void VC::Display( ) const { if ( _state != VC::idle ) { cout << FullName() << ": " << " state: " << VCSTATE[_state]; if((_state == VC::vc_spec_grant) || (_state == VC::active)) { cout << " out_port: " << _out_port << " out_vc: " << _out_vc; } cout << " fill: " << _buffer.size(); if(!_buffer.empty()) { cout << " front: " << _buffer.front()->id; } cout << " pri: " << _pri; cout << endl; } } void VC::DisplayStats( bool print_csv ) { if(print_csv) { for(eVCState state = state_min; state <= state_max; state = eVCState(state+1)) { cout << (float)state_info[state].cycles/(float)total_cycles << ","; } cout << (float)occupancy/(float)total_cycles << endl; } cout << "VC state breakdown:" << endl; for(eVCState state = state_min; state <= state_max; state = eVCState(state+1)) { cout << " " << VCSTATE[state] << ": " << (float)state_info[state].cycles/(float)total_cycles << endl; } cout << " occupancy: " << (float)occupancy/(float)total_cycles << endl; } <|endoftext|>
<commit_before>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University 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 Stanford University 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. */ /*vc.cpp * *this class describes a virtual channel in a router *it includes buffers and virtual channel state and controls * *This class calls the routing functions */ #include "globals.hpp" #include "booksim.hpp" #include "vc.hpp" int VC::total_cycles = 0; const char * const VC::VCSTATE[] = {"idle", "routing", "vc_alloc", "active", "vc_spec", "vc_spec_grant"}; VC::state_info_t VC::state_info[] = {{0}, {0}, {0}, {0}, {0}, {0}}; int VC::occupancy = 0; VC::VC( const Configuration& config, int outputs ) : Module( ) { _Init( config, outputs ); } VC::VC( const Configuration& config, int outputs, Module *parent, const string& name ) : Module( parent, name ) { _Init( config, outputs ); } VC::~VC( ) { } void VC::_Init( const Configuration& config, int outputs ) { _state = idle; _state_time = 0; _size = int( config.GetInt( "vc_buf_size" ) ); _route_set = new OutputSet( outputs ); _occupied_cnt = 0; _total_cycles = 0; _vc_alloc_cycles = 0; _active_cycles = 0; _idle_cycles = 0; _routing_cycles = 0; _pri = 0; _out_port = 0 ; _out_vc = 0 ; _watched = false; } bool VC::AddFlit( Flit *f ) { bool success = false; if ( (int)_buffer.size( ) != _size ) { _buffer.push( f ); success = true; } return success; } Flit *VC::FrontFlit( ) { Flit *f; if ( !_buffer.empty( ) ) { f = _buffer.front( ); } else { f = 0; } return f; } Flit *VC::RemoveFlit( ) { Flit *f; if ( !_buffer.empty( ) ) { f = _buffer.front( ); _buffer.pop( ); } else { f = 0; } return f; } bool VC::Empty( ) const { return _buffer.empty( ); } bool VC::Full( ) const { return (int)_buffer.size( ) == _size; } VC::eVCState VC::GetState( ) const { return _state; } int VC::GetStateTime( ) const { return _state_time; } void VC::SetState( eVCState s ) { Flit * f = FrontFlit(); if(f && f->watch) cout << GetSimTime() << " | " << _fullname << " | " << "Changing state from " << VC::VCSTATE[_state] << " to " << VC::VCSTATE[s] << "." << endl; // do not reset state time for speculation-related pseudo state transitions if(((_state == vc_spec) && (s == vc_spec_grant)) || ((_state == vc_spec_grant) && (s == active))) { assert(f); if(f->watch) cout << GetSimTime() << " | " << _fullname << " | " << "Keeping state time at " << _state_time << "." << endl; } else { if(f && f->watch) cout << GetSimTime() << " | " << _fullname << " | " << "Resetting state time to zero." << endl; _state_time = 0; } if((_state == idle) && (s != idle)) { if(f) { if(f->watch) cout << GetSimTime() << " | " << _fullname << " | " << "Setting priority to " << f->pri << "." << endl; _pri = f->pri; } _occupied_cnt++; } _state = s; } const OutputSet *VC::GetRouteSet( ) const { return _route_set; } void VC::SetOutput( int port, int vc ) { _out_port = port; _out_vc = vc; } int VC::GetOutputPort( ) const { return _out_port; } int VC::GetOutputVC( ) const { return _out_vc; } int VC::GetPriority( ) const { return _pri; } int VC::GetSize() const { return (int)_buffer.size(); } void VC::Route( tRoutingFunction rf, const Router* router, const Flit* f, int in_channel ) { rf( router, f, in_channel, _route_set, false ); } void VC::AdvanceTime( ) { if(!Empty()) { _state_time++; } _total_cycles++; total_cycles++; switch( _state ) { case idle : _idle_cycles++; break; case active : _active_cycles++; break; case vc_spec_grant : _active_cycles++; break; case vc_alloc : _vc_alloc_cycles++; break; case vc_spec : _vc_alloc_cycles++; break; case routing : _routing_cycles++; break; } state_info[_state].cycles++; occupancy += _buffer.size(); } // ==== Debug functions ==== void VC::SetWatch( bool watch ) { _watched = watch; } bool VC::IsWatched( ) const { return _watched; } void VC::Display( ) const { // cout << _fullname << " : " // << "idle " << 100.0 * (double)_idle_cycles / (double)_total_cycles << "% " // << "vc_alloc " << 100.0 * (double)_vc_alloc_cycles / (double)_total_cycles << "% " // << "active " << 100.0 * (double)_active_cycles / (double)_total_cycles << "% " // << endl; if ( _state != VC::idle ) { cout << _fullname << ": " << " state: " << VCSTATE[_state] << " out_port: " << _out_port << " out_vc: " << _out_vc << " fill: " << _buffer.size() << endl ; } } void VC::DisplayStats( bool print_csv ) { if(print_csv) { for(eVCState state = state_min; state <= state_max; state = eVCState(state+1)) { cout << (float)state_info[state].cycles/(float)total_cycles << ","; } cout << (float)occupancy/(float)total_cycles << endl; } cout << "VC state breakdown:" << endl; for(eVCState state = state_min; state <= state_max; state = eVCState(state+1)) { cout << " " << VCSTATE[state] << ": " << (float)state_info[state].cycles/(float)total_cycles << endl; } cout << " occupancy: " << (float)occupancy/(float)total_cycles << endl; } <commit_msg>suppress state time reset for vc_alloc to vc_spec transition<commit_after>// $Id$ /* Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University 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 Stanford University 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. */ /*vc.cpp * *this class describes a virtual channel in a router *it includes buffers and virtual channel state and controls * *This class calls the routing functions */ #include "globals.hpp" #include "booksim.hpp" #include "vc.hpp" int VC::total_cycles = 0; const char * const VC::VCSTATE[] = {"idle", "routing", "vc_alloc", "active", "vc_spec", "vc_spec_grant"}; VC::state_info_t VC::state_info[] = {{0}, {0}, {0}, {0}, {0}, {0}}; int VC::occupancy = 0; VC::VC( const Configuration& config, int outputs ) : Module( ) { _Init( config, outputs ); } VC::VC( const Configuration& config, int outputs, Module *parent, const string& name ) : Module( parent, name ) { _Init( config, outputs ); } VC::~VC( ) { } void VC::_Init( const Configuration& config, int outputs ) { _state = idle; _state_time = 0; _size = int( config.GetInt( "vc_buf_size" ) ); _route_set = new OutputSet( outputs ); _occupied_cnt = 0; _total_cycles = 0; _vc_alloc_cycles = 0; _active_cycles = 0; _idle_cycles = 0; _routing_cycles = 0; _pri = 0; _out_port = 0 ; _out_vc = 0 ; _watched = false; } bool VC::AddFlit( Flit *f ) { bool success = false; if ( (int)_buffer.size( ) != _size ) { _buffer.push( f ); success = true; } return success; } Flit *VC::FrontFlit( ) { Flit *f; if ( !_buffer.empty( ) ) { f = _buffer.front( ); } else { f = 0; } return f; } Flit *VC::RemoveFlit( ) { Flit *f; if ( !_buffer.empty( ) ) { f = _buffer.front( ); _buffer.pop( ); } else { f = 0; } return f; } bool VC::Empty( ) const { return _buffer.empty( ); } bool VC::Full( ) const { return (int)_buffer.size( ) == _size; } VC::eVCState VC::GetState( ) const { return _state; } int VC::GetStateTime( ) const { return _state_time; } void VC::SetState( eVCState s ) { Flit * f = FrontFlit(); if(f && f->watch) cout << GetSimTime() << " | " << _fullname << " | " << "Changing state from " << VC::VCSTATE[_state] << " to " << VC::VCSTATE[s] << "." << endl; // do not reset state time for speculation-related pseudo state transitions if(((_state == vc_alloc) && (s == vc_spec)) || ((_state == vc_spec) && (s == vc_spec_grant)) || ((_state == vc_spec_grant) && (s == active))) { assert(f); if(f->watch) cout << GetSimTime() << " | " << _fullname << " | " << "Keeping state time at " << _state_time << "." << endl; } else { if(f && f->watch) cout << GetSimTime() << " | " << _fullname << " | " << "Resetting state time to zero." << endl; _state_time = 0; } if((_state == idle) && (s != idle)) { if(f) { if(f->watch) cout << GetSimTime() << " | " << _fullname << " | " << "Setting priority to " << f->pri << "." << endl; _pri = f->pri; } _occupied_cnt++; } _state = s; } const OutputSet *VC::GetRouteSet( ) const { return _route_set; } void VC::SetOutput( int port, int vc ) { _out_port = port; _out_vc = vc; } int VC::GetOutputPort( ) const { return _out_port; } int VC::GetOutputVC( ) const { return _out_vc; } int VC::GetPriority( ) const { return _pri; } int VC::GetSize() const { return (int)_buffer.size(); } void VC::Route( tRoutingFunction rf, const Router* router, const Flit* f, int in_channel ) { rf( router, f, in_channel, _route_set, false ); } void VC::AdvanceTime( ) { if(!Empty()) { _state_time++; } _total_cycles++; total_cycles++; switch( _state ) { case idle : _idle_cycles++; break; case active : _active_cycles++; break; case vc_spec_grant : _active_cycles++; break; case vc_alloc : _vc_alloc_cycles++; break; case vc_spec : _vc_alloc_cycles++; break; case routing : _routing_cycles++; break; } state_info[_state].cycles++; occupancy += _buffer.size(); } // ==== Debug functions ==== void VC::SetWatch( bool watch ) { _watched = watch; } bool VC::IsWatched( ) const { return _watched; } void VC::Display( ) const { // cout << _fullname << " : " // << "idle " << 100.0 * (double)_idle_cycles / (double)_total_cycles << "% " // << "vc_alloc " << 100.0 * (double)_vc_alloc_cycles / (double)_total_cycles << "% " // << "active " << 100.0 * (double)_active_cycles / (double)_total_cycles << "% " // << endl; if ( _state != VC::idle ) { cout << _fullname << ": " << " state: " << VCSTATE[_state] << " out_port: " << _out_port << " out_vc: " << _out_vc << " fill: " << _buffer.size() << endl ; } } void VC::DisplayStats( bool print_csv ) { if(print_csv) { for(eVCState state = state_min; state <= state_max; state = eVCState(state+1)) { cout << (float)state_info[state].cycles/(float)total_cycles << ","; } cout << (float)occupancy/(float)total_cycles << endl; } cout << "VC state breakdown:" << endl; for(eVCState state = state_min; state <= state_max; state = eVCState(state+1)) { cout << " " << VCSTATE[state] << ": " << (float)state_info[state].cycles/(float)total_cycles << endl; } cout << " occupancy: " << (float)occupancy/(float)total_cycles << endl; } <|endoftext|>
<commit_before>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include <vector> #include <caf/fwd.hpp> #include <caf/replies_to.hpp> #include <caf/stateful_actor.hpp> #include <caf/typed_actor.hpp> #include <caf/typed_event_based_actor.hpp> #include "vast/fwd.hpp" #include "vast/ids.hpp" #include "vast/store.hpp" #include "vast/system/atoms.hpp" namespace vast::system { /// @relates archive struct archive_state { std::unique_ptr<vast::store> store; static inline const char* name = "archive"; }; /// @relates archive // TODO: change the interface from 'vector<event>' to 'batch'. using archive_type = caf::typed_actor< caf::reacts_to<caf::stream<const_table_slice_ptr>>, caf::reacts_to<std::vector<event>>, caf::replies_to<ids>::with<std::vector<event>> >; /// Stores event batches and answers queries for ID sets. /// @param self The actor handle. /// @param dir The root directory of the archive. /// @param capacity The number of segments to cache in memory. /// @param max_segment_size The maximum segment size in bytes. /// @pre `max_segment_size > 0` archive_type::behavior_type archive(archive_type::stateful_pointer<archive_state> self, path dir, size_t capacity, size_t max_segment_size); } // namespace vast::system <commit_msg>Remove outdated TODO<commit_after>/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #pragma once #include <vector> #include <caf/fwd.hpp> #include <caf/replies_to.hpp> #include <caf/stateful_actor.hpp> #include <caf/typed_actor.hpp> #include <caf/typed_event_based_actor.hpp> #include "vast/fwd.hpp" #include "vast/ids.hpp" #include "vast/store.hpp" #include "vast/system/atoms.hpp" namespace vast::system { /// @relates archive struct archive_state { std::unique_ptr<vast::store> store; static inline const char* name = "archive"; }; /// @relates archive using archive_type = caf::typed_actor< caf::reacts_to<caf::stream<const_table_slice_ptr>>, caf::reacts_to<std::vector<event>>, caf::replies_to<ids>::with<std::vector<event>> >; /// Stores event batches and answers queries for ID sets. /// @param self The actor handle. /// @param dir The root directory of the archive. /// @param capacity The number of segments to cache in memory. /// @param max_segment_size The maximum segment size in bytes. /// @pre `max_segment_size > 0` archive_type::behavior_type archive(archive_type::stateful_pointer<archive_state> self, path dir, size_t capacity, size_t max_segment_size); } // namespace vast::system <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commericial and non commericial * applications, as long as this copyright notice is maintained. * * This application is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * */ #include <sstream> #include <osg/Notify> #include <osgDB/ReaderWriter> #include <osgDB/FileNameUtils> #include <osgDB/Registry> #include "daeReader.h" #include "daeWriter.h" #define EXTENSION_NAME "dae" /////////////////////////////////////////////////////////////////////////// // OSG reader/writer plugin for the COLLADA 1.4.x ".dae" format. // See http://collada.org/ and http://khronos.org/collada/ class ReaderWriterDAE : public osgDB::ReaderWriter { public: ReaderWriterDAE() : dae_(NULL) { } ~ReaderWriterDAE() { if(dae_ != NULL){ delete dae_; DAE::cleanup(); dae_ = NULL; } } const char* className() const { return "COLLADA 1.4.x DAE reader/writer"; } bool acceptsExtension(const std::string& extension) const { return osgDB::equalCaseInsensitive( extension, EXTENSION_NAME ); } ReadResult readNode(const std::string&, const Options*) const; WriteResult writeNode(const osg::Node&, const std::string&, const Options*) const; private: DAE *dae_; }; /////////////////////////////////////////////////////////////////////////// osgDB::ReaderWriter::ReadResult ReaderWriterDAE::readNode(const std::string& fname, const osgDB::ReaderWriter::Options* options) const { std::string ext( osgDB::getLowerCaseFileExtension(fname) ); if( ! acceptsExtension(ext) ) return ReadResult::FILE_NOT_HANDLED; std::string fileName( osgDB::findDataFile( fname, options ) ); if( fileName.empty() ) return ReadResult::FILE_NOT_FOUND; osg::notify(osg::INFO) << "ReaderWriterDAE( \"" << fileName << "\" )" << std::endl; if (dae_ == NULL) const_cast<ReaderWriterDAE *>(this)->dae_ = new DAE(); osgdae::daeReader daeReader(dae_); std::string fileURI( osgDB::convertFileNameToUnixStyle(fileName) ); if ( ! daeReader.convert( fileURI ) ) { osg::notify( osg::WARN ) << "Load failed in COLLADA DOM conversion" << std::endl; return ReadResult::ERROR_IN_READING_FILE; } osg::Node* rootNode( daeReader.getRootNode() ); return rootNode; } /////////////////////////////////////////////////////////////////////////// osgDB::ReaderWriter::WriteResult ReaderWriterDAE::writeNode( const osg::Node& node, const std::string& fname, const osgDB::ReaderWriter::Options* options ) const { std::string ext( osgDB::getLowerCaseFileExtension(fname) ); if( ! acceptsExtension(ext) ) return WriteResult::FILE_NOT_HANDLED; // Process options bool usePolygon(false); if( options ) { std::istringstream iss( options->getOptionString() ); std::string opt; while( std::getline( iss, opt, ',' ) ) { if( opt == "polygon") usePolygon = true; else { osg::notify(osg::WARN) << "\n" "COLLADA dae plugin: unrecognized option \"" << opt << "\"\n" << "comma-delimited options:\n" << "\tpolygon = use polygons instead of polylists for element\n" << "example: osgviewer -O polygon bar.dae" "\n" << std::endl; } } } if (dae_ == NULL) const_cast<ReaderWriterDAE *>(this)->dae_ = new DAE(); osgdae::daeWriter daeWriter(dae_, fname, usePolygon ); daeWriter.setRootNode( node ); const_cast<osg::Node*>(&node)->accept( daeWriter ); osgDB::ReaderWriter::WriteResult retVal( WriteResult::ERROR_IN_WRITING_FILE ); if ( daeWriter.isSuccess() ) { if ( daeWriter.writeFile() ) { retVal = WriteResult::FILE_SAVED; } } return retVal; } /////////////////////////////////////////////////////////////////////////// // Add ourself to the Registry to instantiate the reader/writer. osgDB::RegisterReaderWriterProxy<ReaderWriterDAE> g_readerWriter_DAE_Proxy; // vim: set sw=4 ts=8 et ic ai: <commit_msg>Added SERIALIZER to ReaderWriterDAE to make sure initialization is thread safe.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This application is open source and may be redistributed and/or modified * freely and without restriction, both in commericial and non commericial * applications, as long as this copyright notice is maintained. * * This application is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * */ #include <sstream> #include <osg/Notify> #include <osgDB/ReaderWriter> #include <osgDB/FileNameUtils> #include <osgDB/Registry> #include <OpenThreads/ScopedLock> #include <osgDB/ReentrantMutex> #include "daeReader.h" #include "daeWriter.h" #define EXTENSION_NAME "dae" #define SERIALIZER() OpenThreads::ScopedLock<osgDB::ReentrantMutex> lock(_serializerMutex) /////////////////////////////////////////////////////////////////////////// // OSG reader/writer plugin for the COLLADA 1.4.x ".dae" format. // See http://collada.org/ and http://khronos.org/collada/ class ReaderWriterDAE : public osgDB::ReaderWriter { public: ReaderWriterDAE() : _dae(NULL) { } ~ReaderWriterDAE() { if(_dae != NULL){ delete _dae; DAE::cleanup(); _dae = NULL; } } const char* className() const { return "COLLADA 1.4.x DAE reader/writer"; } bool acceptsExtension(const std::string& extension) const { return osgDB::equalCaseInsensitive( extension, EXTENSION_NAME ); } ReadResult readNode(const std::string&, const Options*) const; WriteResult writeNode(const osg::Node&, const std::string&, const Options*) const; private: mutable DAE *_dae; mutable osgDB::ReentrantMutex _serializerMutex; }; /////////////////////////////////////////////////////////////////////////// osgDB::ReaderWriter::ReadResult ReaderWriterDAE::readNode(const std::string& fname, const osgDB::ReaderWriter::Options* options) const { SERIALIZER(); std::string ext( osgDB::getLowerCaseFileExtension(fname) ); if( ! acceptsExtension(ext) ) return ReadResult::FILE_NOT_HANDLED; std::string fileName( osgDB::findDataFile( fname, options ) ); if( fileName.empty() ) return ReadResult::FILE_NOT_FOUND; osg::notify(osg::INFO) << "ReaderWriterDAE( \"" << fileName << "\" )" << std::endl; if (_dae == NULL) _dae = new DAE(); osgdae::daeReader daeReader(_dae); std::string fileURI( osgDB::convertFileNameToUnixStyle(fileName) ); if ( ! daeReader.convert( fileURI ) ) { osg::notify( osg::WARN ) << "Load failed in COLLADA DOM conversion" << std::endl; return ReadResult::ERROR_IN_READING_FILE; } osg::Node* rootNode( daeReader.getRootNode() ); return rootNode; } /////////////////////////////////////////////////////////////////////////// osgDB::ReaderWriter::WriteResult ReaderWriterDAE::writeNode( const osg::Node& node, const std::string& fname, const osgDB::ReaderWriter::Options* options ) const { SERIALIZER(); std::string ext( osgDB::getLowerCaseFileExtension(fname) ); if( ! acceptsExtension(ext) ) return WriteResult::FILE_NOT_HANDLED; // Process options bool usePolygon(false); if( options ) { std::istringstream iss( options->getOptionString() ); std::string opt; while( std::getline( iss, opt, ',' ) ) { if( opt == "polygon") usePolygon = true; else { osg::notify(osg::WARN) << "\n" "COLLADA dae plugin: unrecognized option \"" << opt << "\"\n" << "comma-delimited options:\n" << "\tpolygon = use polygons instead of polylists for element\n" << "example: osgviewer -O polygon bar.dae" "\n" << std::endl; } } } if (_dae == NULL) _dae = new DAE(); osgdae::daeWriter daeWriter(_dae, fname, usePolygon ); daeWriter.setRootNode( node ); const_cast<osg::Node*>(&node)->accept( daeWriter ); osgDB::ReaderWriter::WriteResult retVal( WriteResult::ERROR_IN_WRITING_FILE ); if ( daeWriter.isSuccess() ) { if ( daeWriter.writeFile() ) { retVal = WriteResult::FILE_SAVED; } } return retVal; } /////////////////////////////////////////////////////////////////////////// // Add ourself to the Registry to instantiate the reader/writer. osgDB::RegisterReaderWriterProxy<ReaderWriterDAE> g_readerWriter_DAE_Proxy; // vim: set sw=4 ts=8 et ic ai: <|endoftext|>
<commit_before>#include <osg/Image> #include <osg/Notify> #include <osg/Geode> #include <osg/Image> #include <osg/GL> //Make the half format work against openEXR libs // #define OPENEXR_DLL #include <osgDB/Registry> #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <ImfRgbaFile.h> #include <ImfIO.h> #include <ImfArray.h> using namespace std; using namespace Imf; using namespace Imath; /**************************************************************************** * * Follows is code written by FOI (www.foi.se) * it is a wraper of openEXR(www.openexr.com) * to add suport of exr images into osg * * Ported to a OSG-plugin, Ragnar Hammarqvist. * For patches, bugs and new features * please send them direct to the OSG dev team. **********************************************************************/ class C_IStream: public Imf::IStream { public: C_IStream (istream *fin) : IStream(""),_inStream(fin){} virtual bool read (char c[/*n*/], int n) { return _inStream->read(c,n).good(); }; virtual Int64 tellg () { return _inStream->tellg(); }; virtual void seekg (Int64 pos) { _inStream->seekg(pos); }; virtual void clear () { _inStream->clear(); }; private: std::istream * _inStream; }; class C_OStream: public Imf::OStream { public: C_OStream (ostream *fin) : OStream(""),_outStream(fin) {}; virtual void write (const char c[/*n*/], int n) { _outStream->write(c,n); }; virtual Int64 tellp () { return _outStream->tellp(); }; virtual void seekp (Int64 pos) { _outStream->seekp(pos); }; private: std::ostream * _outStream; }; unsigned char *exr_load(std::istream& fin, int *width_ret, int *height_ret, int *numComponents_ret, unsigned int *dataType_ret) { unsigned char *buffer=NULL; // returned to sender & as read from the disk bool inputError = false; Array2D<Rgba> pixels; int width,height,numComponents; try { C_IStream inStream = C_IStream(&fin); RgbaInputFile rgbafile(inStream); Box2i dw = rgbafile.dataWindow(); RgbaChannels channels = rgbafile.channels(); (*width_ret) = width = dw.max.x - dw.min.x + 1; (*height_ret)=height = dw.max.y - dw.min.y + 1; (*dataType_ret) = GL_HALF_FLOAT_ARB; pixels.resizeErase (height, width); rgbafile.setFrameBuffer((&pixels)[0][0] - dw.min.x - dw.min.y * width, 1, width); rgbafile.readPixels(dw.min.y, dw.max.y); } catch( char * str ) { inputError = true; } //If error during stream read return a empty pointer if (inputError) { return buffer; } //If there is no information in alpha channel do not store the alpha channel numComponents = 3; for (long i = height-1; i >= 0; i--) { for (long j = 0 ; j < width; j++) { if (pixels[i][j].a != half(1.0f) ) { numComponents = 4; break; } } } (*numComponents_ret) = numComponents; if (!( numComponents == 3 || numComponents == 4)) { return NULL; } //Copy and allocate data to a unsigned char array that OSG can use for texturing unsigned dataSize = (sizeof(half) * height * width * numComponents); //buffer = new unsigned char[dataSize]; buffer = (unsigned char*)malloc(dataSize); half* pOut = (half*) buffer; for (long i = height-1; i >= 0; i--) { for (long j = 0 ; j < width; j++) { (*pOut) = pixels[i][j].r; pOut++; (*pOut) = pixels[i][j].g; pOut++; (*pOut) = pixels[i][j].b; pOut++; if (numComponents >= 4) { (*pOut) = pixels[i][j].a; pOut++; } } } return buffer; } class ReaderWriterEXR : public osgDB::ReaderWriter { public: ReaderWriterEXR() { } virtual bool acceptsExtension(const std::string& extension) const { return osgDB::equalCaseInsensitive(extension,"exr"); } virtual const char* className() const { return "EXR Image Reader"; } virtual ReadResult readObject(std::istream& fin,const osgDB::ReaderWriter::Options* options =NULL) const { return readImage(fin, options); } virtual ReadResult readObject(const std::string& file, const osgDB::ReaderWriter::Options* options =NULL) const { return readImage(file, options); } virtual ReadResult readImage(std::istream& fin,const Options* =NULL) const { return readEXRStream(fin); } virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const { std::string ext = osgDB::getLowerCaseFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName = osgDB::findDataFile( file, options ); if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; std::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary); if(!istream) return ReadResult::FILE_NOT_HANDLED; ReadResult rr = readEXRStream(istream); if(rr.validImage()) { rr.getImage()->setFileName(fileName); } return rr; } virtual WriteResult writeImage(const osg::Image& image,std::ostream& fout,const Options*) const { bool success = writeEXRStream(image, fout, "<output stream>"); if(success) return WriteResult::FILE_SAVED; else return WriteResult::ERROR_IN_WRITING_FILE; } virtual WriteResult writeImage(const osg::Image &img,const std::string& fileName, const osgDB::ReaderWriter::Options*) const { std::string ext = osgDB::getFileExtension(fileName); if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED; std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary); if(!fout) return WriteResult::ERROR_IN_WRITING_FILE; bool success = writeEXRStream(img, fout, fileName); fout.close(); if(success) return WriteResult::FILE_SAVED; else return WriteResult::ERROR_IN_WRITING_FILE; } protected: bool writeEXRStream(const osg::Image &img, std::ostream& fout, const std::string &fileName) const { bool writeOK = true; //Obtain data from texture int width = img.s(); int height = img.t(); unsigned int intenalTextureFormat = img.getInternalTextureFormat(); unsigned int pixelFormat = img.getPixelFormat(); int numComponents = img.computeNumComponents(pixelFormat); unsigned int dataType = img.getDataType(); //Validates image data //if numbers of components matches if (!( numComponents == 3 || numComponents == 4)) { writeOK = false; return false; } if (!( dataType == GL_HALF_FLOAT_ARB || dataType == GL_FLOAT)) { writeOK = false; return false; } //Create a stream to save to C_OStream outStream = C_OStream(&fout); //Copy data from texture to rgba pixel format Array2D<Rgba> outPixels(height,width); //If texture is half format if (dataType == GL_HALF_FLOAT_ARB) { half* pOut = (half*) img.data(); for (long i = height-1; i >= 0; i--) { for (long j = 0 ; j < width; j++) { outPixels[i][j].r = (*pOut); pOut++; outPixels[i][j].g = (*pOut); pOut++; outPixels[i][j].b = (*pOut); pOut++; if (numComponents >= 4) { outPixels[i][j].a = (*pOut); pOut++; } else{outPixels[i][j].a = 1.0f;} } } } else if (dataType == GL_FLOAT) { float* pOut = (float*) img.data(); for (long i = height-1; i >= 0; i--) { for (long j = 0 ; j < width; j++) { outPixels[i][j].r = half(*pOut); pOut++; outPixels[i][j].g = half(*pOut); pOut++; outPixels[i][j].b = half(*pOut); pOut++; if (numComponents >= 4) { outPixels[i][j].a = half(*pOut); pOut++; } else {outPixels[i][j].a = 1.0f;} } } } else { //If texture format not supported return false; } try { //Write to stream Header outHeader(width, height); RgbaOutputFile rgbaFile (outStream, outHeader, WRITE_RGBA); rgbaFile.setFrameBuffer ((&outPixels)[0][0], 1, width); rgbaFile.writePixels (height); } catch( char * str ) { writeOK = false; } return writeOK; } ReadResult readEXRStream(std::istream& fin) const { unsigned char *imageData = NULL; int width_ret = 0; int height_ret = 0; int numComponents_ret = 4; unsigned int dataType_ret = GL_UNSIGNED_BYTE; unsigned int pixelFormat = GL_RGB; unsigned int interNalTextureFormat = GL_RGB; imageData = exr_load(fin,&width_ret,&height_ret,&numComponents_ret,&dataType_ret); if (imageData==NULL) return ReadResult::FILE_NOT_HANDLED; int s = width_ret; int t = height_ret; int r = 1; int internalFormat = numComponents_ret; if (dataType_ret == GL_HALF_FLOAT_ARB) { interNalTextureFormat = numComponents_ret == 1 ? GL_LUMINANCE16F_ARB : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA16F_ARB : numComponents_ret == 3 ? GL_RGB16F_ARB : numComponents_ret == 4 ? GL_RGBA16F_ARB : (GLenum)-1; } else if (dataType_ret == GL_FLOAT) { interNalTextureFormat = numComponents_ret == 1 ? GL_LUMINANCE32F_ARB : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA32F_ARB : numComponents_ret == 3 ? GL_RGB32F_ARB : numComponents_ret == 4 ? GL_RGBA32F_ARB : (GLenum)-1; } pixelFormat = numComponents_ret == 1 ? GL_LUMINANCE : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA : numComponents_ret == 3 ? GL_RGB : numComponents_ret == 4 ? GL_RGBA : (GLenum)-1; unsigned int dataType = dataType_ret; osg::Image* pOsgImage = new osg::Image; pOsgImage->setImage(s,t,r, interNalTextureFormat, pixelFormat, dataType, imageData, osg::Image::USE_MALLOC_FREE); return pOsgImage; } }; // now register with Registry to instantiate the exr suport // reader/writer. REGISTER_OSGPLUGIN(exr, ReaderWriterEXR) <commit_msg>Removed the use of = operator.<commit_after>#include <osg/Image> #include <osg/Notify> #include <osg/Geode> #include <osg/Image> #include <osg/GL> //Make the half format work against openEXR libs // #define OPENEXR_DLL #include <osgDB/Registry> #include <osgDB/FileNameUtils> #include <osgDB/FileUtils> #include <ImfRgbaFile.h> #include <ImfIO.h> #include <ImfArray.h> using namespace std; using namespace Imf; using namespace Imath; /**************************************************************************** * * Follows is code written by FOI (www.foi.se) * it is a wraper of openEXR(www.openexr.com) * to add suport of exr images into osg * * Ported to a OSG-plugin, Ragnar Hammarqvist. * For patches, bugs and new features * please send them direct to the OSG dev team. **********************************************************************/ class C_IStream: public Imf::IStream { public: C_IStream (istream *fin) : IStream(""),_inStream(fin){} virtual bool read (char c[/*n*/], int n) { return _inStream->read(c,n).good(); }; virtual Int64 tellg () { return _inStream->tellg(); }; virtual void seekg (Int64 pos) { _inStream->seekg(pos); }; virtual void clear () { _inStream->clear(); }; private: std::istream * _inStream; }; class C_OStream: public Imf::OStream { public: C_OStream (ostream *fin) : OStream(""),_outStream(fin) {}; virtual void write (const char c[/*n*/], int n) { _outStream->write(c,n); }; virtual Int64 tellp () { return _outStream->tellp(); }; virtual void seekp (Int64 pos) { _outStream->seekp(pos); }; private: std::ostream * _outStream; }; unsigned char *exr_load(std::istream& fin, int *width_ret, int *height_ret, int *numComponents_ret, unsigned int *dataType_ret) { unsigned char *buffer=NULL; // returned to sender & as read from the disk bool inputError = false; Array2D<Rgba> pixels; int width,height,numComponents; try { C_IStream inStream(&fin); RgbaInputFile rgbafile(inStream); Box2i dw = rgbafile.dataWindow(); RgbaChannels channels = rgbafile.channels(); (*width_ret) = width = dw.max.x - dw.min.x + 1; (*height_ret)=height = dw.max.y - dw.min.y + 1; (*dataType_ret) = GL_HALF_FLOAT_ARB; pixels.resizeErase (height, width); rgbafile.setFrameBuffer((&pixels)[0][0] - dw.min.x - dw.min.y * width, 1, width); rgbafile.readPixels(dw.min.y, dw.max.y); } catch( char * str ) { inputError = true; } //If error during stream read return a empty pointer if (inputError) { return buffer; } //If there is no information in alpha channel do not store the alpha channel numComponents = 3; for (long i = height-1; i >= 0; i--) { for (long j = 0 ; j < width; j++) { if (pixels[i][j].a != half(1.0f) ) { numComponents = 4; break; } } } (*numComponents_ret) = numComponents; if (!( numComponents == 3 || numComponents == 4)) { return NULL; } //Copy and allocate data to a unsigned char array that OSG can use for texturing unsigned dataSize = (sizeof(half) * height * width * numComponents); //buffer = new unsigned char[dataSize]; buffer = (unsigned char*)malloc(dataSize); half* pOut = (half*) buffer; for (long i = height-1; i >= 0; i--) { for (long j = 0 ; j < width; j++) { (*pOut) = pixels[i][j].r; pOut++; (*pOut) = pixels[i][j].g; pOut++; (*pOut) = pixels[i][j].b; pOut++; if (numComponents >= 4) { (*pOut) = pixels[i][j].a; pOut++; } } } return buffer; } class ReaderWriterEXR : public osgDB::ReaderWriter { public: ReaderWriterEXR() { } virtual bool acceptsExtension(const std::string& extension) const { return osgDB::equalCaseInsensitive(extension,"exr"); } virtual const char* className() const { return "EXR Image Reader"; } virtual ReadResult readObject(std::istream& fin,const osgDB::ReaderWriter::Options* options =NULL) const { return readImage(fin, options); } virtual ReadResult readObject(const std::string& file, const osgDB::ReaderWriter::Options* options =NULL) const { return readImage(file, options); } virtual ReadResult readImage(std::istream& fin,const Options* =NULL) const { return readEXRStream(fin); } virtual ReadResult readImage(const std::string& file, const osgDB::ReaderWriter::Options* options) const { std::string ext = osgDB::getLowerCaseFileExtension(file); if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; std::string fileName = osgDB::findDataFile( file, options ); if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; std::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary); if(!istream) return ReadResult::FILE_NOT_HANDLED; ReadResult rr = readEXRStream(istream); if(rr.validImage()) { rr.getImage()->setFileName(fileName); } return rr; } virtual WriteResult writeImage(const osg::Image& image,std::ostream& fout,const Options*) const { bool success = writeEXRStream(image, fout, "<output stream>"); if(success) return WriteResult::FILE_SAVED; else return WriteResult::ERROR_IN_WRITING_FILE; } virtual WriteResult writeImage(const osg::Image &img,const std::string& fileName, const osgDB::ReaderWriter::Options*) const { std::string ext = osgDB::getFileExtension(fileName); if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED; std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary); if(!fout) return WriteResult::ERROR_IN_WRITING_FILE; bool success = writeEXRStream(img, fout, fileName); fout.close(); if(success) return WriteResult::FILE_SAVED; else return WriteResult::ERROR_IN_WRITING_FILE; } protected: bool writeEXRStream(const osg::Image &img, std::ostream& fout, const std::string &fileName) const { bool writeOK = true; //Obtain data from texture int width = img.s(); int height = img.t(); unsigned int intenalTextureFormat = img.getInternalTextureFormat(); unsigned int pixelFormat = img.getPixelFormat(); int numComponents = img.computeNumComponents(pixelFormat); unsigned int dataType = img.getDataType(); //Validates image data //if numbers of components matches if (!( numComponents == 3 || numComponents == 4)) { writeOK = false; return false; } if (!( dataType == GL_HALF_FLOAT_ARB || dataType == GL_FLOAT)) { writeOK = false; return false; } //Create a stream to save to C_OStream outStream(&fout); //Copy data from texture to rgba pixel format Array2D<Rgba> outPixels(height,width); //If texture is half format if (dataType == GL_HALF_FLOAT_ARB) { half* pOut = (half*) img.data(); for (long i = height-1; i >= 0; i--) { for (long j = 0 ; j < width; j++) { outPixels[i][j].r = (*pOut); pOut++; outPixels[i][j].g = (*pOut); pOut++; outPixels[i][j].b = (*pOut); pOut++; if (numComponents >= 4) { outPixels[i][j].a = (*pOut); pOut++; } else{outPixels[i][j].a = 1.0f;} } } } else if (dataType == GL_FLOAT) { float* pOut = (float*) img.data(); for (long i = height-1; i >= 0; i--) { for (long j = 0 ; j < width; j++) { outPixels[i][j].r = half(*pOut); pOut++; outPixels[i][j].g = half(*pOut); pOut++; outPixels[i][j].b = half(*pOut); pOut++; if (numComponents >= 4) { outPixels[i][j].a = half(*pOut); pOut++; } else {outPixels[i][j].a = 1.0f;} } } } else { //If texture format not supported return false; } try { //Write to stream Header outHeader(width, height); RgbaOutputFile rgbaFile (outStream, outHeader, WRITE_RGBA); rgbaFile.setFrameBuffer ((&outPixels)[0][0], 1, width); rgbaFile.writePixels (height); } catch( char * str ) { writeOK = false; } return writeOK; } ReadResult readEXRStream(std::istream& fin) const { unsigned char *imageData = NULL; int width_ret = 0; int height_ret = 0; int numComponents_ret = 4; unsigned int dataType_ret = GL_UNSIGNED_BYTE; unsigned int pixelFormat = GL_RGB; unsigned int interNalTextureFormat = GL_RGB; imageData = exr_load(fin,&width_ret,&height_ret,&numComponents_ret,&dataType_ret); if (imageData==NULL) return ReadResult::FILE_NOT_HANDLED; int s = width_ret; int t = height_ret; int r = 1; int internalFormat = numComponents_ret; if (dataType_ret == GL_HALF_FLOAT_ARB) { interNalTextureFormat = numComponents_ret == 1 ? GL_LUMINANCE16F_ARB : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA16F_ARB : numComponents_ret == 3 ? GL_RGB16F_ARB : numComponents_ret == 4 ? GL_RGBA16F_ARB : (GLenum)-1; } else if (dataType_ret == GL_FLOAT) { interNalTextureFormat = numComponents_ret == 1 ? GL_LUMINANCE32F_ARB : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA32F_ARB : numComponents_ret == 3 ? GL_RGB32F_ARB : numComponents_ret == 4 ? GL_RGBA32F_ARB : (GLenum)-1; } pixelFormat = numComponents_ret == 1 ? GL_LUMINANCE : numComponents_ret == 2 ? GL_LUMINANCE_ALPHA : numComponents_ret == 3 ? GL_RGB : numComponents_ret == 4 ? GL_RGBA : (GLenum)-1; unsigned int dataType = dataType_ret; osg::Image* pOsgImage = new osg::Image; pOsgImage->setImage(s,t,r, interNalTextureFormat, pixelFormat, dataType, imageData, osg::Image::USE_MALLOC_FREE); return pOsgImage; } }; // now register with Registry to instantiate the exr suport // reader/writer. REGISTER_OSGPLUGIN(exr, ReaderWriterEXR) <|endoftext|>
<commit_before>// *************************************************************************** // // Generated automatically by genwrapper. // Please DO NOT EDIT this file! // // *************************************************************************** #include <osgIntrospection/ReflectionMacros> #include <osgIntrospection/TypedMethodInfo> #include <osgIntrospection/StaticMethodInfo> #include <osgIntrospection/Attributes> #include <osg/CoordinateSystemNode> #include <osg/CopyOp> #include <osg/Object> #include <osg/Vec3d> #include <osgTerrain/Locator> // Must undefine IN and OUT macros defined in Windows headers #ifdef IN #undef IN #endif #ifdef OUT #undef OUT #endif BEGIN_OBJECT_REFLECTOR(osgTerrain::CartizianLocator) I_BaseType(osgTerrain::Locator); I_ConstructorWithDefaults6(IN, double, originX, , IN, double, originY, , IN, double, lengthX, , IN, double, lengthY, , IN, double, height, 0.0f, IN, double, heightScale, 1.0f, ____CartizianLocator__double__double__double__double__double__double, "", ""); I_MethodWithDefaults6(void, setExtents, IN, double, originX, , IN, double, originY, , IN, double, lengthX, , IN, double, lengthY, , IN, double, height, 0.0f, IN, double, heightScale, 1.0f, Properties::NON_VIRTUAL, __void__setExtents__double__double__double__double__double__double, "", ""); I_Method1(void, setOriginX, IN, double, x, Properties::NON_VIRTUAL, __void__setOriginX__double, "", ""); I_Method0(double, getOriginX, Properties::NON_VIRTUAL, __double__getOriginX, "", ""); I_Method1(void, setOriginY, IN, double, y, Properties::NON_VIRTUAL, __void__setOriginY__double, "", ""); I_Method0(double, getOriginY, Properties::NON_VIRTUAL, __double__getOriginY, "", ""); I_Method1(void, setLengthX, IN, double, x, Properties::NON_VIRTUAL, __void__setLengthX__double, "", ""); I_Method0(double, getLengthX, Properties::NON_VIRTUAL, __double__getLengthX, "", ""); I_Method1(void, setLengthY, IN, double, y, Properties::NON_VIRTUAL, __void__setLengthY__double, "", ""); I_Method0(double, getLengthY, Properties::NON_VIRTUAL, __double__getLengthY, "", ""); I_Method0(bool, orientationOpenGL, Properties::VIRTUAL, __bool__orientationOpenGL, "", ""); I_Method2(bool, convertLocalToModel, IN, const osg::Vec3d &, local, IN, osg::Vec3d &, world, Properties::VIRTUAL, __bool__convertLocalToModel__C5_osg_Vec3d_R1__osg_Vec3d_R1, "", ""); I_Method2(bool, convertModelToLocal, IN, const osg::Vec3d &, world, IN, osg::Vec3d &, local, Properties::VIRTUAL, __bool__convertModelToLocal__C5_osg_Vec3d_R1__osg_Vec3d_R1, "", ""); I_SimpleProperty(double, LengthX, __double__getLengthX, __void__setLengthX__double); I_SimpleProperty(double, LengthY, __double__getLengthY, __void__setLengthY__double); I_SimpleProperty(double, OriginX, __double__getOriginX, __void__setOriginX__double); I_SimpleProperty(double, OriginY, __double__getOriginY, __void__setOriginY__double); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgTerrain::EllipsoidLocator) I_BaseType(osgTerrain::Locator); I_ConstructorWithDefaults6(IN, double, longitude, , IN, double, latitude, , IN, double, deltaLongitude, , IN, double, deltaLatitude, , IN, double, height, 0.0, IN, double, heightScale, 1.0f, ____EllipsoidLocator__double__double__double__double__double__double, "", ""); I_MethodWithDefaults6(void, setExtents, IN, double, longitude, , IN, double, latitude, , IN, double, deltaLongitude, , IN, double, deltaLatitude, , IN, double, height, 0.0, IN, double, heightScale, 1.0f, Properties::NON_VIRTUAL, __void__setExtents__double__double__double__double__double__double, "", ""); I_Method0(double, getLongitude, Properties::NON_VIRTUAL, __double__getLongitude, "", ""); I_Method0(double, getDeltaLongitude, Properties::NON_VIRTUAL, __double__getDeltaLongitude, "", ""); I_Method0(double, getLatitude, Properties::NON_VIRTUAL, __double__getLatitude, "", ""); I_Method0(double, getDeltaLatitude, Properties::NON_VIRTUAL, __double__getDeltaLatitude, "", ""); I_Method0(double, getHeight, Properties::NON_VIRTUAL, __double__getHeight, "", ""); I_Method0(osg::EllipsoidModel *, getEllipsoidModel, Properties::NON_VIRTUAL, __osg_EllipsoidModel_P1__getEllipsoidModel, "", ""); I_Method0(const osg::EllipsoidModel *, getEllipsoidModel, Properties::NON_VIRTUAL, __C5_osg_EllipsoidModel_P1__getEllipsoidModel, "", ""); I_Method0(bool, orientationOpenGL, Properties::VIRTUAL, __bool__orientationOpenGL, "", ""); I_Method2(bool, convertLocalToModel, IN, const osg::Vec3d &, local, IN, osg::Vec3d &, world, Properties::VIRTUAL, __bool__convertLocalToModel__C5_osg_Vec3d_R1__osg_Vec3d_R1, "", ""); I_Method2(bool, convertModelToLocal, IN, const osg::Vec3d &, world, IN, osg::Vec3d &, local, Properties::VIRTUAL, __bool__convertModelToLocal__C5_osg_Vec3d_R1__osg_Vec3d_R1, "", ""); I_SimpleProperty(double, DeltaLatitude, __double__getDeltaLatitude, 0); I_SimpleProperty(double, DeltaLongitude, __double__getDeltaLongitude, 0); I_SimpleProperty(osg::EllipsoidModel *, EllipsoidModel, __osg_EllipsoidModel_P1__getEllipsoidModel, 0); I_SimpleProperty(double, Height, __double__getHeight, 0); I_SimpleProperty(double, Latitude, __double__getLatitude, 0); I_SimpleProperty(double, Longitude, __double__getLongitude, 0); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgTerrain::Locator) I_BaseType(osg::Object); I_Constructor0(____Locator, "", ""); I_ConstructorWithDefaults2(IN, const osgTerrain::Locator &, x, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY, ____Locator__C5_Locator_R1__C5_osg_CopyOp_R1, "Copy constructor using CopyOp to manage deep vs shallow copy. ", ""); I_Method0(osg::Object *, cloneType, Properties::VIRTUAL, __osg_Object_P1__cloneType, "Clone the type of an object, with Object* return type. ", "Must be defined by derived classes. "); I_Method1(osg::Object *, clone, IN, const osg::CopyOp &, copyop, Properties::VIRTUAL, __osg_Object_P1__clone__C5_osg_CopyOp_R1, "Clone an object, with Object* return type. ", "Must be defined by derived classes. "); I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj, Properties::VIRTUAL, __bool__isSameKindAs__C5_osg_Object_P1, "", ""); I_Method0(const char *, libraryName, Properties::VIRTUAL, __C5_char_P1__libraryName, "return the name of the object's library. ", "Must be defined by derived classes. The OpenSceneGraph convention is that the namespace of a library is the same as the library name. "); I_Method0(const char *, className, Properties::VIRTUAL, __C5_char_P1__className, "return the name of the object's class type. ", "Must be defined by derived classes. "); I_Method0(bool, orientationOpenGL, Properties::VIRTUAL, __bool__orientationOpenGL, "", ""); I_Method2(bool, convertLocalToModel, IN, const osg::Vec3d &, x, IN, osg::Vec3d &, x, Properties::VIRTUAL, __bool__convertLocalToModel__C5_osg_Vec3d_R1__osg_Vec3d_R1, "", ""); I_Method2(bool, convertModelToLocal, IN, const osg::Vec3d &, x, IN, osg::Vec3d &, x, Properties::VIRTUAL, __bool__convertModelToLocal__C5_osg_Vec3d_R1__osg_Vec3d_R1, "", ""); I_Method3(bool, computeLocalBounds, IN, osgTerrain::Locator &, source, IN, osg::Vec3d &, bottomLeft, IN, osg::Vec3d &, topRight, Properties::NON_VIRTUAL, __bool__computeLocalBounds__Locator_R1__osg_Vec3d_R1__osg_Vec3d_R1, "", ""); I_StaticMethod4(bool, convertLocalCoordBetween, IN, const osgTerrain::Locator &, source, IN, const osg::Vec3d &, sourceNDC, IN, const osgTerrain::Locator &, destination, IN, osg::Vec3d &, destinationNDC, __bool__convertLocalCoordBetween__C5_Locator_R1__C5_osg_Vec3d_R1__C5_Locator_R1__osg_Vec3d_R1_S, "", ""); END_REFLECTOR <commit_msg>updated wrapper<commit_after>// *************************************************************************** // // Generated automatically by genwrapper. // Please DO NOT EDIT this file! // // *************************************************************************** #include <osgIntrospection/ReflectionMacros> #include <osgIntrospection/TypedMethodInfo> #include <osgIntrospection/StaticMethodInfo> #include <osgIntrospection/Attributes> #include <osg/CoordinateSystemNode> #include <osg/CopyOp> #include <osg/Object> #include <osg/Vec3d> #include <osgTerrain/Locator> // Must undefine IN and OUT macros defined in Windows headers #ifdef IN #undef IN #endif #ifdef OUT #undef OUT #endif BEGIN_OBJECT_REFLECTOR(osgTerrain::CartizianLocator) I_BaseType(osgTerrain::Locator); I_ConstructorWithDefaults6(IN, double, originX, , IN, double, originY, , IN, double, lengthX, , IN, double, lengthY, , IN, double, height, 0.0f, IN, double, heightScale, 1.0f, ____CartizianLocator__double__double__double__double__double__double, "", ""); I_MethodWithDefaults6(void, setExtents, IN, double, originX, , IN, double, originY, , IN, double, lengthX, , IN, double, lengthY, , IN, double, height, 0.0f, IN, double, heightScale, 1.0f, Properties::NON_VIRTUAL, __void__setExtents__double__double__double__double__double__double, "", ""); I_Method1(void, setOriginX, IN, double, x, Properties::NON_VIRTUAL, __void__setOriginX__double, "", ""); I_Method0(double, getOriginX, Properties::NON_VIRTUAL, __double__getOriginX, "", ""); I_Method1(void, setOriginY, IN, double, y, Properties::NON_VIRTUAL, __void__setOriginY__double, "", ""); I_Method0(double, getOriginY, Properties::NON_VIRTUAL, __double__getOriginY, "", ""); I_Method1(void, setLengthX, IN, double, x, Properties::NON_VIRTUAL, __void__setLengthX__double, "", ""); I_Method0(double, getLengthX, Properties::NON_VIRTUAL, __double__getLengthX, "", ""); I_Method1(void, setLengthY, IN, double, y, Properties::NON_VIRTUAL, __void__setLengthY__double, "", ""); I_Method0(double, getLengthY, Properties::NON_VIRTUAL, __double__getLengthY, "", ""); I_Method0(bool, orientationOpenGL, Properties::VIRTUAL, __bool__orientationOpenGL, "", ""); I_Method2(bool, convertLocalToModel, IN, const osg::Vec3d &, local, IN, osg::Vec3d &, world, Properties::VIRTUAL, __bool__convertLocalToModel__C5_osg_Vec3d_R1__osg_Vec3d_R1, "", ""); I_Method2(bool, convertModelToLocal, IN, const osg::Vec3d &, world, IN, osg::Vec3d &, local, Properties::VIRTUAL, __bool__convertModelToLocal__C5_osg_Vec3d_R1__osg_Vec3d_R1, "", ""); I_SimpleProperty(double, LengthX, __double__getLengthX, __void__setLengthX__double); I_SimpleProperty(double, LengthY, __double__getLengthY, __void__setLengthY__double); I_SimpleProperty(double, OriginX, __double__getOriginX, __void__setOriginX__double); I_SimpleProperty(double, OriginY, __double__getOriginY, __void__setOriginY__double); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgTerrain::EllipsoidLocator) I_BaseType(osgTerrain::Locator); I_ConstructorWithDefaults8(IN, double, longitude, , IN, double, latitude, , IN, double, deltaLongitude, , IN, double, deltaLatitude, , IN, double, height, 0.0, IN, double, heightScale, 1.0f, IN, double, radiusEquator, osg::WGS_84_RADIUS_EQUATOR, IN, double, radiusPolar, osg::WGS_84_RADIUS_POLAR, ____EllipsoidLocator__double__double__double__double__double__double__double__double, "", ""); I_MethodWithDefaults6(void, setExtents, IN, double, longitude, , IN, double, latitude, , IN, double, deltaLongitude, , IN, double, deltaLatitude, , IN, double, height, 0.0, IN, double, heightScale, 1.0f, Properties::NON_VIRTUAL, __void__setExtents__double__double__double__double__double__double, "", ""); I_Method0(double, getLongitude, Properties::NON_VIRTUAL, __double__getLongitude, "", ""); I_Method0(double, getDeltaLongitude, Properties::NON_VIRTUAL, __double__getDeltaLongitude, "", ""); I_Method0(double, getLatitude, Properties::NON_VIRTUAL, __double__getLatitude, "", ""); I_Method0(double, getDeltaLatitude, Properties::NON_VIRTUAL, __double__getDeltaLatitude, "", ""); I_Method0(double, getHeight, Properties::NON_VIRTUAL, __double__getHeight, "", ""); I_Method1(void, setEllipsoidModel, IN, osg::EllipsoidModel *, em, Properties::NON_VIRTUAL, __void__setEllipsoidModel__osg_EllipsoidModel_P1, "", ""); I_Method0(osg::EllipsoidModel *, getEllipsoidModel, Properties::NON_VIRTUAL, __osg_EllipsoidModel_P1__getEllipsoidModel, "", ""); I_Method0(const osg::EllipsoidModel *, getEllipsoidModel, Properties::NON_VIRTUAL, __C5_osg_EllipsoidModel_P1__getEllipsoidModel, "", ""); I_Method0(bool, orientationOpenGL, Properties::VIRTUAL, __bool__orientationOpenGL, "", ""); I_Method2(bool, convertLocalToModel, IN, const osg::Vec3d &, local, IN, osg::Vec3d &, world, Properties::VIRTUAL, __bool__convertLocalToModel__C5_osg_Vec3d_R1__osg_Vec3d_R1, "", ""); I_Method2(bool, convertModelToLocal, IN, const osg::Vec3d &, world, IN, osg::Vec3d &, local, Properties::VIRTUAL, __bool__convertModelToLocal__C5_osg_Vec3d_R1__osg_Vec3d_R1, "", ""); I_SimpleProperty(double, DeltaLatitude, __double__getDeltaLatitude, 0); I_SimpleProperty(double, DeltaLongitude, __double__getDeltaLongitude, 0); I_SimpleProperty(osg::EllipsoidModel *, EllipsoidModel, __osg_EllipsoidModel_P1__getEllipsoidModel, __void__setEllipsoidModel__osg_EllipsoidModel_P1); I_SimpleProperty(double, Height, __double__getHeight, 0); I_SimpleProperty(double, Latitude, __double__getLatitude, 0); I_SimpleProperty(double, Longitude, __double__getLongitude, 0); END_REFLECTOR BEGIN_OBJECT_REFLECTOR(osgTerrain::Locator) I_BaseType(osg::Object); I_Constructor0(____Locator, "", ""); I_ConstructorWithDefaults2(IN, const osgTerrain::Locator &, x, , IN, const osg::CopyOp &, copyop, osg::CopyOp::SHALLOW_COPY, ____Locator__C5_Locator_R1__C5_osg_CopyOp_R1, "Copy constructor using CopyOp to manage deep vs shallow copy. ", ""); I_Method0(osg::Object *, cloneType, Properties::VIRTUAL, __osg_Object_P1__cloneType, "Clone the type of an object, with Object* return type. ", "Must be defined by derived classes. "); I_Method1(osg::Object *, clone, IN, const osg::CopyOp &, copyop, Properties::VIRTUAL, __osg_Object_P1__clone__C5_osg_CopyOp_R1, "Clone an object, with Object* return type. ", "Must be defined by derived classes. "); I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj, Properties::VIRTUAL, __bool__isSameKindAs__C5_osg_Object_P1, "", ""); I_Method0(const char *, libraryName, Properties::VIRTUAL, __C5_char_P1__libraryName, "return the name of the object's library. ", "Must be defined by derived classes. The OpenSceneGraph convention is that the namespace of a library is the same as the library name. "); I_Method0(const char *, className, Properties::VIRTUAL, __C5_char_P1__className, "return the name of the object's class type. ", "Must be defined by derived classes. "); I_Method0(bool, orientationOpenGL, Properties::VIRTUAL, __bool__orientationOpenGL, "", ""); I_Method2(bool, convertLocalToModel, IN, const osg::Vec3d &, x, IN, osg::Vec3d &, x, Properties::VIRTUAL, __bool__convertLocalToModel__C5_osg_Vec3d_R1__osg_Vec3d_R1, "", ""); I_Method2(bool, convertModelToLocal, IN, const osg::Vec3d &, x, IN, osg::Vec3d &, x, Properties::VIRTUAL, __bool__convertModelToLocal__C5_osg_Vec3d_R1__osg_Vec3d_R1, "", ""); I_Method3(bool, computeLocalBounds, IN, osgTerrain::Locator &, source, IN, osg::Vec3d &, bottomLeft, IN, osg::Vec3d &, topRight, Properties::NON_VIRTUAL, __bool__computeLocalBounds__Locator_R1__osg_Vec3d_R1__osg_Vec3d_R1, "", ""); I_StaticMethod4(bool, convertLocalCoordBetween, IN, const osgTerrain::Locator &, source, IN, const osg::Vec3d &, sourceNDC, IN, const osgTerrain::Locator &, destination, IN, osg::Vec3d &, destinationNDC, __bool__convertLocalCoordBetween__C5_Locator_R1__C5_osg_Vec3d_R1__C5_Locator_R1__osg_Vec3d_R1_S, "", ""); END_REFLECTOR <|endoftext|>
<commit_before>#include "GraphML.h" #include "DirectedGraph.h" #include "UndirectedGraph.h" #include <tinyxml2.h> #include <Table.h> #include <cassert> #include <map> #include <iostream> using namespace std; using namespace tinyxml2; using namespace table; GraphML::GraphML() : FileTypeHandler("GraphML", true) { addExtension("graphml"); } std::shared_ptr<Graph> GraphML::openGraph(const char * filename) { RenderMode mode = RENDERMODE_3D; XMLDocument doc; doc.LoadFile(filename); XMLElement * graphml_element = doc.FirstChildElement("graphml"); assert(graphml_element); XMLElement * graph_element = graphml_element->FirstChildElement("graph"); assert(graph_element); return createGraphFromElement(*graphml_element, *graph_element); } std::shared_ptr<Graph> GraphML::createGraphFromElement(XMLElement & graphml_element, XMLElement & graph_element) const { map<string, int> nodes_by_id; const char * edgedefault = graph_element.Attribute("edgedefault"); bool directed = true; if (edgedefault && strcmp(edgedefault, "undirected") == 0) { directed = false; } std::shared_ptr<Graph> graph; if (directed) { graph = std::make_shared<DirectedGraph>(); } else { graph = std::make_shared<UndirectedGraph>(); } graph->setNodeArray(std::make_shared<NodeArray>()); auto & node_table = graph->getNodeData(); auto & edge_table = directed ? graph->getEdgeData() : graph->getFaceData(); auto & node_id_column = node_table.addTextColumn("id"); auto & edge_id_column = edge_table.addTextColumn("id"); XMLElement * key_element = graphml_element.FirstChildElement("key"); for ( ; key_element ; key_element = key_element->NextSiblingElement("key") ) { const char * key_type = key_element->Attribute("attr.type"); const char * key_id = key_element->Attribute("id"); const char * for_type = key_element->Attribute("for"); const char * name = key_element->Attribute("attr.name"); assert(key_type && key_id && for_type); std::shared_ptr<Column> column; if (strcmp(key_type, "string") == 0) { column = std::make_shared<ColumnText>(key_id ? key_id : ""); } else if (strcmp(key_type, "double") == 0 || strcmp(key_type, "float") == 0) { column = std::make_shared<ColumnDouble>(key_id ? key_id : ""); } else if (strcmp(key_type, "int") == 0) { column = std::make_shared<ColumnInt>(key_id ? key_id : ""); } else { assert(0); } if (strcmp(for_type, "node") == 0) { node_table.addColumn(column); } else if (strcmp(for_type, "edge") == 0) { edge_table.addColumn(column); } else { assert(0); } } bool is_complex = false; XMLElement * node_element = graph_element.FirstChildElement("node"); for ( ; node_element ; node_element = node_element->NextSiblingElement("node") ) { const char * node_id_text = node_element->Attribute("id"); assert(node_id_text); int node_id = graph->getNodeArray().addNode(); node_id_column.setValue(node_id, node_id_text); nodes_by_id[node_id_text] = node_id + 1; XMLElement * data_element = node_element->FirstChildElement("data"); for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) { const char * key = data_element->Attribute("key"); assert(key); const char * text = data_element->GetText(); if (text) { node_table[key].setValue(node_id, text); } } graph->getNodeArray().updateNodeAppearanceSlow(node_id); XMLElement * nested_graph_element = node_element->FirstChildElement("graph"); if (nested_graph_element) { auto nested_graph = createGraphFromElement(graphml_element, *nested_graph_element); assert(nested_graph.get()); is_complex = true; graph->getNodeArray().setNestedGraph(node_id, nested_graph); } } graph->randomizeGeometry(); graph->setComplexGraph(is_complex); graph->setHasSubGraphs(is_complex); XMLElement * edge_element = graph_element.FirstChildElement("edge"); for ( ; edge_element ; edge_element = edge_element->NextSiblingElement("edge") ) { const char * edge_id_text = edge_element->Attribute("id"); const char * source = edge_element->Attribute("source"); const char * target = edge_element->Attribute("target"); assert(source && target); if (strcmp(source, target) == 0) { cerr << "GraphML: skipping self link for " << source << endl; continue; } int source_node = nodes_by_id[source]; int target_node = nodes_by_id[target]; if (source_node && target_node) { int edge_id; if (directed) { edge_id = graph->addEdge(source_node - 1, target_node - 1); if (edge_id_text && strlen(edge_id_text) != 0) { edge_id_column.setValue(edge_id, edge_id_text); } } else { edge_id = graph->addFace(-1); graph->addEdge(source_node - 1, target_node - 1, edge_id); graph->addEdge(target_node - 1, source_node - 1, edge_id); } XMLElement * data_element = edge_element->FirstChildElement("data"); for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) { const char * key = data_element->Attribute("key"); assert(key); const char * text = data_element->GetText(); if (text) { edge_table[key].setValue(edge_id, text); } } } else { if (!source_node) { // cerr << "cannot find node " << source << endl; } if (!target_node) { // cerr << "cannot find node " << target << endl; } } } return graph; } bool GraphML::saveGraph(const Graph & graph, const std::string & filename) { XMLDocument doc; doc.LinkEndChild(doc.NewDeclaration()); XMLElement * graphml_element = doc.NewElement("graphml"); graphml_element->SetAttribute("xmlns", "http://graphml.graphdrawing.org/xmlns"); bool directed = graph.isDirected(); auto & node_table = graph.getNodeData(); auto & edge_table = directed ? graph.getEdgeData() : graph.getFaceData(); for (auto & col : node_table.getColumns()) { XMLElement * key_element = doc.NewElement("key"); key_element->SetAttribute("attr.name", col.first.c_str()); key_element->SetAttribute("id", col.first.c_str()); key_element->SetAttribute("attr.type", col.second->getTypeText()); key_element->SetAttribute("for", "node"); graphml_element->LinkEndChild(key_element); } for (auto & col : edge_table.getColumns()) { XMLElement * key_element = doc.NewElement("key"); key_element->SetAttribute("attr.name", col.first.c_str()); key_element->SetAttribute("id", col.first.c_str()); key_element->SetAttribute("attr.type", col.second->getTypeText()); key_element->SetAttribute("for", "edge"); graphml_element->LinkEndChild(key_element); } XMLElement * graph_element = doc.NewElement("graph"); graphml_element->LinkEndChild(graph_element); if (!directed) { graph_element->SetAttribute("edgedefault", "undirected"); } for (unsigned int i = 0; i < graph.getNodeCount(); i++) { XMLElement * node_element = doc.NewElement("node"); string node_id = "n" + to_string(i); node_element->SetAttribute("id", node_id.c_str()); for (auto & col : node_table.getColumns()) { XMLElement * data_element = doc.NewElement("data"); data_element->SetAttribute("key", col.first.c_str()); data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str())); node_element->LinkEndChild(data_element); } graph_element->LinkEndChild(node_element); } #if 0 for (unsigned int i = 0; i < graph.getEdgeCount(); i++) { XMLElement * edge_element = doc.NewElement("edge"); auto edge = graph.getEdgeAttributes(i); string node_id1 = "n" + to_string(edge.tail); string node_id2 = "n" + to_string(edge.head); // timestamp, sentiment edge_element->SetAttribute("source", node_id1.c_str()); edge_element->SetAttribute("target", node_id2.c_str()); for (auto & col : edge_table.getColumns()) { XMLElement * data_element = doc.NewElement("data"); data_element->SetAttribute("key", col.first.c_str()); data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str())); edge_element->LinkEndChild(data_element); } graph_element->LinkEndChild(edge_element); } #endif doc.LinkEndChild(graphml_element); doc.SaveFile(filename.c_str()); return true; } <commit_msg>remove namespace table, use NodeArray<commit_after>#include "GraphML.h" #include "DirectedGraph.h" #include "UndirectedGraph.h" #include <tinyxml2.h> #include <Table.h> #include <cassert> #include <map> #include <iostream> using namespace std; using namespace tinyxml2; GraphML::GraphML() : FileTypeHandler("GraphML", true) { addExtension("graphml"); } std::shared_ptr<Graph> GraphML::openGraph(const char * filename) { RenderMode mode = RENDERMODE_3D; XMLDocument doc; doc.LoadFile(filename); XMLElement * graphml_element = doc.FirstChildElement("graphml"); assert(graphml_element); XMLElement * graph_element = graphml_element->FirstChildElement("graph"); assert(graph_element); return createGraphFromElement(*graphml_element, *graph_element); } std::shared_ptr<Graph> GraphML::createGraphFromElement(XMLElement & graphml_element, XMLElement & graph_element) const { map<string, int> nodes_by_id; const char * edgedefault = graph_element.Attribute("edgedefault"); bool directed = true; if (edgedefault && strcmp(edgedefault, "undirected") == 0) { directed = false; } std::shared_ptr<Graph> graph; if (directed) { graph = std::make_shared<DirectedGraph>(); } else { graph = std::make_shared<UndirectedGraph>(); } graph->setNodeArray(std::make_shared<NodeArray>()); auto & node_table = graph->getNodeArray().getTable(); auto & edge_table = directed ? graph->getEdgeData() : graph->getFaceData(); auto & node_id_column = node_table.addTextColumn("id"); auto & edge_id_column = edge_table.addTextColumn("id"); XMLElement * key_element = graphml_element.FirstChildElement("key"); for ( ; key_element ; key_element = key_element->NextSiblingElement("key") ) { const char * key_type = key_element->Attribute("attr.type"); const char * key_id = key_element->Attribute("id"); const char * for_type = key_element->Attribute("for"); const char * name = key_element->Attribute("attr.name"); assert(key_type && key_id && for_type); std::shared_ptr<table::Column> column; if (strcmp(key_type, "string") == 0) { column = std::make_shared<table::ColumnText>(key_id ? key_id : ""); } else if (strcmp(key_type, "double") == 0 || strcmp(key_type, "float") == 0) { column = std::make_shared<table::ColumnDouble>(key_id ? key_id : ""); } else if (strcmp(key_type, "int") == 0) { column = std::make_shared<table::ColumnInt>(key_id ? key_id : ""); } else { assert(0); } if (strcmp(for_type, "node") == 0) { node_table.addColumn(column); } else if (strcmp(for_type, "edge") == 0) { edge_table.addColumn(column); } else { assert(0); } } bool is_complex = false; XMLElement * node_element = graph_element.FirstChildElement("node"); for ( ; node_element ; node_element = node_element->NextSiblingElement("node") ) { const char * node_id_text = node_element->Attribute("id"); assert(node_id_text); int node_id = graph->getNodeArray().addNode(); node_id_column.setValue(node_id, node_id_text); nodes_by_id[node_id_text] = node_id + 1; XMLElement * data_element = node_element->FirstChildElement("data"); for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) { const char * key = data_element->Attribute("key"); assert(key); const char * text = data_element->GetText(); if (text) { node_table[key].setValue(node_id, text); } } graph->getNodeArray().updateNodeAppearanceSlow(node_id); XMLElement * nested_graph_element = node_element->FirstChildElement("graph"); if (nested_graph_element) { auto nested_graph = createGraphFromElement(graphml_element, *nested_graph_element); assert(nested_graph.get()); is_complex = true; graph->getNodeArray().setNestedGraph(node_id, nested_graph); } } graph->randomizeGeometry(); graph->setComplexGraph(is_complex); graph->setHasSubGraphs(is_complex); XMLElement * edge_element = graph_element.FirstChildElement("edge"); for ( ; edge_element ; edge_element = edge_element->NextSiblingElement("edge") ) { const char * edge_id_text = edge_element->Attribute("id"); const char * source = edge_element->Attribute("source"); const char * target = edge_element->Attribute("target"); assert(source && target); if (strcmp(source, target) == 0) { cerr << "GraphML: skipping self link for " << source << endl; continue; } int source_node = nodes_by_id[source]; int target_node = nodes_by_id[target]; if (source_node && target_node) { int edge_id; if (directed) { edge_id = graph->addEdge(source_node - 1, target_node - 1); if (edge_id_text && strlen(edge_id_text) != 0) { edge_id_column.setValue(edge_id, edge_id_text); } } else { edge_id = graph->addFace(-1); graph->addEdge(source_node - 1, target_node - 1, edge_id); graph->addEdge(target_node - 1, source_node - 1, edge_id); } XMLElement * data_element = edge_element->FirstChildElement("data"); for ( ; data_element ; data_element = data_element->NextSiblingElement("data") ) { const char * key = data_element->Attribute("key"); assert(key); const char * text = data_element->GetText(); if (text) { edge_table[key].setValue(edge_id, text); } } } else { if (!source_node) { // cerr << "cannot find node " << source << endl; } if (!target_node) { // cerr << "cannot find node " << target << endl; } } } return graph; } bool GraphML::saveGraph(const Graph & graph, const std::string & filename) { XMLDocument doc; doc.LinkEndChild(doc.NewDeclaration()); XMLElement * graphml_element = doc.NewElement("graphml"); graphml_element->SetAttribute("xmlns", "http://graphml.graphdrawing.org/xmlns"); bool directed = graph.isDirected(); auto & node_table = graph.getNodeArray().getTable(); auto & edge_table = directed ? graph.getEdgeData() : graph.getFaceData(); for (auto & col : node_table.getColumns()) { XMLElement * key_element = doc.NewElement("key"); key_element->SetAttribute("attr.name", col.first.c_str()); key_element->SetAttribute("id", col.first.c_str()); key_element->SetAttribute("attr.type", col.second->getTypeText()); key_element->SetAttribute("for", "node"); graphml_element->LinkEndChild(key_element); } for (auto & col : edge_table.getColumns()) { XMLElement * key_element = doc.NewElement("key"); key_element->SetAttribute("attr.name", col.first.c_str()); key_element->SetAttribute("id", col.first.c_str()); key_element->SetAttribute("attr.type", col.second->getTypeText()); key_element->SetAttribute("for", "edge"); graphml_element->LinkEndChild(key_element); } XMLElement * graph_element = doc.NewElement("graph"); graphml_element->LinkEndChild(graph_element); if (!directed) { graph_element->SetAttribute("edgedefault", "undirected"); } for (unsigned int i = 0; i < graph.getNodeCount(); i++) { XMLElement * node_element = doc.NewElement("node"); string node_id = "n" + to_string(i); node_element->SetAttribute("id", node_id.c_str()); for (auto & col : node_table.getColumns()) { XMLElement * data_element = doc.NewElement("data"); data_element->SetAttribute("key", col.first.c_str()); data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str())); node_element->LinkEndChild(data_element); } graph_element->LinkEndChild(node_element); } #if 0 for (unsigned int i = 0; i < graph.getEdgeCount(); i++) { XMLElement * edge_element = doc.NewElement("edge"); auto edge = graph.getEdgeAttributes(i); string node_id1 = "n" + to_string(edge.tail); string node_id2 = "n" + to_string(edge.head); // timestamp, sentiment edge_element->SetAttribute("source", node_id1.c_str()); edge_element->SetAttribute("target", node_id2.c_str()); for (auto & col : edge_table.getColumns()) { XMLElement * data_element = doc.NewElement("data"); data_element->SetAttribute("key", col.first.c_str()); data_element->LinkEndChild(doc.NewText(col.second->getText(i).c_str())); edge_element->LinkEndChild(data_element); } graph_element->LinkEndChild(edge_element); } #endif doc.LinkEndChild(graphml_element); doc.SaveFile(filename.c_str()); return true; } <|endoftext|>
<commit_before>#include "webcam.hpp" using namespace cv; using namespace std; Mat ellipticKernel(int width, int height = -1) { if (height==-1) { return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2)); } else { return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2)); } } void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) { int width, height; width = inout.size().width; height = inout.size().height; Mat downsample; resize(inout, downsample, Size(smallsize,smallsize)); Mat kernel = ellipticKernel(factor); if (diler) { erode(downsample, downsample, kernel); } else { dilate(downsample, downsample, kernel); } if (eq) { equalizeHist(downsample, downsample); } resize(downsample, inout, Size(width, height)); } int main (int argc, char** argv) { int tracker1, tracker2, tracker3; namedWindow("s",1); createTrackbar("1","s",&tracker1,100); createTrackbar("2","s",&tracker2,100); createTrackbar("3","s",&tracker3,100); CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness for (int i = 0; i < 30; i++) { // capture some frames so exposure correction takes place cvQueryFrame(capture); } Mat background = cvQueryFrame(capture); background = background.clone(); blur(background, background, Size(50,50)); Mat image; Mat channel[3]; while (keepGoing) { image = cvQueryFrame(capture); // preprocess by rotating according to OVR roll // imshow("webcam", image); // let's make multiple masks where 0=not mouth, 1=uncertain // then multiply them together and multiply that with image // and run haar classifier on image Mat gray, blurred_img; cvtColor(image, gray, CV_RGB2GRAY); blur(image, blurred_img, Size(50,50)); // this mask filters out areas with too many edges // removed for now; it didn't generalize well /* Mat canny; Canny(gray, canny, 50, 50, 3); blur(canny, canny, Size(width/20,height/20)); bitwise_not(canny, canny); threshold(canny, canny, 200, 1, THRESH_BINARY); blur(canny*255, canny, Size(width/10, height/10)); threshold(canny, canny, 220, 1, THRESH_BINARY); imshow("canny mask", gray.mul(canny)); */ // this mask filters out areas which have not changed much // background needs to be updated when person is not in frame // use OVR SDK to do this later Mat flow; absdiff(blurred_img, background, flow); cvtColor(flow, flow, CV_RGB2GRAY); morphFast(flow); threshold(flow, flow, 60, 1, THRESH_BINARY); imshow("flow mask", gray.mul(flow)); // this mask gets anything kind of dark (DK2) and dilates Mat kindofdark; equalizeHist(gray, kindofdark); threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV); morphFast(kindofdark, 100, 17, 0); imshow("dark mask", gray.mul(kindofdark)); Mat mask = flow.mul(kindofdark); // close the mask Mat smallMask; resize(mask, smallMask, Size(150,150)); Mat erodeKernel = ellipticKernel(51); erode(smallMask, smallMask, erodeKernel); /* int t2 = tracker2+1-(tracker2%2); if (t2>50) t2=51; if (t2<3) t2=3; Mat dilateKernel = ellipticKernel(t2); //31 dilate(smallMask, smallMask, dilateKernel); */ resize(smallMask, smallMask, Size(width, height)); bitwise_and(smallMask,mask,mask); imshow("morph mask", gray.mul(mask)); // update background with new morph mask // average what we know is background with prior background // erode it first since we really want to be sure it's bg erode(mask, mask, erodeKernel); Mat mask_; subtract(1,mask,mask_); Mat mask3, mask3_; channel[0] = mask; channel[1] = mask; channel[2] = mask; merge(channel, 3, mask3); channel[0] = mask_; channel[1] = mask_; channel[2] = mask_; merge(channel, 3, mask3_); background = background.mul(mask3) + (background.mul(mask3_) + blurred_img.mul(mask3_))/2; imshow("background", background); // Moments lol = moments(mask, 1); // circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); // imshow("leimage", image); CascadeClassifier mouth_cascade; mouth_cascade.load("Mouth.xml"); vector<Rect> mouths; Mat classifyThis = gray; // bilateralFilter(gray, classifyThis, 15, 10, 1); equalizeHist(classifyThis, classifyThis); classifyThis = classifyThis.mul(mask); mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 2, CV_HAAR_SCALE_IMAGE); for (size_t i=0; i<mouths.size(); i++) { Point center( mouths[i].x + mouths[i].width*0.5, mouths[i].y + mouths[i].height*0.5 ); ellipse( image, center, Size( mouths[i].width*0.5, mouths[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 ); } imshow("MOUTH", image); keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <commit_msg>hacking<commit_after>#include "webcam.hpp" using namespace cv; using namespace std; Mat ellipticKernel(int width, int height = -1) { if (height==-1) { return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2)); } else { return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2)); } } void morphFast(Mat inout, int smallsize = 100, int factor = 25, int eq = 1, int diler = 0) { int width, height; width = inout.size().width; height = inout.size().height; Mat downsample; resize(inout, downsample, Size(smallsize,smallsize)); Mat kernel = ellipticKernel(factor); if (diler) { erode(downsample, downsample, kernel); } else { dilate(downsample, downsample, kernel); } if (eq) { equalizeHist(downsample, downsample); } resize(downsample, inout, Size(width, height)); } int main (int argc, char** argv) { int tracker1, tracker2, tracker3; namedWindow("s",1); createTrackbar("1","s",&tracker1,100); createTrackbar("2","s",&tracker2,100); createTrackbar("3","s",&tracker3,100); CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness for (int i = 0; i < 30; i++) { // capture some frames so exposure correction takes place cvQueryFrame(capture); } Mat background = cvQueryFrame(capture); background = background.clone(); blur(background, background, Size(50,50)); Mat image; Mat channel[3]; while (keepGoing) { image = cvQueryFrame(capture); // preprocess by rotating according to OVR roll // imshow("webcam", image); // let's make multiple masks where 0=not mouth, 1=uncertain // then multiply them together and multiply that with image // and run haar classifier on image Mat gray, blurred_img; cvtColor(image, gray, CV_RGB2GRAY); blur(image, blurred_img, Size(50,50)); // this mask filters out areas with too many edges // removed for now; it didn't generalize well /* Mat canny; Canny(gray, canny, 50, 50, 3); blur(canny, canny, Size(width/20,height/20)); bitwise_not(canny, canny); threshold(canny, canny, 200, 1, THRESH_BINARY); blur(canny*255, canny, Size(width/10, height/10)); threshold(canny, canny, 220, 1, THRESH_BINARY); imshow("canny mask", gray.mul(canny)); */ // this mask filters out areas which have not changed much // background needs to be updated when person is not in frame // use OVR SDK to do this later Mat flow; absdiff(blurred_img, background, flow); cvtColor(flow, flow, CV_RGB2GRAY); morphFast(flow); threshold(flow, flow, 60, 1, THRESH_BINARY); imshow("flow mask", gray.mul(flow)); // this mask gets anything kind of dark (DK2) and dilates Mat kindofdark; equalizeHist(gray, kindofdark); threshold(kindofdark, kindofdark, 100, 1, THRESH_BINARY_INV); morphFast(kindofdark, 100, 17, 0); imshow("dark mask", gray.mul(kindofdark)); Mat mask = flow.mul(kindofdark); // close the mask Mat smallMask; resize(mask, smallMask, Size(150,150)); Mat erodeKernel = ellipticKernel(51); erode(smallMask, smallMask, erodeKernel); /* int t2 = tracker2+1-(tracker2%2); if (t2>50) t2=51; if (t2<3) t2=3; Mat dilateKernel = ellipticKernel(t2); //31 dilate(smallMask, smallMask, dilateKernel); */ resize(smallMask, smallMask, Size(width, height)); bitwise_and(smallMask,mask,mask); imshow("morph mask", gray.mul(mask)); // update background with new morph mask // average what we know is background with prior background // erode it first since we really want to be sure it's bg erode(mask, mask, erodeKernel); Mat mask_; subtract(1,mask,mask_); Mat mask3, mask3_; channel[0] = mask; channel[1] = mask; channel[2] = mask; merge(channel, 3, mask3); channel[0] = mask_; channel[1] = mask_; channel[2] = mask_; merge(channel, 3, mask3_); background = background.mul(mask3) + (background.mul(mask3_) + blurred_img.mul(mask3_))/2; imshow("background", background); // Moments lol = moments(mask, 1); // circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); // imshow("leimage", image); CascadeClassifier mouth_cascade; mouth_cascade.load("Mouth.xml"); vector<Rect> mouths; Mat classifyThis; blur(gray, classifyThis, Size(10,10)); // bilateralFilter(gray, classifyThis, 15, 10, 1); equalizeHist(classifyThis, classifyThis); classifyThis = classifyThis.mul(mask); mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 5, CV_HAAR_SCALE_IMAGE); for (size_t i=0; i<mouths.size(); i++) { Point center( mouths[i].x + mouths[i].width*0.5, mouths[i].y + mouths[i].height*0.5 ); ellipse( image, center, Size( mouths[i].width*0.5, mouths[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 ); } imshow("MOUTH", image); keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: MABTables.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: oj $ $Date: 2001-10-12 11:53:28 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_MAB_TABLES_HXX_ #define _CONNECTIVITY_MAB_TABLES_HXX_ #ifndef _CONNECTIVITY_FILE_TABLES_HXX_ #include "file/FTables.hxx" #endif namespace connectivity { namespace mozaddressbook { typedef file::OTables OMozabTables_BASE; class OMozabTables : public OMozabTables_BASE { protected: virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNamed > createObject(const ::rtl::OUString& _rName); public: OMozabTables(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rMetaData,::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex, const ::std::vector< ::rtl::OUString> &_rVector) : OMozabTables_BASE(_rMetaData,_rParent,_rMutex,_rVector) {} }; } } #endif // _CONNECTIVITY_MAB_TABLES_HXX_ <commit_msg>INTEGRATION: CWS dba24 (1.4.262); FILE MERGED 2005/02/09 08:07:57 oj 1.4.262.1: #i26950# remove the need for XNamed<commit_after>/************************************************************************* * * $RCSfile: MABTables.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2005-03-10 15:40:49 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONNECTIVITY_MAB_TABLES_HXX_ #define _CONNECTIVITY_MAB_TABLES_HXX_ #ifndef _CONNECTIVITY_FILE_TABLES_HXX_ #include "file/FTables.hxx" #endif namespace connectivity { namespace mozaddressbook { typedef file::OTables OMozabTables_BASE; class OMozabTables : public OMozabTables_BASE { protected: virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName); public: OMozabTables(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rMetaData,::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex, const ::std::vector< ::rtl::OUString> &_rVector) : OMozabTables_BASE(_rMetaData,_rParent,_rMutex,_rVector) {} }; } } #endif // _CONNECTIVITY_MAB_TABLES_HXX_ <|endoftext|>
<commit_before>/* Copyright (c) 2015, Burak Sarac, burak@linux.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "IOUtils.h" #include <iostream> #include <cmath> #include <math.h> #include <string> #include <sstream> #include <algorithm> #include <iterator> #include <sys/time.h> #include <sys/stat.h> struct timeval timeValue; IOUtils::IOUtils() { // TODO Auto-generated constructor stub } int IOUtils::fileExist(string name) { struct stat buffer; return (stat(name.c_str(), &buffer) == 0); } double* IOUtils::getFeaturedList(double* list, int columnSize, int rowSize) { double* sums = (double*) malloc(sizeof(double) * rowSize); double* means = (double*) malloc(sizeof(double) * rowSize); double* stds = (double*) malloc(sizeof(double) * rowSize); double* featuredList = (double*) malloc(sizeof(double) * rowSize * columnSize); for (int i = 0; i < rowSize; ++i) { double sum = 0.0; double correction = 0.0; for (int j = 0; j < columnSize; ++j) { double y = list[(i * columnSize) + j] - correction; double t = sum + y; correction = (t - sum) - y; sum = t; } sums[i] = sum; means[i] = sums[i] / columnSize; } for (int i = 0; i < rowSize; ++i) { double sum = 0.0; double correction = 0.0; for (int j = 0; j < columnSize; ++j) { double value = std::pow((list[(i * columnSize) + j] - means[i]), 2); double y = value - correction; double t = sum + y; correction = (t - sum) - y; sum = t; } stds[i] = sum; } for (int i = 0; i < rowSize; ++i) { stds[i] = sqrt(stds[i] / columnSize); } for (int i = 0; i < rowSize; ++i) { for (int j = 0; j < columnSize; ++j) { featuredList[(i * columnSize) + j] = (list[(i * columnSize) + j] - means[j]) / stds[j]; } } free(sums); free(means); free(stds); free(list); return featuredList; } void IOUtils::saveThetas(double* thetas, lint size) { gettimeofday(&timeValue, NULL); string fileName = "thetas_"; std::stringstream sstm; sstm << fileName << timeValue.tv_sec << ".dat"; ofstream f(sstm.str().c_str()); copy(thetas, thetas + size, ostream_iterator<double>(f, "\n")); printf("Thetas (%s) has been saved into project folder.", sstm.str().c_str()); } double* IOUtils::getArray(string path, lint rows, lint columns) { ifstream inputStream; lint currentRow = 0; std::string s; inputStream.open(path.c_str()); if(!inputStream.is_open()){ throw 3; } lint size = columns * rows; lint mListSize = sizeof(double) * size; double* list = (double *) malloc(mListSize); while (!inputStream.eof()) { if (currentRow < size) { inputStream >> s; try { list[currentRow++] = strtod(s.c_str(), NULL); } catch (...) { throw 2; } } else { break; } } inputStream.close(); if (currentRow < (size - 1)) { throw 1; } return list; } <commit_msg>change of scaling direction results better on training<commit_after>/* Copyright (c) 2015, Burak Sarac, burak@linux.com All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "IOUtils.h" #include <iostream> #include <cmath> #include <math.h> #include <string> #include <sstream> #include <algorithm> #include <iterator> #include <sys/time.h> #include <sys/stat.h> struct timeval timeValue; IOUtils::IOUtils() { // TODO Auto-generated constructor stub } int IOUtils::fileExist(string name) { struct stat buffer; return (stat(name.c_str(), &buffer) == 0); } double* IOUtils::getFeaturedList(double* list, int columnSize, int rowSize) { double* sums = (double*) malloc(sizeof(double) * columnSize); double* means = (double*) malloc(sizeof(double) * columnSize); double* stds = (double*) malloc(sizeof(double) * columnSize); double* featuredList = (double*) malloc( sizeof(double) * rowSize * columnSize); for (int j = 0; j < columnSize; ++j) { double sum = 0.0; double correction = 0.0; for (int i = 0; i < rowSize; ++i) { double y = list[(i * columnSize) + j] - correction; double t = sum + y; correction = (t - sum) - y; sum = t; } sums[j] = sum; means[j] = sums[j] / rowSize; } for (int j = 0; j < columnSize; ++j) { double sum = 0.0; double correction = 0.0; for (int i = 0; i < rowSize; ++i) { double value = std::pow((list[(i * columnSize) + j] - means[j]), 2); double y = value - correction; double t = sum + y; correction = (t - sum) - y; sum = t; } stds[j] = sum; } for (int i = 0; i < columnSize; ++i) { stds[i] = sqrt(stds[i] / rowSize); } for (int j = 0; j < columnSize; ++j) { for (int i = 0; i < rowSize; ++i) { featuredList[(i * columnSize) + j] = (list[(i * columnSize) + j] - means[j]) / stds[j]; } } free(sums); free(means); free(stds); return featuredList; } void IOUtils::saveThetas(double* thetas, lint size) { gettimeofday(&timeValue, NULL); string fileName = "thetas_"; std::stringstream sstm; sstm << fileName << timeValue.tv_sec << ".dat"; ofstream f(sstm.str().c_str()); copy(thetas, thetas + size, ostream_iterator<double>(f, "\n")); printf("Thetas (%s) has been saved into project folder.", sstm.str().c_str()); } double* IOUtils::getArray(string path, lint rows, lint columns) { ifstream inputStream; lint currentRow = 0; std::string s; inputStream.open(path.c_str()); if (!inputStream.is_open()) { throw 3; } lint size = columns * rows; lint mListSize = sizeof(double) * size; double* list = (double *) malloc(mListSize); while (!inputStream.eof()) { if (currentRow < size) { inputStream >> s; try { list[currentRow++] = strtod(s.c_str(), NULL); } catch (...) { throw 2; } } else { break; } } inputStream.close(); if (currentRow < (size - 1)) { throw 1; } return list; } <|endoftext|>
<commit_before>#include "Job.h" namespace cefpdf { namespace job { Job::Job() : m_outputPath(), m_pageSize(), m_pageOrientation(PageOrientation::PORTRAIT), m_pageMargin(), m_backgrounds(false), m_status(Job::Status::PENDING), m_callback(), m_scale(100) { SetPageSize(cefpdf::constants::pageSize); SetPageMargin("default"); } void Job::SetPageSize(const CefString& pageSize) { m_pageSize = getPageSize(pageSize); } void Job::SetLandscape(bool flag) { m_pageOrientation = (flag ? PageOrientation::LANDSCAPE : PageOrientation::PORTRAIT); } void Job::SetPageMargin(const CefString& pageMargin) { m_pageMargin = getPageMargin(pageMargin); } void Job::SetBackgrounds(bool flag) { m_backgrounds = flag; } void Job::SetScale(int scale) { DLOG(INFO) << "Scale factor: " << m_scale; m_scale = scale; } CefPdfPrintSettings Job::GetCefPdfPrintSettings() const { CefPdfPrintSettings pdfSettings; pdfSettings.scale_factor = m_scale; pdfSettings.backgrounds_enabled = m_backgrounds; pdfSettings.landscape = (m_pageOrientation == PageOrientation::LANDSCAPE); pdfSettings.page_width = m_pageSize.width * 1000; pdfSettings.page_height = m_pageSize.height * 1000; pdfSettings.margin_type = m_pageMargin.type; pdfSettings.margin_top = m_pageMargin.top; pdfSettings.margin_right = m_pageMargin.right; pdfSettings.margin_bottom = m_pageMargin.bottom; pdfSettings.margin_left = m_pageMargin.left; return pdfSettings; } } // namespace job } // namespace cefpdf <commit_msg>Fix typo in DLOG message for --scale<commit_after>#include "Job.h" namespace cefpdf { namespace job { Job::Job() : m_outputPath(), m_pageSize(), m_pageOrientation(PageOrientation::PORTRAIT), m_pageMargin(), m_backgrounds(false), m_status(Job::Status::PENDING), m_callback(), m_scale(100) { SetPageSize(cefpdf::constants::pageSize); SetPageMargin("default"); } void Job::SetPageSize(const CefString& pageSize) { m_pageSize = getPageSize(pageSize); } void Job::SetLandscape(bool flag) { m_pageOrientation = (flag ? PageOrientation::LANDSCAPE : PageOrientation::PORTRAIT); } void Job::SetPageMargin(const CefString& pageMargin) { m_pageMargin = getPageMargin(pageMargin); } void Job::SetBackgrounds(bool flag) { m_backgrounds = flag; } void Job::SetScale(int scale) { DLOG(INFO) << "Scale factor: " << scale; m_scale = scale; } CefPdfPrintSettings Job::GetCefPdfPrintSettings() const { CefPdfPrintSettings pdfSettings; pdfSettings.scale_factor = m_scale; pdfSettings.backgrounds_enabled = m_backgrounds; pdfSettings.landscape = (m_pageOrientation == PageOrientation::LANDSCAPE); pdfSettings.page_width = m_pageSize.width * 1000; pdfSettings.page_height = m_pageSize.height * 1000; pdfSettings.margin_type = m_pageMargin.type; pdfSettings.margin_top = m_pageMargin.top; pdfSettings.margin_right = m_pageMargin.right; pdfSettings.margin_bottom = m_pageMargin.bottom; pdfSettings.margin_left = m_pageMargin.left; return pdfSettings; } } // namespace job } // namespace cefpdf <|endoftext|>
<commit_before>#include "statistics.hpp" #include "indexer/classificator.hpp" #include "indexer/data_factory.hpp" #include "indexer/feature_impl.hpp" #include "indexer/feature_processor.hpp" #include "geometry/triangle2d.hpp" #include "base/logging.hpp" #include "base/string_utils.hpp" #include "std/iomanip.hpp" #include "std/iostream.hpp" using namespace feature; namespace stats { void FileContainerStatistic(string const & fPath) { try { FilesContainerR cont(fPath); cont.ForEachTag([&cont] (FilesContainerR::Tag const & tag) { cout << setw(10) << tag << " : " << cont.GetReader(tag).Size() << endl; }); } catch (Reader::Exception const & ex) { LOG(LWARNING, ("Error reading file:", fPath, ex.Msg())); } } double arrSquares[] = { 0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 360*360 }; size_t GetSquareIndex(double s) { auto end = arrSquares + ARRAY_SIZE(arrSquares); auto i = lower_bound(arrSquares, end, s); ASSERT(i != end, ()); return distance(arrSquares, i); } class AccumulateStatistic { MapInfo & m_info; public: AccumulateStatistic(MapInfo & info) : m_info(info) {} void operator() (FeatureType const & f, uint32_t) { f.ParseBeforeStatistic(); FeatureType::inner_geom_stat_t const innerStats = f.GetInnerStatistic(); m_info.m_inner[0].Add(innerStats.m_points); m_info.m_inner[1].Add(innerStats.m_strips); m_info.m_inner[2].Add(innerStats.m_size); // get geometry size for the best geometry FeatureType::geom_stat_t const geom = f.GetGeometrySize(FeatureType::BEST_GEOMETRY); FeatureType::geom_stat_t const trg = f.GetTrianglesSize(FeatureType::BEST_GEOMETRY); m_info.AddToSet(CountType(geom.m_count), geom.m_size, m_info.m_byPointsCount); m_info.AddToSet(CountType(trg.m_count / 3), trg.m_size, m_info.m_byTrgCount); uint32_t const allSize = innerStats.m_size + geom.m_size + trg.m_size; m_info.AddToSet(f.GetFeatureType(), allSize, m_info.m_byGeomType); f.ForEachType([this, allSize](uint32_t type) { m_info.AddToSet(ClassifType(type), allSize, m_info.m_byClassifType); }); double square = 0.0; f.ForEachTriangle([&square](m2::PointD const & p1, m2::PointD const & p2, m2::PointD const & p3) { square += m2::GetTriangleArea(p1, p2, p3); }, FeatureType::BEST_GEOMETRY); m_info.AddToSet(AreaType(GetSquareIndex(square)), trg.m_size, m_info.m_byAreaSize); } }; void CalcStatistic(string const & fPath, MapInfo & info) { AccumulateStatistic doProcess(info); feature::ForEachFromDat(fPath, doProcess); } void PrintInfo(string const & prefix, GeneralInfo const & info) { cout << prefix << ": size = " << info.m_size << "; count = " << info.m_count << endl; } string GetKey(EGeomType type) { switch (type) { case GEOM_LINE: return "Line"; case GEOM_AREA: return "Area"; default: return "Point"; } } string GetKey(CountType t) { return strings::to_string(t.m_val); } string GetKey(ClassifType t) { return classif().GetFullObjectName(t.m_val); } string GetKey(AreaType t) { return strings::to_string(arrSquares[t.m_val]); } template <class TSortCr, class TSet> void PrintTop(char const * prefix, TSet const & theSet) { cout << prefix << endl; vector<pair<typename TSet::key_type, typename TSet::mapped_type>> vec(theSet.begin(), theSet.end()); sort(vec.begin(), vec.end(), TSortCr()); size_t const count = min(static_cast<size_t>(10), vec.size()); for (size_t i = 0; i < count; ++i) { cout << i << ". "; PrintInfo(GetKey(vec[i].first), vec[i].second); } } struct greater_size { template <class TInfo> bool operator() (TInfo const & r1, TInfo const & r2) const { return r1.second.m_size > r2.second.m_size; } }; struct greater_count { template <class TInfo> bool operator() (TInfo const & r1, TInfo const & r2) const { return r1.second.m_count > r2.second.m_count; } }; void PrintStatistic(MapInfo & info) { PrintInfo("DAT header", info.m_inner[2]); PrintInfo("Points header", info.m_inner[0]); PrintInfo("Strips header", info.m_inner[1]); PrintTop<greater_size>("Top SIZE by Geometry Type", info.m_byGeomType); PrintTop<greater_size>("Top SIZE by Classificator Type", info.m_byClassifType); PrintTop<greater_size>("Top SIZE by Points Count", info.m_byPointsCount); PrintTop<greater_size>("Top SIZE by Triangles Count", info.m_byTrgCount); PrintTop<greater_size>("Top SIZE by Square", info.m_byAreaSize); } } <commit_msg>Review fixes.<commit_after>#include "statistics.hpp" #include "indexer/classificator.hpp" #include "indexer/data_factory.hpp" #include "indexer/feature_impl.hpp" #include "indexer/feature_processor.hpp" #include "geometry/triangle2d.hpp" #include "base/logging.hpp" #include "base/string_utils.hpp" #include "std/iomanip.hpp" #include "std/iostream.hpp" using namespace feature; namespace stats { void FileContainerStatistic(string const & fPath) { try { FilesContainerR cont(fPath); cont.ForEachTag([&cont] (FilesContainerR::Tag const & tag) { cout << setw(10) << tag << " : " << cont.GetReader(tag).Size() << endl; }); } catch (Reader::Exception const & ex) { LOG(LWARNING, ("Error reading file:", fPath, ex.Msg())); } } double arrAreas[] = { 0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 360*360 }; size_t GetAreaIndex(double s) { auto end = arrAreas + ARRAY_SIZE(arrAreas); auto i = lower_bound(arrAreas, end, s); ASSERT(i != end, ()); return distance(arrAreas, i); } class AccumulateStatistic { MapInfo & m_info; public: AccumulateStatistic(MapInfo & info) : m_info(info) {} void operator() (FeatureType const & f, uint32_t) { f.ParseBeforeStatistic(); FeatureType::inner_geom_stat_t const innerStats = f.GetInnerStatistic(); m_info.m_inner[0].Add(innerStats.m_points); m_info.m_inner[1].Add(innerStats.m_strips); m_info.m_inner[2].Add(innerStats.m_size); // get geometry size for the best geometry FeatureType::geom_stat_t const geom = f.GetGeometrySize(FeatureType::BEST_GEOMETRY); FeatureType::geom_stat_t const trg = f.GetTrianglesSize(FeatureType::BEST_GEOMETRY); m_info.AddToSet(CountType(geom.m_count), geom.m_size, m_info.m_byPointsCount); m_info.AddToSet(CountType(trg.m_count / 3), trg.m_size, m_info.m_byTrgCount); uint32_t const allSize = innerStats.m_size + geom.m_size + trg.m_size; m_info.AddToSet(f.GetFeatureType(), allSize, m_info.m_byGeomType); f.ForEachType([this, allSize](uint32_t type) { m_info.AddToSet(ClassifType(type), allSize, m_info.m_byClassifType); }); double area = 0.0; f.ForEachTriangle([&area](m2::PointD const & p1, m2::PointD const & p2, m2::PointD const & p3) { area += m2::GetTriangleArea(p1, p2, p3); }, FeatureType::BEST_GEOMETRY); m_info.AddToSet(AreaType(GetAreaIndex(area)), trg.m_size, m_info.m_byAreaSize); } }; void CalcStatistic(string const & fPath, MapInfo & info) { AccumulateStatistic doProcess(info); feature::ForEachFromDat(fPath, doProcess); } void PrintInfo(string const & prefix, GeneralInfo const & info) { cout << prefix << ": size = " << info.m_size << "; count = " << info.m_count << endl; } string GetKey(EGeomType type) { switch (type) { case GEOM_LINE: return "Line"; case GEOM_AREA: return "Area"; default: return "Point"; } } string GetKey(CountType t) { return strings::to_string(t.m_val); } string GetKey(ClassifType t) { return classif().GetFullObjectName(t.m_val); } string GetKey(AreaType t) { return strings::to_string(arrAreas[t.m_val]); } template <class TSortCr, class TSet> void PrintTop(char const * prefix, TSet const & theSet) { cout << prefix << endl; vector<pair<typename TSet::key_type, typename TSet::mapped_type>> vec(theSet.begin(), theSet.end()); sort(vec.begin(), vec.end(), TSortCr()); size_t const count = min(static_cast<size_t>(10), vec.size()); for (size_t i = 0; i < count; ++i) { cout << i << ". "; PrintInfo(GetKey(vec[i].first), vec[i].second); } } struct greater_size { template <class TInfo> bool operator() (TInfo const & r1, TInfo const & r2) const { return r1.second.m_size > r2.second.m_size; } }; struct greater_count { template <class TInfo> bool operator() (TInfo const & r1, TInfo const & r2) const { return r1.second.m_count > r2.second.m_count; } }; void PrintStatistic(MapInfo & info) { PrintInfo("DAT header", info.m_inner[2]); PrintInfo("Points header", info.m_inner[0]); PrintInfo("Strips header", info.m_inner[1]); PrintTop<greater_size>("Top SIZE by Geometry Type", info.m_byGeomType); PrintTop<greater_size>("Top SIZE by Classificator Type", info.m_byClassifType); PrintTop<greater_size>("Top SIZE by Points Count", info.m_byPointsCount); PrintTop<greater_size>("Top SIZE by Triangles Count", info.m_byTrgCount); PrintTop<greater_size>("Top SIZE by Area", info.m_byAreaSize); } } <|endoftext|>
<commit_before>#include <chrono> #include <fstream> #include <iostream> #include "image.h" using namespace AhoViewer::Booru; #include "browser.h" #include "settings.h" Image::Image(const std::string &path, const std::string &url, const std::string &thumbPath, const std::string &thumbUrl, const std::string &postUrl, std::set<std::string> tags, const Page &page) : AhoViewer::Image(path), m_Url(url), m_ThumbnailUrl(thumbUrl), m_PostUrl(postUrl), m_Tags(tags), m_Page(page), m_Curler(m_Url), m_ThumbnailCurler(new Curler(m_ThumbnailUrl)), m_PixbufError(false) { m_SignalThumbnailLoaded.connect([ this ] { m_ThumbnailCurler.reset(nullptr); }); m_ThumbnailPath = thumbPath; if (!m_isWebM) m_Curler.signal_write().connect(sigc::mem_fun(*this, &Image::on_write)); m_Curler.set_referer(m_PostUrl); m_Curler.signal_progress().connect(sigc::mem_fun(*this, &Image::on_progress)); m_Curler.signal_finished().connect(sigc::mem_fun(*this, &Image::on_finished)); } Image::~Image() { cancel_download(); } bool Image::is_loading() const { return (m_isWebM && !Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS)) || m_Curler.is_active(); } std::string Image::get_filename() const { return m_Page.get_site()->get_name() + "/" + Glib::path_get_basename(m_Path); } const Glib::RefPtr<Gdk::Pixbuf>& Image::get_thumbnail() { if (!m_ThumbnailPixbuf) { if (m_ThumbnailCurler->perform()) { m_ThumbnailCurler->save_file(m_ThumbnailPath); m_ThumbnailLock.writer_lock(); try { m_ThumbnailPixbuf = create_pixbuf_at_size(m_ThumbnailPath, 128, 128); } catch (const Gdk::PixbufError &ex) { std::cerr << ex.what() << std::endl; m_ThumbnailPixbuf = get_missing_pixbuf(); } m_ThumbnailLock.writer_unlock(); } else { std::cerr << "Error while downloading thumbnail " << m_ThumbnailUrl << " " << std::endl << " " << m_ThumbnailCurler->get_error() << std::endl; m_ThumbnailLock.writer_lock(); m_ThumbnailPixbuf = get_missing_pixbuf(); m_ThumbnailLock.writer_unlock(); } m_SignalThumbnailLoaded(); } return m_ThumbnailPixbuf; } void Image::load_pixbuf() { if (!m_Pixbuf && !m_PixbufError) { if (Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS)) { AhoViewer::Image::load_pixbuf(); } else if (!start_download() && !m_isWebM && m_Loader && m_Loader->get_animation()) { m_Pixbuf = m_Loader->get_animation(); } } } void Image::reset_pixbuf() { if (m_Curler.is_active()) cancel_download(); AhoViewer::Image::reset_pixbuf(); } void Image::save(const std::string &path) { if (!Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS)) { start_download(); std::unique_lock<std::mutex> lk(m_DownloadMutex); m_DownloadCond.wait(lk, [ this ] { return m_Curler.is_cancelled() || Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS); }); } if (m_Curler.is_cancelled()) return; Glib::RefPtr<Gio::File> src = Gio::File::create_for_path(m_Path), dst = Gio::File::create_for_path(path); src->copy(dst, Gio::FILE_COPY_OVERWRITE); if (Settings.get_bool("SaveImageTags")) { std::ofstream ofs(path + ".txt"); if (ofs) std::copy(m_Tags.begin(), m_Tags.end(), std::ostream_iterator<std::string>(ofs, "\n")); } } void Image::cancel_download() { m_Curler.cancel(); std::lock_guard<std::mutex> lock(m_DownloadMutex); if (m_Loader) { try { m_Loader->close(); } catch (...) { } m_Loader.reset(); } m_Curler.clear(); m_DownloadCond.notify_one(); } /** * Returns true if the download was started **/ bool Image::start_download() { if (!m_Curler.is_active()) { m_Page.get_image_fetcher().add_handle(&m_Curler); if (!m_isWebM) { m_Loader = Gdk::PixbufLoader::create(); m_Loader->signal_area_prepared().connect(sigc::mem_fun(*this, &Image::on_area_prepared)); m_Loader->signal_area_updated().connect(sigc::mem_fun(*this, &Image::on_area_updated)); } return true; } return false; } void Image::on_write(const unsigned char *d, size_t l) { if (m_Curler.is_cancelled()) return; try { std::lock_guard<std::mutex> lock(m_DownloadMutex); if (!m_Loader) return; m_Loader->write(d, l); } catch (const Gdk::PixbufError &ex) { std::cerr << ex.what() << std::endl; cancel_download(); m_PixbufError = true; } } void Image::on_progress() { double c, t; m_Curler.get_progress(c, t); m_SignalProgress(c, t); } void Image::on_finished() { std::lock_guard<std::mutex> lock(m_DownloadMutex); m_Curler.save_file(m_Path); m_Curler.clear(); if (m_Loader) { try { m_Loader->close(); } catch (...) { } m_Loader.reset(); } m_SignalPixbufChanged(); m_DownloadCond.notify_one(); } void Image::on_area_prepared() { m_ThumbnailLock.reader_lock(); if (m_ThumbnailPixbuf && m_ThumbnailPixbuf != get_missing_pixbuf()) { Glib::RefPtr<Gdk::Pixbuf> pixbuf = m_Loader->get_pixbuf(); m_ThumbnailPixbuf->composite(pixbuf, 0, 0, pixbuf->get_width(), pixbuf->get_height(), 0, 0, static_cast<double>(pixbuf->get_width()) / m_ThumbnailPixbuf->get_width(), static_cast<double>(pixbuf->get_height()) / m_ThumbnailPixbuf->get_height(), Gdk::INTERP_BILINEAR, 255); } m_ThumbnailLock.reader_unlock(); if (!m_Curler.is_cancelled()) { m_Pixbuf = m_Loader->get_animation(); m_SignalPixbufChanged(); } } void Image::on_area_updated(int, int, int, int) { using namespace std::chrono; if (!m_Curler.is_cancelled() && steady_clock::now() >= m_LastDraw + milliseconds(100)) { m_SignalPixbufChanged(); m_LastDraw = steady_clock::now(); } } <commit_msg>booru/image: Variable delay between draw requests for loading images<commit_after>#include <chrono> #include <fstream> #include <iostream> #include "image.h" using namespace AhoViewer::Booru; #include "browser.h" #include "settings.h" Image::Image(const std::string &path, const std::string &url, const std::string &thumbPath, const std::string &thumbUrl, const std::string &postUrl, std::set<std::string> tags, const Page &page) : AhoViewer::Image(path), m_Url(url), m_ThumbnailUrl(thumbUrl), m_PostUrl(postUrl), m_Tags(tags), m_Page(page), m_Curler(m_Url), m_ThumbnailCurler(new Curler(m_ThumbnailUrl)), m_PixbufError(false) { m_SignalThumbnailLoaded.connect([ this ] { m_ThumbnailCurler.reset(nullptr); }); m_ThumbnailPath = thumbPath; if (!m_isWebM) m_Curler.signal_write().connect(sigc::mem_fun(*this, &Image::on_write)); m_Curler.set_referer(m_PostUrl); m_Curler.signal_progress().connect(sigc::mem_fun(*this, &Image::on_progress)); m_Curler.signal_finished().connect(sigc::mem_fun(*this, &Image::on_finished)); } Image::~Image() { cancel_download(); } bool Image::is_loading() const { return (m_isWebM && !Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS)) || m_Curler.is_active(); } std::string Image::get_filename() const { return m_Page.get_site()->get_name() + "/" + Glib::path_get_basename(m_Path); } const Glib::RefPtr<Gdk::Pixbuf>& Image::get_thumbnail() { if (!m_ThumbnailPixbuf) { if (m_ThumbnailCurler->perform()) { m_ThumbnailCurler->save_file(m_ThumbnailPath); m_ThumbnailLock.writer_lock(); try { m_ThumbnailPixbuf = create_pixbuf_at_size(m_ThumbnailPath, 128, 128); } catch (const Gdk::PixbufError &ex) { std::cerr << ex.what() << std::endl; m_ThumbnailPixbuf = get_missing_pixbuf(); } m_ThumbnailLock.writer_unlock(); } else { std::cerr << "Error while downloading thumbnail " << m_ThumbnailUrl << " " << std::endl << " " << m_ThumbnailCurler->get_error() << std::endl; m_ThumbnailLock.writer_lock(); m_ThumbnailPixbuf = get_missing_pixbuf(); m_ThumbnailLock.writer_unlock(); } m_SignalThumbnailLoaded(); } return m_ThumbnailPixbuf; } void Image::load_pixbuf() { if (!m_Pixbuf && !m_PixbufError) { if (Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS)) { AhoViewer::Image::load_pixbuf(); } else if (!start_download() && !m_isWebM && m_Loader && m_Loader->get_animation()) { m_Pixbuf = m_Loader->get_animation(); } } } void Image::reset_pixbuf() { if (m_Curler.is_active()) cancel_download(); AhoViewer::Image::reset_pixbuf(); } void Image::save(const std::string &path) { if (!Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS)) { start_download(); std::unique_lock<std::mutex> lk(m_DownloadMutex); m_DownloadCond.wait(lk, [ this ] { return m_Curler.is_cancelled() || Glib::file_test(m_Path, Glib::FILE_TEST_EXISTS); }); } if (m_Curler.is_cancelled()) return; Glib::RefPtr<Gio::File> src = Gio::File::create_for_path(m_Path), dst = Gio::File::create_for_path(path); src->copy(dst, Gio::FILE_COPY_OVERWRITE); if (Settings.get_bool("SaveImageTags")) { std::ofstream ofs(path + ".txt"); if (ofs) std::copy(m_Tags.begin(), m_Tags.end(), std::ostream_iterator<std::string>(ofs, "\n")); } } void Image::cancel_download() { m_Curler.cancel(); std::lock_guard<std::mutex> lock(m_DownloadMutex); if (m_Loader) { try { m_Loader->close(); } catch (...) { } m_Loader.reset(); } m_Curler.clear(); m_DownloadCond.notify_one(); } /** * Returns true if the download was started **/ bool Image::start_download() { if (!m_Curler.is_active()) { m_Page.get_image_fetcher().add_handle(&m_Curler); if (!m_isWebM) { m_Loader = Gdk::PixbufLoader::create(); m_Loader->signal_area_prepared().connect(sigc::mem_fun(*this, &Image::on_area_prepared)); m_Loader->signal_area_updated().connect(sigc::mem_fun(*this, &Image::on_area_updated)); } return true; } return false; } void Image::on_write(const unsigned char *d, size_t l) { if (m_Curler.is_cancelled()) return; try { std::lock_guard<std::mutex> lock(m_DownloadMutex); if (!m_Loader) return; m_Loader->write(d, l); } catch (const Gdk::PixbufError &ex) { std::cerr << ex.what() << std::endl; cancel_download(); m_PixbufError = true; } } void Image::on_progress() { double c, t; m_Curler.get_progress(c, t); m_SignalProgress(c, t); } void Image::on_finished() { std::lock_guard<std::mutex> lock(m_DownloadMutex); m_Curler.save_file(m_Path); m_Curler.clear(); if (m_Loader) { try { m_Loader->close(); } catch (...) { } m_Loader.reset(); } m_SignalPixbufChanged(); m_DownloadCond.notify_one(); } void Image::on_area_prepared() { m_ThumbnailLock.reader_lock(); if (m_ThumbnailPixbuf && m_ThumbnailPixbuf != get_missing_pixbuf()) { Glib::RefPtr<Gdk::Pixbuf> pixbuf = m_Loader->get_pixbuf(); m_ThumbnailPixbuf->composite(pixbuf, 0, 0, pixbuf->get_width(), pixbuf->get_height(), 0, 0, static_cast<double>(pixbuf->get_width()) / m_ThumbnailPixbuf->get_width(), static_cast<double>(pixbuf->get_height()) / m_ThumbnailPixbuf->get_height(), Gdk::INTERP_BILINEAR, 255); } m_ThumbnailLock.reader_unlock(); if (!m_Curler.is_cancelled()) { m_Pixbuf = m_Loader->get_animation(); m_SignalPixbufChanged(); } } void Image::on_area_updated(int, int, int, int) { using namespace std::chrono; // Wait longer between draw requests for larger images // A better solution might be to have a drawn signal or flag and check that // but knowing for sure when gtk draws something seems impossible Glib::RefPtr<Gdk::Pixbuf> p = m_Loader->get_pixbuf(); auto ms = std::min(std::max((p->get_width() + p->get_height()) / 60.f, 100.f), 800.f); if (!m_Curler.is_cancelled() && steady_clock::now() >= m_LastDraw + milliseconds(static_cast<int>(ms))) { m_SignalPixbufChanged(); m_LastDraw = steady_clock::now(); } } <|endoftext|>
<commit_before>#include "stdafx.h" #include "TimeManager.h" TimeManager* g_pTimeManager=NULL ; TimeManager::TimeManager() { __ENTER_FUNCTION m_CurrentTime = 0 ; __LEAVE_FUNCTION } TimeManager::~TimeManager() { __ENTER_FUNCTION __LEAVE_FUNCTION } BOOL TimeManager::Init() { __ENTER_FUNCTION #if defined(__WINDOWS__) m_StartTime = GetTickCount() ; m_CurrentTime = GetTickCount() ; #elif defined(__LINUX__) m_StartTime = 0; m_CurrentTime = 0; gettimeofday(&_tstart, &tz); #endif SetTime( ) ; // init to current format time CHAR szCurrentFormatTime[ MAX_DATE_LENGTH ]; sprintf( szCurrentFormatTime, "%s", GetCurrentFormatTime() ) ; return TRUE ; __LEAVE_FUNCTION return FALSE ; } UINT TimeManager::CurrentTime() { __ENTER_FUNCTION #if defined(__WINDOWS__) m_CurrentTime = GetTickCount() ; #elif defined(__LINUX__) gettimeofday(&_tend,&tz); double t1, t2; t1 = (double)_tstart.tv_sec*1000 + (double)_tstart.tv_usec/1000; t2 = (double)_tend.tv_sec*1000 + (double)_tend.tv_usec/1000; m_CurrentTime = (UINT)(t2-t1); #endif return m_CurrentTime ; __LEAVE_FUNCTION return 0 ; } UINT TimeManager::CurrentDate() { __ENTER_FUNCTION SetTime() ; UINT Date; ConvertTU(&m_TM,Date); return Date; __LEAVE_FUNCTION return 0; } VOID TimeManager::SetTime( ) { __ENTER_FUNCTION time( &m_SetTime ) ; tm* ptm = localtime( &m_SetTime ) ; m_TM = *ptm ; __LEAVE_FUNCTION } // 得到标准时间 time_t TimeManager::GetANSITime( ) { __ENTER_FUNCTION SetTime(); __LEAVE_FUNCTION return m_SetTime; } UINT TimeManager::Time2DWORD( ) { __ENTER_FUNCTION SetTime() ; UINT uRet = 0 ; uRet += GetYear( ) ; uRet -= 2000 ; uRet =uRet*100 ; uRet += GetMonth( )+1 ; uRet =uRet*100 ; uRet += GetDay( ) ; uRet =uRet*100 ; uRet += GetHour( ) ; uRet =uRet*100 ; uRet += GetMinute( ) ; return uRet ; __LEAVE_FUNCTION return 0 ; } UINT TimeManager::DiffTime( UINT Date1, UINT Date2 ) { __ENTER_FUNCTION tm S_D1, S_D2 ; ConvertUT( Date1, &S_D1 ) ; ConvertUT( Date2, &S_D2 ) ; time_t t1,t2 ; t1 = mktime(&S_D1) ; t2 = mktime(&S_D2) ; UINT dif = (UINT)(difftime(t2,t1)*1000) ; return dif ; __LEAVE_FUNCTION return 0 ; } VOID TimeManager::ConvertUT( UINT Date, tm* TM ) { __ENTER_FUNCTION Assert(TM) ; memset( TM, 0, sizeof(tm) ) ; TM->tm_year = (Date>>26)&0xf ; TM->tm_mon = (Date>>22)&0xf ; TM->tm_mday = (Date>>17)&0x1f ; TM->tm_hour = (Date>>12)&0x1f ; TM->tm_min = (Date>>6) &0x3f ; TM->tm_sec = (Date) &0x3f ; __LEAVE_FUNCTION } VOID TimeManager::ConvertTU( tm* TM, UINT& Date ) { __ENTER_FUNCTION Assert( TM ) ; Date = 0 ; Date += (TM->tm_yday%10) & 0xf ; Date = (Date<<4) ; Date += TM->tm_mon & 0xf ; Date = (Date<<4) ; Date += TM->tm_mday & 0x1f ; Date = (Date<<5) ; Date += TM->tm_hour & 0x1f ; Date = (Date<<5) ; Date += TM->tm_min & 0x3f ; Date = (Date<<6) ; Date += TM->tm_sec & 0x3f ; __LEAVE_FUNCTION } UINT TimeManager::GetDayTime( ) { __ENTER_FUNCTION time_t st ; time( &st ) ; tm* ptm = localtime( &m_SetTime ) ; UINT uRet=0 ; uRet = (ptm->tm_year-100)*1000 ; uRet += ptm->tm_yday ; return uRet ; __LEAVE_FUNCTION return 0 ; } WORD TimeManager::GetTodayTime() { __ENTER_FUNCTION time_t st ; time( &st ) ; tm* ptm = localtime( &m_SetTime ) ; WORD uRet = 0 ; uRet = ptm->tm_hour*100 ; uRet += ptm->tm_min ; return uRet ; __LEAVE_FUNCTION return 0 ; } BOOL TimeManager::FormatTodayTime(WORD& nTime) { __ENTER_FUNCTION BOOL ret = FALSE; WORD wHour = nTime / 100; WORD wMin = nTime % 100; WORD wAddHour = 0; if( wMin > 59 ) { wAddHour = wMin / 60; wMin = wMin % 60; } wHour += wAddHour; if( wHour > 23 ) { ret = TRUE; wHour = wHour % 60; } return ret; __LEAVE_FUNCTION return FALSE ; } /** * @param VOID * @uses get current format time, example: 2013-7-29 16:48:46 */ CHAR* TimeManager::GetCurrentFormatTime() { __ENTER_FUNCTION CHAR szCurrentFormatTime[ MAX_DATE_LENGTH ]; memset( szCurrentFormatTime, 0, sizeof( szCurrentFormatTime ) ); SetTime(); strftime( szCurrentFormatTime, sizeof( szCurrentFormatTime ), "%Y-%m-%d %H:%M:%S", &m_TM ); return szCurrentFormatTime; __LEAVE_FUNCTION return ""; } <commit_msg>reset the code style for mine<commit_after>#include "stdafx.h" #include "TimeManager.h" TimeManager* g_pTimeManager=NULL ; TimeManager::TimeManager() { __ENTER_FUNCTION m_CurrentTime = 0 ; __LEAVE_FUNCTION } TimeManager::~TimeManager() { __ENTER_FUNCTION __LEAVE_FUNCTION } BOOL TimeManager::Init() { __ENTER_FUNCTION #if defined(__WINDOWS__) m_StartTime = GetTickCount() ; m_CurrentTime = GetTickCount() ; #elif defined(__LINUX__) m_StartTime = 0 ; m_CurrentTime = 0 ; gettimeofday(&_tstart, &tz); #endif SetTime( ) ; // init to current format time CHAR szCurrentFormatTime[ MAX_DATE_LENGTH ]; sprintf( szCurrentFormatTime, "%s", GetCurrentFormatTime() ) ; return TRUE ; __LEAVE_FUNCTION return FALSE ; } UINT TimeManager::CurrentTime() { __ENTER_FUNCTION #if defined(__WINDOWS__) m_CurrentTime = GetTickCount() ; #elif defined(__LINUX__) gettimeofday(&_tend,&tz); double t1, t2; t1 = (double)_tstart.tv_sec*1000 + (double)_tstart.tv_usec/1000; t2 = (double)_tend.tv_sec*1000 + (double)_tend.tv_usec/1000; m_CurrentTime = (UINT)(t2-t1); #endif return m_CurrentTime ; __LEAVE_FUNCTION return 0 ; } UINT TimeManager::CurrentDate() { __ENTER_FUNCTION SetTime() ; UINT Date; ConvertTU(&m_TM,Date); return Date; __LEAVE_FUNCTION return 0; } VOID TimeManager::SetTime( ) { __ENTER_FUNCTION time( &m_SetTime ) ; tm* ptm = localtime( &m_SetTime ) ; m_TM = *ptm ; __LEAVE_FUNCTION } // 得到标准时间 time_t TimeManager::GetANSITime( ) { __ENTER_FUNCTION SetTime(); __LEAVE_FUNCTION return m_SetTime; } UINT TimeManager::Time2DWORD( ) { __ENTER_FUNCTION SetTime() ; UINT uRet = 0 ; uRet += GetYear( ) ; uRet -= 2000 ; uRet =uRet*100 ; uRet += GetMonth( )+1 ; uRet =uRet*100 ; uRet += GetDay( ) ; uRet =uRet*100 ; uRet += GetHour( ) ; uRet =uRet*100 ; uRet += GetMinute( ) ; return uRet ; __LEAVE_FUNCTION return 0 ; } UINT TimeManager::DiffTime( UINT Date1, UINT Date2 ) { __ENTER_FUNCTION tm S_D1, S_D2 ; ConvertUT( Date1, &S_D1 ) ; ConvertUT( Date2, &S_D2 ) ; time_t t1,t2 ; t1 = mktime(&S_D1) ; t2 = mktime(&S_D2) ; UINT dif = (UINT)(difftime(t2,t1)*1000) ; return dif ; __LEAVE_FUNCTION return 0 ; } VOID TimeManager::ConvertUT( UINT Date, tm* TM ) { __ENTER_FUNCTION Assert(TM) ; memset( TM, 0, sizeof(tm) ) ; TM->tm_year = (Date>>26)&0xf ; TM->tm_mon = (Date>>22)&0xf ; TM->tm_mday = (Date>>17)&0x1f ; TM->tm_hour = (Date>>12)&0x1f ; TM->tm_min = (Date>>6) &0x3f ; TM->tm_sec = (Date) &0x3f ; __LEAVE_FUNCTION } VOID TimeManager::ConvertTU( tm* TM, UINT& Date ) { __ENTER_FUNCTION Assert( TM ) ; Date = 0 ; Date += (TM->tm_yday%10) & 0xf ; Date = (Date<<4) ; Date += TM->tm_mon & 0xf ; Date = (Date<<4) ; Date += TM->tm_mday & 0x1f ; Date = (Date<<5) ; Date += TM->tm_hour & 0x1f ; Date = (Date<<5) ; Date += TM->tm_min & 0x3f ; Date = (Date<<6) ; Date += TM->tm_sec & 0x3f ; __LEAVE_FUNCTION } UINT TimeManager::GetDayTime( ) { __ENTER_FUNCTION time_t st ; time( &st ) ; tm* ptm = localtime( &m_SetTime ) ; UINT uRet=0 ; uRet = (ptm->tm_year-100)*1000 ; uRet += ptm->tm_yday ; return uRet ; __LEAVE_FUNCTION return 0 ; } WORD TimeManager::GetTodayTime() { __ENTER_FUNCTION time_t st ; time( &st ) ; tm* ptm = localtime( &m_SetTime ) ; WORD uRet = 0 ; uRet = ptm->tm_hour*100 ; uRet += ptm->tm_min ; return uRet ; __LEAVE_FUNCTION return 0 ; } BOOL TimeManager::FormatTodayTime(WORD& nTime) { __ENTER_FUNCTION BOOL ret = FALSE; WORD wHour = nTime / 100; WORD wMin = nTime % 100; WORD wAddHour = 0; if( wMin > 59 ) { wAddHour = wMin / 60; wMin = wMin % 60; } wHour += wAddHour; if( wHour > 23 ) { ret = TRUE; wHour = wHour % 60; } return ret; __LEAVE_FUNCTION return FALSE ; } /** * @param VOID * @uses get current format time, example: 2013-7-29 16:48:46 */ CHAR* TimeManager::GetCurrentFormatTime() { __ENTER_FUNCTION CHAR szCurrentFormatTime[ MAX_DATE_LENGTH ]; memset( szCurrentFormatTime, 0, sizeof( szCurrentFormatTime ) ); SetTime(); strftime( szCurrentFormatTime, sizeof( szCurrentFormatTime ), "%Y-%m-%d %H:%M:%S", &m_TM ); return szCurrentFormatTime; __LEAVE_FUNCTION return ""; } <|endoftext|>
<commit_before><commit_msg>Update Pollard Rho.cpp<commit_after><|endoftext|>
<commit_before>#include "Common.h" #include "Logging.h" #include <stdarg.h> VINYL_NS_BEGIN; namespace Log { FormatVarInt::FormatVarInt(int i) { m_value = i; } FormatVarInt::~FormatVarInt() { if (m_cache != nullptr) { delete m_cache; } } const char* FormatVarInt::GetString() { if (m_cache != nullptr) { delete m_cache; } m_cache = (char*)malloc(14); snprintf(m_cache, 14, "%d", m_value); return m_cache; } FormatVarString::FormatVarString(const char* str) { m_value = str; } const char* FormatVarString::GetString() { return m_value; } s::String Format(const char* format, va_list vl) { s::StackArray<FormatVar> vars; vars.sa_bOnlyPop = true; int numHighest = 0; int bufferLen = 128; s::String ret; int len = strlen(format); for (int i = 0; i < len; i++) { char c = format[i]; if (c == '%') { char cn = format[++i]; char str[5]; int strc = 0; while (cn >= '0' && cn <= '9' && strc < 4 && i < len) { str[strc] = cn; strc++; cn = format[++i]; } i--; str[strc] = '\0'; int num = atoi(str); if (num == 0) { continue; } if (num > numHighest) { for (int j = numHighest; j < num; j++) { FormatVar &newvar = va_arg(vl, FormatVar); vars.Push(&newvar); } numHighest = num; } FormatVar &var = vars[num - 1]; ret += var.GetString(); continue; } ret += c; } return ret; } LogLevel Level = LogLevel_Info; static s::Mutex _mutex; void Trace(const char* format, ...) { _mutex.Lock(); va_list vl; va_start(vl, format); s::String str = Format(format, vl); va_end(vl); #if WINDOWS HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, 8); printf("[TRACE] "); SetConsoleTextAttribute(hConsole, 7); printf("%s\n", (const char*)str); #else printf("[TRACE] %s\n", (const char*)str); #endif _mutex.Unlock(); } void Debug(const char* format, ...) { _mutex.Lock(); va_list vl; va_start(vl, format); s::String str = Format(format, vl); va_end(vl); printf("[DEBUG] %s\n", (const char*)str); _mutex.Unlock(); } void Info(const char* format, ...) { _mutex.Lock(); va_list vl; va_start(vl, format); s::String str = Format(format, vl); va_end(vl); #if WINDOWS HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, 15); printf("[INFO] "); SetConsoleTextAttribute(hConsole, 7); printf("%s\n", (const char*)str); #else printf("\x1B[01m[INFO]\x1B[0m %s\n", (const char*)str); #endif _mutex.Unlock(); } void Warning(const char* format, ...) { _mutex.Lock(); va_list vl; va_start(vl, format); s::String str = Format(format, vl); va_end(vl); #if WINDOWS HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, 13); printf("[WARNING] "); SetConsoleTextAttribute(hConsole, 7); printf("%s\n", (const char*)str); #else printf("\x1B[35m[WARNING]\x1B[0m %s\n", (const char*)str); #endif _mutex.Unlock(); } void Error(const char* format, ...) { _mutex.Lock(); va_list vl; va_start(vl, format); s::String str = Format(format, vl); va_end(vl); #if WINDOWS HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, 14); printf("[ERROR] "); SetConsoleTextAttribute(hConsole, 7); printf("%s\n", (const char*)str); #else printf("\x1B[33m[ERROR]\x1B[0m %s\n", (const char*)str); #endif _mutex.Unlock(); } void Fatal(const char* format, ...) { _mutex.Lock(); va_list vl; va_start(vl, format); s::String str = Format(format, vl); va_end(vl); #if WINDOWS HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, 12); printf("[FATAL] "); SetConsoleTextAttribute(hConsole, 7); printf("%s\n", (const char*)str); #else printf("\x1B[31m[FATAL]\x1B[0m %s\n", (const char*)str); #endif _mutex.Unlock(); } } VINYL_NS_END; <commit_msg>Fix colors on linux<commit_after>#include "Common.h" #include "Logging.h" #include <stdarg.h> VINYL_NS_BEGIN; namespace Log { FormatVarInt::FormatVarInt(int i) { m_value = i; } FormatVarInt::~FormatVarInt() { if (m_cache != nullptr) { delete m_cache; } } const char* FormatVarInt::GetString() { if (m_cache != nullptr) { delete m_cache; } m_cache = (char*)malloc(14); snprintf(m_cache, 14, "%d", m_value); return m_cache; } FormatVarString::FormatVarString(const char* str) { m_value = str; } const char* FormatVarString::GetString() { return m_value; } s::String Format(const char* format, va_list vl) { s::StackArray<FormatVar> vars; vars.sa_bOnlyPop = true; int numHighest = 0; int bufferLen = 128; s::String ret; int len = strlen(format); for (int i = 0; i < len; i++) { char c = format[i]; if (c == '%') { char cn = format[++i]; char str[5]; int strc = 0; while (cn >= '0' && cn <= '9' && strc < 4 && i < len) { str[strc] = cn; strc++; cn = format[++i]; } i--; str[strc] = '\0'; int num = atoi(str); if (num == 0) { continue; } if (num > numHighest) { for (int j = numHighest; j < num; j++) { FormatVar &newvar = va_arg(vl, FormatVar); vars.Push(&newvar); } numHighest = num; } FormatVar &var = vars[num - 1]; ret += var.GetString(); continue; } ret += c; } return ret; } LogLevel Level = LogLevel_Info; static s::Mutex _mutex; void Trace(const char* format, ...) { _mutex.Lock(); va_list vl; va_start(vl, format); s::String str = Format(format, vl); va_end(vl); #if WINDOWS HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, 8); printf("[TRACE] "); SetConsoleTextAttribute(hConsole, 7); printf("%s\n", (const char*)str); #else printf("\x1B[02m[TRACE]\x1B[0m %s\n", (const char*)str); #endif _mutex.Unlock(); } void Debug(const char* format, ...) { _mutex.Lock(); va_list vl; va_start(vl, format); s::String str = Format(format, vl); va_end(vl); printf("[DEBUG] %s\n", (const char*)str); _mutex.Unlock(); } void Info(const char* format, ...) { _mutex.Lock(); va_list vl; va_start(vl, format); s::String str = Format(format, vl); va_end(vl); #if WINDOWS HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, 15); printf("[INFO] "); SetConsoleTextAttribute(hConsole, 7); printf("%s\n", (const char*)str); #else printf("\x1B[38m[INFO]\x1B[0m %s\n", (const char*)str); #endif _mutex.Unlock(); } void Warning(const char* format, ...) { _mutex.Lock(); va_list vl; va_start(vl, format); s::String str = Format(format, vl); va_end(vl); #if WINDOWS HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, 13); printf("[WARNING] "); SetConsoleTextAttribute(hConsole, 7); printf("%s\n", (const char*)str); #else printf("\x1B[35m[WARNING]\x1B[0m %s\n", (const char*)str); #endif _mutex.Unlock(); } void Error(const char* format, ...) { _mutex.Lock(); va_list vl; va_start(vl, format); s::String str = Format(format, vl); va_end(vl); #if WINDOWS HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, 14); printf("[ERROR] "); SetConsoleTextAttribute(hConsole, 7); printf("%s\n", (const char*)str); #else printf("\x1B[33m[ERROR]\x1B[0m %s\n", (const char*)str); #endif _mutex.Unlock(); } void Fatal(const char* format, ...) { _mutex.Lock(); va_list vl; va_start(vl, format); s::String str = Format(format, vl); va_end(vl); #if WINDOWS HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole, 12); printf("[FATAL] "); SetConsoleTextAttribute(hConsole, 7); printf("%s\n", (const char*)str); #else printf("\x1B[31m[FATAL]\x1B[0m %s\n", (const char*)str); #endif _mutex.Unlock(); } } VINYL_NS_END; <|endoftext|>
<commit_before>//---------------------------------------------------------------------------// //! //! \file Utility_TetrahedronHelpers.cpp //! \author Alex Robinson, Eli Moll //! \brief Tetrahedron helper functions //! //---------------------------------------------------------------------------// // Std Lib Includes #include <math.h> // Trilinos Includes #include <Teuchos_ScalarTraits.hpp> // FRENSIE Includes #include "Utility_TetrahedronHelpers.hpp" #include "Utility_ContractException.hpp" #include <moab/Matrix3.hpp> namespace Utility{ // Calculate the volume of a tetrahedron double calculateTetrahedronVolume( const double vertex_a[3], const double vertex_b[3], const double vertex_c[3], const double vertex_d[3] ) { double a1 = vertex_a[0] - vertex_d[0]; double a2 = vertex_a[1] - vertex_d[1]; double a3 = vertex_a[2] - vertex_d[2]; double b1 = vertex_b[0] - vertex_d[0]; double b2 = vertex_b[1] - vertex_d[1]; double b3 = vertex_b[2] - vertex_d[2]; double c1 = vertex_c[0] - vertex_d[0]; double c2 = vertex_c[1] - vertex_d[1]; double c3 = vertex_c[2] - vertex_d[2]; double volume = fabs( a1*(b2*c3-b3*c2) + a2*(b3*c1-b1*c3) + a3*(b1*c2-b2*c1) )/6.0; testPostcondition( !Teuchos::ScalarTraits<double>::isnaninf( volume ) ); testPostcondition( volume > 0.0 ); return volume; } // Calculate the Barycentric Transform Matrix double calculateBarycentricTransformMatrix( const double vertex_a[3], const double vertex_b[3], const double vertex_c[3], const double vertex_d[3] ) { double t1 = vertex_a[0] - vertex_d[0]; double t2 = vertex_b[0] - vertex_d[0]; double t3 = vertex_c[0] - vertex_d[0]; double t4 = vertex_a[1] - vertex_d[1]; double t5 = vertex_b[1] - vertex_d[1]; double t6 = vertex_c[1] - vertex_d[1]; double t7 = vertex_a[2] - vertex_d[2]; double t8 = vertex_b[2] - vertex_d[2]; double t9 = vertex_c[2] - vertex_d[2]; moab::Matrix3 T( t1, t2, t3, t4, t5, t6, t7, t8, t9 ); T = T.inverse(); double* btm = T.array(); return btm; } } // end Utility namespace //---------------------------------------------------------------------------// // end Utility_TetrahedronHelpers.cpp //---------------------------------------------------------------------------// <commit_msg>Fixing return types in Barycentric data<commit_after>//---------------------------------------------------------------------------// //! //! \file Utility_TetrahedronHelpers.cpp //! \author Alex Robinson, Eli Moll //! \brief Tetrahedron helper functions //! //---------------------------------------------------------------------------// // Std Lib Includes #include <math.h> // Trilinos Includes #include <Teuchos_ScalarTraits.hpp> // FRENSIE Includes #include "Utility_TetrahedronHelpers.hpp" #include "Utility_ContractException.hpp" #include <moab/Matrix3.hpp> namespace Utility{ // Calculate the volume of a tetrahedron double calculateTetrahedronVolume( const double vertex_a[3], const double vertex_b[3], const double vertex_c[3], const double vertex_d[3] ) { double a1 = vertex_a[0] - vertex_d[0]; double a2 = vertex_a[1] - vertex_d[1]; double a3 = vertex_a[2] - vertex_d[2]; double b1 = vertex_b[0] - vertex_d[0]; double b2 = vertex_b[1] - vertex_d[1]; double b3 = vertex_b[2] - vertex_d[2]; double c1 = vertex_c[0] - vertex_d[0]; double c2 = vertex_c[1] - vertex_d[1]; double c3 = vertex_c[2] - vertex_d[2]; double volume = fabs( a1*(b2*c3-b3*c2) + a2*(b3*c1-b1*c3) + a3*(b1*c2-b2*c1) )/6.0; testPostcondition( !Teuchos::ScalarTraits<double>::isnaninf( volume ) ); testPostcondition( volume > 0.0 ); return volume; } // Calculate the Barycentric Transform Matrix double calculateBarycentricTransformMatrix( const double vertex_a[3], const double vertex_b[3], const double vertex_c[3], const double vertex_d[3] ) { double t1 = vertex_a[0] - vertex_d[0]; double t2 = vertex_b[0] - vertex_d[0]; double t3 = vertex_c[0] - vertex_d[0]; double t4 = vertex_a[1] - vertex_d[1]; double t5 = vertex_b[1] - vertex_d[1]; double t6 = vertex_c[1] - vertex_d[1]; double t7 = vertex_a[2] - vertex_d[2]; double t8 = vertex_b[2] - vertex_d[2]; double t9 = vertex_c[2] - vertex_d[2]; moab::Matrix3 T( t1, t2, t3, t4, t5, t6, t7, t8, t9 ); T = T.inverse(); return T.array(); } } // end Utility namespace //---------------------------------------------------------------------------// // end Utility_TetrahedronHelpers.cpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>/* ============================================================================ * Copyright (c) 2014 William Lenthe * Copyright (c) 2014 DREAM3D Consortium * 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 William Lenthe or any of the DREAM3D Consortium contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This code was partially written under United States Air Force Contract number * FA8650-10-D-5210 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "ItkWriteImage.h" #include <QtCore/QString> #include <QtCore/QFileInfo> #include "itkImageFileWriter.h" #include "itkRGBPixel.h" #include "itkRGBAPixel.h" #include "itkVectorImage.h" #include "SIMPLib/Common/TemplateHelpers.hpp" #include "SIMPLib/FilterParameters/DataArraySelectionFilterParameter.h" #include "SIMPLib/FilterParameters/OutputFileFilterParameter.h" #include "SIMPLib/FilterParameters/AbstractFilterParametersReader.h" #include "SIMPLib/FilterParameters/SeparatorFilterParameter.h" #include "SIMPLib/Geometry/ImageGeom.h" #include "ImageProcessing/ImageProcessingFilters/ItkBridge.h" /** * @brief This is a private implementation for the filter that handles the actual algorithm implementation details * for us like figuring out if we can use this private implementation with the data array that is assigned. */ template<typename TInputType> class WriteImagePrivate { public: typedef DataArray<TInputType> DataArrayType; WriteImagePrivate() {} virtual ~WriteImagePrivate() {} // ----------------------------------------------------------------------------- // Determine if this is the proper type of an array to downcast from the IDataArray // ----------------------------------------------------------------------------- bool operator()(IDataArray::Pointer p) { return (std::dynamic_pointer_cast<DataArrayType>(p).get() != nullptr); } // ----------------------------------------------------------------------------- // This is the actual templated algorithm // ----------------------------------------------------------------------------- void static Execute(ItkWriteImage* filter, DataContainer::Pointer m, QString attrMatName, IDataArray::Pointer inputDataArray, QString outputFile) { typename DataArrayType::Pointer inputDataPtr = std::dynamic_pointer_cast<DataArrayType>(inputDataArray); // Get a Raw Pointer to the data TInputType* inputData = inputDataPtr->getPointer(0); //size_t numVoxels = inputDataPtr->getNumberOfTuples(); //get utilities //get the total number of components of the data and switch accordingly int numComp = inputDataPtr->getNumberOfComponents(); itk::ProcessObject::Pointer writerObject; if(1 == numComp) //scalar image { typedef ItkBridge<TInputType> ItkBridgeType; //define types and wrap input image typedef typename ItkBridgeType::ScalarImageType ImageType; typename ImageType::Pointer inputImage = ItkBridgeType::CreateItkWrapperForDataPointer(m, attrMatName, inputData); //create writer and execute typedef itk::ImageFileWriter<ImageType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputFile.toLatin1().constData() ); writer->SetInput( inputImage ); writerObject = writer; } else if(3 == numComp)//rgb image { //define types and wrap input image typedef ItkBridge<TInputType> ItkBridgeType; //define types and wrap input image typedef typename ItkBridgeType::RGBImageType ImageType; typedef typename itk::ImageFileWriter<ImageType> WriterType; // typename ImageType::Pointer inputImage = ItkBridgeType::template Dream3DtoITKTemplate<ImageType>(m, attrMatName, inputData); typename ImageType::Pointer inputImage = ItkBridgeType::template Dream3DtoITKImportFilter<typename ImageType::PixelType>(m, attrMatName, inputData)->GetOutput(); //create writer and execute typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputFile.toLatin1().constData() ); writer->SetInput( inputImage ); writerObject = writer; } else if(4 == numComp)//rgba image { typedef ItkBridge<TInputType> ItkBridgeType; //define types and wrap input image typedef typename ItkBridgeType::RGBAImageType ImageType; typedef typename itk::ImageFileWriter<ImageType> WriterType; // typename ImageType::Pointer inputImage = ItkBridgeType::template Dream3DtoITKTemplate<ImageType>(m, attrMatName, inputData); typename ImageType::Pointer inputImage = ItkBridgeType::template Dream3DtoITKImportFilter<typename ImageType::PixelType>(m, attrMatName, inputData)->GetOutput(); //create writer and execute typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputFile.toLatin1().constData() ); writer->SetInput( inputImage ); writerObject = writer; } /** else//vector image { //define types and wrap input image typedef itk::Image<itk::FixedArray<TInputType, numComp> >, ImageProcessingConstants::ImageDimension> ImageType; typedef itk::ImageFileWriter<ImageType> WriterType; ImageType::Pointer inputImage = ItkBridgeType::Dream3DtoITKTemplate<ImageType>(m, attrMatName, inputData); //create writer and execute typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputFile.toLatin1().constData() ); writer->SetInput( inputImage ); writerObject = writer; }*/ try { writerObject->Update(); } catch( itk::ExceptionObject& err ) { filter->setErrorCondition(-5); QString ss = QObject::tr("Failed to write image. Error Message returned from ITK:\n %1").arg(err.GetDescription()); filter->notifyErrorMessage(filter->getHumanLabel(), ss, filter->getErrorCondition()); } } private: WriteImagePrivate(const WriteImagePrivate&); // Copy Constructor Not Implemented void operator=(const WriteImagePrivate&); // Operator '=' Not Implemented }; // Include the MOC generated file for this class #include "moc_ItkWriteImage.cpp" // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- ItkWriteImage::ItkWriteImage() : AbstractFilter(), m_SelectedCellArrayPath("", "", ""), m_OutputFileName(""), m_SelectedCellArray(nullptr) { setupFilterParameters(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- ItkWriteImage::~ItkWriteImage() { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void ItkWriteImage::setupFilterParameters() { FilterParameterVector parameters; parameters.push_back(SeparatorFilterParameter::New("Cell Data", FilterParameter::RequiredArray)); { DataArraySelectionFilterParameter::RequirementType req; parameters.push_back(SIMPL_NEW_DA_SELECTION_FP("Color Data", SelectedCellArrayPath, FilterParameter::RequiredArray, ItkWriteImage, req)); } parameters.push_back(SIMPL_NEW_OUTPUT_FILE_FP("Output File Name", OutputFileName, FilterParameter::Parameter, ItkWriteImage, "*.tif", "TIFF")); setFilterParameters(parameters); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void ItkWriteImage::readFilterParameters(AbstractFilterParametersReader* reader, int index) { reader->openFilterGroup(this, index); setSelectedCellArrayPath( reader->readDataArrayPath( "SelectedCellArrayPath", getSelectedCellArrayPath() ) ); setOutputFileName( reader->readString( "OutputFileName", getOutputFileName() ) ); reader->closeFilterGroup(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void ItkWriteImage::initialize() { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void ItkWriteImage::dataCheck() { setErrorCondition(0); if(m_OutputFileName.isEmpty()) { QString ss = QObject::tr("Output file name/path was not given"); setErrorCondition(-100); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); return; } QFileInfo fi(m_OutputFileName); if(fi.suffix().compare("tif") != 0) { QString ss = QObject::tr("Image Stacks are only supported for TIFF formatted output"); setErrorCondition(-101); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); return; } //pass empty dimensions to allow any size QVector<size_t> compDims; m_SelectedCellArrayPtr = TemplateHelpers::GetPrereqArrayFromPath<AbstractFilter>()(this, getSelectedCellArrayPath(), compDims); if(nullptr != m_SelectedCellArrayPtr.lock().get()) { m_SelectedCellArray = m_SelectedCellArrayPtr.lock().get(); } if(getErrorCondition() < 0) { return; } getDataContainerArray()->getPrereqGeometryFromDataContainer<ImageGeom, AbstractFilter>(this, getSelectedCellArrayPath().getDataContainerName()); // Ignore returning from the dataCheck if this errors out. We are just trying to // ensure an ImageGeometry is selected. If code is added below that starts depending // on the image geometry, then the next line should be uncommented. //if(getErrorCondition() < 0 || nullptr == image.get()) { return; } //make sure dims of selected array are appropriate if(1 == compDims.size()) { if(1 == compDims[0]) //scalar { } else if (3 == compDims[0])//rgb { notifyWarningMessage(getHumanLabel(), "Warning: writing of rgb images is currenlty experimental (unstable behavoir may occur)", 0); } else if (4 == compDims[0])//rgba { notifyWarningMessage(getHumanLabel(), "Warning: writing of rgba images is currenlty experimental (unstable behavoir may occur)", 0); } else //vector { //notifyWarningMessage(getHumanLabel(), "Warning: writing of vector images is currenlty experimental (unstable behavoir may occur)", 0); setErrorCondition(-102); notifyErrorMessage(getHumanLabel(), "Error: writing of vector images is currently not supported", getErrorCondition()); } } else { QString message = QObject::tr("The selected array '%1' has unsupported dimensionality (%2)").arg(m_SelectedCellArrayPath.getDataArrayName()).arg(compDims.size()); setErrorCondition(-101); notifyErrorMessage(getHumanLabel(), message, getErrorCondition()); } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void ItkWriteImage::preflight() { // These are the REQUIRED lines of CODE to make sure the filter behaves correctly setInPreflight(true); // Set the fact that we are preflighting. emit preflightAboutToExecute(); // Emit this signal so that other widgets can do one file update emit updateFilterParameters(this); // Emit this signal to have the widgets push their values down to the filter dataCheck(); // Run our DataCheck to make sure everthing is setup correctly emit preflightExecuted(); // We are done preflighting this filter setInPreflight(false); // Inform the system this filter is NOT in preflight mode anymore. } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void ItkWriteImage::execute() { //int err = 0; dataCheck(); if(getErrorCondition() < 0) { return; } DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getSelectedCellArrayPath().getDataContainerName()); QString attrMatName = getSelectedCellArrayPath().getAttributeMatrixName(); //get input data IDataArray::Pointer inputData = m_SelectedCellArrayPtr.lock(); if(WriteImagePrivate<int8_t>()(inputData)) { WriteImagePrivate<int8_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<uint8_t>()(inputData) ) { WriteImagePrivate<uint8_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<int16_t>()(inputData) ) { WriteImagePrivate<int16_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<uint16_t>()(inputData) ) { WriteImagePrivate<uint16_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<int32_t>()(inputData) ) { WriteImagePrivate<int32_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<uint32_t>()(inputData) ) { WriteImagePrivate<uint32_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<int64_t>()(inputData) ) { WriteImagePrivate<int64_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<uint64_t>()(inputData) ) { WriteImagePrivate<uint64_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<float>()(inputData) ) { WriteImagePrivate<float>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<double>()(inputData) ) { WriteImagePrivate<double>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else { setErrorCondition(-10001); QString ss = QObject::tr("A Supported DataArray type was not used for an input array."); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); return; } /* Let the GUI know we are done with this filter */ notifyStatusMessage(getHumanLabel(), "Complete"); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- AbstractFilter::Pointer ItkWriteImage::newFilterInstance(bool copyFilterParameters) { ItkWriteImage::Pointer filter = ItkWriteImage::New(); if(true == copyFilterParameters) { copyFilterParameterInstanceVariables(filter.get()); } return filter; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString ItkWriteImage::getCompiledLibraryName() {return ImageProcessingConstants::ImageProcessingBaseName;} // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString ItkWriteImage::getGroupName() {return SIMPL::FilterGroups::Unsupported;} // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString ItkWriteImage::getSubGroupName() {return "IO";} // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString ItkWriteImage::getHumanLabel() { return "Export Tiff Image Stack (ImageProcessing)"; } <commit_msg>Fixing incorrect usage of warnings.<commit_after>/* ============================================================================ * Copyright (c) 2014 William Lenthe * Copyright (c) 2014 DREAM3D Consortium * 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 William Lenthe or any of the DREAM3D Consortium contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This code was partially written under United States Air Force Contract number * FA8650-10-D-5210 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "ItkWriteImage.h" #include <QtCore/QString> #include <QtCore/QFileInfo> #include "itkImageFileWriter.h" #include "itkRGBPixel.h" #include "itkRGBAPixel.h" #include "itkVectorImage.h" #include "SIMPLib/Common/TemplateHelpers.hpp" #include "SIMPLib/FilterParameters/DataArraySelectionFilterParameter.h" #include "SIMPLib/FilterParameters/OutputFileFilterParameter.h" #include "SIMPLib/FilterParameters/AbstractFilterParametersReader.h" #include "SIMPLib/FilterParameters/SeparatorFilterParameter.h" #include "SIMPLib/Geometry/ImageGeom.h" #include "ImageProcessing/ImageProcessingFilters/ItkBridge.h" /** * @brief This is a private implementation for the filter that handles the actual algorithm implementation details * for us like figuring out if we can use this private implementation with the data array that is assigned. */ template<typename TInputType> class WriteImagePrivate { public: typedef DataArray<TInputType> DataArrayType; WriteImagePrivate() {} virtual ~WriteImagePrivate() {} // ----------------------------------------------------------------------------- // Determine if this is the proper type of an array to downcast from the IDataArray // ----------------------------------------------------------------------------- bool operator()(IDataArray::Pointer p) { return (std::dynamic_pointer_cast<DataArrayType>(p).get() != nullptr); } // ----------------------------------------------------------------------------- // This is the actual templated algorithm // ----------------------------------------------------------------------------- void static Execute(ItkWriteImage* filter, DataContainer::Pointer m, QString attrMatName, IDataArray::Pointer inputDataArray, QString outputFile) { typename DataArrayType::Pointer inputDataPtr = std::dynamic_pointer_cast<DataArrayType>(inputDataArray); // Get a Raw Pointer to the data TInputType* inputData = inputDataPtr->getPointer(0); //size_t numVoxels = inputDataPtr->getNumberOfTuples(); //get utilities //get the total number of components of the data and switch accordingly int numComp = inputDataPtr->getNumberOfComponents(); itk::ProcessObject::Pointer writerObject; if(1 == numComp) //scalar image { typedef ItkBridge<TInputType> ItkBridgeType; //define types and wrap input image typedef typename ItkBridgeType::ScalarImageType ImageType; typename ImageType::Pointer inputImage = ItkBridgeType::CreateItkWrapperForDataPointer(m, attrMatName, inputData); //create writer and execute typedef itk::ImageFileWriter<ImageType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputFile.toLatin1().constData() ); writer->SetInput( inputImage ); writerObject = writer; } else if(3 == numComp)//rgb image { //define types and wrap input image typedef ItkBridge<TInputType> ItkBridgeType; //define types and wrap input image typedef typename ItkBridgeType::RGBImageType ImageType; typedef typename itk::ImageFileWriter<ImageType> WriterType; // typename ImageType::Pointer inputImage = ItkBridgeType::template Dream3DtoITKTemplate<ImageType>(m, attrMatName, inputData); typename ImageType::Pointer inputImage = ItkBridgeType::template Dream3DtoITKImportFilter<typename ImageType::PixelType>(m, attrMatName, inputData)->GetOutput(); //create writer and execute typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputFile.toLatin1().constData() ); writer->SetInput( inputImage ); writerObject = writer; } else if(4 == numComp)//rgba image { typedef ItkBridge<TInputType> ItkBridgeType; //define types and wrap input image typedef typename ItkBridgeType::RGBAImageType ImageType; typedef typename itk::ImageFileWriter<ImageType> WriterType; // typename ImageType::Pointer inputImage = ItkBridgeType::template Dream3DtoITKTemplate<ImageType>(m, attrMatName, inputData); typename ImageType::Pointer inputImage = ItkBridgeType::template Dream3DtoITKImportFilter<typename ImageType::PixelType>(m, attrMatName, inputData)->GetOutput(); //create writer and execute typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputFile.toLatin1().constData() ); writer->SetInput( inputImage ); writerObject = writer; } /** else//vector image { //define types and wrap input image typedef itk::Image<itk::FixedArray<TInputType, numComp> >, ImageProcessingConstants::ImageDimension> ImageType; typedef itk::ImageFileWriter<ImageType> WriterType; ImageType::Pointer inputImage = ItkBridgeType::Dream3DtoITKTemplate<ImageType>(m, attrMatName, inputData); //create writer and execute typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputFile.toLatin1().constData() ); writer->SetInput( inputImage ); writerObject = writer; }*/ try { writerObject->Update(); } catch( itk::ExceptionObject& err ) { filter->setErrorCondition(-5); QString ss = QObject::tr("Failed to write image. Error Message returned from ITK:\n %1").arg(err.GetDescription()); filter->notifyErrorMessage(filter->getHumanLabel(), ss, filter->getErrorCondition()); } } private: WriteImagePrivate(const WriteImagePrivate&); // Copy Constructor Not Implemented void operator=(const WriteImagePrivate&); // Operator '=' Not Implemented }; // Include the MOC generated file for this class #include "moc_ItkWriteImage.cpp" // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- ItkWriteImage::ItkWriteImage() : AbstractFilter(), m_SelectedCellArrayPath("", "", ""), m_OutputFileName(""), m_SelectedCellArray(nullptr) { setupFilterParameters(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- ItkWriteImage::~ItkWriteImage() { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void ItkWriteImage::setupFilterParameters() { FilterParameterVector parameters; parameters.push_back(SeparatorFilterParameter::New("Cell Data", FilterParameter::RequiredArray)); { DataArraySelectionFilterParameter::RequirementType req; parameters.push_back(SIMPL_NEW_DA_SELECTION_FP("Color Data", SelectedCellArrayPath, FilterParameter::RequiredArray, ItkWriteImage, req)); } parameters.push_back(SIMPL_NEW_OUTPUT_FILE_FP("Output File Name", OutputFileName, FilterParameter::Parameter, ItkWriteImage, "*.tif", "TIFF")); setFilterParameters(parameters); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void ItkWriteImage::readFilterParameters(AbstractFilterParametersReader* reader, int index) { reader->openFilterGroup(this, index); setSelectedCellArrayPath( reader->readDataArrayPath( "SelectedCellArrayPath", getSelectedCellArrayPath() ) ); setOutputFileName( reader->readString( "OutputFileName", getOutputFileName() ) ); reader->closeFilterGroup(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void ItkWriteImage::initialize() { } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void ItkWriteImage::dataCheck() { setErrorCondition(0); if(m_OutputFileName.isEmpty()) { QString ss = QObject::tr("Output file name/path was not given"); setErrorCondition(-100); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); return; } QFileInfo fi(m_OutputFileName); if(fi.suffix().compare("tif") != 0) { QString ss = QObject::tr("Image Stacks are only supported for TIFF formatted output"); setErrorCondition(-101); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); return; } //pass empty dimensions to allow any size QVector<size_t> compDims; m_SelectedCellArrayPtr = TemplateHelpers::GetPrereqArrayFromPath<AbstractFilter>()(this, getSelectedCellArrayPath(), compDims); if(nullptr != m_SelectedCellArrayPtr.lock().get()) { m_SelectedCellArray = m_SelectedCellArrayPtr.lock().get(); } if(getErrorCondition() < 0) { return; } getDataContainerArray()->getPrereqGeometryFromDataContainer<ImageGeom, AbstractFilter>(this, getSelectedCellArrayPath().getDataContainerName()); // Ignore returning from the dataCheck if this errors out. We are just trying to // ensure an ImageGeometry is selected. If code is added below that starts depending // on the image geometry, then the next line should be uncommented. //if(getErrorCondition() < 0 || nullptr == image.get()) { return; } //make sure dims of selected array are appropriate if(1 == compDims.size()) { if(1 == compDims[0]) //scalar { } else if (3 == compDims[0])//rgb { setWarningCondition(-100); notifyWarningMessage(getHumanLabel(), "Warning: writing of rgb images is currenlty experimental (unstable behavoir may occur)", getWarningCondition()); } else if (4 == compDims[0])//rgba { setWarningCondition(-101); notifyWarningMessage(getHumanLabel(), "Warning: writing of rgba images is currenlty experimental (unstable behavoir may occur)", getWarningCondition()); } else //vector { //notifyWarningMessage(getHumanLabel(), "Warning: writing of vector images is currenlty experimental (unstable behavoir may occur)", getWarningCondition()); setErrorCondition(-102); notifyErrorMessage(getHumanLabel(), "Error: writing of vector images is currently not supported", getErrorCondition()); } } else { QString message = QObject::tr("The selected array '%1' has unsupported dimensionality (%2)").arg(m_SelectedCellArrayPath.getDataArrayName()).arg(compDims.size()); setErrorCondition(-103); notifyErrorMessage(getHumanLabel(), message, getErrorCondition()); } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void ItkWriteImage::preflight() { // These are the REQUIRED lines of CODE to make sure the filter behaves correctly setInPreflight(true); // Set the fact that we are preflighting. emit preflightAboutToExecute(); // Emit this signal so that other widgets can do one file update emit updateFilterParameters(this); // Emit this signal to have the widgets push their values down to the filter dataCheck(); // Run our DataCheck to make sure everthing is setup correctly emit preflightExecuted(); // We are done preflighting this filter setInPreflight(false); // Inform the system this filter is NOT in preflight mode anymore. } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void ItkWriteImage::execute() { //int err = 0; dataCheck(); if(getErrorCondition() < 0) { return; } DataContainer::Pointer m = getDataContainerArray()->getDataContainer(getSelectedCellArrayPath().getDataContainerName()); QString attrMatName = getSelectedCellArrayPath().getAttributeMatrixName(); //get input data IDataArray::Pointer inputData = m_SelectedCellArrayPtr.lock(); if(WriteImagePrivate<int8_t>()(inputData)) { WriteImagePrivate<int8_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<uint8_t>()(inputData) ) { WriteImagePrivate<uint8_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<int16_t>()(inputData) ) { WriteImagePrivate<int16_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<uint16_t>()(inputData) ) { WriteImagePrivate<uint16_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<int32_t>()(inputData) ) { WriteImagePrivate<int32_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<uint32_t>()(inputData) ) { WriteImagePrivate<uint32_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<int64_t>()(inputData) ) { WriteImagePrivate<int64_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<uint64_t>()(inputData) ) { WriteImagePrivate<uint64_t>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<float>()(inputData) ) { WriteImagePrivate<float>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else if(WriteImagePrivate<double>()(inputData) ) { WriteImagePrivate<double>::Execute(this, m, attrMatName, inputData, m_OutputFileName); } else { setErrorCondition(-10001); QString ss = QObject::tr("A Supported DataArray type was not used for an input array."); notifyErrorMessage(getHumanLabel(), ss, getErrorCondition()); return; } /* Let the GUI know we are done with this filter */ notifyStatusMessage(getHumanLabel(), "Complete"); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- AbstractFilter::Pointer ItkWriteImage::newFilterInstance(bool copyFilterParameters) { ItkWriteImage::Pointer filter = ItkWriteImage::New(); if(true == copyFilterParameters) { copyFilterParameterInstanceVariables(filter.get()); } return filter; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString ItkWriteImage::getCompiledLibraryName() {return ImageProcessingConstants::ImageProcessingBaseName;} // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString ItkWriteImage::getGroupName() {return SIMPL::FilterGroups::Unsupported;} // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString ItkWriteImage::getSubGroupName() {return "IO";} // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- const QString ItkWriteImage::getHumanLabel() { return "Export Tiff Image Stack (ImageProcessing)"; } <|endoftext|>
<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <random> #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/math/math_function.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; using LoDTensor = framework::LoDTensor; template <typename T, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>; class RpnTargetAssignOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("DistMat"), "Input(DistMat) of RpnTargetAssignOp should not be null"); PADDLE_ENFORCE( ctx->HasOutput("LocationIndex"), "Output(LocationIndex) of RpnTargetAssignOp should not be null"); PADDLE_ENFORCE( ctx->HasOutput("ScoreIndex"), "Output(ScoreIndex) of RpnTargetAssignOp should not be null"); PADDLE_ENFORCE( ctx->HasOutput("TargetLabel"), "Output(TargetLabel) of RpnTargetAssignOp should not be null"); auto in_dims = ctx->GetInputDim("DistMat"); PADDLE_ENFORCE_EQ(in_dims.size(), 2, "The rank of Input(DistMat) must be 2."); } }; template <typename T> class RpnTargetAssignKernel : public framework::OpKernel<T> { public: void ScoreAssign(const T* dist_data, const Tensor& anchor_to_gt_max, const int row, const int col, const float pos_threshold, const float neg_threshold, int64_t* target_label_data, std::vector<int>* fg_inds, std::vector<int>* bg_inds) const { int fg_offset = fg_inds->size(); int bg_offset = bg_inds->size(); for (int64_t i = 0; i < row; ++i) { const T* v = dist_data + i * col; T max_dist = *std::max_element(v, v + col); for (int64_t j = 0; j < col; ++j) { T val = dist_data[i * col + j]; if (val == max_dist) target_label_data[j] = 1; } } // Pick the fg/bg and count the number for (int64_t j = 0; j < col; ++j) { if (anchor_to_gt_max.data<T>()[j] > pos_threshold) { target_label_data[j] = 1; } else if (anchor_to_gt_max.data<T>()[j] < neg_threshold) { target_label_data[j] = 0; } if (target_label_data[j] == 1) { fg_inds->push_back(fg_offset + j); } else if (target_label_data[j] == 0) { bg_inds->push_back(bg_offset + j); } } } void ReservoirSampling(const int num, const int offset, std::minstd_rand engine, std::vector<int>* inds) const { std::uniform_real_distribution<float> uniform(0, 1); if (inds->size() > num) { for (int i = num; i < inds->size(); ++i) { int rng_ind = std::floor(uniform(engine) * i); if (rng_ind < num) std::iter_swap(inds->begin() + rng_ind + offset, inds->begin() + i + offset); } } } void RpnTargetAssign(const framework::ExecutionContext& ctx, const Tensor& dist, const float pos_threshold, const float neg_threshold, const int rpn_batch_size, const int fg_num, std::minstd_rand engine, std::vector<int>* fg_inds, std::vector<int>* bg_inds, int64_t* target_label_data) const { auto* dist_data = dist.data<T>(); int64_t row = dist.dims()[0]; int64_t col = dist.dims()[1]; int fg_offset = fg_inds->size(); int bg_offset = bg_inds->size(); // Calculate the max IoU between anchors and gt boxes Tensor anchor_to_gt_max; anchor_to_gt_max.mutable_data<T>( framework::make_ddim({static_cast<int64_t>(col), 1}), platform::CPUPlace()); auto& place = *ctx.template device_context<platform::CPUDeviceContext>() .eigen_device(); auto x = EigenMatrix<T>::From(dist); auto x_col_max = EigenMatrix<T>::From(anchor_to_gt_max); x_col_max.device(place) = x.maximum(Eigen::DSizes<int, 1>(0)) .reshape(Eigen::DSizes<int, 2>(static_cast<int64_t>(col), 1)); // Follow the Faster RCNN's implementation ScoreAssign(dist_data, anchor_to_gt_max, row, col, pos_threshold, neg_threshold, target_label_data, fg_inds, bg_inds); // Reservoir Sampling ReservoirSampling(fg_num, fg_offset, engine, fg_inds); int bg_num = rpn_batch_size - fg_inds->size(); ReservoirSampling(bg_num, bg_offset, engine, bg_inds); } void Compute(const framework::ExecutionContext& context) const override { auto* dist = context.Input<LoDTensor>("DistMat"); auto* loc_index = context.Output<Tensor>("LocationIndex"); auto* score_index = context.Output<Tensor>("ScoreIndex"); auto* tgt_lbl = context.Output<Tensor>("TargetLabel"); auto col = dist->dims()[1]; int64_t n = dist->lod().size() == 0UL ? 1 : static_cast<int64_t>(dist->lod().back().size() - 1); if (dist->lod().size()) { PADDLE_ENFORCE_EQ(dist->lod().size(), 1UL, "Only support 1 level of LoD."); } int rpn_batch_size = context.Attr<int>("rpn_batch_size_per_im"); float pos_threshold = context.Attr<float>("rpn_positive_overlap"); float neg_threshold = context.Attr<float>("rpn_negative_overlap"); float fg_fraction = context.Attr<float>("fg_fraction"); int fg_num = static_cast<int>(rpn_batch_size * fg_fraction); int64_t* target_label_data = tgt_lbl->mutable_data<int64_t>({n * col, 1}, context.GetPlace()); auto& dev_ctx = context.device_context<platform::CPUDeviceContext>(); math::SetConstant<platform::CPUDeviceContext, int64_t> iset; iset(dev_ctx, tgt_lbl, static_cast<int>(-1)); std::vector<int> fg_inds; std::vector<int> bg_inds; std::random_device rnd; std::minstd_rand engine; int seed = context.Attr<bool>("fix_seed") ? context.Attr<int>("seed") : rnd(); engine.seed(seed); if (n == 1) { RpnTargetAssign(context, *dist, pos_threshold, neg_threshold, rpn_batch_size, fg_num, engine, &fg_inds, &bg_inds, target_label_data); } else { auto lod = dist->lod().back(); for (size_t i = 0; i < lod.size() - 1; ++i) { Tensor one_ins = dist->Slice(lod[i], lod[i + 1]); RpnTargetAssign(context, one_ins, pos_threshold, neg_threshold, rpn_batch_size, fg_num, engine, &fg_inds, &bg_inds, target_label_data + i * col); } } int* loc_index_data = loc_index->mutable_data<int>( {static_cast<int>(fg_inds.size())}, context.GetPlace()); int* score_index_data = score_index->mutable_data<int>( {static_cast<int>(fg_inds.size() + bg_inds.size())}, context.GetPlace()); memcpy(loc_index_data, reinterpret_cast<int*>(&fg_inds[0]), fg_inds.size() * sizeof(int)); memcpy(score_index_data, reinterpret_cast<int*>(&fg_inds[0]), fg_inds.size() * sizeof(int)); memcpy(score_index_data + fg_inds.size(), reinterpret_cast<int*>(&bg_inds[0]), bg_inds.size() * sizeof(int)); } }; class RpnTargetAssignOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput( "DistMat", "(LoDTensor or Tensor) this input is a 2-D LoDTensor with shape " "[K, M]. It is pair-wise distance matrix between the entities " "represented by each row and each column. For example, assumed one " "entity is A with shape [K], another entity is B with shape [M]. The " "DistMat[i][j] is the distance between A[i] and B[j]. The bigger " "the distance is, the better macthing the pairs are. Please note, " "This tensor can contain LoD information to represent a batch of " "inputs. One instance of this batch can contain different numbers of " "entities."); AddAttr<float>( "rpn_positive_overlap", "Minimum overlap required between an anchor and ground-truth " "box for the (anchor, gt box) pair to be a positive example.") .SetDefault(0.7); AddAttr<float>( "rpn_negative_overlap", "Maximum overlap allowed between an anchor and ground-truth " "box for the (anchor, gt box) pair to be a negative examples.") .SetDefault(0.3); AddAttr<float>( "fg_fraction", "Target fraction of RoI minibatch that " "is labeled foreground (i.e. class > 0), 0-th class is background.") .SetDefault(0.25); AddAttr<int>("rpn_batch_size_per_im", "Total number of RPN examples per image.") .SetDefault(256); AddAttr<bool>("fix_seed", "A flag indicating whether to use a fixed seed to generate " "random mask. NOTE: DO NOT set this flag to true in " "training. Setting this flag to true is only useful in " "unittest.") .SetDefault(false); AddAttr<int>("seed", "RpnTargetAssign random seed.").SetDefault(0); AddOutput( "LocationIndex", "(Tensor), The indexes of foreground anchors in all RPN anchors, the " "shape of the LocationIndex is [F], F depends on the value of input " "tensor and attributes."); AddOutput( "ScoreIndex", "(Tensor), The indexes of foreground and background anchors in all " "RPN anchors(The rest anchors are ignored). The shape of the " "ScoreIndex is [F + B], F and B depend on the value of input " "tensor and attributes."); AddOutput("TargetLabel", "(Tensor<int64_t>), The target labels of each anchor with shape " "[K * M, 1], " "K and M is the same as they are in DistMat."); AddComment(R"DOC( This operator can be, for given the IoU between the ground truth bboxes and the anchors, to assign classification and regression targets to each prediction. The Score index and LocationIndex will be generated according to the DistMat. The rest anchors would not contibute to the RPN training loss ScoreIndex is composed of foreground anchor indexes(positive labels) and background anchor indexes(negative labels). LocationIndex is exactly same as the foreground anchor indexes since we can not assign regression target to the background anchors. The classification targets(TargetLabel) is a binary class label (of being an object or not). Following the paper of Faster-RCNN, the positive labels are two kinds of anchors: (i) the anchor/anchors with the highest IoU overlap with a ground-truth box, or (ii) an anchor that has an IoU overlap higher than rpn_positive_overlap(0.7) with any ground-truth box. Note that a single ground-truth box may assign positive labels to multiple anchors. A non-positive anchor is when its IoU ratio is lower than rpn_negative_overlap (0.3) for all ground-truth boxes. Anchors that are neither positive nor negative do not contribute to the training objective. )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(rpn_target_assign, ops::RpnTargetAssignOp, ops::RpnTargetAssignOpMaker, paddle::framework::EmptyGradOpMaker); REGISTER_OP_CPU_KERNEL(rpn_target_assign, ops::RpnTargetAssignKernel<float>, ops::RpnTargetAssignKernel<double>); <commit_msg>fix warning<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <random> #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/math/math_function.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; using LoDTensor = framework::LoDTensor; template <typename T, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>; class RpnTargetAssignOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext* ctx) const override { PADDLE_ENFORCE(ctx->HasInput("DistMat"), "Input(DistMat) of RpnTargetAssignOp should not be null"); PADDLE_ENFORCE( ctx->HasOutput("LocationIndex"), "Output(LocationIndex) of RpnTargetAssignOp should not be null"); PADDLE_ENFORCE( ctx->HasOutput("ScoreIndex"), "Output(ScoreIndex) of RpnTargetAssignOp should not be null"); PADDLE_ENFORCE( ctx->HasOutput("TargetLabel"), "Output(TargetLabel) of RpnTargetAssignOp should not be null"); auto in_dims = ctx->GetInputDim("DistMat"); PADDLE_ENFORCE_EQ(in_dims.size(), 2, "The rank of Input(DistMat) must be 2."); } }; template <typename T> class RpnTargetAssignKernel : public framework::OpKernel<T> { public: void ScoreAssign(const T* dist_data, const Tensor& anchor_to_gt_max, const int row, const int col, const float pos_threshold, const float neg_threshold, int64_t* target_label_data, std::vector<int>* fg_inds, std::vector<int>* bg_inds) const { int fg_offset = fg_inds->size(); int bg_offset = bg_inds->size(); for (int64_t i = 0; i < row; ++i) { const T* v = dist_data + i * col; T max_dist = *std::max_element(v, v + col); for (int64_t j = 0; j < col; ++j) { T val = dist_data[i * col + j]; if (val == max_dist) target_label_data[j] = 1; } } // Pick the fg/bg and count the number for (int64_t j = 0; j < col; ++j) { if (anchor_to_gt_max.data<T>()[j] > pos_threshold) { target_label_data[j] = 1; } else if (anchor_to_gt_max.data<T>()[j] < neg_threshold) { target_label_data[j] = 0; } if (target_label_data[j] == 1) { fg_inds->push_back(fg_offset + j); } else if (target_label_data[j] == 0) { bg_inds->push_back(bg_offset + j); } } } void ReservoirSampling(const int num, const int offset, std::minstd_rand engine, std::vector<int>* inds) const { std::uniform_real_distribution<float> uniform(0, 1); const int64_t size = static_cast<int64_t>(inds->size()); if (size > num) { for (int64_t i = num; i < size; ++i) { int rng_ind = std::floor(uniform(engine) * i); if (rng_ind < num) std::iter_swap(inds->begin() + rng_ind + offset, inds->begin() + i + offset); } } } void RpnTargetAssign(const framework::ExecutionContext& ctx, const Tensor& dist, const float pos_threshold, const float neg_threshold, const int rpn_batch_size, const int fg_num, std::minstd_rand engine, std::vector<int>* fg_inds, std::vector<int>* bg_inds, int64_t* target_label_data) const { auto* dist_data = dist.data<T>(); int64_t row = dist.dims()[0]; int64_t col = dist.dims()[1]; int fg_offset = fg_inds->size(); int bg_offset = bg_inds->size(); // Calculate the max IoU between anchors and gt boxes Tensor anchor_to_gt_max; anchor_to_gt_max.mutable_data<T>( framework::make_ddim({static_cast<int64_t>(col), 1}), platform::CPUPlace()); auto& place = *ctx.template device_context<platform::CPUDeviceContext>() .eigen_device(); auto x = EigenMatrix<T>::From(dist); auto x_col_max = EigenMatrix<T>::From(anchor_to_gt_max); x_col_max.device(place) = x.maximum(Eigen::DSizes<int, 1>(0)) .reshape(Eigen::DSizes<int, 2>(static_cast<int64_t>(col), 1)); // Follow the Faster RCNN's implementation ScoreAssign(dist_data, anchor_to_gt_max, row, col, pos_threshold, neg_threshold, target_label_data, fg_inds, bg_inds); // Reservoir Sampling ReservoirSampling(fg_num, fg_offset, engine, fg_inds); int bg_num = rpn_batch_size - fg_inds->size(); ReservoirSampling(bg_num, bg_offset, engine, bg_inds); } void Compute(const framework::ExecutionContext& context) const override { auto* dist = context.Input<LoDTensor>("DistMat"); auto* loc_index = context.Output<Tensor>("LocationIndex"); auto* score_index = context.Output<Tensor>("ScoreIndex"); auto* tgt_lbl = context.Output<Tensor>("TargetLabel"); auto col = dist->dims()[1]; int64_t n = dist->lod().size() == 0UL ? 1 : static_cast<int64_t>(dist->lod().back().size() - 1); if (dist->lod().size()) { PADDLE_ENFORCE_EQ(dist->lod().size(), 1UL, "Only support 1 level of LoD."); } int rpn_batch_size = context.Attr<int>("rpn_batch_size_per_im"); float pos_threshold = context.Attr<float>("rpn_positive_overlap"); float neg_threshold = context.Attr<float>("rpn_negative_overlap"); float fg_fraction = context.Attr<float>("fg_fraction"); int fg_num = static_cast<int>(rpn_batch_size * fg_fraction); int64_t* target_label_data = tgt_lbl->mutable_data<int64_t>({n * col, 1}, context.GetPlace()); auto& dev_ctx = context.device_context<platform::CPUDeviceContext>(); math::SetConstant<platform::CPUDeviceContext, int64_t> iset; iset(dev_ctx, tgt_lbl, static_cast<int>(-1)); std::vector<int> fg_inds; std::vector<int> bg_inds; std::random_device rnd; std::minstd_rand engine; int seed = context.Attr<bool>("fix_seed") ? context.Attr<int>("seed") : rnd(); engine.seed(seed); if (n == 1) { RpnTargetAssign(context, *dist, pos_threshold, neg_threshold, rpn_batch_size, fg_num, engine, &fg_inds, &bg_inds, target_label_data); } else { auto lod = dist->lod().back(); for (size_t i = 0; i < lod.size() - 1; ++i) { Tensor one_ins = dist->Slice(lod[i], lod[i + 1]); RpnTargetAssign(context, one_ins, pos_threshold, neg_threshold, rpn_batch_size, fg_num, engine, &fg_inds, &bg_inds, target_label_data + i * col); } } int* loc_index_data = loc_index->mutable_data<int>( {static_cast<int>(fg_inds.size())}, context.GetPlace()); int* score_index_data = score_index->mutable_data<int>( {static_cast<int>(fg_inds.size() + bg_inds.size())}, context.GetPlace()); memcpy(loc_index_data, reinterpret_cast<int*>(&fg_inds[0]), fg_inds.size() * sizeof(int)); memcpy(score_index_data, reinterpret_cast<int*>(&fg_inds[0]), fg_inds.size() * sizeof(int)); memcpy(score_index_data + fg_inds.size(), reinterpret_cast<int*>(&bg_inds[0]), bg_inds.size() * sizeof(int)); } }; class RpnTargetAssignOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddInput( "DistMat", "(LoDTensor or Tensor) this input is a 2-D LoDTensor with shape " "[K, M]. It is pair-wise distance matrix between the entities " "represented by each row and each column. For example, assumed one " "entity is A with shape [K], another entity is B with shape [M]. The " "DistMat[i][j] is the distance between A[i] and B[j]. The bigger " "the distance is, the better macthing the pairs are. Please note, " "This tensor can contain LoD information to represent a batch of " "inputs. One instance of this batch can contain different numbers of " "entities."); AddAttr<float>( "rpn_positive_overlap", "Minimum overlap required between an anchor and ground-truth " "box for the (anchor, gt box) pair to be a positive example.") .SetDefault(0.7); AddAttr<float>( "rpn_negative_overlap", "Maximum overlap allowed between an anchor and ground-truth " "box for the (anchor, gt box) pair to be a negative examples.") .SetDefault(0.3); AddAttr<float>( "fg_fraction", "Target fraction of RoI minibatch that " "is labeled foreground (i.e. class > 0), 0-th class is background.") .SetDefault(0.25); AddAttr<int>("rpn_batch_size_per_im", "Total number of RPN examples per image.") .SetDefault(256); AddAttr<bool>("fix_seed", "A flag indicating whether to use a fixed seed to generate " "random mask. NOTE: DO NOT set this flag to true in " "training. Setting this flag to true is only useful in " "unittest.") .SetDefault(false); AddAttr<int>("seed", "RpnTargetAssign random seed.").SetDefault(0); AddOutput( "LocationIndex", "(Tensor), The indexes of foreground anchors in all RPN anchors, the " "shape of the LocationIndex is [F], F depends on the value of input " "tensor and attributes."); AddOutput( "ScoreIndex", "(Tensor), The indexes of foreground and background anchors in all " "RPN anchors(The rest anchors are ignored). The shape of the " "ScoreIndex is [F + B], F and B depend on the value of input " "tensor and attributes."); AddOutput("TargetLabel", "(Tensor<int64_t>), The target labels of each anchor with shape " "[K * M, 1], " "K and M is the same as they are in DistMat."); AddComment(R"DOC( This operator can be, for given the IoU between the ground truth bboxes and the anchors, to assign classification and regression targets to each prediction. The Score index and LocationIndex will be generated according to the DistMat. The rest anchors would not contibute to the RPN training loss ScoreIndex is composed of foreground anchor indexes(positive labels) and background anchor indexes(negative labels). LocationIndex is exactly same as the foreground anchor indexes since we can not assign regression target to the background anchors. The classification targets(TargetLabel) is a binary class label (of being an object or not). Following the paper of Faster-RCNN, the positive labels are two kinds of anchors: (i) the anchor/anchors with the highest IoU overlap with a ground-truth box, or (ii) an anchor that has an IoU overlap higher than rpn_positive_overlap(0.7) with any ground-truth box. Note that a single ground-truth box may assign positive labels to multiple anchors. A non-positive anchor is when its IoU ratio is lower than rpn_negative_overlap (0.3) for all ground-truth boxes. Anchors that are neither positive nor negative do not contribute to the training objective. )DOC"); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OPERATOR(rpn_target_assign, ops::RpnTargetAssignOp, ops::RpnTargetAssignOpMaker, paddle::framework::EmptyGradOpMaker); REGISTER_OP_CPU_KERNEL(rpn_target_assign, ops::RpnTargetAssignKernel<float>, ops::RpnTargetAssignKernel<double>); <|endoftext|>
<commit_before>#include "buffer/core.h" #include "allocators/scalloc_core-inl.h" #include "spinlock-inl.h" #include "typed_allocator.h" #include "utils.h" namespace { scalloc::TypedAllocator<scalloc::CoreBuffer> core_buffer_alloc; SpinLock new_buffer_lock(LINKER_INITIALIZED); } namespace scalloc { uint64_t CoreBuffer::num_cores_; pthread_key_t CoreBuffer::core_key; uint64_t CoreBuffer::thread_counter_; uint64_t CoreBuffer::active_threads_; CoreBuffer* CoreBuffer::buffers_[CoreBuffer::kMaxCores]; void CoreBuffer::Init() { for (uint64_t i = 0; i < kMaxCores; i++) { buffers_[i] = NULL; } num_cores_ = utils::Cpus(); thread_counter_ = 0; active_threads_ = 0; core_buffer_alloc.Init(kPageSize, 64, "core_buffer_alloc"); pthread_key_create(&core_key, CoreBuffer::ThreadDestructor); } CoreBuffer::CoreBuffer(uint64_t core_id) { allocator_ = ScallocCore<LockMode::kSizeClassLocked>::New(core_id); num_threads_ = 1; #ifdef PROFILER profiler_.Init(&GlobalProfiler); #endif // PROFILER } CoreBuffer* CoreBuffer::NewIfNecessary(uint64_t core_id) { LockScope(new_buffer_lock); if (buffers_[core_id] == NULL) { buffers_[core_id] = new(core_buffer_alloc.New()) CoreBuffer(core_id); } return buffers_[core_id]; } void CoreBuffer::DestroyBuffers() { for (uint64_t i = 0; i < kMaxCores; i++) { if (buffers_[i] != NULL) { ScallocCore<LockMode::kSizeClassLocked>::Destroy(buffers_[i]->Allocator()); #ifdef PROFILER buffers_[i]->profiler_.Report(); #endif // PROFILER } } } void CoreBuffer::ThreadDestructor(void* core_buffer) { __sync_fetch_and_sub(&active_threads_, 1); } } <commit_msg>Switch lock type for core buffer allocation. Needs to be adjusted for OSX.<commit_after>#include "buffer/core.h" #include "allocators/scalloc_core-inl.h" #include "common.h" #include "spinlock-inl.h" #include "typed_allocator.h" #include "utils.h" namespace { cache_aligned scalloc::TypedAllocator<scalloc::CoreBuffer> core_buffer_alloc; cache_aligned FastLock new_buffer_lock; } namespace scalloc { uint64_t CoreBuffer::num_cores_; pthread_key_t CoreBuffer::core_key; uint64_t CoreBuffer::thread_counter_; uint64_t CoreBuffer::active_threads_; CoreBuffer* CoreBuffer::buffers_[CoreBuffer::kMaxCores]; void CoreBuffer::Init() { for (uint64_t i = 0; i < kMaxCores; i++) { buffers_[i] = NULL; } new_buffer_lock.Init(); num_cores_ = utils::Cpus(); thread_counter_ = 0; active_threads_ = 0; core_buffer_alloc.Init(kPageSize, 64, "core_buffer_alloc"); pthread_key_create(&core_key, CoreBuffer::ThreadDestructor); } CoreBuffer::CoreBuffer(uint64_t core_id) { allocator_ = ScallocCore<LockMode::kSizeClassLocked>::New(core_id); num_threads_ = 1; #ifdef PROFILER profiler_.Init(&GlobalProfiler); #endif // PROFILER } CoreBuffer* CoreBuffer::NewIfNecessary(uint64_t core_id) { FastLockScope(new_buffer_lock); if (buffers_[core_id] == NULL) { buffers_[core_id] = new(core_buffer_alloc.New()) CoreBuffer(core_id); } return buffers_[core_id]; } void CoreBuffer::DestroyBuffers() { for (uint64_t i = 0; i < kMaxCores; i++) { if (buffers_[i] != NULL) { ScallocCore<LockMode::kSizeClassLocked>::Destroy(buffers_[i]->Allocator()); #ifdef PROFILER buffers_[i]->profiler_.Report(); #endif // PROFILER } } } void CoreBuffer::ThreadDestructor(void* core_buffer) { __sync_fetch_and_sub(&active_threads_, 1); } } <|endoftext|>
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. 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. #pragma once #include <memory> #include <type_traits> namespace iox { namespace cxx { /// @brief cxx::function_ref is a lightweight alternative to std::function /// /// It is a non-owning reference to a callable. /// /// It shall have these features: /// * No heap usage /// * No exceptions /// * Stateful lambda support /// * C++11/14 support /// @code /// // Usage as function parameter /// void fuu(cxx::function_ref<void()> callback) /// { /// callback(); /// } /// // Call the lambda /// fuu([]{ doSomething(); }); /// /// // Usage with l-values /// // Pitfall: Ensure that lifetime of callable suits the point in time of calling callback() /// auto callable = [&]{ doSomething(); }; /// cxx::function_ref<void()> callback(callable); /// // Call the callback /// callback(); /// @endcode template <typename SignatureType> class function_ref; template <class ReturnType, class... ArgTypes> class function_ref<ReturnType(ArgTypes...)> { using SignatureType = ReturnType(ArgTypes...); public: /// @brief Creates an empty function_ref function_ref() noexcept : m_target(nullptr) , m_functionPointer(nullptr) { } /// @brief Creates an empty function_ref function_ref(nullptr_t) noexcept : m_target(nullptr) , m_functionPointer(nullptr) { } /// @brief D'tor ~function_ref() noexcept = default; /// @brief No copy c'tor /// @todo test this function_ref(const function_ref&) noexcept = delete; /// @brief No copy assignment function_ref& operator=(const function_ref&) noexcept = default; /// @brief Create a function_ref /// @todo Type trait std::is_invocable is only available in C++17, workaround for C++11/14? template <typename CallableType, typename = std::enable_if<!std::is_same<std::decay<CallableType>, function_ref>::value>> function_ref(CallableType&& callable) noexcept : m_target(reinterpret_cast<void*>(std::addressof(callable))) { m_functionPointer = [](void* target, ArgTypes... args) -> ReturnType { return (*reinterpret_cast<typename std::add_pointer<CallableType>::type>(target))( std::forward<ArgTypes>(args)...); }; } /// @brief Move assignment function_ref& operator=(function_ref&& rhs) noexcept = default; /// @brief Calls the provided callable auto operator()(ArgTypes... args) const noexcept -> ReturnType { if (!m_target) { // Callable was called without user having assigned one beforehand std::terminate(); } return m_functionPointer(m_target, std::forward<ArgTypes>(args)...); } /// @brief Checks whether a valid target is contained explicit operator bool() const noexcept { return m_target != nullptr; } void swap(function_ref<SignatureType>& rhs) noexcept { std::swap(m_target, rhs.m_target); std::swap(m_functionPointer, rhs.m_functionPointer); } /// @todo Be closer to std::function API // target() ? // target_type() ? private: /// @brief Raw pointer of the callable void* m_target{nullptr}; /// @brief Function pointer to the callable ReturnType (*m_functionPointer)(void*, ArgTypes...){nullptr}; }; template <class ReturnType, class... ArgTypes> void swap(function_ref<ReturnType(ArgTypes...)>& lhs, function_ref<ReturnType(ArgTypes...)>& rhs) noexcept { lhs.swap(rhs); } } // namespace cxx } // namespace iox <commit_msg>iox-#86 Add review comment by Mathias Kraus<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. 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. #pragma once #include <memory> #include <type_traits> namespace iox { namespace cxx { /// @brief cxx::function_ref is a lightweight alternative to std::function /// /// It is a non-owning reference to a callable. /// /// It shall have these features: /// * No heap usage /// * No exceptions /// * Stateful lambda support /// * C++11/14 support /// @code /// // Usage as function parameter /// void fuu(cxx::function_ref<void()> callback) /// { /// callback(); /// } /// // Call the lambda /// fuu([]{ doSomething(); }); /// /// // Usage with l-values /// // Pitfall: Ensure that lifetime of callable suits the point in time of calling callback() /// auto callable = [&]{ doSomething(); }; /// cxx::function_ref<void()> callback(callable); /// // Call the callback /// callback(); /// @endcode template <typename SignatureType> class function_ref; template <class ReturnType, class... ArgTypes> class function_ref<ReturnType(ArgTypes...)> { using SignatureType = ReturnType(ArgTypes...); public: /// @todo Remove empty instantiation , if you want to have it empty, use an cxx::optional around cxx::function_ref /// @brief Creates an empty function_ref function_ref() noexcept : m_target(nullptr) , m_functionPointer(nullptr) { } /// @brief Creates an empty function_ref function_ref(nullptr_t) noexcept : m_target(nullptr) , m_functionPointer(nullptr) { } /// @brief D'tor ~function_ref() noexcept = default; /// @brief No copy c'tor /// @todo test this function_ref(const function_ref&) noexcept = delete; /// @brief No copy assignment function_ref& operator=(const function_ref&) noexcept = default; /// @brief Create a function_ref /// @todo Type trait std::is_invocable is only available in C++17, workaround for C++11/14? template <typename CallableType, typename = std::enable_if<!std::is_same<std::decay<CallableType>, function_ref>::value>> function_ref(CallableType&& callable) noexcept : m_target(reinterpret_cast<void*>(std::addressof(callable))) { m_functionPointer = [](void* target, ArgTypes... args) -> ReturnType { return (*reinterpret_cast<typename std::add_pointer<CallableType>::type>(target))( std::forward<ArgTypes>(args)...); }; } /// @brief Move assignment function_ref& operator=(function_ref&& rhs) noexcept = default; /// @brief Calls the provided callable auto operator()(ArgTypes... args) const noexcept -> ReturnType { if (!m_target) { // Callable was called without user having assigned one beforehand std::terminate(); } return m_functionPointer(m_target, std::forward<ArgTypes>(args)...); } /// @brief Checks whether a valid target is contained explicit operator bool() const noexcept { return m_target != nullptr; } void swap(function_ref<SignatureType>& rhs) noexcept { std::swap(m_target, rhs.m_target); std::swap(m_functionPointer, rhs.m_functionPointer); } /// @todo Be closer to std::function API // target() ? // target_type() ? private: /// @brief Raw pointer of the callable void* m_target{nullptr}; /// @brief Function pointer to the callable ReturnType (*m_functionPointer)(void*, ArgTypes...){nullptr}; }; template <class ReturnType, class... ArgTypes> void swap(function_ref<ReturnType(ArgTypes...)>& lhs, function_ref<ReturnType(ArgTypes...)>& rhs) noexcept { lhs.swap(rhs); } } // namespace cxx } // namespace iox <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUIClipboard.cpp created: 28/5/2011 author: Martin Preisler purpose: Implements platform independent clipboard handling *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUIClipboard.h" // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// Clipboard::Clipboard(): d_mimeType("text/plain"), // reasonable default I think d_buffer(0), d_bufferSize(0), d_nativeProvider(0) {} //----------------------------------------------------------------------------// Clipboard::~Clipboard() { if (d_buffer != 0) { CEGUI_DELETE_ARRAY_PT(d_buffer, void, d_bufferSize, Clipboard); } } //----------------------------------------------------------------------------// void Clipboard::setNativeProvider(NativeClipboardProvider* provider) { d_nativeProvider = provider; } //----------------------------------------------------------------------------// NativeClipboardProvider* Clipboard::getNativeProvider() const { return d_nativeProvider; } //----------------------------------------------------------------------------// void Clipboard::setData(const String& mimeType, const void* buffer, size_t size) { d_mimeType = mimeType; if (size != d_bufferSize) { if (d_buffer != 0) { CEGUI_DELETE_ARRAY_PT(d_buffer, BufferElement, d_bufferSize, Clipboard); d_buffer = 0; } d_bufferSize = size; d_buffer = CEGUI_NEW_ARRAY_PT(BufferElement, d_bufferSize, Clipboard); } memcpy(d_buffer, buffer, d_bufferSize); // we have set the data to the internal clipboard, now sync it with the // system-wide native clipboard if possible if (d_nativeProvider) { d_nativeProvider->sendToClipboard(d_mimeType, d_buffer, d_bufferSize); } } //----------------------------------------------------------------------------// void Clipboard::getData(String& mimeType, const void*& buffer, size_t& size) { // first make sure we are in sync with system-wide native clipboard // (if possible) if (d_nativeProvider) { size_t size; void* buffer; d_nativeProvider->retrieveFromClipboard(d_mimeType, buffer, size); if (size != d_bufferSize) { if (d_buffer != 0) { CEGUI_DELETE_ARRAY_PT(d_buffer, BufferElement, d_bufferSize, Clipboard); d_buffer = 0; } d_bufferSize = size; d_buffer = CEGUI_NEW_ARRAY_PT(BufferElement, d_bufferSize, Clipboard); } memcpy(d_buffer, buffer, size); } mimeType = d_mimeType; buffer = d_buffer; size = d_bufferSize; } //----------------------------------------------------------------------------// void Clipboard::setText(const String& text) { // could be just ASCII if std::string is used as CEGUI::String const char* utf8 = text.c_str(); // we don't want the actual string length, that might not be the buffer size // in case of utf8! // this gets us the number of bytes until \0 is encountered const size_t size = strlen(utf8); setData("text/plain", static_cast<const void*>(utf8), size); } //----------------------------------------------------------------------------// String Clipboard::getText() { String mimeType; const void* buffer; size_t size; // we have to use this, can't use the member variables directly because of // the native clipboard provider! getData(mimeType, buffer, size); if (mimeType == "text/plain" && size != 0) { // d_buffer an utf8 or ASCII C string (ASCII if std::string is used) // !!! However it is not null terminated !!! So we have to tell String // how many code units (not code points!) there are. return String(static_cast<const char*>(d_buffer), d_bufferSize); } else { // the held mime type differs, it's not plain text so we can't // return it as just string return String(); } } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>FIX: NativeClipboardProvider was lacking a destructor impl FIX: shadowing of variables causing unreadable code in Clipboard<commit_after>/*********************************************************************** filename: CEGUIClipboard.cpp created: 28/5/2011 author: Martin Preisler purpose: Implements platform independent clipboard handling *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2011 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUIClipboard.h" // Start of CEGUI namespace section namespace CEGUI { NativeClipboardProvider::~NativeClipboardProvider() {} //----------------------------------------------------------------------------// Clipboard::Clipboard(): d_mimeType("text/plain"), // reasonable default I think d_buffer(0), d_bufferSize(0), d_nativeProvider(0) {} //----------------------------------------------------------------------------// Clipboard::~Clipboard() { if (d_buffer != 0) { CEGUI_DELETE_ARRAY_PT(d_buffer, void, d_bufferSize, Clipboard); } } //----------------------------------------------------------------------------// void Clipboard::setNativeProvider(NativeClipboardProvider* provider) { d_nativeProvider = provider; } //----------------------------------------------------------------------------// NativeClipboardProvider* Clipboard::getNativeProvider() const { return d_nativeProvider; } //----------------------------------------------------------------------------// void Clipboard::setData(const String& mimeType, const void* buffer, size_t size) { d_mimeType = mimeType; if (size != d_bufferSize) { if (d_buffer != 0) { CEGUI_DELETE_ARRAY_PT(d_buffer, BufferElement, d_bufferSize, Clipboard); d_buffer = 0; } d_bufferSize = size; d_buffer = CEGUI_NEW_ARRAY_PT(BufferElement, d_bufferSize, Clipboard); } memcpy(d_buffer, buffer, d_bufferSize); // we have set the data to the internal clipboard, now sync it with the // system-wide native clipboard if possible if (d_nativeProvider) { d_nativeProvider->sendToClipboard(d_mimeType, d_buffer, d_bufferSize); } } //----------------------------------------------------------------------------// void Clipboard::getData(String& mimeType, const void*& buffer, size_t& size) { // first make sure we are in sync with system-wide native clipboard // (if possible) if (d_nativeProvider) { size_t retrievedSize; void* retrievedBuffer; d_nativeProvider->retrieveFromClipboard(d_mimeType, retrievedBuffer, retrievedSize); if (retrievedSize != d_bufferSize) { if (d_buffer != 0) { CEGUI_DELETE_ARRAY_PT(d_buffer, BufferElement, d_bufferSize, Clipboard); d_buffer = 0; } d_bufferSize = retrievedSize; d_buffer = CEGUI_NEW_ARRAY_PT(BufferElement, d_bufferSize, Clipboard); } memcpy(d_buffer, retrievedBuffer, retrievedSize); } mimeType = d_mimeType; buffer = d_buffer; size = d_bufferSize; } //----------------------------------------------------------------------------// void Clipboard::setText(const String& text) { // could be just ASCII if std::string is used as CEGUI::String const char* utf8 = text.c_str(); // we don't want the actual string length, that might not be the buffer size // in case of utf8! // this gets us the number of bytes until \0 is encountered const size_t size = strlen(utf8); setData("text/plain", static_cast<const void*>(utf8), size); } //----------------------------------------------------------------------------// String Clipboard::getText() { String mimeType; const void* buffer; size_t size; // we have to use this, can't use the member variables directly because of // the native clipboard provider! getData(mimeType, buffer, size); if (mimeType == "text/plain" && size != 0) { // d_buffer an utf8 or ASCII C string (ASCII if std::string is used) // !!! However it is not null terminated !!! So we have to tell String // how many code units (not code points!) there are. return String(static_cast<const char*>(d_buffer), d_bufferSize); } else { // the held mime type differs, it's not plain text so we can't // return it as just string return String(); } } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>/* * Pyramid.cpp * * Created on: Sep 13, 2014 * Author: goldman */ #include "Pyramid.h" using namespace std; Pyramid::Pyramid(Random& _rand, Configuration& _config, ImprovementHarness& _harness) : Optimizer(_rand, _config, _harness), sfx_options(harness.epistasis().size()) { iota(sfx_options.begin(), sfx_options.end(), 0); } // TODO Idea about using subfunctions to come up with random colorings of the graph void Pyramid::sfx_tree(vector<vector<size_t>> & blocks) { for (size_t i = 0; i < length; i++) { // creates vectors of size 1 with value i blocks.emplace_back(1, i); } vector<size_t> bit_to_block(length); iota(bit_to_block.begin(), bit_to_block.end(), 0); shuffle(sfx_options.begin(), sfx_options.end(), rand); // for each subfunction in a random order for (const auto& sub : sfx_options) { unordered_set<size_t> block_numbers; // for each bit in the subfunction for (const auto& bit : harness.epistasis()[sub]) { block_numbers.insert(bit_to_block[bit]); } // a merge is necessary if (block_numbers.size() > 1) { // start a new empty block blocks.push_back(vector<size_t>(0)); // the same bit cannot appear in two blocks, so just combine for (const auto& block_number : block_numbers) { for (const auto& bit : blocks[block_number]) { blocks.back().push_back(bit); } } // assign moved bits to new block for (const auto& bit : blocks.back()) { bit_to_block[bit] = blocks.size() - 1; } } } if (blocks.back().size() == length) { blocks.pop_back(); } blocks.erase(blocks.begin(), blocks.begin() + length); } void Pyramid::add_if_unique(const vector<bool>& candidate, size_t level) { if (seen.count(candidate) == 0) { if (solutions.size() == level) { solutions.push_back(vector<vector<bool>>(0)); selector_tool.push_back(vector<size_t>(0)); } selector_tool[level].push_back(selector_tool[level].size()); solutions[level].push_back(candidate); seen.insert(candidate); } } int Pyramid::iterate() { rand_vector(rand, solution); harness.attach(&solution); auto fitness = harness.optimize(rand); bool improved = true; for (size_t level = 0; level < solutions.size(); level++) { if (improved) { add_if_unique(solution, level); improved = false; } vector<vector<size_t>> blocks; sfx_tree(blocks); auto& options = selector_tool[level]; for (size_t index = 0; index < blocks.size(); index++) { size_t limit = options.size(); harness.set_check_point(); while (limit > 0 and harness.modified() == 0) { size_t choice = uniform_int_distribution<size_t>(0, limit - 1)(rand); size_t donor = options[choice]; swap(options[choice], options[limit - 1]); limit--; for (size_t bit : blocks[index]) { if (solution[bit] != solutions[level][donor][bit]) { harness.modify_bit(bit); } } } auto new_fitness = harness.optimize(rand); if (fitness <= new_fitness) { if (fitness < new_fitness) { improved = true; } fitness = new_fitness; harness.set_check_point(); if (fitness >= harness.max_fitness()) { return fitness; } } else { harness.revert(); } } } if (improved) { add_if_unique(solution, solutions.size()); } return fitness; } <commit_msg>Random subsets of clusters, not all clusters<commit_after>/* * Pyramid.cpp * * Created on: Sep 13, 2014 * Author: goldman */ #include "Pyramid.h" using namespace std; Pyramid::Pyramid(Random& _rand, Configuration& _config, ImprovementHarness& _harness) : Optimizer(_rand, _config, _harness), sfx_options(harness.epistasis().size()) { iota(sfx_options.begin(), sfx_options.end(), 0); } // TODO Idea about using subfunctions to come up with random colorings of the graph void Pyramid::sfx_tree(vector<vector<size_t>> & blocks) { for (size_t i = 0; i < length; i++) { // creates vectors of size 1 with value i blocks.emplace_back(1, i); } vector<size_t> bit_to_block(length); iota(bit_to_block.begin(), bit_to_block.end(), 0); shuffle(sfx_options.begin(), sfx_options.end(), rand); // for each subfunction in a random order for (const auto& sub : sfx_options) { unordered_set<size_t> block_numbers; // for each bit in the subfunction for (const auto& bit : harness.epistasis()[sub]) { block_numbers.insert(bit_to_block[bit]); } // a merge is necessary if (block_numbers.size() > 1) { // start a new empty block blocks.push_back(vector<size_t>(0)); // the same bit cannot appear in two blocks, so just combine for (const auto& block_number : block_numbers) { for (const auto& bit : blocks[block_number]) { blocks.back().push_back(bit); } } // assign moved bits to new block for (const auto& bit : blocks.back()) { bit_to_block[bit] = blocks.size() - 1; } } } if (blocks.back().size() == length) { blocks.pop_back(); } blocks.erase(blocks.begin(), blocks.begin() + length); } void Pyramid::add_if_unique(const vector<bool>& candidate, size_t level) { if (seen.count(candidate) == 0) { if (solutions.size() == level) { solutions.push_back(vector<vector<bool>>(0)); selector_tool.push_back(vector<size_t>(0)); } selector_tool[level].push_back(selector_tool[level].size()); solutions[level].push_back(candidate); seen.insert(candidate); } } int Pyramid::iterate() { rand_vector(rand, solution); harness.attach(&solution); auto fitness = harness.optimize(rand); bool improved = true; for (size_t level = 0; level < solutions.size(); level++) { if (improved) { add_if_unique(solution, level); improved = false; } vector<vector<size_t>> blocks; sfx_tree(blocks); shuffle(blocks.begin(), blocks.end(), rand); auto& options = selector_tool[level]; size_t limiter = min(blocks.size(), solutions[level].size()); for (size_t index = 0; index < limiter; index++) { size_t limit = options.size(); harness.set_check_point(); while (limit > 0 and harness.modified() == 0) { size_t choice = uniform_int_distribution<size_t>(0, limit - 1)(rand); size_t donor = options[choice]; swap(options[choice], options[limit - 1]); limit--; for (size_t bit : blocks[index]) { if (solution[bit] != solutions[level][donor][bit]) { harness.modify_bit(bit); } } } auto new_fitness = harness.optimize(rand); if (fitness <= new_fitness) { if (fitness < new_fitness) { improved = true; } fitness = new_fitness; harness.set_check_point(); if (fitness >= harness.max_fitness()) { return fitness; } } else { harness.revert(); } } } if (improved) { add_if_unique(solution, solutions.size()); } return fitness; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLIndexObjectSourceContext.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: dvo $ $Date: 2001-06-29 21:07:22 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_XMLINDEXOBJECTSOURCECONTEXT_HXX_ #include "XMLIndexObjectSourceContext.hxx" #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_ #include <com/sun/star/container/XIndexReplace.hpp> #endif #ifndef _XMLOFF_XMLINDEXTEMPLATECONTEXT_HXX_ #include "XMLIndexTemplateContext.hxx" #endif #ifndef _XMLOFF_XMLINDEXTITLETEMPLATECONTEXT_HXX_ #include "XMLIndexTitleTemplateContext.hxx" #endif #ifndef _XMLOFF_XMLINDEXTOCSTYLESCONTEXT_HXX_ #include "XMLIndexTOCStylesContext.hxx" #endif #ifndef _XMLOFF_XMLICTXT_HXX #include "xmlictxt.hxx" #endif #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLOFF_TEXTIMP_HXX_ #include "txtimp.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif using ::rtl::OUString; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Any; using ::com::sun::star::xml::sax::XAttributeList; using ::xmloff::token::IsXMLToken; using ::xmloff::token::XML_OBJECT_INDEX_ENTRY_TEMPLATE; using ::xmloff::token::XML_TOKEN_INVALID; const sal_Char sAPI_CreateFromStarCalc[] = "CreateFromStarCalc"; const sal_Char sAPI_CreateFromStarChart[] = "CreateFromStarChart"; const sal_Char sAPI_CreateFromStarDraw[] = "CreateFromStarDraw"; const sal_Char sAPI_CreateFromStarImage[] = "CreateFromStarImage"; const sal_Char sAPI_CreateFromStarMath[] = "CreateFromStarMath"; const sal_Char sAPI_CreateFromOtherEmbeddedObjects[] = "CreateFromOtherEmbeddedObjects"; TYPEINIT1( XMLIndexObjectSourceContext, XMLIndexSourceBaseContext ); XMLIndexObjectSourceContext::XMLIndexObjectSourceContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, Reference<XPropertySet> & rPropSet) : XMLIndexSourceBaseContext(rImport, nPrfx, rLocalName, rPropSet, sal_False), sCreateFromStarCalc(RTL_CONSTASCII_USTRINGPARAM( sAPI_CreateFromStarCalc)), sCreateFromStarChart(RTL_CONSTASCII_USTRINGPARAM( sAPI_CreateFromStarChart)), sCreateFromStarDraw(RTL_CONSTASCII_USTRINGPARAM( sAPI_CreateFromStarDraw)), sCreateFromStarMath(RTL_CONSTASCII_USTRINGPARAM( sAPI_CreateFromStarMath)), sCreateFromOtherEmbeddedObjects(RTL_CONSTASCII_USTRINGPARAM( sAPI_CreateFromOtherEmbeddedObjects)), bUseCalc(sal_False), bUseChart(sal_False), bUseDraw(sal_False), bUseMath(sal_False), bUseOtherObjects(sal_False) { } XMLIndexObjectSourceContext::~XMLIndexObjectSourceContext() { } void XMLIndexObjectSourceContext::ProcessAttribute( enum IndexSourceParamEnum eParam, const OUString& rValue) { switch (eParam) { sal_Bool bTmp; case XML_TOK_INDEXSOURCE_USE_OTHER_OBJECTS: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bUseOtherObjects = bTmp; } break; case XML_TOK_INDEXSOURCE_USE_SHEET: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bUseCalc = bTmp; } break; case XML_TOK_INDEXSOURCE_USE_CHART: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bUseChart = bTmp; } break; case XML_TOK_INDEXSOURCE_USE_DRAW: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bUseDraw = bTmp; } break; case XML_TOK_INDEXSOURCE_USE_MATH: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bUseMath = bTmp; } break; default: XMLIndexSourceBaseContext::ProcessAttribute(eParam, rValue); break; } } void XMLIndexObjectSourceContext::EndElement() { Any aAny; aAny.setValue(&bUseCalc, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sCreateFromStarCalc, aAny); aAny.setValue(&bUseChart, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sCreateFromStarChart, aAny); aAny.setValue(&bUseDraw, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sCreateFromStarDraw, aAny); aAny.setValue(&bUseMath, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sCreateFromStarMath, aAny); aAny.setValue(&bUseOtherObjects, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sCreateFromOtherEmbeddedObjects, aAny); XMLIndexSourceBaseContext::EndElement(); } SvXMLImportContext* XMLIndexObjectSourceContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList ) { if ( (XML_NAMESPACE_TEXT == nPrefix) && (IsXMLToken(rLocalName, XML_OBJECT_INDEX_ENTRY_TEMPLATE)) ) { return new XMLIndexTemplateContext(GetImport(), rIndexPropertySet, nPrefix, rLocalName, aLevelNameTableMap, XML_TOKEN_INVALID, // no outline-level attr aLevelStylePropNameTableMap, aAllowedTokenTypesTable); } else { return XMLIndexSourceBaseContext::CreateChildContext(nPrefix, rLocalName, xAttrList); } } <commit_msg>INTEGRATION: CWS ooo19126 (1.3.636); FILE MERGED 2005/09/05 14:39:52 rt 1.3.636.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLIndexObjectSourceContext.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:06:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLOFF_XMLINDEXOBJECTSOURCECONTEXT_HXX_ #include "XMLIndexObjectSourceContext.hxx" #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_ #include <com/sun/star/container/XIndexReplace.hpp> #endif #ifndef _XMLOFF_XMLINDEXTEMPLATECONTEXT_HXX_ #include "XMLIndexTemplateContext.hxx" #endif #ifndef _XMLOFF_XMLINDEXTITLETEMPLATECONTEXT_HXX_ #include "XMLIndexTitleTemplateContext.hxx" #endif #ifndef _XMLOFF_XMLINDEXTOCSTYLESCONTEXT_HXX_ #include "XMLIndexTOCStylesContext.hxx" #endif #ifndef _XMLOFF_XMLICTXT_HXX #include "xmlictxt.hxx" #endif #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLOFF_TEXTIMP_HXX_ #include "txtimp.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _RTL_USTRING_HXX_ #include <rtl/ustring.hxx> #endif using ::rtl::OUString; using ::com::sun::star::beans::XPropertySet; using ::com::sun::star::uno::Reference; using ::com::sun::star::uno::Any; using ::com::sun::star::xml::sax::XAttributeList; using ::xmloff::token::IsXMLToken; using ::xmloff::token::XML_OBJECT_INDEX_ENTRY_TEMPLATE; using ::xmloff::token::XML_TOKEN_INVALID; const sal_Char sAPI_CreateFromStarCalc[] = "CreateFromStarCalc"; const sal_Char sAPI_CreateFromStarChart[] = "CreateFromStarChart"; const sal_Char sAPI_CreateFromStarDraw[] = "CreateFromStarDraw"; const sal_Char sAPI_CreateFromStarImage[] = "CreateFromStarImage"; const sal_Char sAPI_CreateFromStarMath[] = "CreateFromStarMath"; const sal_Char sAPI_CreateFromOtherEmbeddedObjects[] = "CreateFromOtherEmbeddedObjects"; TYPEINIT1( XMLIndexObjectSourceContext, XMLIndexSourceBaseContext ); XMLIndexObjectSourceContext::XMLIndexObjectSourceContext( SvXMLImport& rImport, sal_uInt16 nPrfx, const OUString& rLocalName, Reference<XPropertySet> & rPropSet) : XMLIndexSourceBaseContext(rImport, nPrfx, rLocalName, rPropSet, sal_False), sCreateFromStarCalc(RTL_CONSTASCII_USTRINGPARAM( sAPI_CreateFromStarCalc)), sCreateFromStarChart(RTL_CONSTASCII_USTRINGPARAM( sAPI_CreateFromStarChart)), sCreateFromStarDraw(RTL_CONSTASCII_USTRINGPARAM( sAPI_CreateFromStarDraw)), sCreateFromStarMath(RTL_CONSTASCII_USTRINGPARAM( sAPI_CreateFromStarMath)), sCreateFromOtherEmbeddedObjects(RTL_CONSTASCII_USTRINGPARAM( sAPI_CreateFromOtherEmbeddedObjects)), bUseCalc(sal_False), bUseChart(sal_False), bUseDraw(sal_False), bUseMath(sal_False), bUseOtherObjects(sal_False) { } XMLIndexObjectSourceContext::~XMLIndexObjectSourceContext() { } void XMLIndexObjectSourceContext::ProcessAttribute( enum IndexSourceParamEnum eParam, const OUString& rValue) { switch (eParam) { sal_Bool bTmp; case XML_TOK_INDEXSOURCE_USE_OTHER_OBJECTS: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bUseOtherObjects = bTmp; } break; case XML_TOK_INDEXSOURCE_USE_SHEET: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bUseCalc = bTmp; } break; case XML_TOK_INDEXSOURCE_USE_CHART: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bUseChart = bTmp; } break; case XML_TOK_INDEXSOURCE_USE_DRAW: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bUseDraw = bTmp; } break; case XML_TOK_INDEXSOURCE_USE_MATH: if (SvXMLUnitConverter::convertBool(bTmp, rValue)) { bUseMath = bTmp; } break; default: XMLIndexSourceBaseContext::ProcessAttribute(eParam, rValue); break; } } void XMLIndexObjectSourceContext::EndElement() { Any aAny; aAny.setValue(&bUseCalc, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sCreateFromStarCalc, aAny); aAny.setValue(&bUseChart, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sCreateFromStarChart, aAny); aAny.setValue(&bUseDraw, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sCreateFromStarDraw, aAny); aAny.setValue(&bUseMath, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sCreateFromStarMath, aAny); aAny.setValue(&bUseOtherObjects, ::getBooleanCppuType()); rIndexPropertySet->setPropertyValue(sCreateFromOtherEmbeddedObjects, aAny); XMLIndexSourceBaseContext::EndElement(); } SvXMLImportContext* XMLIndexObjectSourceContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const Reference<XAttributeList> & xAttrList ) { if ( (XML_NAMESPACE_TEXT == nPrefix) && (IsXMLToken(rLocalName, XML_OBJECT_INDEX_ENTRY_TEMPLATE)) ) { return new XMLIndexTemplateContext(GetImport(), rIndexPropertySet, nPrefix, rLocalName, aLevelNameTableMap, XML_TOKEN_INVALID, // no outline-level attr aLevelStylePropNameTableMap, aAllowedTokenTypesTable); } else { return XMLIndexSourceBaseContext::CreateChildContext(nPrefix, rLocalName, xAttrList); } } <|endoftext|>
<commit_before>#include "RThread.h" #include "REventLoop.h" #include "RForwardList.h" #include "RSpinLocker.h" class RThreadPrivate { public: static void run(void *arg); }; static const rtime sTimeBlockMax = std::numeric_limits<rtime>::max() / 1000; static const rtime sTickBlock = sTimeBlockMax / portTICK_PERIOD_MS; /**< ms value matched ticks */ static const rtime sTickBlockToMS = sTickBlock * portTICK_PERIOD_MS; /**< ms value */ static const rtime sTickBlockToUS = sTickBlockToMS * 1000; /**< us value */ // FIXME: Thread list not guarded by mutex now ! static RForwardList<RThread *> sThreads; void RThreadPrivate::run(void *arg) { RThread *thread = static_cast<RThread *>(arg); if(thread) { thread->started.emit(); thread->run(); thread->finished.emit(); } // We must delete self when wan't to exit a task. // Reference to "Implementing a Task" section of FreeRTOS. vTaskDelete(NULL); } RThread::RThread(TaskHandle_t handle) // So that RObject won't create another RThread lead infinite looping : RObject(this) , mStackSize(configMINIMAL_STACK_SIZE * sizeof(word)) , mHandle(handle) , mIsOwnded(false) , mEventLoop(NULL) { // Find matched event loop for specific task. for(auto it = sThreads.begin(); it != sThreads.end(); ++it) { if(handle == (*it)->mHandle) { mEventLoop = (*it)->eventLoop(); break; } } // FIXME: New event loop will generated for task 0 and without free! } RThread::RThread() : RObject(this) , mStackSize(configMINIMAL_STACK_SIZE * sizeof(word)) , mHandle(NULL) , mIsOwnded(false) , mEventLoop(NULL) { R_MAKE_SPINLOCKER(); sThreads.pushFront(this); } RThread::~RThread() { terminate(); R_MAKE_SPINLOCKER(); // Clear this thread pointer in thread list sThreads.remove(this); } void RThread::exit(int returnCode) { eventLoop()->exit(returnCode); } bool RThread::isFinished() const { if(!mHandle) { return true; } return (eDeleted == eTaskGetState(mHandle)); } bool RThread::isRunning() const { if(!mHandle) { return false; } return (eDeleted != eTaskGetState(mHandle)); } RThread::Priority RThread::priority() const { if(!mHandle) { return IdlePriority; } return static_cast<RThread::Priority>(uxTaskPriorityGet(mHandle)); } void RThread::setPriority(RThread::Priority priority) { if(!mHandle) { return; } vTaskPrioritySet(mHandle, static_cast<UBaseType_t>(priority)); } void RThread::setStackSize(size_t stackSize) { mStackSize = stackSize; } size_t RThread::stackSize() const { return mStackSize; } bool RThread::wait(unsigned long time) { /// FIXME: Ugly way to wait for thread finished. /* Block for 100ms each time */ const TickType_t ticksPerBlock = 100 / portTICK_PERIOD_MS; if(currentThreadId() == mHandle) { // You can't wait yourself in the samethread! return false; } while(true) { if(isFinished()) { return true; } if(time < std::numeric_limits<unsigned long>::max()) { if(time <= 100) { // Timeout! return false; } else { time -= 100; } } vTaskDelay(ticksPerBlock); } } void RThread::quit() { this->exit(0); } void RThread::start(RThread::Priority priority) { /* Create the task, storing the handle. */ TaskHandle_t handle = NULL; if(isRunning()) { return; } terminate(); if(InheritPriority == priority) { priority = static_cast<RThread::Priority>(uxTaskPriorityGet(currentThreadId())); } auto ret = xTaskCreate( RThreadPrivate::run, /* Function that implements the task. */ "", /* Text name for the task. */ (stackSize() + 1) / sizeof(uint16_t), /* Stack size in words, not bytes. */ static_cast<void *>(this), /* Parameter passed into the task. */ priority, /* Priority at which the task is created. */ &handle); /* Used to pass out the created task's handle. */ if(ret == pdPASS) { mIsOwnded = true; mHandle = handle; } } void RThread::terminate() { if(mIsOwnded && mHandle) { // Ensure no tasks and interrupts will be trigger during thread event loop // destruction. { R_MAKE_SPINLOCKER(); delete mEventLoop; mEventLoop = NULL; vTaskDelete(mHandle); } terminated.emit(); } mHandle = NULL; } REventLoop * RThread::eventLoop() { if(NULL == mEventLoop) { R_MAKE_SPINLOCKER(); if(mEventLoop) // Avoid previous check passed at the same time. { return mEventLoop; } mEventLoop = new REventLoop(); mEventLoop->moveToThread(const_cast<RThread *>(this)); } return mEventLoop; } RThread * RThread::currentThread() { TaskHandle_t handle = currentThreadId(); for(auto it = sThreads.begin(); it != sThreads.end(); ++it) { if(handle == (*it)->mHandle) { return *it; } } // FIXME: Here generated an orphan RThread object! return new RThread(handle); } TaskHandle_t RThread::currentThreadId() { return xTaskGetCurrentTaskHandle(); } void RThread::yieldCurrentThread() { taskYIELD(); } int RThread::exec() { return eventLoop()->exec(); } void RThread::run() { exec(); } void RThread::msleep(rtime msecs) { if(currentThreadId()) { while(msecs > 0) { if(msecs < sTickBlockToMS) { // Convert to ticks vTaskDelay(msecs / portTICK_PERIOD_MS); break; } vTaskDelay(sTickBlock); msecs -= sTickBlockToMS; } } else { delay(msecs); } } void RThread::sleep(rtime secs) { /**< Time block to milliseconds */ static const rtime sTimeBlockToMS = sTimeBlockMax * 1000; while(secs > 0) { if(secs < sTimeBlockMax) { msleep(secs * 1000); break; } msleep(sTimeBlockToMS); secs -= sTimeBlockMax; } } void RThread::usleep(rtime usecs) { if(currentThreadId()) { while(usecs > 0) { if(usecs < sTickBlockToUS) { // Convert to ticks vTaskDelay(usecs / (1000 * portTICK_PERIOD_MS)); break; } vTaskDelay(sTickBlock); usecs -= sTickBlockToUS; } } else { delayMicroseconds(usecs); } } <commit_msg>Fixed typo<commit_after>#include "RThread.h" #include "REventLoop.h" #include "RForwardList.h" #include "RSpinLocker.h" class RThreadPrivate { public: static void run(void *arg); }; static const rtime sTimeBlockMax = std::numeric_limits<rtime>::max() / 1000; static const rtime sTickBlock = sTimeBlockMax / portTICK_PERIOD_MS; /**< ms value matched ticks */ static const rtime sTickBlockToMS = sTickBlock * portTICK_PERIOD_MS; /**< ms value */ static const rtime sTickBlockToUS = sTickBlockToMS * 1000; /**< us value */ // FIXME: Thread list not guarded by mutex now ! static RForwardList<RThread *> sThreads; void RThreadPrivate::run(void *arg) { RThread *thread = static_cast<RThread *>(arg); if(thread) { thread->started.emit(); thread->run(); thread->finished.emit(); } // We must delete self when want to exit a task. // Reference to "Implementing a Task" section of FreeRTOS. vTaskDelete(NULL); } RThread::RThread(TaskHandle_t handle) // So that RObject won't create another RThread lead infinite looping : RObject(this) , mStackSize(configMINIMAL_STACK_SIZE * sizeof(word)) , mHandle(handle) , mIsOwnded(false) , mEventLoop(NULL) { // Find matched event loop for specific task. for(auto it = sThreads.begin(); it != sThreads.end(); ++it) { if(handle == (*it)->mHandle) { mEventLoop = (*it)->eventLoop(); break; } } // FIXME: New event loop will generated for task 0 and without free! } RThread::RThread() : RObject(this) , mStackSize(configMINIMAL_STACK_SIZE * sizeof(word)) , mHandle(NULL) , mIsOwnded(false) , mEventLoop(NULL) { R_MAKE_SPINLOCKER(); sThreads.pushFront(this); } RThread::~RThread() { terminate(); R_MAKE_SPINLOCKER(); // Clear this thread pointer in thread list sThreads.remove(this); } void RThread::exit(int returnCode) { eventLoop()->exit(returnCode); } bool RThread::isFinished() const { if(!mHandle) { return true; } return (eDeleted == eTaskGetState(mHandle)); } bool RThread::isRunning() const { if(!mHandle) { return false; } return (eDeleted != eTaskGetState(mHandle)); } RThread::Priority RThread::priority() const { if(!mHandle) { return IdlePriority; } return static_cast<RThread::Priority>(uxTaskPriorityGet(mHandle)); } void RThread::setPriority(RThread::Priority priority) { if(!mHandle) { return; } vTaskPrioritySet(mHandle, static_cast<UBaseType_t>(priority)); } void RThread::setStackSize(size_t stackSize) { mStackSize = stackSize; } size_t RThread::stackSize() const { return mStackSize; } bool RThread::wait(unsigned long time) { /// FIXME: Ugly way to wait for thread finished. /* Block for 100ms each time */ const TickType_t ticksPerBlock = 100 / portTICK_PERIOD_MS; if(currentThreadId() == mHandle) { // You can't wait yourself in the samethread! return false; } while(true) { if(isFinished()) { return true; } if(time < std::numeric_limits<unsigned long>::max()) { if(time <= 100) { // Timeout! return false; } else { time -= 100; } } vTaskDelay(ticksPerBlock); } } void RThread::quit() { this->exit(0); } void RThread::start(RThread::Priority priority) { /* Create the task, storing the handle. */ TaskHandle_t handle = NULL; if(isRunning()) { return; } terminate(); if(InheritPriority == priority) { priority = static_cast<RThread::Priority>(uxTaskPriorityGet(currentThreadId())); } auto ret = xTaskCreate( RThreadPrivate::run, /* Function that implements the task. */ "", /* Text name for the task. */ (stackSize() + 1) / sizeof(uint16_t), /* Stack size in words, not bytes. */ static_cast<void *>(this), /* Parameter passed into the task. */ priority, /* Priority at which the task is created. */ &handle); /* Used to pass out the created task's handle. */ if(ret == pdPASS) { mIsOwnded = true; mHandle = handle; } } void RThread::terminate() { if(mIsOwnded && mHandle) { // Ensure no tasks and interrupts will be trigger during thread event loop // destruction. { R_MAKE_SPINLOCKER(); delete mEventLoop; mEventLoop = NULL; vTaskDelete(mHandle); } terminated.emit(); } mHandle = NULL; } REventLoop * RThread::eventLoop() { if(NULL == mEventLoop) { R_MAKE_SPINLOCKER(); if(mEventLoop) // Avoid previous check passed at the same time. { return mEventLoop; } mEventLoop = new REventLoop(); mEventLoop->moveToThread(const_cast<RThread *>(this)); } return mEventLoop; } RThread * RThread::currentThread() { TaskHandle_t handle = currentThreadId(); for(auto it = sThreads.begin(); it != sThreads.end(); ++it) { if(handle == (*it)->mHandle) { return *it; } } // FIXME: Here generated an orphan RThread object! return new RThread(handle); } TaskHandle_t RThread::currentThreadId() { return xTaskGetCurrentTaskHandle(); } void RThread::yieldCurrentThread() { taskYIELD(); } int RThread::exec() { return eventLoop()->exec(); } void RThread::run() { exec(); } void RThread::msleep(rtime msecs) { if(currentThreadId()) { while(msecs > 0) { if(msecs < sTickBlockToMS) { // Convert to ticks vTaskDelay(msecs / portTICK_PERIOD_MS); break; } vTaskDelay(sTickBlock); msecs -= sTickBlockToMS; } } else { delay(msecs); } } void RThread::sleep(rtime secs) { /**< Time block to milliseconds */ static const rtime sTimeBlockToMS = sTimeBlockMax * 1000; while(secs > 0) { if(secs < sTimeBlockMax) { msleep(secs * 1000); break; } msleep(sTimeBlockToMS); secs -= sTimeBlockMax; } } void RThread::usleep(rtime usecs) { if(currentThreadId()) { while(usecs > 0) { if(usecs < sTickBlockToUS) { // Convert to ticks vTaskDelay(usecs / (1000 * portTICK_PERIOD_MS)); break; } vTaskDelay(sTickBlock); usecs -= sTickBlockToUS; } } else { delayMicroseconds(usecs); } } <|endoftext|>
<commit_before>#include "mmcore/CoreInstance.h" #include "mmcore/MegaMolGraph.h" #include "mmcore/utility/log/Log.h" #include "mmcore/utility/log/StreamTarget.h" #include "AbstractFrontendService.hpp" #include "FrontendServiceCollection.hpp" #include "GUI_Service.hpp" #include "Lua_Service_Wrapper.hpp" #include "OpenGL_GLFW_Service.hpp" #include "Screenshot_Service.hpp" #include "mmcore/view/AbstractView_EventConsumption.h" #include <cxxopts.hpp> #include "mmcore/LuaAPI.h" // Filesystem #if defined(_HAS_CXX17) || ((defined(_MSC_VER) && (_MSC_VER > 1916))) // C++2017 or since VS2019 # include <filesystem> namespace stdfs = std::filesystem; #else // WINDOWS # ifdef _WIN32 # include <filesystem> namespace stdfs = std::experimental::filesystem; # else // LINUX # include <experimental/filesystem> namespace stdfs = std::experimental::filesystem; # endif #endif // make sure that all configuration parameters have sane and useful and EXPLICIT initialization values! struct CLIConfig { std::string program_invocation_string = ""; std::vector<std::string> project_files = {}; std::string lua_host_address = "tcp://127.0.0.1:33333"; bool load_example_project = true; bool opengl_khr_debug = true; }; CLIConfig handle_cli_inputs(int argc, char* argv[]); bool set_up_example_graph(megamol::core::MegaMolGraph& graph); int main(int argc, char* argv[]) { auto config = handle_cli_inputs(argc, argv); // setup log megamol::core::utility::log::Log::DefaultLog.SetLogFileName(static_cast<const char*>(NULL), false); megamol::core::utility::log::Log::DefaultLog.SetLevel(megamol::core::utility::log::Log::LEVEL_ALL); megamol::core::utility::log::Log::DefaultLog.SetEchoLevel(megamol::core::utility::log::Log::LEVEL_ALL); megamol::core::utility::log::Log::DefaultLog.SetEchoTarget( std::make_shared<megamol::core::utility::log::StreamTarget>( std::cout, megamol::core::utility::log::Log::LEVEL_ALL)); megamol::core::CoreInstance core; core.Initialise(false); // false makes core not start his own lua service (else we collide on default port) const megamol::core::factories::ModuleDescriptionManager& moduleProvider = core.GetModuleDescriptionManager(); const megamol::core::factories::CallDescriptionManager& callProvider = core.GetCallDescriptionManager(); megamol::frontend::OpenGL_GLFW_Service gl_service; megamol::frontend::OpenGL_GLFW_Service::Config openglConfig; openglConfig.windowTitlePrefix = openglConfig.windowTitlePrefix + " ~ Main3000"; openglConfig.versionMajor = 4; openglConfig.versionMinor = 5; openglConfig.enableKHRDebug = config.opengl_khr_debug; gl_service.setPriority(1); megamol::frontend::GUI_Service gui_service; megamol::frontend::GUI_Service::Config guiConfig; guiConfig.imgui_api = megamol::frontend::GUI_Service::ImGuiAPI::OPEN_GL; guiConfig.core_instance = &core; // priority must be higher than priority of gl_service (=1) // service callbacks get called in order of priority of the service. // postGraphRender() and close() are called in reverse order of priorities. gui_service.setPriority(23); megamol::frontend::Screenshot_Service screenshot_service; megamol::frontend::Screenshot_Service::Config screenshotConfig; screenshot_service.setPriority(30); megamol::core::MegaMolGraph graph(core, moduleProvider, callProvider); bool lua_imperative_only = false; // allow mmFlush, mmList* and mmGetParam* megamol::core::LuaAPI lua_api(graph, lua_imperative_only); megamol::frontend::Lua_Service_Wrapper lua_service_wrapper; megamol::frontend::Lua_Service_Wrapper::Config luaConfig; luaConfig.lua_api_ptr = &lua_api; luaConfig.host_address = config.lua_host_address; lua_service_wrapper.setPriority(0); // the main loop is organized around services that can 'do something' in different parts of the main loop // a service is something that implements the AbstractFrontendService interface from 'megamol\frontend_services\include' // a central mechanism that allows services to communicate with each other and with graph modules are _resources_ // (see ModuleResource in 'megamol\module_resources\include') services may provide resources to the system and they may // request resources they need themselves for functioning. think of a resource as a struct (or some type of your // choice) that gets wrapped by a helper structure and gets a name attached to it. the fronend makes sure (at least // attempts to) to hand each service the resources it requested, or else fail execution of megamol with an error // message. resource assignment is done by the name of the resource, so this is a very loose interface based on // trust. type safety of resources is ensured in the sense that extracting the wrong type from a ModuleResource will // lead to an unhandled bad type cast exception, leading to the shutdown of megamol. bool run_megamol = true; megamol::frontend::FrontendServiceCollection services; services.add(gl_service, &openglConfig); services.add(gui_service, &guiConfig); services.add(lua_service_wrapper, &luaConfig); services.add(screenshot_service, &screenshotConfig); // TODO: gui view and frontend service gui can not coexist => how to kill GUI View in loaded projects? // - FBO size (and others) for newly created views/modules/entrypoints (FBO size event missing). see AbstractView_EventConsumption::view_consume_framebuffer_events // - graph manipulation via GUI still buggy (adding/removing main views, renaming modules/calls, stuff like that) // TODO: port cinematic as frontend service // => explicit FBOs! // TODO: port screenshooter // TODO: ZMQ context as frontend resource // TODO: port CLI commands from mmconsole // => do or dont show GUI in screenshots, depending on ... // TODO: eliminate the core instance: // => extract module/call description manager into new factories; remove from core // => key/value store for CLI configuration as frontend resource (emulate config params) // TODO: main3000 compilation on linux (cmake name conflict, GUI_Windows <-> GUI_ Service dll/lib boundary) // TODO: overall new frontend-related CI compilation issues (mostly on linux) // TODO: main3000 raw hot loop performance vs. mmconsole performance const bool init_ok = services.init(); // runs init(config_ptr) on all services with provided config sructs if (!init_ok) { std::cout << "ERROR: some frontend service could not be initialized successfully. abort. " << std::endl; services.close(); return 1; } // graph is also a resource that may be accessed by services // TODO: how to solve const and non-const resources? // TODO: graph manipulation during execution of graph modules is problematic, undefined? services.getProvidedResources().push_back({"MegaMolGraph", graph}); // proof of concept: a resource that returns a list of names of available resources // used by Lua Wrapper and LuaAPI to return list of available resources via remoteconsole const std::function<std::vector<std::string>()> resource_lister = [&]() -> std::vector<std::string> { std::vector<std::string> resources; for (auto& resource : services.getProvidedResources()) { resources.push_back(resource.getIdentifier()); } return resources; }; services.getProvidedResources().push_back({"FrontendResourcesList", resource_lister}); // distribute registered resources among registered services. const bool resources_ok = services.assignRequestedResources(); // for each service we call their resource callbacks here: // std::vector<ModuleResource>& getProvidedResources() // std::vector<std::string> getRequestedResourceNames() // void setRequestedResources(std::vector<ModuleResource>& resources) if (!resources_ok) { std::cout << "ERROR: frontend could not assign requested service resources. abort. " << std::endl; run_megamol = false; } auto module_resources = services.getProvidedResources(); graph.AddModuleDependencies(module_resources); uint32_t frameID = 0; const auto render_next_frame = [&]() -> bool { // set global Frame Counter guiConfig.core_instance->SetFrameID(frameID++); // services: receive inputs (GLFW poll events [keyboard, mouse, window], network, lua) services.updateProvidedResources(); // aka simulation step // services: digest new inputs via ModuleResources (GUI digest user inputs, lua digest inputs, network ?) // e.g. graph updates, module and call creation via lua and GUI happen here services.digestChangedRequestedResources(); // services tell us wheter we should shut down megamol if (services.shouldShutdown()) return false; { // actual rendering services.preGraphRender(); // e.g. start frame timer, clear render buffers graph.RenderNextFrame(); // executes graph views, those digest input events like keyboard/mouse, then render services.postGraphRender(); // render GUI, glfw swap buffers, stop frame timer } services.resetProvidedResources(); // clear buffers holding glfw keyboard+mouse input return true; }; // lua can issue rendering of frames lua_api.setFlushCallback(render_next_frame); // load project files via lua for (auto& file : config.project_files) { std::string result; if (!lua_api.RunFile(file, result)) { std::cout << "Project file \"" << file << "\" did not execute correctly: " << result << std::endl; run_megamol = false; } } if (config.load_example_project && config.project_files.empty()) { const bool graph_ok = set_up_example_graph(graph); // fill graph with modules and calls if (!graph_ok) { std::cout << "ERROR: frontend could not build graph. abort. " << std::endl; run_megamol = false; } } while (run_megamol) { run_megamol = render_next_frame(); } // close glfw context, network connections, other system resources services.close(); // clean up modules, calls in graph // TODO: implement graph destructor return 0; } CLIConfig handle_cli_inputs(int argc, char* argv[]) { CLIConfig config; cxxopts::Options options(argv[0], "MegaMol Frontend 3000"); config.program_invocation_string = std::string{argv[0]}; // parse input project files options.positional_help("<additional project files>"); options.add_options() ("project-files", "projects to load", cxxopts::value<std::vector<std::string>>()) ("host", "address of lua host server, default: "+config.lua_host_address, cxxopts::value<std::string>()) ("noexample", "dont load minimal spheres example project", cxxopts::value<bool>()) ("nokhrdebug", "disable OpenGL KHR debug messages", cxxopts::value<bool>()) ; options.parse_positional({"project-files"}); auto parsed_options = options.parse(argc, argv); std::string res; // verify project files exist in file system if (parsed_options.count("project-files")) { const auto& v = parsed_options["project-files"].as<std::vector<std::string>>(); for (const auto& p : v) { if (!stdfs::exists(p)) { std::cout << "Project file \"" << p << "\" does not exist!" << std::endl; std::exit(1); } } config.project_files = v; } if (parsed_options.count("host")) { config.lua_host_address = parsed_options["host"].as<std::string>(); } if (parsed_options.count("noexample")) { config.load_example_project = !parsed_options["noexample"].as<bool>(); } if (parsed_options.count("nokhrdebug")) { config.opengl_khr_debug = !parsed_options["nokhrdebug"].as<bool>(); } return config; } bool set_up_example_graph(megamol::core::MegaMolGraph& graph) { #define check(X) \ if (!X) return false; ///check(graph.CreateModule("GUIView", "::gui")); check(graph.CreateModule("View3D_2", "::view")); check(graph.CreateModule("SphereRenderer", "::spheres")); check(graph.CreateModule("TestSpheresDataSource", "::datasource")); ///check(graph.CreateCall("CallRenderView", "::gui::renderview", "::view::render")); check(graph.CreateCall("CallRender3D_2", "::view::rendering", "::spheres::rendering")); check(graph.CreateCall("MultiParticleDataCall", "::spheres::getdata", "::datasource::getData")); ///check(graph.SetGraphEntryPoint("::gui", megamol::core::view::get_gl_view_runtime_resources_requests(), megamol::core::view::view_rendering_execution)); check(graph.SetGraphEntryPoint("::view", megamol::core::view::get_gl_view_runtime_resources_requests(), megamol::core::view::view_rendering_execution)); std::string parameter_name("::datasource::numSpheres"); auto parameterPtr = graph.FindParameter(parameter_name); if (parameterPtr) { parameterPtr->ParseValue("23"); } else { std::cout << "ERROR: could not find parameter: " << parameter_name << std::endl; return false; } return true; } <commit_msg>frontend: clean up main<commit_after>#include "mmcore/CoreInstance.h" #include "mmcore/MegaMolGraph.h" #include "mmcore/utility/log/Log.h" #include "mmcore/utility/log/StreamTarget.h" #include "FrontendServiceCollection.hpp" #include "GUI_Service.hpp" #include "Lua_Service_Wrapper.hpp" #include "OpenGL_GLFW_Service.hpp" #include "Screenshot_Service.hpp" #include "mmcore/view/AbstractView_EventConsumption.h" #include <cxxopts.hpp> #include "mmcore/LuaAPI.h" // Filesystem #if defined(_HAS_CXX17) || ((defined(_MSC_VER) && (_MSC_VER > 1916))) // C++2017 or since VS2019 # include <filesystem> namespace stdfs = std::filesystem; #else // WINDOWS # ifdef _WIN32 # include <filesystem> namespace stdfs = std::experimental::filesystem; # else // LINUX # include <experimental/filesystem> namespace stdfs = std::experimental::filesystem; # endif #endif // make sure that all configuration parameters have sane and useful and EXPLICIT initialization values! struct CLIConfig { std::string program_invocation_string = ""; std::vector<std::string> project_files = {}; std::string lua_host_address = "tcp://127.0.0.1:33333"; bool load_example_project = true; bool opengl_khr_debug = true; }; CLIConfig handle_cli_inputs(int argc, char* argv[]); bool set_up_example_graph(megamol::core::MegaMolGraph& graph); int main(int argc, char* argv[]) { auto config = handle_cli_inputs(argc, argv); // setup log megamol::core::utility::log::Log::DefaultLog.SetLogFileName(static_cast<const char*>(NULL), false); megamol::core::utility::log::Log::DefaultLog.SetLevel(megamol::core::utility::log::Log::LEVEL_ALL); megamol::core::utility::log::Log::DefaultLog.SetEchoLevel(megamol::core::utility::log::Log::LEVEL_ALL); megamol::core::utility::log::Log::DefaultLog.SetEchoTarget( std::make_shared<megamol::core::utility::log::StreamTarget>( std::cout, megamol::core::utility::log::Log::LEVEL_ALL)); megamol::core::CoreInstance core; core.Initialise(false); // false makes core not start his own lua service (else we collide on default port) const megamol::core::factories::ModuleDescriptionManager& moduleProvider = core.GetModuleDescriptionManager(); const megamol::core::factories::CallDescriptionManager& callProvider = core.GetCallDescriptionManager(); megamol::frontend::OpenGL_GLFW_Service gl_service; megamol::frontend::OpenGL_GLFW_Service::Config openglConfig; openglConfig.windowTitlePrefix = openglConfig.windowTitlePrefix + " ~ Main3000"; openglConfig.versionMajor = 4; openglConfig.versionMinor = 5; openglConfig.enableKHRDebug = config.opengl_khr_debug; gl_service.setPriority(1); megamol::frontend::GUI_Service gui_service; megamol::frontend::GUI_Service::Config guiConfig; guiConfig.imgui_api = megamol::frontend::GUI_Service::ImGuiAPI::OPEN_GL; guiConfig.core_instance = &core; // priority must be higher than priority of gl_service (=1) // service callbacks get called in order of priority of the service. // postGraphRender() and close() are called in reverse order of priorities. gui_service.setPriority(23); megamol::frontend::Screenshot_Service screenshot_service; megamol::frontend::Screenshot_Service::Config screenshotConfig; screenshot_service.setPriority(30); megamol::core::MegaMolGraph graph(core, moduleProvider, callProvider); bool lua_imperative_only = false; // allow mmFlush, mmList* and mmGetParam* megamol::core::LuaAPI lua_api(graph, lua_imperative_only); megamol::frontend::Lua_Service_Wrapper lua_service_wrapper; megamol::frontend::Lua_Service_Wrapper::Config luaConfig; luaConfig.lua_api_ptr = &lua_api; luaConfig.host_address = config.lua_host_address; lua_service_wrapper.setPriority(0); // the main loop is organized around services that can 'do something' in different parts of the main loop // a service is something that implements the AbstractFrontendService interface from 'megamol\frontend_services\include' // a central mechanism that allows services to communicate with each other and with graph modules are _resources_ // (see ModuleResource in 'megamol\module_resources\include') services may provide resources to the system and they may // request resources they need themselves for functioning. think of a resource as a struct (or some type of your // choice) that gets wrapped by a helper structure and gets a name attached to it. the fronend makes sure (at least // attempts to) to hand each service the resources it requested, or else fail execution of megamol with an error // message. resource assignment is done by the name of the resource, so this is a very loose interface based on // trust. type safety of resources is ensured in the sense that extracting the wrong type from a ModuleResource will // lead to an unhandled bad type cast exception, leading to the shutdown of megamol. bool run_megamol = true; megamol::frontend::FrontendServiceCollection services; services.add(gl_service, &openglConfig); services.add(gui_service, &guiConfig); services.add(lua_service_wrapper, &luaConfig); services.add(screenshot_service, &screenshotConfig); // TODO: gui view and frontend service gui can not coexist => how to kill GUI View in loaded projects? // - FBO size (and others) for newly created views/modules/entrypoints (FBO size event missing). see AbstractView_EventConsumption::view_consume_framebuffer_events // - graph manipulation via GUI still buggy (adding/removing main views, renaming modules/calls, stuff like that) // TODO: port cinematic as frontend service // => explicit FBOs! // TODO: port screenshooter // TODO: ZMQ context as frontend resource // TODO: port CLI commands from mmconsole // => do or dont show GUI in screenshots, depending on ... // TODO: eliminate the core instance: // => extract module/call description manager into new factories; remove from core // => key/value store for CLI configuration as frontend resource (emulate config params) // TODO: main3000 compilation on linux (cmake name conflict, GUI_Windows <-> GUI_ Service dll/lib boundary) // TODO: overall new frontend-related CI compilation issues (mostly on linux) // TODO: main3000 raw hot loop performance vs. mmconsole performance const bool init_ok = services.init(); // runs init(config_ptr) on all services with provided config sructs if (!init_ok) { std::cout << "ERROR: some frontend service could not be initialized successfully. abort. " << std::endl; services.close(); return 1; } // graph is also a resource that may be accessed by services // TODO: how to solve const and non-const resources? // TODO: graph manipulation during execution of graph modules is problematic, undefined? services.getProvidedResources().push_back({"MegaMolGraph", graph}); // proof of concept: a resource that returns a list of names of available resources // used by Lua Wrapper and LuaAPI to return list of available resources via remoteconsole const std::function<std::vector<std::string>()> resource_lister = [&]() -> std::vector<std::string> { std::vector<std::string> resources; for (auto& resource : services.getProvidedResources()) { resources.push_back(resource.getIdentifier()); } return resources; }; services.getProvidedResources().push_back({"FrontendResourcesList", resource_lister}); // distribute registered resources among registered services. const bool resources_ok = services.assignRequestedResources(); // for each service we call their resource callbacks here: // std::vector<ModuleResource>& getProvidedResources() // std::vector<std::string> getRequestedResourceNames() // void setRequestedResources(std::vector<ModuleResource>& resources) if (!resources_ok) { std::cout << "ERROR: frontend could not assign requested service resources. abort. " << std::endl; run_megamol = false; } auto module_resources = services.getProvidedResources(); graph.AddModuleDependencies(module_resources); uint32_t frameID = 0; const auto render_next_frame = [&]() -> bool { // set global Frame Counter core.SetFrameID(frameID++); // services: receive inputs (GLFW poll events [keyboard, mouse, window], network, lua) services.updateProvidedResources(); // aka simulation step // services: digest new inputs via ModuleResources (GUI digest user inputs, lua digest inputs, network ?) // e.g. graph updates, module and call creation via lua and GUI happen here services.digestChangedRequestedResources(); // services tell us wheter we should shut down megamol if (services.shouldShutdown()) return false; { // actual rendering services.preGraphRender(); // e.g. start frame timer, clear render buffers graph.RenderNextFrame(); // executes graph views, those digest input events like keyboard/mouse, then render services.postGraphRender(); // render GUI, glfw swap buffers, stop frame timer } services.resetProvidedResources(); // clear buffers holding glfw keyboard+mouse input return true; }; // lua can issue rendering of frames lua_api.setFlushCallback(render_next_frame); // load project files via lua for (auto& file : config.project_files) { std::string result; if (!lua_api.RunFile(file, result)) { std::cout << "Project file \"" << file << "\" did not execute correctly: " << result << std::endl; run_megamol = false; } } if (config.load_example_project && config.project_files.empty()) { const bool graph_ok = set_up_example_graph(graph); // fill graph with modules and calls if (!graph_ok) { std::cout << "ERROR: frontend could not build graph. abort. " << std::endl; run_megamol = false; } } while (run_megamol) { run_megamol = render_next_frame(); } // close glfw context, network connections, other system resources services.close(); // clean up modules, calls in graph // TODO: implement graph destructor return 0; } CLIConfig handle_cli_inputs(int argc, char* argv[]) { CLIConfig config; cxxopts::Options options(argv[0], "MegaMol Frontend 3000"); config.program_invocation_string = std::string{argv[0]}; // parse input project files options.positional_help("<additional project files>"); options.add_options() ("project-files", "projects to load", cxxopts::value<std::vector<std::string>>()) ("host", "address of lua host server, default: "+config.lua_host_address, cxxopts::value<std::string>()) ("noexample", "dont load minimal spheres example project", cxxopts::value<bool>()) ("nokhrdebug", "disable OpenGL KHR debug messages", cxxopts::value<bool>()) ; options.parse_positional({"project-files"}); auto parsed_options = options.parse(argc, argv); std::string res; // verify project files exist in file system if (parsed_options.count("project-files")) { const auto& v = parsed_options["project-files"].as<std::vector<std::string>>(); for (const auto& p : v) { if (!stdfs::exists(p)) { std::cout << "Project file \"" << p << "\" does not exist!" << std::endl; std::exit(1); } } config.project_files = v; } if (parsed_options.count("host")) { config.lua_host_address = parsed_options["host"].as<std::string>(); } if (parsed_options.count("noexample")) { config.load_example_project = !parsed_options["noexample"].as<bool>(); } if (parsed_options.count("nokhrdebug")) { config.opengl_khr_debug = !parsed_options["nokhrdebug"].as<bool>(); } return config; } bool set_up_example_graph(megamol::core::MegaMolGraph& graph) { #define check(X) \ if (!X) return false; ///check(graph.CreateModule("GUIView", "::gui")); check(graph.CreateModule("View3D_2", "::view")); check(graph.CreateModule("SphereRenderer", "::spheres")); check(graph.CreateModule("TestSpheresDataSource", "::datasource")); ///check(graph.CreateCall("CallRenderView", "::gui::renderview", "::view::render")); check(graph.CreateCall("CallRender3D_2", "::view::rendering", "::spheres::rendering")); check(graph.CreateCall("MultiParticleDataCall", "::spheres::getdata", "::datasource::getData")); ///check(graph.SetGraphEntryPoint("::gui", megamol::core::view::get_gl_view_runtime_resources_requests(), megamol::core::view::view_rendering_execution)); check(graph.SetGraphEntryPoint("::view", megamol::core::view::get_gl_view_runtime_resources_requests(), megamol::core::view::view_rendering_execution)); std::string parameter_name("::datasource::numSpheres"); auto parameterPtr = graph.FindParameter(parameter_name); if (parameterPtr) { parameterPtr->ParseValue("23"); } else { std::cout << "ERROR: could not find parameter: " << parameter_name << std::endl; return false; } return true; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkOpenGLProjectedPolyDataRayBounder.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to Lisa Sobierajski Avila who developed this class. Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkOpenGLProjectedPolyDataRayBounder.h" #include "vtkNew2VolumeRenderer.h" // Description: // Construct a new vtkOpenGLProjectedPolyDataRayBounder. The depth range // buffer is initially NULL and no display list has been created vtkOpenGLProjectedPolyDataRayBounder::vtkOpenGLProjectedPolyDataRayBounder() { this->DisplayList = 0; this->DepthRangeBuffer = NULL; } // Description: // Destruct the vtkOpenGLProjectedPolyDataRayBounder. Free the // DepthRangeBuffer if necessary vtkOpenGLProjectedPolyDataRayBounder::~vtkOpenGLProjectedPolyDataRayBounder() { if ( this->DepthRangeBuffer ) delete this->DepthRangeBuffer; } // Description: // Create a display list from the polygons contained in pdata. // Lines and vertices are ignored, polys and strips are used. void vtkOpenGLProjectedPolyDataRayBounder::Build( vtkPolyData *pdata ) { vtkCellArray *polys; vtkCellArray *strips; vtkPoints *points; int *pts, npts; int current_num_vertices = -1; int i; polys = pdata->GetPolys(); points = pdata->GetPoints(); strips = pdata->GetStrips(); if ( !glIsList( this->DisplayList ) ) this->DisplayList = glGenLists( 1 ); glNewList( this->DisplayList, GL_COMPILE ); for ( polys->InitTraversal(); polys->GetNextCell( npts, pts ); ) { // If we are doing a different number of vertices, or if this // is a polygon, then end what we were doing and begin again if ( current_num_vertices != npts || npts > 4 ) { // Unless of course this is our first time through - then we // don't want to end if ( current_num_vertices != -1 ) glEnd(); // How many vertices do we have? if ( npts == 3 ) glBegin( GL_TRIANGLES ); else if ( npts == 4 ) glBegin( GL_QUADS ); else glBegin( GL_POLYGON ); } // Draw the vertices for ( i = 0; i < npts; i++ ) glVertex3fv( points->GetPoint( pts[i] ) ); current_num_vertices = npts; } glEnd(); for ( strips->InitTraversal(); strips->GetNextCell( npts, pts ); ) { glBegin( GL_TRIANGLE_STRIP ); // Draw the vertices for ( i = 0; i < npts; i++ ) glVertex3fv( points->GetPoint( pts[i] ) ); glEnd(); } glEndList(); } // Description: // Draw the display list and create the depth range buffer. // // Known problem: // camera clipping planes (near/far) may clip the projected // geometry resulting in incorrect results. float *vtkOpenGLProjectedPolyDataRayBounder::Draw( vtkRenderer *ren, vtkMatrix4x4 *position_matrix ) { GLboolean lighting_on; int size[2]; float *near_buffer, *far_buffer; vtkTransform *transform; vtkMatrix4x4 *matrix; float ren_aspect[2], aspect, range[2]; float *ray_ptr; float *near_ptr, *far_ptr; float *range_ptr; vtkNew2VolumeRenderer *volren; float z_numerator, z_denom_mult, z_denom_add; float zfactor; int i, j; int current_viewport[4]; volren = (vtkNew2VolumeRenderer *) ren->GetNewVolumeRenderer(); // Create some objects that we will need later transform = vtkTransform::New(); matrix = vtkMatrix4x4::New(); // The size of the view rays is the size of the image we are creating ((vtkNew2VolumeRenderer *) (ren->GetNewVolumeRenderer()))->GetViewRaysSize( size ); // This should be fixed - I should not be off in someone else's viewport // if there are more than one of them... glGetIntegerv( GL_VIEWPORT, current_viewport ); glPushAttrib(GL_VIEWPORT_BIT); glViewport( current_viewport[0], current_viewport[1], size[0], size[1] ); // Create the near buffer storage near_buffer = new float[ size[0] * size[1] ]; // Create the far buffer storage far_buffer = new float[ size[0] * size[1] ]; if ( this->DepthRangeBuffer ) delete this->DepthRangeBuffer; this->DepthRangeBuffer = new float[ size[0] * size[1] * 2 ]; // Save previous lighting state, and turn lighting off glGetBooleanv( GL_LIGHTING, &lighting_on ); glDisable( GL_LIGHTING ); // Put the volume's matrix on the stack position_matrix->Transpose(); glPushMatrix(); glMultMatrixf( (*position_matrix)[0] ); // Do the far buffer glDepthFunc( GL_GREATER ); glClearColor( (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0) ); glClearDepth( (GLclampd)(0.0) ); glClear((GLbitfield)(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); glCallList( this->DisplayList ); glReadPixels( 0, 0, size[0], size[1], GL_DEPTH_COMPONENT, GL_FLOAT, far_buffer ); // Do the near buffer glDepthFunc( GL_LESS ); glClearColor( (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0) ); glClearDepth( (GLclampd)(1.0) ); glClear((GLbitfield)(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); glCallList( this->DisplayList ); glReadPixels( 0, 0, size[0], size[1], GL_DEPTH_COMPONENT, GL_FLOAT, near_buffer ); // Clean up glPopMatrix(); glDepthFunc( GL_LEQUAL ); if ( lighting_on ) glEnable( GL_LIGHTING ); glPopAttrib(); near_ptr = near_buffer; far_ptr = far_buffer; range_ptr = this->DepthRangeBuffer; if( ren->GetActiveCamera()->GetParallelProjection() ) { // Get the aspect ratio of the renderer ren->GetAspect( ren_aspect ); aspect = ren_aspect[0]/ren_aspect[1]; // Get the clipping range of the active camera ren->GetActiveCamera()->GetClippingRange( range ); // Create the perspective matrix for the camera. This will be used // to decode z values, so we will need to inverted transform->SetMatrix( ren->GetActiveCamera()->GetPerspectiveTransform( aspect, 0, 1 ) ); transform->Inverse(); // To speed things up, we pull the matrix out of the transform. // This way, we can decode z values faster since we know which elements // of the matrix are important, and which are zero. transform->GetMatrix( *matrix ); // Just checking that our assumptions are correct. This code should // be removed after the debugging phase is complete if( this->Debug ) { if ( matrix->Element[3][0] || matrix->Element[3][1] || matrix->Element[3][2] || matrix->Element[2][3] || (matrix->Element[3][3] != 1.0) ) { vtkErrorMacro( << "Oh no! They aren't 0 like they're supposed to be!"); cout << *transform; } } // These are the important elements of the matrix. We will decode // z values by : ((zbuffer value)*znum3) zfactor = -(matrix->Element[2][2]); for ( j = 0; j < size[1]; j++ ) for ( i = 0; i < size[0]; i++ ) { if ( *near_ptr < 1.0 ) { *(range_ptr++) = ((*(near_ptr++))*2.0 -1.0) * zfactor; *(range_ptr++) = ((*( far_ptr++))*2.0 -1.0) * zfactor; } else { *(range_ptr++) = -1.0; *(range_ptr++) = -1.0; near_ptr++; far_ptr++; } } } else { // Get the aspect ratio of the renderer ren->GetAspect( ren_aspect ); aspect = ren_aspect[0]/ren_aspect[1]; // Get the clipping range of the active camera ren->GetActiveCamera()->GetClippingRange( range ); // Create the perspective matrix for the camera. This will be used // to decode z values, so we will need to invert it transform->SetMatrix( ren->GetActiveCamera()->GetPerspectiveTransform( aspect, 0, 1 ) ); transform->Inverse(); // To speed things up, we pull the matrix out of the transform. // This way, we can decode z values faster since we know which elements // of the matrix are important, and which are zero. transform->GetMatrix( *matrix ); // Just checking that our assumptions are correct. This code should // be removed after the debugging phase is complete if( this->Debug ) { if ( matrix->Element[2][0] || matrix->Element[2][1] || matrix->Element[3][0] || matrix->Element[3][1] || matrix->Element[2][2] ) vtkErrorMacro( << "Oh no! They aren't 0 like they're supposed to be!"); } // These are the important elements of the matrix. We will decode // z values by taking the znum1 and dividing by the zbuffer z value times // zdenom1 plus zdenom2. z_numerator = matrix->Element[2][3]; z_denom_mult = matrix->Element[3][2]; z_denom_add = matrix->Element[3][3]; ray_ptr = volren->GetPerspectiveViewRays(); ray_ptr += 2; for ( j = 0; j < size[1]; j++ ) for ( i = 0; i < size[0]; i++ ) { if ( *near_ptr < 1.0 ) { *(range_ptr++) = (-z_numerator / ( ((*(near_ptr++))*2.0 -1.0) * z_denom_mult + z_denom_add )) / (-(*ray_ptr)); *(range_ptr++) = (-z_numerator / ( ((*(far_ptr++))*2.0 -1.0) * z_denom_mult + z_denom_add )) / (-(*ray_ptr)); ray_ptr += 3; } else { *(range_ptr++) = -1.0; *(range_ptr++) = -1.0; near_ptr++; far_ptr++; ray_ptr += 3; } } } delete near_buffer; delete far_buffer; // Delete the objects we created transform->Delete(); matrix->Delete(); return ( this->DepthRangeBuffer ); } // Description: // Print the vtkOpenGLProjectedPolyDataRayBounder void vtkOpenGLProjectedPolyDataRayBounder::PrintSelf(ostream& os, vtkIndent indent) { vtkProjectedPolyDataRayBounder::PrintSelf(os,indent); } <commit_msg>Some type casting to fix compile bugs on the Sun. (Lisa)<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkOpenGLProjectedPolyDataRayBounder.cxx Language: C++ Date: $Date$ Version: $Revision$ Thanks: Thanks to Lisa Sobierajski Avila who developed this class. Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkOpenGLProjectedPolyDataRayBounder.h" #include "vtkNew2VolumeRenderer.h" // Description: // Construct a new vtkOpenGLProjectedPolyDataRayBounder. The depth range // buffer is initially NULL and no display list has been created vtkOpenGLProjectedPolyDataRayBounder::vtkOpenGLProjectedPolyDataRayBounder() { this->DisplayList = 0; this->DepthRangeBuffer = NULL; } // Description: // Destruct the vtkOpenGLProjectedPolyDataRayBounder. Free the // DepthRangeBuffer if necessary vtkOpenGLProjectedPolyDataRayBounder::~vtkOpenGLProjectedPolyDataRayBounder() { if ( this->DepthRangeBuffer ) delete this->DepthRangeBuffer; } // Description: // Create a display list from the polygons contained in pdata. // Lines and vertices are ignored, polys and strips are used. void vtkOpenGLProjectedPolyDataRayBounder::Build( vtkPolyData *pdata ) { vtkCellArray *polys; vtkCellArray *strips; vtkPoints *points; int *pts, npts; int current_num_vertices = -1; int i; polys = pdata->GetPolys(); points = pdata->GetPoints(); strips = pdata->GetStrips(); if ( !glIsList( this->DisplayList ) ) this->DisplayList = glGenLists( 1 ); glNewList( this->DisplayList, GL_COMPILE ); for ( polys->InitTraversal(); polys->GetNextCell( npts, pts ); ) { // If we are doing a different number of vertices, or if this // is a polygon, then end what we were doing and begin again if ( current_num_vertices != npts || npts > 4 ) { // Unless of course this is our first time through - then we // don't want to end if ( current_num_vertices != -1 ) glEnd(); // How many vertices do we have? if ( npts == 3 ) glBegin( GL_TRIANGLES ); else if ( npts == 4 ) glBegin( GL_QUADS ); else glBegin( GL_POLYGON ); } // Draw the vertices for ( i = 0; i < npts; i++ ) glVertex3fv( points->GetPoint( pts[i] ) ); current_num_vertices = npts; } glEnd(); for ( strips->InitTraversal(); strips->GetNextCell( npts, pts ); ) { glBegin( GL_TRIANGLE_STRIP ); // Draw the vertices for ( i = 0; i < npts; i++ ) glVertex3fv( points->GetPoint( pts[i] ) ); glEnd(); } glEndList(); } // Description: // Draw the display list and create the depth range buffer. // // Known problem: // camera clipping planes (near/far) may clip the projected // geometry resulting in incorrect results. float *vtkOpenGLProjectedPolyDataRayBounder::Draw( vtkRenderer *ren, vtkMatrix4x4 *position_matrix ) { GLboolean lighting_on; int size[2]; float *near_buffer, *far_buffer; vtkTransform *transform; vtkMatrix4x4 *matrix; float ren_aspect[2], aspect, range[2]; float *ray_ptr; float *near_ptr, *far_ptr; float *range_ptr; vtkNew2VolumeRenderer *volren; float z_numerator, z_denom_mult, z_denom_add; float zfactor; int i, j; GLint current_viewport[4]; volren = (vtkNew2VolumeRenderer *) ren->GetNewVolumeRenderer(); // Create some objects that we will need later transform = vtkTransform::New(); matrix = vtkMatrix4x4::New(); // The size of the view rays is the size of the image we are creating ((vtkNew2VolumeRenderer *) (ren->GetNewVolumeRenderer()))->GetViewRaysSize( size ); // This should be fixed - I should not be off in someone else's viewport // if there are more than one of them... glGetIntegerv( GL_VIEWPORT, current_viewport ); glPushAttrib(GL_VIEWPORT_BIT); glViewport( current_viewport[0], current_viewport[1], (GLsizei) size[0], (GLsizei) size[1] ); // Create the near buffer storage near_buffer = new float[ size[0] * size[1] ]; // Create the far buffer storage far_buffer = new float[ size[0] * size[1] ]; if ( this->DepthRangeBuffer ) delete this->DepthRangeBuffer; this->DepthRangeBuffer = new float[ size[0] * size[1] * 2 ]; // Save previous lighting state, and turn lighting off glGetBooleanv( GL_LIGHTING, &lighting_on ); glDisable( GL_LIGHTING ); // Put the volume's matrix on the stack position_matrix->Transpose(); glPushMatrix(); glMultMatrixf( (*position_matrix)[0] ); // Do the far buffer glDepthFunc( GL_GREATER ); glClearColor( (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0) ); glClearDepth( (GLclampd)(0.0) ); glClear((GLbitfield)(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); glCallList( this->DisplayList ); glReadPixels( 0, 0, size[0], size[1], GL_DEPTH_COMPONENT, GL_FLOAT, far_buffer ); // Do the near buffer glDepthFunc( GL_LESS ); glClearColor( (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0), (GLclampf)(0.0) ); glClearDepth( (GLclampd)(1.0) ); glClear((GLbitfield)(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)); glCallList( this->DisplayList ); glReadPixels( (GLint) 0, (GLint) 0, (GLsizei) size[0], (GLsizei) size[1], GL_DEPTH_COMPONENT, GL_FLOAT, near_buffer ); // Clean up glPopMatrix(); glDepthFunc( GL_LEQUAL ); if ( lighting_on ) glEnable( GL_LIGHTING ); glPopAttrib(); near_ptr = near_buffer; far_ptr = far_buffer; range_ptr = this->DepthRangeBuffer; if( ren->GetActiveCamera()->GetParallelProjection() ) { // Get the aspect ratio of the renderer ren->GetAspect( ren_aspect ); aspect = ren_aspect[0]/ren_aspect[1]; // Get the clipping range of the active camera ren->GetActiveCamera()->GetClippingRange( range ); // Create the perspective matrix for the camera. This will be used // to decode z values, so we will need to inverted transform->SetMatrix( ren->GetActiveCamera()->GetPerspectiveTransform( aspect, 0, 1 ) ); transform->Inverse(); // To speed things up, we pull the matrix out of the transform. // This way, we can decode z values faster since we know which elements // of the matrix are important, and which are zero. transform->GetMatrix( *matrix ); // Just checking that our assumptions are correct. This code should // be removed after the debugging phase is complete if( this->Debug ) { if ( matrix->Element[3][0] || matrix->Element[3][1] || matrix->Element[3][2] || matrix->Element[2][3] || (matrix->Element[3][3] != 1.0) ) { vtkErrorMacro( << "Oh no! They aren't 0 like they're supposed to be!"); cout << *transform; } } // These are the important elements of the matrix. We will decode // z values by : ((zbuffer value)*znum3) zfactor = -(matrix->Element[2][2]); for ( j = 0; j < size[1]; j++ ) for ( i = 0; i < size[0]; i++ ) { if ( *near_ptr < 1.0 ) { *(range_ptr++) = ((*(near_ptr++))*2.0 -1.0) * zfactor; *(range_ptr++) = ((*( far_ptr++))*2.0 -1.0) * zfactor; } else { *(range_ptr++) = -1.0; *(range_ptr++) = -1.0; near_ptr++; far_ptr++; } } } else { // Get the aspect ratio of the renderer ren->GetAspect( ren_aspect ); aspect = ren_aspect[0]/ren_aspect[1]; // Get the clipping range of the active camera ren->GetActiveCamera()->GetClippingRange( range ); // Create the perspective matrix for the camera. This will be used // to decode z values, so we will need to invert it transform->SetMatrix( ren->GetActiveCamera()->GetPerspectiveTransform( aspect, 0, 1 ) ); transform->Inverse(); // To speed things up, we pull the matrix out of the transform. // This way, we can decode z values faster since we know which elements // of the matrix are important, and which are zero. transform->GetMatrix( *matrix ); // Just checking that our assumptions are correct. This code should // be removed after the debugging phase is complete if( this->Debug ) { if ( matrix->Element[2][0] || matrix->Element[2][1] || matrix->Element[3][0] || matrix->Element[3][1] || matrix->Element[2][2] ) vtkErrorMacro( << "Oh no! They aren't 0 like they're supposed to be!"); } // These are the important elements of the matrix. We will decode // z values by taking the znum1 and dividing by the zbuffer z value times // zdenom1 plus zdenom2. z_numerator = matrix->Element[2][3]; z_denom_mult = matrix->Element[3][2]; z_denom_add = matrix->Element[3][3]; ray_ptr = volren->GetPerspectiveViewRays(); ray_ptr += 2; for ( j = 0; j < size[1]; j++ ) for ( i = 0; i < size[0]; i++ ) { if ( *near_ptr < 1.0 ) { *(range_ptr++) = (-z_numerator / ( ((*(near_ptr++))*2.0 -1.0) * z_denom_mult + z_denom_add )) / (-(*ray_ptr)); *(range_ptr++) = (-z_numerator / ( ((*(far_ptr++))*2.0 -1.0) * z_denom_mult + z_denom_add )) / (-(*ray_ptr)); ray_ptr += 3; } else { *(range_ptr++) = -1.0; *(range_ptr++) = -1.0; near_ptr++; far_ptr++; ray_ptr += 3; } } } delete near_buffer; delete far_buffer; // Delete the objects we created transform->Delete(); matrix->Delete(); return ( this->DepthRangeBuffer ); } // Description: // Print the vtkOpenGLProjectedPolyDataRayBounder void vtkOpenGLProjectedPolyDataRayBounder::PrintSelf(ostream& os, vtkIndent indent) { vtkProjectedPolyDataRayBounder::PrintSelf(os,indent); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: qtITK.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <qapplication.h> #include <qpushbutton.h> #include "itkImage.h" #include "itkImageFileReader.h" #include "itkAddImageFilter.h" #include "itkQtAdaptor.h" #include "itkQtLightIndicator.h" #include "itkQtProgressBar.h" int main(int argc, char **argv) { typedef itk::Image< float, 2 > ImageType; typedef itk::AddImageFilter< ImageType, ImageType, ImageType > FilterType; typedef itk::ImageFileReader< ImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); FilterType::Pointer filter = FilterType::New(); filter->SetInput1( reader->GetOutput() ); filter->SetInput2( reader->GetOutput() ); // Create Qt Application to let Qt get its // parameters from the command line QApplication app( argc, argv ); reader->SetFileName( argv[1] ); QWidget qb; qb.resize(620,100); const int buttonWidth = 70; const int buttonHeight = 30; const int buttonSpace = 80; int horizontalPosition = 30; QPushButton bb( "Start", &qb ); bb.setGeometry( horizontalPosition, 20, buttonWidth, buttonHeight ); horizontalPosition += buttonWidth + buttonSpace; itk::QtLightIndicator cc( &qb, "State" ); cc.setGeometry( horizontalPosition, 20, buttonWidth, buttonHeight ); cc.Modified(); horizontalPosition += buttonWidth + buttonSpace; QPushButton qt( "Quit", &qb ); qt.setGeometry( horizontalPosition, 20, buttonWidth, buttonHeight ); itk::QtProgressBar qs( &qb, "Progress"); qs.setGeometry( 10, 60, 600, 30 ); // Connect the progress bar to the ITK processObject qs.Observe( filter.GetPointer() ); qs.Observe( reader.GetPointer() ); typedef itk::QtSlotAdaptor<FilterType> SlotAdaptorType; SlotAdaptorType slotAdaptor; // Connect the adaptor to a method of the ITK filter slotAdaptor.SetCallbackFunction( filter, & FilterType::Update ); // Connect the adaptor's Slot to the Qt Widget Signal QObject::connect( &bb, SIGNAL(clicked()), &slotAdaptor, SLOT(Slot()) ); // One signal adaptor for observing the StartEvent() typedef itk::QtSignalAdaptor SignalAdaptorType; SignalAdaptorType signalAdaptor1; // Connect the adaptor as an observer of a Filter's event filter->AddObserver( itk::StartEvent(), signalAdaptor1.GetCommand() ); // Connect the adaptor's Signal to the Qt Widget Slot QObject::connect( &signalAdaptor1, SIGNAL(Signal()), &cc, SLOT(Start()) ); // One signal adaptor for observing the ModifiedEvent() typedef itk::QtSignalAdaptor SignalAdaptorType; SignalAdaptorType signalAdaptor2; // Connect the adaptor as an observer of a Filter's event filter->AddObserver( itk::ModifiedEvent(), signalAdaptor2.GetCommand() ); // Connect the adaptor's Signal to the Qt Widget Slot QObject::connect( &signalAdaptor2, SIGNAL(Signal()), &cc, SLOT(Modified()) ); // One signal adaptor for observing the EndEvent() typedef itk::QtSignalAdaptor SignalAdaptorType; SignalAdaptorType signalAdaptor3; // Connect the adaptor as an observer of a Filter's event filter->AddObserver( itk::EndEvent(), signalAdaptor3.GetCommand() ); // Connect the adaptor's Signal to the Qt Widget Slot QObject::connect( &signalAdaptor3, SIGNAL(Signal()), &cc, SLOT(End()) ); // Connect the Quit button signal to the quit slot of the application QObject::connect( &qt, SIGNAL(clicked()), &app, SLOT(quit()) ); app.setMainWidget( &qb ); qb.show(); return app.exec(); } <commit_msg>ENH: fine tunning button positions.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: qtITK.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <qapplication.h> #include <qpushbutton.h> #include "itkImage.h" #include "itkImageFileReader.h" #include "itkAddImageFilter.h" #include "itkQtAdaptor.h" #include "itkQtLightIndicator.h" #include "itkQtProgressBar.h" int main(int argc, char **argv) { typedef itk::Image< float, 2 > ImageType; typedef itk::AddImageFilter< ImageType, ImageType, ImageType > FilterType; typedef itk::ImageFileReader< ImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); FilterType::Pointer filter = FilterType::New(); filter->SetInput1( reader->GetOutput() ); filter->SetInput2( reader->GetOutput() ); // Create Qt Application to let Qt get its // parameters from the command line QApplication app( argc, argv ); reader->SetFileName( argv[1] ); QWidget qb; qb.resize(620,100); const int buttonHeight = 30; const int buttonWidth = 100; const int buttonSpace = 100; int horizontalPosition = 60; QPushButton bb( "Start", &qb ); bb.setGeometry( horizontalPosition, 20, buttonWidth, buttonHeight ); horizontalPosition += buttonWidth + buttonSpace; itk::QtLightIndicator cc( &qb, "State" ); cc.setGeometry( horizontalPosition, 20, buttonWidth, buttonHeight ); cc.Modified(); horizontalPosition += buttonWidth + buttonSpace; QPushButton qt( "Quit", &qb ); qt.setGeometry( horizontalPosition, 20, buttonWidth, buttonHeight ); itk::QtProgressBar qs( &qb, "Progress"); qs.setGeometry( 10, 60, 600, 30 ); // Connect the progress bar to the ITK processObject qs.Observe( filter.GetPointer() ); qs.Observe( reader.GetPointer() ); typedef itk::QtSlotAdaptor<FilterType> SlotAdaptorType; SlotAdaptorType slotAdaptor; // Connect the adaptor to a method of the ITK filter slotAdaptor.SetCallbackFunction( filter, & FilterType::Update ); // Connect the adaptor's Slot to the Qt Widget Signal QObject::connect( &bb, SIGNAL(clicked()), &slotAdaptor, SLOT(Slot()) ); // One signal adaptor for observing the StartEvent() typedef itk::QtSignalAdaptor SignalAdaptorType; SignalAdaptorType signalAdaptor1; // Connect the adaptor as an observer of a Filter's event filter->AddObserver( itk::StartEvent(), signalAdaptor1.GetCommand() ); // Connect the adaptor's Signal to the Qt Widget Slot QObject::connect( &signalAdaptor1, SIGNAL(Signal()), &cc, SLOT(Start()) ); // One signal adaptor for observing the ModifiedEvent() typedef itk::QtSignalAdaptor SignalAdaptorType; SignalAdaptorType signalAdaptor2; // Connect the adaptor as an observer of a Filter's event filter->AddObserver( itk::ModifiedEvent(), signalAdaptor2.GetCommand() ); // Connect the adaptor's Signal to the Qt Widget Slot QObject::connect( &signalAdaptor2, SIGNAL(Signal()), &cc, SLOT(Modified()) ); // One signal adaptor for observing the EndEvent() typedef itk::QtSignalAdaptor SignalAdaptorType; SignalAdaptorType signalAdaptor3; // Connect the adaptor as an observer of a Filter's event filter->AddObserver( itk::EndEvent(), signalAdaptor3.GetCommand() ); // Connect the adaptor's Signal to the Qt Widget Slot QObject::connect( &signalAdaptor3, SIGNAL(Signal()), &cc, SLOT(End()) ); // Connect the Quit button signal to the quit slot of the application QObject::connect( &qt, SIGNAL(clicked()), &app, SLOT(quit()) ); app.setMainWidget( &qb ); qb.show(); return app.exec(); } <|endoftext|>
<commit_before><commit_msg>Make sure the number of the tokens in the line pointed to by the latchoffset is 5.<commit_after><|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "QtHttpAssetProvider.h" #include "ConfigurationManager.h" #include "EventManager.h" #include "AssetModule.h" #include "RexAsset.h" #include "AssetMetadataInterface.h" #include "AssetServiceInterface.h" #include "AssetEvents.h" #include <QUuid> #include <QNetworkReply> #include <QByteArray> #include <QDebug> #include <QStringList> #define MAX_HTTP_CONNECTIONS 10000 // Basically means no limit to parallel connections namespace Asset { QtHttpAssetProvider::QtHttpAssetProvider(Foundation::Framework *framework) : QObject(), framework_(framework), event_manager_(framework->GetEventManager().get()), name_("QtHttpAssetProvider"), network_manager_(new QNetworkAccessManager()), filling_stack_(false), get_texture_cap_(QUrl()) { asset_timeout_ = framework_->GetDefaultConfig().DeclareSetting("AssetSystem", "http_timeout", 120.0); if (event_manager_) asset_event_category_ = event_manager_->QueryEventCategory("Asset"); if (!asset_event_category_) AssetModule::LogWarning("QtHttpAssetProvider >> Could not get event category for Asset events"); connect(network_manager_, SIGNAL(finished(QNetworkReply*)), SLOT(TranferCompleted(QNetworkReply*))); AssetModule::LogWarning(QString("QtHttpAssetProvider >> Initialized with max %1 parallel HTTP connections").arg(QString::number(MAX_HTTP_CONNECTIONS)).toStdString()); } QtHttpAssetProvider::~QtHttpAssetProvider() { SAFE_DELETE(network_manager_); } void QtHttpAssetProvider::SetGetTextureCap(std::string url) { get_texture_cap_ = QUrl(QString::fromStdString(url)); } // Interface implementation void QtHttpAssetProvider::Update(f64 frametime) { StartTransferFromQueue(); } const std::string& QtHttpAssetProvider::Name() { return name_; } bool QtHttpAssetProvider::IsValidId(const std::string& asset_id, const std::string& asset_type) { // Textures over http with the GetTexture cap if (IsAcceptableAssetType(asset_type)) if (RexUUID::IsValid(asset_id) && get_texture_cap_.isValid()) return true; QString id(asset_id.c_str()); if (!id.startsWith("http://")) return false; QUrl asset_url(id); if (asset_url.isValid()) return true; else return false; } bool QtHttpAssetProvider::RequestAsset(const std::string& asset_id, const std::string& asset_type, request_tag_t tag) { if (!IsValidId(asset_id, asset_type)) return false; QString asset_id_qstring = QString::fromStdString(asset_id); if (assetid_to_transfer_map_.contains(asset_id_qstring)) { assetid_to_transfer_map_[asset_id_qstring]->GetTranferInfo().AddTag(tag); } else { asset_type_t asset_type_int = RexTypes::GetAssetTypeFromTypeName(asset_type); QtHttpAssetTransfer *transfer = 0; if (IsAcceptableAssetType(asset_type)) { // Http texture via cap url QString texture_url_string = get_texture_cap_.toString() + "?texture_id=" + asset_id_qstring; QUrl texture_url(texture_url_string); transfer = new QtHttpAssetTransfer(texture_url, asset_id_qstring, asset_type_int, tag); } else { // Normal http get QUrl asset_url = CreateUrl(asset_id_qstring); transfer = new QtHttpAssetTransfer(asset_url, asset_id_qstring, asset_type_int, tag); } if (!transfer) return false; transfer->setOriginatingObject(transfer); if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS) { assetid_to_transfer_map_[asset_id_qstring] = transfer; network_manager_->get(*transfer); AssetModule::LogDebug("New HTTP asset request: " + asset_id + " type: " + asset_type); } else pending_request_queue_.append(transfer); } return true; } bool QtHttpAssetProvider::InProgress(const std::string& asset_id) { QString qt_asset_id = QString::fromStdString(asset_id); if (assetid_to_transfer_map_.contains(qt_asset_id) || CheckRequestQueue(qt_asset_id)) return true; else return false; } bool QtHttpAssetProvider::QueryAssetStatus(const std::string& asset_id, uint& size, uint& received, uint& received_continuous) { if (InProgress(asset_id)) { // We dont know, QNetworkAccessManager handles these size = 0; received = 0; received_continuous = 0; return true; } else return false; } Foundation::AssetPtr QtHttpAssetProvider::GetIncompleteAsset(const std::string& asset_id, const std::string& asset_type, uint received) { return Foundation::AssetPtr(); } Foundation::AssetTransferInfoVector QtHttpAssetProvider::GetTransferInfo() { Foundation::AssetTransferInfoVector info_vector; foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values()) { HttpAssetTransferInfo iter_info = transfer->GetTranferInfo(); // What we know Foundation::AssetTransferInfo info; info.id_ = iter_info.id.toStdString(); info.type_ = RexTypes::GetAssetTypeString(iter_info.type); info.provider_ = Name(); // The following we dont know, QNetworkAccessManager handles these info.size_ = 0; info.received_ = 0; info.received_continuous_ = 0; info_vector.push_back(info); } return info_vector; } // Private QUrl QtHttpAssetProvider::CreateUrl(QString assed_id) { if (!assed_id.startsWith("http://") && !assed_id.startsWith("https://")) assed_id = "http://" + assed_id; return QUrl(assed_id); } void QtHttpAssetProvider::TranferCompleted(QNetworkReply *reply) { fake_metadata_fetch_ = false; QtHttpAssetTransfer *transfer = dynamic_cast<QtHttpAssetTransfer*>(reply->request().originatingObject()); /**** THIS IS A DATA REQUEST REPLY AND IT FAILED ****/ if (reply->error() != QNetworkReply::NoError && transfer) { // Send asset canceled events HttpAssetTransferInfo error_transfer_data = transfer->GetTranferInfo(); Events::AssetCanceled *data = new Events::AssetCanceled(error_transfer_data.id.toStdString(), RexTypes::GetAssetTypeString(error_transfer_data.type)); Foundation::EventDataPtr data_ptr(data); event_manager_->SendDelayedEvent(asset_event_category_, Events::ASSET_CANCELED, data_ptr, 0); // Clean up RemoveFinishedTransfers(error_transfer_data.id, reply->url()); StartTransferFromQueue(); AssetModule::LogDebug("HTTP asset " + error_transfer_data.id.toStdString() + " canceled"); reply->deleteLater(); return; } /**** THIS IS A /data REQUEST REPLY ****/ if (transfer) { // Create asset pointer HttpAssetTransferInfo tranfer_info = transfer->GetTranferInfo(); std::string id = tranfer_info.id.toStdString(); std::string type = RexTypes::GetTypeNameFromAssetType(tranfer_info.type); Foundation::AssetPtr asset_ptr = Foundation::AssetPtr(new RexAsset(id, type)); // Fill asset data with reply data RexAsset::AssetDataVector& data_vector = checked_static_cast<RexAsset*>(asset_ptr.get())->GetDataInternal(); QByteArray data_array = reply->readAll(); for (int index = 0; index < data_array.count(); ++index) data_vector.push_back(data_array.at(index)); // Get metadata if available QString url_path = tranfer_info.url.path(); if (url_path.endsWith("/data") || url_path.endsWith("/data/")) { // Generate metada url int clip_count; if (url_path.endsWith("/data")) clip_count = 5; else if (url_path.endsWith("/data/")) clip_count = 6; else { reply->deleteLater(); return; } QUrl metadata_url = tranfer_info.url; url_path = url_path.left(url_path.count()-clip_count); url_path = url_path + "/metadata"; metadata_url.setPath(url_path); tranfer_info.url = metadata_url; QNetworkRequest *metada_request = new QNetworkRequest(metadata_url); // Store tranfer data and asset data pointer internally QPair<HttpAssetTransferInfo, Foundation::AssetPtr> data_pair; data_pair.first = tranfer_info; data_pair.second = asset_ptr; metadata_to_assetptr_[metada_request->url()] = data_pair; // Send metadata network request //network_manager_->get(*metada_request); // HACK to avoid metadata fetch for now fake_metadata_url_ = metada_request->url(); fake_metadata_fetch_ = true; } // Asset data feched, lets store else { // Store asset boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = framework_->GetServiceManager()->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock(); if (asset_service) asset_service->StoreAsset(asset_ptr); // Send asset ready events foreach (request_tag_t tag, tranfer_info.tags) { Events::AssetReady event_data(asset_ptr.get()->GetId(), asset_ptr.get()->GetType(), asset_ptr, tag); event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data); } RemoveFinishedTransfers(tranfer_info.id, QUrl()); StartTransferFromQueue(); AssetModule::LogDebug("HTTP asset " + tranfer_info.id.toStdString() + " completed"); } } // Complete /data and /metadata sequence, fake is here as long as we dont have xml parser for metadata // or actually we dont use metadata in naali so thats the main reason its not fetched if (fake_metadata_fetch_) { /**** THIS IS A /metadata REQUEST REPLY ****/ if (metadata_to_assetptr_.contains(fake_metadata_url_)) { // Pull out transfer data and asset pointer assosiated with this reply url QUrl metadata_transfer_url = fake_metadata_url_; HttpAssetTransferInfo transfer_data = metadata_to_assetptr_[metadata_transfer_url].first; Foundation::AssetPtr ready_asset_ptr = metadata_to_assetptr_[metadata_transfer_url].second; if (!ready_asset_ptr) { reply->deleteLater(); return; } // Fill metadata /* const QByteArray &inbound_metadata = reply->readAll(); QString decoded_metadata = QString::fromUtf8(inbound_metadata.data()); #if defined(__GNUC__) RexAssetMetadata *m = dynamic_cast<RexAssetMetadata*>(ready_asset_ptr.get()->GetMetadata()); #else Foundation::AssetMetadataInterface *metadata = ready_asset_ptr.get()->GetMetadata(); RexAssetMetadata *m = static_cast<RexAssetMetadata*>(metadata); #endif std::string std_md(decoded_metadata.toStdString()); m->DesesrializeFromJSON(std_md); // TODO: implement a xml based metadata parser. */ // Store asset boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = framework_->GetServiceManager()->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock(); if (asset_service) asset_service->StoreAsset(ready_asset_ptr); // Send asset ready events foreach (request_tag_t tag, transfer_data.tags) { Events::AssetReady event_data(ready_asset_ptr.get()->GetId(), ready_asset_ptr.get()->GetType(), ready_asset_ptr, tag); event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data); } RemoveFinishedTransfers(transfer_data.id, metadata_transfer_url); StartTransferFromQueue(); AssetModule::LogDebug("HTTP asset " + transfer_data.id.toStdString() + " completed with metadata"); } } reply->deleteLater(); } void QtHttpAssetProvider::RemoveFinishedTransfers(QString asset_transfer_key, QUrl metadata_transfer_key) { QtHttpAssetTransfer *remove_transfer = assetid_to_transfer_map_[asset_transfer_key]; assetid_to_transfer_map_.remove(asset_transfer_key); if (metadata_transfer_key.isValid()) metadata_to_assetptr_.remove(metadata_transfer_key); SAFE_DELETE(remove_transfer); } void QtHttpAssetProvider::ClearAllTransfers() { foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values()) SAFE_DELETE(transfer); assetid_to_transfer_map_.clear(); foreach (QtHttpAssetTransfer *transfer, pending_request_queue_) SAFE_DELETE(transfer); pending_request_queue_.clear(); } void QtHttpAssetProvider::StartTransferFromQueue() { if (pending_request_queue_.count() == 0) return; // If the whole map is empty then go and start new MAX_HTTP_CONNECTIONS amount of http gets if (assetid_to_transfer_map_.count() == 0) filling_stack_ = true; if (!filling_stack_) return; if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS && pending_request_queue_.count() > 0) { if (assetid_to_transfer_map_.count() == MAX_HTTP_CONNECTIONS || pending_request_queue_.count() == 0) filling_stack_ = false; else { QtHttpAssetTransfer *new_transfer = pending_request_queue_.takeAt(0); assetid_to_transfer_map_[new_transfer->GetTranferInfo().id] = new_transfer; network_manager_->get(*new_transfer); AssetModule::LogDebug("New HTTP asset request from queue: " + new_transfer->GetTranferInfo().id.toStdString() + " type: " + RexTypes::GetAssetTypeString(new_transfer->GetTranferInfo().type)); StartTransferFromQueue(); // Recursivly fill the transfer map } } } bool QtHttpAssetProvider::CheckRequestQueue(QString assed_id) { foreach (QtHttpAssetTransfer *transfer, pending_request_queue_) if (transfer->GetTranferInfo().id == assed_id) return true; return false; } bool QtHttpAssetProvider::IsAcceptableAssetType(const std::string& asset_type) { using namespace RexTypes; bool accepted = false; switch (GetAssetTypeFromTypeName(asset_type)) { case RexAT_Texture: case RexAT_Mesh: accepted = true; break; default: accepted = false; break; } return accepted; } }<commit_msg>Bug fix to handle urls properly if caps url not set (modrex addurls etc). Printing a info line to console if server has http assets enabled.<commit_after>// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "QtHttpAssetProvider.h" #include "ConfigurationManager.h" #include "EventManager.h" #include "AssetModule.h" #include "RexAsset.h" #include "AssetMetadataInterface.h" #include "AssetServiceInterface.h" #include "AssetEvents.h" #include <QUuid> #include <QNetworkReply> #include <QByteArray> #include <QDebug> #include <QStringList> #define MAX_HTTP_CONNECTIONS 10000 // Basically means no limit to parallel connections namespace Asset { QtHttpAssetProvider::QtHttpAssetProvider(Foundation::Framework *framework) : QObject(), framework_(framework), event_manager_(framework->GetEventManager().get()), name_("QtHttpAssetProvider"), network_manager_(new QNetworkAccessManager()), filling_stack_(false), get_texture_cap_(QUrl()) { asset_timeout_ = framework_->GetDefaultConfig().DeclareSetting("AssetSystem", "http_timeout", 120.0); if (event_manager_) asset_event_category_ = event_manager_->QueryEventCategory("Asset"); if (!asset_event_category_) AssetModule::LogWarning("QtHttpAssetProvider >> Could not get event category for Asset events"); connect(network_manager_, SIGNAL(finished(QNetworkReply*)), SLOT(TranferCompleted(QNetworkReply*))); AssetModule::LogWarning(QString("QtHttpAssetProvider >> Initialized with max %1 parallel HTTP connections").arg(QString::number(MAX_HTTP_CONNECTIONS)).toStdString()); } QtHttpAssetProvider::~QtHttpAssetProvider() { SAFE_DELETE(network_manager_); } void QtHttpAssetProvider::SetGetTextureCap(std::string url) { get_texture_cap_ = QUrl(QString::fromStdString(url)); if (get_texture_cap_.isValid()) AssetModule::LogInfo("Server supports HTTP assets: using HTTP to fetch textures and meshes."); } // Interface implementation void QtHttpAssetProvider::Update(f64 frametime) { StartTransferFromQueue(); } const std::string& QtHttpAssetProvider::Name() { return name_; } bool QtHttpAssetProvider::IsValidId(const std::string& asset_id, const std::string& asset_type) { // Textures over http with the GetTexture cap if (IsAcceptableAssetType(asset_type)) if (RexUUID::IsValid(asset_id) && get_texture_cap_.isValid()) return true; QString id(asset_id.c_str()); if (!id.startsWith("http://")) return false; QUrl asset_url(id); if (asset_url.isValid()) return true; else return false; } bool QtHttpAssetProvider::RequestAsset(const std::string& asset_id, const std::string& asset_type, request_tag_t tag) { if (!IsValidId(asset_id, asset_type)) return false; QString asset_id_qstring = QString::fromStdString(asset_id); if (assetid_to_transfer_map_.contains(asset_id_qstring)) { assetid_to_transfer_map_[asset_id_qstring]->GetTranferInfo().AddTag(tag); } else { asset_type_t asset_type_int = RexTypes::GetAssetTypeFromTypeName(asset_type); QtHttpAssetTransfer *transfer = 0; if (IsAcceptableAssetType(asset_type) && RexUUID::IsValid(asset_id) && get_texture_cap_.isValid()) { // Http texture/meshes via cap url QString texture_url_string = get_texture_cap_.toString() + "?texture_id=" + asset_id_qstring; QUrl texture_url(texture_url_string); transfer = new QtHttpAssetTransfer(texture_url, asset_id_qstring, asset_type_int, tag); } else { // Normal http get QUrl asset_url = CreateUrl(asset_id_qstring); transfer = new QtHttpAssetTransfer(asset_url, asset_id_qstring, asset_type_int, tag); } if (!transfer) return false; transfer->setOriginatingObject(transfer); if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS) { assetid_to_transfer_map_[asset_id_qstring] = transfer; network_manager_->get(*transfer); AssetModule::LogDebug("New HTTP asset request: " + asset_id + " type: " + asset_type); } else pending_request_queue_.append(transfer); } return true; } bool QtHttpAssetProvider::InProgress(const std::string& asset_id) { QString qt_asset_id = QString::fromStdString(asset_id); if (assetid_to_transfer_map_.contains(qt_asset_id) || CheckRequestQueue(qt_asset_id)) return true; else return false; } bool QtHttpAssetProvider::QueryAssetStatus(const std::string& asset_id, uint& size, uint& received, uint& received_continuous) { if (InProgress(asset_id)) { // We dont know, QNetworkAccessManager handles these size = 0; received = 0; received_continuous = 0; return true; } else return false; } Foundation::AssetPtr QtHttpAssetProvider::GetIncompleteAsset(const std::string& asset_id, const std::string& asset_type, uint received) { return Foundation::AssetPtr(); } Foundation::AssetTransferInfoVector QtHttpAssetProvider::GetTransferInfo() { Foundation::AssetTransferInfoVector info_vector; foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values()) { HttpAssetTransferInfo iter_info = transfer->GetTranferInfo(); // What we know Foundation::AssetTransferInfo info; info.id_ = iter_info.id.toStdString(); info.type_ = RexTypes::GetAssetTypeString(iter_info.type); info.provider_ = Name(); // The following we dont know, QNetworkAccessManager handles these info.size_ = 0; info.received_ = 0; info.received_continuous_ = 0; info_vector.push_back(info); } return info_vector; } // Private QUrl QtHttpAssetProvider::CreateUrl(QString assed_id) { if (!assed_id.startsWith("http://") && !assed_id.startsWith("https://")) assed_id = "http://" + assed_id; return QUrl(assed_id); } void QtHttpAssetProvider::TranferCompleted(QNetworkReply *reply) { fake_metadata_fetch_ = false; QtHttpAssetTransfer *transfer = dynamic_cast<QtHttpAssetTransfer*>(reply->request().originatingObject()); /**** THIS IS A DATA REQUEST REPLY AND IT FAILED ****/ if (reply->error() != QNetworkReply::NoError && transfer) { // Send asset canceled events HttpAssetTransferInfo error_transfer_data = transfer->GetTranferInfo(); Events::AssetCanceled *data = new Events::AssetCanceled(error_transfer_data.id.toStdString(), RexTypes::GetAssetTypeString(error_transfer_data.type)); Foundation::EventDataPtr data_ptr(data); event_manager_->SendDelayedEvent(asset_event_category_, Events::ASSET_CANCELED, data_ptr, 0); // Clean up RemoveFinishedTransfers(error_transfer_data.id, reply->url()); StartTransferFromQueue(); AssetModule::LogDebug("HTTP asset " + error_transfer_data.id.toStdString() + " canceled"); reply->deleteLater(); return; } /**** THIS IS A /data REQUEST REPLY ****/ if (transfer) { // Create asset pointer HttpAssetTransferInfo tranfer_info = transfer->GetTranferInfo(); std::string id = tranfer_info.id.toStdString(); std::string type = RexTypes::GetTypeNameFromAssetType(tranfer_info.type); Foundation::AssetPtr asset_ptr = Foundation::AssetPtr(new RexAsset(id, type)); // Fill asset data with reply data RexAsset::AssetDataVector& data_vector = checked_static_cast<RexAsset*>(asset_ptr.get())->GetDataInternal(); QByteArray data_array = reply->readAll(); for (int index = 0; index < data_array.count(); ++index) data_vector.push_back(data_array.at(index)); // Get metadata if available QString url_path = tranfer_info.url.path(); if (url_path.endsWith("/data") || url_path.endsWith("/data/")) { // Generate metada url int clip_count; if (url_path.endsWith("/data")) clip_count = 5; else if (url_path.endsWith("/data/")) clip_count = 6; else { reply->deleteLater(); return; } QUrl metadata_url = tranfer_info.url; url_path = url_path.left(url_path.count()-clip_count); url_path = url_path + "/metadata"; metadata_url.setPath(url_path); tranfer_info.url = metadata_url; QNetworkRequest *metada_request = new QNetworkRequest(metadata_url); // Store tranfer data and asset data pointer internally QPair<HttpAssetTransferInfo, Foundation::AssetPtr> data_pair; data_pair.first = tranfer_info; data_pair.second = asset_ptr; metadata_to_assetptr_[metada_request->url()] = data_pair; // Send metadata network request //network_manager_->get(*metada_request); // HACK to avoid metadata fetch for now fake_metadata_url_ = metada_request->url(); fake_metadata_fetch_ = true; } // Asset data feched, lets store else { // Store asset boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = framework_->GetServiceManager()->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock(); if (asset_service) asset_service->StoreAsset(asset_ptr); // Send asset ready events foreach (request_tag_t tag, tranfer_info.tags) { Events::AssetReady event_data(asset_ptr.get()->GetId(), asset_ptr.get()->GetType(), asset_ptr, tag); event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data); } RemoveFinishedTransfers(tranfer_info.id, QUrl()); StartTransferFromQueue(); AssetModule::LogDebug("HTTP asset " + tranfer_info.id.toStdString() + " completed"); } } // Complete /data and /metadata sequence, fake is here as long as we dont have xml parser for metadata // or actually we dont use metadata in naali so thats the main reason its not fetched if (fake_metadata_fetch_) { /**** THIS IS A /metadata REQUEST REPLY ****/ if (metadata_to_assetptr_.contains(fake_metadata_url_)) { // Pull out transfer data and asset pointer assosiated with this reply url QUrl metadata_transfer_url = fake_metadata_url_; HttpAssetTransferInfo transfer_data = metadata_to_assetptr_[metadata_transfer_url].first; Foundation::AssetPtr ready_asset_ptr = metadata_to_assetptr_[metadata_transfer_url].second; if (!ready_asset_ptr) { reply->deleteLater(); return; } // Fill metadata /* const QByteArray &inbound_metadata = reply->readAll(); QString decoded_metadata = QString::fromUtf8(inbound_metadata.data()); #if defined(__GNUC__) RexAssetMetadata *m = dynamic_cast<RexAssetMetadata*>(ready_asset_ptr.get()->GetMetadata()); #else Foundation::AssetMetadataInterface *metadata = ready_asset_ptr.get()->GetMetadata(); RexAssetMetadata *m = static_cast<RexAssetMetadata*>(metadata); #endif std::string std_md(decoded_metadata.toStdString()); m->DesesrializeFromJSON(std_md); // TODO: implement a xml based metadata parser. */ // Store asset boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = framework_->GetServiceManager()->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock(); if (asset_service) asset_service->StoreAsset(ready_asset_ptr); // Send asset ready events foreach (request_tag_t tag, transfer_data.tags) { Events::AssetReady event_data(ready_asset_ptr.get()->GetId(), ready_asset_ptr.get()->GetType(), ready_asset_ptr, tag); event_manager_->SendEvent(asset_event_category_, Events::ASSET_READY, &event_data); } RemoveFinishedTransfers(transfer_data.id, metadata_transfer_url); StartTransferFromQueue(); AssetModule::LogDebug("HTTP asset " + transfer_data.id.toStdString() + " completed with metadata"); } } reply->deleteLater(); } void QtHttpAssetProvider::RemoveFinishedTransfers(QString asset_transfer_key, QUrl metadata_transfer_key) { QtHttpAssetTransfer *remove_transfer = assetid_to_transfer_map_[asset_transfer_key]; assetid_to_transfer_map_.remove(asset_transfer_key); if (metadata_transfer_key.isValid()) metadata_to_assetptr_.remove(metadata_transfer_key); SAFE_DELETE(remove_transfer); } void QtHttpAssetProvider::ClearAllTransfers() { foreach (QtHttpAssetTransfer *transfer, assetid_to_transfer_map_.values()) SAFE_DELETE(transfer); assetid_to_transfer_map_.clear(); foreach (QtHttpAssetTransfer *transfer, pending_request_queue_) SAFE_DELETE(transfer); pending_request_queue_.clear(); } void QtHttpAssetProvider::StartTransferFromQueue() { if (pending_request_queue_.count() == 0) return; // If the whole map is empty then go and start new MAX_HTTP_CONNECTIONS amount of http gets if (assetid_to_transfer_map_.count() == 0) filling_stack_ = true; if (!filling_stack_) return; if (assetid_to_transfer_map_.count() <= MAX_HTTP_CONNECTIONS && pending_request_queue_.count() > 0) { if (assetid_to_transfer_map_.count() == MAX_HTTP_CONNECTIONS || pending_request_queue_.count() == 0) filling_stack_ = false; else { QtHttpAssetTransfer *new_transfer = pending_request_queue_.takeAt(0); assetid_to_transfer_map_[new_transfer->GetTranferInfo().id] = new_transfer; network_manager_->get(*new_transfer); AssetModule::LogDebug("New HTTP asset request from queue: " + new_transfer->GetTranferInfo().id.toStdString() + " type: " + RexTypes::GetAssetTypeString(new_transfer->GetTranferInfo().type)); StartTransferFromQueue(); // Recursivly fill the transfer map } } } bool QtHttpAssetProvider::CheckRequestQueue(QString assed_id) { foreach (QtHttpAssetTransfer *transfer, pending_request_queue_) if (transfer->GetTranferInfo().id == assed_id) return true; return false; } bool QtHttpAssetProvider::IsAcceptableAssetType(const std::string& asset_type) { using namespace RexTypes; bool accepted = false; switch (GetAssetTypeFromTypeName(asset_type)) { case RexAT_Texture: case RexAT_Mesh: accepted = true; break; default: accepted = false; break; } return accepted; } }<|endoftext|>
<commit_before>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_SHARED_LEVEL_MANAGER_LEVEL_MANAGER_HPP #define RJ_SHARED_LEVEL_MANAGER_LEVEL_MANAGER_HPP #include "level.hpp" #include "packer_pack.hpp" #include "packer_unpack.hpp" #include <mlk/filesystem/filesystem.h> #include <map> #include <string> namespace rj { using level_id = std::string; class level_manager { mlk::fs::dir_handle m_dirh; mlk::fs::file_handle m_filemgr; const std::string& m_abs_path; std::map<level_id, level> m_loaded_levels; public: level_manager(const std::string& abs_level_path) : m_dirh{abs_level_path}, m_abs_path{m_dirh.get_path()} {this->init();} const level& open_level(const level_id& id) { this->load_to_mgr(id, this->make_path(id)); if(m_loaded_levels.find(id) == std::end(m_loaded_levels)) throw std::runtime_error{"error while open level"}; return m_loaded_levels[id]; } bool save_level(const level_packer<packer_mode::pack>& lv, const level_id& id) { if(!m_filemgr.reopen(this->make_path(id), std::ios::out | std::ios::trunc)) return false; m_filemgr.write(lv.packed_data()); return true; } auto get_levels() const noexcept -> const decltype(m_loaded_levels)& {return m_loaded_levels;} std::size_t num_levels() const noexcept {return m_loaded_levels.size();} private: void init() { mlk::lout("rj::level_manager") << "loading levels recursive from directory '" << m_abs_path << "'..."; auto content(m_dirh.get_content<true>()); auto count(0); for(auto& a : content) if(a.type == mlk::fs::item_type::file) { this->load_to_mgr(a.name, a.path); ++count; } mlk::lout("rj::level_manager") << "loaded " << count << " levels"; } void load_to_mgr(const level_id& id, const std::string& path) { if(!m_filemgr.reopen(path, std::ios::in)) return; auto data(m_filemgr.read_all()); level_packer<packer_mode::unpack> unpacker{data}; m_loaded_levels[id] = unpacker.get_level(); } std::string make_path(const level_id& id) const noexcept {return m_abs_path + id + ".rjl";} }; } #endif // RJ_SHARED_LEVEL_MANAGER_LEVEL_MANAGER_HPP <commit_msg>level_manager: added get_level(...)<commit_after>// // Copyright (c) 2013-2014 Christoph Malek // See LICENSE for more information. // #ifndef RJ_SHARED_LEVEL_MANAGER_LEVEL_MANAGER_HPP #define RJ_SHARED_LEVEL_MANAGER_LEVEL_MANAGER_HPP #include "level.hpp" #include "packer_pack.hpp" #include "packer_unpack.hpp" #include <mlk/filesystem/filesystem.h> #include <map> #include <string> namespace rj { using level_id = std::string; class level_manager { mlk::fs::dir_handle m_dirh; mlk::fs::file_handle m_filemgr; const std::string& m_abs_path; std::map<level_id, level> m_loaded_levels; public: level_manager(const std::string& abs_level_path) : m_dirh{abs_level_path}, m_abs_path{m_dirh.get_path()} {this->init();} const level& open_level(const level_id& id) { this->load_to_mgr(id, this->make_path(id)); if(m_loaded_levels.find(id) == std::end(m_loaded_levels)) throw std::runtime_error{"error while open level"}; return m_loaded_levels[id]; } bool save_level(const level_packer<packer_mode::pack>& lv, const level_id& id) { if(!m_filemgr.reopen(this->make_path(id), std::ios::out | std::ios::trunc)) return false; m_filemgr.write(lv.packed_data()); return true; } const level& get_level(const level_id& id) const noexcept {return m_loaded_levels.at(id);} auto get_levels() const noexcept -> const decltype(m_loaded_levels)& {return m_loaded_levels;} std::size_t num_levels() const noexcept {return m_loaded_levels.size();} private: void init() { mlk::lout("rj::level_manager") << "loading levels recursive from directory '" << m_abs_path << "'..."; auto content(m_dirh.get_content<true>()); auto count(0); for(auto& a : content) if(a.type == mlk::fs::item_type::file) { this->load_to_mgr(a.name, a.path); ++count; } mlk::lout("rj::level_manager") << "loaded " << count << " levels"; } void load_to_mgr(const level_id& id, const std::string& path) { if(!m_filemgr.reopen(path, std::ios::in)) return; auto data(m_filemgr.read_all()); level_packer<packer_mode::unpack> unpacker{data}; m_loaded_levels[id] = unpacker.get_level(); } std::string make_path(const level_id& id) const noexcept {return m_abs_path + id + ".rjl";} }; } #endif // RJ_SHARED_LEVEL_MANAGER_LEVEL_MANAGER_HPP <|endoftext|>
<commit_before>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "zbase/api/MapReduceService.h" #include "zbase/mapreduce/MapReduceTask.h" #include "zbase/mapreduce/MapReduceTaskBuilder.h" #include "zbase/mapreduce/MapReduceScheduler.h" #include "stx/protobuf/MessageDecoder.h" #include "stx/protobuf/JSONEncoder.h" #include "stx/http/HTTPFileDownload.h" #include "sstable/SSTableWriter.h" #include "sstable/sstablereader.h" #include "cstable/CSTableWriter.h" #include "cstable/RecordShredder.h" #include <algorithm> using namespace stx; namespace zbase { MapReduceService::MapReduceService( ConfigDirectory* cdir, AnalyticsAuth* auth, zbase::TSDBService* tsdb, zbase::PartitionMap* pmap, zbase::ReplicationScheme* repl, JSRuntime* js_runtime, const String& cachedir) : cdir_(cdir), auth_(auth), tsdb_(tsdb), pmap_(pmap), repl_(repl), js_runtime_(js_runtime), cachedir_(cachedir), tpool_( thread::ThreadPoolOptions { .thread_name = Some(String("z1d-mapreduce")) }, 1) {} void MapReduceService::executeScript( const AnalyticsSession& session, RefPtr<MapReduceJobSpec> job, const String& program_source) { logDebug( "z1.mapreduce", "Launching mapreduce job; customer=$0", session.customer()); auto task_builder = mkRef(new MapReduceTaskBuilder( session, auth_, pmap_, repl_, tsdb_, cachedir_)); auto scheduler = mkRef(new MapReduceScheduler( session, job, &tpool_, auth_, cachedir_)); auto js_ctx = mkRef(new JavaScriptContext( session.customer(), job, tsdb_, task_builder, scheduler)); js_ctx->loadProgram(program_source); } Option<SHA1Hash> MapReduceService::mapPartition( const AnalyticsSession& session, RefPtr<MapReduceJobSpec> job, const String& table_name, const SHA1Hash& partition_key, const String& map_fn, const String& globals, const String& params) { auto table = pmap_->findTable( session.customer(), table_name); if (table.isEmpty()) { RAISEF( kNotFoundError, "table not found: $0/$1", session.customer(), table_name); } auto partition = pmap_->findPartition( session.customer(), table_name, partition_key); if (partition.isEmpty()) { return None<SHA1Hash>(); } auto schema = table.get()->schema(); auto reader = partition.get()->getReader(); auto output_id = SHA1::compute( StringUtil::format( "$0~$1~$2~$3~$4~$5~$6~$7", session.customer(), table_name, partition_key.toString(), reader->version().toString(), SHA1::compute(map_fn).toString(), SHA1::compute(globals).toString(), SHA1::compute(params).toString())); auto output_path = FileUtil::joinPaths( cachedir_, StringUtil::format("mr-shard-$0.sst", output_id.toString())); if (FileUtil::exists(output_path)) { return Some(output_id); } auto output_path_tmp = StringUtil::format( "$0~$1", output_path, Random::singleton()->hex64()); logDebug( "z1.mapreduce", "Executing map shard; partition=$0/$1/$2 output=$3", session.customer(), table_name, partition_key.toString(), output_id.toString()); try { z1stats()->mapreduce_num_map_tasks.incr(1); auto js_ctx = mkRef(new JavaScriptContext( session.customer(), job, tsdb_, nullptr, nullptr)); js_ctx->loadClosure(map_fn, globals, params); auto writer = sstable::SSTableWriter::create(output_path_tmp, nullptr, 0); reader->fetchRecords( [&schema, &js_ctx, &writer] (const msg::MessageObject& record) { Buffer json; json::JSONOutputStream jsons(BufferOutputStream::fromBuffer(&json)); msg::JSONEncoder::encode(record, *schema, &jsons); Vector<Pair<String, String>> tuples; js_ctx->callMapFunction(json.toString(), &tuples); for (const auto& t : tuples) { writer->appendRow(t.first, t.second); } }); } catch (const StandardException& e) { z1stats()->mapreduce_num_map_tasks.decr(1); throw e; } z1stats()->mapreduce_num_map_tasks.decr(1); FileUtil::mv(output_path_tmp, output_path); return Some(output_id); } Option<SHA1Hash> MapReduceService::reduceTables( const AnalyticsSession& session, RefPtr<MapReduceJobSpec> job, const Vector<String>& input_tables_ref, const String& reduce_fn, const String& globals, const String& params) { auto input_tables = input_tables_ref; std::sort(input_tables.begin(), input_tables.end()); auto output_id = SHA1::compute( StringUtil::format( "$0~$1~$2~$3~$4", session.customer(), StringUtil::join(input_tables, "|"), SHA1::compute(reduce_fn).toString(), SHA1::compute(globals).toString(), SHA1::compute(params).toString())); auto output_path = FileUtil::joinPaths( cachedir_, StringUtil::format("mr-shard-$0.sst", output_id.toString())); if (FileUtil::exists(output_path)) { return Some(output_id); } auto output_path_tmp = StringUtil::format( "$0~$1", output_path, Random::singleton()->hex64()); logDebug( "z1.mapreduce", "Executing reduce shard; customer=$0 input_tables=0/$1 output=$2", session.customer(), input_tables.size(), output_id.toString()); std::random_shuffle(input_tables.begin(), input_tables.end()); // FIXME MOST NAIVE IN MEMORY MERGE AHEAD !! size_t num_input_tables_read = 0; size_t num_bytes_read = 0; try { z1stats()->mapreduce_num_reduce_tasks.incr(1); HashMap<String, Vector<String>> groups; for (const auto& input_table_url : input_tables) { auto api_token = auth_->encodeAuthToken(session); http::HTTPMessage::HeaderList auth_headers; auth_headers.emplace_back( "Authorization", StringUtil::format("Token $0", api_token)); auto req = http::HTTPRequest::mkGet(input_table_url, auth_headers); MapReduceService::downloadResult( req, [&groups, &num_bytes_read] ( const void* key, size_t key_len, const void* val, size_t val_len) { auto key_str = String((const char*) key, key_len); auto& lst = groups[key_str]; lst.emplace_back(key_str); auto rec_size = key_len + val_len; num_bytes_read += rec_size; z1stats()->mapreduce_reduce_memory.incr(rec_size); }); ++num_input_tables_read; logDebug( "z1.mapreduce", "Executing reduce shard; customer=$0 input_tables=$1/$2 output=$3 mem_used=$4MB", session.customer(), input_tables.size(), num_input_tables_read, output_id.toString(), num_bytes_read / 1024.0 / 1024.0); } if (groups.size() == 0) { z1stats()->mapreduce_reduce_memory.decr(num_bytes_read); z1stats()->mapreduce_num_reduce_tasks.decr(1); return None<SHA1Hash>(); } auto js_ctx = mkRef(new JavaScriptContext( session.customer(), job, tsdb_, nullptr, nullptr)); js_ctx->loadClosure(reduce_fn, globals, params); auto writer = sstable::SSTableWriter::create(output_path_tmp, nullptr, 0); for (const auto& cur : groups) { Vector<Pair<String, String>> tuples; js_ctx->callReduceFunction(cur.first, cur.second, &tuples); for (const auto& t : tuples) { writer->appendRow(t.first, t.second); } } } catch (const StandardException& e) { z1stats()->mapreduce_reduce_memory.decr(num_bytes_read); z1stats()->mapreduce_num_reduce_tasks.decr(1); throw e; } z1stats()->mapreduce_reduce_memory.decr(num_bytes_read); z1stats()->mapreduce_num_reduce_tasks.decr(1); FileUtil::mv(output_path_tmp, output_path); return Some(output_id); } Option<String> MapReduceService::getResultFilename( const SHA1Hash& result_id) { auto result_path = FileUtil::joinPaths( cachedir_, StringUtil::format("mr-shard-$0.sst", result_id.toString())); if (FileUtil::exists(result_path)) { return Some(result_path); } else { return None<String>(); } } void MapReduceService::downloadResult( const http::HTTPRequest& req, Function<void (const void*, size_t, const void*, size_t)> fn) { Buffer buffer; bool eos = false; auto handler = [&buffer, &eos, &fn] (const void* data, size_t size) { buffer.append(data, size); size_t consumed = 0; util::BinaryMessageReader reader(buffer.data(), buffer.size()); while (reader.remaining() >= (sizeof(uint32_t) * 2)) { auto key_len = *reader.readUInt32(); auto val_len = *reader.readUInt32(); auto rec_len = key_len + val_len; if (rec_len > reader.remaining()) { break; } if (rec_len == 0) { eos = true; } else { auto key = reader.read(key_len); auto val = reader.read(val_len); fn(key, key_len, val, val_len); } consumed = reader.position(); } Buffer remaining( (char*) buffer.data() + consumed, buffer.size() - consumed); buffer.clear(); buffer.append(remaining); }; auto handler_factory = [&handler] ( const Promise<http::HTTPResponse> promise) -> http::HTTPResponseFuture* { return new http::StreamingResponseFuture(promise, handler); }; http::HTTPClient http_client(&z1stats()->http_client_stats); auto res = http_client.executeRequest(req, handler_factory); handler(nullptr, 0); if (!eos) { RAISE(kRuntimeError, "unexpected EOF"); } if (res.statusCode() != 200) { RAISEF(kRuntimeError, "received non-200 response for $0", req.uri()); } } bool MapReduceService::saveLocalResultToTable( const AnalyticsSession& session, const String& table_name, const SHA1Hash& partition, const SHA1Hash& result_id) { auto table = pmap_->findTable( session.customer(), table_name); if (table.isEmpty()) { RAISEF( kNotFoundError, "table not found: $0/$1", session.customer(), table_name); } auto sstable_file = getResultFilename(result_id); if (sstable_file.isEmpty()) { RAISEF( kNotFoundError, "result not found: $0/$1", session.customer(), result_id.toString()); } logDebug( "z1.mapreduce", "Saving result shard to table; result_id=$0 table=$1/$2/$3", result_id.toString(), session.customer(), table_name, partition.toString()); auto schema = table.get()->schema(); auto tmpfile_path = FileUtil::joinPaths( cachedir_, StringUtil::format("mr-shard-$0.cst", Random::singleton()->hex128())); { auto cstable = cstable::CSTableWriter::createFile( tmpfile_path, cstable::BinaryFormatVersion::v0_1_0, cstable::TableSchema::fromProtobuf(*schema)); cstable::RecordShredder shredder(cstable.get()); sstable::SSTableReader sstable(sstable_file.get()); auto cursor = sstable.getCursor(); while (cursor->valid()) { void* data; size_t data_size; cursor->getData(&data, &data_size); auto json = json::parseJSON(String((const char*) data, data_size)); msg::DynamicMessage msg(schema); msg.fromJSON(json.begin(), json.end()); shredder.addRecordFromProtobuf(msg.data(), *schema); if (!cursor->next()) { break; } } cstable->commit(); } tsdb_->updatePartitionCSTable( session.customer(), table_name, partition, tmpfile_path, WallClock::unixMicros()); return true; } bool MapReduceService::saveRemoteResultsToTable( const AnalyticsSession& session, const String& table_name, const SHA1Hash& partition, const Vector<String>& input_tables_ref) { auto input_tables = input_tables_ref; std::random_shuffle(input_tables.begin(), input_tables.end()); auto table = pmap_->findTable( session.customer(), table_name); if (table.isEmpty()) { RAISEF( kNotFoundError, "table not found: $0/$1", session.customer(), table_name); } logDebug( "z1.mapreduce", "Saving results to table; input_tables=$0 table=$1/$2/$3", input_tables.size(), session.customer(), table_name, partition.toString()); auto schema = table.get()->schema(); auto tmpfile_path = FileUtil::joinPaths( cachedir_, StringUtil::format("mr-shard-$0.cst", Random::singleton()->hex128())); { auto cstable = cstable::CSTableWriter::createFile( tmpfile_path, cstable::BinaryFormatVersion::v0_1_0, cstable::TableSchema::fromProtobuf(*schema)); cstable::RecordShredder shredder(cstable.get()); for (const auto& input_table_url : input_tables) { auto api_token = auth_->encodeAuthToken(session); http::HTTPMessage::HeaderList auth_headers; auth_headers.emplace_back( "Authorization", StringUtil::format("Token $0", api_token)); auto req = http::HTTPRequest::mkGet(input_table_url, auth_headers); MapReduceService::downloadResult( req, [&shredder, &schema] ( const void* key, size_t key_len, const void* val, size_t val_len) { auto json = json::parseJSON(String((const char*) val, val_len)); msg::DynamicMessage msg(schema); msg.fromJSON(json.begin(), json.end()); shredder.addRecordFromProtobuf(msg.data(), *schema); }); } cstable->commit(); } tsdb_->updatePartitionCSTable( session.customer(), table_name, partition, tmpfile_path, WallClock::unixMicros()); return true; } } // namespace zbase <commit_msg>don't rethrow as standardexception<commit_after>/** * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com> * All Rights Reserved. * * This file is CONFIDENTIAL -- Distribution or duplication of this material or * the information contained herein is strictly forbidden unless prior written * permission is obtained. */ #include "zbase/api/MapReduceService.h" #include "zbase/mapreduce/MapReduceTask.h" #include "zbase/mapreduce/MapReduceTaskBuilder.h" #include "zbase/mapreduce/MapReduceScheduler.h" #include "stx/protobuf/MessageDecoder.h" #include "stx/protobuf/JSONEncoder.h" #include "stx/http/HTTPFileDownload.h" #include "sstable/SSTableWriter.h" #include "sstable/sstablereader.h" #include "cstable/CSTableWriter.h" #include "cstable/RecordShredder.h" #include <algorithm> using namespace stx; namespace zbase { MapReduceService::MapReduceService( ConfigDirectory* cdir, AnalyticsAuth* auth, zbase::TSDBService* tsdb, zbase::PartitionMap* pmap, zbase::ReplicationScheme* repl, JSRuntime* js_runtime, const String& cachedir) : cdir_(cdir), auth_(auth), tsdb_(tsdb), pmap_(pmap), repl_(repl), js_runtime_(js_runtime), cachedir_(cachedir), tpool_( thread::ThreadPoolOptions { .thread_name = Some(String("z1d-mapreduce")) }, 1) {} void MapReduceService::executeScript( const AnalyticsSession& session, RefPtr<MapReduceJobSpec> job, const String& program_source) { logDebug( "z1.mapreduce", "Launching mapreduce job; customer=$0", session.customer()); auto task_builder = mkRef(new MapReduceTaskBuilder( session, auth_, pmap_, repl_, tsdb_, cachedir_)); auto scheduler = mkRef(new MapReduceScheduler( session, job, &tpool_, auth_, cachedir_)); auto js_ctx = mkRef(new JavaScriptContext( session.customer(), job, tsdb_, task_builder, scheduler)); js_ctx->loadProgram(program_source); } Option<SHA1Hash> MapReduceService::mapPartition( const AnalyticsSession& session, RefPtr<MapReduceJobSpec> job, const String& table_name, const SHA1Hash& partition_key, const String& map_fn, const String& globals, const String& params) { auto table = pmap_->findTable( session.customer(), table_name); if (table.isEmpty()) { RAISEF( kNotFoundError, "table not found: $0/$1", session.customer(), table_name); } auto partition = pmap_->findPartition( session.customer(), table_name, partition_key); if (partition.isEmpty()) { return None<SHA1Hash>(); } auto schema = table.get()->schema(); auto reader = partition.get()->getReader(); auto output_id = SHA1::compute( StringUtil::format( "$0~$1~$2~$3~$4~$5~$6~$7", session.customer(), table_name, partition_key.toString(), reader->version().toString(), SHA1::compute(map_fn).toString(), SHA1::compute(globals).toString(), SHA1::compute(params).toString())); auto output_path = FileUtil::joinPaths( cachedir_, StringUtil::format("mr-shard-$0.sst", output_id.toString())); if (FileUtil::exists(output_path)) { return Some(output_id); } auto output_path_tmp = StringUtil::format( "$0~$1", output_path, Random::singleton()->hex64()); logDebug( "z1.mapreduce", "Executing map shard; partition=$0/$1/$2 output=$3", session.customer(), table_name, partition_key.toString(), output_id.toString()); try { z1stats()->mapreduce_num_map_tasks.incr(1); auto js_ctx = mkRef(new JavaScriptContext( session.customer(), job, tsdb_, nullptr, nullptr)); js_ctx->loadClosure(map_fn, globals, params); auto writer = sstable::SSTableWriter::create(output_path_tmp, nullptr, 0); reader->fetchRecords( [&schema, &js_ctx, &writer] (const msg::MessageObject& record) { Buffer json; json::JSONOutputStream jsons(BufferOutputStream::fromBuffer(&json)); msg::JSONEncoder::encode(record, *schema, &jsons); Vector<Pair<String, String>> tuples; js_ctx->callMapFunction(json.toString(), &tuples); for (const auto& t : tuples) { writer->appendRow(t.first, t.second); } }); } catch (const Exception& e) { z1stats()->mapreduce_num_map_tasks.decr(1); throw e; } z1stats()->mapreduce_num_map_tasks.decr(1); FileUtil::mv(output_path_tmp, output_path); return Some(output_id); } Option<SHA1Hash> MapReduceService::reduceTables( const AnalyticsSession& session, RefPtr<MapReduceJobSpec> job, const Vector<String>& input_tables_ref, const String& reduce_fn, const String& globals, const String& params) { auto input_tables = input_tables_ref; std::sort(input_tables.begin(), input_tables.end()); auto output_id = SHA1::compute( StringUtil::format( "$0~$1~$2~$3~$4", session.customer(), StringUtil::join(input_tables, "|"), SHA1::compute(reduce_fn).toString(), SHA1::compute(globals).toString(), SHA1::compute(params).toString())); auto output_path = FileUtil::joinPaths( cachedir_, StringUtil::format("mr-shard-$0.sst", output_id.toString())); if (FileUtil::exists(output_path)) { return Some(output_id); } auto output_path_tmp = StringUtil::format( "$0~$1", output_path, Random::singleton()->hex64()); logDebug( "z1.mapreduce", "Executing reduce shard; customer=$0 input_tables=0/$1 output=$2", session.customer(), input_tables.size(), output_id.toString()); std::random_shuffle(input_tables.begin(), input_tables.end()); // FIXME MOST NAIVE IN MEMORY MERGE AHEAD !! size_t num_input_tables_read = 0; size_t num_bytes_read = 0; try { z1stats()->mapreduce_num_reduce_tasks.incr(1); HashMap<String, Vector<String>> groups; for (const auto& input_table_url : input_tables) { auto api_token = auth_->encodeAuthToken(session); http::HTTPMessage::HeaderList auth_headers; auth_headers.emplace_back( "Authorization", StringUtil::format("Token $0", api_token)); auto req = http::HTTPRequest::mkGet(input_table_url, auth_headers); MapReduceService::downloadResult( req, [&groups, &num_bytes_read] ( const void* key, size_t key_len, const void* val, size_t val_len) { auto key_str = String((const char*) key, key_len); auto& lst = groups[key_str]; lst.emplace_back(key_str); auto rec_size = key_len + val_len; num_bytes_read += rec_size; z1stats()->mapreduce_reduce_memory.incr(rec_size); }); ++num_input_tables_read; logDebug( "z1.mapreduce", "Executing reduce shard; customer=$0 input_tables=$1/$2 output=$3 mem_used=$4MB", session.customer(), input_tables.size(), num_input_tables_read, output_id.toString(), num_bytes_read / 1024.0 / 1024.0); } if (groups.size() == 0) { z1stats()->mapreduce_reduce_memory.decr(num_bytes_read); z1stats()->mapreduce_num_reduce_tasks.decr(1); return None<SHA1Hash>(); } auto js_ctx = mkRef(new JavaScriptContext( session.customer(), job, tsdb_, nullptr, nullptr)); js_ctx->loadClosure(reduce_fn, globals, params); auto writer = sstable::SSTableWriter::create(output_path_tmp, nullptr, 0); for (const auto& cur : groups) { Vector<Pair<String, String>> tuples; js_ctx->callReduceFunction(cur.first, cur.second, &tuples); for (const auto& t : tuples) { writer->appendRow(t.first, t.second); } } } catch (const Exception& e) { z1stats()->mapreduce_reduce_memory.decr(num_bytes_read); z1stats()->mapreduce_num_reduce_tasks.decr(1); throw e; } z1stats()->mapreduce_reduce_memory.decr(num_bytes_read); z1stats()->mapreduce_num_reduce_tasks.decr(1); FileUtil::mv(output_path_tmp, output_path); return Some(output_id); } Option<String> MapReduceService::getResultFilename( const SHA1Hash& result_id) { auto result_path = FileUtil::joinPaths( cachedir_, StringUtil::format("mr-shard-$0.sst", result_id.toString())); if (FileUtil::exists(result_path)) { return Some(result_path); } else { return None<String>(); } } void MapReduceService::downloadResult( const http::HTTPRequest& req, Function<void (const void*, size_t, const void*, size_t)> fn) { Buffer buffer; bool eos = false; auto handler = [&buffer, &eos, &fn] (const void* data, size_t size) { buffer.append(data, size); size_t consumed = 0; util::BinaryMessageReader reader(buffer.data(), buffer.size()); while (reader.remaining() >= (sizeof(uint32_t) * 2)) { auto key_len = *reader.readUInt32(); auto val_len = *reader.readUInt32(); auto rec_len = key_len + val_len; if (rec_len > reader.remaining()) { break; } if (rec_len == 0) { eos = true; } else { auto key = reader.read(key_len); auto val = reader.read(val_len); fn(key, key_len, val, val_len); } consumed = reader.position(); } Buffer remaining( (char*) buffer.data() + consumed, buffer.size() - consumed); buffer.clear(); buffer.append(remaining); }; auto handler_factory = [&handler] ( const Promise<http::HTTPResponse> promise) -> http::HTTPResponseFuture* { return new http::StreamingResponseFuture(promise, handler); }; http::HTTPClient http_client(&z1stats()->http_client_stats); auto res = http_client.executeRequest(req, handler_factory); handler(nullptr, 0); if (!eos) { RAISE(kRuntimeError, "unexpected EOF"); } if (res.statusCode() != 200) { RAISEF(kRuntimeError, "received non-200 response for $0", req.uri()); } } bool MapReduceService::saveLocalResultToTable( const AnalyticsSession& session, const String& table_name, const SHA1Hash& partition, const SHA1Hash& result_id) { auto table = pmap_->findTable( session.customer(), table_name); if (table.isEmpty()) { RAISEF( kNotFoundError, "table not found: $0/$1", session.customer(), table_name); } auto sstable_file = getResultFilename(result_id); if (sstable_file.isEmpty()) { RAISEF( kNotFoundError, "result not found: $0/$1", session.customer(), result_id.toString()); } logDebug( "z1.mapreduce", "Saving result shard to table; result_id=$0 table=$1/$2/$3", result_id.toString(), session.customer(), table_name, partition.toString()); auto schema = table.get()->schema(); auto tmpfile_path = FileUtil::joinPaths( cachedir_, StringUtil::format("mr-shard-$0.cst", Random::singleton()->hex128())); { auto cstable = cstable::CSTableWriter::createFile( tmpfile_path, cstable::BinaryFormatVersion::v0_1_0, cstable::TableSchema::fromProtobuf(*schema)); cstable::RecordShredder shredder(cstable.get()); sstable::SSTableReader sstable(sstable_file.get()); auto cursor = sstable.getCursor(); while (cursor->valid()) { void* data; size_t data_size; cursor->getData(&data, &data_size); auto json = json::parseJSON(String((const char*) data, data_size)); msg::DynamicMessage msg(schema); msg.fromJSON(json.begin(), json.end()); shredder.addRecordFromProtobuf(msg.data(), *schema); if (!cursor->next()) { break; } } cstable->commit(); } tsdb_->updatePartitionCSTable( session.customer(), table_name, partition, tmpfile_path, WallClock::unixMicros()); return true; } bool MapReduceService::saveRemoteResultsToTable( const AnalyticsSession& session, const String& table_name, const SHA1Hash& partition, const Vector<String>& input_tables_ref) { auto input_tables = input_tables_ref; std::random_shuffle(input_tables.begin(), input_tables.end()); auto table = pmap_->findTable( session.customer(), table_name); if (table.isEmpty()) { RAISEF( kNotFoundError, "table not found: $0/$1", session.customer(), table_name); } logDebug( "z1.mapreduce", "Saving results to table; input_tables=$0 table=$1/$2/$3", input_tables.size(), session.customer(), table_name, partition.toString()); auto schema = table.get()->schema(); auto tmpfile_path = FileUtil::joinPaths( cachedir_, StringUtil::format("mr-shard-$0.cst", Random::singleton()->hex128())); { auto cstable = cstable::CSTableWriter::createFile( tmpfile_path, cstable::BinaryFormatVersion::v0_1_0, cstable::TableSchema::fromProtobuf(*schema)); cstable::RecordShredder shredder(cstable.get()); for (const auto& input_table_url : input_tables) { auto api_token = auth_->encodeAuthToken(session); http::HTTPMessage::HeaderList auth_headers; auth_headers.emplace_back( "Authorization", StringUtil::format("Token $0", api_token)); auto req = http::HTTPRequest::mkGet(input_table_url, auth_headers); MapReduceService::downloadResult( req, [&shredder, &schema] ( const void* key, size_t key_len, const void* val, size_t val_len) { auto json = json::parseJSON(String((const char*) val, val_len)); msg::DynamicMessage msg(schema); msg.fromJSON(json.begin(), json.end()); shredder.addRecordFromProtobuf(msg.data(), *schema); }); } cstable->commit(); } tsdb_->updatePartitionCSTable( session.customer(), table_name, partition, tmpfile_path, WallClock::unixMicros()); return true; } } // namespace zbase <|endoftext|>
<commit_before>#include "stdafx.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; // // AZuɊւʏ͈ȉ̑ZbgƂĐ䂳܂B // AZuɊ֘AtĂύXɂ́A // ̑lύXĂB // [assembly:AssemblyTitleAttribute("treefrogsetup")]; [assembly:AssemblyDescriptionAttribute("")]; [assembly:AssemblyConfigurationAttribute("")]; [assembly:AssemblyCompanyAttribute("")]; [assembly:AssemblyProductAttribute("treefrogsetup")]; [assembly:AssemblyCopyrightAttribute("Copyright (c) 2010-2022")]; [assembly:AssemblyTrademarkAttribute("")]; [assembly:AssemblyCultureAttribute("")]; // // AZũo[ẂAȉ 4 ‚̒lō\Ă܂: // // Major Version // Minor Version // Build Number // Revision // // ׂĂ̒lw肷邩Â悤 '*' gărWуrhԍ // lɂ邱Ƃł܂: [assembly:AssemblyVersionAttribute("2.3.1")]; [assembly:ComVisible(false)]; [assembly:CLSCompliantAttribute(true)]; [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)]; <commit_msg>update<commit_after>#include "stdafx.h" using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; // // AZuɊւʏ͈ȉ̑ZbgƂĐ䂳܂B // AZuɊ֘AtĂύXɂ́A // ̑lύXĂB // [assembly:AssemblyTitleAttribute("treefrogsetup")]; [assembly:AssemblyDescriptionAttribute("")]; [assembly:AssemblyConfigurationAttribute("")]; [assembly:AssemblyCompanyAttribute("")]; [assembly:AssemblyProductAttribute("treefrogsetup")]; [assembly:AssemblyCopyrightAttribute("Copyright (c) 2010-2022")]; [assembly:AssemblyTrademarkAttribute("")]; [assembly:AssemblyCultureAttribute("")]; // // AZũo[ẂAȉ 4 ‚̒lō\Ă܂: // // Major Version // Minor Version // Build Number // Revision // // ׂĂ̒lw肷邩Â悤 '*' gărWуrhԍ // lɂ邱Ƃł܂: [assembly:AssemblyVersionAttribute("2.4.0")]; [assembly:ComVisible(false)]; [assembly:CLSCompliantAttribute(true)]; [assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)]; <|endoftext|>
<commit_before>#include "Pair.h" namespace zxing { namespace oned { namespace rss { Pair::Pair(int value, int checksumPortion, FinderPattern finderPattern) : DataCharacter (value, checksumPortion), m_finderPattern(finderPattern) { } Pair::Pair() : DataCharacter (0, 0), m_finderPattern(FinderPattern()), m_count(0) { } FinderPattern& Pair::getFinderPattern() { return m_finderPattern; } int Pair::getCount() const { return m_count; } void Pair::incrementCount() { m_count++; } bool Pair::isValid() const { return m_finderPattern.isValid(); } } } } <commit_msg>fix warning of uninitialized values on Pair<commit_after>#include "Pair.h" namespace zxing { namespace oned { namespace rss { Pair::Pair(int value, int checksumPortion, FinderPattern finderPattern) : DataCharacter (value, checksumPortion), m_finderPattern(finderPattern), m_count(0) { } Pair::Pair() : DataCharacter (0, 0), m_finderPattern(FinderPattern()), m_count(0) { } FinderPattern& Pair::getFinderPattern() { return m_finderPattern; } int Pair::getCount() const { return m_count; } void Pair::incrementCount() { m_count++; } bool Pair::isValid() const { return m_finderPattern.isValid(); } } } } <|endoftext|>
<commit_before>// // Created by skgchxngsxyz-carbon on 16/07/31. // #include <stdint.h> #include <stddef.h> #include <ydsh/ydsh.h> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { auto *state = DSState_createWithOption(DS_OPTION_COMPILE_ONLY); DSError dsError; DSState_eval(state, "<dummy>", (const char *)data, size, &dsError); DSState_delete(&state); return 0; }<commit_msg>fix fuzzer<commit_after>// // Created by skgchxngsxyz-carbon on 16/07/31. // #include <stdint.h> #include <stddef.h> #include <ydsh/ydsh.h> extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { auto *state = DSState_createWithMode(DS_EXEC_MODE_COMPILE_ONLY); DSError dsError; DSState_eval(state, "<dummy>", (const char *)data, size, &dsError); DSState_delete(&state); return 0; }<|endoftext|>
<commit_before>#ifndef COMPILE_TIME_STRINGS_HPP_ #define COMPILE_TIME_STRINGS_HPP_ #include <string> #include <type_traits> namespace static_string { template <typename Char, Char...> struct static_string; template <typename Char> struct static_string<Char> { using char_type = Char; using string_type = std::basic_string<Char>; enum { size = 0 }; inline static string_type string() { return {}; } private: template <typename C, C...> friend struct static_string; inline static void append_to(string_type& string) {} }; template <typename Char, Char c, Char... chars> struct static_string<Char, c, chars...> { using char_type = Char; using string_type = std::basic_string<Char>; enum { size = 1 + sizeof...(chars) }; inline static string_type string() { string_type result; result.reserve(size); append_to(result); return result; } private: template <typename C, C...> friend struct static_string; inline static void append_to(string_type& string) { string += c; static_string<Char, chars...>::append_to(string); } }; namespace __impl { template <typename StrProvider, size_t len, typename Char, char... chars> struct build_from_provider { using type = typename build_from_provider<StrProvider, len - 1, Char, StrProvider::str()[len - 1], chars... >::type; }; template <typename StrProvider, typename Char, char... chars> struct build_from_provider<StrProvider, 0, Char, chars...> { using type = static_string<Char, chars...>; }; template <typename StrProvider> struct has_size { using no = char[1]; using yes = char[2]; template <typename T> static yes& test(int(*)[T::size]); // SFINAE! template <typename T> static no& test(...); static constexpr bool value = (sizeof(test<StrProvider>(nullptr)) == sizeof(yes)); }; template <typename StrProvider, bool = has_size<StrProvider>::value> struct size_for; template <typename StrProvider> struct size_for<StrProvider, true> { enum { value = StrProvider::size }; }; template <typename StrProvider> struct size_for<StrProvider, false> { template <typename Char> static constexpr size_t str_length(const Char* str) { return str[0] == Char(0) ? 0 : (1 + str_length(str + 1)); } enum { value = str_length(StrProvider::str()) }; }; template <typename... CTStrings> struct concat; template <typename Char, Char... chars> struct concat<static_string<Char, chars...>> { using type = static_string<Char, chars...>; }; template <typename Char, Char... chars1, Char... chars2, typename... CTStrings> struct concat<static_string<Char, chars1...>, static_string<Char, chars2...>, CTStrings...> { using type = typename concat<static_string<Char, chars1..., chars2...>, CTStrings...>::type; }; } /* namespace __impl */ template <typename StrProvider, size_t len = __impl::size_for<StrProvider>::value> using from_provider = typename __impl::build_from_provider<StrProvider, len, typename std::decay<decltype(StrProvider::str()[0])>::type >::type; template <typename... CTStrings> using concat = typename __impl::concat<CTStrings...>::type; } /* namespace ctstring */ #endif /* COMPILE_TIME_STRINGS_HPP_ */ <commit_msg>static-strings: Change has_size<> SFINAE usage to be cleaner<commit_after>#ifndef STATIC_STRINGS_HPP_ #define STATIC_STRINGS_HPP_ #include <string> #include <type_traits> namespace static_string { template <typename Char, Char...> struct static_string; template <typename Char> struct static_string<Char> { using char_type = Char; using string_type = std::basic_string<Char>; enum { size = 0 }; inline static string_type string() { return {}; } private: template <typename C, C...> friend struct static_string; inline static void append_to(string_type& string) {} }; template <typename Char, Char c, Char... chars> struct static_string<Char, c, chars...> { using char_type = Char; using string_type = std::basic_string<Char>; enum { size = 1 + sizeof...(chars) }; inline static string_type string() { string_type result; result.reserve(size); append_to(result); return result; } private: template <typename C, C...> friend struct static_string; inline static void append_to(string_type& string) { string += c; static_string<Char, chars...>::append_to(string); } }; namespace __impl { template <typename StrProvider, size_t len, typename Char, char... chars> struct build_from_provider { using type = typename build_from_provider<StrProvider, len - 1, Char, StrProvider::str()[len - 1], chars... >::type; }; template <typename StrProvider, typename Char, char... chars> struct build_from_provider<StrProvider, 0, Char, chars...> { using type = static_string<Char, chars...>; }; template <typename StrProvider> struct has_size { template <size_t N> struct Check; template <typename T> static constexpr bool test(Check<T::size>*) { return true; } // SFINAE! template <typename T> static constexpr bool test(...) { return false; } static constexpr bool value = test<StrProvider>(nullptr); }; template <typename StrProvider, bool = has_size<StrProvider>::value> struct size_for; template <typename StrProvider> struct size_for<StrProvider, true> { enum { value = StrProvider::size }; }; template <typename StrProvider> struct size_for<StrProvider, false> { template <typename Char> static constexpr size_t str_length(const Char* str) { return str[0] == Char(0) ? 0 : (1 + str_length(str + 1)); } enum { value = str_length(StrProvider::str()) }; }; template <typename... SSs> struct concat; template <typename Char, Char... chars> struct concat<static_string<Char, chars...>> { using type = static_string<Char, chars...>; }; template <typename Char, Char... chars1, Char... chars2, typename... SSs> struct concat<static_string<Char, chars1...>, static_string<Char, chars2...>, SSs...> { using type = typename concat<static_string<Char, chars1..., chars2...>, SSs...>::type; }; } /* namespace __impl */ template <typename StrProvider, size_t len = __impl::size_for<StrProvider>::value> using from_provider = typename __impl::build_from_provider<StrProvider, len, typename std::decay<decltype(StrProvider::str()[0])>::type >::type; template <typename... SSs> using concat = typename __impl::concat<SSs...>::type; } /* namespace static_string */ #endif /* STATIC_STRINGS_HPP_ */ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: precompiled_stoc.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2006-09-16 17:27:19 $ * * 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): Generated on 2006-09-01 17:50:03.092339 #ifdef PRECOMPILED_HEADERS #endif <commit_msg>INTEGRATION: CWS pchfix04 (1.2.20); FILE MERGED 2006/11/29 10:58:54 mkretzschmar 1.2.20.2: Disable precompiled headers in stoc, breaks registration in pyuno and i18npool. 2006/11/27 15:25:24 mkretzschmar 1.2.20.1: #i71519# fill in stoc pch file. Builds fine on Mac OS X and Linux.<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: precompiled_stoc.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2007-05-10 15:14:53 $ * * 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): Generated on 2006-09-01 17:50:03.092339 // breaks some builds (e.g. pyuno and i18npool on Mac OS X) #if 0 #ifdef PRECOMPILED_HEADERS //---MARKER--- #include "sal/alloca.h" #include "sal/config.h" #include "sal/main.h" #include "sal/types.h" #include "boost/scoped_array.hpp" #include "com/sun/star/beans/IllegalTypeException.hpp" #include "com/sun/star/beans/MethodConcept.hpp" #include "com/sun/star/beans/NamedValue.hpp" #include "com/sun/star/beans/Property.hpp" #include "com/sun/star/beans/PropertyAttribute.hpp" #include "com/sun/star/beans/PropertyChangeEvent.hpp" #include "com/sun/star/beans/PropertyConcept.hpp" #include "com/sun/star/beans/PropertyState.hpp" #include "com/sun/star/beans/PropertyValue.hpp" #include "com/sun/star/beans/PropertyVetoException.hpp" #include "com/sun/star/beans/UnknownPropertyException.hpp" #include "com/sun/star/beans/XExactName.hpp" #include "com/sun/star/beans/XFastPropertySet.hpp" #include "com/sun/star/beans/XIntrospection.hpp" #include "com/sun/star/beans/XIntrospectionAccess.hpp" #include "com/sun/star/beans/XMaterialHolder.hpp" #include "com/sun/star/beans/XPropertyChangeListener.hpp" #include "com/sun/star/beans/XPropertySet.hpp" #include "com/sun/star/beans/XPropertySetInfo.hpp" #include "com/sun/star/beans/XVetoableChangeListener.hpp" #include "com/sun/star/connection/SocketPermission.hpp" #include "com/sun/star/container/ContainerEvent.hpp" #include "com/sun/star/container/ElementExistException.hpp" #include "com/sun/star/container/NoSuchElementException.hpp" #include "com/sun/star/container/XContainer.hpp" #include "com/sun/star/container/XContainerListener.hpp" #include "com/sun/star/container/XContentEnumerationAccess.hpp" #include "com/sun/star/container/XElementAccess.hpp" #include "com/sun/star/container/XEnumeration.hpp" #include "com/sun/star/container/XEnumerationAccess.hpp" #include "com/sun/star/container/XHierarchicalNameAccess.hpp" #include "com/sun/star/container/XIndexAccess.hpp" #include "com/sun/star/container/XIndexContainer.hpp" #include "com/sun/star/container/XIndexReplace.hpp" #include "com/sun/star/container/XNameAccess.hpp" #include "com/sun/star/container/XNameContainer.hpp" #include "com/sun/star/container/XNameReplace.hpp" #include "com/sun/star/container/XSet.hpp" #include "com/sun/star/io/FilePermission.hpp" #include "com/sun/star/java/InvalidJavaSettingsException.hpp" #include "com/sun/star/java/JavaDisabledException.hpp" #include "com/sun/star/java/JavaInitializationException.hpp" #include "com/sun/star/java/JavaNotConfiguredException.hpp" #include "com/sun/star/java/JavaNotFoundException.hpp" #include "com/sun/star/java/JavaVMCreationFailureException.hpp" #include "com/sun/star/java/MissingJavaRuntimeException.hpp" #include "com/sun/star/java/RestartRequiredException.hpp" #include "com/sun/star/java/XJavaThreadRegister_11.hpp" #include "com/sun/star/java/XJavaVM.hpp" #include "com/sun/star/lang/ArrayIndexOutOfBoundsException.hpp" #include "com/sun/star/lang/DisposedException.hpp" #include "com/sun/star/lang/EventObject.hpp" #include "com/sun/star/lang/IllegalAccessException.hpp" #include "com/sun/star/lang/IllegalArgumentException.hpp" #include "com/sun/star/lang/IndexOutOfBoundsException.hpp" #include "com/sun/star/lang/NoSuchMethodException.hpp" #include "com/sun/star/lang/WrappedTargetException.hpp" #include "com/sun/star/lang/WrappedTargetRuntimeException.hpp" #include "com/sun/star/lang/XComponent.hpp" #include "com/sun/star/lang/XEventListener.hpp" #include "com/sun/star/lang/XInitialization.hpp" #include "com/sun/star/lang/XMain.hpp" #include "com/sun/star/lang/XMultiComponentFactory.hpp" #include "com/sun/star/lang/XMultiServiceFactory.hpp" #include "com/sun/star/lang/XServiceInfo.hpp" #include "com/sun/star/lang/XSingleComponentFactory.hpp" #include "com/sun/star/lang/XSingleServiceFactory.hpp" #include "com/sun/star/lang/XTypeProvider.hpp" #include "com/sun/star/lang/XUnoTunnel.hpp" #include "com/sun/star/loader/CannotActivateFactoryException.hpp" #include "com/sun/star/loader/XImplementationLoader.hpp" #include "com/sun/star/reflection/FieldAccessMode.hpp" #include "com/sun/star/reflection/InvalidTypeNameException.hpp" #include "com/sun/star/reflection/InvocationTargetException.hpp" #include "com/sun/star/reflection/MethodMode.hpp" #include "com/sun/star/reflection/NoSuchTypeNameException.hpp" #include "com/sun/star/reflection/ParamInfo.hpp" #include "com/sun/star/reflection/ParamMode.hpp" #include "com/sun/star/reflection/TypeDescriptionSearchDepth.hpp" #include "com/sun/star/reflection/XArrayTypeDescription.hpp" #include "com/sun/star/reflection/XCompoundTypeDescription.hpp" #include "com/sun/star/reflection/XConstantTypeDescription.hpp" #include "com/sun/star/reflection/XConstantsTypeDescription.hpp" #include "com/sun/star/reflection/XEnumTypeDescription.hpp" #include "com/sun/star/reflection/XIdlArray.hpp" #include "com/sun/star/reflection/XIdlClass.hpp" #include "com/sun/star/reflection/XIdlClassProvider.hpp" #include "com/sun/star/reflection/XIdlField.hpp" #include "com/sun/star/reflection/XIdlField2.hpp" #include "com/sun/star/reflection/XIdlMember.hpp" #include "com/sun/star/reflection/XIdlMethod.hpp" #include "com/sun/star/reflection/XIdlReflection.hpp" #include "com/sun/star/reflection/XIndirectTypeDescription.hpp" #include "com/sun/star/reflection/XInterfaceAttributeTypeDescription.hpp" #include "com/sun/star/reflection/XInterfaceAttributeTypeDescription2.hpp" #include "com/sun/star/reflection/XInterfaceMemberTypeDescription.hpp" #include "com/sun/star/reflection/XInterfaceMethodTypeDescription.hpp" #include "com/sun/star/reflection/XInterfaceTypeDescription.hpp" #include "com/sun/star/reflection/XInterfaceTypeDescription2.hpp" #include "com/sun/star/reflection/XMethodParameter.hpp" #include "com/sun/star/reflection/XModuleTypeDescription.hpp" #include "com/sun/star/reflection/XParameter.hpp" #include "com/sun/star/reflection/XPropertyTypeDescription.hpp" #include "com/sun/star/reflection/XProxyFactory.hpp" #include "com/sun/star/reflection/XPublished.hpp" #include "com/sun/star/reflection/XServiceConstructorDescription.hpp" #include "com/sun/star/reflection/XServiceTypeDescription.hpp" #include "com/sun/star/reflection/XServiceTypeDescription2.hpp" #include "com/sun/star/reflection/XSingletonTypeDescription.hpp" #include "com/sun/star/reflection/XSingletonTypeDescription2.hpp" #include "com/sun/star/reflection/XStructTypeDescription.hpp" #include "com/sun/star/reflection/XTypeDescription.hpp" #include "com/sun/star/reflection/XTypeDescriptionEnumeration.hpp" #include "com/sun/star/reflection/XTypeDescriptionEnumerationAccess.hpp" #include "com/sun/star/registry/CannotRegisterImplementationException.hpp" #include "com/sun/star/registry/InvalidRegistryException.hpp" #include "com/sun/star/registry/InvalidValueException.hpp" #include "com/sun/star/registry/MergeConflictException.hpp" #include "com/sun/star/registry/RegistryKeyType.hpp" #include "com/sun/star/registry/RegistryValueType.hpp" #include "com/sun/star/registry/XImplementationRegistration.hpp" #include "com/sun/star/registry/XRegistryKey.hpp" #include "com/sun/star/registry/XSimpleRegistry.hpp" #include "com/sun/star/script/CannotConvertException.hpp" #include "com/sun/star/script/FailReason.hpp" #include "com/sun/star/script/InvocationInfo.hpp" #include "com/sun/star/script/MemberType.hpp" #include "com/sun/star/script/XInvocation.hpp" #include "com/sun/star/script/XInvocation2.hpp" #include "com/sun/star/script/XInvocationAdapterFactory.hpp" #include "com/sun/star/script/XInvocationAdapterFactory2.hpp" #include "com/sun/star/script/XTypeConverter.hpp" #include "com/sun/star/security/AccessControlException.hpp" #include "com/sun/star/security/AllPermission.hpp" #include "com/sun/star/security/RuntimePermission.hpp" #include "com/sun/star/security/XAccessControlContext.hpp" #include "com/sun/star/security/XAccessController.hpp" #include "com/sun/star/security/XAction.hpp" #include "com/sun/star/security/XPolicy.hpp" #include "com/sun/star/task/XInteractionAbort.hpp" #include "com/sun/star/task/XInteractionContinuation.hpp" #include "com/sun/star/task/XInteractionHandler.hpp" #include "com/sun/star/task/XInteractionRequest.hpp" #include "com/sun/star/task/XInteractionRetry.hpp" #include "com/sun/star/uno/Any.h" #include "com/sun/star/uno/Any.hxx" #include "com/sun/star/uno/DeploymentException.hpp" #include "com/sun/star/uno/Exception.hpp" #include "com/sun/star/uno/Reference.h" #include "com/sun/star/uno/Reference.hxx" #include "com/sun/star/uno/RuntimeException.hpp" #include "com/sun/star/uno/SecurityException.hpp" #include "com/sun/star/uno/Sequence.h" #include "com/sun/star/uno/Sequence.hxx" #include "com/sun/star/uno/Type.h" #include "com/sun/star/uno/Type.hxx" #include "com/sun/star/uno/TypeClass.hpp" #include "com/sun/star/uno/Uik.hpp" #include "com/sun/star/uno/XAdapter.hpp" #include "com/sun/star/uno/XAggregation.hpp" #include "com/sun/star/uno/XComponentContext.hpp" #include "com/sun/star/uno/XCurrentContext.hpp" #include "com/sun/star/uno/XInterface.hpp" #include "com/sun/star/uno/XNamingService.hpp" #include "com/sun/star/uno/XReference.hpp" #include "com/sun/star/uno/XUnloadingPreference.hpp" #include "com/sun/star/uri/RelativeUriExcessParentSegments.hpp" #include "com/sun/star/uri/XExternalUriReferenceTranslator.hpp" #include "com/sun/star/uri/XUriReference.hpp" #include "com/sun/star/uri/XUriReferenceFactory.hpp" #include "com/sun/star/uri/XUriSchemeParser.hpp" #include "com/sun/star/uri/XVndSunStarPkgUrlReferenceFactory.hpp" #include "com/sun/star/uri/XVndSunStarScriptUrlReference.hpp" #include "com/sun/star/util/XMacroExpander.hpp" #include "cppu/macros.hxx" #include "cppu/unotype.hxx" #include "cppuhelper/access_control.hxx" #include "cppuhelper/bootstrap.hxx" #include "cppuhelper/component_context.hxx" #include "cppuhelper/exc_hlp.hxx" #include "cppuhelper/factory.hxx" #include "cppuhelper/implementationentry.hxx" #include "cppuhelper/queryinterface.hxx" #include "cppuhelper/servicefactory.hxx" #include "cppuhelper/shlib.hxx" #include "cppuhelper/typeprovider.hxx" #include "cppuhelper/weak.hxx" #include "cppuhelper/weakref.hxx" #include "jvmfwk/framework.h" #include "osl/diagnose.h" #include "osl/doublecheckedlocking.h" #include "osl/file.h" #include "osl/file.hxx" #include "osl/interlck.h" #include "osl/module.h" #include "osl/module.hxx" #include "osl/mutex.hxx" #include "osl/process.h" #include "osl/security.h" #include "osl/socket.hxx" #include "osl/thread.h" #include "osl/thread.hxx" #include "registry/refltype.hxx" #include "registry/registry.hxx" #include "registry/types.h" #include "registry/version.h" #include "rtl/alloc.h" #include "rtl/bootstrap.hxx" #include "rtl/byteseq.hxx" #include "rtl/process.h" #include "rtl/strbuf.hxx" #include "rtl/string.h" #include "rtl/string.hxx" #include "rtl/textenc.h" #include "rtl/unload.h" #include "rtl/uri.h" #include "rtl/ustrbuf.hxx" #include "rtl/ustring.h" #include "rtl/ustring.hxx" #include "salhelper/simplereferenceobject.hxx" #include "typelib/typeclass.h" #include "typelib/typedescription.h" #include "typelib/typedescription.hxx" #include "uno/any2.h" #include "uno/current_context.h" #include "uno/current_context.hxx" #include "uno/data.h" #include "uno/dispatcher.h" #include "uno/dispatcher.hxx" #include "uno/environment.h" #include "uno/environment.hxx" #include "uno/lbnames.h" #include "uno/mapping.hxx" //---MARKER--- #endif #endif <|endoftext|>
<commit_before>#ifndef SYNTH_CGWRAPPERS_HPP_INCLUDED #define SYNTH_CGWRAPPERS_HPP_INCLUDED #include <clang-c/Index.h> #include <boost/noncopyable.hpp> #include <memory> #include <vector> namespace synth { struct DeleterForCXIndex { void operator() (CXIndex cidx) const { clang_disposeIndex(cidx); } }; struct DeleterForCXTranslationUnit { void operator() (CXTranslationUnit tu) const { clang_disposeTranslationUnit(tu); } }; class CgTokensCleanup : private boost::noncopyable { public: CgTokensCleanup(CXToken* data, unsigned ntokens, CXTranslationUnit tu_) : m_data(data), m_ntokens(ntokens), m_tu(tu_) {} ~CgTokensCleanup() { clang_disposeTokens(m_tu, m_data, m_ntokens); } private: CXToken* m_data; unsigned m_ntokens; CXTranslationUnit m_tu; }; using CgIdxHandle = std::unique_ptr< std::remove_pointer_t<CXIndex>, DeleterForCXIndex>; using CgTuHandle = std::unique_ptr< std::remove_pointer_t<CXTranslationUnit>, DeleterForCXTranslationUnit>; } // namespace synth #endif // SYNTH_CGWRAPPERS_HPP_INCLUDED <commit_msg>CgWrappers: Cleanup & add handles for DB.<commit_after>#ifndef SYNTH_CGWRAPPERS_HPP_INCLUDED #define SYNTH_CGWRAPPERS_HPP_INCLUDED #include <clang-c/Index.h> #include <clang-c/CXCompilationDatabase.h> #include <boost/noncopyable.hpp> #include <memory> #include <vector> #include <type_traits> // remove_pointer_t namespace synth { class CgTokensCleanup : private boost::noncopyable { public: CgTokensCleanup(CXToken* data, unsigned ntokens, CXTranslationUnit tu_) : m_data(data), m_ntokens(ntokens), m_tu(tu_) {} ~CgTokensCleanup() { clang_disposeTokens(m_tu, m_data, m_ntokens); } private: CXToken* m_data; unsigned m_ntokens; CXTranslationUnit m_tu; }; #define SYNTH_DEF_DELETER(t, f) \ struct DeleterFor##t { \ void operator() (t v) const { f(v); } \ }; #define SYNTH_DEF_HANDLE(n, t, delf) \ SYNTH_DEF_DELETER(t, delf) \ using n = std::unique_ptr< \ std::remove_pointer_t<t>, DeleterFor##t>; SYNTH_DEF_HANDLE(CgIdxHandle, CXIndex, clang_disposeIndex) SYNTH_DEF_HANDLE(CgTuHandle, CXTranslationUnit, clang_disposeTranslationUnit) SYNTH_DEF_HANDLE( CgDbHandle, CXCompilationDatabase, clang_CompilationDatabase_dispose) SYNTH_DEF_HANDLE( CgCmdsHandle, CXCompileCommands, clang_CompileCommands_dispose) } // namespace synth #endif // SYNTH_CGWRAPPERS_HPP_INCLUDED <|endoftext|>
<commit_before>#include "common.h" #include "parse.h" namespace { class Cursor { public: Cursor(const char* p, int line=1, int column=1) : p_(p), line_(line), column_(column) {} char operator*() const { return *p_; } Cursor& operator++() { incr(); return *this; } Cursor operator++(int) { Cursor prev(p_, line_, column_); incr(); return prev; } int line() const { return line_; } int column() const { return column_; } private: void incr() { if(*p_=='\n') { line_++; column_=1; } else { column_++; } p_++; } const char* p_; int line_, column_; }; void skip_spaces(Cursor& p) { while(*p==' '|| *p=='\t' || *p=='\n') ++p; } bool is_open_paren(char c) { return c=='(' || c=='[' || c=='{'; } bool is_close_paren(char c) { return c==')' || c==']' || c=='}'; } std::string parse_token(Cursor& p) { std::string token; while(*p!=' ' && *p!='\t' && *p!='\n' && !is_close_paren(*p)) token += *p++; return token; } // TODO(kinaba) hex? bool parse_int(const std::string& s, int* value) { int v = 0; for(char c: s) if('0'<=c && c<='9') v = v*10 + (c-'0'); else return false; *value = v; return true; } char paren_match(char op, char cl) { switch(op) { case '(': return cl==')'; case '[': return cl==']'; case '{': return cl=='}'; } return op==cl; } ast::AST parse_expression(Cursor& p) { skip_spaces(p); ast::AST ast(new ast::Impl); ast->line = p.line(); ast->column = p.column(); if(is_open_paren(*p)) { char op = *p; ++p; // ')' std::vector<ast::AST> list; while(skip_spaces(p), !is_close_paren(*p)) list.emplace_back(parse_expression(p)); char cl = *p; assert(paren_match(op,cl)); ++p; // ')' ast->type = ast::LIST; ast->list = list; } else { std::string token = parse_token(p); int value; if(parse_int(token, &value)) { ast->type = ast::VALUE; ast->value = value; } else { ast->type = ast::SYMBOL; ast->symbol = token; } } return ast; } std::string read_skipping_comments(std::istream& in) { std::string all; for(std::string str; getline(in, str); ) { size_t i = str.find(';'); if(i != std::string::npos) str.resize(i); all += str; all += '\n'; } return all; } } // namespace std::vector<ast::AST> parse_program(std::istream& in) { std::string str = read_skipping_comments(in); Cursor p(str.c_str()); std::vector<ast::AST> asts; while(skip_spaces(p), *p) asts.push_back(parse_expression(p)); return asts; } <commit_msg>compiler: paren count check.<commit_after>#include "common.h" #include "parse.h" namespace { class Cursor { public: Cursor(const char* p, int line=1, int column=1) : p_(p), line_(line), column_(column) {} char operator*() const { return *p_; } Cursor& operator++() { incr(); return *this; } Cursor operator++(int) { Cursor prev(p_, line_, column_); incr(); return prev; } int line() const { return line_; } int column() const { return column_; } private: void incr() { if(*p_=='\n') { line_++; column_=1; } else { column_++; } p_++; } const char* p_; int line_, column_; }; void skip_spaces(Cursor& p) { while(*p==' '|| *p=='\t' || *p=='\n') ++p; } bool is_open_paren(char c) { return c=='(' || c=='[' || c=='{'; } bool is_close_paren(char c) { return c==')' || c==']' || c=='}'; } std::string parse_token(Cursor& p) { std::string token; while(*p!=' ' && *p!='\t' && *p!='\n' && !is_close_paren(*p)) token += *p++; return token; } // TODO(kinaba) hex? bool parse_int(const std::string& s, int* value) { int v = 0; for(char c: s) if('0'<=c && c<='9') v = v*10 + (c-'0'); else return false; *value = v; return true; } char paren_match(char op, char cl) { switch(op) { case '(': return cl==')'; case '[': return cl==']'; case '{': return cl=='}'; } return op==cl; } ast::AST parse_expression(Cursor& p) { skip_spaces(p); ast::AST ast(new ast::Impl); ast->line = p.line(); ast->column = p.column(); if(is_open_paren(*p)) { char op = *p; ++p; // ')' std::vector<ast::AST> list; while(skip_spaces(p), *p && !is_close_paren(*p)) list.emplace_back(parse_expression(p)); char cl = *p; if(!*p) std::cerr << "More Open paren than Close paren" << std::endl; assert(paren_match(op,cl)); ++p; // ')' ast->type = ast::LIST; ast->list = list; } else { std::string token = parse_token(p); int value; if(parse_int(token, &value)) { ast->type = ast::VALUE; ast->value = value; } else { ast->type = ast::SYMBOL; ast->symbol = token; } } return ast; } std::string read_skipping_comments(std::istream& in) { std::string all; for(std::string str; getline(in, str); ) { size_t i = str.find(';'); if(i != std::string::npos) str.resize(i); all += str; all += '\n'; } return all; } } // namespace std::vector<ast::AST> parse_program(std::istream& in) { std::string str = read_skipping_comments(in); Cursor p(str.c_str()); std::vector<ast::AST> asts; while(skip_spaces(p), *p) asts.push_back(parse_expression(p)); return asts; } <|endoftext|>
<commit_before>#include "runtime_internal.h" #include "HalideRuntime.h" extern "C" { #define EGLAPI #define EGLAPIENTRY typedef int32_t EGLint; typedef unsigned int EGLBoolean; typedef void *EGLContext; typedef void *EGLDisplay; typedef void *EGLNativeDisplayType; typedef void *EGLConfig; typedef void *EGLSurface; #define EGL_NO_CONTEXT ((EGLContext)0) #define EGL_DEFAULT_DISPLAY ((EGLNativeDisplayType)0) #define EGL_NO_DISPLAY ((EGLDisplay)0) #define EGL_NO_SURFACE ((EGLSurface)0) #define EGL_ALPHA_SIZE 0x3021 #define EGL_BLUE_SIZE 0x3022 #define EGL_GREEN_SIZE 0x3023 #define EGL_RED_SIZE 0x3024 #define EGL_SURFACE_TYPE 0x3033 #define EGL_NONE 0x3038 #define EGL_RENDERABLE_TYPE 0x3040 #define EGL_HEIGHT 0x3056 #define EGL_WIDTH 0x3057 #define EGL_CONTEXT_CLIENT_VERSION 0x3098 #define EGL_PBUFFER_BIT 0x0001 #define EGL_OPENGL_ES2_BIT 0x0004 EGLAPI EGLint EGLAPIENTRY eglGetError(void); EGLAPI EGLContext EGLAPIENTRY eglGetCurrentContext(void); EGLAPI EGLDisplay EGLAPIENTRY eglGetDisplay(EGLNativeDisplayType display_id); EGLAPI EGLBoolean EGLAPIENTRY eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor); EGLAPI EGLBoolean EGLAPIENTRY eglChooseConfig(EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config); EGLAPI EGLContext EGLAPIENTRY eglCreateContext(EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list); EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list); EGLAPI EGLBoolean EGLAPIENTRY eglMakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx); EGLAPI void *eglGetProcAddress(const char *procname); extern int strcmp(const char *, const char *); WEAK int halide_opengl_create_context(void *user_context) { if (eglGetCurrentContext() != EGL_NO_CONTEXT) return 0; EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); if (display == EGL_NO_DISPLAY || !eglInitialize(display, 0, 0)) { error(user_context) << "Could not initialize EGL display: " << eglGetError(); return 1; } EGLint attribs[] = { EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE, }; EGLConfig config; int numconfig; eglChooseConfig(display, attribs, &config, 1, &numconfig); if (numconfig != 1) { error(user_context) << "eglChooseConfig(): config not found: " << eglGetError() << " - " << numconfig; return -1; } EGLint context_attribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; EGLContext context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attribs); if (context == EGL_NO_CONTEXT) { error(user_context) << "Error: eglCreateContext failed: " << eglGetError(); return -1; } EGLint surface_attribs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE }; EGLSurface surface = eglCreatePbufferSurface(display, config, surface_attribs); if (surface == EGL_NO_SURFACE) { error(user_context) << "Error: Could not create EGL window surface: " << eglGetError(); return -1; } eglMakeCurrent(display, surface, surface, context); return 0; } void *halide_opengl_get_proc_address(void *user_context, const char *name) { return (void*)eglGetProcAddress(name); } } // extern "C" <commit_msg>Add missing WEAK to android halide_opengl_get_proc_address()<commit_after>#include "runtime_internal.h" #include "HalideRuntime.h" extern "C" { #define EGLAPI #define EGLAPIENTRY typedef int32_t EGLint; typedef unsigned int EGLBoolean; typedef void *EGLContext; typedef void *EGLDisplay; typedef void *EGLNativeDisplayType; typedef void *EGLConfig; typedef void *EGLSurface; #define EGL_NO_CONTEXT ((EGLContext)0) #define EGL_DEFAULT_DISPLAY ((EGLNativeDisplayType)0) #define EGL_NO_DISPLAY ((EGLDisplay)0) #define EGL_NO_SURFACE ((EGLSurface)0) #define EGL_ALPHA_SIZE 0x3021 #define EGL_BLUE_SIZE 0x3022 #define EGL_GREEN_SIZE 0x3023 #define EGL_RED_SIZE 0x3024 #define EGL_SURFACE_TYPE 0x3033 #define EGL_NONE 0x3038 #define EGL_RENDERABLE_TYPE 0x3040 #define EGL_HEIGHT 0x3056 #define EGL_WIDTH 0x3057 #define EGL_CONTEXT_CLIENT_VERSION 0x3098 #define EGL_PBUFFER_BIT 0x0001 #define EGL_OPENGL_ES2_BIT 0x0004 EGLAPI EGLint EGLAPIENTRY eglGetError(void); EGLAPI EGLContext EGLAPIENTRY eglGetCurrentContext(void); EGLAPI EGLDisplay EGLAPIENTRY eglGetDisplay(EGLNativeDisplayType display_id); EGLAPI EGLBoolean EGLAPIENTRY eglInitialize(EGLDisplay dpy, EGLint *major, EGLint *minor); EGLAPI EGLBoolean EGLAPIENTRY eglChooseConfig(EGLDisplay dpy, const EGLint *attrib_list, EGLConfig *configs, EGLint config_size, EGLint *num_config); EGLAPI EGLContext EGLAPIENTRY eglCreateContext(EGLDisplay dpy, EGLConfig config, EGLContext share_context, const EGLint *attrib_list); EGLAPI EGLSurface EGLAPIENTRY eglCreatePbufferSurface(EGLDisplay dpy, EGLConfig config, const EGLint *attrib_list); EGLAPI EGLBoolean EGLAPIENTRY eglMakeCurrent(EGLDisplay dpy, EGLSurface draw, EGLSurface read, EGLContext ctx); EGLAPI void *eglGetProcAddress(const char *procname); extern int strcmp(const char *, const char *); WEAK int halide_opengl_create_context(void *user_context) { if (eglGetCurrentContext() != EGL_NO_CONTEXT) return 0; EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); if (display == EGL_NO_DISPLAY || !eglInitialize(display, 0, 0)) { error(user_context) << "Could not initialize EGL display: " << eglGetError(); return 1; } EGLint attribs[] = { EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_NONE, }; EGLConfig config; int numconfig; eglChooseConfig(display, attribs, &config, 1, &numconfig); if (numconfig != 1) { error(user_context) << "eglChooseConfig(): config not found: " << eglGetError() << " - " << numconfig; return -1; } EGLint context_attribs[] = { EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE }; EGLContext context = eglCreateContext(display, config, EGL_NO_CONTEXT, context_attribs); if (context == EGL_NO_CONTEXT) { error(user_context) << "Error: eglCreateContext failed: " << eglGetError(); return -1; } EGLint surface_attribs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE }; EGLSurface surface = eglCreatePbufferSurface(display, config, surface_attribs); if (surface == EGL_NO_SURFACE) { error(user_context) << "Error: Could not create EGL window surface: " << eglGetError(); return -1; } eglMakeCurrent(display, surface, surface, context); return 0; } WEAK void *halide_opengl_get_proc_address(void *user_context, const char *name) { return (void*)eglGetProcAddress(name); } } // extern "C" <|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. */ #include <OGRE/OgreLogManager.h> #include <OGRE/OgreLog.h> #include <ros/ros.h> #include "rviz/ogre_helpers/ogre_logging.h" namespace rviz { class RosLogListener: public Ogre::LogListener { public: RosLogListener(): min_lml(Ogre::LML_CRITICAL) {}; virtual ~RosLogListener() {} virtual void messageLogged( const Ogre::String& message, Ogre::LogMessageLevel lml, bool maskDebug, const Ogre::String &logName ) { if ( lml >= min_lml ) { ROS_LOG((ros::console::levels::Level)(lml-1), ROSCONSOLE_DEFAULT_NAME, "%s", message.c_str() ); } } Ogre::LogMessageLevel min_lml; }; OgreLogging::Preference OgreLogging::preference_ = OgreLogging::NoLogging; QString OgreLogging::filename_; /** @brief Configure Ogre to write output to standard out. */ void OgreLogging::useRosLog() { preference_ = StandardOut; } /** @brief Configure Ogre to write output to the given log file * name. If file name is a relative path, it will be relative to * the directory which is current when the program is run. Default * is "Ogre.log". */ void OgreLogging::useLogFile( const QString& filename ) { preference_ = FileLogging; filename_ = filename; } /** @brief Disable Ogre logging entirely. This is the default. */ void OgreLogging::noLog() { preference_ = NoLogging; } /** @brief Configure the Ogre::LogManager to give the behavior * selected by the most recent call to enableStandardOut(), * setLogFile(), or disable(). This must be called before * Ogre::Root is instantiated! Called inside RenderSystem * constructor. */ void OgreLogging::configureLogging() { static RosLogListener ll; Ogre::LogManager* log_manager = new Ogre::LogManager(); Ogre::Log* l = log_manager->createLog( filename_.toStdString(), false, false, preference_==NoLogging ); l->addListener( &ll ); // Printing to standard out is what Ogre does if you don't do any LogManager calls. if( preference_ == StandardOut ) { ll.min_lml=Ogre::LML_NORMAL; } } } // end namespace rviz <commit_msg>Update src/rviz/ogre_helpers/ogre_logging.cpp<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. */ #include <OGRE/OgreLogManager.h> #include <OGRE/OgreLog.h> #include <ros/ros.h> #include "rviz/ogre_helpers/ogre_logging.h" namespace rviz { class RosLogListener: public Ogre::LogListener { public: RosLogListener(): min_lml(Ogre::LML_CRITICAL) {}; virtual ~RosLogListener() {} virtual void messageLogged( const Ogre::String& message, Ogre::LogMessageLevel lml, bool maskDebug, const Ogre::String &logName ) { if ( lml >= min_lml ) { ROS_LOG((ros::console::levels::Level)(lml-1), ROSCONSOLE_DEFAULT_NAME, "%s", message.c_str() ); } } Ogre::LogMessageLevel min_lml; }; OgreLogging::Preference OgreLogging::preference_ = OgreLogging::NoLogging; QString OgreLogging::filename_; /** @brief Configure Ogre to write output to standard out. */ void OgreLogging::useRosLog() { preference_ = StandardOut; } /** @brief Configure Ogre to write output to the given log file * name. If file name is a relative path, it will be relative to * the directory which is current when the program is run. Default * is "Ogre.log". */ void OgreLogging::useLogFile( const QString& filename ) { preference_ = FileLogging; filename_ = filename; } /** @brief Disable Ogre logging entirely. This is the default. */ void OgreLogging::noLog() { preference_ = NoLogging; } /** @brief Configure the Ogre::LogManager to give the behavior * selected by the most recent call to enableStandardOut(), * setLogFile(), or disable(). This must be called before * Ogre::Root is instantiated! Called inside RenderSystem * constructor. */ void OgreLogging::configureLogging() { static RosLogListener ll; Ogre::LogManager* log_manager = new Ogre::LogManager::getSingletonPtr(); Ogre::Log* l = log_manager->createLog( filename_.toStdString(), false, false, preference_==NoLogging ); l->addListener( &ll ); // Printing to standard out is what Ogre does if you don't do any LogManager calls. if( preference_ == StandardOut ) { ll.min_lml=Ogre::LML_NORMAL; } } } // end namespace rviz <|endoftext|>
<commit_before>// Convert file supported by xylib to ascii format // Licence: Lesser GNU Public License 2.1 (LGPL) // $Id$ #include <iostream> #include <fstream> #include <iomanip> #include <string> #include <string.h> #include "xylib/xylib.h" using namespace std; void print_usage() { cout << "Usage:\n" "\txyconv [-t FILETYPE] INPUT_FILE OUTPUT_FILE\n" "\txyconv [-t FILETYPE] -m INPUT_FILE1 ...\n" "\txyconv -i FILETYPE\n" "\txyconv -g INPUT_FILE ...\n" "\txyconv [-l|-v|-h]\n" " Converts INPUT_FILE to ascii OUTPUT_FILE\n" " -t specify filetype of input file\n" " -m convert one or multiple files; output files have the same name\n" " as input, but with extension changed to .xy\n" " -l list all supported file types\n" " -v output version information and exit\n" " -h show this help message and exit\n" " -i show information about filetype\n" " -s do not output metadata\n" " -g guess filetype of file \n"; } // Print version of the library. This program is too small to have own version. void print_version() { cout << XYLIB_VERSION / 10000 << "." << XYLIB_VERSION / 100 % 100 << "." << XYLIB_VERSION % 100 << endl; } void list_supported_formats() { const xylibFormat* format = NULL; for (int i = 0; (format = xylib_get_format(i)) != NULL; ++i) cout << setw(20) << left << format->name << ": " << format->desc << endl; } int print_guessed_filetype(int n, char** paths) { bool ok = true; for (int i = 0; i < n; ++i) { const char* path = paths[i]; if (n > 1) cout << path << ": "; try { ifstream is(path); if (!is) { cout << "Error: can't open input file: " << path << endl; ok = false; continue; } xylib::FormatInfo const* fi = xylib::guess_filetype(path, is); if (fi) cout << fi->name << ": " << fi->desc << endl; else cout << "Format of the file was not detected\n"; } catch (runtime_error const& e) { cout << "Error: " << e.what() << endl; ok = false; } } return ok ? 0 : -1; } void print_filetype_info(string const& filetype) { xylibFormat const* fi = xylib_get_format_by_name(filetype.c_str()); if (fi) { cout << "Name: " << fi->name << endl; cout << "Description: " << fi->desc << endl; bool has_exts = (strlen(fi->exts) != 0); cout << "Possible extensions: " << (has_exts ? fi->exts : "(not specified)") << endl; cout << "Other flags: " << (fi->binary ? "binary-file" : "text-file") << " " << (fi->multiblock ? "multi-block" : "single-block") << endl; } else cout << "Unknown file format." << endl; } void export_metadata(FILE *f, xylib::MetaData const& meta) { for (size_t i = 0; i != meta.size(); ++i) { const string& key = meta.get_key(i); const string& value = meta.get(key); string::size_type pos = 0; for (;;) { string::size_type new_pos = value.find('\n', pos); string vline = value.substr(pos, new_pos-pos); fprintf(f, "# %s: %s\n", key.c_str(), vline.c_str()); if (new_pos == string::npos) break; pos = new_pos + 1; } } } void export_plain_text(xylib::DataSet const *d, string const &fname, bool with_metadata) { FILE *f; if (fname == "-") f = stdout; else { f = fopen(fname.c_str(), "w"); if (!f) throw xylib::RunTimeError("can't create file: " + fname); } // output the file-level meta-info fprintf(f, "# exported by xylib from a %s file\n", d->fi->name); if (with_metadata && d->meta.size() != 0) { export_metadata(f, d->meta); fprintf(f, "\n"); } int nb = d->get_block_count(); //printf("%d block(s).\n", nb); for (int i = 0; i < nb; ++i) { const xylib::Block *block = d->get_block(i); if (nb > 1 || !block->get_name().empty()) fprintf(f, "\n### block #%d %s\n", i, block->get_name().c_str()); if (with_metadata) export_metadata(f, block->meta); int ncol = block->get_column_count(); fprintf(f, "# "); // column 0 is pseudo-column with point indices, we skip it for (int k = 1; k <= ncol; ++k) { string const& name = block->get_column(k).get_name(); if (k > 1) fprintf(f, "\t"); if (name.empty()) fprintf(f, "column_%d", k); else fprintf(f, "%s", name.c_str()); } fprintf(f, "\n"); int nrow = block->get_point_count(); for (int j = 0; j < nrow; ++j) { for (int k = 1; k <= ncol; ++k) { if (k > 1) fprintf(f, "\t"); fprintf(f, "%.6f", block->get_column(k).get_value(j)); } fprintf(f, "\n"); } } if (fname != "-") fclose(f); } int convert_file(string const& input, string const& output, string const& filetype, bool with_metadata) { try { xylib::DataSet *d = xylib::load_file(input, filetype); export_plain_text(d, output, with_metadata); delete d; } catch (runtime_error const& e) { cerr << "Error. " << e.what() << endl; return -1; } return 0; } int main(int argc, char **argv) { // options -l -h -i -g -v are not combined with other options if (argc == 2 && strcmp(argv[1], "-l") == 0) { list_supported_formats(); return 0; } else if (argc == 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) { print_usage(); return 0; } else if (argc == 2 && (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0)) { print_version(); return 0; } else if (argc == 3 && strcmp(argv[1], "-i") == 0) { print_filetype_info(argv[2]); return 0; } else if (argc >= 3 && strcmp(argv[1], "-g") == 0) return print_guessed_filetype(argc - 2, argv + 2); else if (argc < 3) { print_usage(); return -1; } string filetype; bool option_m = false; bool option_s = false; int n = 1; while (n < argc - 1) { if (strcmp(argv[n], "-m") == 0) { option_m = true; ++n; } else if (strcmp(argv[n], "-s") == 0) { option_s = true; ++n; } else if (strcmp(argv[n], "-t") == 0 && n+1 < argc - 1) { filetype = argv[n+1]; n += 2; } else break; } if (!option_m && n != argc - 2) { print_usage(); return -1; } if (option_m) { for ( ; n < argc; ++n) { string out = argv[n]; size_t p = out.rfind('.'); if (p != string::npos) out.erase(p); out += ".xy"; cout << "converting " << argv[n] << " to " << out << endl; convert_file(argv[n], out, filetype, !option_s); } return 0; } else return convert_file(argv[argc-2], argv[argc-1], filetype, !option_s); } <commit_msg>xyconv: added one line to the usage description<commit_after>// Convert file supported by xylib to ascii format // Licence: Lesser GNU Public License 2.1 (LGPL) // $Id$ #include <iostream> #include <fstream> #include <iomanip> #include <string> #include <string.h> #include "xylib/xylib.h" using namespace std; void print_usage() { cout << "Usage:\n" "\txyconv [-t FILETYPE] INPUT_FILE OUTPUT_FILE\n" "\txyconv [-t FILETYPE] -m INPUT_FILE1 ...\n" "\txyconv -i FILETYPE\n" "\txyconv -g INPUT_FILE ...\n" "\txyconv [-l|-v|-h]\n" " Converts INPUT_FILE to ascii OUTPUT_FILE\n" " -t specify filetype of input file\n" " -m convert one or multiple files; output files have the same name\n" " as input, but with extension changed to .xy\n" " -l list all supported file types\n" " -v output version information and exit\n" " -h show this help message and exit\n" " -i show information about filetype\n" " -s do not output metadata\n" " -g guess filetype of file \n" " To write the results to standard output use `-' as OUTPUT_FILE\n"; } // Print version of the library. This program is too small to have own version. void print_version() { cout << XYLIB_VERSION / 10000 << "." << XYLIB_VERSION / 100 % 100 << "." << XYLIB_VERSION % 100 << endl; } void list_supported_formats() { const xylibFormat* format = NULL; for (int i = 0; (format = xylib_get_format(i)) != NULL; ++i) cout << setw(20) << left << format->name << ": " << format->desc << endl; } int print_guessed_filetype(int n, char** paths) { bool ok = true; for (int i = 0; i < n; ++i) { const char* path = paths[i]; if (n > 1) cout << path << ": "; try { ifstream is(path); if (!is) { cout << "Error: can't open input file: " << path << endl; ok = false; continue; } xylib::FormatInfo const* fi = xylib::guess_filetype(path, is); if (fi) cout << fi->name << ": " << fi->desc << endl; else cout << "Format of the file was not detected\n"; } catch (runtime_error const& e) { cout << "Error: " << e.what() << endl; ok = false; } } return ok ? 0 : -1; } void print_filetype_info(string const& filetype) { xylibFormat const* fi = xylib_get_format_by_name(filetype.c_str()); if (fi) { cout << "Name: " << fi->name << endl; cout << "Description: " << fi->desc << endl; bool has_exts = (strlen(fi->exts) != 0); cout << "Possible extensions: " << (has_exts ? fi->exts : "(not specified)") << endl; cout << "Other flags: " << (fi->binary ? "binary-file" : "text-file") << " " << (fi->multiblock ? "multi-block" : "single-block") << endl; } else cout << "Unknown file format." << endl; } void export_metadata(FILE *f, xylib::MetaData const& meta) { for (size_t i = 0; i != meta.size(); ++i) { const string& key = meta.get_key(i); const string& value = meta.get(key); string::size_type pos = 0; for (;;) { string::size_type new_pos = value.find('\n', pos); string vline = value.substr(pos, new_pos-pos); fprintf(f, "# %s: %s\n", key.c_str(), vline.c_str()); if (new_pos == string::npos) break; pos = new_pos + 1; } } } void export_plain_text(xylib::DataSet const *d, string const &fname, bool with_metadata) { FILE *f; if (fname == "-") f = stdout; else { f = fopen(fname.c_str(), "w"); if (!f) throw xylib::RunTimeError("can't create file: " + fname); } // output the file-level meta-info fprintf(f, "# exported by xylib from a %s file\n", d->fi->name); if (with_metadata && d->meta.size() != 0) { export_metadata(f, d->meta); fprintf(f, "\n"); } int nb = d->get_block_count(); //printf("%d block(s).\n", nb); for (int i = 0; i < nb; ++i) { const xylib::Block *block = d->get_block(i); if (nb > 1 || !block->get_name().empty()) fprintf(f, "\n### block #%d %s\n", i, block->get_name().c_str()); if (with_metadata) export_metadata(f, block->meta); int ncol = block->get_column_count(); fprintf(f, "# "); // column 0 is pseudo-column with point indices, we skip it for (int k = 1; k <= ncol; ++k) { string const& name = block->get_column(k).get_name(); if (k > 1) fprintf(f, "\t"); if (name.empty()) fprintf(f, "column_%d", k); else fprintf(f, "%s", name.c_str()); } fprintf(f, "\n"); int nrow = block->get_point_count(); for (int j = 0; j < nrow; ++j) { for (int k = 1; k <= ncol; ++k) { if (k > 1) fprintf(f, "\t"); fprintf(f, "%.6f", block->get_column(k).get_value(j)); } fprintf(f, "\n"); } } if (fname != "-") fclose(f); } int convert_file(string const& input, string const& output, string const& filetype, bool with_metadata) { try { xylib::DataSet *d = xylib::load_file(input, filetype); export_plain_text(d, output, with_metadata); delete d; } catch (runtime_error const& e) { cerr << "Error. " << e.what() << endl; return -1; } return 0; } int main(int argc, char **argv) { // options -l -h -i -g -v are not combined with other options if (argc == 2 && strcmp(argv[1], "-l") == 0) { list_supported_formats(); return 0; } else if (argc == 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) { print_usage(); return 0; } else if (argc == 2 && (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--version") == 0)) { print_version(); return 0; } else if (argc == 3 && strcmp(argv[1], "-i") == 0) { print_filetype_info(argv[2]); return 0; } else if (argc >= 3 && strcmp(argv[1], "-g") == 0) return print_guessed_filetype(argc - 2, argv + 2); else if (argc < 3) { print_usage(); return -1; } string filetype; bool option_m = false; bool option_s = false; int n = 1; while (n < argc - 1) { if (strcmp(argv[n], "-m") == 0) { option_m = true; ++n; } else if (strcmp(argv[n], "-s") == 0) { option_s = true; ++n; } else if (strcmp(argv[n], "-t") == 0 && n+1 < argc - 1) { filetype = argv[n+1]; n += 2; } else break; } if (!option_m && n != argc - 2) { print_usage(); return -1; } if (option_m) { for ( ; n < argc; ++n) { string out = argv[n]; size_t p = out.rfind('.'); if (p != string::npos) out.erase(p); out += ".xy"; cout << "converting " << argv[n] << " to " << out << endl; convert_file(argv[n], out, filetype, !option_s); } return 0; } else return convert_file(argv[argc-2], argv[argc-1], filetype, !option_s); } <|endoftext|>
<commit_before>#include <string> #include "nbind/api.h" #include "control.h" #include "ui.h" class UiButton : public UiControl { DEFINE_EVENT(onClicked) public: UiButton(std::string text); UiButton(); ~UiButton(); DEFINE_CONTROL_METHODS() void setText(std::string text); std::string getText(); void onDestroy(uiControl *control) override; }; void UiButton::onDestroy(uiControl *control) { /* freeing event callbacks to allow JS to garbage collect this class when there are no references to it left in JS code. */ delete onClickedCallback; onClickedCallback = nullptr; } UiButton::~UiButton() { printf("UiButton %p destroyed with wrapper %p.\n", getHandle(), this); } UiButton::UiButton(std::string text) : UiControl(uiControl(uiNewButton(text.c_str()))) {} UiButton::UiButton() : UiControl(uiControl(uiNewButton(""))) {} INHERITS_CONTROL_METHODS(UiButton) void UiButton::setText(std::string text) { uiButtonSetText(uiButton(getHandle()), text.c_str()); } std::string UiButton::getText() { char *char_ptr = uiButtonText(uiButton(getHandle())); std::string s(char_ptr); uiFreeText(char_ptr); return s; } IMPLEMENT_EVENT(UiButton, uiButton, onClicked, uiButtonOnClicked) NBIND_CLASS(UiButton) { construct<std::string>(); construct<>(); DECLARE_CHILD_CONTROL_METHODS() getset(getText, setText); method(getText); method(setText); method(onClicked); } <commit_msg>Fixed events leak -> UiButton<commit_after>#include <string> #include "nbind/api.h" #include "control.h" #include "ui.h" class UiButton : public UiControl { DEFINE_EVENT(onClicked) public: UiButton(std::string text); UiButton(); ~UiButton(); DEFINE_CONTROL_METHODS() void setText(std::string text); std::string getText(); void onDestroy(uiControl *control) override; }; void UiButton::onDestroy(uiControl *control) { /* freeing event callbacks to allow JS to garbage collect this class when there are no references to it left in JS code. */ if (onClickedCallback != nullptr) { delete onClickedCallback; onClickedCallback = nullptr; } } UiButton::~UiButton() { printf("UiButton %p destroyed with wrapper %p.\n", getHandle(), this); } UiButton::UiButton(std::string text) : UiControl(uiControl(uiNewButton(text.c_str()))) {} UiButton::UiButton() : UiControl(uiControl(uiNewButton(""))) {} INHERITS_CONTROL_METHODS(UiButton) void UiButton::setText(std::string text) { uiButtonSetText(uiButton(getHandle()), text.c_str()); } std::string UiButton::getText() { char *char_ptr = uiButtonText(uiButton(getHandle())); std::string s(char_ptr); uiFreeText(char_ptr); return s; } IMPLEMENT_EVENT(UiButton, uiButton, onClicked, uiButtonOnClicked) NBIND_CLASS(UiButton) { construct<std::string>(); construct<>(); DECLARE_CHILD_CONTROL_METHODS() getset(getText, setText); method(getText); method(setText); method(onClicked); } <|endoftext|>
<commit_before>#pragma once #include "priority_queue.hpp" #include "timing.hpp" #include "helpers.hpp" namespace search { // // Lifelong planning // namespace lp { // // Lifelong A* // class LpAstarCore { // // Algorithm // auto validate(Cell c) const { return c.row >= 0 && c.row < (int)matrix.rows() && c.col >= 0 && c.col < (int)matrix.cols(); } auto build_path() const { string inverse_path; for (auto c = goal; c != start; ) { for (auto direction = '1'; direction != '9'; ++direction) { auto neighbour = DIRECTIONS.at(direction)(c); if (validate(neighbour) && (at(neighbour).g + cost() == at(c).g)) { inverse_path.push_back(direction); c = neighbour; break; } } } string path; for (auto i = inverse_path.crbegin(); i != inverse_path.crend(); ++i) path.push_back(*i); for (auto& ch : path) ch = 2 * '0' + 9 - ch; return path; } auto valid_neighbours_of(Cell c) const { Cells neighbours; for (auto direction = '1'; direction != '9'; ++direction) { auto n = DIRECTIONS.at(direction)(c); if (validate(n)) neighbours.insert(n); } return neighbours; } auto initialize() { q.reset(); at(start).r = 0; q.push(start); } auto update_vertex(LpState& s) { if (s.cell != start) { auto minimum = huge(); for (auto neighbour : valid_neighbours_of(s.cell)) minimum = min(minimum, (at(neighbour).g + cost())); s.r = minimum; } q.remove(s.cell); if (s.g != s.r) q.push(s.cell); } auto update_neighbours_of(Cell cell) { for (auto neighbour : valid_neighbours_of(cell)) if (!at(neighbour).bad) update_vertex(at(neighbour)); } auto compute_shortest_path() { Timing t{ run_time }; while (!q.empty() && (Key{ at(q.top()) } < Key{ at(goal) } || at(goal).r != at(goal).g)) { auto c = q.pop(); if (at(c).g > at(c).r) at(c).g = at(c).r; else at(c).g = huge(), update_vertex(at(c)); update_neighbours_of(c); { max_q_size = max(max_q_size, q.size()); expansions.insert(c); } } path = build_path(); } // // helpers // auto at(Cell c) const -> LpState const& { return matrix.at(c); } auto at(Cell c) -> LpState& { return matrix.at(c); } auto mark_bad_cells(Cells const& bad_cells) { for (auto c : bad_cells) at(c).bad = true; } auto mark_h_values_with(Cell terminal) { auto mark_h = [=](Cell c) { at(c).h = hfunc(c, terminal); }; matrix.each_cell(mark_h); } auto reset_statistics() { run_time = max_q_size = 0; expansions.clear(), path.clear(); } public: // // Constructor // LpAstarCore(unsigned rows, unsigned cols, Cell start, Cell goal, string heuristic, Cells const& bad_cells) : matrix{ rows, cols }, start{ start }, goal{ goal }, hfunc{ HEURISTICS.at(heuristic) }, q{ [this](Cell l, Cell r) { return Key{ at(l) } < Key{ at(r) }; } } { mark_bad_cells(bad_cells); mark_h_values_with(goal); //h value : goal to current reset_statistics(); } auto plan() { reset_statistics(); initialize(); compute_shortest_path(); } auto replan(Cells const& cells_to_toggle = {}) { reset_statistics(); for (auto c : cells_to_toggle) { at(c).bad = !at(c).bad; if (!at(c).bad) update_vertex(at(c)); else at(c).g = at(c).r = huge(); update_neighbours_of(c); } compute_shortest_path(); } // // data members // Matrix matrix; Cell const start, goal; function<int(Cell, Cell)> const hfunc; PriorityQueue < Cell, function<bool(Cell, Cell)> > q; // // statistics // size_t max_q_size; Cells expansions; string path; long long run_time; }; } }//end of namespace search<commit_msg>polished<commit_after>#pragma once #include "priority_queue.hpp" #include "timing.hpp" #include "helpers.hpp" namespace search { // // Lifelong planning // namespace lp { // // Lifelong A* // class LpAstarCore { // // Algorithm // auto validate(Cell c) const { return c.row >= 0 && c.row < (int)matrix.rows() && c.col >= 0 && c.col < (int)matrix.cols(); } auto build_path() const { string inverse_path; for (auto c = goal; c != start; ) { for (auto direction = '1'; direction != '9'; ++direction) { auto neighbour = DIRECTIONS.at(direction)(c); if (validate(neighbour) && (at(neighbour).g + cost() == at(c).g)) { inverse_path.push_back(direction); c = neighbour; break; } } } string path; for (auto i = inverse_path.crbegin(); i != inverse_path.crend(); ++i) path.push_back(*i); for (auto& ch : path) ch = 2 * '0' + 9 - ch; return path; } auto valid_neighbours_of(Cell c) const { Cells neighbours; for (auto direction = '1'; direction != '9'; ++direction) { auto n = DIRECTIONS.at(direction)(c); if (validate(n)) neighbours.insert(n); } return neighbours; } auto initialize() { q.reset(); at(start).r = 0; q.push(start); } auto update_vertex(LpState& s) { if (s.cell != start) { auto minimum = huge(); for (auto neighbour : valid_neighbours_of(s.cell)) minimum = min(minimum, (at(neighbour).g + cost())); s.r = minimum; } q.remove(s.cell); if (s.g != s.r) q.push(s.cell); } auto update_neighbours_of(Cell cell) { for (auto neighbour : valid_neighbours_of(cell)) if (!at(neighbour).bad) update_vertex(at(neighbour)); } auto compute_shortest_path() { Timing t{ run_time }; while (!q.empty() && (Key{ at(q.top()) } < Key{ at(goal) } || at(goal).r != at(goal).g)) { auto c = q.pop(); if (at(c).g > at(c).r) at(c).g = at(c).r; else at(c).g = huge(), update_vertex(at(c)); update_neighbours_of(c); { max_q_size = max(max_q_size, q.size()); expansions.insert(c); } } path = build_path(); } // // helpers // auto at(Cell c) const -> LpState const& { return matrix.at(c); } auto at(Cell c) -> LpState& { return matrix.at(c); } auto mark_bad_cells(Cells const& bad_cells) { for (auto c : bad_cells) at(c).bad = true; } auto mark_h_values_with(Cell terminal) { auto mark_h = [=](Cell c) { at(c).h = hfunc(c, terminal); }; matrix.each_cell(mark_h); } auto reset_statistics() { run_time = max_q_size = 0; expansions.clear(), path.clear(); } public: // // Constructor // LpAstarCore(unsigned rows, unsigned cols, Cell start, Cell goal, string heuristic, Cells const& bad_cells) : matrix{ rows, cols }, start{ start }, goal{ goal }, hfunc{ HEURISTICS.at(heuristic) }, q{ [this](Cell l, Cell r) { return Key{ at(l) } < Key{ at(r) }; } } { mark_bad_cells(bad_cells); mark_h_values_with(goal); //h value : goal to current reset_statistics(); } auto plan() { reset_statistics(); initialize(); compute_shortest_path(); } auto replan(Cells const& cells_to_toggle = {}) { reset_statistics(); for (auto c : cells_to_toggle) { at(c).bad = !at(c).bad; if (!at(c).bad) update_vertex(at(c)); else at(c).g = at(c).r = huge(); update_neighbours_of(c); } compute_shortest_path(); } // // data members // Matrix matrix; Cell const start, goal; function<int(Cell, Cell)> const hfunc; PriorityQueue < Cell, function<bool(Cell, Cell)> > q; // // statistics // size_t max_q_size; Cells expansions; string path; long long run_time; }; } }//end of namespace search<|endoftext|>
<commit_before>// -------------------------------------------------------------------- // Utility.cpp // // Created by Barrett Davis on 5/11/16. // Copyright © 2016 Tree Frog Software. All rights reserved. // -------------------------------------------------------------------- #include <cmath> // log() #include <cstdlib> // rand(), srand(), RAND_MAX #include <limits> #include "Utility.h" namespace tfs { // Tree Frog Software // Random functions: // The thinking here is that by centeralizing the random functions, we can choose different implementations // in the future and change the implementation in just this file. For example, if we want a predictable // distribution. void randomSeed( unsigned int seed ) { srand( seed ); } DNN_NUMERIC random( void ) { // 0.0 to 1.0 return (DNN_NUMERIC) rand() / (DNN_NUMERIC)(RAND_MAX); } DNN_NUMERIC random( const DNN_NUMERIC maxValue ) { // 0.0 to maxValue return (((DNN_NUMERIC) rand() * maxValue ) / (DNN_NUMERIC)(RAND_MAX)); } DNN_NUMERIC random( const DNN_NUMERIC minValue, const DNN_NUMERIC maxValue ) { // minValue to maxValue const DNN_NUMERIC difference = maxValue - minValue; return (((DNN_NUMERIC) rand() / (DNN_NUMERIC)(RAND_MAX)) * difference) + minValue; } DNN_INTEGER randomInt( void ) { return (DNN_INTEGER) rand() / (DNN_INTEGER)(RAND_MAX); } DNN_INTEGER randomInt( const DNN_INTEGER maxValue ) { return (((DNN_INTEGER) rand() * maxValue ) / (DNN_INTEGER)(RAND_MAX)); } DNN_INTEGER randomInt( const DNN_INTEGER minValue, const DNN_INTEGER maxValue ) { const DNN_INTEGER difference = maxValue - minValue; return ((((DNN_INTEGER) rand() * difference ) / (DNN_INTEGER)(RAND_MAX))) + minValue; } DNN_NUMERIC randomSigmoid( void ) { // 0.0 to 1.0 return ((DNN_NUMERIC) rand() / (DNN_NUMERIC)(RAND_MAX)); } DNN_NUMERIC randomTanh( void ) { // -1.0 to 1.0 return (((DNN_NUMERIC) rand() / (DNN_NUMERIC)(RAND_MAX)) * 2.0) - 1.0; } DNN_NUMERIC randomGauss( void ) { // -------------------------------------------------------------------- // 0.0 to 1.0, gausian distribution. Box–Muller transform // This form probably a little faster than randomGaussian() below. // -------------------------------------------------------------------- const DNN_NUMERIC scale = 2.0 / (DNN_NUMERIC) RAND_MAX; static DNN_NUMERIC z1 = 0.0; static bool return_z1 = false; if( return_z1 ) { return_z1 = false; return z1; // Return z1 (prevously calculated) } return_z1 = true; DNN_NUMERIC u, v, r; do { u = ((DNN_NUMERIC) rand() * scale) -1.0; // [ -1.0, 1.0 ] v = ((DNN_NUMERIC) rand() * scale) -1.0; r = u*u + v*v; } while( r == 0.0 || r > 1.0 ); const DNN_NUMERIC c = sqrt( -2.0 * log( r ) / r ); z1 = v * c; // Remember z1 for next time. return u * c; // Return z0 } DNN_NUMERIC randomGaussian( DNN_NUMERIC mu, DNN_NUMERIC sigma ) { // -------------------------------------------------------------------- // From: https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform // -------------------------------------------------------------------- const DNN_NUMERIC epsilon = std::numeric_limits<double>::min(); const DNN_NUMERIC two_pi = 2.0 * M_PI; const DNN_NUMERIC scale = 1.0 / (DNN_NUMERIC) RAND_MAX; static DNN_NUMERIC z1 = 0.0; static bool generate = false; generate = !generate; if( !generate ) { return z1 * sigma + mu; } DNN_NUMERIC u1, u2; do { u1 = rand() * scale; // [0.0,1.0] u2 = rand() * scale; } while ( u1 <= epsilon ); const DNN_NUMERIC pu = two_pi * u2; const DNN_NUMERIC cc = sqrt(-2.0 * log(u1)); const DNN_NUMERIC z0 = cc * cos( pu ); z1 = cc * sin( pu ); return z0 * sigma + mu; } } // namespace tfs <commit_msg>minor clean up<commit_after>// -------------------------------------------------------------------- // Utility.cpp // // Created by Barrett Davis on 5/11/16. // Copyright © 2016 Tree Frog Software. All rights reserved. // -------------------------------------------------------------------- #include <cmath> // log() #include <cstdlib> // rand(), srand(), RAND_MAX #include <limits> #include "Utility.h" namespace tfs { // Tree Frog Software // Random functions: // The thinking here is that by centeralizing the random functions, we can choose different implementations // in the future and change the implementation in just this file. For example, if we want a predictable // distribution. void randomSeed( unsigned int seed ) { srand( seed ); } DNN_NUMERIC random( void ) { // 0.0 to 1.0 return (DNN_NUMERIC) rand() / (DNN_NUMERIC)(RAND_MAX); } DNN_NUMERIC random( const DNN_NUMERIC maxValue ) { // 0.0 to maxValue return (((DNN_NUMERIC) rand() * maxValue ) / (DNN_NUMERIC)(RAND_MAX)); } DNN_NUMERIC random( const DNN_NUMERIC minValue, const DNN_NUMERIC maxValue ) { // minValue to maxValue const DNN_NUMERIC difference = maxValue - minValue; return (((DNN_NUMERIC) rand() / (DNN_NUMERIC)(RAND_MAX)) * difference) + minValue; } DNN_INTEGER randomInt( void ) { return (DNN_INTEGER) rand() / (DNN_INTEGER)(RAND_MAX); } DNN_INTEGER randomInt( const DNN_INTEGER maxValue ) { return (((DNN_INTEGER) rand() * maxValue ) / (DNN_INTEGER)(RAND_MAX)); } DNN_INTEGER randomInt( const DNN_INTEGER minValue, const DNN_INTEGER maxValue ) { const DNN_INTEGER difference = maxValue - minValue; return ((((DNN_INTEGER) rand() * difference ) / (DNN_INTEGER)(RAND_MAX))) + minValue; } DNN_NUMERIC randomSigmoid( void ) { // 0.0 to 1.0 return ((DNN_NUMERIC) rand() / (DNN_NUMERIC)(RAND_MAX)); } DNN_NUMERIC randomTanh( void ) { // -1.0 to 1.0 return (((DNN_NUMERIC) rand() / (DNN_NUMERIC)(RAND_MAX)) * 2.0) - 1.0; } DNN_NUMERIC randomGauss( void ) { // -------------------------------------------------------------------- // 0.0 to 1.0, gausian distribution. Box–Muller transform // This form is probably a little faster than randomGaussian() below. // -------------------------------------------------------------------- const DNN_NUMERIC scale = 2.0 / (DNN_NUMERIC) RAND_MAX; static DNN_NUMERIC z1 = 0.0; static bool return_z1 = false; if( return_z1 ) { return_z1 = false; return z1; // Return z1 (prevously calculated) } return_z1 = true; DNN_NUMERIC u, v, r; do { u = ((DNN_NUMERIC) rand() * scale) -1.0; // [ -1.0, 1.0 ] v = ((DNN_NUMERIC) rand() * scale) -1.0; r = u*u + v*v; } while( r == 0.0 || r > 1.0 ); const DNN_NUMERIC c = sqrt( -2.0 * log( r ) / r ); z1 = v * c; // Remember z1 for next time. return u * c; // Return z0 } DNN_NUMERIC randomGaussian( DNN_NUMERIC mu, DNN_NUMERIC sigma ) { // -------------------------------------------------------------------- // From: https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform // -------------------------------------------------------------------- const DNN_NUMERIC epsilon = std::numeric_limits<double>::min(); const DNN_NUMERIC two_pi = 2.0 * M_PI; const DNN_NUMERIC scale = 1.0 / (DNN_NUMERIC) RAND_MAX; static bool generate = false; generate = !generate; static DNN_NUMERIC z1 = 0.0; if( !generate ) { return z1 * sigma + mu; } DNN_NUMERIC u1, u2; do { u1 = rand() * scale; // [0.0,1.0] u2 = rand() * scale; } while ( u1 <= epsilon ); const DNN_NUMERIC pu = two_pi * u2; const DNN_NUMERIC cc = sqrt(-2.0 * log(u1)); const DNN_NUMERIC z0 = cc * cos( pu ); z1 = cc * sin( pu ); return z0 * sigma + mu; } } // namespace tfs <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: options.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2007-06-27 21:15:08 $ * * 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 2006 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_svtools.hxx" #include "sal/config.h" #include <svtools/options.hxx> using svt::detail::Options; Options::Options() {} Options::~Options() {} <commit_msg>INTEGRATION: CWS changefileheader (1.4.246); FILE MERGED 2008/03/31 13:01:26 rt 1.4.246.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: options.cxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svtools.hxx" #include "sal/config.h" #include <svtools/options.hxx> using svt::detail::Options; Options::Options() {} Options::~Options() {} <|endoftext|>
<commit_before><commit_msg>ByteString::ConvertToUnicode->rtl::OUString::ctor::toChar<commit_after><|endoftext|>
<commit_before>/******************************************************************************* * Copyright (c) 2015 Wojciech Migda * All rights reserved * Distributed under the terms of the GNU LGPL v3 ******************************************************************************* * * Filename: array2d.hpp * * Description: * Let's try to have a numpy-like environment * * Authors: * Wojciech Migda (wm) * ******************************************************************************* * History: * -------- * Date Who Ticket Description * ---------- --- --------- ------------------------------------------------ * 2015-01-30 wm Initial version. TripSafetyFactors * 2015-02-22 wm ChildStuntedness5 * ******************************************************************************/ #ifndef ARRAY2D_HPP_ #define ARRAY2D_HPP_ #include "num.hpp" #include <cstdlib> #include <utility> #include <valarray> #include <map> #include <algorithm> #include <iostream> #include <cassert> #include <string> #include <sstream> #include <type_traits> #include <unordered_set> namespace num { typedef std::pair<size_type, size_type> shape_type; /** ******************************************************************************* * @brief 2d array ******************************************************************************* * @history @code * DATE VERSION WHO DESCRIPTION * ----------- ------- ------ ----------- * 2015-01-30 wm Class created. * 2015-02-22 wm @c column interface: size_type -> int * 2015-02-22 wm @c at method * @endcode ******************************************************************************* * 2d clone of numpy's ndarray: * http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html ******************************************************************************* */ template<typename _Type> class array2d { public: enum class Axis { Row, Column }; typedef _Type value_type; typedef std::size_t size_type; typedef std::pair<size_type, size_type> shape_type; typedef std::valarray<value_type> vector_type; array2d(shape_type shape, value_type initializer); shape_type shape(void) const; value_type at(int p, int q) const; value_type & at(int p, int q); std::slice row(size_type n) const; std::slice column(int n) const; std::slice stripe(size_type n, enum Axis axis) const; std::gslice columns(int p, int q) const; void mul( const Axis, const std::valarray<value_type> & ivector, std::valarray<value_type> & ovector) const; template<typename _Op> void mul( const Axis, const std::valarray<value_type> & ivector, std::valarray<value_type> & ovector, _Op op) const; std::valarray<value_type> operator[](std::slice slicearr) const; std::slice_array<value_type> operator[](std::slice slicearr); std::valarray<value_type> operator[](const std::gslice & gslicearr) const; std::gslice_array<value_type> operator[](const std::gslice & gslicearr); private: shape_type m_shape; vector_type m_varray; }; template<typename _Type> inline array2d<_Type>::array2d(shape_type shape, array2d<_Type>::value_type initializer) : m_shape(shape), m_varray(initializer, shape.first * shape.second) { } template<typename _Type> inline shape_type array2d<_Type>::shape(void) const { return m_shape; } template<typename _Type> inline _Type array2d<_Type>::at(int p, int q) const { if (p < 0) { assert(-p < m_shape.second); p = m_shape.second + p; } if (q < 0) { assert(-q < m_shape.second); q = m_shape.second + q; } return m_varray[p * m_shape.second + q]; } template<typename _Type> inline _Type & array2d<_Type>::at(int p, int q) { if (p < 0) { assert(-p < m_shape.second); p = m_shape.second + p; } if (q < 0) { assert(-q < m_shape.second); q = m_shape.second + q; } return m_varray[p * m_shape.second + q]; } template<typename _Type> inline std::slice array2d<_Type>::row(size_type n) const { return std::slice(n * m_shape.second, m_shape.second, 1); } template<typename _Type> inline std::slice array2d<_Type>::column(int n) const { if (n < 0) { assert(-n < m_shape.second); n = m_shape.second + n; } return std::slice(n, m_shape.first, m_shape.second); } template<typename _Type> inline std::gslice array2d<_Type>::columns(int p, int q) const { if (p < 0) { assert(-p < m_shape.second); p = m_shape.second + p; } if (q < 0) { assert(-q < m_shape.second); q = m_shape.second + q; } return std::gslice( p, {m_shape.first, {q - p + 1u}}, {m_shape.second, 1u} ); } template<typename _Type> inline std::slice array2d<_Type>::stripe(size_type n, enum Axis axis) const { return axis == Axis::Row ? row(n) : column(n); } template<typename _Type> inline void array2d<_Type>::mul( const enum Axis axis, const std::valarray<_Type> & ivector, std::valarray<_Type> & ovector) const { mul(axis, ivector, ovector, [](const value_type & lhs, const value_type & rhs) -> value_type { return rhs; } ); } template<typename _Type> template<typename _Op> inline void array2d<_Type>::mul( const enum Axis axis, const std::valarray<_Type> & ivector, std::valarray<_Type> & ovector, _Op op) const { if (axis == Axis::Column) { assert(ivector.size() == m_shape.first); assert(ovector.size() == m_shape.second); // std::valarray<_Type> temp = ovector; // for (size_type r{0}; r < m_shape.first; ++r) // { //// ovector = op(ovector, m_varray[row(r)] * ivector[r]); // ovector += m_varray[row(r)] * ivector[r]; // } for (size_type c{0}; c < m_shape.second; ++c) { ovector[c] = op(ovector[c], (m_varray[column(c)] * ivector).sum()); } } else { assert(ivector.size() == m_shape.second); assert(ovector.size() == m_shape.first); for (size_type r{0}; r < m_shape.first; ++r) { ovector[r] = op(ovector[r], (m_varray[row(r)] * ivector).sum()); } } } template<typename _Type> inline std::valarray<_Type> array2d<_Type>::operator[](std::slice slicearr) const { return m_varray[slicearr]; } template<typename _Type> inline std::slice_array<_Type> array2d<_Type>::operator[](std::slice slicearr) { return m_varray[slicearr]; } template<typename _Type> inline std::valarray<_Type> array2d<_Type>::operator[](const std::gslice & gslicearr) const { return m_varray[gslicearr]; } template<typename _Type> inline std::gslice_array<_Type> array2d<_Type>::operator[](const std::gslice & gslicearr) { return m_varray[gslicearr]; } template<typename _Type> inline array2d<_Type> zeros(shape_type shape) { return array2d<_Type>(shape, 0.0); } template<typename _Type> inline array2d<_Type> ones(shape_type shape) { return array2d<_Type>(shape, 1.0); } /** ******************************************************************************* * @brief Configuration for @c loadtxt ******************************************************************************* * @history @code * DATE VERSION WHO DESCRIPTION * ----------- ------- ------ ----------- * 2015-02-07 wm Class created. TripSafetyFactors * 2015-02-22 wm Index of -1 for converters means all cols * 2015-02-22 wm use_cols accessor * @endcode ******************************************************************************* */ template<typename _Type = double> struct loadtxtCfg { typedef std::map<int, _Type(*)(const char *)> converters_type; typedef std::unordered_set<size_type> use_cols_type; loadtxtCfg() : m_comments{'#'}, m_delimiter{' '}, m_converters{}, m_skip_header{0}, m_skip_footer{0}, m_use_cols{} {} loadtxtCfg & comments(char _comments) { m_comments = _comments; return *this; } char delimiter(void) const { return m_delimiter; } loadtxtCfg & delimiter(char _delimiter) { m_delimiter = _delimiter; return *this; } const converters_type & converters(void) const { return m_converters; } loadtxtCfg & converters(converters_type && _converters) { m_converters = std::move(_converters); return *this; } size_type skip_header(void) const { return m_skip_header; } loadtxtCfg & skip_header(size_type _skip_header) { m_skip_header = _skip_header; return *this; } size_type skip_footer(void) const { return m_skip_footer; } loadtxtCfg & skip_footer(size_type _skip_footer) { m_skip_footer = _skip_footer; return *this; } const use_cols_type & use_cols(void) const { return m_use_cols; } loadtxtCfg & use_cols(const use_cols_type & _use_cols) { m_use_cols = _use_cols; return *this; } loadtxtCfg & use_cols(use_cols_type && _use_cols) { m_use_cols = std::move(_use_cols); return *this; } char m_comments; char m_delimiter; converters_type m_converters; size_type m_skip_header; size_type m_skip_footer; use_cols_type m_use_cols; }; /** ******************************************************************************* * @brief Load data from a vector of strings. ******************************************************************************* * @history @code * DATE VERSION WHO DESCRIPTION * ----------- ------- ------ ----------- * 2015-02-07 wm Class created. TripSafetyFactors * 2015-02-22 wm Index of -1 for converters means all cols * 2015-02-22 wm use_cols selector applied * @endcode ******************************************************************************* * @param txt vector of strings to read from * @param cfg confguration of the processor ******************************************************************************* * @return 2d array created from passed vector of strings ******************************************************************************* * Implementation based on * http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html * interface. ******************************************************************************* */ template<typename _Type> array2d<_Type> loadtxt( std::vector<std::string> && txt, loadtxtCfg<_Type> && cfg ) { typedef _Type value_type; const bool skip_empty = false; auto count_delimiters = [&skip_empty](std::string where, char delim) -> size_type { auto predicate = [&delim](char _this, char _that) { return _this == _that && _this == delim; }; if (skip_empty) { std::unique(where.begin(), where.end(), predicate); } return std::count(where.cbegin(), where.cend(), delim); }; assert(txt.size() >= (cfg.skip_header() + cfg.skip_footer())); const size_type NROWS = txt.size() - cfg.skip_header() - cfg.skip_footer(); if (NROWS == 0) { return zeros<value_type>(shape_type(0, 0)); } const bool WIDESPAN_CONVERTER = cfg.converters().find(-1) != cfg.converters().cend(); const bool USE_COLS = cfg.use_cols().size() != 0; const size_type NICOLS = 1 + count_delimiters(txt.front(), cfg.delimiter()); // TODO const size_type NCOLS = USE_COLS ? cfg.use_cols().size() : NICOLS; array2d<_Type> result = zeros<value_type>(shape_type(NROWS, NCOLS)); for (size_type ridx{0}; ridx < NROWS; ++ridx) { std::valarray<value_type> row(NROWS); std::stringstream ss(txt[ridx + cfg.skip_header()]); std::string item; size_type ocidx{0}; for (size_type icidx{0}; icidx < NICOLS && std::getline(ss, item, cfg.delimiter()); ++icidx) // TODO { if (USE_COLS && (cfg.use_cols().find(icidx) == cfg.use_cols().cend())) { continue; } if (WIDESPAN_CONVERTER) { row[ocidx] = cfg.converters().at(-1)(item.c_str()); } else if (cfg.converters().find(icidx) != cfg.converters().cend()) { row[ocidx] = cfg.converters().at(icidx)(item.c_str()); } else if (std::is_convertible<value_type, long double>::value) { row[ocidx] = std::strtold(item.c_str(), nullptr); } else if (std::is_convertible<value_type, long long>::value) { row[ocidx] = std::atoll(item.c_str()); } else { std::stringstream item_ss(item); item_ss >> row[ocidx]; } ++ocidx; } result[result.row(ridx)] = row; } return result; } } // namespace num namespace std { std::ostream & operator<<(std::ostream & os, const num::shape_type & shape) { os << '(' << shape.first << ',' << shape.second << ')'; return os; } } // namespace std #endif /* ARRAY2D_HPP_ */ <commit_msg>little cleanup<commit_after>/******************************************************************************* * Copyright (c) 2015 Wojciech Migda * All rights reserved * Distributed under the terms of the GNU LGPL v3 ******************************************************************************* * * Filename: array2d.hpp * * Description: * Let's try to have a numpy-like environment * * Authors: * Wojciech Migda (wm) * ******************************************************************************* * History: * -------- * Date Who Ticket Description * ---------- --- --------- ------------------------------------------------ * 2015-01-30 wm Initial version. TripSafetyFactors * 2015-02-22 wm ChildStuntedness5 * ******************************************************************************/ #ifndef ARRAY2D_HPP_ #define ARRAY2D_HPP_ #include "num.hpp" #include <cstdlib> #include <utility> #include <valarray> #include <map> #include <algorithm> #include <iostream> #include <cassert> #include <string> #include <sstream> #include <type_traits> #include <unordered_set> namespace num { typedef std::pair<size_type, size_type> shape_type; /** ******************************************************************************* * @brief 2d array ******************************************************************************* * @history @code * DATE VERSION WHO DESCRIPTION * ----------- ------- ------ ----------- * 2015-01-30 wm Class created. * 2015-02-22 wm @c column interface: size_type -> int * 2015-02-22 wm @c at method * @endcode ******************************************************************************* * 2d clone of numpy's ndarray: * http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html ******************************************************************************* */ template<typename _Type> class array2d { public: enum class Axis { Row, Column }; typedef _Type value_type; typedef std::size_t size_type; typedef std::pair<size_type, size_type> shape_type; typedef std::valarray<value_type> vector_type; array2d(shape_type shape, value_type initializer); shape_type shape(void) const; value_type at(int p, int q) const; value_type & at(int p, int q); std::slice row(size_type n) const; std::slice column(int n) const; std::slice stripe(size_type n, enum Axis axis) const; std::gslice columns(int p, int q) const; void mul( const Axis, const std::valarray<value_type> & ivector, std::valarray<value_type> & ovector) const; template<typename _Op> void mul( const Axis, const std::valarray<value_type> & ivector, std::valarray<value_type> & ovector, _Op op) const; std::valarray<value_type> operator[](std::slice slicearr) const; std::slice_array<value_type> operator[](std::slice slicearr); std::valarray<value_type> operator[](const std::gslice & gslicearr) const; std::gslice_array<value_type> operator[](const std::gslice & gslicearr); private: shape_type m_shape; vector_type m_varray; }; template<typename _Type> inline array2d<_Type>::array2d(shape_type shape, array2d<_Type>::value_type initializer) : m_shape(shape), m_varray(initializer, shape.first * shape.second) { } template<typename _Type> inline shape_type array2d<_Type>::shape(void) const { return m_shape; } template<typename _Type> inline _Type array2d<_Type>::at(int p, int q) const { if (p < 0) { assert(-p < m_shape.second); p = m_shape.second + p; } if (q < 0) { assert(-q < m_shape.second); q = m_shape.second + q; } return m_varray[p * m_shape.second + q]; } template<typename _Type> inline _Type & array2d<_Type>::at(int p, int q) { if (p < 0) { assert(-p < m_shape.second); p = m_shape.second + p; } if (q < 0) { assert(-q < m_shape.second); q = m_shape.second + q; } return m_varray[p * m_shape.second + q]; } template<typename _Type> inline std::slice array2d<_Type>::row(size_type n) const { return std::slice(n * m_shape.second, m_shape.second, 1); } template<typename _Type> inline std::slice array2d<_Type>::column(int n) const { if (n < 0) { assert(-n < m_shape.second); n = m_shape.second + n; } return std::slice(n, m_shape.first, m_shape.second); } template<typename _Type> inline std::gslice array2d<_Type>::columns(int p, int q) const { if (p < 0) { assert(-p < m_shape.second); p = m_shape.second + p; } if (q < 0) { assert(-q < m_shape.second); q = m_shape.second + q; } return std::gslice( p, {m_shape.first, {q - p + 1u}}, {m_shape.second, 1u} ); } template<typename _Type> inline std::slice array2d<_Type>::stripe(size_type n, enum Axis axis) const { return axis == Axis::Row ? row(n) : column(n); } template<typename _Type> inline void array2d<_Type>::mul( const enum Axis axis, const std::valarray<_Type> & ivector, std::valarray<_Type> & ovector) const { mul(axis, ivector, ovector, [](const value_type & lhs, const value_type & rhs) -> value_type { return rhs; } ); } template<typename _Type> template<typename _Op> inline void array2d<_Type>::mul( const enum Axis axis, const std::valarray<_Type> & ivector, std::valarray<_Type> & ovector, _Op op) const { if (axis == Axis::Column) { assert(ivector.size() == m_shape.first); assert(ovector.size() == m_shape.second); // this is faster, but sadly, has more error // for (size_type r{0}; r < m_shape.first; ++r) // { // ovector = op(ovector, m_varray[row(r)] * ivector[r]); // } for (size_type c{0}; c < m_shape.second; ++c) { ovector[c] = op(ovector[c], (m_varray[column(c)] * ivector).sum()); } } else { assert(ivector.size() == m_shape.second); assert(ovector.size() == m_shape.first); for (size_type r{0}; r < m_shape.first; ++r) { ovector[r] = op(ovector[r], (m_varray[row(r)] * ivector).sum()); } } } template<typename _Type> inline std::valarray<_Type> array2d<_Type>::operator[](std::slice slicearr) const { return m_varray[slicearr]; } template<typename _Type> inline std::slice_array<_Type> array2d<_Type>::operator[](std::slice slicearr) { return m_varray[slicearr]; } template<typename _Type> inline std::valarray<_Type> array2d<_Type>::operator[](const std::gslice & gslicearr) const { return m_varray[gslicearr]; } template<typename _Type> inline std::gslice_array<_Type> array2d<_Type>::operator[](const std::gslice & gslicearr) { return m_varray[gslicearr]; } template<typename _Type> inline array2d<_Type> zeros(shape_type shape) { return array2d<_Type>(shape, 0.0); } template<typename _Type> inline array2d<_Type> ones(shape_type shape) { return array2d<_Type>(shape, 1.0); } /** ******************************************************************************* * @brief Configuration for @c loadtxt ******************************************************************************* * @history @code * DATE VERSION WHO DESCRIPTION * ----------- ------- ------ ----------- * 2015-02-07 wm Class created. TripSafetyFactors * 2015-02-22 wm Index of -1 for converters means all cols * 2015-02-22 wm use_cols accessor * @endcode ******************************************************************************* */ template<typename _Type = double> struct loadtxtCfg { typedef std::map<int, _Type(*)(const char *)> converters_type; typedef std::unordered_set<size_type> use_cols_type; loadtxtCfg() : m_comments{'#'}, m_delimiter{' '}, m_converters{}, m_skip_header{0}, m_skip_footer{0}, m_use_cols{} {} loadtxtCfg & comments(char _comments) { m_comments = _comments; return *this; } char delimiter(void) const { return m_delimiter; } loadtxtCfg & delimiter(char _delimiter) { m_delimiter = _delimiter; return *this; } const converters_type & converters(void) const { return m_converters; } loadtxtCfg & converters(converters_type && _converters) { m_converters = std::move(_converters); return *this; } size_type skip_header(void) const { return m_skip_header; } loadtxtCfg & skip_header(size_type _skip_header) { m_skip_header = _skip_header; return *this; } size_type skip_footer(void) const { return m_skip_footer; } loadtxtCfg & skip_footer(size_type _skip_footer) { m_skip_footer = _skip_footer; return *this; } const use_cols_type & use_cols(void) const { return m_use_cols; } loadtxtCfg & use_cols(const use_cols_type & _use_cols) { m_use_cols = _use_cols; return *this; } loadtxtCfg & use_cols(use_cols_type && _use_cols) { m_use_cols = std::move(_use_cols); return *this; } char m_comments; char m_delimiter; converters_type m_converters; size_type m_skip_header; size_type m_skip_footer; use_cols_type m_use_cols; }; /** ******************************************************************************* * @brief Load data from a vector of strings. ******************************************************************************* * @history @code * DATE VERSION WHO DESCRIPTION * ----------- ------- ------ ----------- * 2015-02-07 wm Class created. TripSafetyFactors * 2015-02-22 wm Index of -1 for converters means all cols * 2015-02-22 wm use_cols selector applied * @endcode ******************************************************************************* * @param txt vector of strings to read from * @param cfg confguration of the processor ******************************************************************************* * @return 2d array created from passed vector of strings ******************************************************************************* * Implementation based on * http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html * interface. ******************************************************************************* */ template<typename _Type> array2d<_Type> loadtxt( std::vector<std::string> && txt, loadtxtCfg<_Type> && cfg ) { typedef _Type value_type; const bool skip_empty = false; auto count_delimiters = [&skip_empty](std::string where, char delim) -> size_type { auto predicate = [&delim](char _this, char _that) { return _this == _that && _this == delim; }; if (skip_empty) { std::unique(where.begin(), where.end(), predicate); } return std::count(where.cbegin(), where.cend(), delim); }; assert(txt.size() >= (cfg.skip_header() + cfg.skip_footer())); const size_type NROWS = txt.size() - cfg.skip_header() - cfg.skip_footer(); if (NROWS == 0) { return zeros<value_type>(shape_type(0, 0)); } const bool WIDESPAN_CONVERTER = cfg.converters().find(-1) != cfg.converters().cend(); const bool USE_COLS = cfg.use_cols().size() != 0; const size_type NICOLS = 1 + count_delimiters(txt.front(), cfg.delimiter()); // TODO const size_type NCOLS = USE_COLS ? cfg.use_cols().size() : NICOLS; array2d<_Type> result = zeros<value_type>(shape_type(NROWS, NCOLS)); for (size_type ridx{0}; ridx < NROWS; ++ridx) { std::valarray<value_type> row(NROWS); std::stringstream ss(txt[ridx + cfg.skip_header()]); std::string item; size_type ocidx{0}; for (size_type icidx{0}; icidx < NICOLS && std::getline(ss, item, cfg.delimiter()); ++icidx) // TODO { if (USE_COLS && (cfg.use_cols().find(icidx) == cfg.use_cols().cend())) { continue; } if (WIDESPAN_CONVERTER) { row[ocidx] = cfg.converters().at(-1)(item.c_str()); } else if (cfg.converters().find(icidx) != cfg.converters().cend()) { row[ocidx] = cfg.converters().at(icidx)(item.c_str()); } else if (std::is_convertible<value_type, long double>::value) { row[ocidx] = std::strtold(item.c_str(), nullptr); } else if (std::is_convertible<value_type, long long>::value) { row[ocidx] = std::atoll(item.c_str()); } else { std::stringstream item_ss(item); item_ss >> row[ocidx]; } ++ocidx; } result[result.row(ridx)] = row; } return result; } } // namespace num namespace std { std::ostream & operator<<(std::ostream & os, const num::shape_type & shape) { os << '(' << shape.first << ',' << shape.second << ')'; return os; } } // namespace std #endif /* ARRAY2D_HPP_ */ <|endoftext|>
<commit_before>/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.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. * */ #include <stdlib.h> #include <votca/csg/csgapplication.h> using namespace std; using namespace votca::csg; class CsgDumpApp : public CsgApplication { string ProgramName() { return "csg_dump"; } void HelpText(ostream &out) { out << "Print atoms that are read from topology file to help" " debugging atom naming."; } void Initialize() { CsgApplication::Initialize(); AddProgramOptions("Specific options") ("excl", " display exclusion list instead of molecule list"); } bool EvaluateTopology(Topology *top, Topology *top_ref); bool DoMapping() {return true;} bool DoMappingDefault(void) { return false; } }; int main(int argc, char** argv) { CsgDumpApp app; return app.Exec(argc, argv); } bool CsgDumpApp::EvaluateTopology(Topology *top, Topology *top_ref) { if(!OptionsMap().count("excl")) { cout << "\nList of molecules:\n"; MoleculeContainer::iterator mol; for (mol = top->Molecules().begin(); mol != top->Molecules().end(); ++mol) { cout << "molecule: " << (*mol)->getId() + 1 << " " << (*mol)->getName() << " beads: " << (*mol)->BeadCount() << endl; for (int i = 0; i < (*mol)->BeadCount(); ++i) { cout << (*mol)->getBeadId(i) << " " << (*mol)->getBeadName(i) << " " << (*mol)->getBead(i)->getType()->getName() << endl; } } } else { cout << "\nList of exclusions:\n" << top->getExclusions(); } return true; } <commit_msg>csg_dump: print bead mass<commit_after>/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.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. * */ #include <stdlib.h> #include <votca/csg/csgapplication.h> using namespace std; using namespace votca::csg; class CsgDumpApp : public CsgApplication { string ProgramName() { return "csg_dump"; } void HelpText(ostream &out) { out << "Print atoms that are read from topology file to help" " debugging atom naming."; } void Initialize() { CsgApplication::Initialize(); AddProgramOptions("Specific options") ("excl", " display exclusion list instead of molecule list"); } bool EvaluateTopology(Topology *top, Topology *top_ref); bool DoMapping() {return true;} bool DoMappingDefault(void) { return false; } }; int main(int argc, char** argv) { CsgDumpApp app; return app.Exec(argc, argv); } bool CsgDumpApp::EvaluateTopology(Topology *top, Topology *top_ref) { if(!OptionsMap().count("excl")) { cout << "\nList of molecules:\n"; MoleculeContainer::iterator mol; for (mol = top->Molecules().begin(); mol != top->Molecules().end(); ++mol) { cout << "molecule: " << (*mol)->getId() + 1 << " " << (*mol)->getName() << " beads: " << (*mol)->BeadCount() << endl; for (int i = 0; i < (*mol)->BeadCount(); ++i) { cout << (*mol)->getBeadId(i) << " Name " << (*mol)->getBeadName(i) << " Type " << (*mol)->getBead(i)->getType()->getName() << " Mass " << (*mol)->getBead(i)->getM() << endl; } } } else { cout << "\nList of exclusions:\n" << top->getExclusions(); } return true; } <|endoftext|>
<commit_before>/* * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.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. * */ #include <stdlib.h> #include <votca/csg/csgapplication.h> using namespace std; using namespace votca::csg; class CsgDumpApp : public CsgApplication { string ProgramName() { return "csg_dump"; } void HelpText(ostream &out) { out << "Print atoms that are read from topology file to help" " debugging atom naming."; } void Initialize() { CsgApplication::Initialize(); AddProgramOptions("Specific options") ("excl", " display exclusion list instead of molecule list"); } bool EvaluateTopology(Topology *top, Topology *top_ref); bool DoMapping() {return true;} bool DoMappingDefault(void) { return false; } }; int main(int argc, char** argv) { CsgDumpApp app; return app.Exec(argc, argv); } bool CsgDumpApp::EvaluateTopology(Topology *top, Topology *top_ref) { if(!OptionsMap().count("excl")) { cout << "Boundary Condition: "; if(top->getBoxType()==BoundaryCondition::typeAuto) { cout << "auto"; } else if (top->getBoxType()==BoundaryCondition::typeTriclinic) { cout << "triclinic"; } else if (top->getBoxType()==BoundaryCondition::typeOrthorhombic) { cout << "orthorhombic"; } else if (top->getBoxType()==BoundaryCondition::typeOpen) { cout << "open"; } cout << endl; if (top->getBoxType()!=BoundaryCondition::typeOpen) { cout << " Box matix:"; matrix box=top->getBox(); for (int i=0;i<3;i++){ for (int j=0;j<3;j++){ cout << " " << box[i][j]; } cout << endl << " "; } } cout << "\nList of residues:\n"; for (int i=0; i<top->ResidueCount(); i++){ cout << i << " name: " << top->getResidue(i)->getName() << " id: " << top->getResidue(i)->getId() << endl; } cout << "\nList of molecules:\n"; MoleculeContainer::iterator mol; for (mol = top->Molecules().begin(); mol != top->Molecules().end(); ++mol) { cout << "molecule: " << (*mol)->getId() + 1 << " " << (*mol)->getName() << " beads: " << (*mol)->BeadCount() << endl; for (int i = 0; i < (*mol)->BeadCount(); ++i) { int resnr=(*mol)->getBead(i)->getResnr(); auto weak_type = (*mol)->getBead(i)->getType(); if(auto type = weak_type.lock()){ cout << (*mol)->getBeadId(i) << " Name " << (*mol)->getBeadName(i) << " Type " << type->getName() << " Mass " << (*mol)->getBead(i)->getMass() << " Resnr " << resnr << " Resname " << top->getResidue(resnr)->getName() << " Charge " << (*mol)->getBead(i)->getQ() << endl; }else{ throw runtime_error("Error cannot access beadtype in csg_dump."); } } } } else { cout << "\nList of exclusions:\n" << top->getExclusions(); } return true; } <commit_msg>Reduced syntax by using getBeadTypeName() method<commit_after>/* * Copyright 2009-2018 The VOTCA Development Team (http://www.votca.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. * */ #include <stdlib.h> #include <votca/csg/csgapplication.h> using namespace std; using namespace votca::csg; class CsgDumpApp : public CsgApplication { string ProgramName() { return "csg_dump"; } void HelpText(ostream &out) { out << "Print atoms that are read from topology file to help" " debugging atom naming."; } void Initialize() { CsgApplication::Initialize(); AddProgramOptions("Specific options") ("excl", " display exclusion list instead of molecule list"); } bool EvaluateTopology(Topology *top, Topology *top_ref); bool DoMapping() {return true;} bool DoMappingDefault(void) { return false; } }; int main(int argc, char** argv) { CsgDumpApp app; return app.Exec(argc, argv); } bool CsgDumpApp::EvaluateTopology(Topology *top, Topology *top_ref) { if(!OptionsMap().count("excl")) { cout << "Boundary Condition: "; if(top->getBoxType()==BoundaryCondition::typeAuto) { cout << "auto"; } else if (top->getBoxType()==BoundaryCondition::typeTriclinic) { cout << "triclinic"; } else if (top->getBoxType()==BoundaryCondition::typeOrthorhombic) { cout << "orthorhombic"; } else if (top->getBoxType()==BoundaryCondition::typeOpen) { cout << "open"; } cout << endl; if (top->getBoxType()!=BoundaryCondition::typeOpen) { cout << " Box matix:"; matrix box=top->getBox(); for (int i=0;i<3;i++){ for (int j=0;j<3;j++){ cout << " " << box[i][j]; } cout << endl << " "; } } cout << "\nList of residues:\n"; for (int i=0; i<top->ResidueCount(); i++){ cout << i << " name: " << top->getResidue(i)->getName() << " id: " << top->getResidue(i)->getId() << endl; } cout << "\nList of molecules:\n"; MoleculeContainer::iterator mol; for (mol = top->Molecules().begin(); mol != top->Molecules().end(); ++mol) { cout << "molecule: " << (*mol)->getId() + 1 << " " << (*mol)->getName() << " beads: " << (*mol)->BeadCount() << endl; for (int i = 0; i < (*mol)->BeadCount(); ++i) { int resnr=(*mol)->getBead(i)->getResnr(); cout << (*mol)->getBeadId(i) << " Name " << (*mol)->getBeadName(i) << " Type " << (*mol)->getBead(i)->getBeadTypeName() << " Mass " << (*mol)->getBead(i)->getMass() << " Resnr " << resnr << " Resname " << top->getResidue(resnr)->getName() << " Charge " << (*mol)->getBead(i)->getQ() << endl; } } } else { cout << "\nList of exclusions:\n" << top->getExclusions(); } return true; } <|endoftext|>
<commit_before>#include <exodus/program.h> programinit() function main() { var dbname2 = COMMAND.a(2); var filenames = COMMAND.field(FM, 3, 999999); if (not dbname2 and not OPTIONS) { var syntax = "dbattach - Attach foreign database files to the current default database\n" "\n" "Syntax is dbattach TARGETDB [FILENAME,...] {OPTION...}\n" "\n" "Options:\n" "\n" " F Forcibly delete any normal files in the current default database.\n" "\n" " R Detach foreign files\n" " RR Remove foreign database connection.\n" " RRR Remove all foreign database connections and attachments.\n" "\n" " L List attached foreign files in the current default database\n" "\n" "If no filenames are provided then a database connection is created.\n" "This is *required* before filenames can be provided and attached.\n" "\n" "Notes:\n" "\n" "Attachments are permanent until re-attached or removed.\n" "\n" "Indexes on attached files behave strangely.\n" "\n" "Issues:\n" "\n" "TARGETDB must be on the same connection as the current default database.\n" "\n" "Current user must have access to the foreign database.\n" "\n" "If EXO_USER and EXO_PASS are not set then exodus defaults are used.\n" "\n" "exodus .config file is not used currently.\n" ; abort(syntax); } // TODO Get user from .config/Allow control var dbname1 = osgetenv("EXO_DATA"); if (not dbname1) dbname1 = "exodus"; // TODO Get user from .config/Allow control var dbuser1 = osgetenv("EXO_USER"); if (not dbuser1) dbuser1 = "exodus"; // TODO Allow control over dbuser2/dbpass2 var dbuser2 = dbuser1; var dbpass2 = osgetenv("EXO_PASS"); if (not dbpass2) dbpass2 = "somesillysecret"; // Default connection var conn1; if (not conn1.connect()) abort(conn1.lasterror()); var sql; if (OPTIONS.index("L")) { sql = "select foreign_server_name, foreign_table_name from information_schema.foreign_tables;"; var result; if (not conn1.sqlexec(sql, result)) abort(conn1.lasterror()); // change RM to FM etc. and remove column headings result.lowerer(); result.remover(1); //format for printing result.converter(FM, "\n"); result.converter(VM, " "); printl(result); stop(); } //////////////////////////////////////////////////////////////////////////// // Create an interdb connection from default database to the target database //////////////////////////////////////////////////////////////////////////// // If no filenames are provided then just setup the interdb connection if (not filenames or OPTIONS.index("R")) { ///////////////////////////////////////////////////////////////////////// // Must be done as a superuser eg postgres or exodus with superuser power ///////////////////////////////////////////////////////////////////////// // Check we are a superuser sql = "ALTER USER " ^ dbuser1 ^ " WITH SUPERUSER"; if (not conn1.sqlexec(sql)) abort(conn1.lasterror()); // Reset all interdb connections if (OPTIONS.index("RRR")) { if (not conn1.sqlexec("DROP EXTENSION IF EXISTS postgres_fdw CASCADE")) abort(conn1.lasterror()); stop(); } // Install extension required to establish interdb connections if (not conn1.sqlexec("CREATE EXTENSION IF NOT EXISTS postgres_fdw WITH SCHEMA public")) abort(conn1.lasterror()); if (not dbname2) stop(); // Reset the interdb connection to the target db. Remove all connected tables. if (not conn1.sqlexec("DROP SERVER IF EXISTS " ^ dbname2 ^ " CASCADE")) abort(conn1.lasterror()); // Create an interdb connection to the target server if (OPTIONS.index("RR")) exit(0); if (not conn1.sqlexec("CREATE SERVER IF NOT EXISTS " ^ dbname2 ^ " FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'localhost', dbname '" ^ dbname2 ^ "', port '5432')")) abort(conn1.lasterror()); // Allow current user to use the interdb connection if (not conn1.sqlexec("GRANT USAGE ON FOREIGN SERVER " ^ dbname2 ^ " TO " ^ dbuser1)) abort(conn1.lasterror()); // Remove any existing user/connection configuration if (not conn1.sqlexec("DROP USER MAPPING IF EXISTS FOR " ^ dbuser1 ^ " SERVER " ^ dbname2)) abort(conn1.lasterror()); if (OPTIONS.index("R")) exit(0); // Configure user/connection parameters. Target dbuser and dbpass. if (not conn1.sqlexec("CREATE USER MAPPING FOR " ^ dbuser1 ^ " SERVER " ^ dbname2 ^ " OPTIONS (user '" ^ dbuser2 ^ "', password '" ^dbpass2 ^ "')")) abort(conn1.lasterror()); //printl("OK user " ^ dbuser1 ^ " in db " ^ dbname1 ^ " now has access to db " ^ dbname2); return 0; } /////////////////////////////////////////////////////////////////// // Attach target db files as apparent files in the default database /////////////////////////////////////////////////////////////////// // Remainder must be done as operating user eg exodus //\psql -h localhost -p 5432 adlinec3 exodus // Convert filenames to a comma separated list filenames.converter(",", FM).trimmer(FM); for (var filename : filenames) { if (not filename) continue; if (conn1.open(filename)) { // Option to forcibly delete any existing files in the default database if (OPTIONS.index("F")) { //logputl("Remove any existing table " ^ filename); //if (not conn1.sqlexec("DROP TABLE IF EXISTS " ^ filenames.swap(","," "))) // abort(conn1.lasterror()); if (not conn1.deletefile(filename)) {};//logputl(conn1.lasterror()); } //logputl("Remove any existing connected foreign table " ^ filename); if (conn1.open(filename) and not conn1.sqlexec("DROP FOREIGN TABLE IF EXISTS " ^ filename)) {};//abort(conn1.lasterror()); } //logputl("Connect to the foreign table " ^ filename); var sql = "IMPORT FOREIGN SCHEMA public LIMIT TO (" ^ filename ^ ") FROM SERVER " ^ dbname2 ^ " INTO public"; if (not conn1.sqlexec(sql)) { var lasterror = conn1.lasterror(); // If the server is not already attached then attach it // ERROR: server "adlinek_test" does not exist // sqlstate:42704^IMPORT FOREIGN SCHEMA public LIMIT TO (markets) FROM SERVER adlinek_test INTO public if (lasterror.index("sqlstate:42704")) { if (not osshell(SENTENCE.field(" ", 1, 2))) abort(""); } if (not conn1.sqlexec(sql)) abort(conn1.lasterror()); } } return 0; } programexit() <commit_msg>Improve doc embedded in dbattach<commit_after>#include <exodus/program.h> programinit() function main() { var dbname2 = COMMAND.a(2); var filenames = COMMAND.field(FM, 3, 999999); if (not dbname2 and not OPTIONS) { var syntax = "NAME\n" " dbattach - Attach foreign database files to the current default database\n" "\n" "SYNOPSIS\n" " dbattach TARGETDB [FILENAME,...] {OPTION...}\n" "\n" "EXAMPLE\n" " EXO_DATA=db1 dbattach db2 file1 filen2 {F}\n" "\n" " file1 and file2 in db1 are foreign and actually resident in db2\n" "\n" "OPTIONS\n" " F Forcibly delete any normal files in the current default database.\n" "\n" " R Detach foreign files\n" " RR Remove foreign database connection.\n" " RRR Remove all foreign database connections and attachments.\n" "\n" " L List attached foreign files in the current default database\n" "\n" "NOTES\n" " Attachments are permanent until re-attached or removed.\n" "\n" " Indexes on attached files behave strangely.\n" "\n" " Detaching will result in missing files because attaching {F} deletes them.\n" " Fix by pg_dump detached files from source and importing into target\n" "\n" "ISSUES\n" " TARGETDB must be on the same connection as the current default database.\n" "\n" " Current user must have access to the foreign database.\n" "\n" " If EXO_USER and EXO_PASS are not set then exodus defaults are used.\n" "\n" " exodus .config file is not used currently.\n" ; abort(syntax); } // TODO Get user from .config/Allow control var dbname1 = osgetenv("EXO_DATA"); if (not dbname1) dbname1 = "exodus"; // TODO Get user from .config/Allow control var dbuser1 = osgetenv("EXO_USER"); if (not dbuser1) dbuser1 = "exodus"; // TODO Allow control over dbuser2/dbpass2 var dbuser2 = dbuser1; var dbpass2 = osgetenv("EXO_PASS"); if (not dbpass2) dbpass2 = "somesillysecret"; // Default connection var conn1; if (not conn1.connect()) abort(conn1.lasterror()); var sql; if (OPTIONS.index("L")) { sql = "select foreign_server_name, foreign_table_name from information_schema.foreign_tables;"; var result; if (not conn1.sqlexec(sql, result)) abort(conn1.lasterror()); // change RM to FM etc. and remove column headings result.lowerer(); result.remover(1); //format for printing result.converter(FM, "\n"); result.converter(VM, " "); printl(result); stop(); } //////////////////////////////////////////////////////////////////////////// // Create an interdb connection from default database to the target database //////////////////////////////////////////////////////////////////////////// // If no filenames are provided then just setup the interdb connection if (not filenames or OPTIONS.index("R")) { ///////////////////////////////////////////////////////////////////////// // Must be done as a superuser eg postgres or exodus with superuser power ///////////////////////////////////////////////////////////////////////// // Check we are a superuser sql = "ALTER USER " ^ dbuser1 ^ " WITH SUPERUSER"; if (not conn1.sqlexec(sql)) abort(conn1.lasterror()); // Reset all interdb connections if (OPTIONS.index("RRR")) { if (not conn1.sqlexec("DROP EXTENSION IF EXISTS postgres_fdw CASCADE")) abort(conn1.lasterror()); stop(); } // Install extension required to establish interdb connections if (not conn1.sqlexec("CREATE EXTENSION IF NOT EXISTS postgres_fdw WITH SCHEMA public")) abort(conn1.lasterror()); if (not dbname2) stop(); // Reset the interdb connection to the target db. Remove all connected tables. if (not conn1.sqlexec("DROP SERVER IF EXISTS " ^ dbname2 ^ " CASCADE")) abort(conn1.lasterror()); // Create an interdb connection to the target server if (OPTIONS.index("RR")) exit(0); if (not conn1.sqlexec("CREATE SERVER IF NOT EXISTS " ^ dbname2 ^ " FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host 'localhost', dbname '" ^ dbname2 ^ "', port '5432')")) abort(conn1.lasterror()); // Allow current user to use the interdb connection if (not conn1.sqlexec("GRANT USAGE ON FOREIGN SERVER " ^ dbname2 ^ " TO " ^ dbuser1)) abort(conn1.lasterror()); // Remove any existing user/connection configuration if (not conn1.sqlexec("DROP USER MAPPING IF EXISTS FOR " ^ dbuser1 ^ " SERVER " ^ dbname2)) abort(conn1.lasterror()); if (OPTIONS.index("R")) exit(0); // Configure user/connection parameters. Target dbuser and dbpass. if (not conn1.sqlexec("CREATE USER MAPPING FOR " ^ dbuser1 ^ " SERVER " ^ dbname2 ^ " OPTIONS (user '" ^ dbuser2 ^ "', password '" ^dbpass2 ^ "')")) abort(conn1.lasterror()); //printl("OK user " ^ dbuser1 ^ " in db " ^ dbname1 ^ " now has access to db " ^ dbname2); return 0; } /////////////////////////////////////////////////////////////////// // Attach target db files as apparent files in the default database /////////////////////////////////////////////////////////////////// // Remainder must be done as operating user eg exodus //\psql -h localhost -p 5432 adlinec3 exodus // Convert filenames to a comma separated list filenames.converter(",", FM).trimmer(FM); for (var filename : filenames) { if (not filename) continue; if (conn1.open(filename)) { // Option to forcibly delete any existing files in the default database if (OPTIONS.index("F")) { //logputl("Remove any existing table " ^ filename); //if (not conn1.sqlexec("DROP TABLE IF EXISTS " ^ filenames.swap(","," "))) // abort(conn1.lasterror()); if (not conn1.deletefile(filename)) {};//logputl(conn1.lasterror()); } //logputl("Remove any existing connected foreign table " ^ filename); if (conn1.open(filename) and not conn1.sqlexec("DROP FOREIGN TABLE IF EXISTS " ^ filename)) {};//abort(conn1.lasterror()); } //logputl("Connect to the foreign table " ^ filename); var sql = "IMPORT FOREIGN SCHEMA public LIMIT TO (" ^ filename ^ ") FROM SERVER " ^ dbname2 ^ " INTO public"; if (not conn1.sqlexec(sql)) { var lasterror = conn1.lasterror(); // If the server is not already attached then attach it // ERROR: server "adlinek_test" does not exist // sqlstate:42704^IMPORT FOREIGN SCHEMA public LIMIT TO (markets) FROM SERVER adlinek_test INTO public if (lasterror.index("sqlstate:42704")) { if (not osshell(SENTENCE.field(" ", 1, 2))) abort(""); } if (not conn1.sqlexec(sql)) abort(conn1.lasterror()); } } return 0; } programexit() <|endoftext|>
<commit_before>// Copyright 2020 The Pigweed 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 <cstddef> #include <cstdint> #include <cstdio> #include "pw_assert/check.h" #include "pw_hdlc/rpc_channel.h" #include "pw_hdlc/rpc_packets.h" #include "pw_log/log.h" #include "pw_rpc_system_server/rpc_server.h" #include "pw_stream/socket_stream.h" namespace pw::rpc::system_server { namespace { constexpr size_t kMaxTransmissionUnit = 512; uint16_t socket_port = 33000; stream::SocketStream socket_stream; hdlc::RpcChannelOutput hdlc_channel_output(socket_stream, hdlc::kDefaultRpcAddress, "HDLC channel"); Channel channels[] = {rpc::Channel::Create<1>(&hdlc_channel_output)}; rpc::Server server(channels); } // namespace void set_socket_port(uint16_t new_socket_port) { socket_port = new_socket_port; } void Init() { log_basic::SetOutput([](std::string_view log) { std::fprintf(stderr, "%.*s\n", static_cast<int>(log.size()), log.data()); hdlc::WriteUIFrame(1, std::as_bytes(std::span(log)), socket_stream) .IgnoreError(); // TODO(pwbug/387): Handle Status properly }); PW_LOG_INFO("Starting pw_rpc server on port %d", socket_port); PW_CHECK_OK(socket_stream.Serve(socket_port)); } rpc::Server& Server() { return server; } Status Start() { // Declare a buffer for decoding incoming HDLC frames. std::array<std::byte, kMaxTransmissionUnit> input_buffer; hdlc::Decoder decoder(input_buffer); while (true) { std::array<std::byte, kMaxTransmissionUnit> data; auto ret_val = socket_stream.Read(data); if (!ret_val.ok()) { continue; } for (std::byte byte : ret_val.value()) { auto result = decoder.Process(byte); if (!result.ok()) { // Non-OK means there isn't a complete packet yet, or there was some // other issue. Wait for more bytes that form a complete packet. continue; } hdlc::Frame& frame = result.value(); if (frame.address() != hdlc::kDefaultRpcAddress) { // Wrong address; ignore the packet for now. In the future, this branch // could expand to add packet routing or metrics. continue; } server.ProcessPacket(frame.data(), hdlc_channel_output).IgnoreError(); } } } } // namespace pw::rpc::system_server <commit_msg>pw_rpc: Make system_rpc_server exit when the connection is terminated<commit_after>// Copyright 2020 The Pigweed 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 <cstddef> #include <cstdint> #include <cstdio> #include "pw_assert/check.h" #include "pw_hdlc/rpc_channel.h" #include "pw_hdlc/rpc_packets.h" #include "pw_log/log.h" #include "pw_rpc_system_server/rpc_server.h" #include "pw_stream/socket_stream.h" namespace pw::rpc::system_server { namespace { constexpr size_t kMaxTransmissionUnit = 512; uint16_t socket_port = 33000; stream::SocketStream socket_stream; hdlc::RpcChannelOutput hdlc_channel_output(socket_stream, hdlc::kDefaultRpcAddress, "HDLC channel"); Channel channels[] = {rpc::Channel::Create<1>(&hdlc_channel_output)}; rpc::Server server(channels); } // namespace void set_socket_port(uint16_t new_socket_port) { socket_port = new_socket_port; } void Init() { log_basic::SetOutput([](std::string_view log) { std::fprintf(stderr, "%.*s\n", static_cast<int>(log.size()), log.data()); hdlc::WriteUIFrame(1, std::as_bytes(std::span(log)), socket_stream) .IgnoreError(); // TODO(pwbug/387): Handle Status properly }); PW_LOG_INFO("Starting pw_rpc server on port %d", socket_port); PW_CHECK_OK(socket_stream.Serve(socket_port)); } rpc::Server& Server() { return server; } Status Start() { // Declare a buffer for decoding incoming HDLC frames. std::array<std::byte, kMaxTransmissionUnit> input_buffer; hdlc::Decoder decoder(input_buffer); while (true) { std::array<std::byte, kMaxTransmissionUnit> data; auto ret_val = socket_stream.Read(data); if (!ret_val.ok()) { if (ret_val.status() == Status::OutOfRange()) { // An out of range status indicates the remote end has disconnected. return OkStatus(); } continue; } // Empty read indicates connection termianation // // TODO: remove check on empty once pwrev/90900 lands. if (ret_val.value().empty()) { return OkStatus(); } for (std::byte byte : ret_val.value()) { auto result = decoder.Process(byte); if (!result.ok()) { // Non-OK means there isn't a complete packet yet, or there was some // other issue. Wait for more bytes that form a complete packet. continue; } hdlc::Frame& frame = result.value(); if (frame.address() != hdlc::kDefaultRpcAddress) { // Wrong address; ignore the packet for now. In the future, this branch // could expand to add packet routing or metrics. continue; } server.ProcessPacket(frame.data(), hdlc_channel_output).IgnoreError(); } } } } // namespace pw::rpc::system_server <|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/internal/mincore.h" #include <sys/mman.h> #include <unistd.h> #include <algorithm> #include <cstdint> #include <memory> #include <set> #include "benchmark/benchmark.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace tcmalloc { namespace tcmalloc_internal { using ::testing::Eq; // Mock interface to mincore() which has reports residence based on // an array provided at construction. class MInCoreMock : public MInCoreInterface { public: MInCoreMock() : mapped_() {} ~MInCoreMock() override {} // Implementation of minCore that reports presence based on provided array. int mincore(void* addr, size_t length, unsigned char* result) override { const size_t kPageSize = getpagesize(); uintptr_t uAddress = reinterpret_cast<uintptr_t>(addr); // Check that we only pass page aligned addresses into mincore(). EXPECT_THAT(uAddress & (kPageSize - 1), Eq(0)); uintptr_t uEndAddress = uAddress + length; int index = 0; // Check for presence of the target pages in the map. while (uAddress < uEndAddress) { result[index] = (mapped_.find(uAddress) != mapped_.end() ? 1 : 0); uAddress += kPageSize; index++; } return 0; } void addPage(uintptr_t uAddress) { mapped_.insert(uAddress); } private: std::set<uintptr_t> mapped_; }; // Friend class of MInCore which calls the mincore mock. class MInCoreTest { public: MInCoreTest() : mcm_() {} ~MInCoreTest() {} size_t residence(uintptr_t addr, size_t size) { return MInCore::residence_impl(reinterpret_cast<void*>(addr), size, &mcm_); } void addPage(uintptr_t page) { mcm_.addPage(page); } // Expose the internal size of array that we use to call mincore() so // that we can be sure to need multiple calls to cover large memory regions. const size_t chunkSize() { return MInCore::kArrayLength; } private: MInCoreMock mcm_; }; namespace { using ::testing::Eq; TEST(MInCoreTest, TestResidence) { MInCoreTest mct; const size_t kPageSize = getpagesize(); // Set up a pattern with a few resident pages. // page 0 not mapped mct.addPage(kPageSize); // page 2 not mapped mct.addPage(3 * kPageSize); mct.addPage(4 * kPageSize); // An object of size zero should have a residence of zero. EXPECT_THAT(mct.residence(320, 0), Eq(0)); // Check that an object entirely on the first page is // reported as entirely unmapped. EXPECT_THAT(mct.residence(320, 55), Eq(0)); // Check that an object entirely on the second page is // reported as entirely mapped. EXPECT_THAT(mct.residence(kPageSize + 320, 55), Eq(55)); // An object of size zero should have a residence of zero. EXPECT_THAT(mct.residence(kPageSize + 320, 0), Eq(0)); // Check that an object over a mapped and unmapped page is half mapped. EXPECT_THAT(mct.residence(kPageSize / 2, kPageSize), Eq(kPageSize / 2)); // Check that an object which spans two pages is reported as being mapped // only on the page that's resident. EXPECT_THAT(mct.residence(kPageSize / 2 * 3, kPageSize), Eq(kPageSize / 2)); // Check that an object that is on two mapped pages is reported as entirely // resident. EXPECT_THAT(mct.residence(kPageSize / 2 * 7, kPageSize), Eq(kPageSize)); // Check that an object that is on one mapped page is reported as only // resident on the mapped page. EXPECT_THAT(mct.residence(kPageSize * 2, kPageSize + 1), Eq(1)); // Check that an object that is on one mapped page is reported as only // resident on the mapped page. EXPECT_THAT(mct.residence(kPageSize + 1, kPageSize + 1), Eq(kPageSize - 1)); // Check that an object which spans beyond the mapped pages is reported // as unmapped EXPECT_THAT(mct.residence(kPageSize * 6, kPageSize), Eq(0)); // Check an object that spans three pages, two of them mapped. EXPECT_THAT(mct.residence(kPageSize / 2 * 7 + 1, kPageSize * 2), Eq(kPageSize * 3 / 2 - 1)); } // Test whether we are correctly handling multiple calls to mincore. TEST(MInCoreTest, TestLargeResidence) { MInCoreTest mct; uintptr_t uAddress = 0; const size_t kPageSize = getpagesize(); // Set up a pattern covering 6 * page size * MInCore::kArrayLength to // allow us to test for situations where the region we're checking // requires multiple calls to mincore(). // Use a mapped/unmapped/unmapped pattern, this will mean that // the regions examined by mincore() do not have regular alignment // with the pattern. for (int i = 0; i < 2 * mct.chunkSize(); i++) { mct.addPage(uAddress); uAddress += 3 * kPageSize; } uintptr_t baseAddress = 0; for (int size = kPageSize; size < 32 * 1024 * 1024; size += 2 * kPageSize) { uintptr_t unit = kPageSize * 3; EXPECT_THAT(mct.residence(baseAddress, size), Eq(kPageSize * ((size + unit - 1) / unit))); } } TEST(MInCoreTest, UnmappedMemory) { const size_t kPageSize = getpagesize(); const int kNumPages = 16; // Overallocate kNumPages of memory, so we can munmap the page before and // after it. void* p = mmap(nullptr, (kNumPages + 2) * kPageSize, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); ASSERT_NE(p, MAP_FAILED) << errno; ASSERT_EQ(munmap(p, kPageSize), 0); void* q = reinterpret_cast<char*>(p) + kPageSize; void* last = reinterpret_cast<char*>(p) + (kNumPages + 1) * kPageSize; ASSERT_EQ(munmap(last, kPageSize), 0); memset(q, 0, kNumPages * kPageSize); ::benchmark::DoNotOptimize(q); EXPECT_EQ(0, MInCore::residence(nullptr, kPageSize)); EXPECT_EQ(0, MInCore::residence(p, kPageSize)); for (int i = 0; i <= kNumPages; i++) { EXPECT_EQ(i * kPageSize, MInCore::residence(q, i * kPageSize)); } ASSERT_EQ(munmap(q, kNumPages * kPageSize), 0); } } // namespace } // namespace tcmalloc_internal } // namespace tcmalloc <commit_msg>trivial: add edge case test to mincore_test<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/internal/mincore.h" #include <sys/mman.h> #include <unistd.h> #include <algorithm> #include <cstdint> #include <memory> #include <set> #include "benchmark/benchmark.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace tcmalloc { namespace tcmalloc_internal { using ::testing::Eq; // Mock interface to mincore() which has reports residence based on // an array provided at construction. class MInCoreMock : public MInCoreInterface { public: MInCoreMock() : mapped_() {} ~MInCoreMock() override {} // Implementation of minCore that reports presence based on provided array. int mincore(void* addr, size_t length, unsigned char* result) override { const size_t kPageSize = getpagesize(); uintptr_t uAddress = reinterpret_cast<uintptr_t>(addr); // Check that we only pass page aligned addresses into mincore(). EXPECT_THAT(uAddress & (kPageSize - 1), Eq(0)); uintptr_t uEndAddress = uAddress + length; int index = 0; // Check for presence of the target pages in the map. while (uAddress < uEndAddress) { result[index] = (mapped_.find(uAddress) != mapped_.end() ? 1 : 0); uAddress += kPageSize; index++; } return 0; } void addPage(uintptr_t uAddress) { mapped_.insert(uAddress); } private: std::set<uintptr_t> mapped_; }; // Friend class of MInCore which calls the mincore mock. class MInCoreTest { public: MInCoreTest() : mcm_() {} ~MInCoreTest() {} size_t residence(uintptr_t addr, size_t size) { return MInCore::residence_impl(reinterpret_cast<void*>(addr), size, &mcm_); } void addPage(uintptr_t page) { mcm_.addPage(page); } // Expose the internal size of array that we use to call mincore() so // that we can be sure to need multiple calls to cover large memory regions. const size_t chunkSize() { return MInCore::kArrayLength; } private: MInCoreMock mcm_; }; namespace { using ::testing::Eq; TEST(MInCoreTest, TestResidence) { MInCoreTest mct; const size_t kPageSize = getpagesize(); // Set up a pattern with a few resident pages. // page 0 not mapped mct.addPage(kPageSize); // page 2 not mapped mct.addPage(3 * kPageSize); mct.addPage(4 * kPageSize); // An object of size zero should have a residence of zero. EXPECT_THAT(mct.residence(320, 0), Eq(0)); // Check that an object entirely on the first page is // reported as entirely unmapped. EXPECT_THAT(mct.residence(320, 55), Eq(0)); // Check that an object entirely on the second page is // reported as entirely mapped. EXPECT_THAT(mct.residence(kPageSize + 320, 55), Eq(55)); // An object of size zero should have a residence of zero. EXPECT_THAT(mct.residence(kPageSize + 320, 0), Eq(0)); // Check that an object over a mapped and unmapped page is half mapped. EXPECT_THAT(mct.residence(kPageSize / 2, kPageSize), Eq(kPageSize / 2)); // Check that an object which spans two pages is reported as being mapped // only on the page that's resident. EXPECT_THAT(mct.residence(kPageSize / 2 * 3, kPageSize), Eq(kPageSize / 2)); // Check that an object that is on two mapped pages is reported as entirely // resident. EXPECT_THAT(mct.residence(kPageSize / 2 * 7, kPageSize), Eq(kPageSize)); // Check that an object that is on one mapped page is reported as only // resident on the mapped page. EXPECT_THAT(mct.residence(kPageSize * 2, kPageSize + 1), Eq(1)); // Check that an object that is on one mapped page is reported as only // resident on the mapped page. EXPECT_THAT(mct.residence(kPageSize + 1, kPageSize + 1), Eq(kPageSize - 1)); // Check that an object which spans beyond the mapped pages is reported // as unmapped EXPECT_THAT(mct.residence(kPageSize * 6, kPageSize), Eq(0)); // Check an object that spans three pages, two of them mapped. EXPECT_THAT(mct.residence(kPageSize / 2 * 7 + 1, kPageSize * 2), Eq(kPageSize * 3 / 2 - 1)); } // Test whether we are correctly handling multiple calls to mincore. TEST(MInCoreTest, TestLargeResidence) { MInCoreTest mct; uintptr_t uAddress = 0; const size_t kPageSize = getpagesize(); // Set up a pattern covering 6 * page size * MInCore::kArrayLength to // allow us to test for situations where the region we're checking // requires multiple calls to mincore(). // Use a mapped/unmapped/unmapped pattern, this will mean that // the regions examined by mincore() do not have regular alignment // with the pattern. for (int i = 0; i < 2 * mct.chunkSize(); i++) { mct.addPage(uAddress); uAddress += 3 * kPageSize; } uintptr_t baseAddress = 0; for (int size = kPageSize; size < 32 * 1024 * 1024; size += 2 * kPageSize) { uintptr_t unit = kPageSize * 3; EXPECT_THAT(mct.residence(baseAddress, size), Eq(kPageSize * ((size + unit - 1) / unit))); } } TEST(MInCoreTest, UnmappedMemory) { const size_t kPageSize = getpagesize(); const int kNumPages = 16; // Overallocate kNumPages of memory, so we can munmap the page before and // after it. void* p = mmap(nullptr, (kNumPages + 2) * kPageSize, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0); ASSERT_NE(p, MAP_FAILED) << errno; ASSERT_EQ(munmap(p, kPageSize), 0); void* q = reinterpret_cast<char*>(p) + kPageSize; void* last = reinterpret_cast<char*>(p) + (kNumPages + 1) * kPageSize; ASSERT_EQ(munmap(last, kPageSize), 0); memset(q, 0, kNumPages * kPageSize); ::benchmark::DoNotOptimize(q); EXPECT_EQ(0, MInCore::residence(nullptr, kPageSize)); EXPECT_EQ(0, MInCore::residence(p, kPageSize)); for (int i = 0; i <= kNumPages; i++) { EXPECT_EQ(i * kPageSize, MInCore::residence(q, i * kPageSize)); } // Note we can only query regions that are entirely mapped, but we should also // test the edge case of incomplete pages. EXPECT_EQ((kNumPages - 1) * kPageSize, MInCore::residence(reinterpret_cast<char*>(q) + 7, (kNumPages - 1) * kPageSize)); ASSERT_EQ(munmap(q, kNumPages * kPageSize), 0); } } // namespace } // namespace tcmalloc_internal } // namespace tcmalloc <|endoftext|>
<commit_before>// RUN: %clang_cc1 -fsyntax-only -verify -faccess-control -std=c++0x -Wsign-compare %s // C++ rules for ?: are a lot stricter than C rules, and have to take into // account more conversion options. // This test runs in C++0x mode for the contextual conversion of the condition. struct ToBool { explicit operator bool(); }; struct B; struct A { A(); A(const B&); }; // expected-note 2 {{candidate constructor}} struct B { operator A() const; }; // expected-note 2 {{candidate function}} struct I { operator int(); }; struct J { operator I(); }; struct K { operator double(); }; typedef void (*vfn)(); struct F { operator vfn(); }; struct G { operator vfn(); }; struct Base { int trick(); A trick() const; void fn1(); }; struct Derived : Base { void fn2(); }; struct Convertible { operator Base&(); }; struct Priv : private Base {}; // expected-note 4 {{'private' inheritance specifier here}} struct Mid : Base {}; struct Fin : Mid, Derived {}; typedef void (Derived::*DFnPtr)(); struct ToMemPtr { operator DFnPtr(); }; struct BadDerived; struct BadBase { operator BadDerived&(); }; struct BadDerived : BadBase {}; struct Fields { int i1, i2, b1 : 3, b2 : 3; }; struct MixedFields { int i; volatile int vi; const int ci; const volatile int cvi; }; struct MixedFieldsDerived : MixedFields { }; enum Enum { EVal }; struct Ambig { operator short(); // expected-note 2 {{candidate function}} operator signed char(); // expected-note 2 {{candidate function}} }; void test() { // This function tests C++0x 5.16 // p1 (contextually convert to bool) int i1 = ToBool() ? 0 : 1; // p2 (one or both void, and throwing) i1 ? throw 0 : throw 1; i1 ? test() : throw 1; i1 ? throw 0 : test(); i1 ? test() : test(); i1 = i1 ? throw 0 : 0; i1 = i1 ? 0 : throw 0; i1 ? 0 : test(); // expected-error {{right operand to ? is void, but left operand is of type 'int'}} i1 ? test() : 0; // expected-error {{left operand to ? is void, but right operand is of type 'int'}} (i1 ? throw 0 : i1) = 0; // expected-error {{expression is not assignable}} (i1 ? i1 : throw 0) = 0; // expected-error {{expression is not assignable}} // p3 (one or both class type, convert to each other) // b1 (lvalues) Base base; Derived derived; Convertible conv; Base &bar1 = i1 ? base : derived; Base &bar2 = i1 ? derived : base; Base &bar3 = i1 ? base : conv; Base &bar4 = i1 ? conv : base; // these are ambiguous BadBase bb; BadDerived bd; (void)(i1 ? bb : bd); // expected-error {{conditional expression is ambiguous; 'struct BadBase' can be converted to 'struct BadDerived' and vice versa}} (void)(i1 ? bd : bb); // expected-error {{conditional expression is ambiguous}} // curiously enough (and a defect?), these are not // for rvalues, hierarchy takes precedence over other conversions (void)(i1 ? BadBase() : BadDerived()); (void)(i1 ? BadDerived() : BadBase()); // b2.1 (hierarchy stuff) const Base constret(); const Derived constder(); // should use const overload A a1((i1 ? constret() : Base()).trick()); A a2((i1 ? Base() : constret()).trick()); A a3((i1 ? constret() : Derived()).trick()); A a4((i1 ? Derived() : constret()).trick()); // should use non-const overload i1 = (i1 ? Base() : Base()).trick(); i1 = (i1 ? Base() : Base()).trick(); i1 = (i1 ? Base() : Derived()).trick(); i1 = (i1 ? Derived() : Base()).trick(); // should fail: const lost (void)(i1 ? Base() : constder()); // expected-error {{incompatible operand types ('struct Base' and 'struct Derived const')}} (void)(i1 ? constder() : Base()); // expected-error {{incompatible operand types ('struct Derived const' and 'struct Base')}} Priv priv; Fin fin; (void)(i1 ? Base() : Priv()); // expected-error{{conversion from 'struct Priv' to inaccessible base class 'struct Base'}} (void)(i1 ? Priv() : Base()); // expected-error{{error: conversion from 'struct Priv' to inaccessible base class 'struct Base'}} (void)(i1 ? Base() : Fin()); // expected-error{{ambiguous conversion from derived class 'struct Fin' to base class 'struct Base'}} (void)(i1 ? Fin() : Base()); // expected-error{{ambiguous conversion from derived class 'struct Fin' to base class 'struct Base'}} (void)(i1 ? base : priv); // expected-error {{conversion from 'struct Priv' to inaccessible base class 'struct Base'}} (void)(i1 ? priv : base); // expected-error {{conversion from 'struct Priv' to inaccessible base class 'struct Base'}} (void)(i1 ? base : fin); // expected-error {{ambiguous conversion from derived class 'struct Fin' to base class 'struct Base'}} (void)(i1 ? fin : base); // expected-error {{ambiguous conversion from derived class 'struct Fin' to base class 'struct Base'}} // b2.2 (non-hierarchy) i1 = i1 ? I() : i1; i1 = i1 ? i1 : I(); I i2(i1 ? I() : J()); I i3(i1 ? J() : I()); // "the type [it] woud have if E2 were converted to an rvalue" vfn pfn = i1 ? F() : test; pfn = i1 ? test : F(); // these are ambiguous - better messages would be nice (void)(i1 ? A() : B()); // expected-error {{conversion from 'struct B' to 'struct A' is ambiguous}} (void)(i1 ? B() : A()); // expected-error {{conversion from 'struct B' to 'struct A' is ambiguous}} (void)(i1 ? 1 : Ambig()); // expected-error {{conversion from 'struct Ambig' to 'int' is ambiguous}} (void)(i1 ? Ambig() : 1); // expected-error {{conversion from 'struct Ambig' to 'int' is ambiguous}} // By the way, this isn't an lvalue: &(i1 ? i1 : i2); // expected-error {{address expression must be an lvalue or a function designator}} // p4 (lvalue, same type) Fields flds; int &ir1 = i1 ? flds.i1 : flds.i2; (i1 ? flds.b1 : flds.i2) = 0; (i1 ? flds.i1 : flds.b2) = 0; (i1 ? flds.b1 : flds.b2) = 0; // p5 (conversion to built-in types) // GCC 4.3 fails these double d1 = i1 ? I() : K(); pfn = i1 ? F() : G(); DFnPtr pfm; pfm = i1 ? DFnPtr() : &Base::fn1; pfm = i1 ? &Base::fn1 : DFnPtr(); // p6 (final conversions) i1 = i1 ? i1 : ir1; int *pi1 = i1 ? &i1 : 0; pi1 = i1 ? 0 : &i1; i1 = i1 ? i1 : EVal; // expected-warning {{operands of ? are integers of different signs}} ?? i1 = i1 ? EVal : i1; // expected-warning {{operands of ? are integers of different signs}} ?? d1 = i1 ? 'c' : 4.0; d1 = i1 ? 4.0 : 'c'; Base *pb = i1 ? (Base*)0 : (Derived*)0; pb = i1 ? (Derived*)0 : (Base*)0; pfm = i1 ? &Base::fn1 : &Derived::fn2; pfm = i1 ? &Derived::fn2 : &Base::fn1; pfm = i1 ? &Derived::fn2 : 0; pfm = i1 ? 0 : &Derived::fn2; const int (MixedFieldsDerived::*mp1) = i1 ? &MixedFields::ci : &MixedFieldsDerived::i; const volatile int (MixedFields::*mp2) = i1 ? &MixedFields::ci : &MixedFields::cvi; (void)(i1 ? &MixedFields::ci : &MixedFields::vi); // Conversion of primitives does not result in an lvalue. &(i1 ? i1 : d1); // expected-error {{address expression must be an lvalue or a function designator}} (void)&(i1 ? flds.b1 : flds.i1); // expected-error {{address of bit-field requested}} (void)&(i1 ? flds.i1 : flds.b1); // expected-error {{address of bit-field requested}} unsigned long test0 = 5; test0 = test0 ? (long) test0 : test0; // expected-warning {{operands of ? are integers of different signs}} test0 = test0 ? (int) test0 : test0; // expected-warning {{operands of ? are integers of different signs}} test0 = test0 ? (short) test0 : test0; // expected-warning {{operands of ? are integers of different signs}} test0 = test0 ? test0 : (long) test0; // expected-warning {{operands of ? are integers of different signs}} test0 = test0 ? test0 : (int) test0; // expected-warning {{operands of ? are integers of different signs}} test0 = test0 ? test0 : (short) test0; // expected-warning {{operands of ? are integers of different signs}} test0 = test0 ? test0 : (long) 10; test0 = test0 ? test0 : (int) 10; test0 = test0 ? test0 : (short) 10; test0 = test0 ? (long) 10 : test0; test0 = test0 ? (int) 10 : test0; test0 = test0 ? (short) 10 : test0; test0 = test0 ? EVal : test0; test0 = test0 ? EVal : (int) test0; // expected-warning {{operands of ? are integers of different signs}} // Note the thing that this does not test: since DR446, various situations // *must* create a separate temporary copy of class objects. This can only // be properly tested at runtime, though. } <commit_msg>Chris thinks these diagnostics are better now. :)<commit_after>// RUN: %clang_cc1 -fsyntax-only -verify -faccess-control -std=c++0x -Wsign-compare %s // C++ rules for ?: are a lot stricter than C rules, and have to take into // account more conversion options. // This test runs in C++0x mode for the contextual conversion of the condition. struct ToBool { explicit operator bool(); }; struct B; struct A { A(); A(const B&); }; // expected-note 2 {{candidate constructor}} struct B { operator A() const; }; // expected-note 2 {{candidate function}} struct I { operator int(); }; struct J { operator I(); }; struct K { operator double(); }; typedef void (*vfn)(); struct F { operator vfn(); }; struct G { operator vfn(); }; struct Base { int trick(); A trick() const; void fn1(); }; struct Derived : Base { void fn2(); }; struct Convertible { operator Base&(); }; struct Priv : private Base {}; // expected-note 4 {{'private' inheritance specifier here}} struct Mid : Base {}; struct Fin : Mid, Derived {}; typedef void (Derived::*DFnPtr)(); struct ToMemPtr { operator DFnPtr(); }; struct BadDerived; struct BadBase { operator BadDerived&(); }; struct BadDerived : BadBase {}; struct Fields { int i1, i2, b1 : 3, b2 : 3; }; struct MixedFields { int i; volatile int vi; const int ci; const volatile int cvi; }; struct MixedFieldsDerived : MixedFields { }; enum Enum { EVal }; struct Ambig { operator short(); // expected-note 2 {{candidate function}} operator signed char(); // expected-note 2 {{candidate function}} }; void test() { // This function tests C++0x 5.16 // p1 (contextually convert to bool) int i1 = ToBool() ? 0 : 1; // p2 (one or both void, and throwing) i1 ? throw 0 : throw 1; i1 ? test() : throw 1; i1 ? throw 0 : test(); i1 ? test() : test(); i1 = i1 ? throw 0 : 0; i1 = i1 ? 0 : throw 0; i1 ? 0 : test(); // expected-error {{right operand to ? is void, but left operand is of type 'int'}} i1 ? test() : 0; // expected-error {{left operand to ? is void, but right operand is of type 'int'}} (i1 ? throw 0 : i1) = 0; // expected-error {{expression is not assignable}} (i1 ? i1 : throw 0) = 0; // expected-error {{expression is not assignable}} // p3 (one or both class type, convert to each other) // b1 (lvalues) Base base; Derived derived; Convertible conv; Base &bar1 = i1 ? base : derived; Base &bar2 = i1 ? derived : base; Base &bar3 = i1 ? base : conv; Base &bar4 = i1 ? conv : base; // these are ambiguous BadBase bb; BadDerived bd; (void)(i1 ? bb : bd); // expected-error {{conditional expression is ambiguous; 'struct BadBase' can be converted to 'struct BadDerived' and vice versa}} (void)(i1 ? bd : bb); // expected-error {{conditional expression is ambiguous}} // curiously enough (and a defect?), these are not // for rvalues, hierarchy takes precedence over other conversions (void)(i1 ? BadBase() : BadDerived()); (void)(i1 ? BadDerived() : BadBase()); // b2.1 (hierarchy stuff) const Base constret(); const Derived constder(); // should use const overload A a1((i1 ? constret() : Base()).trick()); A a2((i1 ? Base() : constret()).trick()); A a3((i1 ? constret() : Derived()).trick()); A a4((i1 ? Derived() : constret()).trick()); // should use non-const overload i1 = (i1 ? Base() : Base()).trick(); i1 = (i1 ? Base() : Base()).trick(); i1 = (i1 ? Base() : Derived()).trick(); i1 = (i1 ? Derived() : Base()).trick(); // should fail: const lost (void)(i1 ? Base() : constder()); // expected-error {{incompatible operand types ('struct Base' and 'struct Derived const')}} (void)(i1 ? constder() : Base()); // expected-error {{incompatible operand types ('struct Derived const' and 'struct Base')}} Priv priv; Fin fin; (void)(i1 ? Base() : Priv()); // expected-error{{conversion from 'struct Priv' to inaccessible base class 'struct Base'}} (void)(i1 ? Priv() : Base()); // expected-error{{error: conversion from 'struct Priv' to inaccessible base class 'struct Base'}} (void)(i1 ? Base() : Fin()); // expected-error{{ambiguous conversion from derived class 'struct Fin' to base class 'struct Base'}} (void)(i1 ? Fin() : Base()); // expected-error{{ambiguous conversion from derived class 'struct Fin' to base class 'struct Base'}} (void)(i1 ? base : priv); // expected-error {{conversion from 'struct Priv' to inaccessible base class 'struct Base'}} (void)(i1 ? priv : base); // expected-error {{conversion from 'struct Priv' to inaccessible base class 'struct Base'}} (void)(i1 ? base : fin); // expected-error {{ambiguous conversion from derived class 'struct Fin' to base class 'struct Base'}} (void)(i1 ? fin : base); // expected-error {{ambiguous conversion from derived class 'struct Fin' to base class 'struct Base'}} // b2.2 (non-hierarchy) i1 = i1 ? I() : i1; i1 = i1 ? i1 : I(); I i2(i1 ? I() : J()); I i3(i1 ? J() : I()); // "the type [it] woud have if E2 were converted to an rvalue" vfn pfn = i1 ? F() : test; pfn = i1 ? test : F(); (void)(i1 ? A() : B()); // expected-error {{conversion from 'struct B' to 'struct A' is ambiguous}} (void)(i1 ? B() : A()); // expected-error {{conversion from 'struct B' to 'struct A' is ambiguous}} (void)(i1 ? 1 : Ambig()); // expected-error {{conversion from 'struct Ambig' to 'int' is ambiguous}} (void)(i1 ? Ambig() : 1); // expected-error {{conversion from 'struct Ambig' to 'int' is ambiguous}} // By the way, this isn't an lvalue: &(i1 ? i1 : i2); // expected-error {{address expression must be an lvalue or a function designator}} // p4 (lvalue, same type) Fields flds; int &ir1 = i1 ? flds.i1 : flds.i2; (i1 ? flds.b1 : flds.i2) = 0; (i1 ? flds.i1 : flds.b2) = 0; (i1 ? flds.b1 : flds.b2) = 0; // p5 (conversion to built-in types) // GCC 4.3 fails these double d1 = i1 ? I() : K(); pfn = i1 ? F() : G(); DFnPtr pfm; pfm = i1 ? DFnPtr() : &Base::fn1; pfm = i1 ? &Base::fn1 : DFnPtr(); // p6 (final conversions) i1 = i1 ? i1 : ir1; int *pi1 = i1 ? &i1 : 0; pi1 = i1 ? 0 : &i1; i1 = i1 ? i1 : EVal; // expected-warning {{operands of ? are integers of different signs}} ?? i1 = i1 ? EVal : i1; // expected-warning {{operands of ? are integers of different signs}} ?? d1 = i1 ? 'c' : 4.0; d1 = i1 ? 4.0 : 'c'; Base *pb = i1 ? (Base*)0 : (Derived*)0; pb = i1 ? (Derived*)0 : (Base*)0; pfm = i1 ? &Base::fn1 : &Derived::fn2; pfm = i1 ? &Derived::fn2 : &Base::fn1; pfm = i1 ? &Derived::fn2 : 0; pfm = i1 ? 0 : &Derived::fn2; const int (MixedFieldsDerived::*mp1) = i1 ? &MixedFields::ci : &MixedFieldsDerived::i; const volatile int (MixedFields::*mp2) = i1 ? &MixedFields::ci : &MixedFields::cvi; (void)(i1 ? &MixedFields::ci : &MixedFields::vi); // Conversion of primitives does not result in an lvalue. &(i1 ? i1 : d1); // expected-error {{address expression must be an lvalue or a function designator}} (void)&(i1 ? flds.b1 : flds.i1); // expected-error {{address of bit-field requested}} (void)&(i1 ? flds.i1 : flds.b1); // expected-error {{address of bit-field requested}} unsigned long test0 = 5; test0 = test0 ? (long) test0 : test0; // expected-warning {{operands of ? are integers of different signs}} test0 = test0 ? (int) test0 : test0; // expected-warning {{operands of ? are integers of different signs}} test0 = test0 ? (short) test0 : test0; // expected-warning {{operands of ? are integers of different signs}} test0 = test0 ? test0 : (long) test0; // expected-warning {{operands of ? are integers of different signs}} test0 = test0 ? test0 : (int) test0; // expected-warning {{operands of ? are integers of different signs}} test0 = test0 ? test0 : (short) test0; // expected-warning {{operands of ? are integers of different signs}} test0 = test0 ? test0 : (long) 10; test0 = test0 ? test0 : (int) 10; test0 = test0 ? test0 : (short) 10; test0 = test0 ? (long) 10 : test0; test0 = test0 ? (int) 10 : test0; test0 = test0 ? (short) 10 : test0; test0 = test0 ? EVal : test0; test0 = test0 ? EVal : (int) test0; // expected-warning {{operands of ? are integers of different signs}} // Note the thing that this does not test: since DR446, various situations // *must* create a separate temporary copy of class objects. This can only // be properly tested at runtime, though. } <|endoftext|>
<commit_before>/* * Copyright (C) 2018 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <seastar/testing/test_case.hh> #include <seastar/testing/thread_test_case.hh> #include "test/boost/sstable_test.hh" #include "test/lib/exception_utils.hh" using namespace sstables; namespace { struct my_consumer { stop_iteration consume(static_row sr) { return stop_iteration::no; } stop_iteration consume(clustering_row cr) { return stop_iteration::no; } stop_iteration consume(range_tombstone rt) { return stop_iteration::no; } stop_iteration consume(tombstone tomb) { return stop_iteration::no; } void consume_end_of_stream() {} void consume_new_partition(const dht::decorated_key& dk) {} stop_iteration consume_end_of_partition() { return stop_iteration::no; } }; } static void broken_sst(sstring dir, unsigned long generation, schema_ptr s, sstring msg, sstable_version_types version = la) { try { sstables::test_env env; sstable_ptr sstp = env.reusable_sst(s, dir, generation, version).get0(); auto r = sstp->read_rows_flat(s, tests::make_permit()); r.consume(my_consumer{}, db::no_timeout).get(); BOOST_FAIL("expecting exception"); } catch (malformed_sstable_exception& e) { BOOST_REQUIRE_EQUAL(sstring(e.what()), msg); } } static void broken_sst(sstring dir, unsigned long generation, sstring msg) { // Using an empty schema for this function, which is only about loading // a malformed component and checking that it fails. auto s = make_shared_schema({}, "ks", "cf", {}, {}, {}, {}, utf8_type); return broken_sst(dir, generation, s, msg); } SEASTAR_THREAD_TEST_CASE(test_empty_index) { auto s = schema_builder("test_ks", "test_table") .with_column("pk", int32_type, column_kind::partition_key) .with_column("ck", int32_type, column_kind::clustering_key) .with_column("val", int32_type) .set_compressor_params(compression_parameters::no_compression()) .build(); sstables::test_env env; sstable_ptr sstp = env.reusable_sst(s, "test/resource/sstables/empty_index", 36, sstable_version_types::mc).get0(); sstp->load().get(); auto fut = sstables::test(sstp).read_indexes(); BOOST_REQUIRE_EXCEPTION(fut.get(), malformed_sstable_exception, exception_predicate::message_equals( "missing index entry in sstable test/resource/sstables/empty_index/mc-36-big-Index.db")); } SEASTAR_THREAD_TEST_CASE(missing_column_in_schema) { schema_ptr s = schema_builder("test_ks", "test_table") .with_column("key1", utf8_type, column_kind::partition_key) .with_column("key2", utf8_type, column_kind::clustering_key) .with_column("key3", utf8_type, column_kind::clustering_key) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/incompatible_serialized_type", 122, s, "Column val missing in current schema in sstable " "test/resource/sstables/incompatible_serialized_type/mc-122-big-Data.db", sstable::version_types::mc); } SEASTAR_THREAD_TEST_CASE(incompatible_serialized_type) { schema_ptr s = schema_builder("test_ks", "test_table") .with_column("key1", utf8_type, column_kind::partition_key) .with_column("key2", utf8_type, column_kind::clustering_key) .with_column("key3", utf8_type, column_kind::clustering_key) .with_column("val", int32_type, column_kind::regular_column) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/incompatible_serialized_type", 122, s, "val definition in serialization header does not match schema. Expected " "org.apache.cassandra.db.marshal.Int32Type but got " "org.apache.cassandra.db.marshal.UTF8Type in sstable " "test/resource/sstables/incompatible_serialized_type/mc-122-big-Data.db", sstable::version_types::mc); } SEASTAR_THREAD_TEST_CASE(invalid_boundary) { schema_ptr s = schema_builder("test_ks", "test_t") .with_column("p", int32_type, column_kind::partition_key) .with_column("a", int32_type, column_kind::clustering_key) .with_column("b", int32_type, column_kind::clustering_key) .with_column("c", int32_type, column_kind::clustering_key) .with_column("r", int32_type, column_kind::regular_column) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/invalid_boundary", 33, s, "Corrupted range tombstone: invalid boundary type static_clustering in sstable " "test/resource/sstables/invalid_boundary/mc-33-big-Data.db", sstable::version_types::mc); } SEASTAR_THREAD_TEST_CASE(mismatched_timestamp) { schema_ptr s = schema_builder("test_ks", "test_table") .with_column("key1", utf8_type, column_kind::partition_key) .with_column("key2", utf8_type, column_kind::clustering_key) .with_column("key3", utf8_type, column_kind::clustering_key) .with_column("val", utf8_type, column_kind::regular_column) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/mismatched_timestamp", 122, s, "Range tombstone with ck ckp{00056b65793262} and two different tombstones at ends: " "{tombstone: timestamp=1544745393692803, deletion_time=1544745393}, {tombstone: " "timestamp=1446576446577440, deletion_time=1442880998} in sstable " "test/resource/sstables/mismatched_timestamp/mc-122-big-Data.db", sstable::version_types::mc); } SEASTAR_THREAD_TEST_CASE(broken_open_tombstone) { schema_ptr s = schema_builder("test_ks", "test_table") .with_column("key1", utf8_type, column_kind::partition_key) .with_column("key2", utf8_type, column_kind::clustering_key) .with_column("key3", utf8_type, column_kind::clustering_key) .with_column("val", utf8_type, column_kind::regular_column) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/broken_open_tombstone", 122, s, "Range tombstones have to be disjoint: current opened range tombstone { clustering: " "ckp{00056b65793262}, kind: incl start, tombstone: {tombstone: timestamp=1544745393692803, " "deletion_time=1544745393} }, new tombstone {tombstone: timestamp=1544745393692803, " "deletion_time=1544745393} in sstable " "test/resource/sstables/broken_open_tombstone/mc-122-big-Data.db", sstable::version_types::mc); } SEASTAR_THREAD_TEST_CASE(broken_close_tombstone) { schema_ptr s = schema_builder("test_ks", "test_table") .with_column("key1", utf8_type, column_kind::partition_key) .with_column("key2", utf8_type, column_kind::clustering_key) .with_column("key3", utf8_type, column_kind::clustering_key) .with_column("val", utf8_type, column_kind::regular_column) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/broken_close_tombstone", 122, s, "Closing range tombstone that wasn't opened: clustering ckp{00056b65793262}, kind incl " "end, tombstone {tombstone: timestamp=1544745393692803, deletion_time=1544745393} in " "sstable test/resource/sstables/broken_close_tombstone/mc-122-big-Data.db", sstable::version_types::mc); } SEASTAR_THREAD_TEST_CASE(broken_start_composite) { schema_ptr s = schema_builder("test_ks", "test_table") .with_column("test_key", utf8_type, column_kind::partition_key) .with_column("test_val", utf8_type, column_kind::clustering_key) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/broken_start_composite", 76, s, "Unexpected start composite marker 2 in sstable test/resource/sstables/broken_start_composite/la-76-big-Data.db"); } SEASTAR_THREAD_TEST_CASE(broken_end_composite) { schema_ptr s = schema_builder("test_ks", "test_table") .with_column("test_key", utf8_type, column_kind::partition_key) .with_column("test_val", utf8_type, column_kind::clustering_key) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/broken_end_composite", 76, s, "Unexpected end composite marker 3 in sstable test/resource/sstables/broken_end_composite/la-76-big-Data.db"); } SEASTAR_THREAD_TEST_CASE(static_mismatch) { schema_ptr s = schema_builder("test_foo_bar_zed_baz_ks", "test_foo_bar_zed_baz_table") .with_column("test_foo_bar_zed_baz_key", utf8_type, column_kind::partition_key) .with_column("test_foo_bar_zed_baz_val", utf8_type, column_kind::clustering_key) .with_column("test_foo_bar_zed_baz_static", utf8_type, column_kind::regular_column) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/static_column", 58, s, "Mismatch between static cell and non-static column definition in sstable " "test/resource/sstables/static_column/la-58-big-Data.db"); } SEASTAR_THREAD_TEST_CASE(static_with_clustering) { schema_ptr s = schema_builder("test_foo_bar_zed_baz_ks", "test_foo_bar_zed_baz_table") .with_column("test_foo_bar_zed_baz_key", utf8_type, column_kind::partition_key) .with_column("test_foo_bar_zed_baz_val", utf8_type, column_kind::clustering_key) .with_column("test_foo_bar_zed_baz_static", utf8_type, column_kind::static_column) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/static_with_clustering", 58, s, "Static row has clustering key information. I didn't expect that! in sstable " "test/resource/sstables/static_with_clustering/la-58-big-Data.db"); } SEASTAR_THREAD_TEST_CASE(zero_sized_histogram) { broken_sst("test/resource/sstables/zero_sized_histogram", 5, "Estimated histogram with zero size found. Can't continue! in sstable " "test/resource/sstables/zero_sized_histogram/la-5-big-Statistics.db"); } SEASTAR_THREAD_TEST_CASE(bad_column_name) { broken_sst("test/resource/sstables/bad_column_name", 58, "Found 3 clustering elements in column name. Was not expecting that! in sstable " "test/resource/sstables/bad_column_name/la-58-big-Data.db"); } SEASTAR_THREAD_TEST_CASE(empty_toc) { broken_sst("test/resource/sstables/badtoc", 1, "Empty TOC in sstable test/resource/sstables/badtoc/la-1-big-TOC.txt"); } SEASTAR_THREAD_TEST_CASE(alien_toc) { broken_sst("test/resource/sstables/badtoc", 2, "test/resource/sstables/badtoc/la-2-big-Statistics.db: file not found"); } SEASTAR_THREAD_TEST_CASE(truncated_toc) { broken_sst("test/resource/sstables/badtoc", 3, "test/resource/sstables/badtoc/la-3-big-Statistics.db: file not found"); } SEASTAR_THREAD_TEST_CASE(wrong_format_toc) { broken_sst("test/resource/sstables/badtoc", 4, "test/resource/sstables/badtoc/la-4-big-TOC.txt: file not found"); } SEASTAR_THREAD_TEST_CASE(compression_truncated) { broken_sst("test/resource/sstables/badcompression", 1, "test/resource/sstables/badcompression/la-1-big-Statistics.db: file not found"); } SEASTAR_THREAD_TEST_CASE(compression_bytes_flipped) { broken_sst("test/resource/sstables/badcompression", 2, "test/resource/sstables/badcompression/la-2-big-Statistics.db: file not found"); } <commit_msg>test: broken_sstable_test: prepare for asynchronously closed sstables_manager<commit_after>/* * Copyright (C) 2018 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <seastar/testing/test_case.hh> #include <seastar/testing/thread_test_case.hh> #include "test/boost/sstable_test.hh" #include "test/lib/exception_utils.hh" using namespace sstables; namespace { struct my_consumer { stop_iteration consume(static_row sr) { return stop_iteration::no; } stop_iteration consume(clustering_row cr) { return stop_iteration::no; } stop_iteration consume(range_tombstone rt) { return stop_iteration::no; } stop_iteration consume(tombstone tomb) { return stop_iteration::no; } void consume_end_of_stream() {} void consume_new_partition(const dht::decorated_key& dk) {} stop_iteration consume_end_of_partition() { return stop_iteration::no; } }; } static void broken_sst(sstring dir, unsigned long generation, schema_ptr s, sstring msg, sstable_version_types version = la) { sstables::test_env::do_with_async([&] (sstables::test_env& env) { try { sstable_ptr sstp = env.reusable_sst(s, dir, generation, version).get0(); auto r = sstp->read_rows_flat(s, tests::make_permit()); r.consume(my_consumer{}, db::no_timeout).get(); BOOST_FAIL("expecting exception"); } catch (malformed_sstable_exception& e) { BOOST_REQUIRE_EQUAL(sstring(e.what()), msg); } }).get(); } static void broken_sst(sstring dir, unsigned long generation, sstring msg) { // Using an empty schema for this function, which is only about loading // a malformed component and checking that it fails. auto s = make_shared_schema({}, "ks", "cf", {}, {}, {}, {}, utf8_type); return broken_sst(dir, generation, s, msg); } SEASTAR_THREAD_TEST_CASE(test_empty_index) { sstables::test_env::do_with_async([&] (sstables::test_env& env) { auto s = schema_builder("test_ks", "test_table") .with_column("pk", int32_type, column_kind::partition_key) .with_column("ck", int32_type, column_kind::clustering_key) .with_column("val", int32_type) .set_compressor_params(compression_parameters::no_compression()) .build(); sstable_ptr sstp = env.reusable_sst(s, "test/resource/sstables/empty_index", 36, sstable_version_types::mc).get0(); sstp->load().get(); auto fut = sstables::test(sstp).read_indexes(); BOOST_REQUIRE_EXCEPTION(fut.get(), malformed_sstable_exception, exception_predicate::message_equals( "missing index entry in sstable test/resource/sstables/empty_index/mc-36-big-Index.db")); }).get(); } SEASTAR_THREAD_TEST_CASE(missing_column_in_schema) { schema_ptr s = schema_builder("test_ks", "test_table") .with_column("key1", utf8_type, column_kind::partition_key) .with_column("key2", utf8_type, column_kind::clustering_key) .with_column("key3", utf8_type, column_kind::clustering_key) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/incompatible_serialized_type", 122, s, "Column val missing in current schema in sstable " "test/resource/sstables/incompatible_serialized_type/mc-122-big-Data.db", sstable::version_types::mc); } SEASTAR_THREAD_TEST_CASE(incompatible_serialized_type) { schema_ptr s = schema_builder("test_ks", "test_table") .with_column("key1", utf8_type, column_kind::partition_key) .with_column("key2", utf8_type, column_kind::clustering_key) .with_column("key3", utf8_type, column_kind::clustering_key) .with_column("val", int32_type, column_kind::regular_column) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/incompatible_serialized_type", 122, s, "val definition in serialization header does not match schema. Expected " "org.apache.cassandra.db.marshal.Int32Type but got " "org.apache.cassandra.db.marshal.UTF8Type in sstable " "test/resource/sstables/incompatible_serialized_type/mc-122-big-Data.db", sstable::version_types::mc); } SEASTAR_THREAD_TEST_CASE(invalid_boundary) { schema_ptr s = schema_builder("test_ks", "test_t") .with_column("p", int32_type, column_kind::partition_key) .with_column("a", int32_type, column_kind::clustering_key) .with_column("b", int32_type, column_kind::clustering_key) .with_column("c", int32_type, column_kind::clustering_key) .with_column("r", int32_type, column_kind::regular_column) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/invalid_boundary", 33, s, "Corrupted range tombstone: invalid boundary type static_clustering in sstable " "test/resource/sstables/invalid_boundary/mc-33-big-Data.db", sstable::version_types::mc); } SEASTAR_THREAD_TEST_CASE(mismatched_timestamp) { schema_ptr s = schema_builder("test_ks", "test_table") .with_column("key1", utf8_type, column_kind::partition_key) .with_column("key2", utf8_type, column_kind::clustering_key) .with_column("key3", utf8_type, column_kind::clustering_key) .with_column("val", utf8_type, column_kind::regular_column) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/mismatched_timestamp", 122, s, "Range tombstone with ck ckp{00056b65793262} and two different tombstones at ends: " "{tombstone: timestamp=1544745393692803, deletion_time=1544745393}, {tombstone: " "timestamp=1446576446577440, deletion_time=1442880998} in sstable " "test/resource/sstables/mismatched_timestamp/mc-122-big-Data.db", sstable::version_types::mc); } SEASTAR_THREAD_TEST_CASE(broken_open_tombstone) { schema_ptr s = schema_builder("test_ks", "test_table") .with_column("key1", utf8_type, column_kind::partition_key) .with_column("key2", utf8_type, column_kind::clustering_key) .with_column("key3", utf8_type, column_kind::clustering_key) .with_column("val", utf8_type, column_kind::regular_column) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/broken_open_tombstone", 122, s, "Range tombstones have to be disjoint: current opened range tombstone { clustering: " "ckp{00056b65793262}, kind: incl start, tombstone: {tombstone: timestamp=1544745393692803, " "deletion_time=1544745393} }, new tombstone {tombstone: timestamp=1544745393692803, " "deletion_time=1544745393} in sstable " "test/resource/sstables/broken_open_tombstone/mc-122-big-Data.db", sstable::version_types::mc); } SEASTAR_THREAD_TEST_CASE(broken_close_tombstone) { schema_ptr s = schema_builder("test_ks", "test_table") .with_column("key1", utf8_type, column_kind::partition_key) .with_column("key2", utf8_type, column_kind::clustering_key) .with_column("key3", utf8_type, column_kind::clustering_key) .with_column("val", utf8_type, column_kind::regular_column) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/broken_close_tombstone", 122, s, "Closing range tombstone that wasn't opened: clustering ckp{00056b65793262}, kind incl " "end, tombstone {tombstone: timestamp=1544745393692803, deletion_time=1544745393} in " "sstable test/resource/sstables/broken_close_tombstone/mc-122-big-Data.db", sstable::version_types::mc); } SEASTAR_THREAD_TEST_CASE(broken_start_composite) { schema_ptr s = schema_builder("test_ks", "test_table") .with_column("test_key", utf8_type, column_kind::partition_key) .with_column("test_val", utf8_type, column_kind::clustering_key) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/broken_start_composite", 76, s, "Unexpected start composite marker 2 in sstable test/resource/sstables/broken_start_composite/la-76-big-Data.db"); } SEASTAR_THREAD_TEST_CASE(broken_end_composite) { schema_ptr s = schema_builder("test_ks", "test_table") .with_column("test_key", utf8_type, column_kind::partition_key) .with_column("test_val", utf8_type, column_kind::clustering_key) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/broken_end_composite", 76, s, "Unexpected end composite marker 3 in sstable test/resource/sstables/broken_end_composite/la-76-big-Data.db"); } SEASTAR_THREAD_TEST_CASE(static_mismatch) { schema_ptr s = schema_builder("test_foo_bar_zed_baz_ks", "test_foo_bar_zed_baz_table") .with_column("test_foo_bar_zed_baz_key", utf8_type, column_kind::partition_key) .with_column("test_foo_bar_zed_baz_val", utf8_type, column_kind::clustering_key) .with_column("test_foo_bar_zed_baz_static", utf8_type, column_kind::regular_column) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/static_column", 58, s, "Mismatch between static cell and non-static column definition in sstable " "test/resource/sstables/static_column/la-58-big-Data.db"); } SEASTAR_THREAD_TEST_CASE(static_with_clustering) { schema_ptr s = schema_builder("test_foo_bar_zed_baz_ks", "test_foo_bar_zed_baz_table") .with_column("test_foo_bar_zed_baz_key", utf8_type, column_kind::partition_key) .with_column("test_foo_bar_zed_baz_val", utf8_type, column_kind::clustering_key) .with_column("test_foo_bar_zed_baz_static", utf8_type, column_kind::static_column) .build(schema_builder::compact_storage::no); broken_sst("test/resource/sstables/static_with_clustering", 58, s, "Static row has clustering key information. I didn't expect that! in sstable " "test/resource/sstables/static_with_clustering/la-58-big-Data.db"); } SEASTAR_THREAD_TEST_CASE(zero_sized_histogram) { broken_sst("test/resource/sstables/zero_sized_histogram", 5, "Estimated histogram with zero size found. Can't continue! in sstable " "test/resource/sstables/zero_sized_histogram/la-5-big-Statistics.db"); } SEASTAR_THREAD_TEST_CASE(bad_column_name) { broken_sst("test/resource/sstables/bad_column_name", 58, "Found 3 clustering elements in column name. Was not expecting that! in sstable " "test/resource/sstables/bad_column_name/la-58-big-Data.db"); } SEASTAR_THREAD_TEST_CASE(empty_toc) { broken_sst("test/resource/sstables/badtoc", 1, "Empty TOC in sstable test/resource/sstables/badtoc/la-1-big-TOC.txt"); } SEASTAR_THREAD_TEST_CASE(alien_toc) { broken_sst("test/resource/sstables/badtoc", 2, "test/resource/sstables/badtoc/la-2-big-Statistics.db: file not found"); } SEASTAR_THREAD_TEST_CASE(truncated_toc) { broken_sst("test/resource/sstables/badtoc", 3, "test/resource/sstables/badtoc/la-3-big-Statistics.db: file not found"); } SEASTAR_THREAD_TEST_CASE(wrong_format_toc) { broken_sst("test/resource/sstables/badtoc", 4, "test/resource/sstables/badtoc/la-4-big-TOC.txt: file not found"); } SEASTAR_THREAD_TEST_CASE(compression_truncated) { broken_sst("test/resource/sstables/badcompression", 1, "test/resource/sstables/badcompression/la-1-big-Statistics.db: file not found"); } SEASTAR_THREAD_TEST_CASE(compression_bytes_flipped) { broken_sst("test/resource/sstables/badcompression", 2, "test/resource/sstables/badcompression/la-2-big-Statistics.db: file not found"); } <|endoftext|>
<commit_before>#include <stdio.h> #include "Halide.h" #include <algorithm> #include <iostream> using namespace Halide; using namespace Halide::Internal; void print_term(const Term &t) { if (!t.var) { if (t.coeff.defined()) { std::cout << t.coeff; } else { std::cout << 0; } } else { std::cout << t.coeff << " * " << t.var->name; } } void print_terms(const std::vector<Term> &terms) { std::cout << "{"; for (int i = 0; i < terms.size(); ++i) { print_term(terms[i]); if (i < terms.size()-1) std::cout << ", "; } std::cout << "}"; } int find_term(const Variable *v, const std::vector<Term> &terms) { for (int i = 0; i < terms.size(); ++i) { if ((!v && !terms[i].var) || (v && terms[i].var && terms[i].var->name == v->name)) { return i; } } return -1; } bool check_terms(const std::vector<Term> &expected_terms, const std::vector<Term> &actual_terms) { if (expected_terms.size() != actual_terms.size()) { std::cout << "Actual " << actual_terms.size() << " linear terms. " << "Expected " << expected_terms.size() << "\n"; return false; } std::vector<bool> found_term(expected_terms.size(), false); for (int i = 0; i < actual_terms.size(); ++i) { const Term &t = actual_terms[i]; int idx = find_term(t.var, expected_terms); if (idx == -1) { std::cout << "Could not find actual term "; print_term(t); std::cout << " among expected terms:\n"; print_terms(expected_terms); std::cout << "\n"; return false; } else { found_term[idx] = true; } } for (int i = 0; i < found_term.size(); ++i) { if (!found_term[i]) { std::cout << "Could not find expected term "; print_term(expected_terms[i]); std::cout << " among actual terms:\n"; print_terms(actual_terms); std::cout << "\n"; return false; } } return true; } bool test_collect_linear_terms() { Var x("x"), y("y"), z("z"); Expr x_var = Variable::make(Float(32), "x"); Expr y_var = Variable::make(Float(32), "y"); Expr z_var = Variable::make(Float(32), "z"); Scope<int> free_vars; free_vars.push("x", 0); free_vars.push("y", 0); free_vars.push("z", 0); /* Simplify an expression by collecting linear terms: * * 3(x - y + (z - 1)/15) + (x/2) - (y + 3*z)/6 * * Should simplify to: * * (3 + 1/2)x + (-3 - 1/6)y + (3/15 - 3/6)z + (-3/15) * = 3.5*x - 3.16667*y - 0.3*z - 0.2 */ Expr e1 = 3.f*(x - y + (z - 1.f) / 15.f) + (x / 2.f) - (y + 3.f*z) / 6.f; Term t1_0 = {-0.2f, NULL}; Term t1_x = {3.5f, x_var.as<Variable>()}; Term t1_y = {-3.f - 1.f/6.f, y_var.as<Variable>()}; Term t1_z = {-0.3f, z_var.as<Variable>()}; std::vector<Term> e1_terms(4); e1_terms[0] = t1_0; e1_terms[1] = t1_x; e1_terms[2] = t1_y; e1_terms[3] = t1_z; std::vector<Term> terms; collect_linear_terms(e1, terms, free_vars); if (!check_terms(e1_terms, terms)) { return false; } /* Simplify an expression by collecting linear terms: * * 10z - (2x + y)/3 + 10y * * Should simplify to: * * 10z - (2/3)x + (10 - 1/3)y * = 10*z - 0.666667x + 9.666667*y */ Expr e2 = 10.f*z - (2.f*x + y)/3.f + 10.f*y; Term t2_0 = {Expr(), NULL}; Term t2_x = {2.f / 3.f, x_var.as<Variable>()}; Term t2_y = {10.f - 1.f/3.f, y_var.as<Variable>()}; Term t2_z = {10.f, z_var.as<Variable>()}; std::vector<Term> e2_terms(4); e2_terms[0] = t2_0; e2_terms[1] = t2_x; e2_terms[2] = t2_y; e2_terms[3] = t2_z; terms.clear(); collect_linear_terms(e2, terms, free_vars); if (!check_terms(e2_terms, terms)) { return false; } return true; } bool test_linear_solve() { Var x("x"), y("y"), z("z"); Scope<int> free_vars; free_vars.push("x", 0); free_vars.push("y", 0); free_vars.push("z", 0); /* Solve an equation for a specific variable: * * 3(x - y + (z - 1)/15) + (x/2) - (y + 3*z)/6 * = 10z - (2x + y)/3 + 10y * * Should simplify to: * * x = [(13 - 1/6)y + (10.3)z - (3/15)] / (3 + 1/2 + 2/3) */ Expr e1 = 3.f*(x - y + (z - 1.f) / 15.f) + (x / 2.f) - (y + 3.f*z) / 6.f; Expr e2 = 10.f*z - (2.f*x + y)/3.f + 10.f*y; Expr eq = (e1 == e2); Expr expected = ((13.f - 1.f/6.f)*y + 10.3f*z - 0.2f) / (3.5f + 2.f/3.f); Expr ans = solve_for_linear_variable(eq, x, free_vars); Expr actual = ans.as<EQ>()->b; std::vector<Term> expected_terms; std::vector<Term> actual_terms; collect_linear_terms(expected, expected_terms, free_vars); collect_linear_terms(actual, actual_terms, free_vars); if (!check_terms(expected_terms, actual_terms)) { std::cout << "Solving linear expression failed!\n" << "Expected solution: " << expected << "\n" << "Actual solution: " << ans << "\n"; return false; } return true; } int main() { if (!test_collect_linear_terms()) { std::cout << "Failure.\n"; return -1; } if (!test_linear_solve()) { std::cout << "Failure.\n"; return -1; } std::cout << "Success!\n"; return 0; } <commit_msg>Add test case involving a let to linear solve test<commit_after>#include <stdio.h> #include "Halide.h" #include <algorithm> #include <iostream> using namespace Halide; using namespace Halide::Internal; void print_term(const Term &t) { if (!t.var) { if (t.coeff.defined()) { std::cout << t.coeff; } else { std::cout << 0; } } else { std::cout << t.coeff << " * " << t.var->name; } } void print_terms(const std::vector<Term> &terms) { std::cout << "{"; for (int i = 0; i < terms.size(); ++i) { print_term(terms[i]); if (i < terms.size()-1) std::cout << ", "; } std::cout << "}"; } int find_term(const Variable *v, const std::vector<Term> &terms) { for (int i = 0; i < terms.size(); ++i) { if ((!v && !terms[i].var) || (v && terms[i].var && terms[i].var->name == v->name)) { return i; } } return -1; } bool check_terms(const std::vector<Term> &expected_terms, const std::vector<Term> &actual_terms) { if (expected_terms.size() != actual_terms.size()) { std::cout << "Actual " << actual_terms.size() << " linear terms. " << "Expected " << expected_terms.size() << "\n"; return false; } std::vector<bool> found_term(expected_terms.size(), false); for (int i = 0; i < actual_terms.size(); ++i) { const Term &t = actual_terms[i]; int idx = find_term(t.var, expected_terms); if (idx == -1) { std::cout << "Could not find actual term "; print_term(t); std::cout << " among expected terms:\n"; print_terms(expected_terms); std::cout << "\n"; return false; } else { found_term[idx] = true; } } for (int i = 0; i < found_term.size(); ++i) { if (!found_term[i]) { std::cout << "Could not find expected term "; print_term(expected_terms[i]); std::cout << " among actual terms:\n"; print_terms(actual_terms); std::cout << "\n"; return false; } } return true; } bool test_collect_linear_terms() { Var x("x"), y("y"), z("z"); Expr x_var = Variable::make(Float(32), "x"); Expr y_var = Variable::make(Float(32), "y"); Expr z_var = Variable::make(Float(32), "z"); Scope<int> free_vars; free_vars.push("x", 0); free_vars.push("y", 0); free_vars.push("z", 0); /* Simplify an expression by collecting linear terms: * * 3(x - y + (z - 1)/15) + (x/2) - (y + 3*z)/6 * * Should simplify to: * * (3 + 1/2)x + (-3 - 1/6)y + (3/15 - 3/6)z + (-3/15) * = 3.5*x - 3.16667*y - 0.3*z - 0.2 */ Expr e1 = 3.f*(x - y + (z - 1.f) / 15.f) + (x / 2.f) - (y + 3.f*z) / 6.f; Term t1_0 = {-0.2f, NULL}; Term t1_x = {3.5f, x_var.as<Variable>()}; Term t1_y = {-3.f - 1.f/6.f, y_var.as<Variable>()}; Term t1_z = {-0.3f, z_var.as<Variable>()}; std::vector<Term> e1_terms(4); e1_terms[0] = t1_0; e1_terms[1] = t1_x; e1_terms[2] = t1_y; e1_terms[3] = t1_z; std::vector<Term> terms; collect_linear_terms(e1, terms, free_vars); if (!check_terms(e1_terms, terms)) { return false; } /* Simplify an expression by collecting linear terms: * * 10z - (2x + y)/3 + 10y * * Should simplify to: * * 10z - (2/3)x + (10 - 1/3)y * = 10*z - 0.666667x + 9.666667*y */ Expr e2 = 10.f*z - (2.f*x + y)/3.f + 10.f*y; Term t2_0 = {Expr(), NULL}; Term t2_x = {2.f / 3.f, x_var.as<Variable>()}; Term t2_y = {10.f - 1.f/3.f, y_var.as<Variable>()}; Term t2_z = {10.f, z_var.as<Variable>()}; std::vector<Term> e2_terms(4); e2_terms[0] = t2_0; e2_terms[1] = t2_x; e2_terms[2] = t2_y; e2_terms[3] = t2_z; terms.clear(); collect_linear_terms(e2, terms, free_vars); if (!check_terms(e2_terms, terms)) { return false; } return true; } bool test_linear_solve() { Var x("x"), y("y"), z("z"); Scope<int> free_vars; free_vars.push("x", 0); free_vars.push("y", 0); free_vars.push("z", 0); /* Solve an equation for a specific variable: * * 3(x - y + (z - 1)/15) + (x/2) - (y + 3*z)/6 * = 10z - (2x + y)/3 + 10y * * Should simplify to: * * x = [(13 - 1/6)y + (10.3)z - (3/15)] / (3 + 1/2 + 2/3) */ Expr e1 = 3.f*(x - y + (z - 1.f) / 15.f) + (x / 2.f) - (y + 3.f*z) / 6.f; Expr e2 = 10.f*z - (2.f*x + y)/3.f + 10.f*y; Expr eq = (e1 == e2); Expr expected = ((13.f - 1.f/6.f)*y + 10.3f*z - 0.2f) / (3.5f + 2.f/3.f); Expr ans = solve_for_linear_variable(eq, x, free_vars); Expr actual = ans.as<EQ>()->b; std::vector<Term> expected_terms; std::vector<Term> actual_terms; collect_linear_terms(expected, expected_terms, free_vars); collect_linear_terms(actual, actual_terms, free_vars); if (!check_terms(expected_terms, actual_terms)) { std::cout << "Solving linear expression failed!\n" << "Expected solution: " << expected << "\n" << "Actual solution: " << ans << "\n"; return false; } { Param<int> q; Scope<Expr> scope; Scope<int> free_vars; scope.push("z", 2*x-2*q); scope.push("y", z+7); free_vars.push("x", 0); debug(0) << solve_for_linear_variable(y > 3, x, free_vars, scope) << "\n"; } return true; } int main() { if (!test_collect_linear_terms()) { std::cout << "Failure.\n"; return -1; } if (!test_linear_solve()) { std::cout << "Failure.\n"; return -1; } std::cout << "Success!\n"; return 0; } <|endoftext|>
<commit_before>/************************************************************************** Copyright (c) 2017 sewenew 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 <unistd.h> #include <chrono> #include <tuple> #include <iostream> #include <sw/redis++/redis++.h> #include "sanity_test.h" #include "connection_cmds_test.h" #include "keys_cmds_test.h" #include "string_cmds_test.h" #include "list_cmds_test.h" #include "hash_cmds_test.h" #include "set_cmds_test.h" #include "zset_cmds_test.h" #include "hyperloglog_cmds_test.h" #include "geo_cmds_test.h" #include "script_cmds_test.h" #include "pubsub_test.h" #include "pipeline_transaction_test.h" #include "threads_test.h" #include "stream_cmds_test.h" #include "benchmark_test.h" namespace { void print_help(); auto parse_options(int argc, char **argv) -> std::tuple<sw::redis::Optional<sw::redis::ConnectionOptions>, sw::redis::Optional<sw::redis::ConnectionOptions>, sw::redis::Optional<sw::redis::test::BenchmarkOptions>>; template <typename RedisInstance> void run_test(const sw::redis::ConnectionOptions &opts); template <typename RedisInstance> void run_benchmark(const sw::redis::ConnectionOptions &opts, const sw::redis::test::BenchmarkOptions &benchmark_opts); } int main(int argc, char **argv) { try { sw::redis::Optional<sw::redis::ConnectionOptions> opts; sw::redis::Optional<sw::redis::ConnectionOptions> cluster_node_opts; sw::redis::Optional<sw::redis::test::BenchmarkOptions> benchmark_opts; std::tie(opts, cluster_node_opts, benchmark_opts) = parse_options(argc, argv); if (opts) { std::cout << "Testing Redis..." << std::endl; if (benchmark_opts) { run_benchmark<sw::redis::Redis>(*opts, *benchmark_opts); } else { run_test<sw::redis::Redis>(*opts); } } if (cluster_node_opts) { std::cout << "Testing RedisCluster..." << std::endl; if (benchmark_opts) { run_benchmark<sw::redis::RedisCluster>(*cluster_node_opts, *benchmark_opts); } else { run_test<sw::redis::RedisCluster>(*cluster_node_opts); } } std::cout << "Pass all tests" << std::endl; } catch (const sw::redis::Error &e) { std::cerr << "Test failed: " << e.what() << std::endl; return -1; } return 0; } namespace { void print_help() { std::cerr << "Usage: test_redis++ -h host -p port" << " -n cluster_node -c cluster_port [-a auth] [-b]\n\n"; std::cerr << "See https://github.com/sewenew/redis-plus-plus#run-tests-optional" << " for details on how to run test" << std::endl; } auto parse_options(int argc, char **argv) -> std::tuple<sw::redis::Optional<sw::redis::ConnectionOptions>, sw::redis::Optional<sw::redis::ConnectionOptions>, sw::redis::Optional<sw::redis::test::BenchmarkOptions>> { std::string host; int port = 0; std::string auth; std::string cluster_node; int cluster_port = 0; bool benchmark = false; sw::redis::test::BenchmarkOptions tmp_benchmark_opts; int opt = 0; while ((opt = getopt(argc, argv, "h:p:a:n:c:k:v:r:t:bs:")) != -1) { switch (opt) { case 'h': host = optarg; break; case 'p': port = std::stoi(optarg); break; case 'a': auth = optarg; break; case 'n': cluster_node = optarg; break; case 'c': cluster_port = std::stoi(optarg); break; case 'b': benchmark = true; break; case 'k': tmp_benchmark_opts.key_len = std::stoi(optarg); break; case 'v': tmp_benchmark_opts.val_len = std::stoi(optarg); break; case 'r': tmp_benchmark_opts.total_request_num = std::stoi(optarg); break; case 't': tmp_benchmark_opts.thread_num = std::stoi(optarg); break; case 's': tmp_benchmark_opts.pool_size = std::stoi(optarg); break; default: print_help(); throw sw::redis::Error("Failed to parse connection options"); break; } } sw::redis::Optional<sw::redis::ConnectionOptions> opts; if (!host.empty() && port > 0) { sw::redis::ConnectionOptions tmp; tmp.host = host; tmp.port = port; tmp.password = auth; opts = sw::redis::Optional<sw::redis::ConnectionOptions>(tmp); } sw::redis::Optional<sw::redis::ConnectionOptions> cluster_opts; if (!cluster_node.empty() && cluster_port > 0) { sw::redis::ConnectionOptions tmp; tmp.host = cluster_node; tmp.port = cluster_port; tmp.password = auth; cluster_opts = sw::redis::Optional<sw::redis::ConnectionOptions>(tmp); } if (!opts && !cluster_opts) { print_help(); throw sw::redis::Error("Invalid connection options"); } sw::redis::Optional<sw::redis::test::BenchmarkOptions> benchmark_opts; if (benchmark) { benchmark_opts = sw::redis::Optional<sw::redis::test::BenchmarkOptions>(tmp_benchmark_opts); } return std::make_tuple(std::move(opts), std::move(cluster_opts), std::move(benchmark_opts)); } template <typename RedisInstance> void run_test(const sw::redis::ConnectionOptions &opts) { auto instance = RedisInstance(opts); sw::redis::test::SanityTest<RedisInstance> sanity_test(opts, instance); sanity_test.run(); std::cout << "Pass sanity tests" << std::endl; sw::redis::test::ConnectionCmdTest<RedisInstance> connection_test(instance); connection_test.run(); std::cout << "Pass connection commands tests" << std::endl; sw::redis::test::KeysCmdTest<RedisInstance> keys_test(instance); keys_test.run(); std::cout << "Pass keys commands tests" << std::endl; sw::redis::test::StringCmdTest<RedisInstance> string_test(instance); string_test.run(); std::cout << "Pass string commands tests" << std::endl; sw::redis::test::ListCmdTest<RedisInstance> list_test(instance); list_test.run(); std::cout << "Pass list commands tests" << std::endl; sw::redis::test::HashCmdTest<RedisInstance> hash_test(instance); hash_test.run(); std::cout << "Pass hash commands tests" << std::endl; sw::redis::test::SetCmdTest<RedisInstance> set_test(instance); set_test.run(); std::cout << "Pass set commands tests" << std::endl; sw::redis::test::ZSetCmdTest<RedisInstance> zset_test(instance); zset_test.run(); std::cout << "Pass zset commands tests" << std::endl; sw::redis::test::HyperloglogCmdTest<RedisInstance> hll_test(instance); hll_test.run(); std::cout << "Pass hyperloglog commands tests" << std::endl; sw::redis::test::GeoCmdTest<RedisInstance> geo_test(instance); geo_test.run(); std::cout << "Pass geo commands tests" << std::endl; sw::redis::test::ScriptCmdTest<RedisInstance> script_test(instance); script_test.run(); std::cout << "Pass script commands tests" << std::endl; sw::redis::test::PubSubTest<RedisInstance> pubsub_test(instance); pubsub_test.run(); std::cout << "Pass pubsub tests" << std::endl; sw::redis::test::PipelineTransactionTest<RedisInstance> pipe_tx_test(instance); pipe_tx_test.run(); std::cout << "Pass pipeline and transaction tests" << std::endl; sw::redis::test::ThreadsTest<RedisInstance> threads_test(opts); threads_test.run(); std::cout << "Pass threads tests" << std::endl; sw::redis::test::StreamCmdsTest<RedisInstance> stream_test(instance); stream_test.run(); std::cout << "Pass stream commands tests" << std::endl; } template <typename RedisInstance> void run_benchmark(const sw::redis::ConnectionOptions &opts, const sw::redis::test::BenchmarkOptions &benchmark_opts) { std::cout << "Benchmark test options:" << std::endl; std::cout << " Thread number: " << benchmark_opts.thread_num << std::endl; std::cout << " Connection pool size: " << benchmark_opts.pool_size << std::endl; std::cout << " Length of key: " << benchmark_opts.key_len << std::endl; std::cout << " Length of value: " << benchmark_opts.val_len << std::endl; auto instance = RedisInstance(opts); sw::redis::test::BenchmarkTest<RedisInstance> benchmark_test(benchmark_opts, instance); benchmark_test.run(); } } <commit_msg>fix invalid command options for test program<commit_after>/************************************************************************** Copyright (c) 2017 sewenew 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 <unistd.h> #include <chrono> #include <tuple> #include <iostream> #include <sw/redis++/redis++.h> #include "sanity_test.h" #include "connection_cmds_test.h" #include "keys_cmds_test.h" #include "string_cmds_test.h" #include "list_cmds_test.h" #include "hash_cmds_test.h" #include "set_cmds_test.h" #include "zset_cmds_test.h" #include "hyperloglog_cmds_test.h" #include "geo_cmds_test.h" #include "script_cmds_test.h" #include "pubsub_test.h" #include "pipeline_transaction_test.h" #include "threads_test.h" #include "stream_cmds_test.h" #include "benchmark_test.h" namespace { void print_help(); auto parse_options(int argc, char **argv) -> std::tuple<sw::redis::Optional<sw::redis::ConnectionOptions>, sw::redis::Optional<sw::redis::ConnectionOptions>, sw::redis::Optional<sw::redis::test::BenchmarkOptions>>; template <typename RedisInstance> void run_test(const sw::redis::ConnectionOptions &opts); template <typename RedisInstance> void run_benchmark(const sw::redis::ConnectionOptions &opts, const sw::redis::test::BenchmarkOptions &benchmark_opts); } int main(int argc, char **argv) { try { sw::redis::Optional<sw::redis::ConnectionOptions> opts; sw::redis::Optional<sw::redis::ConnectionOptions> cluster_node_opts; sw::redis::Optional<sw::redis::test::BenchmarkOptions> benchmark_opts; std::tie(opts, cluster_node_opts, benchmark_opts) = parse_options(argc, argv); if (opts) { std::cout << "Testing Redis..." << std::endl; if (benchmark_opts) { run_benchmark<sw::redis::Redis>(*opts, *benchmark_opts); } else { run_test<sw::redis::Redis>(*opts); } } if (cluster_node_opts) { std::cout << "Testing RedisCluster..." << std::endl; if (benchmark_opts) { run_benchmark<sw::redis::RedisCluster>(*cluster_node_opts, *benchmark_opts); } else { run_test<sw::redis::RedisCluster>(*cluster_node_opts); } } std::cout << "Pass all tests" << std::endl; } catch (const sw::redis::Error &e) { std::cerr << "Test failed: " << e.what() << std::endl; return -1; } return 0; } namespace { void print_help() { std::cerr << "Usage: test_redis++ -h host -p port" << " -n cluster_node -c cluster_port [-a auth] [-b]\n\n"; std::cerr << "See https://github.com/sewenew/redis-plus-plus#run-tests-optional" << " for details on how to run test" << std::endl; } auto parse_options(int argc, char **argv) -> std::tuple<sw::redis::Optional<sw::redis::ConnectionOptions>, sw::redis::Optional<sw::redis::ConnectionOptions>, sw::redis::Optional<sw::redis::test::BenchmarkOptions>> { std::string host; int port = 0; std::string auth; std::string cluster_node; int cluster_port = 0; bool benchmark = false; sw::redis::test::BenchmarkOptions tmp_benchmark_opts; int opt = 0; while ((opt = getopt(argc, argv, "h:p:a:n:c:k:v:r:t:bs:")) != -1) { try { switch (opt) { case 'h': host = optarg; break; case 'p': port = std::stoi(optarg); break; case 'a': auth = optarg; break; case 'n': cluster_node = optarg; break; case 'c': cluster_port = std::stoi(optarg); break; case 'b': benchmark = true; break; case 'k': tmp_benchmark_opts.key_len = std::stoi(optarg); break; case 'v': tmp_benchmark_opts.val_len = std::stoi(optarg); break; case 'r': tmp_benchmark_opts.total_request_num = std::stoi(optarg); break; case 't': tmp_benchmark_opts.thread_num = std::stoi(optarg); break; case 's': tmp_benchmark_opts.pool_size = std::stoi(optarg); break; default: throw sw::redis::Error("Unknow command line option"); break; } } catch (const sw::redis::Error &e) { print_help(); throw; } catch (const std::exception &e) { print_help(); throw sw::redis::Error("Invalid command line option"); } } sw::redis::Optional<sw::redis::ConnectionOptions> opts; if (!host.empty() && port > 0) { sw::redis::ConnectionOptions tmp; tmp.host = host; tmp.port = port; tmp.password = auth; opts = sw::redis::Optional<sw::redis::ConnectionOptions>(tmp); } sw::redis::Optional<sw::redis::ConnectionOptions> cluster_opts; if (!cluster_node.empty() && cluster_port > 0) { sw::redis::ConnectionOptions tmp; tmp.host = cluster_node; tmp.port = cluster_port; tmp.password = auth; cluster_opts = sw::redis::Optional<sw::redis::ConnectionOptions>(tmp); } if (!opts && !cluster_opts) { print_help(); throw sw::redis::Error("Invalid connection options"); } sw::redis::Optional<sw::redis::test::BenchmarkOptions> benchmark_opts; if (benchmark) { benchmark_opts = sw::redis::Optional<sw::redis::test::BenchmarkOptions>(tmp_benchmark_opts); } return std::make_tuple(std::move(opts), std::move(cluster_opts), std::move(benchmark_opts)); } template <typename RedisInstance> void run_test(const sw::redis::ConnectionOptions &opts) { auto instance = RedisInstance(opts); sw::redis::test::SanityTest<RedisInstance> sanity_test(opts, instance); sanity_test.run(); std::cout << "Pass sanity tests" << std::endl; sw::redis::test::ConnectionCmdTest<RedisInstance> connection_test(instance); connection_test.run(); std::cout << "Pass connection commands tests" << std::endl; sw::redis::test::KeysCmdTest<RedisInstance> keys_test(instance); keys_test.run(); std::cout << "Pass keys commands tests" << std::endl; sw::redis::test::StringCmdTest<RedisInstance> string_test(instance); string_test.run(); std::cout << "Pass string commands tests" << std::endl; sw::redis::test::ListCmdTest<RedisInstance> list_test(instance); list_test.run(); std::cout << "Pass list commands tests" << std::endl; sw::redis::test::HashCmdTest<RedisInstance> hash_test(instance); hash_test.run(); std::cout << "Pass hash commands tests" << std::endl; sw::redis::test::SetCmdTest<RedisInstance> set_test(instance); set_test.run(); std::cout << "Pass set commands tests" << std::endl; sw::redis::test::ZSetCmdTest<RedisInstance> zset_test(instance); zset_test.run(); std::cout << "Pass zset commands tests" << std::endl; sw::redis::test::HyperloglogCmdTest<RedisInstance> hll_test(instance); hll_test.run(); std::cout << "Pass hyperloglog commands tests" << std::endl; sw::redis::test::GeoCmdTest<RedisInstance> geo_test(instance); geo_test.run(); std::cout << "Pass geo commands tests" << std::endl; sw::redis::test::ScriptCmdTest<RedisInstance> script_test(instance); script_test.run(); std::cout << "Pass script commands tests" << std::endl; sw::redis::test::PubSubTest<RedisInstance> pubsub_test(instance); pubsub_test.run(); std::cout << "Pass pubsub tests" << std::endl; sw::redis::test::PipelineTransactionTest<RedisInstance> pipe_tx_test(instance); pipe_tx_test.run(); std::cout << "Pass pipeline and transaction tests" << std::endl; sw::redis::test::ThreadsTest<RedisInstance> threads_test(opts); threads_test.run(); std::cout << "Pass threads tests" << std::endl; sw::redis::test::StreamCmdsTest<RedisInstance> stream_test(instance); stream_test.run(); std::cout << "Pass stream commands tests" << std::endl; } template <typename RedisInstance> void run_benchmark(const sw::redis::ConnectionOptions &opts, const sw::redis::test::BenchmarkOptions &benchmark_opts) { std::cout << "Benchmark test options:" << std::endl; std::cout << " Thread number: " << benchmark_opts.thread_num << std::endl; std::cout << " Connection pool size: " << benchmark_opts.pool_size << std::endl; std::cout << " Length of key: " << benchmark_opts.key_len << std::endl; std::cout << " Length of value: " << benchmark_opts.val_len << std::endl; auto instance = RedisInstance(opts); sw::redis::test::BenchmarkTest<RedisInstance> benchmark_test(benchmark_opts, instance); benchmark_test.run(); } } <|endoftext|>
<commit_before>#include "scoped-pass.hpp" #include "posix-virtual-aligner.hpp" #include <analloc2> using namespace analloc; PosixVirtualAligner aligner; void TestFullRegion(); bool HandleFailure(FreeTreeAllocator<AvlTree, uint16_t, uint8_t> *); int main() { TestFullRegion(); return 0; } void TestFullRegion() { ScopedPass pass("FreeTreeAllocator [full-region]"); FreeTreeAllocator<AvlTree, uint16_t, uint8_t> allocator(aligner, HandleFailure); allocator.Dealloc(0x100, 0x10); allocator.Dealloc(0x111, 0x1); allocator.Dealloc(0x120, 0x10); uint16_t result; assert(allocator.Alloc(result, 0x10)); assert(result == 0x100); assert(allocator.Alloc(result, 0x10)); assert(result == 0x120); assert(!allocator.Alloc(result, 0x10)); assert(allocator.Alloc(result, 0x1)); assert(result == 0x111); } bool HandleFailure(FreeTreeAllocator<AvlTree, uint16_t, uint8_t> *) { std::cerr << "HandleFailure()" << std::endl; abort(); } <commit_msg>all FreeTreeAllocator tests pass<commit_after>#include "scoped-pass.hpp" #include "posix-virtual-aligner.hpp" #include <analloc2> using namespace analloc; PosixVirtualAligner aligner; typedef FreeTreeAllocator<AvlTree, uint16_t, uint8_t> AllocatorClass; void TestFullRegion(); void TestPartialRegion(); void TestJoins(); bool HandleFailure(AllocatorClass *); int main() { TestFullRegion(); assert(aligner.GetAllocCount() == 0); TestPartialRegion(); assert(aligner.GetAllocCount() == 0); TestJoins(); assert(aligner.GetAllocCount() == 0); return 0; } void TestFullRegion() { ScopedPass pass("FreeTreeAllocator [full-region]"); AllocatorClass allocator(aligner, HandleFailure); allocator.Dealloc(0x100, 0x10); allocator.Dealloc(0x111, 0x1); allocator.Dealloc(0x120, 0x10); uint16_t result; assert(allocator.Alloc(result, 0x10)); assert(result == 0x100); assert(allocator.Alloc(result, 0x10)); assert(result == 0x120); assert(!allocator.Alloc(result, 0x10)); assert(allocator.Alloc(result, 0x1)); assert(result == 0x111); } void TestPartialRegion() { ScopedPass pass("FreeTreeAllocator [partial]"); AllocatorClass allocator(aligner, HandleFailure); uint16_t addr; allocator.Dealloc(0x100, 0x10); for (int i = 0; i < 0x10; ++i) { assert(allocator.Alloc(addr, 1)); assert(addr == (uint16_t)i + 0x100); } assert(!allocator.Alloc(addr, 1)); allocator.Dealloc(0x100, 0x10); allocator.Dealloc(0x120, 0x10); allocator.Dealloc(0x140, 0x10); assert(allocator.Alloc(addr, 0x8)); assert(addr == 0x100); assert(allocator.Alloc(addr, 0x9)); assert(addr == 0x120); assert(allocator.Alloc(addr, 0x10)); assert(addr == 0x140); assert(allocator.Alloc(addr, 0x8)); assert(addr == 0x108); assert(allocator.Alloc(addr, 0x7)); assert(addr == 0x129); assert(!allocator.Alloc(addr, 1)); // Deallocate a couple regions so that the main() function can test if the // destructor properly frees regions. allocator.Dealloc(0x100, 1); allocator.Dealloc(0x102, 1); } void TestJoins() { ScopedPass pass("FreeTreeAllocator [joins]"); AllocatorClass allocator(aligner, HandleFailure); uint16_t addr; // Joining a middle region to two outer regions allocator.Dealloc(0x100, 0x10); allocator.Dealloc(0x120, 0x10); allocator.Dealloc(0x110, 0x10); assert(allocator.Alloc(addr, 0x30)); assert(addr == 0x100); assert(!allocator.Alloc(addr, 1)); // Joining a region with it's previous region (with another further region) allocator.Dealloc(0x100, 0x10); allocator.Dealloc(0x120, 0x10); allocator.Dealloc(0x110, 0xf); assert(allocator.Alloc(addr, 0x1f)); assert(addr == 0x100); assert(allocator.Alloc(addr, 0x10)); assert(addr == 0x120); assert(!allocator.Alloc(addr, 1)); // Joining a region with the next region (with a distant region below it) allocator.Dealloc(0x100, 0xf); allocator.Dealloc(0x120, 0x10); allocator.Dealloc(0x110, 0x10); assert(allocator.Alloc(addr, 0x20)); assert(addr == 0x110); assert(allocator.Alloc(addr, 0xf)); assert(addr == 0x100); assert(!allocator.Alloc(addr, 1)); // Joining a region with it's previous region (no distant region) allocator.Dealloc(0x100, 0x10); allocator.Dealloc(0x110, 0xf); assert(allocator.Alloc(addr, 0x1f)); assert(addr == 0x100); assert(!allocator.Alloc(addr, 1)); // Joining a region with it's next region (no distant region) allocator.Dealloc(0x110, 0xf); allocator.Dealloc(0x100, 0x10); assert(allocator.Alloc(addr, 0x1f)); assert(addr == 0x100); assert(!allocator.Alloc(addr, 1)); } bool HandleFailure(FreeTreeAllocator<AvlTree, uint16_t, uint8_t> *) { std::cerr << "HandleFailure()" << std::endl; abort(); } <|endoftext|>
<commit_before>#include "libtorrent/lazy_entry.hpp" #include <boost/lexical_cast.hpp> #include <iostream> #include "test.hpp" #include "libtorrent/time.hpp" using namespace libtorrent; int test_main() { using namespace libtorrent; ptime start(time_now()); for (int i = 0; i < 1000000; ++i) { char b[] = "d1:ai12453e1:b3:aaa1:c3:bbbe"; lazy_entry e; int ret = lazy_bdecode(b, b + sizeof(b)-1, e); } ptime stop(time_now()); std::cout << "done in " << total_milliseconds(stop - start) / 1000. << " seconds per million message" << std::endl; return 0; } <commit_msg>made test_bdecode_performance run in a more reasonable amount of time<commit_after>#include "libtorrent/lazy_entry.hpp" #include <boost/lexical_cast.hpp> #include <iostream> #include "test.hpp" #include "libtorrent/time.hpp" using namespace libtorrent; int test_main() { using namespace libtorrent; ptime start(time_now()); for (int i = 0; i < 100000; ++i) { char b[] = "d1:ai12453e1:b3:aaa1:c3:bbbe"; lazy_entry e; int ret = lazy_bdecode(b, b + sizeof(b)-1, e); } ptime stop(time_now()); std::cout << "done in " << total_milliseconds(stop - start) / 100. << " seconds per million message" << std::endl; return 0; } <|endoftext|>
<commit_before>// Copyright (C) 2011 Milo Yip // // 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 "unittest.h" #include "rapidjson/document.h" using namespace rapidjson; static char* ReadFile(const char* filename, size_t& length) { FILE *fp = fopen(filename, "rb"); if (!fp) fp = fopen(filename, "rb"); if (!fp) return 0; fseek(fp, 0, SEEK_END); length = (size_t)ftell(fp); fseek(fp, 0, SEEK_SET); char* json = (char*)malloc(length + 1); size_t readLength = fread(json, 1, length, fp); json[readLength] = '\0'; fclose(fp); return json; } TEST(JsonChecker, Reader) { char filename[256]; // jsonchecker/failXX.json for (int i = 1; i <= 33; i++) { if (i == 1) // fail1.json is valid in rapidjson, which has no limitation on type of root element (RFC 7159). continue; if (i == 18) // fail18.json is valid in rapidjson, which has no limitation on depth of nesting. continue; sprintf(filename, "jsonchecker/fail%d.json", i); size_t length; char* json = ReadFile(filename, length); if (!json) { sprintf(filename, "../../bin/jsonchecker/fail%d.json", i); json = ReadFile(filename, length); if (!json) { printf("jsonchecker file %s not found", filename); ADD_FAILURE(); continue; } } GenericDocument<UTF8<>, CrtAllocator> document; // Use Crt allocator to check exception-safety (no memory leak) if (!document.Parse((const char*)json).HasParseError()) ADD_FAILURE_AT(filename, document.GetErrorOffset()); free(json); } // passX.json for (int i = 1; i <= 3; i++) { sprintf(filename, "jsonchecker/pass%d.json", i); size_t length; char* json = ReadFile(filename, length); if (!json) { sprintf(filename, "../../bin/jsonchecker/pass%d.json", i); json = ReadFile(filename, length); if (!json) { printf("jsonchecker file %s not found", filename); continue; } } GenericDocument<UTF8<>, CrtAllocator> document; // Use Crt allocator to check exception-safety (no memory leak) document.Parse((const char*)json); EXPECT_TRUE(!document.HasParseError()); free(json); } } <commit_msg>jsoncheckertest: add checks for iterative parser as well<commit_after>// Copyright (C) 2011 Milo Yip // // 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 "unittest.h" #include "rapidjson/document.h" using namespace rapidjson; static char* ReadFile(const char* filename, size_t& length) { FILE *fp = fopen(filename, "rb"); if (!fp) fp = fopen(filename, "rb"); if (!fp) return 0; fseek(fp, 0, SEEK_END); length = (size_t)ftell(fp); fseek(fp, 0, SEEK_SET); char* json = (char*)malloc(length + 1); size_t readLength = fread(json, 1, length, fp); json[readLength] = '\0'; fclose(fp); return json; } TEST(JsonChecker, Reader) { char filename[256]; // jsonchecker/failXX.json for (int i = 1; i <= 33; i++) { if (i == 1) // fail1.json is valid in rapidjson, which has no limitation on type of root element (RFC 7159). continue; if (i == 18) // fail18.json is valid in rapidjson, which has no limitation on depth of nesting. continue; sprintf(filename, "jsonchecker/fail%d.json", i); size_t length; char* json = ReadFile(filename, length); if (!json) { sprintf(filename, "../../bin/jsonchecker/fail%d.json", i); json = ReadFile(filename, length); if (!json) { printf("jsonchecker file %s not found", filename); ADD_FAILURE(); continue; } } GenericDocument<UTF8<>, CrtAllocator> document; // Use Crt allocator to check exception-safety (no memory leak) document.Parse((const char*)json); EXPECT_TRUE(document.HasParseError()); document.Parse<kParseIterativeFlag>((const char*)json); EXPECT_TRUE(document.HasParseError()); free(json); } // passX.json for (int i = 1; i <= 3; i++) { sprintf(filename, "jsonchecker/pass%d.json", i); size_t length; char* json = ReadFile(filename, length); if (!json) { sprintf(filename, "../../bin/jsonchecker/pass%d.json", i); json = ReadFile(filename, length); if (!json) { printf("jsonchecker file %s not found", filename); continue; } } GenericDocument<UTF8<>, CrtAllocator> document; // Use Crt allocator to check exception-safety (no memory leak) document.Parse((const char*)json); EXPECT_FALSE(document.HasParseError()); document.Parse<kParseIterativeFlag>((const char*)json); EXPECT_FALSE(document.HasParseError()); free(json); } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: officeresourcebundle.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2006-03-29 12:45:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef COMPHELPER_OFFICE_RESOURCE_BUNDLE_HXX #include <comphelper/officeresourcebundle.hxx> #endif /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_RESOURCE_XRESOURCEBUNDLE_HPP_ #include <com/sun/star/resource/XResourceBundle.hpp> #endif #ifndef _COM_SUN_STAR_RESOURCE_XRESOURCEBUNDLELOADER_HPP_ #include <com/sun/star/resource/XResourceBundleLoader.hpp> #endif #ifndef _COM_SUN_STAR_LANG_NULLPOINTEREXCEPTION_HPP_ #include <com/sun/star/lang/NullPointerException.hpp> #endif /** === end UNO includes === **/ #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif //........................................................................ namespace comphelper { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::uno::Reference; using com::sun::star::resource::XResourceBundle; using com::sun::star::resource::XResourceBundleLoader; using com::sun::star::resource::MissingResourceException; using ::com::sun::star::uno::XComponentContext; using ::com::sun::star::lang::NullPointerException; using ::com::sun::star::uno::UNO_QUERY; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::Any; /** === end UNO using === **/ //==================================================================== //= ResourceBundle_Impl //==================================================================== class ResourceBundle_Impl { private: Reference< XComponentContext > m_xContext; ::rtl::OUString m_sBaseName; Reference< XResourceBundle > m_xBundle; bool m_bAttemptedCreate; mutable ::osl::Mutex m_aMutex; public: ResourceBundle_Impl( const Reference< XComponentContext >& _context, const ::rtl::OUString& _baseName ) :m_xContext( _context ) ,m_sBaseName( _baseName ) ,m_bAttemptedCreate( false ) { } public: /** loads the string with the given resource id from the resource bundle @param _resourceId the id of the string to load @return the requested resource string. If no string with the given id exists in the resource bundle, an empty string is returned. In a non-product version, an OSL_ENSURE will notify you of this then. */ ::rtl::OUString loadString( sal_Int32 _resourceId ) const; private: /** loads the bundle represented by the instance The method is safe against multiple calls: If a previos call succeeded or failed, the previous result will be returned, without any other processing. @precond Our mutex is locked. */ bool impl_loadBundle_nothrow(); }; //-------------------------------------------------------------------- ::rtl::OUString ResourceBundle_Impl::loadString( sal_Int32 _resourceId ) const { ::osl::MutexGuard aGuard( m_aMutex ); ::rtl::OUString sString; if ( const_cast< ResourceBundle_Impl* >( this )->impl_loadBundle_nothrow() ) { ::rtl::OUStringBuffer key; key.appendAscii( "string:" ); key.append( _resourceId ); try { OSL_VERIFY( m_xBundle->getByName( key.makeStringAndClear() ) >>= sString ); } catch( const Exception& ) { OSL_ENSURE( false, "ResourceBundle_Impl::loadString: caught an exception!" ); } } return sString; } //-------------------------------------------------------------------- bool ResourceBundle_Impl::impl_loadBundle_nothrow() { if ( m_bAttemptedCreate ) return m_xBundle.is(); m_bAttemptedCreate = true; Reference< XResourceBundleLoader > xLoader; try { Any aValue( m_xContext->getValueByName( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/singletons/com.sun.star.resource.OfficeResourceLoader" ) ) ) ); OSL_VERIFY( aValue >>= xLoader ); } catch( const Exception& ) { OSL_ENSURE( false, "ResourceBundle_Impl::impl_loadBundle_nopthrow: could not create the resource loader!" ); } if ( !xLoader.is() ) return false; try { m_xBundle = xLoader->loadBundle_Default( m_sBaseName ); } catch( const MissingResourceException& ) { OSL_ENSURE( false, "ResourceBundle_Impl::impl_loadBundle_nopthrow: missing the given resource bundle!" ); } return m_xBundle.is(); } //==================================================================== //= OfficeResourceBundle //==================================================================== //-------------------------------------------------------------------- OfficeResourceBundle::OfficeResourceBundle( const Reference< XComponentContext >& _context, const ::rtl::OUString& _bundleBaseName ) :m_pImpl( new ResourceBundle_Impl( _context, _bundleBaseName ) ) { if ( !_context.is() ) throw NullPointerException(); } //-------------------------------------------------------------------- OfficeResourceBundle::OfficeResourceBundle( const Reference< XComponentContext >& _context, const sal_Char* _bundleBaseAsciiName ) :m_pImpl( new ResourceBundle_Impl( _context, ::rtl::OUString::createFromAscii( _bundleBaseAsciiName ) ) ) { if ( !_context.is() ) throw NullPointerException(); } //-------------------------------------------------------------------- OfficeResourceBundle::~OfficeResourceBundle() { } //-------------------------------------------------------------------- ::rtl::OUString OfficeResourceBundle::loadString( sal_Int32 _resourceId ) const { return m_pImpl->loadString( _resourceId ); } //........................................................................ } // namespace comphelper //........................................................................ <commit_msg>INTEGRATION: CWS pchfix02 (1.2.54); FILE MERGED 2006/09/01 17:19:43 kaib 1.2.54.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: officeresourcebundle.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-17 17:13:09 $ * * 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_comphelper.hxx" #ifndef COMPHELPER_OFFICE_RESOURCE_BUNDLE_HXX #include <comphelper/officeresourcebundle.hxx> #endif /** === begin UNO includes === **/ #ifndef _COM_SUN_STAR_RESOURCE_XRESOURCEBUNDLE_HPP_ #include <com/sun/star/resource/XResourceBundle.hpp> #endif #ifndef _COM_SUN_STAR_RESOURCE_XRESOURCEBUNDLELOADER_HPP_ #include <com/sun/star/resource/XResourceBundleLoader.hpp> #endif #ifndef _COM_SUN_STAR_LANG_NULLPOINTEREXCEPTION_HPP_ #include <com/sun/star/lang/NullPointerException.hpp> #endif /** === end UNO includes === **/ #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _OSL_DIAGNOSE_H_ #include <osl/diagnose.h> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif //........................................................................ namespace comphelper { //........................................................................ /** === begin UNO using === **/ using ::com::sun::star::uno::Reference; using com::sun::star::resource::XResourceBundle; using com::sun::star::resource::XResourceBundleLoader; using com::sun::star::resource::MissingResourceException; using ::com::sun::star::uno::XComponentContext; using ::com::sun::star::lang::NullPointerException; using ::com::sun::star::uno::UNO_QUERY; using ::com::sun::star::uno::Exception; using ::com::sun::star::uno::Any; /** === end UNO using === **/ //==================================================================== //= ResourceBundle_Impl //==================================================================== class ResourceBundle_Impl { private: Reference< XComponentContext > m_xContext; ::rtl::OUString m_sBaseName; Reference< XResourceBundle > m_xBundle; bool m_bAttemptedCreate; mutable ::osl::Mutex m_aMutex; public: ResourceBundle_Impl( const Reference< XComponentContext >& _context, const ::rtl::OUString& _baseName ) :m_xContext( _context ) ,m_sBaseName( _baseName ) ,m_bAttemptedCreate( false ) { } public: /** loads the string with the given resource id from the resource bundle @param _resourceId the id of the string to load @return the requested resource string. If no string with the given id exists in the resource bundle, an empty string is returned. In a non-product version, an OSL_ENSURE will notify you of this then. */ ::rtl::OUString loadString( sal_Int32 _resourceId ) const; private: /** loads the bundle represented by the instance The method is safe against multiple calls: If a previos call succeeded or failed, the previous result will be returned, without any other processing. @precond Our mutex is locked. */ bool impl_loadBundle_nothrow(); }; //-------------------------------------------------------------------- ::rtl::OUString ResourceBundle_Impl::loadString( sal_Int32 _resourceId ) const { ::osl::MutexGuard aGuard( m_aMutex ); ::rtl::OUString sString; if ( const_cast< ResourceBundle_Impl* >( this )->impl_loadBundle_nothrow() ) { ::rtl::OUStringBuffer key; key.appendAscii( "string:" ); key.append( _resourceId ); try { OSL_VERIFY( m_xBundle->getByName( key.makeStringAndClear() ) >>= sString ); } catch( const Exception& ) { OSL_ENSURE( false, "ResourceBundle_Impl::loadString: caught an exception!" ); } } return sString; } //-------------------------------------------------------------------- bool ResourceBundle_Impl::impl_loadBundle_nothrow() { if ( m_bAttemptedCreate ) return m_xBundle.is(); m_bAttemptedCreate = true; Reference< XResourceBundleLoader > xLoader; try { Any aValue( m_xContext->getValueByName( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/singletons/com.sun.star.resource.OfficeResourceLoader" ) ) ) ); OSL_VERIFY( aValue >>= xLoader ); } catch( const Exception& ) { OSL_ENSURE( false, "ResourceBundle_Impl::impl_loadBundle_nopthrow: could not create the resource loader!" ); } if ( !xLoader.is() ) return false; try { m_xBundle = xLoader->loadBundle_Default( m_sBaseName ); } catch( const MissingResourceException& ) { OSL_ENSURE( false, "ResourceBundle_Impl::impl_loadBundle_nopthrow: missing the given resource bundle!" ); } return m_xBundle.is(); } //==================================================================== //= OfficeResourceBundle //==================================================================== //-------------------------------------------------------------------- OfficeResourceBundle::OfficeResourceBundle( const Reference< XComponentContext >& _context, const ::rtl::OUString& _bundleBaseName ) :m_pImpl( new ResourceBundle_Impl( _context, _bundleBaseName ) ) { if ( !_context.is() ) throw NullPointerException(); } //-------------------------------------------------------------------- OfficeResourceBundle::OfficeResourceBundle( const Reference< XComponentContext >& _context, const sal_Char* _bundleBaseAsciiName ) :m_pImpl( new ResourceBundle_Impl( _context, ::rtl::OUString::createFromAscii( _bundleBaseAsciiName ) ) ) { if ( !_context.is() ) throw NullPointerException(); } //-------------------------------------------------------------------- OfficeResourceBundle::~OfficeResourceBundle() { } //-------------------------------------------------------------------- ::rtl::OUString OfficeResourceBundle::loadString( sal_Int32 _resourceId ) const { return m_pImpl->loadString( _resourceId ); } //........................................................................ } // namespace comphelper //........................................................................ <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Pelagicore AB * All rights reserved. */ #include "gmock/gmock.h" #include "gtest/gtest.h" #include "pulsegateway.h" #include "pulsegateway_unittest_data.h" #include "generators.h" #include "log.h" using namespace pelagicore; class PulseMockController: public ControllerAbstractInterface { public: virtual bool startApp() { return true; } virtual bool shutdown() { return true; } virtual bool hasBeenStarted() const { return true; } virtual bool initialize() { return true; } MOCK_METHOD1(systemCall, bool(const std::string &cmd)); MOCK_METHOD2(setEnvironmentVariable, bool(const std::string &variable, const std::string &value)); }; class MockSystemcallInterface: public SystemcallAbstractInterface { public: virtual bool makeCall(const std::string &cmd, int &exitCode) { exitCode = 0; return true; } MOCK_METHOD1(makeCall, bool(const std::string &cmd)); MOCK_METHOD3(makePopenCall, pid_t(const std::string &command, int *infp, int *outfp)); MOCK_METHOD3(makePcloseCall, bool(pid_t pid, int infp, int outfp)); }; using ::testing::DefaultValue; using ::testing::InSequence; using ::testing::_; using ::testing::Return; using ::testing::NiceMock; using ::testing::StrictMock; using ::testing::StrEq; using ::testing::A; class PulseGatewayTest: public ::testing::Test { protected: virtual void SetUp() { DefaultValue<bool>::Set(true); // ContainerName and gatewayDir must be passed to constructor containerName = "fake-containerName"; containerRoot = "/fake-directory/"; containerDir = containerRoot + "/" + containerName; gatewayDir = containerDir + "/gateways"; } virtual void TearDown() { using ::testing::DefaultValue; DefaultValue<bool>::Clear(); } NiceMock<PulseMockController> controllerInterface; std::string containerName; std::string gatewayDir; std::string containerRoot; std::string containerDir; }; /*! Test that id is correct ("pulseaudio") */ TEST_F(PulseGatewayTest, TestIdEqualspulseaudio) { PulseGateway gw(gatewayDir, containerName, controllerInterface); ASSERT_STREQ(gw.id().c_str(), "pulseaudio"); } /*! Test well-formed configuration that enables the gateway. * * Tests with configurations that are syntactically correct, i.e. not * causing errors, and that enables audio. */ class PulseGatewayValidConfig: public testing::TestWithParam<pulseTestData> {}; INSTANTIATE_TEST_CASE_P(InstantiationName, PulseGatewayValidConfig, ::testing::ValuesIn(validConfigs)); TEST_P(PulseGatewayValidConfig, TestCanParseValidConfig) { StrictMock<PulseMockController> controllerInterface; PulseGateway gw("fake-gatewayDir", "fake-containerName", controllerInterface); struct pulseTestData config = GetParam(); DefaultValue<bool>::Set(true); EXPECT_CALL(controllerInterface, setEnvironmentVariable( A<const std::string &>(), A<const std::string &>())); bool success = gw.setConfig(config.data); DefaultValue<bool>::Clear(); ASSERT_TRUE(success); success = gw.activate(); ASSERT_TRUE(success); ASSERT_TRUE(gw.teardown()); } /*! Test malformed configuration that disables the gateway. * * Tests with configurations that are syntactically incorrect, i.e. * causing parsing errors. */ class PulseGatewayInvalidConfig: public testing::TestWithParam<pulseTestData> {}; INSTANTIATE_TEST_CASE_P(InstantiationName, PulseGatewayInvalidConfig, ::testing::ValuesIn(invalidConfigs)); TEST_P(PulseGatewayInvalidConfig, TestCanParseInvalidConfig) { StrictMock<PulseMockController> controllerInterface; PulseGateway gw("fake-gatewayDir", "fake-containerName", controllerInterface); struct pulseTestData config = GetParam(); bool success = gw.setConfig(config.data); ASSERT_TRUE(!success); } /*! Test well-formed configuration that disables the gateway. * * Tests with configurations that are syntactically correct, i.e. not * causing errors, but that disables audio. */ class PulseGatewayDisablingConfig: public testing::TestWithParam<pulseTestData> {}; INSTANTIATE_TEST_CASE_P(InstantiationName, PulseGatewayDisablingConfig, ::testing::ValuesIn(disablingConfigs)); TEST_P(PulseGatewayDisablingConfig, TestCanParseDisablingConfig) { StrictMock<PulseMockController> controllerInterface; PulseGateway gw("fake-gatewayDir", "fake-containerName", controllerInterface); struct pulseTestData config = GetParam(); EXPECT_CALL(controllerInterface, setEnvironmentVariable(_, _)).Times(0); bool success = gw.setConfig(config.data); ASSERT_TRUE(success); } <commit_msg>pulsegateway_unittest.cpp: Disabled test that interacts mostly with pulseaudio. This test seems to test pulseaudio more than anytning and can fail due to the environment set up.<commit_after>/* * Copyright (C) 2014 Pelagicore AB * All rights reserved. */ #include "gmock/gmock.h" #include "gtest/gtest.h" #include "pulsegateway.h" #include "pulsegateway_unittest_data.h" #include "generators.h" #include "log.h" using namespace pelagicore; class PulseMockController: public ControllerAbstractInterface { public: virtual bool startApp() { return true; } virtual bool shutdown() { return true; } virtual bool hasBeenStarted() const { return true; } virtual bool initialize() { return true; } MOCK_METHOD1(systemCall, bool(const std::string &cmd)); MOCK_METHOD2(setEnvironmentVariable, bool(const std::string &variable, const std::string &value)); }; class MockSystemcallInterface: public SystemcallAbstractInterface { public: virtual bool makeCall(const std::string &cmd, int &exitCode) { exitCode = 0; return true; } MOCK_METHOD1(makeCall, bool(const std::string &cmd)); MOCK_METHOD3(makePopenCall, pid_t(const std::string &command, int *infp, int *outfp)); MOCK_METHOD3(makePcloseCall, bool(pid_t pid, int infp, int outfp)); }; using ::testing::DefaultValue; using ::testing::InSequence; using ::testing::_; using ::testing::Return; using ::testing::NiceMock; using ::testing::StrictMock; using ::testing::StrEq; using ::testing::A; class PulseGatewayTest: public ::testing::Test { protected: virtual void SetUp() { DefaultValue<bool>::Set(true); // ContainerName and gatewayDir must be passed to constructor containerName = "fake-containerName"; containerRoot = "/fake-directory/"; containerDir = containerRoot + "/" + containerName; gatewayDir = containerDir + "/gateways"; } virtual void TearDown() { using ::testing::DefaultValue; DefaultValue<bool>::Clear(); } NiceMock<PulseMockController> controllerInterface; std::string containerName; std::string gatewayDir; std::string containerRoot; std::string containerDir; }; /*! Test that id is correct ("pulseaudio") */ TEST_F(PulseGatewayTest, TestIdEqualspulseaudio) { PulseGateway gw(gatewayDir, containerName, controllerInterface); ASSERT_STREQ(gw.id().c_str(), "pulseaudio"); } /*! Test well-formed configuration that enables the gateway. * * Tests with configurations that are syntactically correct, i.e. not * causing errors, and that enables audio. */ class PulseGatewayValidConfig: public testing::TestWithParam<pulseTestData> {}; INSTANTIATE_TEST_CASE_P(InstantiationName, PulseGatewayValidConfig, ::testing::ValuesIn(validConfigs)); TEST_P(PulseGatewayValidConfig, DISABLED_TestCanParseValidConfig) { StrictMock<PulseMockController> controllerInterface; PulseGateway gw("fake-gatewayDir", "fake-containerName", controllerInterface); struct pulseTestData config = GetParam(); DefaultValue<bool>::Set(true); EXPECT_CALL(controllerInterface, setEnvironmentVariable( A<const std::string &>(), A<const std::string &>())); bool success = gw.setConfig(config.data); DefaultValue<bool>::Clear(); ASSERT_TRUE(success); success = gw.activate(); ASSERT_TRUE(success); ASSERT_TRUE(gw.teardown()); } /*! Test malformed configuration that disables the gateway. * * Tests with configurations that are syntactically incorrect, i.e. * causing parsing errors. */ class PulseGatewayInvalidConfig: public testing::TestWithParam<pulseTestData> {}; INSTANTIATE_TEST_CASE_P(InstantiationName, PulseGatewayInvalidConfig, ::testing::ValuesIn(invalidConfigs)); TEST_P(PulseGatewayInvalidConfig, TestCanParseInvalidConfig) { StrictMock<PulseMockController> controllerInterface; PulseGateway gw("fake-gatewayDir", "fake-containerName", controllerInterface); struct pulseTestData config = GetParam(); bool success = gw.setConfig(config.data); ASSERT_TRUE(!success); } /*! Test well-formed configuration that disables the gateway. * * Tests with configurations that are syntactically correct, i.e. not * causing errors, but that disables audio. */ class PulseGatewayDisablingConfig: public testing::TestWithParam<pulseTestData> {}; INSTANTIATE_TEST_CASE_P(InstantiationName, PulseGatewayDisablingConfig, ::testing::ValuesIn(disablingConfigs)); TEST_P(PulseGatewayDisablingConfig, TestCanParseDisablingConfig) { StrictMock<PulseMockController> controllerInterface; PulseGateway gw("fake-gatewayDir", "fake-containerName", controllerInterface); struct pulseTestData config = GetParam(); EXPECT_CALL(controllerInterface, setEnvironmentVariable(_, _)).Times(0); bool success = gw.setConfig(config.data); ASSERT_TRUE(success); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: filedlgimpl.hxx,v $ * * $Revision: 1.13 $ * * last change: $Author: ihi $ $Date: 2007-11-19 16:32:06 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SFX_FILEDLGIMPL_HXX #define _SFX_FILEDLGIMPL_HXX #ifndef _SV_TIMER_HXX #include <vcl/timer.hxx> #endif #ifndef _SV_GRAPH_HXX #include <vcl/graph.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_STRINGPAIR_HPP_ #include <com/sun/star/beans/StringPair.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_ #include <com/sun/star/ui/dialogs/XFilePicker.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERLISTENER_HPP_ #include <com/sun/star/ui/dialogs/XFilePickerListener.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XDIALOGCLOSEDLISTENER_HPP_ #include <com/sun/star/ui/dialogs/XDialogClosedListener.hpp> #endif #ifndef _SFX_FCONTNR_HXX #include <sfx2/fcontnr.hxx> #endif #define _SVSTDARR_STRINGSDTOR #include <svtools/svstdarr.hxx> #include <sfx2/filedlghelper.hxx> #include <comphelper/sequenceasvector.hxx> class SfxFilterMatcher; class GraphicFilter; class FileDialogHelper; namespace sfx2 { typedef ::com::sun::star::beans::StringPair FilterPair; class FileDialogHelper_Impl : public ::cppu::WeakImplHelper2< ::com::sun::star::ui::dialogs::XFilePickerListener, ::com::sun::star::ui::dialogs::XDialogClosedListener > { friend class FileDialogHelper; ::com::sun::star::uno::Reference < ::com::sun::star::ui::dialogs::XFilePicker > mxFileDlg; ::com::sun::star::uno::Reference < ::com::sun::star::container::XNameAccess > mxFilterCFG; std::vector< FilterPair > maFilters; SfxFilterMatcher* mpMatcher; GraphicFilter* mpGraphicFilter; FileDialogHelper* mpAntiImpl; Window* mpPreferredParentWindow; ::comphelper::SequenceAsVector< ::rtl::OUString > mlLastURLs; ::rtl::OUString maPath; ::rtl::OUString maFileName; ::rtl::OUString maCurFilter; ::rtl::OUString maSelectFilter; ::rtl::OUString maButtonLabel; Timer maPreViewTimer; Graphic maGraphic; const short m_nDialogType; SfxFilterFlags m_nMustFlags; SfxFilterFlags m_nDontFlags; ULONG mnPostUserEventId; ErrCode mnError; FileDialogHelper::Context meContext; sal_Bool mbHasPassword : 1; sal_Bool mbIsPwdEnabled : 1; sal_Bool m_bHaveFilterOptions : 1; sal_Bool mbHasVersions : 1; sal_Bool mbHasAutoExt : 1; sal_Bool mbHasLink : 1; sal_Bool mbHasPreview : 1; sal_Bool mbShowPreview : 1; sal_Bool mbIsSaveDlg : 1; sal_Bool mbExport : 1; sal_Bool mbDeleteMatcher : 1; sal_Bool mbInsert : 1; sal_Bool mbSystemPicker : 1; sal_Bool mbPwdCheckBoxState : 1; sal_Bool mbSelection : 1; sal_Bool mbSelectionEnabled : 1; private: void addFilters( sal_Int64 nFlags, const String& rFactory, SfxFilterFlags nMust, SfxFilterFlags nDont ); void addFilter( const ::rtl::OUString& rFilterName, const ::rtl::OUString& rExtension ); void addGraphicFilter(); void enablePasswordBox( sal_Bool bInit ); void updateFilterOptionsBox(); void updateExportButton(); void updateSelectionBox(); void updateVersions(); void updatePreviewState( sal_Bool _bUpdatePreviewWindow = sal_True ); void dispose(); void loadConfig(); void saveConfig(); const SfxFilter* getCurentSfxFilter(); sal_Bool updateExtendedControl( sal_Int16 _nExtendedControlId, sal_Bool _bEnable ); ErrCode getGraphic( const ::rtl::OUString& rURL, Graphic& rGraphic ) const; void setDefaultValues(); void preExecute(); void postExecute( sal_Int16 _nResult ); sal_Int16 implDoExecute(); void implStartExecute(); void correctVirtualDialogType(); void setControlHelpIds( const sal_Int16* _pControlId, const sal_Int32* _pHelpId ); void setDialogHelpId( const sal_Int32 _nHelpId ); sal_Bool CheckFilterOptionsCapability( const SfxFilter* _pFilter ); sal_Bool isInOpenMode() const; String getCurrentFilterUIName() const; void LoadLastUsedFilter( const ::rtl::OUString& _rContextIdentifier ); void SaveLastUsedFilter( const ::rtl::OUString& _rContextIdentifier ); void SaveLastUsedFilter( void ); void implInitializeFileName( ); void implGetAndCacheFiles( const ::com::sun::star::uno::Reference< XInterface >& xPicker , SvStringsDtor*& rpURLList, const SfxFilter* pFilter ); String implEnsureURLExtension(const String& sURL , const String& sExtension); DECL_LINK( TimeOutHdl_Impl, Timer* ); DECL_LINK( HandleEvent, FileDialogHelper* ); DECL_LINK( InitControls, void* ); public: // XFilePickerListener methods virtual void SAL_CALL fileSelectionChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL directoryChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL helpRequested( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL controlStateChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL dialogSizeChanged() throw( ::com::sun::star::uno::RuntimeException ); // XDialogClosedListener methods virtual void SAL_CALL dialogClosed( const ::com::sun::star::ui::dialogs::DialogClosedEvent& _rEvent ) throw (::com::sun::star::uno::RuntimeException); // XEventListener methods virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw( ::com::sun::star::uno::RuntimeException ); // handle XFilePickerListener events void handleFileSelectionChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); void handleDirectoryChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); ::rtl::OUString handleHelpRequested( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); void handleControlStateChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); void handleDialogSizeChanged(); // Own methods FileDialogHelper_Impl( FileDialogHelper* _pAntiImpl, const short nDialogType, sal_Int64 nFlags, Window* _pPreferredParentWindow = NULL ); virtual ~FileDialogHelper_Impl(); ErrCode execute( SvStringsDtor*& rpURLList, SfxItemSet *& rpSet, String& rFilter ); ErrCode execute(); void setFilter( const ::rtl::OUString& rFilter ); /** sets the directory which should be browsed <p>If the given path does not point to a valid (existent and accessible) folder, the request is silently dropped</p> */ void displayFolder( const ::rtl::OUString& rPath ); void setFileName( const ::rtl::OUString& _rFile ); ::rtl::OUString getPath() const; ::rtl::OUString getFilter() const; void getRealFilter( String& _rFilter ) const; ErrCode getGraphic( Graphic& rGraphic ) const; void createMatcher( const String& rFactory ); sal_Bool isShowFilterExtensionEnabled() const; void addFilterPair( const ::rtl::OUString& rFilter, const ::rtl::OUString& rFilterWithExtension ); ::rtl::OUString getFilterName( const ::rtl::OUString& rFilterWithExtension ) const; ::rtl::OUString getFilterWithExtension( const ::rtl::OUString& rFilter ) const; void SetContext( FileDialogHelper::Context _eNewContext ); inline sal_Bool isSystemFilePicker() const { return mbSystemPicker; } inline sal_Bool isPasswordEnabled() const { return mbIsPwdEnabled; } }; } // end of namespace sfx2 #endif // _SFX_FILEDLGIMPL_HXX <commit_msg>INTEGRATION: CWS tkr06 (1.12.98); FILE MERGED 2007/10/30 09:39:01 jsc 1.12.98.1: #i83075# new var for dialog configuration<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: filedlgimpl.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: ihi $ $Date: 2007-11-26 16:47:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SFX_FILEDLGIMPL_HXX #define _SFX_FILEDLGIMPL_HXX #ifndef _SV_TIMER_HXX #include <vcl/timer.hxx> #endif #ifndef _SV_GRAPH_HXX #include <vcl/graph.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX_ #include <cppuhelper/implbase2.hxx> #endif #ifndef _COM_SUN_STAR_BEANS_STRINGPAIR_HPP_ #include <com/sun/star/beans/StringPair.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKER_HPP_ #include <com/sun/star/ui/dialogs/XFilePicker.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERLISTENER_HPP_ #include <com/sun/star/ui/dialogs/XFilePickerListener.hpp> #endif #ifndef _COM_SUN_STAR_UI_DIALOGS_XDIALOGCLOSEDLISTENER_HPP_ #include <com/sun/star/ui/dialogs/XDialogClosedListener.hpp> #endif #ifndef _SFX_FCONTNR_HXX #include <sfx2/fcontnr.hxx> #endif #define _SVSTDARR_STRINGSDTOR #include <svtools/svstdarr.hxx> #include <sfx2/filedlghelper.hxx> #include <comphelper/sequenceasvector.hxx> class SfxFilterMatcher; class GraphicFilter; class FileDialogHelper; namespace sfx2 { typedef ::com::sun::star::beans::StringPair FilterPair; class FileDialogHelper_Impl : public ::cppu::WeakImplHelper2< ::com::sun::star::ui::dialogs::XFilePickerListener, ::com::sun::star::ui::dialogs::XDialogClosedListener > { friend class FileDialogHelper; ::com::sun::star::uno::Reference < ::com::sun::star::ui::dialogs::XFilePicker > mxFileDlg; ::com::sun::star::uno::Reference < ::com::sun::star::container::XNameAccess > mxFilterCFG; std::vector< FilterPair > maFilters; SfxFilterMatcher* mpMatcher; GraphicFilter* mpGraphicFilter; FileDialogHelper* mpAntiImpl; Window* mpPreferredParentWindow; ::comphelper::SequenceAsVector< ::rtl::OUString > mlLastURLs; ::rtl::OUString maPath; ::rtl::OUString maFileName; ::rtl::OUString maCurFilter; ::rtl::OUString maSelectFilter; ::rtl::OUString maButtonLabel; Timer maPreViewTimer; Graphic maGraphic; const short m_nDialogType; SfxFilterFlags m_nMustFlags; SfxFilterFlags m_nDontFlags; ULONG mnPostUserEventId; ErrCode mnError; FileDialogHelper::Context meContext; sal_Bool mbHasPassword : 1; sal_Bool mbIsPwdEnabled : 1; sal_Bool m_bHaveFilterOptions : 1; sal_Bool mbHasVersions : 1; sal_Bool mbHasAutoExt : 1; sal_Bool mbHasLink : 1; sal_Bool mbHasPreview : 1; sal_Bool mbShowPreview : 1; sal_Bool mbIsSaveDlg : 1; sal_Bool mbExport : 1; sal_Bool mbDeleteMatcher : 1; sal_Bool mbInsert : 1; sal_Bool mbSystemPicker : 1; sal_Bool mbPwdCheckBoxState : 1; sal_Bool mbSelection : 1; sal_Bool mbSelectionEnabled : 1; private: void addFilters( sal_Int64 nFlags, const String& rFactory, SfxFilterFlags nMust, SfxFilterFlags nDont ); void addFilter( const ::rtl::OUString& rFilterName, const ::rtl::OUString& rExtension ); void addGraphicFilter(); void enablePasswordBox( sal_Bool bInit ); void updateFilterOptionsBox(); void updateExportButton(); void updateSelectionBox(); void updateVersions(); void updatePreviewState( sal_Bool _bUpdatePreviewWindow = sal_True ); void dispose(); void loadConfig(); void saveConfig(); const SfxFilter* getCurentSfxFilter(); sal_Bool updateExtendedControl( sal_Int16 _nExtendedControlId, sal_Bool _bEnable ); ErrCode getGraphic( const ::rtl::OUString& rURL, Graphic& rGraphic ) const; void setDefaultValues(); void preExecute(); void postExecute( sal_Int16 _nResult ); sal_Int16 implDoExecute(); void implStartExecute(); void correctVirtualDialogType(); void setControlHelpIds( const sal_Int16* _pControlId, const sal_Int32* _pHelpId ); void setDialogHelpId( const sal_Int32 _nHelpId ); sal_Bool CheckFilterOptionsCapability( const SfxFilter* _pFilter ); sal_Bool isInOpenMode() const; String getCurrentFilterUIName() const; void LoadLastUsedFilter( const ::rtl::OUString& _rContextIdentifier ); void SaveLastUsedFilter( const ::rtl::OUString& _rContextIdentifier ); void SaveLastUsedFilter( void ); void implInitializeFileName( ); void implGetAndCacheFiles( const ::com::sun::star::uno::Reference< XInterface >& xPicker , SvStringsDtor*& rpURLList, const SfxFilter* pFilter ); String implEnsureURLExtension(const String& sURL , const String& sExtension); DECL_LINK( TimeOutHdl_Impl, Timer* ); DECL_LINK( HandleEvent, FileDialogHelper* ); DECL_LINK( InitControls, void* ); public: // XFilePickerListener methods virtual void SAL_CALL fileSelectionChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL directoryChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual ::rtl::OUString SAL_CALL helpRequested( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL controlStateChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL dialogSizeChanged() throw( ::com::sun::star::uno::RuntimeException ); // XDialogClosedListener methods virtual void SAL_CALL dialogClosed( const ::com::sun::star::ui::dialogs::DialogClosedEvent& _rEvent ) throw (::com::sun::star::uno::RuntimeException); // XEventListener methods virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw( ::com::sun::star::uno::RuntimeException ); // handle XFilePickerListener events void handleFileSelectionChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); void handleDirectoryChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); ::rtl::OUString handleHelpRequested( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); void handleControlStateChanged( const ::com::sun::star::ui::dialogs::FilePickerEvent& aEvent ); void handleDialogSizeChanged(); // Own methods FileDialogHelper_Impl( FileDialogHelper* _pAntiImpl, const short nDialogType, sal_Int64 nFlags, sal_Int16 nDialog = SFX2_IMPL_DIALOG_CONFIG, Window* _pPreferredParentWindow = NULL ); virtual ~FileDialogHelper_Impl(); ErrCode execute( SvStringsDtor*& rpURLList, SfxItemSet *& rpSet, String& rFilter ); ErrCode execute(); void setFilter( const ::rtl::OUString& rFilter ); /** sets the directory which should be browsed <p>If the given path does not point to a valid (existent and accessible) folder, the request is silently dropped</p> */ void displayFolder( const ::rtl::OUString& rPath ); void setFileName( const ::rtl::OUString& _rFile ); ::rtl::OUString getPath() const; ::rtl::OUString getFilter() const; void getRealFilter( String& _rFilter ) const; ErrCode getGraphic( Graphic& rGraphic ) const; void createMatcher( const String& rFactory ); sal_Bool isShowFilterExtensionEnabled() const; void addFilterPair( const ::rtl::OUString& rFilter, const ::rtl::OUString& rFilterWithExtension ); ::rtl::OUString getFilterName( const ::rtl::OUString& rFilterWithExtension ) const; ::rtl::OUString getFilterWithExtension( const ::rtl::OUString& rFilter ) const; void SetContext( FileDialogHelper::Context _eNewContext ); inline sal_Bool isSystemFilePicker() const { return mbSystemPicker; } inline sal_Bool isPasswordEnabled() const { return mbIsPwdEnabled; } }; } // end of namespace sfx2 #endif // _SFX_FILEDLGIMPL_HXX <|endoftext|>
<commit_before>/* * Smithsonian Astrophysical Observatory, Cambridge, MA, USA * This code has been modified under the terms listed below and is made * available under the same terms. */ /* * Copyright 1993-2004 George A Howlett. * * 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 <math.h> #include <tk.h> #include <tkPort.h> #include <tkInt.h> #include "bltGrText.h" #include "bltGraph.h" #include "bltGrPSOutput.h" using namespace Blt; TextStyle::TextStyle(Graph* graphPtr) { ops_ = (TextStyleOptions*)calloc(1, sizeof(TextStyleOptions)); TextStyleOptions* ops = (TextStyleOptions*)ops_; graphPtr_ = graphPtr; manageOptions_ = 1; ops->anchor =TK_ANCHOR_NW; ops->color =NULL; ops->font =NULL; ops->angle =0; ops->justify =TK_JUSTIFY_LEFT; xPad_ = 0; yPad_ = 0; gc_ = NULL; } TextStyle::TextStyle(Graph* graphPtr, TextStyleOptions* ops) { ops_ = (TextStyleOptions*)ops; graphPtr_ = graphPtr; manageOptions_ = 0; xPad_ = 0; yPad_ = 0; gc_ = NULL; } TextStyle::~TextStyle() { // TextStyleOptions* ops = (TextStyleOptions*)ops_; if (gc_) Tk_FreeGC(graphPtr_->display_, gc_); if (manageOptions_) free(ops_); } void TextStyle::drawText(Drawable drawable, const char *text, int x, int y) { TextStyleOptions* ops = (TextStyleOptions*)ops_; if (!text || !(*text)) return; if (!gc_) resetStyle(); int w1, h1; Tk_TextLayout layout = Tk_ComputeTextLayout(ops->font, text, -1, -1, ops->justify, 0, &w1, &h1); Point2d rr = rotateText(x, y, w1, h1); TkDrawAngledTextLayout(graphPtr_->display_, drawable, gc_, layout, rr.x, rr.y, ops->angle, 0, -1); } void TextStyle::drawText2(Drawable drawable, const char *text, int x, int y, int* ww, int* hh) { TextStyleOptions* ops = (TextStyleOptions*)ops_; if (!text || !(*text)) return; if (!gc_) resetStyle(); int w1, h1; Tk_TextLayout layout = Tk_ComputeTextLayout(ops->font, text, -1, -1, ops->justify, 0, &w1, &h1); Point2d rr = rotateText(x, y, w1, h1); TkDrawAngledTextLayout(graphPtr_->display_, drawable, gc_, layout, rr.x, rr.y, ops->angle, 0, -1); float angle = fmod(ops->angle, 360.0); if (angle < 0.0) angle += 360.0; if (angle != 0.0) { double rotWidth, rotHeight; graphPtr_->getBoundingBox(w1, h1, angle, &rotWidth, &rotHeight, NULL); w1 = rotWidth; h1 = rotHeight; } *ww = w1; *hh = h1; } void TextStyle::printText(PSOutput* psPtr, const char *text, int x, int y) { TextStyleOptions* ops = (TextStyleOptions*)ops_; if (!text || !(*text)) return; int w1, h1; Tk_TextLayout layout = Tk_ComputeTextLayout(ops->font, text, -1, -1, ops->justify, 0, &w1, &h1); int xx =0; int yy =0; switch (ops->anchor) { case TK_ANCHOR_NW: xx = 0; yy = 0; break; case TK_ANCHOR_N: xx = 1; yy = 0; break; case TK_ANCHOR_NE: xx = 2; yy = 0; break; case TK_ANCHOR_E: xx = 2; yy = 1; break; case TK_ANCHOR_SE: xx = 2; yy = 2; break; case TK_ANCHOR_S: xx = 1; yy = 2; break; case TK_ANCHOR_SW: xx = 0; yy = 2; break; case TK_ANCHOR_W: xx = 0; yy = 1; break; case TK_ANCHOR_CENTER: xx = 1; yy = 1; break; } const char* justify =NULL; switch (ops->justify) { case TK_JUSTIFY_LEFT: justify = "0"; break; case TK_JUSTIFY_CENTER: justify = "0.5"; break; case TK_JUSTIFY_RIGHT: justify = "1"; break; } psPtr->setFont(ops->font); psPtr->setForeground(ops->color); psPtr->format("%g %d %d [\n", ops->angle, x, y); Tcl_ResetResult(graphPtr_->interp_); Tk_TextLayoutToPostscript(graphPtr_->interp_, layout); psPtr->append(Tcl_GetStringResult(graphPtr_->interp_)); Tcl_ResetResult(graphPtr_->interp_); psPtr->format("] %g %g %s DrawText\n", xx/-2.0, yy/-2.0, justify); } void TextStyle::resetStyle() { TextStyleOptions* ops = (TextStyleOptions*)ops_; unsigned long gcMask; gcMask = GCFont; XGCValues gcValues; gcValues.font = Tk_FontId(ops->font); if (ops->color) { gcMask |= GCForeground; gcValues.foreground = ops->color->pixel; } GC newGC = Tk_GetGC(graphPtr_->tkwin_, gcMask, &gcValues); if (gc_) Tk_FreeGC(graphPtr_->display_, gc_); gc_ = newGC; } Point2d TextStyle::rotateText(int x, int y, int w1, int h1) { TextStyleOptions* ops = (TextStyleOptions*)ops_; // Matrix t0 = Translate(-x,-y); // Matrix t1 = Translate(-w1/2,-h1/2); // Matrix rr = Rotate(angle); // Matrix t2 = Translate(w2/2,h2/2); // Matrix t3 = Translate(x,y); double angle = ops->angle; double ccos = cos(M_PI*angle/180.); double ssin = sin(M_PI*angle/180.); double w2, h2; graphPtr_->getBoundingBox(w1, h1, angle, &w2, &h2, NULL); double x1 = x+w1/2.; double y1 = y+h1/2.; double x2 = w2/2.+x; double y2 = h2/2.+y; double rx = x*ccos + y*ssin + (-x1*ccos -y1*ssin +x2); double ry = -x*ssin + y*ccos + ( x1*ssin -y1*ccos +y2); return graphPtr_->anchorPoint(rx, ry, w2, h2, ops->anchor); } void TextStyle::getExtents(const char *text, int* ww, int* hh) { TextStyleOptions* ops = (TextStyleOptions*)ops_; int w, h; graphPtr_->getTextExtents(ops->font, text, -1, &w, &h); *ww = w + 2*xPad_; *hh = h + 2*yPad_; } <commit_msg>*** empty log message ***<commit_after>/* * Smithsonian Astrophysical Observatory, Cambridge, MA, USA * This code has been modified under the terms listed below and is made * available under the same terms. */ /* * Copyright 1993-2004 George A Howlett. * * 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 <math.h> #include <tk.h> #include <tkPort.h> #include <tkInt.h> #include "bltGrText.h" #include "bltGraph.h" #include "bltGrPSOutput.h" using namespace Blt; TextStyle::TextStyle(Graph* graphPtr) { ops_ = (TextStyleOptions*)calloc(1, sizeof(TextStyleOptions)); TextStyleOptions* ops = (TextStyleOptions*)ops_; graphPtr_ = graphPtr; manageOptions_ = 1; ops->anchor =TK_ANCHOR_NW; ops->color =NULL; ops->font =NULL; ops->angle =0; ops->justify =TK_JUSTIFY_LEFT; xPad_ = 0; yPad_ = 0; gc_ = NULL; } TextStyle::TextStyle(Graph* graphPtr, TextStyleOptions* ops) { ops_ = (TextStyleOptions*)ops; graphPtr_ = graphPtr; manageOptions_ = 0; xPad_ = 0; yPad_ = 0; gc_ = NULL; } TextStyle::~TextStyle() { // TextStyleOptions* ops = (TextStyleOptions*)ops_; if (gc_) Tk_FreeGC(graphPtr_->display_, gc_); if (manageOptions_) free(ops_); } void TextStyle::drawText(Drawable drawable, const char *text, int x, int y) { TextStyleOptions* ops = (TextStyleOptions*)ops_; if (!text || !(*text)) return; if (!gc_) resetStyle(); int w1, h1; Tk_TextLayout layout = Tk_ComputeTextLayout(ops->font, text, -1, -1, ops->justify, 0, &w1, &h1); Point2d rr = rotateText(x, y, w1, h1); #if (TCL_MAJOR_VERSION == 8) || (TCL_MINOR_VERSION >= 6) TkDrawAngledTextLayout(graphPtr_->display_, drawable, gc_, layout, rr.x, rr.y, ops->angle, 0, -1); #else Tk_DrawTextLayout(graphPtr_->display_, drawable, gc_, layout, rr.x, rr.y, 0, -1); #endif } void TextStyle::drawText2(Drawable drawable, const char *text, int x, int y, int* ww, int* hh) { TextStyleOptions* ops = (TextStyleOptions*)ops_; if (!text || !(*text)) return; if (!gc_) resetStyle(); int w1, h1; Tk_TextLayout layout = Tk_ComputeTextLayout(ops->font, text, -1, -1, ops->justify, 0, &w1, &h1); Point2d rr = rotateText(x, y, w1, h1); #if (TCL_MAJOR_VERSION == 8) || (TCL_MINOR_VERSION >= 6) TkDrawAngledTextLayout(graphPtr_->display_, drawable, gc_, layout, rr.x, rr.y, ops->angle, 0, -1); #else Tk_DrawTextLayout(graphPtr_->display_, drawable, gc_, layout, rr.x, rr.y, 0, -1); #endif float angle = fmod(ops->angle, 360.0); if (angle < 0.0) angle += 360.0; if (angle != 0.0) { double rotWidth, rotHeight; graphPtr_->getBoundingBox(w1, h1, angle, &rotWidth, &rotHeight, NULL); w1 = rotWidth; h1 = rotHeight; } *ww = w1; *hh = h1; } void TextStyle::printText(PSOutput* psPtr, const char *text, int x, int y) { TextStyleOptions* ops = (TextStyleOptions*)ops_; if (!text || !(*text)) return; int w1, h1; Tk_TextLayout layout = Tk_ComputeTextLayout(ops->font, text, -1, -1, ops->justify, 0, &w1, &h1); int xx =0; int yy =0; switch (ops->anchor) { case TK_ANCHOR_NW: xx = 0; yy = 0; break; case TK_ANCHOR_N: xx = 1; yy = 0; break; case TK_ANCHOR_NE: xx = 2; yy = 0; break; case TK_ANCHOR_E: xx = 2; yy = 1; break; case TK_ANCHOR_SE: xx = 2; yy = 2; break; case TK_ANCHOR_S: xx = 1; yy = 2; break; case TK_ANCHOR_SW: xx = 0; yy = 2; break; case TK_ANCHOR_W: xx = 0; yy = 1; break; case TK_ANCHOR_CENTER: xx = 1; yy = 1; break; } const char* justify =NULL; switch (ops->justify) { case TK_JUSTIFY_LEFT: justify = "0"; break; case TK_JUSTIFY_CENTER: justify = "0.5"; break; case TK_JUSTIFY_RIGHT: justify = "1"; break; } psPtr->setFont(ops->font); psPtr->setForeground(ops->color); psPtr->format("%g %d %d [\n", ops->angle, x, y); Tcl_ResetResult(graphPtr_->interp_); Tk_TextLayoutToPostscript(graphPtr_->interp_, layout); psPtr->append(Tcl_GetStringResult(graphPtr_->interp_)); Tcl_ResetResult(graphPtr_->interp_); psPtr->format("] %g %g %s DrawText\n", xx/-2.0, yy/-2.0, justify); } void TextStyle::resetStyle() { TextStyleOptions* ops = (TextStyleOptions*)ops_; unsigned long gcMask; gcMask = GCFont; XGCValues gcValues; gcValues.font = Tk_FontId(ops->font); if (ops->color) { gcMask |= GCForeground; gcValues.foreground = ops->color->pixel; } GC newGC = Tk_GetGC(graphPtr_->tkwin_, gcMask, &gcValues); if (gc_) Tk_FreeGC(graphPtr_->display_, gc_); gc_ = newGC; } Point2d TextStyle::rotateText(int x, int y, int w1, int h1) { TextStyleOptions* ops = (TextStyleOptions*)ops_; // Matrix t0 = Translate(-x,-y); // Matrix t1 = Translate(-w1/2,-h1/2); // Matrix rr = Rotate(angle); // Matrix t2 = Translate(w2/2,h2/2); // Matrix t3 = Translate(x,y); double angle = ops->angle; double ccos = cos(M_PI*angle/180.); double ssin = sin(M_PI*angle/180.); double w2, h2; graphPtr_->getBoundingBox(w1, h1, angle, &w2, &h2, NULL); double x1 = x+w1/2.; double y1 = y+h1/2.; double x2 = w2/2.+x; double y2 = h2/2.+y; double rx = x*ccos + y*ssin + (-x1*ccos -y1*ssin +x2); double ry = -x*ssin + y*ccos + ( x1*ssin -y1*ccos +y2); return graphPtr_->anchorPoint(rx, ry, w2, h2, ops->anchor); } void TextStyle::getExtents(const char *text, int* ww, int* hh) { TextStyleOptions* ops = (TextStyleOptions*)ops_; int w, h; graphPtr_->getTextExtents(ops->font, text, -1, &w, &h); *ww = w + 2*xPad_; *hh = h + 2*yPad_; } <|endoftext|>
<commit_before>/** * @file dtnn_rules_impl.hpp * @author Ryan Curtin * * Implementation of DualTreeKMeansRules. */ #ifndef __MLPACK_METHODS_KMEANS_DTNN_RULES_IMPL_HPP #define __MLPACK_METHODS_KMEANS_DTNN_RULES_IMPL_HPP #include "dtnn_rules.hpp" namespace mlpack { namespace kmeans { template<typename MetricType, typename TreeType> DTNNKMeansRules<MetricType, TreeType>::DTNNKMeansRules( const arma::mat& centroids, const arma::mat& dataset, arma::Col<size_t>& assignments, arma::vec& upperBounds, arma::vec& lowerBounds, MetricType& metric, const std::vector<bool>& prunedPoints, const std::vector<size_t>& oldFromNewCentroids, std::vector<bool>& visited) : centroids(centroids), dataset(dataset), assignments(assignments), upperBounds(upperBounds), lowerBounds(lowerBounds), metric(metric), prunedPoints(prunedPoints), oldFromNewCentroids(oldFromNewCentroids), visited(visited), baseCases(0), scores(0) { // Nothing to do. } template<typename MetricType, typename TreeType> inline force_inline double DTNNKMeansRules<MetricType, TreeType>::BaseCase( const size_t queryIndex, const size_t referenceIndex) { if (prunedPoints[queryIndex]) return 0.0; // Returning 0 shouldn't be a problem. // Any base cases imply that we will get a result. visited[queryIndex] = true; // Calculate the distance. ++baseCases; const double distance = metric.Evaluate(dataset.col(queryIndex), centroids.col(referenceIndex)); if (distance < upperBounds[queryIndex]) { lowerBounds[queryIndex] = upperBounds[queryIndex]; upperBounds[queryIndex] = distance; assignments[queryIndex] = (tree::TreeTraits<TreeType>::RearrangesDataset) ? oldFromNewCentroids[referenceIndex] : referenceIndex; } else if (distance < lowerBounds[queryIndex]) { lowerBounds[queryIndex] = distance; } return distance; } template<typename MetricType, typename TreeType> inline double DTNNKMeansRules<MetricType, TreeType>::Score( const size_t queryIndex, TreeType& /* referenceNode */) { // If the query point has already been pruned, then don't recurse further. if (prunedPoints[queryIndex]) return DBL_MAX; // No pruning at this level (for now). return 0; } template<typename MetricType, typename TreeType> inline double DTNNKMeansRules<MetricType, TreeType>::Score( TreeType& queryNode, TreeType& referenceNode) { if (queryNode.Stat().StaticPruned() == true) return DBL_MAX; // Pruned() for the root node must never be set to size_t(-1). if (queryNode.Stat().Pruned() == size_t(-1)) { queryNode.Stat().Pruned() = queryNode.Parent()->Stat().Pruned(); queryNode.Stat().LowerBound() = queryNode.Parent()->Stat().LowerBound(); queryNode.Stat().Owner() = queryNode.Parent()->Stat().Owner(); } if (queryNode.Stat().Pruned() == centroids.n_cols) { return DBL_MAX; } // Get minimum and maximum distances. math::Range distances = queryNode.RangeDistance(&referenceNode); double score = distances.Lo(); ++scores; if (distances.Lo() > queryNode.Stat().UpperBound()) { // The reference node can own no points in this query node. We may improve // the lower bound on pruned nodes, though. if (distances.Lo() < queryNode.Stat().LowerBound()) queryNode.Stat().LowerBound() = distances.Lo(); // This assumes that reference clusters don't appear elsewhere in the tree. queryNode.Stat().Pruned() += referenceNode.NumDescendants(); score = DBL_MAX; } else if (distances.Hi() < queryNode.Stat().UpperBound()) { // We can improve the best estimate. queryNode.Stat().UpperBound() = distances.Hi(); // If this node has only one descendant, then it may be the owner. if (referenceNode.NumDescendants() == 1) queryNode.Stat().Owner() = (tree::TreeTraits<TreeType>::RearrangesDataset) ? oldFromNewCentroids[referenceNode.Descendant(0)] : referenceNode.Descendant(0); } // Is everything pruned? if (queryNode.Stat().Pruned() == centroids.n_cols - 1) { queryNode.Stat().Pruned() = centroids.n_cols; // Owner() is already set. return DBL_MAX; } return score; } template<typename MetricType, typename TreeType> inline double DTNNKMeansRules<MetricType, TreeType>::Rescore( const size_t /* queryIndex */, TreeType& /* referenceNode */, const double oldScore) { // No rescoring (for now). return oldScore; } template<typename MetricType, typename TreeType> inline double DTNNKMeansRules<MetricType, TreeType>::Rescore( TreeType& /* queryNode */, TreeType& /* referenceNode */, const double oldScore) { // No rescoring (for now). return oldScore; } } // namespace kmeans } // namespace mlpack #endif <commit_msg>Implement Rescore(). Minor speedup.<commit_after>/** * @file dtnn_rules_impl.hpp * @author Ryan Curtin * * Implementation of DualTreeKMeansRules. */ #ifndef __MLPACK_METHODS_KMEANS_DTNN_RULES_IMPL_HPP #define __MLPACK_METHODS_KMEANS_DTNN_RULES_IMPL_HPP #include "dtnn_rules.hpp" namespace mlpack { namespace kmeans { template<typename MetricType, typename TreeType> DTNNKMeansRules<MetricType, TreeType>::DTNNKMeansRules( const arma::mat& centroids, const arma::mat& dataset, arma::Col<size_t>& assignments, arma::vec& upperBounds, arma::vec& lowerBounds, MetricType& metric, const std::vector<bool>& prunedPoints, const std::vector<size_t>& oldFromNewCentroids, std::vector<bool>& visited) : centroids(centroids), dataset(dataset), assignments(assignments), upperBounds(upperBounds), lowerBounds(lowerBounds), metric(metric), prunedPoints(prunedPoints), oldFromNewCentroids(oldFromNewCentroids), visited(visited), baseCases(0), scores(0) { // Nothing to do. } template<typename MetricType, typename TreeType> inline force_inline double DTNNKMeansRules<MetricType, TreeType>::BaseCase( const size_t queryIndex, const size_t referenceIndex) { if (prunedPoints[queryIndex]) return 0.0; // Returning 0 shouldn't be a problem. // Any base cases imply that we will get a result. visited[queryIndex] = true; // Calculate the distance. ++baseCases; const double distance = metric.Evaluate(dataset.col(queryIndex), centroids.col(referenceIndex)); if (distance < upperBounds[queryIndex]) { lowerBounds[queryIndex] = upperBounds[queryIndex]; upperBounds[queryIndex] = distance; assignments[queryIndex] = (tree::TreeTraits<TreeType>::RearrangesDataset) ? oldFromNewCentroids[referenceIndex] : referenceIndex; } else if (distance < lowerBounds[queryIndex]) { lowerBounds[queryIndex] = distance; } return distance; } template<typename MetricType, typename TreeType> inline double DTNNKMeansRules<MetricType, TreeType>::Score( const size_t queryIndex, TreeType& /* referenceNode */) { // If the query point has already been pruned, then don't recurse further. if (prunedPoints[queryIndex]) return DBL_MAX; // No pruning at this level; we're not likely to encounter a single query // point with a reference node.. return 0; } template<typename MetricType, typename TreeType> inline double DTNNKMeansRules<MetricType, TreeType>::Score( TreeType& queryNode, TreeType& referenceNode) { if (queryNode.Stat().StaticPruned() == true) return DBL_MAX; // Pruned() for the root node must never be set to size_t(-1). if (queryNode.Stat().Pruned() == size_t(-1)) { queryNode.Stat().Pruned() = queryNode.Parent()->Stat().Pruned(); queryNode.Stat().LowerBound() = queryNode.Parent()->Stat().LowerBound(); queryNode.Stat().Owner() = queryNode.Parent()->Stat().Owner(); } if (queryNode.Stat().Pruned() == centroids.n_cols) return DBL_MAX; // Get minimum and maximum distances. math::Range distances = queryNode.RangeDistance(&referenceNode); double score = distances.Lo(); ++scores; if (distances.Lo() > queryNode.Stat().UpperBound()) { // The reference node can own no points in this query node. We may improve // the lower bound on pruned nodes, though. if (distances.Lo() < queryNode.Stat().LowerBound()) queryNode.Stat().LowerBound() = distances.Lo(); // This assumes that reference clusters don't appear elsewhere in the tree. queryNode.Stat().Pruned() += referenceNode.NumDescendants(); score = DBL_MAX; } else if (distances.Hi() < queryNode.Stat().UpperBound()) { // We can improve the best estimate. queryNode.Stat().UpperBound() = distances.Hi(); // If this node has only one descendant, then it may be the owner. if (referenceNode.NumDescendants() == 1) queryNode.Stat().Owner() = (tree::TreeTraits<TreeType>::RearrangesDataset) ? oldFromNewCentroids[referenceNode.Descendant(0)] : referenceNode.Descendant(0); } // Is everything pruned? if (queryNode.Stat().Pruned() == centroids.n_cols - 1) { queryNode.Stat().Pruned() = centroids.n_cols; // Owner() is already set. return DBL_MAX; } return score; } template<typename MetricType, typename TreeType> inline double DTNNKMeansRules<MetricType, TreeType>::Rescore( const size_t /* queryIndex */, TreeType& /* referenceNode */, const double oldScore) { // No rescoring (for now). return oldScore; } template<typename MetricType, typename TreeType> inline double DTNNKMeansRules<MetricType, TreeType>::Rescore( TreeType& queryNode, TreeType& referenceNode, const double oldScore) { if (oldScore == DBL_MAX) return DBL_MAX; // It's already pruned. // oldScore contains the minimum distance between queryNode and referenceNode. // In the time since Score() has been called, the upper bound *may* have // tightened. If it has tightened enough, we may prune this node now. if (oldScore > queryNode.Stat().UpperBound()) { // We may still be able to improve the lower bound on pruned nodes. if (oldScore < queryNode.Stat().LowerBound()) queryNode.Stat().LowerBound() = oldScore; // This assumes that reference clusters don't appear elsewhere in the tree. queryNode.Stat().Pruned() += referenceNode.NumDescendants(); return DBL_MAX; } // Also, check if everything has been pruned. if (queryNode.Stat().Pruned() == centroids.n_cols - 1) { queryNode.Stat().Pruned() = centroids.n_cols; // Owner() is already set. return DBL_MAX; } return oldScore; } } // namespace kmeans } // namespace mlpack #endif <|endoftext|>
<commit_before> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkShader.h" static void assert_ifDrawnTo(skiatest::Reporter* reporter, const SkBitmap& bm, bool shouldBeDrawn) { for (int y = 0; y < bm.height(); ++y) { for (int x = 0; x < bm.width(); ++x) { if (shouldBeDrawn) { if (0 == *bm.getAddr32(x, y)) { REPORTER_ASSERT(reporter, false); return; } } else { // should not be drawn if (*bm.getAddr32(x, y)) { REPORTER_ASSERT(reporter, false); return; } } } } } static void test_wacky_bitmapshader(skiatest::Reporter* reporter, int width, int height, bool shouldBeDrawn) { SkBitmap dev; dev.setConfig(SkBitmap::kARGB_8888_Config, 0x56F, 0x4f6); dev.allocPixels(); dev.eraseColor(0); // necessary, so we know if we draw to it SkMatrix matrix; SkCanvas c(dev); matrix.setAll(-119.34097, -43.436558, 93489.945, 43.436558, -119.34097, 123.98426, 0, 0, 1); c.concat(matrix); SkBitmap bm; bm.setConfig(SkBitmap::kARGB_8888_Config, width, height); bm.allocPixels(); bm.eraseColor(SK_ColorRED); SkShader* s = SkShader::CreateBitmapShader(bm, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); matrix.setAll(0.0078740157, 0, 249, 0, 0.0078740157, 239, 0, 0, 1); s->setLocalMatrix(matrix); SkPaint paint; paint.setShader(s)->unref(); SkRect r = SkRect::MakeXYWH(681, 239, 695, 253); c.drawRect(r, paint); assert_ifDrawnTo(reporter, dev, shouldBeDrawn); } /* * Original bug was asserting that the matrix-proc had generated a (Y) value * that was out of range. This led (in the release build) to the sampler-proc * reading memory out-of-bounds of the original bitmap. * * We were numerically overflowing our 16bit coordinates that we communicate * between these two procs. The fixes was in two parts: * * 1. Just don't draw bitmaps larger than 64K-1 in width or height, since we * can't represent those coordinates in our transport format (yet). * 2. Perform an unsigned shift during the calculation, so we don't get * sign-extension bleed when packing the two values (X,Y) into our 32bit * slot. * * This tests exercises the original setup, plus 3 more to ensure that we can, * in fact, handle bitmaps at 64K-1 (assuming we don't exceed the total * memory allocation limit). */ static void test_giantrepeat_crbug118018(skiatest::Reporter* reporter) { static const struct { int fWidth; int fHeight; bool fExpectedToDraw; } gTests[] = { { 0x1b294, 0x7f, false }, // crbug 118018 (width exceeds 64K) { 0xFFFF, 0x7f, true }, // should draw, test max width { 0x7f, 0xFFFF, true }, // should draw, test max height { 0xFFFF, 0xFFFF, false }, // allocation fails (too much RAM) }; for (size_t i = 0; i < SK_ARRAY_COUNT(gTests); ++i) { test_wacky_bitmapshader(reporter, gTests[i].fWidth, gTests[i].fHeight, gTests[i].fExpectedToDraw); } } /////////////////////////////////////////////////////////////////////////////// static void test_nan_antihair(skiatest::Reporter* reporter) { SkBitmap bm; bm.setConfig(SkBitmap::kARGB_8888_Config, 20, 20); bm.allocPixels(); SkCanvas canvas(bm); SkPath path; path.moveTo(0, 0); path.lineTo(10, SK_ScalarNaN); SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); // before our fix to SkScan_Antihair.cpp to check for integral NaN (0x800...) // this would trigger an assert/crash. // // see rev. 3558 canvas.drawPath(path, paint); } static bool check_for_all_zeros(const SkBitmap& bm) { SkAutoLockPixels alp(bm); size_t count = bm.width() * bm.bytesPerPixel(); for (int y = 0; y < bm.height(); y++) { const uint8_t* ptr = reinterpret_cast<const uint8_t*>(bm.getAddr(0, y)); for (size_t i = 0; i < count; i++) { if (ptr[i]) { return false; } } } return true; } static const int gWidth = 256; static const int gHeight = 256; static void create(SkBitmap* bm, SkBitmap::Config config, SkColor color) { bm->setConfig(config, gWidth, gHeight); bm->allocPixels(); bm->eraseColor(color); } static void TestDrawBitmapRect(skiatest::Reporter* reporter) { SkBitmap src, dst; create(&src, SkBitmap::kARGB_8888_Config, 0xFFFFFFFF); create(&dst, SkBitmap::kARGB_8888_Config, 0); SkCanvas canvas(dst); SkIRect srcR = { gWidth, 0, gWidth + 16, 16 }; SkRect dstR = { 0, 0, SkIntToScalar(16), SkIntToScalar(16) }; canvas.drawBitmapRect(src, &srcR, dstR, NULL); // ensure that we draw nothing if srcR does not intersect the bitmap REPORTER_ASSERT(reporter, check_for_all_zeros(dst)); test_nan_antihair(reporter); test_giantrepeat_crbug118018(reporter); } #include "TestClassDef.h" DEFINE_TESTCLASS("DrawBitmapRect", TestDrawBitmapRectClass, TestDrawBitmapRect) <commit_msg>fix fixed-point build<commit_after> /* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkShader.h" #ifdef SK_SCALAR_IS_FLOAT static void assert_ifDrawnTo(skiatest::Reporter* reporter, const SkBitmap& bm, bool shouldBeDrawn) { for (int y = 0; y < bm.height(); ++y) { for (int x = 0; x < bm.width(); ++x) { if (shouldBeDrawn) { if (0 == *bm.getAddr32(x, y)) { REPORTER_ASSERT(reporter, false); return; } } else { // should not be drawn if (*bm.getAddr32(x, y)) { REPORTER_ASSERT(reporter, false); return; } } } } } static void test_wacky_bitmapshader(skiatest::Reporter* reporter, int width, int height, bool shouldBeDrawn) { SkBitmap dev; dev.setConfig(SkBitmap::kARGB_8888_Config, 0x56F, 0x4f6); dev.allocPixels(); dev.eraseColor(0); // necessary, so we know if we draw to it SkMatrix matrix; SkCanvas c(dev); matrix.setAll(-119.34097, -43.436558, 93489.945, 43.436558, -119.34097, 123.98426, 0, 0, 1); c.concat(matrix); SkBitmap bm; bm.setConfig(SkBitmap::kARGB_8888_Config, width, height); bm.allocPixels(); bm.eraseColor(SK_ColorRED); SkShader* s = SkShader::CreateBitmapShader(bm, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode); matrix.setAll(0.0078740157, 0, 249, 0, 0.0078740157, 239, 0, 0, 1); s->setLocalMatrix(matrix); SkPaint paint; paint.setShader(s)->unref(); SkRect r = SkRect::MakeXYWH(681, 239, 695, 253); c.drawRect(r, paint); assert_ifDrawnTo(reporter, dev, shouldBeDrawn); } #endif /* * Original bug was asserting that the matrix-proc had generated a (Y) value * that was out of range. This led (in the release build) to the sampler-proc * reading memory out-of-bounds of the original bitmap. * * We were numerically overflowing our 16bit coordinates that we communicate * between these two procs. The fixes was in two parts: * * 1. Just don't draw bitmaps larger than 64K-1 in width or height, since we * can't represent those coordinates in our transport format (yet). * 2. Perform an unsigned shift during the calculation, so we don't get * sign-extension bleed when packing the two values (X,Y) into our 32bit * slot. * * This tests exercises the original setup, plus 3 more to ensure that we can, * in fact, handle bitmaps at 64K-1 (assuming we don't exceed the total * memory allocation limit). */ static void test_giantrepeat_crbug118018(skiatest::Reporter* reporter) { #ifdef SK_SCALAR_IS_FLOAT static const struct { int fWidth; int fHeight; bool fExpectedToDraw; } gTests[] = { { 0x1b294, 0x7f, false }, // crbug 118018 (width exceeds 64K) { 0xFFFF, 0x7f, true }, // should draw, test max width { 0x7f, 0xFFFF, true }, // should draw, test max height { 0xFFFF, 0xFFFF, false }, // allocation fails (too much RAM) }; for (size_t i = 0; i < SK_ARRAY_COUNT(gTests); ++i) { test_wacky_bitmapshader(reporter, gTests[i].fWidth, gTests[i].fHeight, gTests[i].fExpectedToDraw); } #endif } /////////////////////////////////////////////////////////////////////////////// static void test_nan_antihair(skiatest::Reporter* reporter) { SkBitmap bm; bm.setConfig(SkBitmap::kARGB_8888_Config, 20, 20); bm.allocPixels(); SkCanvas canvas(bm); SkPath path; path.moveTo(0, 0); path.lineTo(10, SK_ScalarNaN); SkPaint paint; paint.setAntiAlias(true); paint.setStyle(SkPaint::kStroke_Style); // before our fix to SkScan_Antihair.cpp to check for integral NaN (0x800...) // this would trigger an assert/crash. // // see rev. 3558 canvas.drawPath(path, paint); } static bool check_for_all_zeros(const SkBitmap& bm) { SkAutoLockPixels alp(bm); size_t count = bm.width() * bm.bytesPerPixel(); for (int y = 0; y < bm.height(); y++) { const uint8_t* ptr = reinterpret_cast<const uint8_t*>(bm.getAddr(0, y)); for (size_t i = 0; i < count; i++) { if (ptr[i]) { return false; } } } return true; } static const int gWidth = 256; static const int gHeight = 256; static void create(SkBitmap* bm, SkBitmap::Config config, SkColor color) { bm->setConfig(config, gWidth, gHeight); bm->allocPixels(); bm->eraseColor(color); } static void TestDrawBitmapRect(skiatest::Reporter* reporter) { SkBitmap src, dst; create(&src, SkBitmap::kARGB_8888_Config, 0xFFFFFFFF); create(&dst, SkBitmap::kARGB_8888_Config, 0); SkCanvas canvas(dst); SkIRect srcR = { gWidth, 0, gWidth + 16, 16 }; SkRect dstR = { 0, 0, SkIntToScalar(16), SkIntToScalar(16) }; canvas.drawBitmapRect(src, &srcR, dstR, NULL); // ensure that we draw nothing if srcR does not intersect the bitmap REPORTER_ASSERT(reporter, check_for_all_zeros(dst)); test_nan_antihair(reporter); test_giantrepeat_crbug118018(reporter); } #include "TestClassDef.h" DEFINE_TESTCLASS("DrawBitmapRect", TestDrawBitmapRectClass, TestDrawBitmapRect) <|endoftext|>
<commit_before>#include "variant_adder.hpp" namespace vg { using namespace std; VariantAdder::VariantAdder(VG& graph) : graph(graph) { // Nothing to do! } // We need a function to grab the index for a path PathIndex& VariantAdder::get_path_index(const string& path_name) { if (!indexes.count(path_name)) { // Not already made. Generate it. indexes.emplace(piecewise_construct, forward_as_tuple(path_name), // Make the key forward_as_tuple(graph, path_name, true)); // Make the PathIndex } return indexes.at(path_name); } void VariantAdder::update_path_indexes(const vector<Translation>& translations) { for (auto& kv : indexes) { // We need to touch every index (IN PLACE!) // Feed each index all the translations, which it will parse into node- // partitioning translations and then apply. kv.second.apply_translations(translations); } } void VariantAdder::add_variants(vcflib::VariantCallFile* vcf) { // We collect all the edits we need to make, and then make them all at // once. vector<Path> edits_to_make; // Make a buffer WindowedVcfBuffer buffer(vcf, variant_range); while(buffer.next()) { // For each variant in its context of nonoverlapping variants vcflib::Variant* variant; vector<vcflib::Variant*> before; vector<vcflib::Variant*> after; tie(before, variant, after) = buffer.get_nonoverlapping(); // Where is it? auto& variant_path_name = variant->sequenceName; auto& variant_path_offset = variant->position; // Already made 0-based by the buffer if (!graph.paths.has_path(variant_path_name)) { // Explode if the path is not in the vg cerr << "error:[vg add] could not find path" << variant_path_name << " in graph" << endl; throw runtime_error("Missing path " + variant_path_name); } // Grab the path index. // It's a reference so it can be updated when we apply translations to all indexes. auto& index = get_path_index(variant_path_name); // Make the list of all the local variants in one vector vector<vcflib::Variant*> local_variants{before}; local_variants.push_back(variant); copy(after.begin(), after.end(), back_inserter(local_variants)); #ifdef debug cerr << "Local variants: "; for (auto* v : local_variants) { cerr << v->sequenceName << ":" << v->position << " "; } cerr << endl; #endif // Where does the group start? size_t group_start = local_variants.front()->position; // And where does it end (exclusive)? size_t group_end = local_variants.back()->position + local_variants.back()->ref.size(); // Get the leading and trailing ref sequence on either side of this group of variants (to pin the outside variants down). // On the left we want either flank_range bases or all the bases before the first base in the group. size_t left_context_length = max(min((int64_t)flank_range, (int64_t) group_start - (int64_t) 1), (int64_t) 0); // On the right we want either flank_range bases or all the bases after the last base in the group. size_t right_context_length = min(index.sequence.size() - group_end, (size_t) flank_range); string left_context = index.sequence.substr(group_start - left_context_length, left_context_length); string right_context = index.sequence.substr(group_end, right_context_length); // Get the unique haplotypes auto haplotypes = get_unique_haplotypes(local_variants); #ifdef debug cerr << "Have " << haplotypes.size() << " haplotypes for variant " << *variant << endl; #endif for (auto& haplotype : haplotypes) { // For each haplotype #ifdef debug cerr << "Haplotype "; for (auto& allele_number : haplotype) { cerr << allele_number << " "; } cerr << endl; #endif // Make its combined string stringstream to_align; to_align << left_context << haplotype_to_string(haplotype, local_variants) << right_context; #ifdef debug cerr << "Align " << to_align.str() << endl; #endif // Find the node that the variant falls on right now NodeSide center = index.at_position(variant_path_offset); #ifdef debug cerr << "Center node: " << center << endl; #endif // Extract its graph context for realignment VG context; graph.nonoverlapping_node_context_without_paths(graph.get_node(center.node), context); // TODO: how many nodes should this be? // TODO: write/copy the search from xg so we can do this by node length. graph.expand_context(context, 10, false); // Do the alignment Alignment aln = context.align(to_align.str(), 0, false, false, 30); #ifdef debug cerr << "Alignment: " << pb2json(aln) << endl; #endif // Make this path's edits to the original graph and get the // translations. auto translations = graph.edit(vector<Path>{aln.path()}); #ifdef debug cerr << "Translations: " << endl; for (auto& t : translations) { cerr << "\t" << pb2json(t) << endl; } #endif // Apply each translation to all the path indexes that might touch // the nodes it changed. update_path_indexes(translations); } } } set<vector<int>> VariantAdder::get_unique_haplotypes(const vector<vcflib::Variant*>& variants) const { set<vector<int>> haplotypes; if (variants.empty()) { // Nothing's there return haplotypes; } for (auto& sample_name : variants.front()->sampleNames) { // For every sample // Make its haplotype(s) on the region. We have a map from haplotype // number to actual vector. We'll tack stuff on the ends when they are // used, then throw out any that aren't full-length. map<size_t, vector<int>> sample_haplotypes; for (auto* variant : variants) { // Get the genotype for each sample auto genotype = variant->getGenotype(sample_name); // Fake it being phased replace(genotype.begin(), genotype.end(), '/', '|'); auto alts = vcflib::decomposePhasedGenotype(genotype); for (size_t phase = 0; phase < alts.size(); phase++) { // Stick each allele number at the end of its appropriate phase sample_haplotypes[phase].push_back(alts[phase]); } } for (auto& kv : sample_haplotypes) { auto& haplotype = kv.second; // For every haplotype in this sample if (haplotype.size() != variants.size()) { // If it's not the full length, it means some variants don't // have it. Skip. continue; } // Otherwise, add it to the set of observed haplotypes haplotypes.insert(haplotype); } } // After processing all the samples, return the unique haplotypes return haplotypes; } string VariantAdder::haplotype_to_string(const vector<int>& haplotype, const vector<vcflib::Variant*>& variants) { // We'll fill this in with variants and separating sequences. stringstream result; // These lists need to be in 1 to 1 correspondence assert(haplotype.size() == variants.size()); if (variants.empty()) { // No variants means no string representation. return ""; } // Do the first variant result << variants.front()->alleles.at(haplotype.at(0)); for (size_t i = 1; i < variants.size(); i++) { // For each subsequent variant auto* variant = variants.at(i); auto* last_variant = variants.at(i - 1); // Do the intervening sequence. // Where does that sequence start? size_t sep_start = last_variant->position + last_variant->ref.size(); // And how long does it run? size_t sep_length = variant->position - sep_start; // Pull out the separator sequence and tack it on. result << get_path_index(variant->sequenceName).sequence.substr(sep_start, sep_length); // Then put the appropriate allele of this variant result << variant->alleles.at(haplotype.at(i)); } return result.str(); } } <commit_msg>Fix lonely left base from vg add<commit_after>#include "variant_adder.hpp" namespace vg { using namespace std; VariantAdder::VariantAdder(VG& graph) : graph(graph) { // Nothing to do! } // We need a function to grab the index for a path PathIndex& VariantAdder::get_path_index(const string& path_name) { if (!indexes.count(path_name)) { // Not already made. Generate it. indexes.emplace(piecewise_construct, forward_as_tuple(path_name), // Make the key forward_as_tuple(graph, path_name, true)); // Make the PathIndex } return indexes.at(path_name); } void VariantAdder::update_path_indexes(const vector<Translation>& translations) { for (auto& kv : indexes) { // We need to touch every index (IN PLACE!) // Feed each index all the translations, which it will parse into node- // partitioning translations and then apply. kv.second.apply_translations(translations); } } void VariantAdder::add_variants(vcflib::VariantCallFile* vcf) { // We collect all the edits we need to make, and then make them all at // once. vector<Path> edits_to_make; // Make a buffer WindowedVcfBuffer buffer(vcf, variant_range); while(buffer.next()) { // For each variant in its context of nonoverlapping variants vcflib::Variant* variant; vector<vcflib::Variant*> before; vector<vcflib::Variant*> after; tie(before, variant, after) = buffer.get_nonoverlapping(); // Where is it? auto& variant_path_name = variant->sequenceName; auto& variant_path_offset = variant->position; // Already made 0-based by the buffer if (!graph.paths.has_path(variant_path_name)) { // Explode if the path is not in the vg cerr << "error:[vg add] could not find path" << variant_path_name << " in graph" << endl; throw runtime_error("Missing path " + variant_path_name); } // Grab the path index. // It's a reference so it can be updated when we apply translations to all indexes. auto& index = get_path_index(variant_path_name); // Make the list of all the local variants in one vector vector<vcflib::Variant*> local_variants{before}; local_variants.push_back(variant); copy(after.begin(), after.end(), back_inserter(local_variants)); #ifdef debug cerr << "Local variants: "; for (auto* v : local_variants) { cerr << v->sequenceName << ":" << v->position << " "; } cerr << endl; #endif // Where does the group start? size_t group_start = local_variants.front()->position; // And where does it end (exclusive)? size_t group_end = local_variants.back()->position + local_variants.back()->ref.size(); // Get the leading and trailing ref sequence on either side of this group of variants (to pin the outside variants down). // On the left we want either flank_range bases or all the bases before the first base in the group. size_t left_context_length = max(min((int64_t)flank_range, (int64_t) group_start), (int64_t) 0); // On the right we want either flank_range bases or all the bases after the last base in the group. size_t right_context_length = min(index.sequence.size() - group_end, (size_t) flank_range); string left_context = index.sequence.substr(group_start - left_context_length, left_context_length); string right_context = index.sequence.substr(group_end, right_context_length); // Get the unique haplotypes auto haplotypes = get_unique_haplotypes(local_variants); #ifdef debug cerr << "Have " << haplotypes.size() << " haplotypes for variant " << *variant << endl; #endif for (auto& haplotype : haplotypes) { // For each haplotype #ifdef debug cerr << "Haplotype "; for (auto& allele_number : haplotype) { cerr << allele_number << " "; } cerr << endl; #endif // Make its combined string stringstream to_align; to_align << left_context << haplotype_to_string(haplotype, local_variants) << right_context; #ifdef debug cerr << "Align " << to_align.str() << endl; #endif // Find the node that the variant falls on right now NodeSide center = index.at_position(variant_path_offset); #ifdef debug cerr << "Center node: " << center << endl; #endif // Extract its graph context for realignment VG context; graph.nonoverlapping_node_context_without_paths(graph.get_node(center.node), context); // TODO: how many nodes should this be? // TODO: write/copy the search from xg so we can do this by node length. graph.expand_context(context, 10, false); // Do the alignment Alignment aln = context.align(to_align.str(), 0, false, false, 30); #ifdef debug cerr << "Alignment: " << pb2json(aln) << endl; #endif // Make this path's edits to the original graph and get the // translations. auto translations = graph.edit(vector<Path>{aln.path()}); #ifdef debug cerr << "Translations: " << endl; for (auto& t : translations) { cerr << "\t" << pb2json(t) << endl; } #endif // Apply each translation to all the path indexes that might touch // the nodes it changed. update_path_indexes(translations); } } } set<vector<int>> VariantAdder::get_unique_haplotypes(const vector<vcflib::Variant*>& variants) const { set<vector<int>> haplotypes; if (variants.empty()) { // Nothing's there return haplotypes; } for (auto& sample_name : variants.front()->sampleNames) { // For every sample // Make its haplotype(s) on the region. We have a map from haplotype // number to actual vector. We'll tack stuff on the ends when they are // used, then throw out any that aren't full-length. map<size_t, vector<int>> sample_haplotypes; for (auto* variant : variants) { // Get the genotype for each sample auto genotype = variant->getGenotype(sample_name); // Fake it being phased replace(genotype.begin(), genotype.end(), '/', '|'); auto alts = vcflib::decomposePhasedGenotype(genotype); for (size_t phase = 0; phase < alts.size(); phase++) { // Stick each allele number at the end of its appropriate phase sample_haplotypes[phase].push_back(alts[phase]); } } for (auto& kv : sample_haplotypes) { auto& haplotype = kv.second; // For every haplotype in this sample if (haplotype.size() != variants.size()) { // If it's not the full length, it means some variants don't // have it. Skip. continue; } // Otherwise, add it to the set of observed haplotypes haplotypes.insert(haplotype); } } // After processing all the samples, return the unique haplotypes return haplotypes; } string VariantAdder::haplotype_to_string(const vector<int>& haplotype, const vector<vcflib::Variant*>& variants) { // We'll fill this in with variants and separating sequences. stringstream result; // These lists need to be in 1 to 1 correspondence assert(haplotype.size() == variants.size()); if (variants.empty()) { // No variants means no string representation. return ""; } // Do the first variant result << variants.front()->alleles.at(haplotype.at(0)); for (size_t i = 1; i < variants.size(); i++) { // For each subsequent variant auto* variant = variants.at(i); auto* last_variant = variants.at(i - 1); // Do the intervening sequence. // Where does that sequence start? size_t sep_start = last_variant->position + last_variant->ref.size(); // And how long does it run? size_t sep_length = variant->position - sep_start; // Pull out the separator sequence and tack it on. result << get_path_index(variant->sequenceName).sequence.substr(sep_start, sep_length); // Then put the appropriate allele of this variant result << variant->alleles.at(haplotype.at(i)); } return result.str(); } } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "compressor.h" #include "hash.h" #include "pubkey.h" #include "script/standard.h" bool CScriptCompressor::IsToKeyID(CKeyID &hash) const { if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 && script[2] == 20 && script[23] == OP_EQUALVERIFY && script[24] == OP_CHECKSIG) { memcpy(&hash, &script[3], 20); return true; } return false; } bool CScriptCompressor::IsToScriptID(CScriptID &hash) const { if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20 && script[22] == OP_EQUAL) { memcpy(&hash, &script[2], 20); return true; } return false; } bool CScriptCompressor::IsToPubKey(CPubKey &pubkey) const { if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG && (script[1] == 0x02 || script[1] == 0x03)) { pubkey.Set(&script[1], &script[34]); return true; } if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG && script[1] == 0x04) { pubkey.Set(&script[1], &script[66]); return pubkey.IsFullyValid(); // if not fully valid, a case that would not be compressible } return false; } bool CScriptCompressor::Compress(std::vector<unsigned char> &out) const { CKeyID keyID; if (IsToKeyID(keyID)) { out.resize(21); out[0] = 0x00; memcpy(&out[1], &keyID, 20); return true; } CScriptID scriptID; if (IsToScriptID(scriptID)) { out.resize(21); out[0] = 0x01; memcpy(&out[1], &scriptID, 20); return true; } CPubKey pubkey; if (IsToPubKey(pubkey)) { out.resize(33); memcpy(&out[1], &pubkey[1], 32); if (pubkey[0] == 0x02 || pubkey[0] == 0x03) { out[0] = pubkey[0]; return true; } else if (pubkey[0] == 0x04) { out[0] = 0x04 | (pubkey[64] & 0x01); return true; } } return false; } unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const { if (nSize == 0 || nSize == 1) return 20; if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5) return 32; return 0; } bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char> &in) { switch(nSize) { case 0x00: script.resize(25); script[0] = OP_DUP; script[1] = OP_HASH160; script[2] = 20; memcpy(&script[3], &in[0], 20); script[23] = OP_EQUALVERIFY; script[24] = OP_CHECKSIG; return true; case 0x01: script.resize(23); script[0] = OP_HASH160; script[1] = 20; memcpy(&script[2], &in[0], 20); script[22] = OP_EQUAL; return true; case 0x02: case 0x03: script.resize(35); script[0] = 33; script[1] = nSize; memcpy(&script[2], &in[0], 32); script[34] = OP_CHECKSIG; return true; case 0x04: case 0x05: unsigned char vch[33] = {}; vch[0] = nSize - 2; memcpy(&vch[1], &in[0], 32); CPubKey pubkey(&vch[0], &vch[33]); if (!pubkey.Decompress()) return false; assert(pubkey.size() == 65); script.resize(67); script[0] = 65; memcpy(&script[1], pubkey.begin(), 65); script[66] = OP_CHECKSIG; return true; } return false; } // Amount compression: // * If the amount is 0, output 0 // * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9) // * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10) // * call the result n // * output 1 + 10*(9*n + d - 1) + e // * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9 // (this is decodable, as d is in [1-9] and e is in [0-9]) uint64_t CTxOutCompressor::CompressAmount(uint64_t n) { if (n == 0) return 0; int e = 0; while (((n % 10) == 0) && e < 9) { n /= 10; e++; } if (e < 9) { int d = (n % 10); assert(d >= 1 && d <= 9); n /= 10; return 1 + (n*9 + d - 1)*10 + e; } else { return 1 + (n - 1)*10 + 9; } } uint64_t CTxOutCompressor::DecompressAmount(uint64_t x) { // x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9 if (x == 0) return 0; x--; // x = 10*(9*n + d - 1) + e int e = x % 10; x /= 10; uint64_t n = 0; if (e < 9) { // x = 9*n + d - 1 int d = (x % 9) + 1; x /= 9; // x = n n = x*10 + d; } else { n = x+1; } while (e) { n *= 10; e--; } return n; } <commit_msg>Delete compressor.cpp<commit_after><|endoftext|>
<commit_before>#include <vector> #include <iostream> #include "controller.h" #include "query.h" #include "split.h" #include "item.h" const std::string Controller::ADD_CMD = "ADD"; const std::string Controller::DEL_CMD = "DEL"; const std::string Controller::QUERY_CMD = "QUERY"; const std::string Controller::WQUERY_CMD = "WQUERY"; Controller::Controller( std::shared_ptr<QueryParser> queryParser, std::shared_ptr<MemoryService> memoryService, std::ostream &os) : out(os) { this->queryParser = queryParser; this->memoryService = memoryService; } void Controller::call(const std::string &command) { size_t i = command.find(' '); if (i == std::string::npos) { throw std::invalid_argument("Could not parse command!"); } std::string action = command.substr(0, i); if (action == Controller::ADD_CMD) { this->add(command); } else if (action == Controller::DEL_CMD) { this->del(command); } else if (action == Controller::QUERY_CMD) { this->query(command); } else if (action == Controller::WQUERY_CMD) { this->query(command); } else { throw std::invalid_argument("Invalid command!"); } } void Controller::add(const std::string &command) { std::vector<std::string> tokens = split(command, ' ', 5); ItemType type = itemtype(tokens[1]); double score = std::stod(tokens[3]); Item item { type, tokens[2], score, tokens[4] }; this->memoryService->add(item); } void Controller::del(const std::string &command) { std::vector<std::string> tokens = split(command, ' '); this->memoryService->del(tokens[1]); } void Controller::query(const std::string &command) { Query q = this->queryParser->parse(command); std::vector<std::string> results = this->memoryService->query(q); for (std::string &id : results) { this->out << id << " "; } this->out << std::endl; } <commit_msg>Output fix.<commit_after>#include <vector> #include <iostream> #include "controller.h" #include "query.h" #include "split.h" #include "item.h" const std::string Controller::ADD_CMD = "ADD"; const std::string Controller::DEL_CMD = "DEL"; const std::string Controller::QUERY_CMD = "QUERY"; const std::string Controller::WQUERY_CMD = "WQUERY"; Controller::Controller( std::shared_ptr<QueryParser> queryParser, std::shared_ptr<MemoryService> memoryService, std::ostream &os) : out(os) { this->queryParser = queryParser; this->memoryService = memoryService; } void Controller::call(const std::string &command) { size_t i = command.find(' '); if (i == std::string::npos) { throw std::invalid_argument("Could not parse command!"); } std::string action = command.substr(0, i); if (action == Controller::ADD_CMD) { this->add(command); } else if (action == Controller::DEL_CMD) { this->del(command); } else if (action == Controller::QUERY_CMD) { this->query(command); } else if (action == Controller::WQUERY_CMD) { this->query(command); } else { throw std::invalid_argument("Invalid command!"); } } void Controller::add(const std::string &command) { std::vector<std::string> tokens = split(command, ' ', 5); ItemType type = itemtype(tokens[1]); double score = std::stod(tokens[3]); Item item { type, tokens[2], score, tokens[4] }; this->memoryService->add(item); } void Controller::del(const std::string &command) { std::vector<std::string> tokens = split(command, ' '); this->memoryService->del(tokens[1]); } void Controller::query(const std::string &command) { Query q = this->queryParser->parse(command); std::vector<std::string> results = this->memoryService->query(q); std::string space = ""; for (std::string &id : results) { this->out << space << id; space = " "; } this->out << std::endl; } <|endoftext|>
<commit_before>#pragma once #include <iostream> #include "binary.hxx" namespace despairagus { namespace bitwisetrie { using std::cout; using std::ostream; template <typename A> class bitwisetrie { template<typename B> using conref = const B &; using bitA = std::bitset<sizeof(A) << 3>; using byte = unsigned char; using bit = bool; explicit bitwisetrie(void) = delete; }; } }<commit_msg>use access specifiers<commit_after>#pragma once #include <iostream> #include "binary.hxx" namespace despairagus { namespace bitwisetrie { using std::cout; using std::ostream; template <typename A> class bitwisetrie { template<typename B> using conref = const B &; using bitA = std::bitset<sizeof(A) << 3>; using byte = unsigned char; using bit = bool; public: explicit bitwisetrie(void) = delete; private: }; } }<|endoftext|>
<commit_before>#pragma once #include <iostream> #include "binary.hxx" namespace despairagus { namespace bitwisetrie { using std::cout; using std::ostream; template <typename A> class bitwisetrie final { template<typename B> using conref = const B &; using bitA = std::bitset<sizeof(A) << 3>; using byte = unsigned char; using bit = bool; public: explicit bitwisetrie(void) = delete; private: }; } }<commit_msg>add bitnode header<commit_after>#pragma once #include <iostream> #include "binary.hxx" #include "bitnode.hxx" namespace despairagus { namespace bitwisetrie { using std::cout; using std::ostream; template <typename A> class bitwisetrie final { template<typename B> using conref = const B &; using bitA = std::bitset<sizeof(A) << 3>; using byte = unsigned char; using bit = bool; public: explicit bitwisetrie(void) = delete; private: }; } }<|endoftext|>
<commit_before>/* * ctapdev.cc * * Created on: 24.06.2013 * Author: andreas */ #include <ctapdev.h> using namespace dptmap; extern int errno; ctapdev::ctapdev( cnetdev_owner *netdev_owner, std::string const& devname, rofl::cmacaddr const& hwaddr) : cnetdev(netdev_owner, devname), fd(-1) { tap_open(devname, hwaddr); } ctapdev::~ctapdev() { tap_close(); } void ctapdev::tap_open(std::string const& devname, rofl::cmacaddr const& hwaddr) { try { struct ifreq ifr; int rc; if (fd > -1) { tap_close(); } if ((fd = open("/dev/net/tun", O_RDWR|O_NONBLOCK)) < 0) { throw eTapDevOpenFailed(); } memset(&ifr, 0, sizeof(ifr)); /* Flags: IFF_TUN - TUN device (no Ethernet headers) * IFF_TAP - TAP device * * IFF_NO_PI - Do not provide packet information */ ifr.ifr_flags = IFF_TAP | IFF_NO_PI; strncpy(ifr.ifr_name, devname.c_str(), IFNAMSIZ); if ((rc = ioctl(fd, TUNSETIFF, (void *)&ifr)) < 0) { close(fd); throw eTapDevIoctlFailed(); } enable_interface(); set_hwaddr(hwaddr); //netdev_owner->netdev_open(this); register_filedesc_r(fd); } catch (eTapDevOpenFailed& e) { fprintf(stderr, "ctapdev::tap_open() open() failed: dev[%s] (%d:%s)\n", devname.c_str(), errno, strerror(errno)); throw eNetDevCritical(); } catch (eTapDevIoctlFailed& e) { fprintf(stderr, "ctapdev::tap_open() ioctl() failed: dev[%s] (%d:%s)\n", devname.c_str(), errno, strerror(errno)); throw eNetDevCritical(); } } void ctapdev::tap_close() { if (fd == -1) { return; } //netdev_owner->netdev_close(this); disable_interface(); deregister_filedesc_r(fd); close(fd); fd = -1; } void ctapdev::enqueue(rofl::cpacket *pkt) { if (fd == -1) { cpacketpool::get_instance().release_pkt(pkt); return; } // store pkt in outgoing queue pout_queue.push_back(pkt); register_filedesc_w(fd); } void ctapdev::enqueue(std::vector<rofl::cpacket*> pkts) { if (fd == -1) { for (std::vector<rofl::cpacket*>::iterator it = pkts.begin(); it != pkts.end(); ++it) { cpacketpool::get_instance().release_pkt((*it)); } return; } // store pkts in outgoing queue for (std::vector<rofl::cpacket*>::iterator it = pkts.begin(); it != pkts.end(); ++it) { pout_queue.push_back(*it); } register_filedesc_w(fd); } void ctapdev::handle_revent(int fd) { rofl::cpacket *pkt = (rofl::cpacket*)0; try { rofl::cmemory mem(1518); int rc = read(fd, mem.somem(), mem.memlen()); // error occured (or non-blocking) if (rc < 0) { switch (errno) { case EAGAIN: throw eNetDevAgain(); default: throw eNetDevCritical(); } } else { pkt = cpacketpool::get_instance().acquire_pkt(); pkt->unpack(OFPP_CONTROLLER, mem.somem(), rc); netdev_owner->enqueue(this, pkt); } } catch (ePacketPoolExhausted& e) { fprintf(stderr, "ctapdev::handle_revent() packet pool exhausted, no idle slots available\n"); } catch (eNetDevAgain& e) { fprintf(stderr, "ctapdev::handle_revent() (%d:%s) => " "retry later\n", errno, strerror(errno)); cpacketpool::get_instance().release_pkt(pkt); } catch (eNetDevCritical& e) { fprintf(stderr, "ctapdev::handle_revent() critical error (%d:%s): " "calling self-destruction\n", errno, strerror(errno)); cpacketpool::get_instance().release_pkt(pkt); delete this; return; } } void ctapdev::handle_wevent(int fd) { rofl::cpacket * pkt = (rofl::cpacket*)0; try { while (not pout_queue.empty()) { pkt = pout_queue.front(); int rc = 0; if ((rc = write(fd, pkt->soframe(), pkt->framelen())) < 0) { switch (errno) { case EAGAIN: throw eNetDevAgain(); default: throw eNetDevCritical(); } } cpacketpool::get_instance().release_pkt(pkt); pout_queue.pop_front(); } if (pout_queue.empty()) { deregister_filedesc_w(fd); } } catch (eNetDevAgain& e) { // keep fd in wfds fprintf(stderr, "ctapdev::handle_wevent() (%d:%s) => " "retry later\n", errno, strerror(errno)); } catch (eNetDevCritical& e) { fprintf(stderr, "ctapdev::handle_wevent() critical error (%d:%s): " "calling self-destruction\n", errno, strerror(errno)); cpacketpool::get_instance().release_pkt(pkt); delete this; return; } } <commit_msg>ctapdev: changing a mac address must occur before enabling the interface ... oh, really? :)<commit_after>/* * ctapdev.cc * * Created on: 24.06.2013 * Author: andreas */ #include <ctapdev.h> using namespace dptmap; extern int errno; ctapdev::ctapdev( cnetdev_owner *netdev_owner, std::string const& devname, rofl::cmacaddr const& hwaddr) : cnetdev(netdev_owner, devname), fd(-1) { tap_open(devname, hwaddr); } ctapdev::~ctapdev() { tap_close(); } void ctapdev::tap_open(std::string const& devname, rofl::cmacaddr const& hwaddr) { try { struct ifreq ifr; int rc; if (fd > -1) { tap_close(); } if ((fd = open("/dev/net/tun", O_RDWR|O_NONBLOCK)) < 0) { throw eTapDevOpenFailed(); } memset(&ifr, 0, sizeof(ifr)); /* Flags: IFF_TUN - TUN device (no Ethernet headers) * IFF_TAP - TAP device * * IFF_NO_PI - Do not provide packet information */ ifr.ifr_flags = IFF_TAP | IFF_NO_PI; strncpy(ifr.ifr_name, devname.c_str(), IFNAMSIZ); if ((rc = ioctl(fd, TUNSETIFF, (void *)&ifr)) < 0) { close(fd); throw eTapDevIoctlFailed(); } set_hwaddr(hwaddr); enable_interface(); //netdev_owner->netdev_open(this); register_filedesc_r(fd); } catch (eTapDevOpenFailed& e) { fprintf(stderr, "ctapdev::tap_open() open() failed: dev[%s] (%d:%s)\n", devname.c_str(), errno, strerror(errno)); throw eNetDevCritical(); } catch (eTapDevIoctlFailed& e) { fprintf(stderr, "ctapdev::tap_open() ioctl() failed: dev[%s] (%d:%s)\n", devname.c_str(), errno, strerror(errno)); throw eNetDevCritical(); } } void ctapdev::tap_close() { if (fd == -1) { return; } //netdev_owner->netdev_close(this); disable_interface(); deregister_filedesc_r(fd); close(fd); fd = -1; } void ctapdev::enqueue(rofl::cpacket *pkt) { if (fd == -1) { cpacketpool::get_instance().release_pkt(pkt); return; } // store pkt in outgoing queue pout_queue.push_back(pkt); register_filedesc_w(fd); } void ctapdev::enqueue(std::vector<rofl::cpacket*> pkts) { if (fd == -1) { for (std::vector<rofl::cpacket*>::iterator it = pkts.begin(); it != pkts.end(); ++it) { cpacketpool::get_instance().release_pkt((*it)); } return; } // store pkts in outgoing queue for (std::vector<rofl::cpacket*>::iterator it = pkts.begin(); it != pkts.end(); ++it) { pout_queue.push_back(*it); } register_filedesc_w(fd); } void ctapdev::handle_revent(int fd) { rofl::cpacket *pkt = (rofl::cpacket*)0; try { rofl::cmemory mem(1518); int rc = read(fd, mem.somem(), mem.memlen()); // error occured (or non-blocking) if (rc < 0) { switch (errno) { case EAGAIN: throw eNetDevAgain(); default: throw eNetDevCritical(); } } else { pkt = cpacketpool::get_instance().acquire_pkt(); pkt->unpack(OFPP_CONTROLLER, mem.somem(), rc); netdev_owner->enqueue(this, pkt); } } catch (ePacketPoolExhausted& e) { fprintf(stderr, "ctapdev::handle_revent() packet pool exhausted, no idle slots available\n"); } catch (eNetDevAgain& e) { fprintf(stderr, "ctapdev::handle_revent() (%d:%s) => " "retry later\n", errno, strerror(errno)); cpacketpool::get_instance().release_pkt(pkt); } catch (eNetDevCritical& e) { fprintf(stderr, "ctapdev::handle_revent() critical error (%d:%s): " "calling self-destruction\n", errno, strerror(errno)); cpacketpool::get_instance().release_pkt(pkt); delete this; return; } } void ctapdev::handle_wevent(int fd) { rofl::cpacket * pkt = (rofl::cpacket*)0; try { while (not pout_queue.empty()) { pkt = pout_queue.front(); int rc = 0; if ((rc = write(fd, pkt->soframe(), pkt->framelen())) < 0) { switch (errno) { case EAGAIN: throw eNetDevAgain(); default: throw eNetDevCritical(); } } cpacketpool::get_instance().release_pkt(pkt); pout_queue.pop_front(); } if (pout_queue.empty()) { deregister_filedesc_w(fd); } } catch (eNetDevAgain& e) { // keep fd in wfds fprintf(stderr, "ctapdev::handle_wevent() (%d:%s) => " "retry later\n", errno, strerror(errno)); } catch (eNetDevCritical& e) { fprintf(stderr, "ctapdev::handle_wevent() critical error (%d:%s): " "calling self-destruction\n", errno, strerror(errno)); cpacketpool::get_instance().release_pkt(pkt); delete this; return; } } <|endoftext|>
<commit_before>#include <map> #include <ros/ros.h> #include <control_msgs/FollowJointTrajectoryAction.h> #include <actionlib/server/simple_action_server.h> #include <std_msgs/Float32.h> std::map<std::string, ros::Publisher> g_gripper_servo_angle_pub; class GripperAction { protected: ros::NodeHandle nh_; // NodeHandle instance mustbe created before this line, actionlib::SimpleActionServer<control_msgs::FollowJointTrajectoryAction> as_; std::string action_name_, side_; // create messages that are used to publisssh feedback/result control_msgs::FollowJointTrajectoryFeedback feedback_; control_msgs::FollowJointTrajectoryResult result_; public: GripperAction(std::string name, std::string side); void executeCB(const control_msgs::FollowJointTrajectoryGoalConstPtr& goal); }; GripperAction::GripperAction(std::string name, std::string side): as_(nh_, name, boost::bind(&GripperAction::executeCB, this, _1), false), action_name_(name), side_(side) { as_.start(); } void GripperAction::executeCB(const control_msgs::FollowJointTrajectoryGoalConstPtr& goal) { bool success = true; std::string node_name(ros::this_node::getName()); ROS_INFO("%s: Executing requested joint trajectory for %s gripper", node_name.c_str(), side_.c_str()); // Wait for the specified execution time, if not provided use now ros::Time start_time = goal->trajectory.header.stamp; if (start_time == ros::Time(0, 0)) start_time = ros::Time::now(); ros::Duration wait = start_time - ros::Time::now(); if (wait > ros::Duration(0)) wait.sleep(); ros::Time start_segment_time = start_time; float prev_rad = 0; // Loop until end of trajectory for (int i = 0; i < goal->trajectory.points.size(); i++) { ros::Duration segment_time = goal->trajectory.points[i].time_from_start; if ( i > 0 ) segment_time = segment_time - goal->trajectory.points[i-1].time_from_start; if (as_.isPreemptRequested()) { ROS_INFO("%s: Preempted for %s gripper", node_name.c_str(), side_.c_str()); as_.setPreempted(); success = false; break; } if (!ros::ok()) { ROS_INFO("%s: Aborted for %s gripper", node_name.c_str(), side_.c_str()); as_.setAborted(); return; } float rad = goal->trajectory.points[i].positions[0]; std_msgs::Float32 angle_msg; // Publish feedbacks until next point ros::Rate feedback_rate(100); // 10 msec ros::Time now; // float velocity = 0; if ( i < goal->trajectory.points.size() - 1) { float d0 = rad - prev_rad; float d1 = goal->trajectory.points[i+1].positions[0]; float t0 = segment_time.toSec(); float t1 = goal->trajectory.points[i+1].time_from_start.toSec(); float v0 = d0/t0; float v1 = d1/t1; if ( v0 * v1 >= 0 ) { velocity = 0.5 * (v0 + v1); } else { velocity = 0; } } static float x = prev_rad; static float v = 0; static float a = 0; float gx = rad; float gv = velocity; float ga = 0; float target_t = segment_time.toSec(); float A=(gx-(x+v*target_t+(a/2.0)*target_t*target_t))/(target_t*target_t*target_t); float B=(gv-(v+a*target_t))/(target_t*target_t); float C=(ga-a)/target_t; float a0=x; float a1=v; float a2=a/2.0; float a3=10*A-4*B+0.5*C; float a4=(-15*A+7*B-C)/target_t; float a5=(6*A-3*B+0.5*C)/(target_t*target_t); do { // see seqplay::playPattern in https://github.com/fkanehiro/hrpsys-base/blob/master/rtc/SequencePlayer/seqplay.cpp now = ros::Time::now(); // hoff arbib code is copied from https://github.com/fkanehiro/hrpsys-base/blob/master/rtc/SequencePlayer/interpolator.cpp float t = (now - start_segment_time).toSec(); // angle_msg.data = (rad - prev_rad) * (now - start_segment_time).toSec()/segment_time.toSec() + prev_rad; // linear angle_msg.data = a0+a1*t+a2*t*t+a3*t*t*t+a4*t*t*t*t+a5*t*t*t*t*t; g_gripper_servo_angle_pub[side_].publish(angle_msg); feedback_rate.sleep(); control_msgs::FollowJointTrajectoryFeedback feedback_; feedback_.joint_names.push_back(goal->trajectory.joint_names[0]); feedback_.desired.positions.resize(1); feedback_.actual.positions.resize(1); feedback_.error.positions.resize(1); feedback_.desired.positions[0] = rad; feedback_.actual.positions[0] = rad; feedback_.error.positions[0] = 0; feedback_.desired.time_from_start = now - start_time; feedback_.actual.time_from_start = now - start_time; feedback_.error.time_from_start = now - start_time; feedback_.header.stamp = ros::Time::now(); as_.publishFeedback(feedback_); } while (ros::ok() && now < (start_time + goal->trajectory.points[i].time_from_start)); start_segment_time = now; prev_rad = rad; x = gx; v = gv; a = ga; } control_msgs::FollowJointTrajectoryResult result_; if (success) { ROS_INFO("%s: Succeeded for %s gripper", node_name.c_str(), side_.c_str()); result_.error_code = result_.SUCCESSFUL; as_.setSucceeded(result_); } } int main(int argc, char** argv) { ros::init(argc, argv, "gripper_joint_trajectory_action_server"); ros::NodeHandle n; g_gripper_servo_angle_pub["right"] = n.advertise<std_msgs::Float32>("gripper_front/limb/right/servo/angle", 10); g_gripper_servo_angle_pub["left"] = n.advertise<std_msgs::Float32>("gripper_front/limb/left/servo/angle", 10); GripperAction right_server("gripper_front/limb/right/follow_joint_trajectory", "right"); GripperAction left_server("gripper_front/limb/left/follow_joint_trajectory", "left"); ros::spin(); return 0; } <commit_msg>include pub/sub within c++ object<commit_after>#include <map> #include <ros/ros.h> #include <control_msgs/FollowJointTrajectoryAction.h> #include <actionlib/server/simple_action_server.h> #include <std_msgs/Float32.h> class GripperAction { protected: ros::NodeHandle nh_; // member variables must be initialized in the order they're declared in. // http://stackoverflow.com/questions/12222417/why-should-i-initialize-member-variables-in-the-order-theyre-declared-in std::string side_; std::string ns_name_; actionlib::SimpleActionServer<control_msgs::FollowJointTrajectoryAction> as_; // create messages that are used to publisssh feedback/result control_msgs::FollowJointTrajectoryFeedback feedback_; control_msgs::FollowJointTrajectoryResult result_; ros::Publisher gripper_servo_angle_pub_; ros::Subscriber gripper_servo_angle_sub_; float angle_state_; public: GripperAction(std::string name, std::string side); void executeCB(const control_msgs::FollowJointTrajectoryGoalConstPtr& goal); void angle_stateCB(const std_msgs::Float32::ConstPtr& angle); }; GripperAction::GripperAction(std::string name, std::string side): side_(side), ns_name_(name), as_(nh_, ns_name_+side_ + "follow_joint_trajectory", boost::bind(&GripperAction::executeCB, this, _1), false) { angle_state_ = 0; gripper_servo_angle_pub_ = nh_.advertise<std_msgs::Float32>(ns_name_ + side_ + "/servo/angle", 10); gripper_servo_angle_sub_ = nh_.subscribe<std_msgs::Float32>(ns_name_ + side_ + "/servo/angle/state", 10, &GripperAction::angle_stateCB, this); as_.start(); } void GripperAction::angle_stateCB(const std_msgs::Float32::ConstPtr& angle) { angle_state_ = angle->data; } void GripperAction::executeCB(const control_msgs::FollowJointTrajectoryGoalConstPtr& goal) { bool success = true; std::string node_name(ros::this_node::getName()); ROS_INFO("%s: Executing requested joint trajectory for %s gripper", node_name.c_str(), side_.c_str()); // Wait for the specified execution time, if not provided use now ros::Time start_time = goal->trajectory.header.stamp; if (start_time == ros::Time(0, 0)) start_time = ros::Time::now(); ros::Duration wait = start_time - ros::Time::now(); if (wait > ros::Duration(0)) wait.sleep(); ros::Time start_segment_time = start_time; float prev_rad = angle_state_; // Loop until end of trajectory for (int i = 0; i < goal->trajectory.points.size(); i++) { ros::Duration segment_time = goal->trajectory.points[i].time_from_start; if ( i > 0 ) segment_time = segment_time - goal->trajectory.points[i-1].time_from_start; if (as_.isPreemptRequested()) { ROS_INFO("%s: Preempted for %s gripper", node_name.c_str(), side_.c_str()); as_.setPreempted(); success = false; break; } if (!ros::ok()) { ROS_INFO("%s: Aborted for %s gripper", node_name.c_str(), side_.c_str()); as_.setAborted(); return; } float rad = goal->trajectory.points[i].positions[0]; std_msgs::Float32 angle_msg; // Publish feedbacks until next point ros::Rate feedback_rate(100); // 10 msec ros::Time now; // float velocity = 0; if ( i < goal->trajectory.points.size() - 1) { float d0 = rad - prev_rad; float d1 = goal->trajectory.points[i+1].positions[0]; float t0 = segment_time.toSec(); float t1 = goal->trajectory.points[i+1].time_from_start.toSec(); float v0 = d0/t0; float v1 = d1/t1; if ( v0 * v1 >= 0 ) { velocity = 0.5 * (v0 + v1); } else { velocity = 0; } } float x = prev_rad; float v = 0; float a = 0; float gx = rad; float gv = velocity; float ga = 0; float target_t = segment_time.toSec(); float A=(gx-(x+v*target_t+(a/2.0)*target_t*target_t))/(target_t*target_t*target_t); float B=(gv-(v+a*target_t))/(target_t*target_t); float C=(ga-a)/target_t; float a0=x; float a1=v; float a2=a/2.0; float a3=10*A-4*B+0.5*C; float a4=(-15*A+7*B-C)/target_t; float a5=(6*A-3*B+0.5*C)/(target_t*target_t); do { // see seqplay::playPattern in https://github.com/fkanehiro/hrpsys-base/blob/master/rtc/SequencePlayer/seqplay.cpp now = ros::Time::now(); // hoff arbib code is copied from https://github.com/fkanehiro/hrpsys-base/blob/master/rtc/SequencePlayer/interpolator.cpp float t = (now - start_segment_time).toSec(); // angle_msg.data = (rad - prev_rad) * (now - start_segment_time).toSec()/segment_time.toSec() + prev_rad; // linear angle_msg.data = a0+a1*t+a2*t*t+a3*t*t*t+a4*t*t*t*t+a5*t*t*t*t*t; gripper_servo_angle_pub_.publish(angle_msg); feedback_rate.sleep(); control_msgs::FollowJointTrajectoryFeedback feedback_; feedback_.joint_names.push_back(goal->trajectory.joint_names[0]); feedback_.desired.positions.resize(1); feedback_.actual.positions.resize(1); feedback_.error.positions.resize(1); feedback_.desired.positions[0] = rad; feedback_.actual.positions[0] = rad; feedback_.error.positions[0] = 0; feedback_.desired.time_from_start = now - start_time; feedback_.actual.time_from_start = now - start_time; feedback_.error.time_from_start = now - start_time; feedback_.header.stamp = ros::Time::now(); as_.publishFeedback(feedback_); } while (ros::ok() && now < (start_time + goal->trajectory.points[i].time_from_start)); start_segment_time = now; prev_rad = rad; x = gx; v = gv; a = ga; } angle_state_ = prev_rad; // just in case anlge_stae is not updated; control_msgs::FollowJointTrajectoryResult result_; if (success) { ROS_INFO("%s: Succeeded for %s gripper", node_name.c_str(), side_.c_str()); result_.error_code = result_.SUCCESSFUL; as_.setSucceeded(result_); } } int main(int argc, char** argv) { ros::init(argc, argv, "gripper_joint_trajectory_action_server"); GripperAction right_server("gripper_front/limb/", "right/"); GripperAction left_server("gripper_front/limb/", "left/"); ros::spin(); return 0; } <|endoftext|>
<commit_before>// std includes #include <iostream> // Qt includes #include <QDebug> #include <QTreeView> #include <QTabBar> #include <QSettings> #include <QAction> #include <QModelIndex> #include <QCheckBox> // ctkDICOMCore includes #include "ctkDICOMDatabase.h" #include "ctkDICOMIndexer.h" // ctkDICOMWidgets includes #include "ctkDICOMModel.h" #include "ctkDICOMAppWidget.h" #include "ctkDICOMQueryResultsTabWidget.h" #include "ui_ctkDICOMAppWidget.h" #include "ctkDirectoryButton.h" #include "ctkFileDialog.h" #include "ctkDICOMQueryRetrieveWidget.h" #include "ctkDICOMImportWidget.h" //logger #include <ctkLogger.h> static ctkLogger logger("org.commontk.DICOM.Widgets.ctkDICOMAppWidget"); //---------------------------------------------------------------------------- class ctkDICOMAppWidgetPrivate: public Ui_ctkDICOMAppWidget { public: ctkDICOMAppWidgetPrivate(); ctkFileDialog* ImportDialog; ctkDICOMQueryRetrieveWidget* QueryRetrieveWidget; QSharedPointer<ctkDICOMDatabase> DICOMDatabase; ctkDICOMModel DICOMModel; QSharedPointer<ctkDICOMIndexer> DICOMIndexer; }; //---------------------------------------------------------------------------- // ctkDICOMAppWidgetPrivate methods ctkDICOMAppWidgetPrivate::ctkDICOMAppWidgetPrivate(){ DICOMDatabase = QSharedPointer<ctkDICOMDatabase> (new ctkDICOMDatabase); DICOMIndexer = QSharedPointer<ctkDICOMIndexer> (new ctkDICOMIndexer); } //---------------------------------------------------------------------------- // ctkDICOMAppWidget methods //---------------------------------------------------------------------------- ctkDICOMAppWidget::ctkDICOMAppWidget(QWidget* _parent):Superclass(_parent), d_ptr(new ctkDICOMAppWidgetPrivate) { Q_D(ctkDICOMAppWidget); d->setupUi(this); //Set toolbar button style d->toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); //Initialize Q/R widget d->QueryRetrieveWidget = new ctkDICOMQueryRetrieveWidget(); connect(d->directoryButton, SIGNAL(directoryChanged(const QString&)), this, SLOT(setDatabaseDirectory(const QString&))); //Initialize import widget d->ImportDialog = new ctkFileDialog(); QCheckBox* importCheckbox = new QCheckBox("Copy on import", d->ImportDialog); d->ImportDialog->setBottomWidget(importCheckbox); d->ImportDialog->setFileMode(QFileDialog::Directory); d->ImportDialog->setLabelText(QFileDialog::Accept,"Import"); d->ImportDialog->setWindowTitle("Import DICOM files from directory ..."); d->ImportDialog->setWindowModality(Qt::ApplicationModal); //Set thumbnails width in thumbnail widget //d->thumbnailsWidget->setThumbnailWidth(128); //Test add thumbnails //d->thumbnailsWidget->addTestThumbnail(); //connect signal and slots connect(d->treeView, SIGNAL(clicked(const QModelIndex&)), this, SLOT(onDICOMModelSelected(const QModelIndex &))); connect(d->thumbnailsWidget, SIGNAL(selected(const ctkDICOMThumbnailWidget&)), this, SLOT(onThumbnailSelected(const ctkDICOMThumbnailWidget&))); connect(d->ImportDialog, SIGNAL(fileSelected(QString)),this,SLOT(onImportDirectory(QString))); } //---------------------------------------------------------------------------- ctkDICOMAppWidget::~ctkDICOMAppWidget() { Q_D(ctkDICOMAppWidget); d->QueryRetrieveWidget->deleteLater(); d->ImportDialog->deleteLater(); } //---------------------------------------------------------------------------- void ctkDICOMAppWidget::setDatabaseDirectory(const QString& directory) { Q_D(ctkDICOMAppWidget); QSettings settings; settings.setValue("DatabaseDirectory", directory); settings.sync(); //close the active DICOM database d->DICOMDatabase->closeDatabase(); //open DICOM database on the directory QString databaseFileName = directory + QString("/ctkDICOM.sql"); try { d->DICOMDatabase->openDatabase( databaseFileName ); } catch (std::exception e) { std::cerr << "Database error: " << qPrintable(d->DICOMDatabase->lastError()) << "\n"; d->DICOMDatabase->closeDatabase(); return; } d->DICOMModel.setDatabase(d->DICOMDatabase->database()); d->treeView->setModel(&d->DICOMModel); //pass DICOM database instance to Import widget // d->ImportDialog->setDICOMDatabase(d->DICOMDatabase); d->QueryRetrieveWidget->setRetrieveDatabase(d->DICOMDatabase); } void ctkDICOMAppWidget::onAddToDatabase() { //Q_D(ctkDICOMAppWidget); //d-> } //---------------------------------------------------------------------------- void ctkDICOMAppWidget::onImport(){ Q_D(ctkDICOMAppWidget); d->ImportDialog->show(); d->ImportDialog->raise(); } void ctkDICOMAppWidget::onExport(){ } void ctkDICOMAppWidget::onQuery(){ Q_D(ctkDICOMAppWidget); d->QueryRetrieveWidget->show(); d->QueryRetrieveWidget->raise(); } void ctkDICOMAppWidget::onDICOMModelSelected(const QModelIndex& index){ Q_D(ctkDICOMAppWidget); //TODO: update thumbnails and previewer d->thumbnailsWidget->setModelIndex(index); } void ctkDICOMAppWidget::onThumbnailSelected(const ctkDICOMThumbnailWidget& widget){ //TODO: update previewer } void ctkDICOMAppWidget::onImportDirectory(QString directory) { Q_D(ctkDICOMAppWidget); if (QDir(directory).exists()) { QCheckBox* copyOnImport = qobject_cast<QCheckBox*>(d->ImportDialog->bottomWidget()); QString targetDirectory; if (copyOnImport->isEnabled()) { targetDirectory = d->DICOMDatabase->databaseDirectory(); } d->DICOMIndexer->addDirectory(*d->DICOMDatabase,directory,targetDirectory); d->DICOMModel.reset(); } } <commit_msg>Show thumbnail of selected image in preview window<commit_after>// std includes #include <iostream> // Qt includes #include <QDebug> #include <QTreeView> #include <QTabBar> #include <QSettings> #include <QAction> #include <QModelIndex> #include <QCheckBox> // ctkDICOMCore includes #include "ctkDICOMDatabase.h" #include "ctkDICOMIndexer.h" // ctkDICOMWidgets includes #include "ctkDICOMModel.h" #include "ctkDICOMAppWidget.h" #include "ctkDICOMQueryResultsTabWidget.h" #include "ui_ctkDICOMAppWidget.h" #include "ctkDirectoryButton.h" #include "ctkFileDialog.h" #include "ctkDICOMQueryRetrieveWidget.h" #include "ctkDICOMImportWidget.h" //logger #include <ctkLogger.h> static ctkLogger logger("org.commontk.DICOM.Widgets.ctkDICOMAppWidget"); //---------------------------------------------------------------------------- class ctkDICOMAppWidgetPrivate: public Ui_ctkDICOMAppWidget { public: ctkDICOMAppWidgetPrivate(); ctkFileDialog* ImportDialog; ctkDICOMQueryRetrieveWidget* QueryRetrieveWidget; QSharedPointer<ctkDICOMDatabase> DICOMDatabase; ctkDICOMModel DICOMModel; QSharedPointer<ctkDICOMIndexer> DICOMIndexer; }; //---------------------------------------------------------------------------- // ctkDICOMAppWidgetPrivate methods ctkDICOMAppWidgetPrivate::ctkDICOMAppWidgetPrivate(){ DICOMDatabase = QSharedPointer<ctkDICOMDatabase> (new ctkDICOMDatabase); DICOMIndexer = QSharedPointer<ctkDICOMIndexer> (new ctkDICOMIndexer); } //---------------------------------------------------------------------------- // ctkDICOMAppWidget methods //---------------------------------------------------------------------------- ctkDICOMAppWidget::ctkDICOMAppWidget(QWidget* _parent):Superclass(_parent), d_ptr(new ctkDICOMAppWidgetPrivate) { Q_D(ctkDICOMAppWidget); d->setupUi(this); //Set toolbar button style d->toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon); //Initialize Q/R widget d->QueryRetrieveWidget = new ctkDICOMQueryRetrieveWidget(); connect(d->directoryButton, SIGNAL(directoryChanged(const QString&)), this, SLOT(setDatabaseDirectory(const QString&))); //Initialize import widget d->ImportDialog = new ctkFileDialog(); QCheckBox* importCheckbox = new QCheckBox("Copy on import", d->ImportDialog); d->ImportDialog->setBottomWidget(importCheckbox); d->ImportDialog->setFileMode(QFileDialog::Directory); d->ImportDialog->setLabelText(QFileDialog::Accept,"Import"); d->ImportDialog->setWindowTitle("Import DICOM files from directory ..."); d->ImportDialog->setWindowModality(Qt::ApplicationModal); //Set thumbnails width in thumbnail widget //d->thumbnailsWidget->setThumbnailWidth(128); //Test add thumbnails //d->thumbnailsWidget->addTestThumbnail(); //connect signal and slots connect(d->treeView, SIGNAL(clicked(const QModelIndex&)), this, SLOT(onDICOMModelSelected(const QModelIndex &))); connect(d->thumbnailsWidget, SIGNAL(selected(const ctkDICOMThumbnailWidget&)), this, SLOT(onThumbnailSelected(const ctkDICOMThumbnailWidget&))); connect(d->ImportDialog, SIGNAL(fileSelected(QString)),this,SLOT(onImportDirectory(QString))); connect(d->DICOMDatabase.data(), SIGNAL( databaseChanged() ), &(d->DICOMModel), SLOT( reset() ) ); } //---------------------------------------------------------------------------- ctkDICOMAppWidget::~ctkDICOMAppWidget() { Q_D(ctkDICOMAppWidget); d->QueryRetrieveWidget->deleteLater(); d->ImportDialog->deleteLater(); } //---------------------------------------------------------------------------- void ctkDICOMAppWidget::setDatabaseDirectory(const QString& directory) { Q_D(ctkDICOMAppWidget); QSettings settings; settings.setValue("DatabaseDirectory", directory); settings.sync(); //close the active DICOM database d->DICOMDatabase->closeDatabase(); //open DICOM database on the directory QString databaseFileName = directory + QString("/ctkDICOM.sql"); try { d->DICOMDatabase->openDatabase( databaseFileName ); } catch (std::exception e) { std::cerr << "Database error: " << qPrintable(d->DICOMDatabase->lastError()) << "\n"; d->DICOMDatabase->closeDatabase(); return; } d->DICOMModel.setDatabase(d->DICOMDatabase->database()); d->treeView->setModel(&d->DICOMModel); //pass DICOM database instance to Import widget // d->ImportDialog->setDICOMDatabase(d->DICOMDatabase); d->QueryRetrieveWidget->setRetrieveDatabase(d->DICOMDatabase); } void ctkDICOMAppWidget::onAddToDatabase() { //Q_D(ctkDICOMAppWidget); //d-> } //---------------------------------------------------------------------------- void ctkDICOMAppWidget::onImport(){ Q_D(ctkDICOMAppWidget); d->ImportDialog->show(); d->ImportDialog->raise(); } void ctkDICOMAppWidget::onExport(){ } void ctkDICOMAppWidget::onQuery(){ Q_D(ctkDICOMAppWidget); d->QueryRetrieveWidget->show(); d->QueryRetrieveWidget->raise(); } void ctkDICOMAppWidget::onDICOMModelSelected(const QModelIndex& index) { Q_D(ctkDICOMAppWidget); //TODO: update thumbnails and previewer d->thumbnailsWidget->setModelIndex(index); // TODO: this could check the type of the model entries QString thumbnailPath = d->DICOMDatabase->databaseDirectory(); thumbnailPath.append("/thumbs/").append(d->DICOMModel.data(index.parent().parent() ,ctkDICOMModel::UIDRole).toString()); thumbnailPath.append("/").append(d->DICOMModel.data(index.parent() ,ctkDICOMModel::UIDRole).toString()); thumbnailPath.append("/").append(d->DICOMModel.data(index ,ctkDICOMModel::UIDRole).toString()); thumbnailPath.append(".png"); if (QFile(thumbnailPath).exists()) { d->imagePreview->setPixmap(QPixmap(thumbnailPath)); } else { d->imagePreview->setText("No preview"); } } void ctkDICOMAppWidget::onThumbnailSelected(const ctkDICOMThumbnailWidget& widget){ //TODO: update previewer } void ctkDICOMAppWidget::onImportDirectory(QString directory) { Q_D(ctkDICOMAppWidget); if (QDir(directory).exists()) { QCheckBox* copyOnImport = qobject_cast<QCheckBox*>(d->ImportDialog->bottomWidget()); QString targetDirectory; if (copyOnImport->isEnabled()) { targetDirectory = d->DICOMDatabase->databaseDirectory(); } d->DICOMIndexer->addDirectory(*d->DICOMDatabase,directory,targetDirectory); d->DICOMModel.reset(); } } <|endoftext|>
<commit_before>#ifndef RINGBUFFER_H #define RINGBUFFER_H #include <cassert> #include <boost/circular_buffer.hpp> #include "contrib/pa_ringbuffer.h" #include "errors.hpp" /** * Abstraction over a ring buffer. * * This generic abstract class represents a general concept of a ring buffer * for samples. It can be implemented, for example, by adapters over the * PortAudio or Boost ring buffers. * * Note that all quantities are represented in terms of sample counts, not * the underlying representation RepT. Implementations should ensure that they * implement the virtual methods of this class in terms of the former and not * the latter. */ template <typename RepT, typename SampleCountT> class RingBuffer { public: /** * The current write capacity. * * @return The number of samples this ring buffer has space to store. */ virtual SampleCountT WriteCapacity() const = 0; /** * The current read capacity. * * @return The number of samples available in this ring buffer. */ virtual SampleCountT ReadCapacity() const = 0; /** * Writes samples from an array into the ring buffer. * * To write one sample, pass a count of 1 and take a pointer to the * sample variable. * * Note that start pointer is not constant. This is because the * underlying implementation of the ring buffer might not guarantee * that the array is left untouched. * * @param start The start of the array buffer from which we write * samples. Must not be nullptr. * @param count The number of samples to write. This must not exceed * the minimum of WriteCapacity() and the length of the * array. * * @return The number of samples written, which should not exceed count. */ virtual SampleCountT Write(RepT *start, SampleCountT count) = 0; /** * Reads samples from the ring buffer into an array. * * To read one sample, pass a count of 1 and take a pointer to the * sample variable. * * @param start The start of the array buffer to which we write samples. * Must not be nullptr. * @param count The number of samples to read. This must not exceed the * minimum of ReadCapacity() and the length of the array. * * @return The number of samples read, which should not exceed count. */ virtual SampleCountT Read(RepT *start, SampleCountT count) = 0; /** * Empties the ring buffer. */ virtual void Flush() = 0; }; /** * Implementation of RingBuffer using the Boost circular buffer. * * This is currently experimental and has known audio glitches when used. * Here be undiscovered bugs. */ template <typename T1, typename T2, int P> class BoostRingBuffer : public RingBuffer<T1, T2> { public: BoostRingBuffer(int size = sizeof(T1)) { this->rb = new boost::circular_buffer<char>((1 << P) * size); this->size = size; } ~BoostRingBuffer() { assert(this->rb != nullptr); delete this->rb; } T2 WriteCapacity() const { return static_cast<T2>(this->rb->reserve() / this->size); } T2 ReadCapacity() const { return static_cast<T2>(this->rb->size() / this->size); } T2 Write(T1 *start, T2 count) { T2 i; for (i = 0; i < count * this->size; i++) { this->rb->push_back(start[i]); } return (i + 1) / this->size; } T2 Read(T1 *start, T2 count) { T2 i; for (i = 0; i < count * this->size; i++) { start[i] = this->rb->front(); this->rb->pop_front(); } return (i + 1) / this->size; } void Flush() { this->rb->clear(); } private: boost::circular_buffer<char> *rb; ///< The internal Boost ring buffer. int size; ///< The size of one sample, in bytes. }; /** * Implementation of RingBuffer using the PortAudio C ring buffer. * * This is stable and performs well, but, as it is C code, necessitates some * hoop jumping to integrate and could do with being replaced with a native * solution. * * The PortAudio ring buffer is provided in the contrib/ directory. */ template <typename T1, typename T2, int P> class PaRingBuffer : public RingBuffer<T1, T2> { public: /** * Constructs a PaRingBuffer. * @param size The size of one element in the ring buffer. */ PaRingBuffer(int size = sizeof(T1)) { this->rb = new PaUtilRingBuffer; this->buffer = new char[(1 << P) * size]; if (PaUtil_InitializeRingBuffer( this->rb, size, static_cast<ring_buffer_size_t>(1 << P), this->buffer) != 0) { throw Error(ErrorCode::INTERNAL_ERROR, "ringbuf failed to init"); } } ~PaRingBuffer() { assert(this->rb != nullptr); delete this->rb; assert(this->buffer != nullptr); delete[] this->buffer; } T2 WriteCapacity() const { return CountCast(PaUtil_GetRingBufferWriteAvailable(this->rb)); } T2 ReadCapacity() const { return CountCast(PaUtil_GetRingBufferReadAvailable(this->rb)); } T2 Write(T1 *start, T2 count) { return CountCast(PaUtil_WriteRingBuffer( this->rb, start, static_cast<ring_buffer_size_t>(count))); } T2 Read(T1 *start, T2 count) { return CountCast(PaUtil_ReadRingBuffer( this->rb, start, static_cast<ring_buffer_size_t>(count))); } void Flush() { PaUtil_FlushRingBuffer(this->rb); } private: char *buffer; ///< The array used by the ringbuffer. PaUtilRingBuffer *rb; ///< The internal PortAudio ringbuffer. /** * Converts a ring buffer size into an external size. * @param count The size/count in PortAudio form. * @return The size/count after casting to T2. */ T2 CountCast(ring_buffer_size_t count) const { return static_cast<T2>(count); } }; #endif // RINGBUFFER_H <commit_msg>Eliminate redundancy in Boost buffer.<commit_after>#ifndef RINGBUFFER_H #define RINGBUFFER_H #include <cassert> #include <boost/circular_buffer.hpp> #include "contrib/pa_ringbuffer.h" #include "errors.hpp" /** * Abstraction over a ring buffer. * * This generic abstract class represents a general concept of a ring buffer * for samples. It can be implemented, for example, by adapters over the * PortAudio or Boost ring buffers. * * Note that all quantities are represented in terms of sample counts, not * the underlying representation RepT. Implementations should ensure that they * implement the virtual methods of this class in terms of the former and not * the latter. */ template <typename RepT, typename SampleCountT> class RingBuffer { public: /** * The current write capacity. * * @return The number of samples this ring buffer has space to store. */ virtual SampleCountT WriteCapacity() const = 0; /** * The current read capacity. * * @return The number of samples available in this ring buffer. */ virtual SampleCountT ReadCapacity() const = 0; /** * Writes samples from an array into the ring buffer. * * To write one sample, pass a count of 1 and take a pointer to the * sample variable. * * Note that start pointer is not constant. This is because the * underlying implementation of the ring buffer might not guarantee * that the array is left untouched. * * @param start The start of the array buffer from which we write * samples. Must not be nullptr. * @param count The number of samples to write. This must not exceed * the minimum of WriteCapacity() and the length of the * array. * * @return The number of samples written, which should not exceed count. */ virtual SampleCountT Write(RepT *start, SampleCountT count) = 0; /** * Reads samples from the ring buffer into an array. * * To read one sample, pass a count of 1 and take a pointer to the * sample variable. * * @param start The start of the array buffer to which we write samples. * Must not be nullptr. * @param count The number of samples to read. This must not exceed the * minimum of ReadCapacity() and the length of the array. * * @return The number of samples read, which should not exceed count. */ virtual SampleCountT Read(RepT *start, SampleCountT count) = 0; /** * Empties the ring buffer. */ virtual void Flush() = 0; }; /** * Implementation of RingBuffer using the Boost circular buffer. * * This is currently experimental and has known audio glitches when used. * Here be undiscovered bugs. */ template <typename T1, typename T2, int P> class BoostRingBuffer : public RingBuffer<T1, T2> { public: BoostRingBuffer(int size = sizeof(T1)) { this->rb = new boost::circular_buffer<char>((1 << P) * size); this->size = size; } ~BoostRingBuffer() { assert(this->rb != nullptr); delete this->rb; } T2 WriteCapacity() const { return static_cast<T2>(this->rb->reserve() / this->size); } T2 ReadCapacity() const { return static_cast<T2>(this->rb->size() / this->size); } T2 Write(T1 *start, T2 count) { return OnBuffer(start, count, [this](T1 *e) { this->rb->push_back(e); }); } T2 Read(T1 *start, T2 count) { return OnBuffer(start, count, [this](T1 *e) { *e = this->rb->front(); this->rb->pop_front(); }); } void Flush() { this->rb->clear(); } private: boost::circular_buffer<T1> *rb; ///< The internal Boost ring buffer. int size; ///< The size of one sample, in bytes. /** * Transfers between this ring buffer and an external array buffer. * @param start The start of the array buffer. * @param count The number of samples in the array buffer. * @param f A function to perform on each position in the array * buffer. * @return The number of samples affected in the array buffer. */ T2 OnBuffer(T1 *start, T2 count, std::function<void(T1 *)> f) { T2 i; for (i = 0; i < count * this->size; i++) { f(start + i); } return (i + 1) / this->size; } }; /** * Implementation of RingBuffer using the PortAudio C ring buffer. * * This is stable and performs well, but, as it is C code, necessitates some * hoop jumping to integrate and could do with being replaced with a native * solution. * * The PortAudio ring buffer is provided in the contrib/ directory. */ template <typename T1, typename T2, int P> class PaRingBuffer : public RingBuffer<T1, T2> { public: /** * Constructs a PaRingBuffer. * @param size The size of one element in the ring buffer. */ PaRingBuffer(int size = sizeof(T1)) { this->rb = new PaUtilRingBuffer; this->buffer = new char[(1 << P) * size]; if (PaUtil_InitializeRingBuffer( this->rb, size, static_cast<ring_buffer_size_t>(1 << P), this->buffer) != 0) { throw Error(ErrorCode::INTERNAL_ERROR, "ringbuf failed to init"); } } ~PaRingBuffer() { assert(this->rb != nullptr); delete this->rb; assert(this->buffer != nullptr); delete[] this->buffer; } T2 WriteCapacity() const { return CountCast(PaUtil_GetRingBufferWriteAvailable(this->rb)); } T2 ReadCapacity() const { return CountCast(PaUtil_GetRingBufferReadAvailable(this->rb)); } T2 Write(T1 *start, T2 count) { return CountCast(PaUtil_WriteRingBuffer( this->rb, start, static_cast<ring_buffer_size_t>(count))); } T2 Read(T1 *start, T2 count) { return CountCast(PaUtil_ReadRingBuffer( this->rb, start, static_cast<ring_buffer_size_t>(count))); } void Flush() { PaUtil_FlushRingBuffer(this->rb); } private: char *buffer; ///< The array used by the ringbuffer. PaUtilRingBuffer *rb; ///< The internal PortAudio ringbuffer. /** * Converts a ring buffer size into an external size. * @param count The size/count in PortAudio form. * @return The size/count after casting to T2. */ T2 CountCast(ring_buffer_size_t count) const { return static_cast<T2>(count); } }; #endif // RINGBUFFER_H <|endoftext|>
<commit_before>#include "BasicAIModule.h" using namespace BWAPI; void BasicAIModule::onStart() { this->showManagerAssignments=false; if (Broodwar->isReplay()) return; // Enable some cheat flags Broodwar->enableFlag(Flag::UserInput); //Broodwar->enableFlag(Flag::CompleteMapInformation); BWTA::readMap(); BWTA::analyze(); this->analyzed=true; this->buildManager = new BuildManager(&this->arbitrator); this->techManager = new TechManager(&this->arbitrator); this->upgradeManager = new UpgradeManager(&this->arbitrator); this->scoutManager = new ScoutManager(&this->arbitrator); this->workerManager = new WorkerManager(&this->arbitrator); this->buildOrderManager = new BuildOrderManager(this->buildManager,this->techManager,this->upgradeManager,this->workerManager); this->baseManager = new BaseManager(); this->supplyManager = new SupplyManager(); this->defenseManager = new DefenseManager(&this->arbitrator); this->informationManager = new InformationManager(); this->borderManager = new BorderManager(); this->unitGroupManager = new UnitGroupManager(); this->enhancedUI = new EnhancedUI(); this->supplyManager->setBuildManager(this->buildManager); this->supplyManager->setBuildOrderManager(this->buildOrderManager); this->techManager->setBuildingPlacer(this->buildManager->getBuildingPlacer()); this->upgradeManager->setBuildingPlacer(this->buildManager->getBuildingPlacer()); this->workerManager->setBaseManager(this->baseManager); this->workerManager->setBuildOrderManager(this->buildOrderManager); this->baseManager->setBuildOrderManager(this->buildOrderManager); this->borderManager->setInformationManager(this->informationManager); this->baseManager->setBorderManager(this->borderManager); this->defenseManager->setBorderManager(this->borderManager); BWAPI::Race race = Broodwar->self()->getRace(); BWAPI::Race enemyRace = Broodwar->enemy()->getRace(); BWAPI::UnitType workerType=*(race.getWorker()); double minDist; BWTA::BaseLocation* natural=NULL; BWTA::BaseLocation* home=BWTA::getStartLocation(Broodwar->self()); for(std::set<BWTA::BaseLocation*>::const_iterator b=BWTA::getBaseLocations().begin();b!=BWTA::getBaseLocations().end();b++) { if (*b==home) continue; double dist=home->getGroundDistance(*b); if (dist>0) { if (natural==NULL || dist<minDist) { minDist=dist; natural=*b; } } } this->buildOrderManager->enableDependencyResolver(); //make the basic production facility if (race == Races::Zerg) { //send an overlord out if Zerg this->scoutManager->setScoutCount(1); //12 hatch this->buildOrderManager->build(12,workerType,80); this->baseManager->expand(natural,79); this->buildOrderManager->build(20,workerType,78); this->buildOrderManager->buildAdditional(1,UnitTypes::Zerg_Spawning_Pool,60); this->buildOrderManager->buildAdditional(3,UnitTypes::Zerg_Zergling,82); } else if (race == Races::Terran) { this->buildOrderManager->build(20,workerType,80); if (enemyRace == Races::Zerg) { this->buildOrderManager->buildAdditional(1,UnitTypes::Terran_Barracks,60); this->buildOrderManager->buildAdditional(9,UnitTypes::Terran_Marine,45); this->buildOrderManager->buildAdditional(1,UnitTypes::Terran_Refinery,42); this->buildOrderManager->buildAdditional(1,UnitTypes::Terran_Barracks,40); this->buildOrderManager->buildAdditional(1,UnitTypes::Terran_Academy,39); this->buildOrderManager->buildAdditional(9,UnitTypes::Terran_Medic,38); this->buildOrderManager->research(TechTypes::Stim_Packs,35); this->buildOrderManager->research(TechTypes::Tank_Siege_Mode,35); this->buildOrderManager->buildAdditional(3,UnitTypes::Terran_Siege_Tank_Tank_Mode,34); this->buildOrderManager->buildAdditional(2,UnitTypes::Terran_Science_Vessel,30); this->buildOrderManager->research(TechTypes::Irradiate,30); this->buildOrderManager->upgrade(1,UpgradeTypes::Terran_Infantry_Weapons,20); this->buildOrderManager->build(3,UnitTypes::Terran_Missile_Turret,13); this->buildOrderManager->upgrade(3,UpgradeTypes::Terran_Infantry_Weapons,12); this->buildOrderManager->upgrade(3,UpgradeTypes::Terran_Infantry_Armor,12); this->buildOrderManager->build(1,UnitTypes::Terran_Engineering_Bay,11); this->buildOrderManager->buildAdditional(40,UnitTypes::Terran_Marine,10); this->buildOrderManager->build(6,UnitTypes::Terran_Barracks,8); this->buildOrderManager->build(2,UnitTypes::Terran_Engineering_Bay,7); this->buildOrderManager->buildAdditional(10,UnitTypes::Terran_Siege_Tank_Tank_Mode,5); } else { this->buildOrderManager->buildAdditional(2,BWAPI::UnitTypes::Terran_Machine_Shop,70); this->buildOrderManager->buildAdditional(3,BWAPI::UnitTypes::Terran_Factory,60); this->buildOrderManager->research(TechTypes::Spider_Mines,55); this->buildOrderManager->research(TechTypes::Tank_Siege_Mode,55); this->buildOrderManager->buildAdditional(20,BWAPI::UnitTypes::Terran_Vulture,40); this->buildOrderManager->buildAdditional(20,BWAPI::UnitTypes::Terran_Siege_Tank_Tank_Mode,40); this->buildOrderManager->upgrade(3,UpgradeTypes::Terran_Vehicle_Weapons,20); } } else if (race == Races::Protoss) { this->buildOrderManager->build(20,workerType,80); this->buildOrderManager->buildAdditional(10,UnitTypes::Protoss_Dragoon,70); this->buildOrderManager->buildAdditional(10,UnitTypes::Protoss_Zealot,70); this->buildOrderManager->upgrade(1,UpgradeTypes::Singularity_Charge,61); this->buildOrderManager->buildAdditional(20,UnitTypes::Protoss_Carrier,60); } this->workerManager->enableAutoBuild(); this->workerManager->setAutoBuildPriority(40); } void BasicAIModule::onFrame() { if (Broodwar->isReplay()) return; if (!this->analyzed) return; this->buildManager->update(); this->buildOrderManager->update(); this->baseManager->update(); this->workerManager->update(); this->techManager->update(); this->upgradeManager->update(); this->supplyManager->update(); this->scoutManager->update(); this->enhancedUI->update(); this->borderManager->update(); this->defenseManager->update(); this->arbitrator.update(); if (Broodwar->getFrameCount()>24*50) scoutManager->setScoutCount(1); std::set<Unit*> units=Broodwar->self()->getUnits(); if (this->showManagerAssignments) { for(std::set<Unit*>::iterator i=units.begin();i!=units.end();i++) { if (this->arbitrator.hasBid(*i)) { int x=(*i)->getPosition().x(); int y=(*i)->getPosition().y(); std::list< std::pair< Arbitrator::Controller<BWAPI::Unit*,double>*, double> > bids=this->arbitrator.getAllBidders(*i); int y_off=0; bool first = false; const char activeColor = '\x07', inactiveColor = '\x16'; char color = activeColor; for(std::list< std::pair< Arbitrator::Controller<BWAPI::Unit*,double>*, double> >::iterator j=bids.begin();j!=bids.end();j++) { Broodwar->drawText(CoordinateType::Map,x,y+y_off,"%c%s: %d",color,j->first->getShortName().c_str(),(int)j->second); y_off+=15; color = inactiveColor; } } } } UnitGroup myPylonsAndGateways = SelectAll()(Pylon,Gateway)(HitPoints,"<=",200); for each(Unit* u in myPylonsAndGateways) { Broodwar->drawCircleMap(u->getPosition().x(),u->getPosition().y(),20,Colors::Red); } } void BasicAIModule::onUnitDestroy(BWAPI::Unit* unit) { this->arbitrator.onRemoveObject(unit); this->buildManager->onRemoveUnit(unit); this->techManager->onRemoveUnit(unit); this->upgradeManager->onRemoveUnit(unit); this->workerManager->onRemoveUnit(unit); this->scoutManager->onRemoveUnit(unit); this->defenseManager->onRemoveUnit(unit); this->informationManager->onUnitDestroy(unit); } void BasicAIModule::onUnitShow(BWAPI::Unit* unit) { this->informationManager->onUnitShow(unit); this->unitGroupManager->onUnitShow(unit); } void BasicAIModule::onUnitHide(BWAPI::Unit* unit) { this->informationManager->onUnitHide(unit); this->unitGroupManager->onUnitHide(unit); } void BasicAIModule::onUnitMorph(BWAPI::Unit* unit) { this->unitGroupManager->onUnitMorph(unit); } void BasicAIModule::onUnitRenegade(BWAPI::Unit* unit) { this->unitGroupManager->onUnitRenegade(unit); } bool BasicAIModule::onSendText(std::string text) { UnitType type=UnitTypes::getUnitType(text); if (text=="debug") { this->showManagerAssignments=true; this->buildOrderManager->enableDebugMode(); this->scoutManager->enableDebugMode(); return true; } if (text=="expand") { this->baseManager->expand(); } if (type!=UnitTypes::Unknown) { this->buildOrderManager->buildAdditional(1,type,300); } else { TechType type=TechTypes::getTechType(text); if (type!=TechTypes::Unknown) { this->techManager->research(type); } else { UpgradeType type=UpgradeTypes::getUpgradeType(text); if (type!=UpgradeTypes::Unknown) { this->upgradeManager->upgrade(type); } else Broodwar->printf("You typed '%s'!",text.c_str()); } } return true; } <commit_msg>added call to base manager from AIModule::onUnitDestroy.<commit_after>#include "BasicAIModule.h" using namespace BWAPI; void BasicAIModule::onStart() { this->showManagerAssignments=false; if (Broodwar->isReplay()) return; // Enable some cheat flags Broodwar->enableFlag(Flag::UserInput); //Broodwar->enableFlag(Flag::CompleteMapInformation); BWTA::readMap(); BWTA::analyze(); this->analyzed=true; this->buildManager = new BuildManager(&this->arbitrator); this->techManager = new TechManager(&this->arbitrator); this->upgradeManager = new UpgradeManager(&this->arbitrator); this->scoutManager = new ScoutManager(&this->arbitrator); this->workerManager = new WorkerManager(&this->arbitrator); this->buildOrderManager = new BuildOrderManager(this->buildManager,this->techManager,this->upgradeManager,this->workerManager); this->baseManager = new BaseManager(); this->supplyManager = new SupplyManager(); this->defenseManager = new DefenseManager(&this->arbitrator); this->informationManager = new InformationManager(); this->borderManager = new BorderManager(); this->unitGroupManager = new UnitGroupManager(); this->enhancedUI = new EnhancedUI(); this->supplyManager->setBuildManager(this->buildManager); this->supplyManager->setBuildOrderManager(this->buildOrderManager); this->techManager->setBuildingPlacer(this->buildManager->getBuildingPlacer()); this->upgradeManager->setBuildingPlacer(this->buildManager->getBuildingPlacer()); this->workerManager->setBaseManager(this->baseManager); this->workerManager->setBuildOrderManager(this->buildOrderManager); this->baseManager->setBuildOrderManager(this->buildOrderManager); this->borderManager->setInformationManager(this->informationManager); this->baseManager->setBorderManager(this->borderManager); this->defenseManager->setBorderManager(this->borderManager); BWAPI::Race race = Broodwar->self()->getRace(); BWAPI::Race enemyRace = Broodwar->enemy()->getRace(); BWAPI::UnitType workerType=*(race.getWorker()); double minDist; BWTA::BaseLocation* natural=NULL; BWTA::BaseLocation* home=BWTA::getStartLocation(Broodwar->self()); for(std::set<BWTA::BaseLocation*>::const_iterator b=BWTA::getBaseLocations().begin();b!=BWTA::getBaseLocations().end();b++) { if (*b==home) continue; double dist=home->getGroundDistance(*b); if (dist>0) { if (natural==NULL || dist<minDist) { minDist=dist; natural=*b; } } } this->buildOrderManager->enableDependencyResolver(); //make the basic production facility if (race == Races::Zerg) { //send an overlord out if Zerg this->scoutManager->setScoutCount(1); //12 hatch this->buildOrderManager->build(12,workerType,80); this->baseManager->expand(natural,79); this->buildOrderManager->build(20,workerType,78); this->buildOrderManager->buildAdditional(1,UnitTypes::Zerg_Spawning_Pool,60); this->buildOrderManager->buildAdditional(3,UnitTypes::Zerg_Zergling,82); } else if (race == Races::Terran) { this->buildOrderManager->build(20,workerType,80); if (enemyRace == Races::Zerg) { this->buildOrderManager->buildAdditional(1,UnitTypes::Terran_Barracks,60); this->buildOrderManager->buildAdditional(9,UnitTypes::Terran_Marine,45); this->buildOrderManager->buildAdditional(1,UnitTypes::Terran_Refinery,42); this->buildOrderManager->buildAdditional(1,UnitTypes::Terran_Barracks,40); this->buildOrderManager->buildAdditional(1,UnitTypes::Terran_Academy,39); this->buildOrderManager->buildAdditional(9,UnitTypes::Terran_Medic,38); this->buildOrderManager->research(TechTypes::Stim_Packs,35); this->buildOrderManager->research(TechTypes::Tank_Siege_Mode,35); this->buildOrderManager->buildAdditional(3,UnitTypes::Terran_Siege_Tank_Tank_Mode,34); this->buildOrderManager->buildAdditional(2,UnitTypes::Terran_Science_Vessel,30); this->buildOrderManager->research(TechTypes::Irradiate,30); this->buildOrderManager->upgrade(1,UpgradeTypes::Terran_Infantry_Weapons,20); this->buildOrderManager->build(3,UnitTypes::Terran_Missile_Turret,13); this->buildOrderManager->upgrade(3,UpgradeTypes::Terran_Infantry_Weapons,12); this->buildOrderManager->upgrade(3,UpgradeTypes::Terran_Infantry_Armor,12); this->buildOrderManager->build(1,UnitTypes::Terran_Engineering_Bay,11); this->buildOrderManager->buildAdditional(40,UnitTypes::Terran_Marine,10); this->buildOrderManager->build(6,UnitTypes::Terran_Barracks,8); this->buildOrderManager->build(2,UnitTypes::Terran_Engineering_Bay,7); this->buildOrderManager->buildAdditional(10,UnitTypes::Terran_Siege_Tank_Tank_Mode,5); } else { this->buildOrderManager->buildAdditional(2,BWAPI::UnitTypes::Terran_Machine_Shop,70); this->buildOrderManager->buildAdditional(3,BWAPI::UnitTypes::Terran_Factory,60); this->buildOrderManager->research(TechTypes::Spider_Mines,55); this->buildOrderManager->research(TechTypes::Tank_Siege_Mode,55); this->buildOrderManager->buildAdditional(20,BWAPI::UnitTypes::Terran_Vulture,40); this->buildOrderManager->buildAdditional(20,BWAPI::UnitTypes::Terran_Siege_Tank_Tank_Mode,40); this->buildOrderManager->upgrade(3,UpgradeTypes::Terran_Vehicle_Weapons,20); } } else if (race == Races::Protoss) { this->buildOrderManager->build(20,workerType,80); this->buildOrderManager->buildAdditional(10,UnitTypes::Protoss_Dragoon,70); this->buildOrderManager->buildAdditional(10,UnitTypes::Protoss_Zealot,70); this->buildOrderManager->upgrade(1,UpgradeTypes::Singularity_Charge,61); this->buildOrderManager->buildAdditional(20,UnitTypes::Protoss_Carrier,60); } this->workerManager->enableAutoBuild(); this->workerManager->setAutoBuildPriority(40); } void BasicAIModule::onFrame() { if (Broodwar->isReplay()) return; if (!this->analyzed) return; this->buildManager->update(); this->buildOrderManager->update(); this->baseManager->update(); this->workerManager->update(); this->techManager->update(); this->upgradeManager->update(); this->supplyManager->update(); this->scoutManager->update(); this->enhancedUI->update(); this->borderManager->update(); this->defenseManager->update(); this->arbitrator.update(); if (Broodwar->getFrameCount()>24*50) scoutManager->setScoutCount(1); std::set<Unit*> units=Broodwar->self()->getUnits(); if (this->showManagerAssignments) { for(std::set<Unit*>::iterator i=units.begin();i!=units.end();i++) { if (this->arbitrator.hasBid(*i)) { int x=(*i)->getPosition().x(); int y=(*i)->getPosition().y(); std::list< std::pair< Arbitrator::Controller<BWAPI::Unit*,double>*, double> > bids=this->arbitrator.getAllBidders(*i); int y_off=0; bool first = false; const char activeColor = '\x07', inactiveColor = '\x16'; char color = activeColor; for(std::list< std::pair< Arbitrator::Controller<BWAPI::Unit*,double>*, double> >::iterator j=bids.begin();j!=bids.end();j++) { Broodwar->drawText(CoordinateType::Map,x,y+y_off,"%c%s: %d",color,j->first->getShortName().c_str(),(int)j->second); y_off+=15; color = inactiveColor; } } } } UnitGroup myPylonsAndGateways = SelectAll()(Pylon,Gateway)(HitPoints,"<=",200); for each(Unit* u in myPylonsAndGateways) { Broodwar->drawCircleMap(u->getPosition().x(),u->getPosition().y(),20,Colors::Red); } } void BasicAIModule::onUnitDestroy(BWAPI::Unit* unit) { this->arbitrator.onRemoveObject(unit); this->buildManager->onRemoveUnit(unit); this->techManager->onRemoveUnit(unit); this->upgradeManager->onRemoveUnit(unit); this->workerManager->onRemoveUnit(unit); this->scoutManager->onRemoveUnit(unit); this->defenseManager->onRemoveUnit(unit); this->informationManager->onUnitDestroy(unit); this->baseManager->onRemoveUnit(unit); } void BasicAIModule::onUnitShow(BWAPI::Unit* unit) { this->informationManager->onUnitShow(unit); this->unitGroupManager->onUnitShow(unit); } void BasicAIModule::onUnitHide(BWAPI::Unit* unit) { this->informationManager->onUnitHide(unit); this->unitGroupManager->onUnitHide(unit); } void BasicAIModule::onUnitMorph(BWAPI::Unit* unit) { this->unitGroupManager->onUnitMorph(unit); } void BasicAIModule::onUnitRenegade(BWAPI::Unit* unit) { this->unitGroupManager->onUnitRenegade(unit); } bool BasicAIModule::onSendText(std::string text) { UnitType type=UnitTypes::getUnitType(text); if (text=="debug") { this->showManagerAssignments=true; this->buildOrderManager->enableDebugMode(); this->scoutManager->enableDebugMode(); return true; } if (text=="expand") { this->baseManager->expand(); } if (type!=UnitTypes::Unknown) { this->buildOrderManager->buildAdditional(1,type,300); } else { TechType type=TechTypes::getTechType(text); if (type!=TechTypes::Unknown) { this->techManager->research(type); } else { UpgradeType type=UpgradeTypes::getUpgradeType(text); if (type!=UpgradeTypes::Unknown) { this->upgradeManager->upgrade(type); } else Broodwar->printf("You typed '%s'!",text.c_str()); } } return true; } <|endoftext|>
<commit_before>#include "anki/resource/MaterialShaderProgramCreator.h" #include "anki/util/Assert.h" #include "anki/util/Exception.h" #include "anki/misc/Xml.h" #include "anki/core/Logger.h" #include <algorithm> #include <sstream> namespace anki { //============================================================================== MaterialShaderProgramCreator::MaterialShaderProgramCreator( const XmlElement& el) { parseShaderProgramTag(el); } //============================================================================== MaterialShaderProgramCreator::~MaterialShaderProgramCreator() {} //============================================================================== void MaterialShaderProgramCreator::parseShaderProgramTag( const XmlElement& shaderProgramEl) { XmlElement shaderEl = shaderProgramEl.getChildElement("shader"); do { parseShaderTag(shaderEl); shaderEl = shaderEl.getNextSiblingElement("shader"); } while(shaderEl); source = srcLines.join("\n"); //std::cout << source << std::endl; } //============================================================================== void MaterialShaderProgramCreator::parseShaderTag( const XmlElement& shaderEl) { // <type></type> // std::string type = shaderEl.getChildElement("type").getText(); srcLines.push_back("#pragma anki start " + type + "Shader"); // <includes></includes> // Vector<std::string> includeLines; XmlElement includesEl = shaderEl.getChildElement("includes"); XmlElement includeEl = includesEl.getChildElement("include"); do { std::string fname = includeEl.getText(); includeLines.push_back(std::string("#pragma anki include \"") + fname + "\""); includeEl = includeEl.getNextSiblingElement("include"); } while(includeEl); //std::sort(includeLines.begin(), includeLines.end(), compareStrings); srcLines.insert(srcLines.end(), includeLines.begin(), includeLines.end()); // <inputs></inputs> // XmlElement inputsEl = shaderEl.getChildElementOptional("inputs"); if(inputsEl) { // Store the source of the uniform vars Vector<std::string> uniformsLines; XmlElement inputEl = inputsEl.getChildElement("input"); do { std::string line; parseInputTag(inputEl, line); uniformsLines.push_back(line); inputEl = inputEl.getNextSiblingElement("input"); } while(inputEl); srcLines.push_back(""); std::sort(uniformsLines.begin(), uniformsLines.end(), compareStrings); srcLines.insert(srcLines.end(), uniformsLines.begin(), uniformsLines.end()); } // <operations></operations> // srcLines.push_back("\nvoid main()\n{"); XmlElement opsEl = shaderEl.getChildElement("operations"); XmlElement opEl = opsEl.getChildElement("operation"); do { parseOperationTag(opEl); opEl = opEl.getNextSiblingElement("operation"); } while(opEl); srcLines.push_back("}\n"); } //============================================================================== void MaterialShaderProgramCreator::parseInputTag( const XmlElement& inputEl, std::string& line) { Input* inpvar = new Input; inpvar->name = inputEl.getChildElement("name").getText(); inpvar->type = inputEl.getChildElement("type").getText(); XmlElement constEl = inputEl.getChildElementOptional("const"); XmlElement valueEl = inputEl.getChildElement("value"); if(constEl) { inpvar->const_ = constEl.getInt(); } if(valueEl.getText()) { inpvar->value = StringList::splitString(valueEl.getText(), ' '); } if(inpvar->const_ == false) { line = "uniform " + inpvar->type + " " + inpvar->name + ";"; } else { if(inpvar->value.size() == 0) { throw ANKI_EXCEPTION("Empty value and const is illogical"); } line = "const " + inpvar->type + " " + inpvar->name + " = " + inpvar->type + "(" + inpvar->value.join(", ") + ");"; } inputs.push_back(inpvar); } //============================================================================== void MaterialShaderProgramCreator::parseOperationTag( const XmlElement& operationTag) { // <id></id> int id = operationTag.getChildElement("id").getInt(); // <returnType></returnType> XmlElement retTypeEl = operationTag.getChildElement("returnType"); std::string retType = retTypeEl.getText(); std::string operationOut; if(retType != "void") { operationOut = "operationOut" + std::to_string(id); } // <function>functionName</function> std::string funcName = operationTag.getChildElement("function").getText(); // <arguments></arguments> XmlElement argsEl = operationTag.getChildElementOptional("arguments"); StringList argsList; if(argsEl) { // Get all arguments XmlElement argEl = argsEl.getChildElement("argument"); do { argsList.push_back(argEl.getText()); argEl = argEl.getNextSiblingElement("argument"); } while(argEl); } // Now write everything std::stringstream line; line << "#if defined(" << funcName << "_DEFINED)"; // XXX Regexpr features still missing //std::regex expr("^operationOut[0-9]*$"); for(const std::string& arg : argsList) { //if(std::regex_match(arg, expr)) if(arg.find("operationOut") == 0) { line << " && defined(" << arg << "_DEFINED)"; } } line << "\n"; if(retType != "void") { line << "#\tdefine " << operationOut << "_DEFINED\n"; line << '\t' << retTypeEl.getText() << " " << operationOut << " = "; } else { line << '\t'; } line << funcName << "("; line << argsList.join(", "); line << ");\n"; line << "#endif"; // Done srcLines.push_back(line.str()); } //============================================================================== bool MaterialShaderProgramCreator::compareStrings( const std::string& a, const std::string& b) { return a < b; } } // end namespace anki <commit_msg>Nothing important<commit_after>#include "anki/resource/MaterialShaderProgramCreator.h" #include "anki/util/Assert.h" #include "anki/util/Exception.h" #include "anki/misc/Xml.h" #include "anki/core/Logger.h" #include <algorithm> #include <sstream> namespace anki { //============================================================================== MaterialShaderProgramCreator::MaterialShaderProgramCreator( const XmlElement& el) { parseShaderProgramTag(el); } //============================================================================== MaterialShaderProgramCreator::~MaterialShaderProgramCreator() {} //============================================================================== void MaterialShaderProgramCreator::parseShaderProgramTag( const XmlElement& shaderProgramEl) { XmlElement shaderEl = shaderProgramEl.getChildElement("shader"); do { parseShaderTag(shaderEl); shaderEl = shaderEl.getNextSiblingElement("shader"); } while(shaderEl); // Create block StringList block; block.push_back("layout(std140, row_major, binding = 0) " "uniform commonBlock\n{"); for(Input* in : inputs) { if(in->type == "sampler2D" || in->const_) { continue; } block.push_back("\tuniform " + in->type + " " + in->name + "_;"); } block.push_back("};\n"); if(block.size() > 2) { source = block.join("\n") + srcLines.join("\n"); } else { source = srcLines.join("\n"); } } //============================================================================== void MaterialShaderProgramCreator::parseShaderTag( const XmlElement& shaderEl) { // <type></type> // std::string type = shaderEl.getChildElement("type").getText(); srcLines.push_back("#pragma anki start " + type + "Shader"); // <includes></includes> // Vector<std::string> includeLines; XmlElement includesEl = shaderEl.getChildElement("includes"); XmlElement includeEl = includesEl.getChildElement("include"); do { std::string fname = includeEl.getText(); includeLines.push_back(std::string("#pragma anki include \"") + fname + "\""); includeEl = includeEl.getNextSiblingElement("include"); } while(includeEl); //std::sort(includeLines.begin(), includeLines.end(), compareStrings); srcLines.insert(srcLines.end(), includeLines.begin(), includeLines.end()); // <inputs></inputs> // XmlElement inputsEl = shaderEl.getChildElementOptional("inputs"); if(inputsEl) { // Store the source of the uniform vars Vector<std::string> uniformsLines; XmlElement inputEl = inputsEl.getChildElement("input"); do { std::string line; parseInputTag(inputEl, line); uniformsLines.push_back(line); inputEl = inputEl.getNextSiblingElement("input"); } while(inputEl); srcLines.push_back(""); std::sort(uniformsLines.begin(), uniformsLines.end(), compareStrings); srcLines.insert(srcLines.end(), uniformsLines.begin(), uniformsLines.end()); } // <operations></operations> // srcLines.push_back("\nvoid main()\n{"); XmlElement opsEl = shaderEl.getChildElement("operations"); XmlElement opEl = opsEl.getChildElement("operation"); do { parseOperationTag(opEl); opEl = opEl.getNextSiblingElement("operation"); } while(opEl); srcLines.push_back("}\n"); } //============================================================================== void MaterialShaderProgramCreator::parseInputTag( const XmlElement& inputEl, std::string& line) { Input* inpvar = new Input; inpvar->name = inputEl.getChildElement("name").getText(); inpvar->type = inputEl.getChildElement("type").getText(); XmlElement constEl = inputEl.getChildElementOptional("const"); XmlElement valueEl = inputEl.getChildElement("value"); if(constEl) { inpvar->const_ = constEl.getInt(); } else { inpvar->const_ = false; } if(valueEl.getText()) { inpvar->value = StringList::splitString(valueEl.getText(), ' '); } if(inpvar->const_ == false) { line = "uniform " + inpvar->type + " " + inpvar->name + ";"; } else { if(inpvar->value.size() == 0) { throw ANKI_EXCEPTION("Empty value and const is illogical"); } line = "const " + inpvar->type + " " + inpvar->name + " = " + inpvar->type + "(" + inpvar->value.join(", ") + ");"; } inputs.push_back(inpvar); } //============================================================================== void MaterialShaderProgramCreator::parseOperationTag( const XmlElement& operationTag) { // <id></id> int id = operationTag.getChildElement("id").getInt(); // <returnType></returnType> XmlElement retTypeEl = operationTag.getChildElement("returnType"); std::string retType = retTypeEl.getText(); std::string operationOut; if(retType != "void") { operationOut = "operationOut" + std::to_string(id); } // <function>functionName</function> std::string funcName = operationTag.getChildElement("function").getText(); // <arguments></arguments> XmlElement argsEl = operationTag.getChildElementOptional("arguments"); StringList argsList; if(argsEl) { // Get all arguments XmlElement argEl = argsEl.getChildElement("argument"); do { argsList.push_back(argEl.getText()); argEl = argEl.getNextSiblingElement("argument"); } while(argEl); } // Now write everything std::stringstream line; line << "#if defined(" << funcName << "_DEFINED)"; // XXX Regexpr features still missing //std::regex expr("^operationOut[0-9]*$"); for(const std::string& arg : argsList) { //if(std::regex_match(arg, expr)) if(arg.find("operationOut") == 0) { line << " && defined(" << arg << "_DEFINED)"; } } line << "\n"; if(retType != "void") { line << "#\tdefine " << operationOut << "_DEFINED\n"; line << '\t' << retTypeEl.getText() << " " << operationOut << " = "; } else { line << '\t'; } line << funcName << "("; line << argsList.join(", "); line << ");\n"; line << "#endif"; // Done srcLines.push_back(line.str()); } //============================================================================== bool MaterialShaderProgramCreator::compareStrings( const std::string& a, const std::string& b) { return a < b; } } // end namespace anki <|endoftext|>
<commit_before>/*++ Copyright (c) 2012 Microsoft Corporation Module Name: smt_strategic_solver.h Abstract: Create a strategic solver with tactic for all main logics used in SMT. Author: Leonardo (leonardo) 2012-02-19 Notes: --*/ #include"cmd_context.h" #include"combined_solver.h" #include"tactic2solver.h" #include"qfbv_tactic.h" #include"qflia_tactic.h" #include"qfnia_tactic.h" #include"qfnra_tactic.h" #include"qfuf_tactic.h" #include"qflra_tactic.h" #include"quant_tactics.h" #include"qfauflia_tactic.h" #include"qfaufbv_tactic.h" #include"qfufbv_tactic.h" #include"qfidl_tactic.h" #include"default_tactic.h" #include"ufbv_tactic.h" #include"qffp_tactic.h" #include"qfufnra_tactic.h" #include"horn_tactic.h" #include"smt_solver.h" #include"inc_sat_solver.h" tactic * mk_tactic_for_logic(ast_manager & m, params_ref const & p, symbol const & logic) { if (logic=="QF_UF") return mk_qfuf_tactic(m, p); else if (logic=="QF_BV") return mk_qfbv_tactic(m, p); else if (logic=="QF_IDL") return mk_qfidl_tactic(m, p); else if (logic=="QF_LIA") return mk_qflia_tactic(m, p); else if (logic=="QF_LRA") return mk_qflra_tactic(m, p); else if (logic=="QF_NIA") return mk_qfnia_tactic(m, p); else if (logic=="QF_NRA") return mk_qfnra_tactic(m, p); else if (logic=="QF_AUFLIA") return mk_qfauflia_tactic(m, p); else if (logic=="QF_AUFBV") return mk_qfaufbv_tactic(m, p); else if (logic=="QF_ABV") return mk_qfaufbv_tactic(m, p); else if (logic=="QF_UFBV") return mk_qfufbv_tactic(m, p); else if (logic=="AUFLIA") return mk_auflia_tactic(m, p); else if (logic=="AUFLIRA") return mk_auflira_tactic(m, p); else if (logic=="AUFNIRA") return mk_aufnira_tactic(m, p); else if (logic=="UFNIA") return mk_ufnia_tactic(m, p); else if (logic=="UFLRA") return mk_uflra_tactic(m, p); else if (logic=="LRA") return mk_lra_tactic(m, p); else if (logic=="LIA") return mk_lia_tactic(m, p); else if (logic=="UFBV") return mk_ufbv_tactic(m, p); else if (logic=="BV") return mk_ufbv_tactic(m, p); else if (logic=="QF_FP") return mk_qffp_tactic(m, p); else if (logic == "QF_FPBV" || logic == "QF_BVFP") return mk_qffpbv_tactic(m, p); else if (logic=="HORN") return mk_horn_tactic(m, p); //else if (logic=="QF_UFNRA") // return mk_qfufnra_tactic(m, p); else return mk_default_tactic(m, p); } static solver* mk_solver_for_logic(ast_manager & m, params_ref const & p, symbol const& logic) { if (logic == "QF_BV") return mk_inc_sat_solver(m, p); return mk_smt_solver(m, p, logic); } class smt_strategic_solver_factory : public solver_factory { symbol m_logic; public: smt_strategic_solver_factory(symbol const & logic):m_logic(logic) {} virtual ~smt_strategic_solver_factory() {} virtual solver * operator()(ast_manager & m, params_ref const & p, bool proofs_enabled, bool models_enabled, bool unsat_core_enabled, symbol const & logic) { symbol l; if (m_logic != symbol::null) l = m_logic; else l = logic; tactic * t = mk_tactic_for_logic(m, p, l); return mk_combined_solver(mk_tactic2solver(m, t, p, proofs_enabled, models_enabled, unsat_core_enabled, l), mk_solver_for_logic(m, p, l), //mk_smt_solver(m, p, l), p); } }; solver_factory * mk_smt_strategic_solver_factory(symbol const & logic) { return alloc(smt_strategic_solver_factory, logic); } <commit_msg>fix issue #212 - don't use SAT solver core when division semantics is disabled<commit_after>/*++ Copyright (c) 2012 Microsoft Corporation Module Name: smt_strategic_solver.h Abstract: Create a strategic solver with tactic for all main logics used in SMT. Author: Leonardo (leonardo) 2012-02-19 Notes: --*/ #include"cmd_context.h" #include"combined_solver.h" #include"tactic2solver.h" #include"qfbv_tactic.h" #include"qflia_tactic.h" #include"qfnia_tactic.h" #include"qfnra_tactic.h" #include"qfuf_tactic.h" #include"qflra_tactic.h" #include"quant_tactics.h" #include"qfauflia_tactic.h" #include"qfaufbv_tactic.h" #include"qfufbv_tactic.h" #include"qfidl_tactic.h" #include"default_tactic.h" #include"ufbv_tactic.h" #include"qffp_tactic.h" #include"qfufnra_tactic.h" #include"horn_tactic.h" #include"smt_solver.h" #include"inc_sat_solver.h" #include"bv_rewriter.h" tactic * mk_tactic_for_logic(ast_manager & m, params_ref const & p, symbol const & logic) { if (logic=="QF_UF") return mk_qfuf_tactic(m, p); else if (logic=="QF_BV") return mk_qfbv_tactic(m, p); else if (logic=="QF_IDL") return mk_qfidl_tactic(m, p); else if (logic=="QF_LIA") return mk_qflia_tactic(m, p); else if (logic=="QF_LRA") return mk_qflra_tactic(m, p); else if (logic=="QF_NIA") return mk_qfnia_tactic(m, p); else if (logic=="QF_NRA") return mk_qfnra_tactic(m, p); else if (logic=="QF_AUFLIA") return mk_qfauflia_tactic(m, p); else if (logic=="QF_AUFBV") return mk_qfaufbv_tactic(m, p); else if (logic=="QF_ABV") return mk_qfaufbv_tactic(m, p); else if (logic=="QF_UFBV") return mk_qfufbv_tactic(m, p); else if (logic=="AUFLIA") return mk_auflia_tactic(m, p); else if (logic=="AUFLIRA") return mk_auflira_tactic(m, p); else if (logic=="AUFNIRA") return mk_aufnira_tactic(m, p); else if (logic=="UFNIA") return mk_ufnia_tactic(m, p); else if (logic=="UFLRA") return mk_uflra_tactic(m, p); else if (logic=="LRA") return mk_lra_tactic(m, p); else if (logic=="LIA") return mk_lia_tactic(m, p); else if (logic=="UFBV") return mk_ufbv_tactic(m, p); else if (logic=="BV") return mk_ufbv_tactic(m, p); else if (logic=="QF_FP") return mk_qffp_tactic(m, p); else if (logic == "QF_FPBV" || logic == "QF_BVFP") return mk_qffpbv_tactic(m, p); else if (logic=="HORN") return mk_horn_tactic(m, p); //else if (logic=="QF_UFNRA") // return mk_qfufnra_tactic(m, p); else return mk_default_tactic(m, p); } static solver* mk_solver_for_logic(ast_manager & m, params_ref const & p, symbol const& logic) { bv_rewriter rw(m); if (logic == "QF_BV" && rw.hi_div0()) return mk_inc_sat_solver(m, p); return mk_smt_solver(m, p, logic); } class smt_strategic_solver_factory : public solver_factory { symbol m_logic; public: smt_strategic_solver_factory(symbol const & logic):m_logic(logic) {} virtual ~smt_strategic_solver_factory() {} virtual solver * operator()(ast_manager & m, params_ref const & p, bool proofs_enabled, bool models_enabled, bool unsat_core_enabled, symbol const & logic) { symbol l; if (m_logic != symbol::null) l = m_logic; else l = logic; tactic * t = mk_tactic_for_logic(m, p, l); return mk_combined_solver(mk_tactic2solver(m, t, p, proofs_enabled, models_enabled, unsat_core_enabled, l), mk_solver_for_logic(m, p, l), //mk_smt_solver(m, p, l), p); } }; solver_factory * mk_smt_strategic_solver_factory(symbol const & logic) { return alloc(smt_strategic_solver_factory, logic); } <|endoftext|>
<commit_before>#include "BaseScene.h" ofColor BaseScene::twitterColour = ofColor(255,0,0); // ---------------------------------------------------- BaseScene::BaseScene() { audioPtr = NULL; generateComplimentaryColours(); } // ---------------------------------------------------- BaseScene::~BaseScene() { } // ---------------------------------------------------- void BaseScene::drawBackground() { ofSetColor(ofColor::black); ofFill(); ofRect(0, 0, CUBE_SCREEN_WIDTH, CUBE_SCREEN_HEIGHT); } // ---------------------------------------------------- void BaseScene::draw() { ofSetColor(255); AppAssets::inst()->appFont.drawString(name, 10, 15); }; void BaseScene::generateComplimentaryColours(){ cout << "Making new complimentary colours " << endl; //twitterColour is the value that we are going to work with float hue, saturation, brightness; twitterColour.getHsb( hue, saturation, brightness ); //lets clear out any old colours complimentaryColours.clear(); size_t numberOfComplimentaryColours = 16; complimentaryColours.resize(numberOfComplimentaryColours); //first pass at a colour generator for(int i = 0; i < complimentaryColours.size(); i++){ float newHue = hue;//fmodf(hue + ofRandom(0, 12.f), 255.f); float newSaturation = saturation;//fmodf(saturation + ofRandom(0.f, 255.f), 255.f); float newBrightness = fmodf(brightness + ofRandom(0.f, 128.f), 255.f); if(i==0){ newHue = hue; newSaturation = saturation; newBrightness = brightness; } complimentaryColours[i] = ofColor::fromHsb(newHue, newSaturation, newBrightness); } }; <commit_msg>changed colour generation to be hue variance with a small brightness swizzle to prevent totally black cell scenes<commit_after>#include "BaseScene.h" ofColor BaseScene::twitterColour = ofColor(255,0,0); // ---------------------------------------------------- BaseScene::BaseScene() { audioPtr = NULL; generateComplimentaryColours(); } // ---------------------------------------------------- BaseScene::~BaseScene() { } // ---------------------------------------------------- void BaseScene::drawBackground() { ofSetColor(ofColor::black); ofFill(); ofRect(0, 0, CUBE_SCREEN_WIDTH, CUBE_SCREEN_HEIGHT); } // ---------------------------------------------------- void BaseScene::draw() { ofSetColor(255); AppAssets::inst()->appFont.drawString(name, 10, 15); }; void BaseScene::generateComplimentaryColours(){ cout << "Making new complimentary colours " << endl; //twitterColour is the value that we are going to work with float hue, saturation, brightness; twitterColour.getHsb( hue, saturation, brightness ); //lets clear out any old colours complimentaryColours.clear(); size_t numberOfComplimentaryColours = 16; complimentaryColours.resize(numberOfComplimentaryColours); //first pass at a colour generator for(int i = 0; i < complimentaryColours.size(); i++){ float newHue = fmodf(hue + ofRandom(-36.f, 36.f), 255.f); float newSaturation = saturation;//fmodf(saturation + ofRandom(0.f, 255.f), 255.f); float newBrightness = fmodf(brightness + ofRandom(-10.f, 10.f), 255.f); //to prevent a completely dull black screen in cell scene if(i==0){ newHue = hue; newSaturation = saturation; newBrightness = brightness; } complimentaryColours[i] = ofColor::fromHsb(newHue, newSaturation, newBrightness); } }; <|endoftext|>
<commit_before>/* * ServalCommunication.cpp * * Created on: Apr 15, 2016 * Author: sni */ #include "ServalCommunication.h" #include <chrono> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <ice/communication/messages/Message.h> #include <serval_interface.h> #include <serval_wrapper/MDPSocket.h> #include "ice/Entity.h" #include "IceServalBridge.h" // Short alias for this namespace namespace pt = boost::property_tree; namespace ice { ServalCommunication::ServalCommunication(std::weak_ptr<ICEngine> engine, std::string configPath, std::string const host, int const port, std::string const authName, std::string const authPass, bool const local) : CommunicationInterface(engine), configPath(configPath), host(host), port(port), authName(authName), authPass(authPass), serval(nullptr), local(local), running (false) { _log = el::Loggers::getLogger("ServalCommunication"); this->maxMessageSend = 1; } ServalCommunication::~ServalCommunication() { if (this->running) { this->running = false; } } std::shared_ptr<serval_interface> ServalCommunication::getServalInterface() { return this->serval; } void ServalCommunication::setOwnSid(std::string const &sid) { this->ownSid = sid; } void ServalCommunication::initInternal() { // create interface this->serval = std::make_shared<serval_interface>(this->configPath, this->host, this->port, this->authName, this->authPass); // get own id if (local) { auto oid = this->serval->keyring.addIdentity(); if (oid == nullptr) { // error case, own id could not be determined throw(std::runtime_error("Own serval id could not be determined")); } this->ownSid = oid->sid; this->self->addId(EntityDirectory::ID_SERVAL, this->ownSid); } else { if (this->ownSid == "") { auto id = this->serval->keyring.getSelf(); if (id == nullptr || id->size() == 0) { // error case, own id could not be determined throw(std::runtime_error("Own serval id could not be determined")); } this->ownSid = id->at(0).sid; this->self->addId(EntityDirectory::ID_SERVAL, this->ownSid); } } // create socket this->socket = this->serval->createSocket(SERVAL_PORT, this->ownSid); if (this->socket == nullptr) { throw (std::runtime_error("MDP socket could not be created")); return; } // init read thread this->running = true; this->worker = std::thread(&ServalCommunication::read, this); this->worker.detach(); } void ServalCommunication::cleanUpInternal() { this->running = false; if (this->serval != nullptr) { this->serval->cleanUp(); this->serval = nullptr; } } void ServalCommunication::read() { uint8_t buffer[4096]; std::string sid; while (this->running) { int recCount = this->socket->receive(sid, buffer, 4096); if (false == this->running) return; if (recCount == 0) { // huge amount of emtpy messages, will be skipped // _log->debug("Received empty message from sid %v", sid); continue; } if (recCount < 0) { _log->info("Received broken message from sid %v", sid); continue; } auto entity = this->directory->lookup(EntityDirectory::ID_SERVAL, sid, false); if (entity == nullptr) { this->_log->info("Received message from unknown serval node '%v'", sid); // Create new instance and request ids entity = this->directory->create(EntityDirectory::ID_SERVAL, sid); // At the beginning each discovered node is expected to be an ice node entity->setAvailable(true); this->discoveredEntity(entity); } else if (sid == this->ownSid) { // own message, will not be processed this->_log->debug("Received own message, will be skipped"); continue; } this->traffic.receivedBytes += recCount; ++this->traffic.messageReceivedCount; std::string json(buffer+3, buffer+recCount); auto message = Message::parse(buffer[0], json, this->containerFactory); message->setJobId(buffer[1]); message->setJobIndex(buffer[2]); if (message == nullptr) { this->_log->info("Received unknown or broken message from serval node '%v'", sid); continue; } message->setEntity(entity); // m.command = buffer[0]; // m.payload.clear(); // m.payload.reserve(recCount-1); // std::copy(buffer + 1, buffer + recCount, std::back_inserter(m.payload)); this->handleMessage(message); } } void ServalCommunication::discover() { std::unique_ptr<std::vector<serval_identity>> peers; if (this->local) { peers = this->serval->keyring.getSelf(); } else { peers = this->serval->keyring.getPeerIdentities(); } for (auto &sid : *peers) { auto entity = this->directory->lookup(EntityDirectory::ID_SERVAL, sid.sid); if (entity == nullptr) { // Create new instance and request ids entity = this->directory->create(EntityDirectory::ID_SERVAL, sid.sid); // At the beginning each discovered node is expected to be an ice node entity->setAvailable(true); this->discoveredEntity(entity); _log->info("New ID discovered: %v", entity->toString()); } entity->setActiveTimestamp(); } } int ServalCommunication::readMessage(std::vector<std::shared_ptr<Message>> &outMessages) { return 0; // reading messages is done in own thread } void ServalCommunication::sendMessage(std::shared_ptr<Message> msg) { std::string sid; if (false == msg->getEntity()->isAvailable()) { this->_log->error("Dropped Msg: Trying to send message to not available serval instance %v", msg->getEntity()->toString()); return; } if (false == msg->getEntity()->getId(EntityDirectory::ID_SERVAL, sid)) { this->_log->error("Trying to send message with serval to none serval instance %v", msg->getEntity()->toString()); return; } int size = 3; if (msg->isPayload()) { std::string json = msg->toJson(); size = json.size() + 3; if (size > 1024) { this->_log->error("Message could not be send to instance '%v', to large '%v' byte", msg->getEntity()->toString(), size); return; } std::lock_guard<std::mutex> guard(_mtxSend); std::copy(json.begin(), json.end(), this->buffer + 3); } buffer[0] = msg->getId(); buffer[1] = msg->getJobId(); buffer[2] = msg->getJobIndex(); this->traffic.sendBytes += size; ++this->traffic.messageSendCount; this->socket->send(sid, buffer, size); // std::cout << size << std::endl; } std::shared_ptr<BaseInformationSender> ServalCommunication::createSender(std::shared_ptr<BaseInformationStream> stream) { return nullptr; } std::shared_ptr<InformationReceiver> ServalCommunication::createReceiver(std::shared_ptr<BaseInformationStream> stream) { return nullptr; } } /* namespace ice */ <commit_msg>stuff<commit_after>/* * ServalCommunication.cpp * * Created on: Apr 15, 2016 * Author: sni */ #include "ServalCommunication.h" #include <chrono> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <ice/communication/messages/Message.h> #include <serval_interface.h> #include <serval_wrapper/MDPSocket.h> #include "ice/Entity.h" #include "IceServalBridge.h" // Short alias for this namespace namespace pt = boost::property_tree; namespace ice { ServalCommunication::ServalCommunication(std::weak_ptr<ICEngine> engine, std::string configPath, std::string const host, int const port, std::string const authName, std::string const authPass, bool const local) : CommunicationInterface(engine), configPath(configPath), host(host), port(port), authName(authName), authPass(authPass), serval(nullptr), local(local), running (false) { _log = el::Loggers::getLogger("ServalCommunication"); this->maxMessageSend = 2; } ServalCommunication::~ServalCommunication() { if (this->running) { this->running = false; } } std::shared_ptr<serval_interface> ServalCommunication::getServalInterface() { return this->serval; } void ServalCommunication::setOwnSid(std::string const &sid) { this->ownSid = sid; } void ServalCommunication::initInternal() { // create interface this->serval = std::make_shared<serval_interface>(this->configPath, this->host, this->port, this->authName, this->authPass); // get own id if (local) { auto oid = this->serval->keyring.addIdentity(); if (oid == nullptr) { // error case, own id could not be determined throw(std::runtime_error("Own serval id could not be determined")); } this->ownSid = oid->sid; this->self->addId(EntityDirectory::ID_SERVAL, this->ownSid); } else { if (this->ownSid == "") { auto id = this->serval->keyring.getSelf(); if (id == nullptr || id->size() == 0) { // error case, own id could not be determined throw(std::runtime_error("Own serval id could not be determined")); } this->ownSid = id->at(0).sid; this->self->addId(EntityDirectory::ID_SERVAL, this->ownSid); } } // create socket this->socket = this->serval->createSocket(SERVAL_PORT, this->ownSid); if (this->socket == nullptr) { throw (std::runtime_error("MDP socket could not be created")); return; } // init read thread this->running = true; this->worker = std::thread(&ServalCommunication::read, this); this->worker.detach(); } void ServalCommunication::cleanUpInternal() { this->running = false; if (this->serval != nullptr) { this->serval->cleanUp(); this->serval = nullptr; } } void ServalCommunication::read() { uint8_t buffer[4096]; std::string sid; while (this->running) { int recCount = this->socket->receive(sid, buffer, 4096); if (false == this->running) return; if (recCount == 0) { // huge amount of emtpy messages, will be skipped // _log->debug("Received empty message from sid %v", sid); continue; } if (recCount < 0) { _log->info("Received broken message from sid %v", sid); continue; } auto entity = this->directory->lookup(EntityDirectory::ID_SERVAL, sid, false); if (entity == nullptr) { this->_log->info("Received message from unknown serval node '%v'", sid); // Create new instance and request ids entity = this->directory->create(EntityDirectory::ID_SERVAL, sid); // At the beginning each discovered node is expected to be an ice node entity->setAvailable(true); this->discoveredEntity(entity); } else if (sid == this->ownSid) { // own message, will not be processed this->_log->debug("Received own message, will be skipped"); continue; } this->traffic.receivedBytes += recCount; ++this->traffic.messageReceivedCount; std::string json(buffer+3, buffer+recCount); auto message = Message::parse(buffer[0], json, this->containerFactory); message->setJobId(buffer[1]); message->setJobIndex(buffer[2]); if (message == nullptr) { this->_log->info("Received unknown or broken message from serval node '%v'", sid); continue; } message->setEntity(entity); // m.command = buffer[0]; // m.payload.clear(); // m.payload.reserve(recCount-1); // std::copy(buffer + 1, buffer + recCount, std::back_inserter(m.payload)); this->handleMessage(message); } } void ServalCommunication::discover() { std::unique_ptr<std::vector<serval_identity>> peers; if (this->local) { peers = this->serval->keyring.getSelf(); } else { peers = this->serval->keyring.getPeerIdentities(); } for (auto &sid : *peers) { auto entity = this->directory->lookup(EntityDirectory::ID_SERVAL, sid.sid); if (entity == nullptr) { // Create new instance and request ids entity = this->directory->create(EntityDirectory::ID_SERVAL, sid.sid); // At the beginning each discovered node is expected to be an ice node entity->setAvailable(true); this->discoveredEntity(entity); _log->info("New ID discovered: %v", entity->toString()); } entity->setActiveTimestamp(); } } int ServalCommunication::readMessage(std::vector<std::shared_ptr<Message>> &outMessages) { return 0; // reading messages is done in own thread } void ServalCommunication::sendMessage(std::shared_ptr<Message> msg) { std::string sid; if (false == msg->getEntity()->isAvailable()) { this->_log->error("Dropped Msg: Trying to send message to not available serval instance %v", msg->getEntity()->toString()); return; } if (false == msg->getEntity()->getId(EntityDirectory::ID_SERVAL, sid)) { this->_log->error("Trying to send message with serval to none serval instance %v", msg->getEntity()->toString()); return; } int size = 3; if (msg->isPayload()) { std::string json = msg->toJson(); size = json.size() + 3; if (size > 1024) { this->_log->error("Message could not be send to instance '%v', to large '%v' byte", msg->getEntity()->toString(), size); return; } std::lock_guard<std::mutex> guard(_mtxSend); std::copy(json.begin(), json.end(), this->buffer + 3); } buffer[0] = msg->getId(); buffer[1] = msg->getJobId(); buffer[2] = msg->getJobIndex(); this->traffic.sendBytes += size; ++this->traffic.messageSendCount; this->socket->send(sid, buffer, size); // std::cout << size << std::endl; } std::shared_ptr<BaseInformationSender> ServalCommunication::createSender(std::shared_ptr<BaseInformationStream> stream) { return nullptr; } std::shared_ptr<InformationReceiver> ServalCommunication::createReceiver(std::shared_ptr<BaseInformationStream> stream) { return nullptr; } } /* namespace ice */ <|endoftext|>
<commit_before>#include "MemAllocator.h" #include <iostream> #include <Windows.h> #define CHUNK_MAX_SIZE ~(1 << 31) MemAllocator::MemAllocator() { poolSize = 10 * 1024; memoryPool = VirtualAlloc(NULL, poolSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (!memoryPool) { throw std::exception("Failed to allocate memory"); } setSize(memoryPool, poolSize - 2 * sizeof(unsigned int)); setAllocated(memoryPool, 0); } MemAllocator::~MemAllocator() { VirtualFree(memoryPool, poolSize, MEM_RELEASE); } void* MemAllocator::MyMalloc(size_t size) { return NULL; } void MemAllocator::MyFree(void* ptr) { } void MemAllocator::setSize(void* ptr, unsigned int size) { if (!ptr) { return; } if (size > CHUNK_MAX_SIZE) { throw std::exception("Chunk size is too big!"); } *(unsigned int*)ptr = size; *(unsigned int*)((char*)ptr + sizeof(unsigned int) + size) = size; } void MemAllocator::setAllocated(void* ptr, char isAllocated) { if (!ptr){ return; } unsigned int chunkSize = *(unsigned int*)ptr; if (isAllocated) { *(unsigned int*)ptr |= (1 << 31); *(unsigned int*)((char*)ptr + sizeof(unsigned int) + chunkSize) |= (1 << 31); } else { *(unsigned int*)ptr &= 0; *(unsigned int*)((char*)ptr + sizeof(unsigned int) + chunkSize) &= 0; } } void MemAllocator::mergeChunks(void* l, void* r) { if (!l || !r) { return; } setSize(l, chunkSize(l) + chunkSize(r)); setAllocated(l, 0); } unsigned int MemAllocator::chunkSize(void* ptr) { return (*(unsigned int*)ptr & ~(1 << 31)); } bool MemAllocator::isAllocated(void* ptr) { return (*(unsigned int*)ptr & (1 << 31)); }<commit_msg>fixed setAllocated, setSize and start implementing MyMalloc<commit_after>#include "MemAllocator.h" #include <iostream> #include <Windows.h> #define CHUNK_MAX_SIZE ~(1 << 31) MemAllocator::MemAllocator() { poolSize = 10 * 1024; memoryPool = VirtualAlloc(NULL, poolSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (!memoryPool) { throw std::exception("Failed to allocate memory"); } setSize(memoryPool, poolSize - 2 * sizeof(unsigned int)); setAllocated(memoryPool, 0); } MemAllocator::~MemAllocator() { VirtualFree(memoryPool, poolSize, MEM_RELEASE); } void* MemAllocator::MyMalloc(size_t size) { bool done = false; char* currentPos = (char*)memoryPool; char* poolEnd = (char*)memoryPool + poolSize; for (;; currentPos += chunkSize(currentPos) + 2*sizeof(unsigned int) - 1) { if (!isAllocated(currentPos)) { int a; a = 4; //setAllocated(currentPos, 1); } if (currentPos + 2 * sizeof(unsigned int) + chunkSize(currentPos) == poolEnd) { break; } } return NULL; } void MemAllocator::MyFree(void* ptr) { } void MemAllocator::setSize(void* ptr, unsigned int size) { if (!ptr) { return; } if (size > CHUNK_MAX_SIZE) { throw std::exception("Chunk size is too big!"); } *(unsigned int*)ptr = size; *(unsigned int*)((char*)ptr + 2*sizeof(unsigned int) + size - 1) = size; } void MemAllocator::setAllocated(void* ptr, char isAllocated) { if (!ptr){ return; } unsigned int chunkSize = *(unsigned int*)ptr; if (isAllocated) { *(unsigned int*)ptr |= (1 << 31); *(unsigned int*)((char*)ptr + 2*sizeof(unsigned int) + chunkSize - 1) |= (1 << 31); } else { *(unsigned int*)ptr &= ~(1 << 31); *(unsigned int*)((char*)ptr + 2*sizeof(unsigned int) + chunkSize - 1) &= ~(1 << 31); } } void MemAllocator::mergeChunks(void* l, void* r) { if (!l || !r) { return; } setSize(l, chunkSize(l) + chunkSize(r)); setAllocated(l, 0); } unsigned int MemAllocator::chunkSize(void* ptr) { return (*(unsigned int*)ptr & ~(1 << 31)); } bool MemAllocator::isAllocated(void* ptr) { return (*(unsigned int*)ptr & (1 << 31)); }<|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <gtest/gtest.h> #include <tvm/te/operation.h> #include <tvm/topi/elemwise.h> namespace tvm { namespace topi { TEST(Tensor, Basic) { using namespace tvm; Var m("m"), n("n"), l("l"); Tensor A = placeholder({m, l}, DataType::Float(32), "A"); auto C = topi::exp(A); } } // namespace topi } // namespace tvm int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); testing::FLAGS_gtest_death_test_style = "threadsafe"; return RUN_ALL_TESTS(); } <commit_msg>Remove unused variable in topi cpp test (#8549)<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #include <gtest/gtest.h> #include <tvm/te/operation.h> #include <tvm/topi/elemwise.h> namespace tvm { namespace topi { TEST(Tensor, Basic) { using namespace tvm; Var m("m"), l("l"); Tensor A = placeholder({m, l}, DataType::Float(32), "A"); auto C = topi::exp(A); } } // namespace topi } // namespace tvm int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); testing::FLAGS_gtest_death_test_style = "threadsafe"; return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/* * Copyright 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #define BOOST_TEST_MODULE core #include <boost/test/unit_test.hpp> #include "utils/dynamic_bitset.hh" BOOST_AUTO_TEST_CASE(test_set_clear_test) { utils::dynamic_bitset bits(178); for (size_t i = 0; i < 178; i++) { BOOST_REQUIRE(!bits.test(i)); } for (size_t i = 0; i < 178; i += 2) { bits.set(i); } for (size_t i = 0; i < 178; i++) { if (i % 2) { BOOST_REQUIRE(!bits.test(i)); } else { BOOST_REQUIRE(bits.test(i)); } } for (size_t i = 0; i < 178; i += 4) { bits.clear(i); } for (size_t i = 0; i < 178; i++) { if (i % 2 || i % 4 == 0) { BOOST_REQUIRE(!bits.test(i)); } else { BOOST_REQUIRE(bits.test(i)); } } } BOOST_AUTO_TEST_CASE(test_find_first_next) { utils::dynamic_bitset bits(178); for (size_t i = 0; i < 178; i++) { BOOST_REQUIRE(!bits.test(i)); } BOOST_REQUIRE_EQUAL(bits.find_first_set(), utils::dynamic_bitset::npos); for (size_t i = 0; i < 178; i += 2) { bits.set(i); } size_t i = bits.find_first_set(); BOOST_REQUIRE_EQUAL(i, 0); do { auto j = bits.find_next_set(i); BOOST_REQUIRE_EQUAL(i + 2, j); i = j; } while (i < 176); BOOST_REQUIRE_EQUAL(bits.find_next_set(i), utils::dynamic_bitset::npos); for (size_t i = 0; i < 178; i += 4) { bits.clear(i); } i = bits.find_first_set(); BOOST_REQUIRE_EQUAL(i, 2); do { auto j = bits.find_next_set(i); BOOST_REQUIRE_EQUAL(i + 4, j); i = j; } while (i < 174); BOOST_REQUIRE_EQUAL(bits.find_next_set(i), utils::dynamic_bitset::npos); } BOOST_AUTO_TEST_CASE(test_find_last_prev) { utils::dynamic_bitset bits(178); for (size_t i = 0; i < 178; i++) { BOOST_REQUIRE(!bits.test(i)); } BOOST_REQUIRE_EQUAL(bits.find_last_set(), utils::dynamic_bitset::npos); for (size_t i = 0; i < 178; i += 2) { bits.set(i); } size_t i = bits.find_last_set(); BOOST_REQUIRE_EQUAL(i, 176); for (size_t i = 0; i < 178; i += 4) { bits.clear(i); } i = bits.find_last_set(); BOOST_REQUIRE_EQUAL(i, 174); } <commit_msg>tests: add random test for dynamic_bitset<commit_after>/* * Copyright 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #define BOOST_TEST_MODULE core #include <boost/test/unit_test.hpp> #include <boost/algorithm/cxx11/any_of.hpp> #include <boost/range/irange.hpp> #include <vector> #include <random> #include "utils/dynamic_bitset.hh" BOOST_AUTO_TEST_CASE(test_set_clear_test) { utils::dynamic_bitset bits(178); for (size_t i = 0; i < 178; i++) { BOOST_REQUIRE(!bits.test(i)); } for (size_t i = 0; i < 178; i += 2) { bits.set(i); } for (size_t i = 0; i < 178; i++) { if (i % 2) { BOOST_REQUIRE(!bits.test(i)); } else { BOOST_REQUIRE(bits.test(i)); } } for (size_t i = 0; i < 178; i += 4) { bits.clear(i); } for (size_t i = 0; i < 178; i++) { if (i % 2 || i % 4 == 0) { BOOST_REQUIRE(!bits.test(i)); } else { BOOST_REQUIRE(bits.test(i)); } } } BOOST_AUTO_TEST_CASE(test_find_first_next) { utils::dynamic_bitset bits(178); for (size_t i = 0; i < 178; i++) { BOOST_REQUIRE(!bits.test(i)); } BOOST_REQUIRE_EQUAL(bits.find_first_set(), utils::dynamic_bitset::npos); for (size_t i = 0; i < 178; i += 2) { bits.set(i); } size_t i = bits.find_first_set(); BOOST_REQUIRE_EQUAL(i, 0); do { auto j = bits.find_next_set(i); BOOST_REQUIRE_EQUAL(i + 2, j); i = j; } while (i < 176); BOOST_REQUIRE_EQUAL(bits.find_next_set(i), utils::dynamic_bitset::npos); for (size_t i = 0; i < 178; i += 4) { bits.clear(i); } i = bits.find_first_set(); BOOST_REQUIRE_EQUAL(i, 2); do { auto j = bits.find_next_set(i); BOOST_REQUIRE_EQUAL(i + 4, j); i = j; } while (i < 174); BOOST_REQUIRE_EQUAL(bits.find_next_set(i), utils::dynamic_bitset::npos); } BOOST_AUTO_TEST_CASE(test_find_last_prev) { utils::dynamic_bitset bits(178); for (size_t i = 0; i < 178; i++) { BOOST_REQUIRE(!bits.test(i)); } BOOST_REQUIRE_EQUAL(bits.find_last_set(), utils::dynamic_bitset::npos); for (size_t i = 0; i < 178; i += 2) { bits.set(i); } size_t i = bits.find_last_set(); BOOST_REQUIRE_EQUAL(i, 176); for (size_t i = 0; i < 178; i += 4) { bits.clear(i); } i = bits.find_last_set(); BOOST_REQUIRE_EQUAL(i, 174); } static void test_random_ops(size_t size, std::random_device& rd ) { // BOOST_REQUIRE and friends are very slow, just use regular throws instead. auto require = [] (bool b) { if (!b) { throw 0; } }; auto require_equal = [&] (const auto& a, const auto& b) { require(a == b); }; utils::dynamic_bitset db{size}; std::vector<bool> bv(size, false); std::uniform_int_distribution<size_t> global_op_dist(0, size-1); std::uniform_int_distribution<size_t> bit_dist(0, size-1); std::uniform_int_distribution<int> global_op_selection_dist(0, 1); std::uniform_int_distribution<int> single_op_selection_dist(0, 5); auto is_set = [&] (size_t i) -> bool { return bv[i]; }; size_t limit = size * 100; #ifdef DEBUG limit = std::min<size_t>(limit, 20000); #endif for (size_t i = 0; i != limit; ++i) { if (global_op_dist(rd) == 0) { // perform a global operation switch (global_op_selection_dist(rd)) { case 0: for (size_t j = 0; j != size; ++j) { db.clear(j); bv[j] = false; } break; case 1: for (size_t j = 0; j != size; ++j) { db.set(j); bv[j] = true; } break; } } else { // perform a single-bit operation switch (single_op_selection_dist(rd)) { case 0: { auto bit = bit_dist(rd); db.set(bit); bv[bit] = true; break; } case 1: { auto bit = bit_dist(rd); db.clear(bit); bv[bit] = false; break; } case 2: { auto bit = bit_dist(rd); bool dbb = db.test(bit); bool bvb = bv[bit]; require_equal(dbb, bvb); break; } case 3: { auto bit = bit_dist(rd); auto next = db.find_next_set(bit); if (next == db.npos) { require(!boost::algorithm::any_of(boost::irange<size_t>(bit+1, size), is_set)); } else { require(!boost::algorithm::any_of(boost::irange<size_t>(bit+1, next), is_set)); require(is_set(next)); } break; } case 4: { auto next = db.find_first_set(); if (next == db.npos) { require(!boost::algorithm::any_of(boost::irange<size_t>(0, size), is_set)); } else { require(!boost::algorithm::any_of(boost::irange<size_t>(0, next), is_set)); require(is_set(next)); } break; } case 5: { auto next = db.find_last_set(); if (next == db.npos) { require(!boost::algorithm::any_of(boost::irange<size_t>(0, size), is_set)); } else { require(!boost::algorithm::any_of(boost::irange<size_t>(next + 1, size), is_set)); require(is_set(next)); } break; } } } } } BOOST_AUTO_TEST_CASE(test_random_operations) { std::random_device rd; for (auto size : { 1, 63, 64, 65, 2000, 4096-65, 4096-64, 4096-63, 4096-1, 4096, 4096+1, 262144-1, 262144, 262144+1}) { BOOST_CHECK_NO_THROW(test_random_ops(size, rd)); } } <|endoftext|>
<commit_before>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #include <dune/stuff/test/test_common.hh> #include <dune/common/exceptions.hh> #ifndef HAVE_ALUGRID static_assert(false, "This test requires alugrid!"); #endif #include <dune/grid/alugrid.hh> #include <dune/stuff/common/color.hh> #undef HAVE_FASP #include "elliptic-testcases.hh" #include "elliptic-cg-discretization.hh" #include "elliptic-sipdg-discretization.hh" #include "elliptic-swipdg-discretization.hh" class errors_are_not_as_expected : public Dune::Exception { }; typedef Dune::ALUConformGrid<2, 2> AluConform2dGridType; // change this to toggle output std::ostream& out = std::cout; // std::ostream& out = DSC_LOG.devnull(); typedef testing::Types<EllipticTestCase::ESV07<AluConform2dGridType>, EllipticTestCase::LocalThermalBlock<AluConform2dGridType>, EllipticTestCase::ER07<AluConform2dGridType>, EllipticTestCase::MixedBoundaryTypes<AluConform2dGridType>, EllipticTestCase::Spe10Model1<AluConform2dGridType>> AluConform2dTestCases; template <class TestCase> struct EllipticCGDiscretization : public ::testing::Test { void check() const { const TestCase test_case; test_case.print_header(out); out << std::endl; EllipticCG::EocStudy<TestCase, 1> eoc_study(test_case); auto errors = eoc_study.run(out); for (const auto& norm : eoc_study.provided_norms()) if (errors[norm] > eoc_study.expected_results(norm)) DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!"); } }; TYPED_TEST_CASE(EllipticCGDiscretization, AluConform2dTestCases); TYPED_TEST(EllipticCGDiscretization, produces_correct_results) { this->check(); } template <class TestCase> struct EllipticSIPDGDiscretization : public ::testing::Test { void check() const { if (std::is_same<TestCase, EllipticTestCase::Spe10Model1<Dune::ALUConformGrid<2, 2>>>::value) { std::cerr << Dune::Stuff::Common::colorStringRed( "EllipticSIPDGDiscretization does not work for " + "EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > >!") << std::end; } else { const TestCase test_case; test_case.print_header(out); out << std::endl; size_t failure = 0; EllipticSIPDG::EocStudy<TestCase, 1> eoc_study_1(test_case); auto errors_1 = eoc_study_1.run(out); out << std::endl; EllipticSIPDG::EocStudy<TestCase, 2> eoc_study_2(test_case); auto errors_2 = eoc_study_2.run(out); for (const auto& norm : eoc_study_1.provided_norms()) if (errors_1[norm] > eoc_study_1.expected_results(norm)) ++failure; for (const auto& norm : eoc_study_2.provided_norms()) if (errors_2[norm] > eoc_study_2.expected_results(norm)) ++failure; if (failure) DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!"); } } }; TYPED_TEST_CASE(EllipticSIPDGDiscretization, AluConform2dTestCases); TYPED_TEST(EllipticSIPDGDiscretization, produces_correct_results) { this->check(); } template <class TestCase> struct EllipticSWIPDGDiscretization : public ::testing::Test { void check() const { const TestCase test_case; test_case.print_header(out); out << std::endl; size_t failure = 0; EllipticSWIPDG::EocStudy<TestCase, 1> eoc_study_1(test_case); auto errors_1 = eoc_study_1.run(out); out << std::endl; EllipticSWIPDG::EocStudy<TestCase, 2> eoc_study_2(test_case); auto errors_2 = eoc_study_2.run(out); for (const auto& norm : eoc_study_1.provided_norms()) if (errors_1[norm] > eoc_study_1.expected_results(norm)) ++failure; for (const auto& norm : eoc_study_2.provided_norms()) if (errors_2[norm] > eoc_study_2.expected_results(norm)) ++failure; if (failure) DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!"); } }; TYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases); TYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) { this->check(); } int main(int argc, char** argv) { try { test_init(argc, argv); return RUN_ALL_TESTS(); } catch (Dune::Exception& e) { std::cerr << "Dune reported error: " << e.what() << std::endl; std::abort(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; std::abort(); } catch (...) { std::cerr << "Unknown exception thrown!" << std::endl; std::abort(); } // try } <commit_msg>[elliptic-discretizations] fixed d30dede42b70<commit_after>// This file is part of the dune-gdt project: // http://users.dune-project.org/projects/dune-gdt // Copyright holders: Felix Albrecht // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) #include <dune/stuff/test/test_common.hh> #include <dune/common/exceptions.hh> #ifndef HAVE_ALUGRID static_assert(false, "This test requires alugrid!"); #endif #include <dune/grid/alugrid.hh> #include <dune/stuff/common/color.hh> #undef HAVE_FASP #include "elliptic-testcases.hh" #include "elliptic-cg-discretization.hh" #include "elliptic-sipdg-discretization.hh" #include "elliptic-swipdg-discretization.hh" class errors_are_not_as_expected : public Dune::Exception { }; typedef Dune::ALUConformGrid<2, 2> AluConform2dGridType; // change this to toggle output std::ostream& out = std::cout; // std::ostream& out = DSC_LOG.devnull(); typedef testing::Types<EllipticTestCase::ESV07<AluConform2dGridType>, EllipticTestCase::LocalThermalBlock<AluConform2dGridType>, EllipticTestCase::ER07<AluConform2dGridType>, EllipticTestCase::MixedBoundaryTypes<AluConform2dGridType>, EllipticTestCase::Spe10Model1<AluConform2dGridType>> AluConform2dTestCases; template <class TestCase> struct EllipticCGDiscretization : public ::testing::Test { void check() const { const TestCase test_case; test_case.print_header(out); out << std::endl; EllipticCG::EocStudy<TestCase, 1> eoc_study(test_case); auto errors = eoc_study.run(out); for (const auto& norm : eoc_study.provided_norms()) if (errors[norm] > eoc_study.expected_results(norm)) DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!"); } }; TYPED_TEST_CASE(EllipticCGDiscretization, AluConform2dTestCases); TYPED_TEST(EllipticCGDiscretization, produces_correct_results) { this->check(); } template <class TestCase> struct EllipticSIPDGDiscretization : public ::testing::Test { void check() const { if (std::is_same<TestCase, EllipticTestCase::Spe10Model1<Dune::ALUConformGrid<2, 2>>>::value) { std::cerr << Dune::Stuff::Common::colorStringRed("EllipticSIPDGDiscretization does not work for " "EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > >!") << std::endl; } else { const TestCase test_case; test_case.print_header(out); out << std::endl; size_t failure = 0; EllipticSIPDG::EocStudy<TestCase, 1> eoc_study_1(test_case); auto errors_1 = eoc_study_1.run(out); out << std::endl; EllipticSIPDG::EocStudy<TestCase, 2> eoc_study_2(test_case); auto errors_2 = eoc_study_2.run(out); for (const auto& norm : eoc_study_1.provided_norms()) if (errors_1[norm] > eoc_study_1.expected_results(norm)) ++failure; for (const auto& norm : eoc_study_2.provided_norms()) if (errors_2[norm] > eoc_study_2.expected_results(norm)) ++failure; if (failure) DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!"); } } }; TYPED_TEST_CASE(EllipticSIPDGDiscretization, AluConform2dTestCases); TYPED_TEST(EllipticSIPDGDiscretization, produces_correct_results) { this->check(); } template <class TestCase> struct EllipticSWIPDGDiscretization : public ::testing::Test { void check() const { const TestCase test_case; test_case.print_header(out); out << std::endl; size_t failure = 0; EllipticSWIPDG::EocStudy<TestCase, 1> eoc_study_1(test_case); auto errors_1 = eoc_study_1.run(out); out << std::endl; EllipticSWIPDG::EocStudy<TestCase, 2> eoc_study_2(test_case); auto errors_2 = eoc_study_2.run(out); for (const auto& norm : eoc_study_1.provided_norms()) if (errors_1[norm] > eoc_study_1.expected_results(norm)) ++failure; for (const auto& norm : eoc_study_2.provided_norms()) if (errors_2[norm] > eoc_study_2.expected_results(norm)) ++failure; if (failure) DUNE_THROW(errors_are_not_as_expected, "They really ain't (or you have to lower the expectations)!"); } }; TYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases); TYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) { this->check(); } int main(int argc, char** argv) { try { test_init(argc, argv); return RUN_ALL_TESTS(); } catch (Dune::Exception& e) { std::cerr << "Dune reported error: " << e.what() << std::endl; std::abort(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; std::abort(); } catch (...) { std::cerr << "Unknown exception thrown!" << std::endl; std::abort(); } // try } <|endoftext|>
<commit_before>/* * Launch and manage WAS child processes. * * author: Max Kellermann <mk@cm4all.com> */ #include "was_stock.hxx" #include "was_quark.h" #include "was_launch.hxx" #include "stock/MapStock.hxx" #include "stock/Class.hxx" #include "stock/Item.hxx" #include "child_manager.hxx" #include "async.hxx" #include "net/ConnectSocket.hxx" #include "spawn/ChildOptions.hxx" #include "spawn/JailConfig.hxx" #include "pool.hxx" #include "event/Event.hxx" #include "event/Callback.hxx" #include "util/ConstBuffer.hxx" #include "util/Cast.hxx" #include <daemon/log.h> #include <glib.h> #include <assert.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <sys/socket.h> #include <sys/un.h> #include <signal.h> #include <stdlib.h> struct WasChildParams { const char *executable_path; ConstBuffer<const char *> args; const ChildOptions *options; WasChildParams(const char *_executable_path, ConstBuffer<const char *> _args, const ChildOptions &_options) :executable_path(_executable_path), args(_args), options(&_options) {} const char *GetStockKey(struct pool &pool) const; }; struct WasChild final : PoolStockItem { const char *key; JailParams jail_params; struct jail_config jail_config; WasProcess process; Event event; explicit WasChild(struct pool &_pool, CreateStockItem c) :PoolStockItem(_pool, c) {} ~WasChild() override; void EventCallback(evutil_socket_t fd, short events); /* virtual methods from class StockItem */ bool Borrow(gcc_unused void *ctx) override { event.Delete(); return true; } bool Release(gcc_unused void *ctx) override { static constexpr struct timeval tv = { .tv_sec = 300, .tv_usec = 0, }; event.Add(tv); return true; } }; const char * WasChildParams::GetStockKey(struct pool &pool) const { const char *key = executable_path; for (auto i : args) key = p_strcat(&pool, key, " ", i, nullptr); for (auto i : options->env) key = p_strcat(&pool, key, "$", i, nullptr); char options_buffer[4096]; *options->MakeId(options_buffer) = 0; if (*options_buffer != 0) key = p_strcat(&pool, key, options_buffer, nullptr); return key; } static void was_child_callback(gcc_unused int status, void *ctx) { WasChild *child = (WasChild *)ctx; child->process.pid = -1; } /* * libevent callback * */ inline void WasChild::EventCallback(evutil_socket_t fd, short events) { assert(fd == process.control_fd); if ((events & EV_TIMEOUT) == 0) { char buffer; ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT); if (nbytes < 0) daemon_log(2, "error on idle WAS control connection: %s\n", strerror(errno)); else if (nbytes > 0) daemon_log(2, "unexpected data from idle WAS control connection\n"); } InvokeIdleDisconnect(); pool_commit(); } /* * stock class * */ static void was_stock_create(gcc_unused void *ctx, struct pool &parent_pool, CreateStockItem c, const char *key, void *info, struct pool &caller_pool, struct async_operation_ref &async_ref) { WasChildParams *params = (WasChildParams *)info; auto &pool = *pool_new_linear(&parent_pool, "was_child", 2048); auto *child = NewFromPool<WasChild>(pool, pool, c); (void)caller_pool; (void)async_ref; assert(key != nullptr); assert(params != nullptr); assert(params->executable_path != nullptr); child->key = p_strdup(pool, key); const ChildOptions &options = *params->options; if (options.jail.enabled) { child->jail_params.CopyFrom(pool, options.jail); if (!jail_config_load(&child->jail_config, "/etc/cm4all/jailcgi/jail.conf", &pool)) { GError *error = g_error_new(was_quark(), 0, "Failed to load /etc/cm4all/jailcgi/jail.conf"); child->InvokeCreateError(error); return; } } else child->jail_params.enabled = false; GError *error = nullptr; if (!was_launch(&child->process, params->executable_path, params->args, options, &error)) { child->InvokeCreateError(error); return; } child_register(child->process.pid, key, was_child_callback, child); child->event.Set(child->process.control_fd, EV_READ|EV_TIMEOUT, MakeEventCallback(WasChild, EventCallback), child); child->InvokeCreateSuccess(); } WasChild::~WasChild() { if (process.pid >= 0) child_kill(process.pid); if (process.control_fd >= 0) event.Delete(); process.Close(); } static constexpr StockClass was_stock_class = { .create = was_stock_create, }; /* * interface * */ StockMap * was_stock_new(struct pool *pool, unsigned limit, unsigned max_idle) { return hstock_new(*pool, was_stock_class, nullptr, limit, max_idle); } void was_stock_get(StockMap *hstock, struct pool *pool, const ChildOptions &options, const char *executable_path, ConstBuffer<const char *> args, StockGetHandler &handler, struct async_operation_ref &async_ref) { auto params = NewFromPool<WasChildParams>(*pool, executable_path, args, options); hstock_get(*hstock, *pool, params->GetStockKey(*pool), params, handler, async_ref); } const WasProcess & was_stock_item_get(const StockItem &item) { auto *child = (const WasChild *)&item; return child->process; } const char * was_stock_translate_path(const StockItem &item, const char *path, struct pool *pool) { auto *child = (const WasChild *)&item; if (!child->jail_params.enabled) /* no JailCGI - application's namespace is the same as ours, no translation needed */ return path; const char *jailed = jail_translate_path(&child->jail_config, path, child->jail_params.home_directory, pool); return jailed != nullptr ? jailed : path; } <commit_msg>was/stock: convert pointer to reference<commit_after>/* * Launch and manage WAS child processes. * * author: Max Kellermann <mk@cm4all.com> */ #include "was_stock.hxx" #include "was_quark.h" #include "was_launch.hxx" #include "stock/MapStock.hxx" #include "stock/Class.hxx" #include "stock/Item.hxx" #include "child_manager.hxx" #include "async.hxx" #include "net/ConnectSocket.hxx" #include "spawn/ChildOptions.hxx" #include "spawn/JailConfig.hxx" #include "pool.hxx" #include "event/Event.hxx" #include "event/Callback.hxx" #include "util/ConstBuffer.hxx" #include "util/Cast.hxx" #include <daemon/log.h> #include <glib.h> #include <assert.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <string.h> #include <sys/socket.h> #include <sys/un.h> #include <signal.h> #include <stdlib.h> struct WasChildParams { const char *executable_path; ConstBuffer<const char *> args; const ChildOptions &options; WasChildParams(const char *_executable_path, ConstBuffer<const char *> _args, const ChildOptions &_options) :executable_path(_executable_path), args(_args), options(_options) {} const char *GetStockKey(struct pool &pool) const; }; struct WasChild final : PoolStockItem { const char *key; JailParams jail_params; struct jail_config jail_config; WasProcess process; Event event; explicit WasChild(struct pool &_pool, CreateStockItem c) :PoolStockItem(_pool, c) {} ~WasChild() override; void EventCallback(evutil_socket_t fd, short events); /* virtual methods from class StockItem */ bool Borrow(gcc_unused void *ctx) override { event.Delete(); return true; } bool Release(gcc_unused void *ctx) override { static constexpr struct timeval tv = { .tv_sec = 300, .tv_usec = 0, }; event.Add(tv); return true; } }; const char * WasChildParams::GetStockKey(struct pool &pool) const { const char *key = executable_path; for (auto i : args) key = p_strcat(&pool, key, " ", i, nullptr); for (auto i : options.env) key = p_strcat(&pool, key, "$", i, nullptr); char options_buffer[4096]; *options.MakeId(options_buffer) = 0; if (*options_buffer != 0) key = p_strcat(&pool, key, options_buffer, nullptr); return key; } static void was_child_callback(gcc_unused int status, void *ctx) { WasChild *child = (WasChild *)ctx; child->process.pid = -1; } /* * libevent callback * */ inline void WasChild::EventCallback(evutil_socket_t fd, short events) { assert(fd == process.control_fd); if ((events & EV_TIMEOUT) == 0) { char buffer; ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT); if (nbytes < 0) daemon_log(2, "error on idle WAS control connection: %s\n", strerror(errno)); else if (nbytes > 0) daemon_log(2, "unexpected data from idle WAS control connection\n"); } InvokeIdleDisconnect(); pool_commit(); } /* * stock class * */ static void was_stock_create(gcc_unused void *ctx, struct pool &parent_pool, CreateStockItem c, const char *key, void *info, struct pool &caller_pool, struct async_operation_ref &async_ref) { WasChildParams *params = (WasChildParams *)info; auto &pool = *pool_new_linear(&parent_pool, "was_child", 2048); auto *child = NewFromPool<WasChild>(pool, pool, c); (void)caller_pool; (void)async_ref; assert(key != nullptr); assert(params != nullptr); assert(params->executable_path != nullptr); child->key = p_strdup(pool, key); const ChildOptions &options = params->options; if (options.jail.enabled) { child->jail_params.CopyFrom(pool, options.jail); if (!jail_config_load(&child->jail_config, "/etc/cm4all/jailcgi/jail.conf", &pool)) { GError *error = g_error_new(was_quark(), 0, "Failed to load /etc/cm4all/jailcgi/jail.conf"); child->InvokeCreateError(error); return; } } else child->jail_params.enabled = false; GError *error = nullptr; if (!was_launch(&child->process, params->executable_path, params->args, options, &error)) { child->InvokeCreateError(error); return; } child_register(child->process.pid, key, was_child_callback, child); child->event.Set(child->process.control_fd, EV_READ|EV_TIMEOUT, MakeEventCallback(WasChild, EventCallback), child); child->InvokeCreateSuccess(); } WasChild::~WasChild() { if (process.pid >= 0) child_kill(process.pid); if (process.control_fd >= 0) event.Delete(); process.Close(); } static constexpr StockClass was_stock_class = { .create = was_stock_create, }; /* * interface * */ StockMap * was_stock_new(struct pool *pool, unsigned limit, unsigned max_idle) { return hstock_new(*pool, was_stock_class, nullptr, limit, max_idle); } void was_stock_get(StockMap *hstock, struct pool *pool, const ChildOptions &options, const char *executable_path, ConstBuffer<const char *> args, StockGetHandler &handler, struct async_operation_ref &async_ref) { auto params = NewFromPool<WasChildParams>(*pool, executable_path, args, options); hstock_get(*hstock, *pool, params->GetStockKey(*pool), params, handler, async_ref); } const WasProcess & was_stock_item_get(const StockItem &item) { auto *child = (const WasChild *)&item; return child->process; } const char * was_stock_translate_path(const StockItem &item, const char *path, struct pool *pool) { auto *child = (const WasChild *)&item; if (!child->jail_params.enabled) /* no JailCGI - application's namespace is the same as ours, no translation needed */ return path; const char *jailed = jail_translate_path(&child->jail_config, path, child->jail_params.home_directory, pool); return jailed != nullptr ? jailed : path; } <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \author (rdo@rk9.bmstu.ru) \authors (lord.tiran@gmail.com) \date 10.05.2009 \brief common- \indent 4T */ // ----------------------------------------------------------------------- PLATFORM #include "utils/platform.h" // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include <boost/regex.hpp> #define BOOST_TEST_MODULE RDOCommon_Test #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/rdocommon.h" #include "utils/rdofile.h" #include "utils/rdotime.h" #include "utils/test/utils_common_test/resource.h" // -------------------------------------------------------------------------------- const tstring s_testFileName(_T("test_file")); const tstring s_resourceStr1(_T("test_101")); const tstring s_resourceStr2(_T("test_102 22")); const tstring s_resourceStr3(_T("test_103 test_101 33 test_102 22")); const ruint64 s_createTestLocalTime = 129557633912040000; BOOST_AUTO_TEST_SUITE(RDOCommon_Test) #ifdef OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_ResourceFormat) { tstring str1 = rdo::format(IDS_STRING101); BOOST_CHECK(str1 == s_resourceStr1); tstring str2 = rdo::format(IDS_STRING102, 22); BOOST_CHECK(str2 == s_resourceStr2); tstring str3 = rdo::format(IDS_STRING103, str1.c_str(), 33, str2.c_str()); BOOST_CHECK(str3 == s_resourceStr3); } #endif // OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_FileCreate) { BOOST_CHECK(rdo::File::create(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileExist) { BOOST_CHECK(rdo::File::exist(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileReadOnly) { BOOST_CHECK(!rdo::File::read_only(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileRemove) { BOOST_CHECK(rdo::File::unlink(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInLinux) { tstring file(_T("/rdo/ /files/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T("/rdo/ /files/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInLinux) { tstring file(_T("/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T("/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } #ifdef OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows) { tstring file(_T(":/rdo/ /files/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":/rdo/ /files/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows) { tstring file(_T(":/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows_BackSlash) { tstring file(_T(":\\rdo\\ \\files\\.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":\\rdo\\ \\files\\")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows_BackSlash) { tstring file(_T(":\\.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":\\")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } #endif // #endif BOOST_AUTO_TEST_CASE(RDOCommon_GetTempFile) { std::set<tstring> name_set; for(int i = 0; i < 15; ++i) { tstring file_name = rdo::File::getTempFileName(); BOOST_CHECK(name_set.find(file_name) == name_set.end()); name_set.insert(file_name); } } BOOST_AUTO_TEST_CASE(RDOCommon_Time) { rdo::Time timeValue = rdo::Time::local(); BOOST_CHECK(timeValue > s_createTestLocalTime); std::cout << _T("Today: ") << timeValue.asString() << _T(" is not it?"); } BOOST_AUTO_TEST_SUITE_END() // RDOCommon_Test <commit_msg> - тест сервера автосборки<commit_after>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \author (rdo@rk9.bmstu.ru) \authors (lord.tiran@gmail.com) \date 10.05.2009 \brief common- \indent 4T */ // ----------------------------------------------------------------------- PLATFORM #include "utils/platform.h" // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include <boost/regex.hpp> #define BOOST_TEST_MODULE RDOCommon_Test #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "utils/rdocommon.h" #include "utils/rdofile.h" #include "utils/rdotime.h" #include "utils/test/utils_common_test/resource.h" // -------------------------------------------------------------------------------- const tstring s_testFileName(_T("test_file")); const tstring s_resourceStr1(_T("test_101")); const tstring s_resourceStr2(_T("test_102 22")); const tstring s_resourceStr3(_T("test_103 test_101 33 test_102 22")); const ruint64 s_createTestLocalTime = 129557633912040000; BOOST_AUTO_TEST_SUITE(RDOCommon_Test) #ifdef OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_ResourceFormat) { tstring str1 = rdo::format(IDS_STRING101); BOOST_CHECK(str1 == s_resourceStr1); tstring str2 = rdo::format(IDS_STRING102, 22); BOOST_CHECK(str2 == s_resourceStr2); tstring str3 = rdo::format(IDS_STRING103, str1.c_str(), 33, str2.c_str()); BOOST_CHECK(str3 == s_resourceStr3); } #endif // OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_FileCreate) { BOOST_CHECK(rdo::File::create(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileExist) { BOOST_CHECK(rdo::File::exist(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileReadOnly) { BOOST_CHECK(!rdo::File::read_only(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileRemove) { BOOST_CHECK(rdo::File::unlink(s_testFileName)); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInLinux) { tstring file(_T("/rdo/ /files/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T("/rdo/ /files/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr2")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInLinux) { tstring file(_T("/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T("/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } #ifdef OST_WINDOWS BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows) { tstring file(_T(":/rdo/ /files/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":/rdo/ /files/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows) { tstring file(_T(":/.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":/")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitPathInWindows_BackSlash) { tstring file(_T(":\\rdo\\ \\files\\.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":\\rdo\\ \\files\\")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } BOOST_AUTO_TEST_CASE(RDOCommon_FileSplitByRootPathInWindows_BackSlash) { tstring file(_T(":\\.smr")); tstring dir; tstring name; tstring ext; BOOST_CHECK(rdo::File::splitpath(file, dir, name, ext)); BOOST_CHECK(dir == _T(":\\")); BOOST_CHECK(name == _T("")); BOOST_CHECK(ext == _T(".smr")); } #endif // #endif BOOST_AUTO_TEST_CASE(RDOCommon_GetTempFile) { std::set<tstring> name_set; for(int i = 0; i < 15; ++i) { tstring file_name = rdo::File::getTempFileName(); BOOST_CHECK(name_set.find(file_name) == name_set.end()); name_set.insert(file_name); } } BOOST_AUTO_TEST_CASE(RDOCommon_Time) { rdo::Time timeValue = rdo::Time::local(); BOOST_CHECK(timeValue > s_createTestLocalTime); std::cout << _T("Today: ") << timeValue.asString() << _T(" is not it?"); } BOOST_AUTO_TEST_SUITE_END() // RDOCommon_Test <|endoftext|>
<commit_before>/* * Copyright (c) 2006, Mathieu Champlon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met : * * . Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * . Neither the name of the copyright holders nor the names of the * 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 THE COPYRIGHT * OWNERS 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 "xeumeuleu_test_pch.h" #include "xeumeuleu/xml.h" using namespace mockpp; // ----------------------------------------------------------------------------- // Name: created_output_sub_stream_starts_from_current_stream_level // Created: MCO 2006-03-18 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( created_output_sub_stream_starts_from_current_stream_level ) { xml::xostringstream xos; xos << xml::start( "element" ); xml::xosubstream xoss( xos ); xoss << xml::start( "sub-node" ) << xml::end(); xos << xml::end(); const std::string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<element>\n" " <sub-node/>\n" "</element>\n"; BOOST_CHECK_EQUAL( xml, xos.str() ); } // ----------------------------------------------------------------------------- // Name: streaming_end_to_an_output_sub_stream_at_root_level_throws_an_exception // Created: MCO 2006-03-18 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_end_to_an_output_sub_stream_at_root_level_throws_an_exception ) { xml::xostringstream xos; xos << xml::start( "element" ); xml::xosubstream xoss( xos ); BOOST_CHECK_THROW( xoss << xml::end(), xml::exception ); } // ----------------------------------------------------------------------------- // Name: creating_root_element_after_it_has_been_created_in_sub_stream_throws_an_exception // Created: MCO 2006-03-20 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_root_element_after_it_has_been_created_in_sub_stream_throws_an_exception ) { xml::xostringstream xos; xml::xosubstream xoss( xos ); xoss << xml::start( "element" ); BOOST_CHECK_THROW( xos << xml::start( "element" ), xml::exception ); } // ----------------------------------------------------------------------------- // Name: creating_a_sub_stream_does_not_modify_original_output_stream // Created: MCO 2006-03-18 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_a_sub_stream_does_not_modify_original_output_stream ) { xml::xostringstream xos; xos << xml::start( "element" ); xml::xosubstream xoss( xos ); xoss << xml::start( "sub-node" ); BOOST_CHECK_NO_THROW( xos << xml::end() ); const std::string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<element>\n" " <sub-node/>\n" "</element>\n"; BOOST_CHECK_EQUAL( xml, xos.str() ); } // ----------------------------------------------------------------------------- // Name: creating_root_element_in_sub_stream_completes_the_stream_upon_end // Created: MCO 2006-03-20 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_root_element_in_sub_stream_completes_the_stream_upon_end ) { xml::xostringstream xos; xml::xosubstream xoss( xos ); xoss << xml::start( "element" ) << xml::end(); const std::string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<element/>\n"; BOOST_CHECK_EQUAL( xml, xos.str() ); } // ----------------------------------------------------------------------------- // Name: creating_root_element_in_sub_stream_without_completes_the_stream_upon_sub_stream_destruction // Created: MCO 2008-05-07 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_root_element_in_sub_stream_completes_the_stream2 ) { xml::xostringstream xos; { xml::xosubstream xoss( xos ); xoss << xml::start( "element" ); } const std::string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<element/>\n"; BOOST_CHECK_EQUAL( xml, xos.str() ); } // ----------------------------------------------------------------------------- // Name: creating_sub_stream_in_sub_stream_is_valid // Created: MCO 2006-03-20 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_sub_stream_in_sub_stream_is_valid ) { xml::xostringstream xos; xml::xosubstream xoss( xos ); xml::xosubstream xosss( xoss ); } <commit_msg>Cleanup<commit_after>/* * Copyright (c) 2006, Mathieu Champlon * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met : * * . Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * . Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * . Neither the name of the copyright holders nor the names of the * 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 THE COPYRIGHT * OWNERS 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 "xeumeuleu_test_pch.h" #include "xeumeuleu/xml.h" using namespace mockpp; // ----------------------------------------------------------------------------- // Name: created_output_sub_stream_starts_from_current_stream_level // Created: MCO 2006-03-18 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( created_output_sub_stream_starts_from_current_stream_level ) { xml::xostringstream xos; xos << xml::start( "element" ); xml::xosubstream xoss( xos ); xoss << xml::start( "sub-node" ) << xml::end(); xos << xml::end(); const std::string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<element>\n" " <sub-node/>\n" "</element>\n"; BOOST_CHECK_EQUAL( xml, xos.str() ); } // ----------------------------------------------------------------------------- // Name: streaming_end_to_an_output_sub_stream_at_root_level_throws_an_exception // Created: MCO 2006-03-18 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( streaming_end_to_an_output_sub_stream_at_root_level_throws_an_exception ) { xml::xostringstream xos; xos << xml::start( "element" ); xml::xosubstream xoss( xos ); BOOST_CHECK_THROW( xoss << xml::end(), xml::exception ); } // ----------------------------------------------------------------------------- // Name: creating_root_element_after_it_has_been_created_in_sub_stream_throws_an_exception // Created: MCO 2006-03-20 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_root_element_after_it_has_been_created_in_sub_stream_throws_an_exception ) { xml::xostringstream xos; xml::xosubstream xoss( xos ); xoss << xml::start( "element" ); BOOST_CHECK_THROW( xos << xml::start( "element" ), xml::exception ); } // ----------------------------------------------------------------------------- // Name: creating_a_sub_stream_does_not_modify_original_output_stream // Created: MCO 2006-03-18 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_a_sub_stream_does_not_modify_original_output_stream ) { xml::xostringstream xos; xos << xml::start( "element" ); xml::xosubstream xoss( xos ); xoss << xml::start( "sub-node" ); BOOST_CHECK_NO_THROW( xos << xml::end() ); const std::string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<element>\n" " <sub-node/>\n" "</element>\n"; BOOST_CHECK_EQUAL( xml, xos.str() ); } // ----------------------------------------------------------------------------- // Name: creating_root_element_in_sub_stream_completes_the_stream_upon_end // Created: MCO 2006-03-20 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_root_element_in_sub_stream_completes_the_stream_upon_end ) { xml::xostringstream xos; xml::xosubstream xoss( xos ); xoss << xml::start( "element" ) << xml::end(); const std::string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<element/>\n"; BOOST_CHECK_EQUAL( xml, xos.str() ); } // ----------------------------------------------------------------------------- // Name: creating_root_element_in_sub_stream_without_completes_the_stream_upon_sub_stream_destruction // Created: MCO 2008-05-07 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_root_element_in_sub_stream_without_completes_the_stream_upon_sub_stream_destruction ) { xml::xostringstream xos; { xml::xosubstream xoss( xos ); xoss << xml::start( "element" ); } const std::string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>\n" "<element/>\n"; BOOST_CHECK_EQUAL( xml, xos.str() ); } // ----------------------------------------------------------------------------- // Name: creating_sub_stream_in_sub_stream_is_valid // Created: MCO 2006-03-20 // ----------------------------------------------------------------------------- BOOST_AUTO_TEST_CASE( creating_sub_stream_in_sub_stream_is_valid ) { xml::xostringstream xos; xml::xosubstream xoss( xos ); xml::xosubstream xosss( xoss ); } <|endoftext|>
<commit_before>#include <string> #include <vector> #include <iostream> #include <stdlib.h> #include <cstdio> #include <sys/wait.h> #include <sys/stat.h> using namespace std; class command{ protected: vector<string> commandlist; bool commandPass; string commandType; bool allCount; string nextConnector; public: command(){} command(vector<string> c){ commandlist = c; commandType = ";"; allCount = true; nextConnector = ";" } command(vector<string> c, string t){ commandlist = c; commandType = t; allCount = true; nextConnector = ";" } bool getPass(){ return commandPass; } string getType(){ return commandType; } void runCommand(vector<string> com){ char* argv[1024]; for(unsigned int i = 0; i < com.size(); i++){ argv[i] = (char*)com.at(i).c_str(); } argv[com.size()] = NULL; pid_t pid; int status; pid = fork(); if (pid == 0){ prevCommandPass = true; execvp(argv[0], argv); perror("execvp failed: "); exit(-1); } else{ if (waitpid(pid, &status, 0) == -1){ perror("Wait: "); } if (WIFEXITED(status) && WEXITSTATUS(status) != 0){ prevCommandPass = false; } } } void runAllCommands(){ vector<string> commandsublist; unsigned int i = 0; unsigned int j = 0; while (i < commandlist.size()){ j = 0; if (checkCommandRun()){ while (!checkBreaker(i)){ //Exit check if (commandlist.at(i) == "exit"){ cout << "Forced Exit." << endl; forceExit = true; _Exit(0); } // Comment check if (commandlist.at(i) == "#" || checkComment(commandlist.at(i))){ runCommand(commandsublist); return; } if (commandlist.at(i) == "["){ i++; commandsublist.push_back(commandlist.at(i); if (commandlist.at(i) == "-e" || commandlist.at(i) == "-f" || commandlist.at(i) == "d"){ i++; commandsublist.push_back(commandlist.at(i)); } else{ i++; } if (commandlist.at(i) == "]"){ i++; checkTest(commandsublist); commandsublist.clear(); } else{ cout << "Error: Missing close bracket." << endl; _exit(1); } break; } if (commandlist.at(i) == "test"){ i++; commandsublist.push_back(commandlist.at(i)); if (commandlist.at(i) == "-e" || commandlist.at(i) == "-f" || commandlist.at(i) == "d"){ i++; commandsublist.push_back(commandlist.at(i)); } else{ i++; } checkTest(commandsublist); commandsublist.clear(); break; } //Adds command to the list commandsublist.push_back(commandlist.at(i)); i++; j++; if (i == commandlist.size()){ runCommand(commandsublist); return; } } if (commandsublist.size() > 0){ runCommand(commandsublist); commandsublist.clear(); } if (checkBreaker(i)){ if (nextConnector == "||"){ if (allCount == true){ prevCommandPass = true; } else{ if (prevCommandPass == false){ allCount = false; } else{ allCount = true; } } } else if (nextConnector == "&&"){ if (allCount == true){ if (prevCommandPass == false){ allCount = false; } } else{ allCount = false; prevCommandPass = false; } } else if (nextConnector == ";"){ if (prevCommandPass == true){ allCount = true; } else{ allCount = false; } } if (commandlist.at(i) == "|"){ nextConnector = "||"; } else if (commandlist.at(i) == "&"){ nextConnector = "&&"; } else if (commandlist.at(i) == ";"){ nextConnector = ";"; } i++; } i++; } else{ i++; } } } // Checks if there is a '#' at the front of the string bool checkComment(string str){ if (str.at(0) == '#'){ return true; } return false; } // Checks if the string is a breaker bool checkBreaker(int i){ if ( (unsigned)i < commandlist.size() + 1){ if (commandlist.at(i) == "|" && commandlist.at(i + 1) == "|"){ return true; } else if (commandlist.at(i) == "&" && commandlist.at(i + 1) == "&"){ return true; } else if (commandlist.at(i) == ";"){ return true; } else{ return false; } } else if( (unsigned)i == commandlist.size() + 1){ if(commandlist.at(i) == ";"){ return true; } return false; } else{ return false; } } // Checks if the next command should be run bool checkCommandRun(){ if (nextConnector == "||"){ if(allCount == true){ return false; } else{ return true; } } else if (nextConnector == "&&"){ if(allCount == true){ return true; } return false; } else if (nextConnector == ";"){ return true; } return false; } bool checkTest(vector<string> temp){ if (temp.at(0) == "-e"){ return fileExists(temp.at(1)); } else if (temp.at(0) == "-f"){ return regFileExists(temp.at(1)); } else if (temp.at(0) == "-d"){ return dirExists(temp.at(1)); } else{ return fileExists(temp.at(1)); } } bool fileExists(string& path){ struct stat buffer; return (stat(file, &buffer) == 0); } bool dirExists(string& path){ struct stat buffer; if (stat(path, &buffer) == 0 && S_ISDIR(buffer.st_mode)){ return true; } return false; } bool regFileExists(string& path){ struct stat buffer; if (stat(path, &buffer) == 0 && S_ISREG(buffer.st_mode)){ return true; } return false; } void execute(bool prevCommand){ if (prevCommand){ if (commandType == "&&"){ runAllCommands(); if (allCount){ commandPass = true; } else{ commandPass = false; } } else if (commandType == "||"){ commandPass = true; } else if (commandType == ";"){ runAllCommands(); commandPass = true; } else{ if (commandType == "&&"){ commandPass = false; } else if (commandType == "||"){ runAllCommands(); if (allCount){ commandPass = true; } else{ commandPass = false; } } else if (commandType == ";"){ runAllCommands(); commandPass = true; } } } }; <commit_msg>Test error fixes<commit_after>#include <string> #include <vector> #include <iostream> #include <stdlib.h> #include <cstdio> #include <sys/wait.h> #include <sys/stat.h> using namespace std; class command{ protected: vector<string> commandlist; bool commandPass; string commandType; bool allCount; string nextConnector; public: command(){} command(vector<string> c){ commandlist = c; commandType = ";"; allCount = true; nextConnector = ";" } command(vector<string> c, string t){ commandlist = c; commandType = t; allCount = true; nextConnector = ";" } bool getPass(){ return commandPass; } string getType(){ return commandType; } void runCommand(vector<string> com){ char* argv[1024]; for(unsigned int i = 0; i < com.size(); i++){ argv[i] = (char*)com.at(i).c_str(); } argv[com.size()] = NULL; pid_t pid; int status; pid = fork(); if (pid == 0){ prevCommandPass = true; execvp(argv[0], argv); perror("execvp failed: "); exit(-1); } else{ if (waitpid(pid, &status, 0) == -1){ perror("Wait: "); } if (WIFEXITED(status) && WEXITSTATUS(status) != 0){ prevCommandPass = false; } } } void runAllCommands(){ vector<string> commandsublist; unsigned int i = 0; unsigned int j = 0; while (i < commandlist.size()){ j = 0; if (checkCommandRun()){ while (!checkBreaker(i)){ //Exit check if (commandlist.at(i) == "exit"){ cout << "Forced Exit." << endl; forceExit = true; _Exit(0); } // Comment check if (commandlist.at(i) == "#" || checkComment(commandlist.at(i))){ runCommand(commandsublist); return; } if (commandlist.at(i) == "["){ i++; commandsublist.push_back(commandlist.at(i); if (commandlist.at(i) == "-e" || commandlist.at(i) == "-f" || commandlist.at(i) == "d"){ i++; commandsublist.push_back(commandlist.at(i)); } else{ i++; } if (commandlist.at(i) == "]"){ i++; if (checkTest(commandsublist)){ cout << "(True)" << endl; } else{ cout << "(False)" << endl; } commandsublist.clear(); } else{ cout << "Error: Missing close bracket." << endl; _exit(1); } break; } if (commandlist.at(i) == "test"){ i++; commandsublist.push_back(commandlist.at(i)); if (commandlist.at(i) == "-e" || commandlist.at(i) == "-f" || commandlist.at(i) == "d"){ i++; commandsublist.push_back(commandlist.at(i)); } else{ i++; } if (checkTest(commandsublist)){ cout << "(True)" << endl; } else{ cout << "(False)" << endl; } commandsublist.clear(); break; } //Adds command to the list commandsublist.push_back(commandlist.at(i)); i++; j++; if (i == commandlist.size()){ runCommand(commandsublist); return; } } if (commandsublist.size() > 0){ runCommand(commandsublist); commandsublist.clear(); } if (checkBreaker(i)){ if (nextConnector == "||"){ if (allCount == true){ prevCommandPass = true; } else{ if (prevCommandPass == false){ allCount = false; } else{ allCount = true; } } } else if (nextConnector == "&&"){ if (allCount == true){ if (prevCommandPass == false){ allCount = false; } } else{ allCount = false; prevCommandPass = false; } } else if (nextConnector == ";"){ if (prevCommandPass == true){ allCount = true; } else{ allCount = false; } } if (commandlist.at(i) == "|"){ nextConnector = "||"; } else if (commandlist.at(i) == "&"){ nextConnector = "&&"; } else if (commandlist.at(i) == ";"){ nextConnector = ";"; } i++; } i++; } else{ i++; } } } // Checks if there is a '#' at the front of the string bool checkComment(string str){ if (str.at(0) == '#'){ return true; } return false; } // Checks if the string is a breaker bool checkBreaker(int i){ if ( (unsigned)i < commandlist.size() + 1){ if (commandlist.at(i) == "|" && commandlist.at(i + 1) == "|"){ return true; } else if (commandlist.at(i) == "&" && commandlist.at(i + 1) == "&"){ return true; } else if (commandlist.at(i) == ";"){ return true; } else{ return false; } } else if( (unsigned)i == commandlist.size() + 1){ if(commandlist.at(i) == ";"){ return true; } return false; } else{ return false; } } // Checks if the next command should be run bool checkCommandRun(){ if (nextConnector == "||"){ if(allCount == true){ return false; } else{ return true; } } else if (nextConnector == "&&"){ if(allCount == true){ return true; } return false; } else if (nextConnector == ";"){ return true; } return false; } bool checkTest(vector<string> temp){ if (temp.at(0) == "-e"){ return fileExists(temp.at(1)); } else if (temp.at(0) == "-f"){ return regFileExists(temp.at(1)); } else if (temp.at(0) == "-d"){ return dirExists(temp.at(1)); } else{ return fileExists(temp.at(1)); } } bool fileExists(string& path){ struct stat buffer; return (stat(file, &buffer) == 0); } bool dirExists(string& path){ struct stat buffer; if (stat(path, &buffer) == 0 && S_ISDIR(buffer.st_mode)){ return true; } return false; } bool regFileExists(string& path){ struct stat buffer; if (stat(path, &buffer) == 0 && S_ISREG(buffer.st_mode)){ return true; } return false; } void execute(bool prevCommand){ if (prevCommand){ if (commandType == "&&"){ runAllCommands(); if (allCount){ commandPass = true; } else{ commandPass = false; } } else if (commandType == "||"){ commandPass = true; } else if (commandType == ";"){ runAllCommands(); commandPass = true; } else{ if (commandType == "&&"){ commandPass = false; } else if (commandType == "||"){ runAllCommands(); if (allCount){ commandPass = true; } else{ commandPass = false; } } else if (commandType == ";"){ runAllCommands(); commandPass = true; } } } }; <|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 "media/cast/transport/transport/udp_transport.h" #include <algorithm> #include <string> #include <vector> #include "base/bind.h" #include "base/callback.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "media/cast/transport/cast_transport_config.h" #include "net/base/net_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace media { namespace cast { namespace transport { class MockPacketReceiver { public: MockPacketReceiver(const base::Closure& callback) : packet_callback_(callback) {} void ReceivedPacket(scoped_ptr<Packet> packet) { packet_ = std::string(packet->size(), '\0'); std::copy(packet->begin(), packet->end(), packet_.begin()); packet_callback_.Run(); } std::string packet() const { return packet_; } transport::PacketReceiverCallback packet_receiver() { return base::Bind(&MockPacketReceiver::ReceivedPacket, base::Unretained(this)); } private: std::string packet_; base::Closure packet_callback_; DISALLOW_COPY_AND_ASSIGN(MockPacketReceiver); }; void SendPacket(UdpTransport* transport, Packet packet) { transport->SendPacket(packet); } static void UpdateCastTransportStatus(transport::CastTransportStatus status) { NOTREACHED(); } TEST(UdpTransport, SendAndReceive) { base::MessageLoopForIO message_loop; net::IPAddressNumber local_addr_number; net::IPAddressNumber empty_addr_number; net::ParseIPLiteralToNumber("127.0.0.1", &local_addr_number); net::ParseIPLiteralToNumber("0.0.0.0", &empty_addr_number); UdpTransport send_transport(NULL, message_loop.message_loop_proxy(), net::IPEndPoint(local_addr_number, 2344), net::IPEndPoint(local_addr_number, 2345), base::Bind(&UpdateCastTransportStatus)); UdpTransport recv_transport(NULL, message_loop.message_loop_proxy(), net::IPEndPoint(local_addr_number, 2345), net::IPEndPoint(empty_addr_number, 0), base::Bind(&UpdateCastTransportStatus)); Packet packet; packet.push_back('t'); packet.push_back('e'); packet.push_back('s'); packet.push_back('t'); base::RunLoop run_loop; MockPacketReceiver receiver1(run_loop.QuitClosure()); MockPacketReceiver receiver2( base::Bind(&SendPacket, &recv_transport, packet)); send_transport.StartReceiving(receiver1.packet_receiver()); recv_transport.StartReceiving(receiver2.packet_receiver()); send_transport.SendPacket(packet); run_loop.Run(); EXPECT_TRUE( std::equal(packet.begin(), packet.end(), receiver1.packet().begin())); EXPECT_TRUE( std::equal(packet.begin(), packet.end(), receiver2.packet().begin())); } static void SaveStatusAndQuit(base::Closure quit_closure, transport::CastTransportStatus* out_status, transport::CastTransportStatus status) { *out_status = status; quit_closure.Run(); } TEST(UdpTransport, TransportError) { base::MessageLoopForIO message_loop; net::IPAddressNumber empty_addr_number; net::ParseIPLiteralToNumber("0.0.0.0", &empty_addr_number); net::IPAddressNumber invalid_addr_number; net::ParseIPLiteralToNumber("0.42.42.42", &invalid_addr_number); base::RunLoop run_loop; transport::CastTransportStatus status; UdpTransport send_transport( NULL, message_loop.message_loop_proxy(), net::IPEndPoint(empty_addr_number, 0), net::IPEndPoint(invalid_addr_number, 2345), base::Bind(&SaveStatusAndQuit, run_loop.QuitClosure(), &status)); MockPacketReceiver receiver(run_loop.QuitClosure()); send_transport.StartReceiving(receiver.packet_receiver()); run_loop.Run(); EXPECT_EQ(TRANSPORT_SOCKET_ERROR, status); } } // namespace transport } // namespace cast } // namespace media <commit_msg>Revert 254047 "Cast: Add a unit test for connect to an invalid r..."<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 "media/cast/transport/transport/udp_transport.h" #include <algorithm> #include <string> #include <vector> #include "base/bind.h" #include "base/callback.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "media/cast/transport/cast_transport_config.h" #include "net/base/net_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace media { namespace cast { namespace transport { class MockPacketReceiver { public: MockPacketReceiver(const base::Closure& callback) : packet_callback_(callback) {} void ReceivedPacket(scoped_ptr<Packet> packet) { packet_ = std::string(packet->size(), '\0'); std::copy(packet->begin(), packet->end(), packet_.begin()); packet_callback_.Run(); } std::string packet() const { return packet_; } transport::PacketReceiverCallback packet_receiver() { return base::Bind(&MockPacketReceiver::ReceivedPacket, base::Unretained(this)); } private: std::string packet_; base::Closure packet_callback_; DISALLOW_COPY_AND_ASSIGN(MockPacketReceiver); }; void SendPacket(UdpTransport* transport, Packet packet) { transport->SendPacket(packet); } static void UpdateCastTransportStatus(transport::CastTransportStatus status) { NOTREACHED(); } TEST(UdpTransport, SendAndReceive) { base::MessageLoopForIO message_loop; net::IPAddressNumber local_addr_number; net::IPAddressNumber empty_addr_number; net::ParseIPLiteralToNumber("127.0.0.1", &local_addr_number); net::ParseIPLiteralToNumber("0.0.0.0", &empty_addr_number); UdpTransport send_transport(NULL, message_loop.message_loop_proxy(), net::IPEndPoint(local_addr_number, 2344), net::IPEndPoint(local_addr_number, 2345), base::Bind(&UpdateCastTransportStatus)); UdpTransport recv_transport(NULL, message_loop.message_loop_proxy(), net::IPEndPoint(local_addr_number, 2345), net::IPEndPoint(empty_addr_number, 0), base::Bind(&UpdateCastTransportStatus)); Packet packet; packet.push_back('t'); packet.push_back('e'); packet.push_back('s'); packet.push_back('t'); base::RunLoop run_loop; MockPacketReceiver receiver1(run_loop.QuitClosure()); MockPacketReceiver receiver2( base::Bind(&SendPacket, &recv_transport, packet)); send_transport.StartReceiving(receiver1.packet_receiver()); recv_transport.StartReceiving(receiver2.packet_receiver()); send_transport.SendPacket(packet); run_loop.Run(); EXPECT_TRUE( std::equal(packet.begin(), packet.end(), receiver1.packet().begin())); EXPECT_TRUE( std::equal(packet.begin(), packet.end(), receiver2.packet().begin())); } } // namespace transport } // namespace cast } // namespace media <|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 "content/renderer/media/capture_video_decoder.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "content/renderer/media/video_capture_impl_manager.h" #include "media/base/filter_host.h" #include "media/base/limits.h" #include "media/base/video_util.h" using media::CopyYPlane; using media::CopyUPlane; using media::CopyVPlane; CaptureVideoDecoder::CaptureVideoDecoder( base::MessageLoopProxy* message_loop_proxy, media::VideoCaptureSessionId video_stream_id, VideoCaptureImplManager* vc_manager, const media::VideoCapture::VideoCaptureCapability& capability) : message_loop_proxy_(message_loop_proxy), vc_manager_(vc_manager), capability_(capability), natural_size_(capability.width, capability.height), state_(kUnInitialized), got_first_frame_(false), video_stream_id_(video_stream_id), capture_engine_(NULL) { DCHECK(vc_manager); } CaptureVideoDecoder::~CaptureVideoDecoder() {} void CaptureVideoDecoder::Initialize( media::DemuxerStream* demuxer_stream, const media::PipelineStatusCB& status_cb, const media::StatisticsCB& statistics_cb) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::InitializeOnDecoderThread, this, make_scoped_refptr(demuxer_stream), status_cb, statistics_cb)); } void CaptureVideoDecoder::Read(const ReadCB& read_cb) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::ReadOnDecoderThread, this, read_cb)); } const gfx::Size& CaptureVideoDecoder::natural_size() { return natural_size_; } void CaptureVideoDecoder::Play(const base::Closure& callback) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::PlayOnDecoderThread, this, callback)); } void CaptureVideoDecoder::Pause(const base::Closure& callback) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::PauseOnDecoderThread, this, callback)); } void CaptureVideoDecoder::Flush(const base::Closure& callback) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::FlushOnDecoderThread, this, callback)); } void CaptureVideoDecoder::Stop(const base::Closure& callback) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::StopOnDecoderThread, this, callback)); } void CaptureVideoDecoder::Seek(base::TimeDelta time, const media::PipelineStatusCB& cb) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::SeekOnDecoderThread, this, time, cb)); } void CaptureVideoDecoder::OnStarted(media::VideoCapture* capture) { NOTIMPLEMENTED(); } void CaptureVideoDecoder::OnStopped(media::VideoCapture* capture) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::OnStoppedOnDecoderThread, this, capture)); } void CaptureVideoDecoder::OnPaused(media::VideoCapture* capture) { NOTIMPLEMENTED(); } void CaptureVideoDecoder::OnError(media::VideoCapture* capture, int error_code) { NOTIMPLEMENTED(); } void CaptureVideoDecoder::OnRemoved(media::VideoCapture* capture) { NOTIMPLEMENTED(); } void CaptureVideoDecoder::OnBufferReady( media::VideoCapture* capture, scoped_refptr<media::VideoCapture::VideoFrameBuffer> buf) { DCHECK(buf); message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::OnBufferReadyOnDecoderThread, this, capture, buf)); } void CaptureVideoDecoder::OnDeviceInfoReceived( media::VideoCapture* capture, const media::VideoCaptureParams& device_info) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::OnDeviceInfoReceivedOnDecoderThread, this, capture, device_info)); } void CaptureVideoDecoder::InitializeOnDecoderThread( media::DemuxerStream* demuxer_stream, const media::PipelineStatusCB& status_cb, const media::StatisticsCB& statistics_cb) { DVLOG(1) << "InitializeOnDecoderThread"; DCHECK(message_loop_proxy_->BelongsToCurrentThread()); capture_engine_ = vc_manager_->AddDevice(video_stream_id_, this); statistics_cb_ = statistics_cb; status_cb.Run(media::PIPELINE_OK); state_ = kNormal; capture_engine_->StartCapture(this, capability_); } void CaptureVideoDecoder::ReadOnDecoderThread(const ReadCB& read_cb) { DCHECK(message_loop_proxy_->BelongsToCurrentThread()); CHECK(read_cb_.is_null()); read_cb_ = read_cb; } void CaptureVideoDecoder::PlayOnDecoderThread(const base::Closure& callback) { DVLOG(1) << "PlayOnDecoderThread"; DCHECK(message_loop_proxy_->BelongsToCurrentThread()); callback.Run(); } void CaptureVideoDecoder::PauseOnDecoderThread(const base::Closure& callback) { DVLOG(1) << "PauseOnDecoderThread"; DCHECK(message_loop_proxy_->BelongsToCurrentThread()); state_ = kPaused; callback.Run(); } void CaptureVideoDecoder::FlushOnDecoderThread(const base::Closure& callback) { DVLOG(1) << "FlushOnDecoderThread"; DCHECK(message_loop_proxy_->BelongsToCurrentThread()); if (!read_cb_.is_null()) { scoped_refptr<media::VideoFrame> video_frame = media::VideoFrame::CreateBlackFrame(natural_size_.width(), natural_size_.height()); DeliverFrame(video_frame); } media::VideoDecoder::Flush(callback); } void CaptureVideoDecoder::StopOnDecoderThread(const base::Closure& callback) { DVLOG(1) << "StopOnDecoderThread"; DCHECK(message_loop_proxy_->BelongsToCurrentThread()); pending_stop_cb_ = callback; state_ = kStopped; capture_engine_->StopCapture(this); } void CaptureVideoDecoder::SeekOnDecoderThread( base::TimeDelta time, const media::PipelineStatusCB& cb) { DVLOG(1) << "SeekOnDecoderThread"; DCHECK(message_loop_proxy_->BelongsToCurrentThread()); cb.Run(media::PIPELINE_OK); state_ = kNormal; } void CaptureVideoDecoder::OnStoppedOnDecoderThread( media::VideoCapture* capture) { DVLOG(1) << "OnStoppedOnDecoderThread"; DCHECK(message_loop_proxy_->BelongsToCurrentThread()); if (!pending_stop_cb_.is_null()) base::ResetAndReturn(&pending_stop_cb_).Run(); vc_manager_->RemoveDevice(video_stream_id_, this); } void CaptureVideoDecoder::OnDeviceInfoReceivedOnDecoderThread( media::VideoCapture* capture, const media::VideoCaptureParams& device_info) { DCHECK(message_loop_proxy_->BelongsToCurrentThread()); if (device_info.width != natural_size_.width() || device_info.height != natural_size_.height()) { natural_size_.SetSize(device_info.width, device_info.height); host()->SetNaturalVideoSize(natural_size_); } } void CaptureVideoDecoder::OnBufferReadyOnDecoderThread( media::VideoCapture* capture, scoped_refptr<media::VideoCapture::VideoFrameBuffer> buf) { DCHECK(message_loop_proxy_->BelongsToCurrentThread()); if (read_cb_.is_null() || kNormal != state_) { // TODO(wjia): revisit TS adjustment when crbug.com/111672 is resolved. if (got_first_frame_) { start_time_ += buf->timestamp - last_frame_timestamp_; } last_frame_timestamp_ = buf->timestamp; capture->FeedBuffer(buf); return; } // TODO(wjia): should we always expect device to send device info before // any buffer, and buffers should have dimension stated in device info? // Or should we be flexible as in following code? if (buf->width != natural_size_.width() || buf->height != natural_size_.height()) { natural_size_.SetSize(buf->width, buf->height); host()->SetNaturalVideoSize(natural_size_); } // Need to rebase timestamp with zero as starting point. if (!got_first_frame_) { start_time_ = buf->timestamp; got_first_frame_ = true; } // Always allocate a new frame. // // TODO(scherkus): migrate this to proper buffer recycling. scoped_refptr<media::VideoFrame> video_frame = media::VideoFrame::CreateFrame(media::VideoFrame::YV12, natural_size_.width(), natural_size_.height(), buf->timestamp - start_time_, base::TimeDelta::FromMilliseconds(0)); last_frame_timestamp_ = buf->timestamp; uint8* buffer = buf->memory_pointer; // Assume YV12 format. Note that camera gives YUV and media pipeline video // renderer asks for YVU. The following code did the conversion. DCHECK_EQ(capability_.raw_type, media::VideoFrame::I420); int y_width = buf->width; int y_height = buf->height; int uv_width = buf->width / 2; int uv_height = buf->height / 2; // YV12 format. CopyYPlane(buffer, y_width, y_height, video_frame); buffer += y_width * y_height; CopyUPlane(buffer, uv_width, uv_height, video_frame); buffer += uv_width * uv_height; CopyVPlane(buffer, uv_width, uv_height, video_frame); DeliverFrame(video_frame); capture->FeedBuffer(buf); } void CaptureVideoDecoder::DeliverFrame( const scoped_refptr<media::VideoFrame>& video_frame) { // Reset the callback before running to protect against reentrancy. ReadCB read_cb = read_cb_; read_cb_.Reset(); read_cb.Run(video_frame); } <commit_msg>video decoder doesn't update host with natural size. it should be video renderer.<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 "content/renderer/media/capture_video_decoder.h" #include "base/bind.h" #include "base/callback_helpers.h" #include "content/renderer/media/video_capture_impl_manager.h" #include "media/base/filter_host.h" #include "media/base/limits.h" #include "media/base/video_util.h" using media::CopyYPlane; using media::CopyUPlane; using media::CopyVPlane; CaptureVideoDecoder::CaptureVideoDecoder( base::MessageLoopProxy* message_loop_proxy, media::VideoCaptureSessionId video_stream_id, VideoCaptureImplManager* vc_manager, const media::VideoCapture::VideoCaptureCapability& capability) : message_loop_proxy_(message_loop_proxy), vc_manager_(vc_manager), capability_(capability), natural_size_(capability.width, capability.height), state_(kUnInitialized), got_first_frame_(false), video_stream_id_(video_stream_id), capture_engine_(NULL) { DCHECK(vc_manager); } CaptureVideoDecoder::~CaptureVideoDecoder() {} void CaptureVideoDecoder::Initialize( media::DemuxerStream* demuxer_stream, const media::PipelineStatusCB& status_cb, const media::StatisticsCB& statistics_cb) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::InitializeOnDecoderThread, this, make_scoped_refptr(demuxer_stream), status_cb, statistics_cb)); } void CaptureVideoDecoder::Read(const ReadCB& read_cb) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::ReadOnDecoderThread, this, read_cb)); } const gfx::Size& CaptureVideoDecoder::natural_size() { return natural_size_; } void CaptureVideoDecoder::Play(const base::Closure& callback) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::PlayOnDecoderThread, this, callback)); } void CaptureVideoDecoder::Pause(const base::Closure& callback) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::PauseOnDecoderThread, this, callback)); } void CaptureVideoDecoder::Flush(const base::Closure& callback) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::FlushOnDecoderThread, this, callback)); } void CaptureVideoDecoder::Stop(const base::Closure& callback) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::StopOnDecoderThread, this, callback)); } void CaptureVideoDecoder::Seek(base::TimeDelta time, const media::PipelineStatusCB& cb) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::SeekOnDecoderThread, this, time, cb)); } void CaptureVideoDecoder::OnStarted(media::VideoCapture* capture) { NOTIMPLEMENTED(); } void CaptureVideoDecoder::OnStopped(media::VideoCapture* capture) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::OnStoppedOnDecoderThread, this, capture)); } void CaptureVideoDecoder::OnPaused(media::VideoCapture* capture) { NOTIMPLEMENTED(); } void CaptureVideoDecoder::OnError(media::VideoCapture* capture, int error_code) { NOTIMPLEMENTED(); } void CaptureVideoDecoder::OnRemoved(media::VideoCapture* capture) { NOTIMPLEMENTED(); } void CaptureVideoDecoder::OnBufferReady( media::VideoCapture* capture, scoped_refptr<media::VideoCapture::VideoFrameBuffer> buf) { DCHECK(buf); message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::OnBufferReadyOnDecoderThread, this, capture, buf)); } void CaptureVideoDecoder::OnDeviceInfoReceived( media::VideoCapture* capture, const media::VideoCaptureParams& device_info) { message_loop_proxy_->PostTask( FROM_HERE, base::Bind(&CaptureVideoDecoder::OnDeviceInfoReceivedOnDecoderThread, this, capture, device_info)); } void CaptureVideoDecoder::InitializeOnDecoderThread( media::DemuxerStream* demuxer_stream, const media::PipelineStatusCB& status_cb, const media::StatisticsCB& statistics_cb) { DVLOG(1) << "InitializeOnDecoderThread"; DCHECK(message_loop_proxy_->BelongsToCurrentThread()); capture_engine_ = vc_manager_->AddDevice(video_stream_id_, this); statistics_cb_ = statistics_cb; status_cb.Run(media::PIPELINE_OK); state_ = kNormal; capture_engine_->StartCapture(this, capability_); } void CaptureVideoDecoder::ReadOnDecoderThread(const ReadCB& read_cb) { DCHECK(message_loop_proxy_->BelongsToCurrentThread()); CHECK(read_cb_.is_null()); read_cb_ = read_cb; } void CaptureVideoDecoder::PlayOnDecoderThread(const base::Closure& callback) { DVLOG(1) << "PlayOnDecoderThread"; DCHECK(message_loop_proxy_->BelongsToCurrentThread()); callback.Run(); } void CaptureVideoDecoder::PauseOnDecoderThread(const base::Closure& callback) { DVLOG(1) << "PauseOnDecoderThread"; DCHECK(message_loop_proxy_->BelongsToCurrentThread()); state_ = kPaused; callback.Run(); } void CaptureVideoDecoder::FlushOnDecoderThread(const base::Closure& callback) { DVLOG(1) << "FlushOnDecoderThread"; DCHECK(message_loop_proxy_->BelongsToCurrentThread()); if (!read_cb_.is_null()) { scoped_refptr<media::VideoFrame> video_frame = media::VideoFrame::CreateBlackFrame(natural_size_.width(), natural_size_.height()); DeliverFrame(video_frame); } media::VideoDecoder::Flush(callback); } void CaptureVideoDecoder::StopOnDecoderThread(const base::Closure& callback) { DVLOG(1) << "StopOnDecoderThread"; DCHECK(message_loop_proxy_->BelongsToCurrentThread()); pending_stop_cb_ = callback; state_ = kStopped; capture_engine_->StopCapture(this); } void CaptureVideoDecoder::SeekOnDecoderThread( base::TimeDelta time, const media::PipelineStatusCB& cb) { DVLOG(1) << "SeekOnDecoderThread"; DCHECK(message_loop_proxy_->BelongsToCurrentThread()); cb.Run(media::PIPELINE_OK); state_ = kNormal; } void CaptureVideoDecoder::OnStoppedOnDecoderThread( media::VideoCapture* capture) { DVLOG(1) << "OnStoppedOnDecoderThread"; DCHECK(message_loop_proxy_->BelongsToCurrentThread()); if (!pending_stop_cb_.is_null()) base::ResetAndReturn(&pending_stop_cb_).Run(); vc_manager_->RemoveDevice(video_stream_id_, this); } void CaptureVideoDecoder::OnDeviceInfoReceivedOnDecoderThread( media::VideoCapture* capture, const media::VideoCaptureParams& device_info) { DCHECK(message_loop_proxy_->BelongsToCurrentThread()); if (device_info.width != natural_size_.width() || device_info.height != natural_size_.height()) { natural_size_.SetSize(device_info.width, device_info.height); } } void CaptureVideoDecoder::OnBufferReadyOnDecoderThread( media::VideoCapture* capture, scoped_refptr<media::VideoCapture::VideoFrameBuffer> buf) { DCHECK(message_loop_proxy_->BelongsToCurrentThread()); if (read_cb_.is_null() || kNormal != state_) { // TODO(wjia): revisit TS adjustment when crbug.com/111672 is resolved. if (got_first_frame_) { start_time_ += buf->timestamp - last_frame_timestamp_; } last_frame_timestamp_ = buf->timestamp; capture->FeedBuffer(buf); return; } // TODO(wjia): should we always expect device to send device info before // any buffer, and buffers should have dimension stated in device info? // Or should we be flexible as in following code? if (buf->width != natural_size_.width() || buf->height != natural_size_.height()) { natural_size_.SetSize(buf->width, buf->height); } // Need to rebase timestamp with zero as starting point. if (!got_first_frame_) { start_time_ = buf->timestamp; got_first_frame_ = true; } // Always allocate a new frame. // // TODO(scherkus): migrate this to proper buffer recycling. scoped_refptr<media::VideoFrame> video_frame = media::VideoFrame::CreateFrame(media::VideoFrame::YV12, natural_size_.width(), natural_size_.height(), buf->timestamp - start_time_, base::TimeDelta::FromMilliseconds(0)); last_frame_timestamp_ = buf->timestamp; uint8* buffer = buf->memory_pointer; // Assume YV12 format. Note that camera gives YUV and media pipeline video // renderer asks for YVU. The following code did the conversion. DCHECK_EQ(capability_.raw_type, media::VideoFrame::I420); int y_width = buf->width; int y_height = buf->height; int uv_width = buf->width / 2; int uv_height = buf->height / 2; // YV12 format. CopyYPlane(buffer, y_width, y_height, video_frame); buffer += y_width * y_height; CopyUPlane(buffer, uv_width, uv_height, video_frame); buffer += uv_width * uv_height; CopyVPlane(buffer, uv_width, uv_height, video_frame); DeliverFrame(video_frame); capture->FeedBuffer(buf); } void CaptureVideoDecoder::DeliverFrame( const scoped_refptr<media::VideoFrame>& video_frame) { // Reset the callback before running to protect against reentrancy. ReadCB read_cb = read_cb_; read_cb_.Reset(); read_cb.Run(video_frame); } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreStableHeaders.h" #include "OgreException.h" #include "OgreScriptLexer.h" namespace Ogre{ ScriptLexer::ScriptLexer() { } ScriptTokenListPtr ScriptLexer::tokenize(const String &str, const String &source) { // State enums enum{ READY = 0, COMMENT, MULTICOMMENT, WORD, QUOTE, VAR, POSSIBLECOMMENT }; // Set up some constant characters of interest const wchar_t varopener = '$', quote = '\"', slash = '/', backslash = '\\', openbrace = '{', closebrace = '}', colon = ':', star = '*', cr = '\r', lf = '\n'; char c = 0, lastc = 0; String lexeme; uint32 line = 1, state = READY, lastQuote = 0; ScriptTokenListPtr tokens(OGRE_NEW_T(ScriptTokenList, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T); // Iterate over the input String::const_iterator i = str.begin(), end = str.end(); while(i != end) { lastc = c; c = *i; if(c == quote) lastQuote = line; switch(state) { case READY: if(c == slash && lastc == slash) { // Comment start, clear out the lexeme lexeme = ""; state = COMMENT; } else if(c == star && lastc == slash) { lexeme = ""; state = MULTICOMMENT; } else if(c == quote) { // Clear out the lexeme ready to be filled with quotes! lexeme = c; state = QUOTE; } else if(c == varopener) { // Set up to read in a variable lexeme = c; state = VAR; } else if(isNewline(c)) { lexeme = c; setToken(lexeme, line, source, tokens.get()); } else if(!isWhitespace(c)) { lexeme = c; if(c == slash) state = POSSIBLECOMMENT; else state = WORD; } break; case COMMENT: // This newline happens to be ignored automatically if(isNewline(c)) state = READY; break; case MULTICOMMENT: if(c == slash && lastc == star) state = READY; break; case POSSIBLECOMMENT: if(c == slash && lastc == slash) { lexeme = ""; state = COMMENT; break; } else if(c == star && lastc == slash) { lexeme = ""; state = MULTICOMMENT; break; } else { state = WORD; } case WORD: if(isNewline(c)) { setToken(lexeme, line, source, tokens.get()); lexeme = c; setToken(lexeme, line, source, tokens.get()); state = READY; } else if(isWhitespace(c)) { setToken(lexeme, line, source, tokens.get()); state = READY; } else if(c == openbrace || c == closebrace || c == colon) { setToken(lexeme, line, source, tokens.get()); lexeme = c; setToken(lexeme, line, source, tokens.get()); state = READY; } else { lexeme += c; } break; case QUOTE: if(c != backslash) { // Allow embedded quotes with escaping if(c == quote && lastc == backslash) { lexeme += c; } else if(c == quote) { lexeme += c; setToken(lexeme, line, source, tokens.get()); state = READY; } else { // Backtrack here and allow a backslash normally within the quote if(lastc == backslash) lexeme = lexeme + "\\" + c; else lexeme += c; } } break; case VAR: if(isNewline(c)) { setToken(lexeme, line, source, tokens.get()); lexeme = c; setToken(lexeme, line, source, tokens.get()); state = READY; } else if(isWhitespace(c)) { setToken(lexeme, line, source, tokens.get()); state = READY; } else if(c == openbrace || c == closebrace || c == colon) { setToken(lexeme, line, source, tokens.get()); lexeme = c; setToken(lexeme, line, source, tokens.get()); state = READY; } else { lexeme += c; } break; } // Separate check for newlines just to track line numbers if(c == cr || (c == lf && lastc != cr)) line++; i++; } // Check for valid exit states if(state == WORD || state == VAR) { if(!lexeme.empty()) setToken(lexeme, line, source, tokens.get()); } else { if(state == QUOTE) { OGRE_EXCEPT(Exception::ERR_INVALID_STATE, Ogre::String("no matching \" found for \" at line ") + Ogre::StringConverter::toString(lastQuote), "ScriptLexer::tokenize"); } } return tokens; } void ScriptLexer::setToken(const Ogre::String &lexeme, Ogre::uint32 line, const String &source, Ogre::ScriptTokenList *tokens) { const char openBracket = '{', closeBracket = '}', colon = ':', quote = '\"', var = '$'; ScriptTokenPtr token(OGRE_NEW_T(ScriptToken, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T); token->lexeme = lexeme; token->line = line; token->file = source; bool ignore = false; // Check the user token map first if(lexeme.size() == 1 && isNewline(lexeme[0])) { token->type = TID_NEWLINE; if(!tokens->empty() && tokens->back()->type == TID_NEWLINE) ignore = true; } else if(lexeme.size() == 1 && lexeme[0] == openBracket) token->type = TID_LBRACKET; else if(lexeme.size() == 1 && lexeme[0] == closeBracket) token->type = TID_RBRACKET; else if(lexeme.size() == 1 && lexeme[0] == colon) token->type = TID_COLON; else if(lexeme[0] == var) token->type = TID_VARIABLE; else { // This is either a non-zero length phrase or quoted phrase if(lexeme.size() >= 2 && lexeme[0] == quote && lexeme[lexeme.size() - 1] == quote) { token->type = TID_QUOTE; } else { token->type = TID_WORD; } } if(!ignore) tokens->push_back(token); } bool ScriptLexer::isWhitespace(Ogre::String::value_type c) const { return c == ' ' || c == '\r' || c == '\t'; } bool ScriptLexer::isNewline(Ogre::String::value_type c) const { return c == '\n' || c == '\r'; } } <commit_msg>[OGRE-474] fixed script lexer issue with single comments in the same line after valid script tokens "hiding" the tokens from the next line<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org Copyright (c) 2000-2014 Torus Knot Software Ltd 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 "OgreStableHeaders.h" #include "OgreException.h" #include "OgreScriptLexer.h" namespace Ogre{ ScriptLexer::ScriptLexer() { } ScriptTokenListPtr ScriptLexer::tokenize(const String &str, const String &source) { // State enums enum{ READY = 0, COMMENT, MULTICOMMENT, WORD, QUOTE, VAR, POSSIBLECOMMENT }; // Set up some constant characters of interest const wchar_t varopener = '$', quote = '\"', slash = '/', backslash = '\\', openbrace = '{', closebrace = '}', colon = ':', star = '*', cr = '\r', lf = '\n'; char c = 0, lastc = 0; String lexeme; uint32 line = 1, state = READY, lastQuote = 0; ScriptTokenListPtr tokens(OGRE_NEW_T(ScriptTokenList, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T); // Iterate over the input String::const_iterator i = str.begin(), end = str.end(); while(i != end) { lastc = c; c = *i; if(c == quote) lastQuote = line; switch(state) { case READY: if(c == slash && lastc == slash) { // Comment start, clear out the lexeme lexeme = ""; state = COMMENT; } else if(c == star && lastc == slash) { lexeme = ""; state = MULTICOMMENT; } else if(c == quote) { // Clear out the lexeme ready to be filled with quotes! lexeme = c; state = QUOTE; } else if(c == varopener) { // Set up to read in a variable lexeme = c; state = VAR; } else if(isNewline(c)) { lexeme = c; setToken(lexeme, line, source, tokens.get()); } else if(!isWhitespace(c)) { lexeme = c; if(c == slash) state = POSSIBLECOMMENT; else state = WORD; } break; case COMMENT: if(isNewline(c)) { lexeme = c; setToken(lexeme, line, source, tokens.get()); state = READY; } break; case MULTICOMMENT: if(c == slash && lastc == star) state = READY; break; case POSSIBLECOMMENT: if(c == slash && lastc == slash) { lexeme = ""; state = COMMENT; break; } else if(c == star && lastc == slash) { lexeme = ""; state = MULTICOMMENT; break; } else { state = WORD; } case WORD: if(isNewline(c)) { setToken(lexeme, line, source, tokens.get()); lexeme = c; setToken(lexeme, line, source, tokens.get()); state = READY; } else if(isWhitespace(c)) { setToken(lexeme, line, source, tokens.get()); state = READY; } else if(c == openbrace || c == closebrace || c == colon) { setToken(lexeme, line, source, tokens.get()); lexeme = c; setToken(lexeme, line, source, tokens.get()); state = READY; } else { lexeme += c; } break; case QUOTE: if(c != backslash) { // Allow embedded quotes with escaping if(c == quote && lastc == backslash) { lexeme += c; } else if(c == quote) { lexeme += c; setToken(lexeme, line, source, tokens.get()); state = READY; } else { // Backtrack here and allow a backslash normally within the quote if(lastc == backslash) lexeme = lexeme + "\\" + c; else lexeme += c; } } break; case VAR: if(isNewline(c)) { setToken(lexeme, line, source, tokens.get()); lexeme = c; setToken(lexeme, line, source, tokens.get()); state = READY; } else if(isWhitespace(c)) { setToken(lexeme, line, source, tokens.get()); state = READY; } else if(c == openbrace || c == closebrace || c == colon) { setToken(lexeme, line, source, tokens.get()); lexeme = c; setToken(lexeme, line, source, tokens.get()); state = READY; } else { lexeme += c; } break; } // Separate check for newlines just to track line numbers if(c == cr || (c == lf && lastc != cr)) line++; i++; } // Check for valid exit states if(state == WORD || state == VAR) { if(!lexeme.empty()) setToken(lexeme, line, source, tokens.get()); } else { if(state == QUOTE) { OGRE_EXCEPT(Exception::ERR_INVALID_STATE, Ogre::String("no matching \" found for \" at line ") + Ogre::StringConverter::toString(lastQuote), "ScriptLexer::tokenize"); } } return tokens; } void ScriptLexer::setToken(const Ogre::String &lexeme, Ogre::uint32 line, const String &source, Ogre::ScriptTokenList *tokens) { const char openBracket = '{', closeBracket = '}', colon = ':', quote = '\"', var = '$'; ScriptTokenPtr token(OGRE_NEW_T(ScriptToken, MEMCATEGORY_GENERAL)(), SPFM_DELETE_T); token->lexeme = lexeme; token->line = line; token->file = source; bool ignore = false; // Check the user token map first if(lexeme.size() == 1 && isNewline(lexeme[0])) { token->type = TID_NEWLINE; if(!tokens->empty() && tokens->back()->type == TID_NEWLINE) ignore = true; } else if(lexeme.size() == 1 && lexeme[0] == openBracket) token->type = TID_LBRACKET; else if(lexeme.size() == 1 && lexeme[0] == closeBracket) token->type = TID_RBRACKET; else if(lexeme.size() == 1 && lexeme[0] == colon) token->type = TID_COLON; else if(lexeme[0] == var) token->type = TID_VARIABLE; else { // This is either a non-zero length phrase or quoted phrase if(lexeme.size() >= 2 && lexeme[0] == quote && lexeme[lexeme.size() - 1] == quote) { token->type = TID_QUOTE; } else { token->type = TID_WORD; } } if(!ignore) tokens->push_back(token); } bool ScriptLexer::isWhitespace(Ogre::String::value_type c) const { return c == ' ' || c == '\r' || c == '\t'; } bool ScriptLexer::isNewline(Ogre::String::value_type c) const { return c == '\n' || c == '\r'; } } <|endoftext|>