text
stringlengths
5
1.04M
//----------------------------------------------------------------------------// /* * Copyright (c) 2009 Sony Pictures Imageworks 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 Sony Pictures Imageworks 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. */ //----------------------------------------------------------------------------// /*! \file SparseFile.cpp \brief Contains implementations relating to reading of sparse field files. */ //----------------------------------------------------------------------------// // SparseField.h includes SparseFile.h, but we need the definition of // SparseBlock from SparseField.h, so just include that to get both // files #include "SparseField.h" //----------------------------------------------------------------------------// FIELD3D_NAMESPACE_OPEN //----------------------------------------------------------------------------// // Static instances //----------------------------------------------------------------------------// SparseFileManager *SparseFileManager::ms_singleton = 0; //----------------------------------------------------------------------------// // SparseFileManager //----------------------------------------------------------------------------// SparseFileManager & SparseFileManager::singleton() { if (!ms_singleton) { ms_singleton = new SparseFileManager; } return *ms_singleton; } //----------------------------------------------------------------------------// void SparseFileManager::setLimitMemUse(bool enabled) { m_limitMemUse = enabled; } //----------------------------------------------------------------------------// bool SparseFileManager::doLimitMemUse() const { return m_limitMemUse; } //----------------------------------------------------------------------------// void SparseFileManager::setMaxMemUse(float maxMemUse) { m_maxMemUse = maxMemUse; m_maxMemUseInBytes = static_cast<int>(m_maxMemUse * 1024*1024); } //----------------------------------------------------------------------------// template <class Data_T> int SparseFileManager::deallocateBlock(const SparseFile::CacheBlock &cb) { int bytesFreed = 0; SparseFile::Reference<Data_T> &reference = m_fileData.ref<Data_T>(cb.refIdx); // Note: we don't need to lock the block's mutex because // deallocateBlock() is only called while the SparseFileManager's // mutex is also locked (in flushCache() or deallocateBlocks()). // Don't lock the block, to make sure we don't have a deadlock by // holding two locks at the same time. (Because addBlockToCache() // locks the manager but is also in a block-specific lock.) // lock the current block to make sure its blockUsed flag and ref // counts don't change // Note: this lock order is made consistent w/ allocate to prevent // deadlocks and crashes. boost::mutex::scoped_lock lock_B(reference.blockMutex[cb.blockIdx]); // check whether the block is still in use if (reference.refCounts[cb.blockIdx] > 0) return bytesFreed; if (reference.blockUsed[cb.blockIdx]) { // the block was recently used according to Second-chance paging // algorithm, so skip it reference.blockUsed[cb.blockIdx] = false; } else { // the block wasn't in use, so free it reference.unloadBlock(cb.blockIdx); bytesFreed = reference.blockSize(cb.blockIdx); m_memUse -= bytesFreed; CacheList::iterator toRemove = m_nextBlock; ++m_nextBlock; m_blockCacheList.erase(toRemove); } return bytesFreed; } //----------------------------------------------------------------------------// template <class Data_T> void SparseFileManager::deallocateBlock(CacheList::iterator &it) { SparseFile::CacheBlock &cb = *it; SparseFile::Reference<Data_T> &reference = m_fileData.ref<Data_T>(cb.refIdx); int bytesFreed = reference.blockSize(cb.blockIdx); m_memUse -= bytesFreed; reference.unloadBlock(cb.blockIdx); it = m_blockCacheList.erase(it); } //----------------------------------------------------------------------------// void SparseFileManager::deallocateBlocks(int bytesNeeded) { boost::mutex::scoped_lock lock_A(m_mutex); while (m_blockCacheList.begin() != m_blockCacheList.end() && m_maxMemUseInBytes-m_memUse < bytesNeeded) { if (m_nextBlock == m_blockCacheList.end()) m_nextBlock = m_blockCacheList.begin(); SparseFile::CacheBlock &cb = *m_nextBlock; // if bytesFreed is set to >0, then we've already freed a block // and advanced the "clock hand" iterator int bytesFreed = 0; switch(cb.blockType) { case DataTypeHalf: bytesFreed = deallocateBlock<half>(cb); if (bytesFreed > 0) { continue; } break; case DataTypeFloat: bytesFreed = deallocateBlock<float>(cb); if (bytesFreed > 0) { continue; } break; case DataTypeDouble: bytesFreed = deallocateBlock<double>(cb); if (bytesFreed > 0) { continue; } break; case DataTypeVecHalf: bytesFreed = deallocateBlock<V3h>(cb); if (bytesFreed > 0) { continue; } break; case DataTypeVecFloat: bytesFreed = deallocateBlock<V3f>(cb); if (bytesFreed > 0) { continue; } break; case DataTypeVecDouble: bytesFreed = deallocateBlock<V3d>(cb); if (bytesFreed > 0) { continue; } break; case DataTypeUnknown: default: break; } ++m_nextBlock; } } //----------------------------------------------------------------------------// void SparseFileManager::flushCache() { boost::mutex::scoped_lock lock(m_mutex); CacheList::iterator it = m_blockCacheList.begin(); while (it != m_blockCacheList.end()) { SparseFile::CacheBlock &cb = *it; switch(cb.blockType) { case DataTypeHalf: deallocateBlock<half>(it); break; case DataTypeFloat: deallocateBlock<float>(it); break; case DataTypeDouble: deallocateBlock<double>(it); break; case DataTypeVecHalf: deallocateBlock<V3h>(it); break; case DataTypeVecFloat: deallocateBlock<V3f>(it); break; case DataTypeVecDouble: deallocateBlock<V3d>(it); break; case DataTypeUnknown: default: break; } } m_nextBlock = m_blockCacheList.begin(); } //----------------------------------------------------------------------------// void SparseFileManager::addBlockToCache(DataTypeEnum blockType, int fileId, int blockIdx) { // Note: this lock is obtained while we also have a lock on the // specific block (in activateBlock()), so we should make sure we // never lock the SparseFileManager and *then* a block, to ensure we // don't have a deadlock. // // Note: this was changed so the order was consistent w/ dealloc // again, see activateBlock() // boost::mutex::scoped_lock lock(m_mutex); SparseFile::CacheBlock block(blockType, fileId, blockIdx); if (m_nextBlock == m_blockCacheList.end()) { m_blockCacheList.push_back(block); } else { m_blockCacheList.insert(m_nextBlock, block); } } //----------------------------------------------------------------------------// SparseFileManager::SparseFileManager() : m_memUse(0), m_limitMemUse(false) { setMaxMemUse(1000.0); m_nextBlock = m_blockCacheList.begin(); } //----------------------------------------------------------------------------// long long SparseFileManager::totalLoads() { long long int numLoads = 0; for (int i=0; i<m_fileData.numRefs<half>(); i++) { numLoads += m_fileData.ref<half>(i).totalLoads(); } for (int i=0; i<m_fileData.numRefs<V3h>(); i++) { numLoads += m_fileData.ref<V3h>(i).totalLoads(); } for (int i=0; i<m_fileData.numRefs<float>(); i++) { numLoads += m_fileData.ref<float>(i).totalLoads(); } for (int i=0; i<m_fileData.numRefs<V3f>(); i++) { numLoads += m_fileData.ref<V3f>(i).totalLoads(); } for (int i=0; i<m_fileData.numRefs<double>(); i++) { numLoads += m_fileData.ref<double>(i).totalLoads(); } for (int i=0; i<m_fileData.numRefs<V3d>(); i++) { numLoads += m_fileData.ref<V3d>(i).totalLoads(); } return numLoads; } //----------------------------------------------------------------------------// long long SparseFileManager::numLoadedBlocks() { long long int numBlocks = 0; for (int i=0; i<m_fileData.numRefs<half>(); i++) { numBlocks += m_fileData.ref<half>(i).numLoadedBlocks(); } for (int i=0; i<m_fileData.numRefs<V3h>(); i++) { numBlocks += m_fileData.ref<V3h>(i).numLoadedBlocks(); } for (int i=0; i<m_fileData.numRefs<float>(); i++) { numBlocks += m_fileData.ref<float>(i).numLoadedBlocks(); } for (int i=0; i<m_fileData.numRefs<V3f>(); i++) { numBlocks += m_fileData.ref<V3f>(i).numLoadedBlocks(); } for (int i=0; i<m_fileData.numRefs<double>(); i++) { numBlocks += m_fileData.ref<double>(i).numLoadedBlocks(); } for (int i=0; i<m_fileData.numRefs<V3d>(); i++) { numBlocks += m_fileData.ref<V3d>(i).numLoadedBlocks(); } return numBlocks; } //----------------------------------------------------------------------------// long long SparseFileManager::totalLoadedBlocks() { long long int numBlocks = 0; for (int i=0; i<m_fileData.numRefs<half>(); i++) { numBlocks += m_fileData.ref<half>(i).totalLoadedBlocks(); } for (int i=0; i<m_fileData.numRefs<V3h>(); i++) { numBlocks += m_fileData.ref<V3h>(i).totalLoadedBlocks(); } for (int i=0; i<m_fileData.numRefs<float>(); i++) { numBlocks += m_fileData.ref<float>(i).totalLoadedBlocks(); } for (int i=0; i<m_fileData.numRefs<V3f>(); i++) { numBlocks += m_fileData.ref<V3f>(i).totalLoadedBlocks(); } for (int i=0; i<m_fileData.numRefs<double>(); i++) { numBlocks += m_fileData.ref<double>(i).totalLoadedBlocks(); } for (int i=0; i<m_fileData.numRefs<V3d>(); i++) { numBlocks += m_fileData.ref<V3d>(i).totalLoadedBlocks(); } return numBlocks; } //----------------------------------------------------------------------------// float SparseFileManager::cacheFractionLoaded() { return ((double)numLoadedBlocks())/std::max(1.0, ((double)totalLoadedBlocks())); } //----------------------------------------------------------------------------// float SparseFileManager::cacheLoadsPerBlock() { return ((double)totalLoads())/std::max(1.0, ((double)totalLoadedBlocks())); } //----------------------------------------------------------------------------// float SparseFileManager::cacheEfficiency() { return ((double)totalLoadedBlocks())/std::max(1.0, ((double)totalLoads())); } //----------------------------------------------------------------------------// void SparseFileManager::resetCacheStatistics() { for (int i=0; i<m_fileData.numRefs<half>(); i++) { m_fileData.ref<half>(i).resetCacheStatistics(); } for (int i=0; i<m_fileData.numRefs<V3h>(); i++) { m_fileData.ref<V3h>(i).resetCacheStatistics(); } for (int i=0; i<m_fileData.numRefs<float>(); i++) { m_fileData.ref<float>(i).resetCacheStatistics(); } for (int i=0; i<m_fileData.numRefs<V3f>(); i++) { m_fileData.ref<V3f>(i).resetCacheStatistics(); } for (int i=0; i<m_fileData.numRefs<double>(); i++) { m_fileData.ref<double>(i).resetCacheStatistics(); } for (int i=0; i<m_fileData.numRefs<V3d>(); i++) { m_fileData.ref<V3d>(i).resetCacheStatistics(); } } //----------------------------------------------------------------------------// FIELD3D_NAMESPACE_HEADER_CLOSE //----------------------------------------------------------------------------//
#pragma once #include "ResourcePath.hpp" namespace Engine { // TODO: Move to RED4ext.SDK struct ResourceAsyncReference { explicit ResourceAsyncReference(ResourcePath aPath = "") : path(aPath) {} ResourcePath path; }; static_assert(sizeof(ResourceAsyncReference) == 0x8); }
// Copyright (c) 2014-2019, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER 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 "common/dns_utils.h" #include "common/command_line.h" #include "version.h" #include "daemon/command_parser_executor.h" #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY "daemon" namespace daemonize { t_command_parser_executor::t_command_parser_executor( uint32_t ip , uint16_t port , const boost::optional<tools::login>& login , const epee::net_utils::ssl_options_t& ssl_options , bool is_rpc , cryptonote::core_rpc_server* rpc_server ) : m_executor(ip, port, login, ssl_options, is_rpc, rpc_server) {} bool t_command_parser_executor::print_peer_list(const std::vector<std::string>& args) { if (args.size() > 3) { std::cout << "use: print_pl [white] [gray] [<limit>] [pruned] [publicrpc]" << std::endl; return true; } bool white = false; bool gray = false; bool pruned = false; bool publicrpc = false; size_t limit = 0; for (size_t i = 0; i < args.size(); ++i) { if (args[i] == "white") { white = true; } else if (args[i] == "gray") { gray = true; } else if (args[i] == "pruned") { pruned = true; } else if (args[i] == "publicrpc") { publicrpc = true; } else if (!epee::string_tools::get_xtype_from_string(limit, args[i])) { std::cout << "unexpected argument: " << args[i] << std::endl; return true; } } const bool print_both = !white && !gray; return m_executor.print_peer_list(white | print_both, gray | print_both, limit, pruned, publicrpc); } bool t_command_parser_executor::print_peer_list_stats(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.print_peer_list_stats(); } bool t_command_parser_executor::save_blockchain(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.save_blockchain(); } bool t_command_parser_executor::show_hash_rate(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.show_hash_rate(); } bool t_command_parser_executor::hide_hash_rate(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.hide_hash_rate(); } bool t_command_parser_executor::show_difficulty(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.show_difficulty(); } bool t_command_parser_executor::show_status(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.show_status(); } bool t_command_parser_executor::print_connections(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.print_connections(); } bool t_command_parser_executor::print_net_stats(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.print_net_stats(); } bool t_command_parser_executor::print_blockchain_info(const std::vector<std::string>& args) { if(!args.size()) { std::cout << "need block index parameter" << std::endl; return false; } uint64_t start_index = 0; uint64_t end_index = 0; if(!epee::string_tools::get_xtype_from_string(start_index, args[0])) { std::cout << "wrong starter block index parameter" << std::endl; return false; } if(args.size() >1 && !epee::string_tools::get_xtype_from_string(end_index, args[1])) { std::cout << "wrong end block index parameter" << std::endl; return false; } return m_executor.print_blockchain_info(start_index, end_index); } bool t_command_parser_executor::set_log_level(const std::vector<std::string>& args) { if(args.size() > 1) { std::cout << "use: set_log [<log_level_number_0-4> | <categories>]" << std::endl; return true; } if (args.empty()) { return m_executor.set_log_categories("+"); } uint16_t l = 0; if(epee::string_tools::get_xtype_from_string(l, args[0])) { if(4 < l) { std::cout << "wrong number range, use: set_log <log_level_number_0-4>" << std::endl; return true; } return m_executor.set_log_level(l); } else { return m_executor.set_log_categories(args.front()); } } bool t_command_parser_executor::print_height(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.print_height(); } bool t_command_parser_executor::print_block(const std::vector<std::string>& args) { bool include_hex = false; // Assumes that optional flags come after mandatory argument <transaction_hash> for (unsigned int i = 1; i < args.size(); ++i) { if (args[i] == "+hex") include_hex = true; else { std::cout << "unexpected argument: " << args[i] << std::endl; return true; } } if (args.empty()) { std::cout << "expected: print_block (<block_hash> | <block_height>) [+hex]" << std::endl; return false; } const std::string& arg = args.front(); try { uint64_t height = boost::lexical_cast<uint64_t>(arg); return m_executor.print_block_by_height(height, include_hex); } catch (const boost::bad_lexical_cast&) { crypto::hash block_hash; if (parse_hash256(arg, block_hash)) { return m_executor.print_block_by_hash(block_hash, include_hex); } } return false; } bool t_command_parser_executor::print_transaction(const std::vector<std::string>& args) { bool include_hex = false; bool include_json = false; // Assumes that optional flags come after mandatory argument <transaction_hash> for (unsigned int i = 1; i < args.size(); ++i) { if (args[i] == "+hex") include_hex = true; else if (args[i] == "+json") include_json = true; else { std::cout << "unexpected argument: " << args[i] << std::endl; return true; } } if (args.empty()) { std::cout << "expected: print_tx <transaction_hash> [+hex] [+json]" << std::endl; return true; } const std::string& str_hash = args.front(); crypto::hash tx_hash; if (parse_hash256(str_hash, tx_hash)) { m_executor.print_transaction(tx_hash, include_hex, include_json); } return true; } bool t_command_parser_executor::is_key_image_spent(const std::vector<std::string>& args) { if (args.empty()) { std::cout << "expected: is_key_image_spent <key_image>" << std::endl; return true; } const std::string& str = args.front(); crypto::key_image ki; crypto::hash hash; if (parse_hash256(str, hash)) { memcpy(&ki, &hash, sizeof(ki)); m_executor.is_key_image_spent(ki); } return true; } bool t_command_parser_executor::print_transaction_pool_long(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.print_transaction_pool_long(); } bool t_command_parser_executor::print_transaction_pool_short(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.print_transaction_pool_short(); } bool t_command_parser_executor::print_transaction_pool_stats(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.print_transaction_pool_stats(); } bool t_command_parser_executor::start_mining(const std::vector<std::string>& args) { if(!args.size()) { std::cout << "Please specify a wallet address to mine for: start_mining <addr> [<threads>|auto]" << std::endl; return true; } cryptonote::address_parse_info info; cryptonote::network_type nettype = cryptonote::MAINNET; if(!cryptonote::get_account_address_from_str(info, cryptonote::MAINNET, args.front())) { if(!cryptonote::get_account_address_from_str(info, cryptonote::TESTNET, args.front())) { if(!cryptonote::get_account_address_from_str(info, cryptonote::STAGENET, args.front())) { bool dnssec_valid; std::string address_str = tools::dns_utils::get_account_address_as_str_from_url(args.front(), dnssec_valid, [](const std::string &url, const std::vector<std::string> &addresses, bool dnssec_valid){return addresses[0];}); if(!cryptonote::get_account_address_from_str(info, cryptonote::MAINNET, address_str)) { if(!cryptonote::get_account_address_from_str(info, cryptonote::TESTNET, address_str)) { if(!cryptonote::get_account_address_from_str(info, cryptonote::STAGENET, address_str)) { std::cout << "target account address has wrong format" << std::endl; return true; } else { nettype = cryptonote::STAGENET; } } else { nettype = cryptonote::TESTNET; } } } else { nettype = cryptonote::STAGENET; } } else { nettype = cryptonote::TESTNET; } } if (info.is_subaddress) { tools::fail_msg_writer() << "subaddress for mining reward is not yet supported!" << std::endl; return true; } if(nettype != cryptonote::MAINNET) std::cout << "Mining to a " << (nettype == cryptonote::TESTNET ? "testnet" : "stagenet") << " address, make sure this is intentional!" << std::endl; uint64_t threads_count = 1; bool do_background_mining = false; bool ignore_battery = false; if(args.size() > 4) { return false; } if(args.size() == 4) { if(args[3] == "true" || command_line::is_yes(args[3]) || args[3] == "1") { ignore_battery = true; } else if(args[3] != "false" && !command_line::is_no(args[3]) && args[3] != "0") { return false; } } if(args.size() >= 3) { if(args[2] == "true" || command_line::is_yes(args[2]) || args[2] == "1") { do_background_mining = true; } else if(args[2] != "false" && !command_line::is_no(args[2]) && args[2] != "0") { return false; } } if(args.size() >= 2) { if (args[1] == "auto" || args[1] == "autodetect") { threads_count = 0; } else { bool ok = epee::string_tools::get_xtype_from_string(threads_count, args[1]); threads_count = (ok && 0 < threads_count) ? threads_count : 1; } } m_executor.start_mining(info.address, threads_count, nettype, do_background_mining, ignore_battery); return true; } bool t_command_parser_executor::stop_mining(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.stop_mining(); } bool t_command_parser_executor::mining_status(const std::vector<std::string>& args) { return m_executor.mining_status(); } bool t_command_parser_executor::stop_daemon(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.stop_daemon(); } bool t_command_parser_executor::print_status(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.print_status(); } bool t_command_parser_executor::set_limit(const std::vector<std::string>& args) { if(args.size()>1) return false; if(args.size()==0) { return m_executor.get_limit(); } int64_t limit; try { limit = std::stoll(args[0]); } catch(const std::exception& ex) { std::cout << "failed to parse argument" << std::endl; return false; } return m_executor.set_limit(limit, limit); } bool t_command_parser_executor::set_limit_up(const std::vector<std::string>& args) { if(args.size()>1) return false; if(args.size()==0) { return m_executor.get_limit_up(); } int64_t limit; try { limit = std::stoll(args[0]); } catch(const std::exception& ex) { std::cout << "failed to parse argument" << std::endl; return false; } return m_executor.set_limit(0, limit); } bool t_command_parser_executor::set_limit_down(const std::vector<std::string>& args) { if(args.size()>1) return false; if(args.size()==0) { return m_executor.get_limit_down(); } int64_t limit; try { limit = std::stoll(args[0]); } catch(const std::exception& ex) { std::cout << "failed to parse argument" << std::endl; return false; } return m_executor.set_limit(limit, 0); } bool t_command_parser_executor::out_peers(const std::vector<std::string>& args) { bool set = false; uint32_t limit = 0; try { if (!args.empty()) { limit = std::stoi(args[0]); set = true; } } catch(const std::exception& ex) { _erro("stoi exception"); return false; } return m_executor.out_peers(set, limit); } bool t_command_parser_executor::in_peers(const std::vector<std::string>& args) { bool set = false; uint32_t limit = 0; try { if (!args.empty()) { limit = std::stoi(args[0]); set = true; } } catch(const std::exception& ex) { _erro("stoi exception"); return false; } return m_executor.in_peers(set, limit); } bool t_command_parser_executor::hard_fork_info(const std::vector<std::string>& args) { int version; if (args.size() == 0) { version = 0; } else if (args.size() == 1) { try { version = std::stoi(args[0]); } catch(const std::exception& ex) { return false; } if (version <= 0 || version > 255) return false; } else { return false; } return m_executor.hard_fork_info(version); } bool t_command_parser_executor::show_bans(const std::vector<std::string>& args) { if (!args.empty()) return false; return m_executor.print_bans(); } bool t_command_parser_executor::ban(const std::vector<std::string>& args) { if (args.size() != 1 && args.size() != 2) return false; std::string ip = args[0]; time_t seconds = P2P_IP_BLOCKTIME; if (args.size() > 1) { try { seconds = std::stoi(args[1]); } catch (const std::exception &e) { return false; } if (seconds == 0) { return false; } } return m_executor.ban(ip, seconds); } bool t_command_parser_executor::unban(const std::vector<std::string>& args) { if (args.size() != 1) return false; std::string ip = args[0]; return m_executor.unban(ip); } bool t_command_parser_executor::banned(const std::vector<std::string>& args) { if (args.size() != 1) return false; std::string address = args[0]; return m_executor.banned(address); } bool t_command_parser_executor::flush_txpool(const std::vector<std::string>& args) { if (args.size() > 1) return false; std::string txid; if (args.size() == 1) { crypto::hash hash; if (!parse_hash256(args[0], hash)) { std::cout << "failed to parse tx id" << std::endl; return true; } txid = args[0]; } return m_executor.flush_txpool(txid); } bool t_command_parser_executor::output_histogram(const std::vector<std::string>& args) { std::vector<uint64_t> amounts; uint64_t min_count = 3; uint64_t max_count = 0; size_t n_raw = 0; for (size_t n = 0; n < args.size(); ++n) { if (args[n][0] == '@') { amounts.push_back(boost::lexical_cast<uint64_t>(args[n].c_str() + 1)); } else if (n_raw == 0) { min_count = boost::lexical_cast<uint64_t>(args[n]); n_raw++; } else if (n_raw == 1) { max_count = boost::lexical_cast<uint64_t>(args[n]); n_raw++; } else { std::cout << "Invalid syntax: more than two non-amount parameters" << std::endl; return true; } } return m_executor.output_histogram(amounts, min_count, max_count); } bool t_command_parser_executor::print_coinbase_tx_sum(const std::vector<std::string>& args) { if(!args.size()) { std::cout << "need block height parameter" << std::endl; return false; } uint64_t height = 0; uint64_t count = 0; if(!epee::string_tools::get_xtype_from_string(height, args[0])) { std::cout << "wrong starter block height parameter" << std::endl; return false; } if(args.size() >1 && !epee::string_tools::get_xtype_from_string(count, args[1])) { std::cout << "wrong count parameter" << std::endl; return false; } return m_executor.print_coinbase_tx_sum(height, count); } bool t_command_parser_executor::alt_chain_info(const std::vector<std::string>& args) { if(args.size() > 1) { std::cout << "usage: alt_chain_info [block_hash|>N|-N]" << std::endl; return false; } std::string tip; size_t above = 0; uint64_t last_blocks = 0; if (args.size() == 1) { if (args[0].size() > 0 && args[0][0] == '>') { if (!epee::string_tools::get_xtype_from_string(above, args[0].c_str() + 1)) { std::cout << "invalid above parameter" << std::endl; return false; } } else if (args[0].size() > 0 && args[0][0] == '-') { if (!epee::string_tools::get_xtype_from_string(last_blocks, args[0].c_str() + 1)) { std::cout << "invalid last_blocks parameter" << std::endl; return false; } } else { tip = args[0]; } } return m_executor.alt_chain_info(tip, above, last_blocks); } bool t_command_parser_executor::print_blockchain_dynamic_stats(const std::vector<std::string>& args) { if(args.size() != 1) { std::cout << "Exactly one parameter is needed" << std::endl; return false; } uint64_t nblocks = 0; if(!epee::string_tools::get_xtype_from_string(nblocks, args[0]) || nblocks == 0) { std::cout << "wrong number of blocks" << std::endl; return false; } return m_executor.print_blockchain_dynamic_stats(nblocks); } bool t_command_parser_executor::update(const std::vector<std::string>& args) { if(args.size() != 1) { std::cout << "Exactly one parameter is needed: check, download, or update" << std::endl; return false; } return m_executor.update(args.front()); } bool t_command_parser_executor::relay_tx(const std::vector<std::string>& args) { if (args.size() != 1) return false; std::string txid; crypto::hash hash; if (!parse_hash256(args[0], hash)) { std::cout << "failed to parse tx id" << std::endl; return true; } txid = args[0]; return m_executor.relay_tx(txid); } bool t_command_parser_executor::sync_info(const std::vector<std::string>& args) { if (args.size() != 0) return false; return m_executor.sync_info(); } bool t_command_parser_executor::pop_blocks(const std::vector<std::string>& args) { if (args.size() != 1) { std::cout << "Exactly one parameter is needed" << std::endl; return false; } try { uint64_t nblocks = boost::lexical_cast<uint64_t>(args[0]); if (nblocks < 1) { std::cout << "number of blocks must be greater than 0" << std::endl; return false; } return m_executor.pop_blocks(nblocks); } catch (const boost::bad_lexical_cast&) { std::cout << "number of blocks must be a number greater than 0" << std::endl; } return false; } bool t_command_parser_executor::rpc_payments(const std::vector<std::string>& args) { if (args.size() != 0) return false; return m_executor.rpc_payments(); } bool t_command_parser_executor::version(const std::vector<std::string>& args) { std::cout << "Monerov '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << std::endl; return true; } bool t_command_parser_executor::prune_blockchain(const std::vector<std::string>& args) { if (args.size() > 1) return false; if (args.empty() || args[0] != "confirm") { std::cout << "Warning: pruning from within xmvd will not shrink the database file size." << std::endl; std::cout << "Instead, parts of the file will be marked as free, so the file will not grow" << std::endl; std::cout << "until that newly free space is used up. If you want a smaller file size now," << std::endl; std::cout << "exit xmvd and run xmv-blockchain-prune (you will temporarily need more" << std::endl; std::cout << "disk space for the database conversion though). If you are OK with the database" << std::endl; std::cout << "file keeping the same size, re-run this command with the \"confirm\" parameter." << std::endl; return true; } return m_executor.prune_blockchain(); } bool t_command_parser_executor::check_blockchain_pruning(const std::vector<std::string>& args) { return m_executor.check_blockchain_pruning(); } bool t_command_parser_executor::set_bootstrap_daemon(const std::vector<std::string>& args) { const size_t args_count = args.size(); if (args_count < 1 || args_count > 3) { return false; } return m_executor.set_bootstrap_daemon( args[0] != "none" ? args[0] : std::string(), args_count > 1 ? args[1] : std::string(), args_count > 2 ? args[2] : std::string()); } bool t_command_parser_executor::flush_cache(const std::vector<std::string>& args) { if (args.empty()) goto show_list; if (args[0] == "bad-txs") return m_executor.flush_cache(true); show_list: std::cout << "Cache type needed: bad-txs" << std::endl; return true; } } // namespace daemonize
#include "Jankpch.h" #include "LayerStack.h" namespace Jank { LayerStack::LayerStack() { } LayerStack::~LayerStack() { for (Layer* layer : m_Layers) { delete layer; } } void LayerStack::PushLayer(Layer* layer) { m_Layers.emplace(m_Layers.begin() + m_LayerInsertIndex, layer); m_LayerInsertIndex++; } void LayerStack::PushOverlay(Layer* overlay) { m_Layers.emplace_back(overlay); } void LayerStack::PopLayer(Layer* layer) { auto it = std::find(m_Layers.begin(), m_Layers.end(), layer); if (it != m_Layers.end()) { m_Layers.erase(it); m_LayerInsertIndex--; } } void LayerStack::PopOverlay(Layer* overlay) { auto it = std::find(m_Layers.begin(), m_Layers.end(), overlay); if (it != m_Layers.end()) { m_Layers.erase(it); } } }
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItemStructure_Flag_Manticore_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function PrimalItemStructure_Flag_Manticore.PrimalItemStructure_Flag_Manticore_C.ExecuteUbergraph_PrimalItemStructure_Flag_Manticore struct UPrimalItemStructure_Flag_Manticore_C_ExecuteUbergraph_PrimalItemStructure_Flag_Manticore_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the QtXmlPatterns module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qbuiltintypes_p.h" #include "qgyearmonth_p.h" QT_BEGIN_NAMESPACE using namespace QPatternist; GYearMonth::GYearMonth(const QDateTime &dateTime) : AbstractDateTime(dateTime) { } GYearMonth::Ptr GYearMonth::fromLexical(const QString &lexical) { static const CaptureTable captureTable( // STATIC DATA /* The extra paranthesis is a build fix for GCC 3.3. */ (QRegExp(QLatin1String( "^\\s*" /* Any preceding whitespace. */ "(-?)" /* Any preceding minus. */ "(\\d{4,})" /* The year part. */ "-" /* Delimiter. */ "(\\d{2})" /* The month part. */ "(?:(\\+|-)(\\d{2}):(\\d{2})|(Z))?" /* The zone offset, "+08:24". */ "\\s*$" /* Any terminating whitespace. */))), /*zoneOffsetSignP*/ 4, /*zoneOffsetHourP*/ 5, /*zoneOffsetMinuteP*/ 6, /*zoneOffsetUTCSymbolP*/ 7, /*yearP*/ 2, /*monthP*/ 3, /*dayP*/ -1, /*hourP*/ -1, /*minutesP*/ -1, /*secondsP*/ -1, /*msecondsP*/ -1, /*yearSign*/ 1); AtomicValue::Ptr err; const QDateTime retval(create(err, lexical, captureTable)); return err ? err : GYearMonth::Ptr(new GYearMonth(retval)); } GYearMonth::Ptr GYearMonth::fromDateTime(const QDateTime &dt) { QDateTime result(QDate(dt.date().year(), dt.date().month(), DefaultDay)); copyTimeSpec(dt, result); return GYearMonth::Ptr(new GYearMonth(result)); } QString GYearMonth::stringValue() const { return m_dateTime.toString(QLatin1String("yyyy-MM")) + zoneOffsetToString(); } ItemType::Ptr GYearMonth::type() const { return BuiltinTypes::xsGYearMonth; } QT_END_NAMESPACE
/* ----------------------------------------------------------------------------- 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 "PlayPenTests.h" #include "OgreResourceGroupManager.h" #include "OgreCodec.h" #include "OgreFileSystemLayer.h" #include "OgreLodConfig.h" #include "OgreMovablePlane.h" #include "OgreRectangle2D.h" #include "OgreMovableObject.h" #include "OgreBillboard.h" #include "OgreParticleSystem.h" #ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR #include "OgreMeshLodGenerator.h" #endif using namespace Ogre; struct OrientedLightPtr { Light* l; SceneNode* ln; OrientedLightPtr(Light* _l) : l(_l) { ln = l->_getManager()->getRootSceneNode()->createChildSceneNode(); ln->attachObject(l); } OrientedLightPtr* operator->() { return this; } void setType(Light::LightTypes type) { l->setType(type); } void setDirection(const Vector3& v) { ln->setDirection(v, Node::TS_WORLD); } void setCastShadows(bool b) { l->setCastShadows(b); } void setDiffuseColour(float r, float g, float b) { l->setDiffuseColour(r, g, b); } void setSpecularColour(float r, float g, float b) { l->setSpecularColour(r, g, b); } }; static void createRandomEntityClones(Entity* ent, size_t cloneCount, const Vector3& min, const Vector3& max, SceneManager* mgr); #ifdef OGRE_BUILD_COMPONENT_MESHLODGENERATOR PlayPen_ManualLOD::PlayPen_ManualLOD() { mInfo["Title"] = "PlayPen_ManualLOD"; mInfo["Description"] = "Testing meshes with manual LODs assigned"; addScreenshotFrame(75); } //--------------------------------------------------------------------------- void PlayPen_ManualLOD::setupContent() { String meshName = getLODMesh(); Entity *ent; for (int i = 0; i < 5; ++i) { ent = mSceneMgr->createEntity("robot" + StringConverter::toString(i), meshName); // Add entity to the scene node SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode( Vector3(0, 0, (i * 50) - (5 * 50 / 2))); n->setScale(0.2, 0.2, 0.2); n->attachObject(ent); } mAnimation = ent->getAnimationState("Walk"); mAnimation->setEnabled(true); // Give it a little ambience with lights Light* l; l = mSceneMgr->createLight("BlueLight"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200,-80,-100))->attachObject(l); l->setDiffuseColour(0.5, 0.5, 1.0); l = mSceneMgr->createLight("GreenLight"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,0,-100))->attachObject(l); l->setDiffuseColour(0.5, 1.0, 0.5); // Position the camera mCameraNode->setPosition(100,25,100); mCameraNode->lookAt(Vector3(-50, 0, -25), Node::TS_PARENT); mSceneMgr->setAmbientLight(ColourValue::White); } //--------------------------------------------------------------------------- bool PlayPen_ManualLOD::frameStarted(const FrameEvent& evt) { mAnimation->addTime(evt.timeSinceLastFrame); return true; } //----------------------------------------------------------------------- String PlayPen_ManualLOD::getLODMesh() { MeshPtr msh1 = MeshManager::getSingleton().load("robot.mesh", ASSETS_RESOURCE_GROUP); LodConfig lodConfig(msh1); lodConfig.createManualLodLevel(136, "razor.mesh"); lodConfig.createManualLodLevel(211, "sphere.mesh"); MeshLodGenerator().generateLodLevels(lodConfig); return msh1->getName(); } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- PlayPen_ManualLODFromFile::PlayPen_ManualLODFromFile() { mInfo["Title"] = "PlayPen_ManualLOD_File"; mInfo["Description"] = "Testing meshes with manual LODs assigned, loaded from a file"; addScreenshotFrame(75); } //--------------------------------------------------------------------- String PlayPen_ManualLODFromFile::getLODMesh() { MeshPtr msh1 = MeshManager::getSingleton().load("robot.mesh", ASSETS_RESOURCE_GROUP); LodConfig lodConfig(msh1); lodConfig.createManualLodLevel(136, "razor.mesh"); lodConfig.createManualLodLevel(211, "sphere.mesh"); MeshLodGenerator().generateLodLevels(lodConfig); // this time, we save this data to a file and re-load it MeshSerializer ser; const ResourceGroupManager::LocationList& ll = ResourceGroupManager::getSingleton().getResourceLocationList("Tests"); String prefix; for (ResourceGroupManager::LocationList::const_iterator i = ll.begin(); i != ll.end(); ++i) { if (StringUtil::endsWith(i->archive->getName(), "media")) { prefix = i->archive->getName(); } } ser.exportMesh(msh1.get(), prefix + "/testlod.mesh"); MeshManager::getSingleton().removeAll(); return "testlod.mesh"; } #endif //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- PlayPen_ManualBlend::PlayPen_ManualBlend() { mInfo["Title"] = "PlayPen_ManualBlending"; mInfo["Description"] = "Manual blending"; addScreenshotFrame(10); } //--------------------------------------------------------------------------- void PlayPen_ManualBlend::setupContent() { // create material MaterialPtr mat = MaterialManager::getSingleton().create("TestMat", TRANSIENT_RESOURCE_GROUP); Pass * p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->createTextureUnitState("Dirt.jpg"); TextureUnitState* t = p->createTextureUnitState("ogrelogo.png"); t->setColourOperationEx(LBX_BLEND_MANUAL, LBS_TEXTURE, LBS_CURRENT, ColourValue::White, ColourValue::White, 0.75); Entity *planeEnt = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(planeEnt); planeEnt->setMaterialName("TestMat"); mCameraNode->setPosition(0,0,600); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //--------------------------------------------------------------------- //--------------------------------------------------------------------- PlayPen_ProjectSphere::PlayPen_ProjectSphere() { mInfo["Title"] = "PlayPen_ProjectSphere"; mInfo["Description"] = "Projecting a sphere's bounds onto the camera."; addScreenshotFrame(10); } //--------------------------------------------------------------------------- void PlayPen_ProjectSphere::setupContent() { mSceneMgr->setAmbientLight(ColourValue::White); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 0; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 4500,4500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("Examples/GrassFloor"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); mProjectionSphere = new Sphere(Vector3(0, 2000, 0), 1500.0); ManualObject* debugSphere = mSceneMgr->createManualObject("debugSphere"); debugSphere->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_STRIP); for (int i = 0; i <= 20; ++i) { Vector3 basePos(mProjectionSphere->getRadius(), 0, 0); Quaternion quat; quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Y); basePos = quat * basePos; debugSphere->position(basePos); } for (int i = 0; i <= 20; ++i) { Vector3 basePos(mProjectionSphere->getRadius(), 0, 0); Quaternion quat; quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Z); basePos = quat * basePos; debugSphere->position(basePos); } debugSphere->end(); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,2000,0))->attachObject(debugSphere); MaterialPtr mat = MaterialManager::getSingleton().create( "scissormat", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setDepthWriteEnabled(false); p->setSceneBlending(SBT_TRANSPARENT_ALPHA); TextureUnitState* t = p->createTextureUnitState(); t->setColourOperationEx(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, ColourValue::Red); t->setAlphaOperation(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, 0.5f); mScissorRect = mSceneMgr->createManualObject("mScissorRect"); mScissorRect->setUseIdentityProjection(true); mScissorRect->setUseIdentityView(true); AxisAlignedBox aabb; aabb.setInfinite(); mScissorRect->setBoundingBox(aabb); mScissorRect->begin(mat->getName()); mScissorRect->position(Vector3::ZERO); mScissorRect->position(Vector3::ZERO); mScissorRect->position(Vector3::ZERO); mScissorRect->quad(0, 1, 2, 3); mScissorRect->end(); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(mScissorRect); mCameraNode->setPosition(0,3000,5000); mCameraNode->lookAt(mProjectionSphere->getCenter(), Node::TS_PARENT); } //--------------------------------------------------------------------------- bool PlayPen_ProjectSphere::frameStarted(const FrameEvent& evt) { Real left, top, right, bottom; mCamera->projectSphere(*mProjectionSphere, &left, &top, &right, &bottom); mScissorRect->beginUpdate(0); mScissorRect->position(left, top, 0); mScissorRect->position(left, bottom, 0); mScissorRect->position(right, bottom, 0); mScissorRect->position(right, top, 0); mScissorRect->quad(0,1,2,3); mScissorRect->end(); return true; } //--------------------------------------------------------------------- //--------------------------------------------------------------------- PlayPen_CameraSetDirection::PlayPen_CameraSetDirection() : mUseParentNode(false) , mUseFixedYaw(true) , mFocus(100,200,-300) { mInfo["Title"] = "PlayPen_CameraSetDirection"; mInfo["Description"] = "Testing various settings for Camera::setDirection"; addScreenshotFrame(10); } //--------------------------------------------------------------------- void PlayPen_CameraSetDirection::setupContent() { mSceneMgr->setAmbientLight(ColourValue::White); Entity* e = mSceneMgr->createEntity("1", "knot.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode(mFocus)->attachObject(e); mCameraNode->setPosition(200,1000,1000); mCameraNode->lookAt(mFocus, Node::TS_PARENT); //mTrayMgr->createButton(OgreBites::TL_BOTTOM, "Look At", "Look At"); //mTrayMgr->createCheckBox(OgreBites::TL_BOTTOM, "tglParent", "Use Parent Node"); //OgreBites::CheckBox* chk = mTrayMgr->createCheckBox(OgreBites::TL_BOTTOM, "tglFixedYaw", "Use Fixed Yaw"); //chk->setChecked(true, false); //mTrayMgr->showCursor(); //setDragLook(true); mParentNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(1000, 2000, -1000)); } //--------------------------------------------------------------------- void PlayPen_CameraSetDirection::buttonHit(OgreBites::Button* button) { mCameraNode->lookAt(mFocus, Node::TS_PARENT); } //--------------------------------------------------------------------- void PlayPen_CameraSetDirection::checkBoxToggled(OgreBites::CheckBox* box) { if (box->getName() == "tglParent") { mUseParentNode = !mUseParentNode; if (mUseParentNode) mParentNode->attachObject(mCamera); else mParentNode->detachAllObjects(); } else if (box->getName() == "tglFixedYaw") { mUseFixedYaw = !mUseFixedYaw; if (mUseFixedYaw) mCameraNode->setFixedYawAxis(true); else mCameraNode->setFixedYawAxis(false); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- PlayPen_MorphAnimationWithNormals::PlayPen_MorphAnimationWithNormals() { mInfo["Title"] = "PlayPen_MorphAnimNormals"; mInfo["Description"] = "Testing morph animation with normals"; addScreenshotFrame(200); } //--------------------------------------------------------------------- void PlayPen_MorphAnimationWithNormals::setupContent() { // explicitly disable stencil volume prep MeshManager::getSingleton().setPrepareAllMeshesForShadowVolumes(false); // Cannot change this to true, not possible to use software morph // animation + normals with stencil shadows because the former // requires pos & normals to be in the same buffer, and the latter // requires positions to be on their own. // bool testStencil = false; //if (testStencil) // mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); Vector3 dir(-1, -1, 0.5); dir.normalise(); OrientedLightPtr l = mSceneMgr->createLight("light1"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(dir); MeshPtr mesh = MeshManager::getSingleton().load("sphere.mesh", ASSETS_RESOURCE_GROUP); String morphName = "testmorphwithnormals.mesh"; mesh = mesh->clone(morphName); SubMesh* sm = mesh->getSubMesh(0); // Re-organise geometry since this mesh has no animation and all // vertex elements are packed into one buffer VertexDeclaration* newDecl = sm->vertexData->vertexDeclaration->getAutoOrganisedDeclaration(false, true, true); sm->vertexData->reorganiseBuffers(newDecl); //if (testStencil) // sm->vertexData->prepareForShadowVolume(); // need to re-prep since reorganised // get the position buffer (which should now be separate); const VertexElement* posElem = sm->vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); HardwareVertexBufferSharedPtr origbuf = sm->vertexData->vertexBufferBinding->getBuffer( posElem->getSource()); // Create a new position & normal buffer with updated values HardwareVertexBufferSharedPtr newbuf = HardwareBufferManager::getSingleton().createVertexBuffer( VertexElement::getTypeSize(VET_FLOAT3) * 2, sm->vertexData->vertexCount, HardwareBuffer::HBU_STATIC, true); float* pSrc = static_cast<float*>(origbuf->lock(HardwareBuffer::HBL_READ_ONLY)); float* pDst = static_cast<float*>(newbuf->lock(HardwareBuffer::HBL_DISCARD)); // Make the sphere turn into a cube // Do this just by clamping each of the directions (we shrink it) float cubeDimension = 0.3f * mesh->getBoundingSphereRadius(); size_t srcSkip = origbuf->getVertexSize() / sizeof(float) - 3; for (size_t v = 0; v < sm->vertexData->vertexCount; ++v) { // x/y/z position Vector3 pos; for (int d = 0; d < 3; ++d) { if (*pSrc >= 0) { pos.ptr()[d] = std::min(cubeDimension, *pSrc++); } else { pos.ptr()[d] = std::max(-cubeDimension, *pSrc++); } *pDst++ = pos.ptr()[d]; } // normal // this should point along the major axis // unfortunately since vertices are not duplicated at edges there will be // some inaccuracy here but the most important thing is to add sharp edges Vector3 norm = pos.normalisedCopy(); norm = norm.primaryAxis(); *pDst++ = norm.x; *pDst++ = norm.y; *pDst++ = norm.z; pSrc += srcSkip; } origbuf->unlock(); newbuf->unlock(); // create a morph animation Animation* anim = mesh->createAnimation("testAnim", 10.0f); VertexAnimationTrack* vt = anim->createVertexTrack(1, sm->vertexData, VAT_MORPH); // re-use start positions for frame 0 VertexMorphKeyFrame* kf = vt->createVertexMorphKeyFrame(0); kf->setVertexBuffer(origbuf); // Use translated buffer for mid frame kf = vt->createVertexMorphKeyFrame(4.0f); kf->setVertexBuffer(newbuf); // Pause there kf = vt->createVertexMorphKeyFrame(6.0f); kf->setVertexBuffer(newbuf); // re-use start positions for final frame kf = vt->createVertexMorphKeyFrame(10.0f); kf->setVertexBuffer(origbuf); // Export the mesh String outPath, baseName; String exportName = mFSLayer->getWritablePath(morphName); StringUtil::splitFilename(exportName, baseName, outPath); Ogre::ResourceGroupManager& resMgr = Ogre::ResourceGroupManager::getSingleton(); resMgr.addResourceLocation(outPath, "FileSystem", TRANSIENT_RESOURCE_GROUP, false, false); DataStreamPtr stream = resMgr.createResource(morphName, TRANSIENT_RESOURCE_GROUP); MeshSerializer ser; ser.exportMesh(mesh.get(), stream); stream->close(); // Unload old mesh to force reload MeshManager::getSingleton().remove(mesh->getHandle()); mesh->unload(); mesh.reset(); Entity* e = mSceneMgr->createEntity("test", morphName); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); AnimationState* animState = e->getAnimationState("testAnim"); animState->setEnabled(true); animState->setWeight(1.0f); mAnimations[0] = animState; e = mSceneMgr->createEntity("test2", morphName); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(200,0,0))->attachObject(e); // test hardware morph e->setMaterialName("Examples/HardwareMorphAnimationWithNormals"); animState = e->getAnimationState("testAnim"); animState->setEnabled(true); animState->setWeight(1.0f); mAnimations[1] = animState; resMgr.deleteResource(morphName, TRANSIENT_RESOURCE_GROUP); mCamera->setNearClipDistance(0.5); mCameraNode->setPosition(0,100,-400); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); //mSceneMgr->setShowDebugShadows(true); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 200; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); } bool PlayPen_MorphAnimationWithNormals::frameStarted(const FrameEvent& evt) { mAnimations[0]->addTime(evt.timeSinceLastFrame); mAnimations[1]->addTime(evt.timeSinceLastFrame); return true; } //--------------------------------------------------------------------- //--------------------------------------------------------------------- PlayPen_MorphAnimationWithoutNormals::PlayPen_MorphAnimationWithoutNormals() { mInfo["Title"] = "PlayPen_MorphAnimNoNormals"; mInfo["Description"] = "Testing morph animation without normals"; addScreenshotFrame(200); } //--------------------------------------------------------------------- void PlayPen_MorphAnimationWithoutNormals::setupContent() { //bool testStencil = false; //if (testStencil) // mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); Vector3 dir(-1, -1, 0.5); dir.normalise(); OrientedLightPtr l = mSceneMgr->createLight("light1"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(dir); MeshPtr mesh = MeshManager::getSingleton().load("sphere.mesh", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); String morphName = "testmorphnonormals.mesh"; mesh = mesh->clone(morphName); SubMesh* sm = mesh->getSubMesh(0); // Re-organise geometry since this mesh has no animation and all // vertex elements are packed into one buffer VertexDeclaration* newDecl = sm->vertexData->vertexDeclaration->getAutoOrganisedDeclaration(false, true, false); sm->vertexData->reorganiseBuffers(newDecl); //if (testStencil) // sm->vertexData->prepareForShadowVolume(); // need to re-prep since reorganised // get the position buffer (which should now be separate); const VertexElement* posElem = sm->vertexData->vertexDeclaration->findElementBySemantic(VES_POSITION); HardwareVertexBufferSharedPtr origbuf = sm->vertexData->vertexBufferBinding->getBuffer( posElem->getSource()); // Create a new position & normal buffer with updated values HardwareVertexBufferSharedPtr newbuf = HardwareBufferManager::getSingleton().createVertexBuffer( VertexElement::getTypeSize(VET_FLOAT3), sm->vertexData->vertexCount, HardwareBuffer::HBU_STATIC, true); float* pSrc = static_cast<float*>(origbuf->lock(HardwareBuffer::HBL_READ_ONLY)); float* pDst = static_cast<float*>(newbuf->lock(HardwareBuffer::HBL_DISCARD)); // Make the sphere turn into a cube // Do this just by clamping each of the directions (we shrink it) float cubeDimension = 0.3f * mesh->getBoundingSphereRadius(); for (size_t v = 0; v < sm->vertexData->vertexCount; ++v) { // x/y/z position Vector3 pos; for (int d = 0; d < 3; ++d) { if (*pSrc >= 0) { pos.ptr()[d] = std::min(cubeDimension, *pSrc++); } else { pos.ptr()[d] = std::max(-cubeDimension, *pSrc++); } *pDst++ = pos.ptr()[d]; } } origbuf->unlock(); newbuf->unlock(); // create a morph animation Animation* anim = mesh->createAnimation("testAnim", 10.0f); VertexAnimationTrack* vt = anim->createVertexTrack(1, sm->vertexData, VAT_MORPH); // re-use start positions for frame 0 VertexMorphKeyFrame* kf = vt->createVertexMorphKeyFrame(0); kf->setVertexBuffer(origbuf); // Use translated buffer for mid frame kf = vt->createVertexMorphKeyFrame(4.0f); kf->setVertexBuffer(newbuf); // Pause there kf = vt->createVertexMorphKeyFrame(6.0f); kf->setVertexBuffer(newbuf); // re-use start positions for final frame kf = vt->createVertexMorphKeyFrame(10.0f); kf->setVertexBuffer(origbuf); // Add resource location for exported mesh String exportName = mFSLayer->getWritablePath(morphName); String path; StringUtil::splitFilename(exportName, morphName, path); ResourceGroupManager::getSingleton().addResourceLocation(path, "FileSystem", TRANSIENT_RESOURCE_GROUP, false, false); // Export the mesh DataStreamPtr stream = ResourceGroupManager::getSingleton().createResource(morphName, TRANSIENT_RESOURCE_GROUP); MeshSerializer ser; ser.exportMesh(mesh.get(), stream); stream->close(); // Unload old mesh to force reload MeshManager::getSingleton().remove(mesh->getHandle()); mesh->unload(); mesh.reset(); Entity* e = mSceneMgr->createEntity("test", morphName); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); AnimationState* animState = e->getAnimationState("testAnim"); animState->setEnabled(true); animState->setWeight(1.0f); mAnimations[0] = animState; e = mSceneMgr->createEntity("test2", morphName); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(200,0,0))->attachObject(e); // test hardware morph e->setMaterialName("Examples/HardwareMorphAnimation"); animState = e->getAnimationState("testAnim"); animState->setEnabled(true); animState->setWeight(1.0f); mAnimations[1] = animState; ResourceGroupManager::getSingleton().deleteResource(morphName, TRANSIENT_RESOURCE_GROUP); mCamera->setNearClipDistance(0.5); mCameraNode->setPosition(0,100,-400); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); // mSceneMgr->setShowDebugShadows(true); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 200; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); } bool PlayPen_MorphAnimationWithoutNormals::frameStarted(const FrameEvent& evt) { mAnimations[0]->addTime(evt.timeSinceLastFrame); mAnimations[1]->addTime(evt.timeSinceLastFrame); return true; } //--------------------------------------------------------------------- //--------------------------------------------------------------------- PlayPen_PoseAnimationWithNormals::PlayPen_PoseAnimationWithNormals() { mInfo["Title"] = "PlayPen_PoseAnimNormals"; mInfo["Description"] = "Testing pose animation with normals"; addScreenshotFrame(200); } //--------------------------------------------------------------------- void PlayPen_PoseAnimationWithNormals::setupContent() { mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); Vector3 dir(-1, -1, 0.5); dir.normalise(); OrientedLightPtr l = mSceneMgr->createLight("light1"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(dir); MeshPtr mesh = MeshManager::getSingleton().load("cube.mesh", ASSETS_RESOURCE_GROUP); String newName = "testposewithnormals.mesh"; mesh = mesh->clone(newName); SubMesh* sm = mesh->getSubMesh(0); // Re-organise geometry since this mesh has no animation and all // vertex elements are packed into one buffer VertexDeclaration* newDecl = sm->vertexData->vertexDeclaration->getAutoOrganisedDeclaration(false, true, true); sm->vertexData->reorganiseBuffers(newDecl); // create 2 poses Pose* pose = mesh->createPose(1, "pose1"); // Pose1 moves vertices 0, 1, 2 and 3 upward and pushes normals left Vector3 offset1(0, 50, 0); pose->addVertex(0, offset1, Vector3::NEGATIVE_UNIT_X); pose->addVertex(1, offset1, Vector3::NEGATIVE_UNIT_X); pose->addVertex(2, offset1, Vector3::NEGATIVE_UNIT_X); pose->addVertex(3, offset1, Vector3::NEGATIVE_UNIT_X); pose = mesh->createPose(1, "pose2"); // Pose2 moves vertices 3, 4, and 5 to the right and pushes normals right // Note 3 gets affected by both Vector3 offset2(100, 0, 0); pose->addVertex(3, offset2, Vector3::UNIT_X); pose->addVertex(4, offset2, Vector3::UNIT_X); pose->addVertex(5, offset2, Vector3::UNIT_X); Animation* anim = mesh->createAnimation("poseanim", 20.0f); VertexAnimationTrack* vt = anim->createVertexTrack(1, sm->vertexData, VAT_POSE); // Frame 0 - no effect vt->createVertexPoseKeyFrame(0); // Frame 1 - bring in pose 1 (index 0) VertexPoseKeyFrame* kf = vt->createVertexPoseKeyFrame(3); kf->addPoseReference(0, 1.0f); // Frame 2 - remove all vt->createVertexPoseKeyFrame(6); // Frame 3 - bring in pose 2 (index 1) kf = vt->createVertexPoseKeyFrame(9); kf->addPoseReference(1, 1.0f); // Frame 4 - remove all vt->createVertexPoseKeyFrame(12); // Frame 5 - bring in pose 1 at 50%, pose 2 at 100% kf = vt->createVertexPoseKeyFrame(15); kf->addPoseReference(0, 0.5f); kf->addPoseReference(1, 1.0f); // Frame 6 - bring in pose 1 at 100%, pose 2 at 50% kf = vt->createVertexPoseKeyFrame(18); kf->addPoseReference(0, 1.0f); kf->addPoseReference(1, 0.5f); // Frame 7 - reset vt->createVertexPoseKeyFrame(20); // Export the mesh String exportName = mFSLayer->getWritablePath(newName); String outPath, baseName; StringUtil::splitFilename(exportName, baseName, outPath); Ogre::ResourceGroupManager& resMgr = Ogre::ResourceGroupManager::getSingleton(); resMgr.addResourceLocation(outPath, "FileSystem", TRANSIENT_RESOURCE_GROUP, false, false); DataStreamPtr stream = resMgr.createResource(newName, TRANSIENT_RESOURCE_GROUP); MeshSerializer ser; ser.exportMesh(mesh.get(), stream); stream->close(); // Unload old mesh to force reload MeshManager::getSingleton().remove(mesh->getHandle()); mesh->unload(); mesh.reset(); Entity* e; AnimationState* animState; // software pose e = mSceneMgr->createEntity("test2", newName); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(150,0,0))->attachObject(e); animState = e->getAnimationState("poseanim"); animState->setEnabled(true); animState->setWeight(1.0f); mAnimations[0] = animState; // test hardware pose e = mSceneMgr->createEntity("test", newName); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); e->setMaterialName("Examples/HardwarePoseAnimationWithNormals"); animState = e->getAnimationState("poseanim"); animState->setEnabled(true); animState->setWeight(1.0f); mAnimations[1] = animState; resMgr.deleteResource(newName, TRANSIENT_RESOURCE_GROUP); mCamera->setNearClipDistance(0.5); mSceneMgr->setShowDebugShadows(true); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 200; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); mCameraNode->setPosition(0,-200,-300); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); } //--------------------------------------------------------------------- bool PlayPen_PoseAnimationWithNormals::frameStarted(const FrameEvent& evt) { mAnimations[0]->addTime(evt.timeSinceLastFrame); mAnimations[1]->addTime(evt.timeSinceLastFrame); return true; } //--------------------------------------------------------------------- //--------------------------------------------------------------------- PlayPen_PoseAnimationWithoutNormals::PlayPen_PoseAnimationWithoutNormals() { mInfo["Title"] = "PlayPen_PoseAnimNoNormals"; mInfo["Description"] = "Testing pose animation without normals"; addScreenshotFrame(200); } //--------------------------------------------------------------------- void PlayPen_PoseAnimationWithoutNormals::setupContent() { mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); Vector3 dir(-1, -1, 0.5); dir.normalise(); OrientedLightPtr l = mSceneMgr->createLight("light1"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(dir); MeshPtr mesh = MeshManager::getSingleton().load("cube.mesh", ASSETS_RESOURCE_GROUP); String newName = "testposenonormals.mesh"; mesh = mesh->clone(newName); SubMesh* sm = mesh->getSubMesh(0); // Re-organise geometry since this mesh has no animation and all // vertex elements are packed into one buffer VertexDeclaration* newDecl = sm->vertexData->vertexDeclaration->getAutoOrganisedDeclaration(false, true, false); sm->vertexData->reorganiseBuffers(newDecl); // create 2 poses Pose* pose = mesh->createPose(1, "pose1"); // Pose1 moves vertices 0, 1, 2 and 3 upward Vector3 offset1(0, 50, 0); pose->addVertex(0, offset1); pose->addVertex(1, offset1); pose->addVertex(2, offset1); pose->addVertex(3, offset1); pose = mesh->createPose(1, "pose2"); // Pose2 moves vertices 3, 4, and 5 to the right // Note 3 gets affected by both Vector3 offset2(100, 0, 0); pose->addVertex(3, offset2); pose->addVertex(4, offset2); pose->addVertex(5, offset2); Animation* anim = mesh->createAnimation("poseanim", 20.0f); VertexAnimationTrack* vt = anim->createVertexTrack(1, sm->vertexData, VAT_POSE); // Frame 0 - no effect vt->createVertexPoseKeyFrame(0); // Frame 1 - bring in pose 1 (index 0) VertexPoseKeyFrame* kf = vt->createVertexPoseKeyFrame(3); kf->addPoseReference(0, 1.0f); // Frame 2 - remove all vt->createVertexPoseKeyFrame(6); // Frame 3 - bring in pose 2 (index 1) kf = vt->createVertexPoseKeyFrame(9); kf->addPoseReference(1, 1.0f); // Frame 4 - remove all vt->createVertexPoseKeyFrame(12); // Frame 5 - bring in pose 1 at 50%, pose 2 at 100% kf = vt->createVertexPoseKeyFrame(15); kf->addPoseReference(0, 0.5f); kf->addPoseReference(1, 1.0f); // Frame 6 - bring in pose 1 at 100%, pose 2 at 50% kf = vt->createVertexPoseKeyFrame(18); kf->addPoseReference(0, 1.0f); kf->addPoseReference(1, 0.5f); // Frame 7 - reset vt->createVertexPoseKeyFrame(20); // Export the mesh String outPath, baseName; String exportName = mFSLayer->getWritablePath(newName); StringUtil::splitFilename(exportName, baseName, outPath); Ogre::ResourceGroupManager& resMgr = Ogre::ResourceGroupManager::getSingleton(); resMgr.addResourceLocation(outPath, "FileSystem", TRANSIENT_RESOURCE_GROUP, false, false); DataStreamPtr stream = resMgr.createResource(newName, TRANSIENT_RESOURCE_GROUP); MeshSerializer ser; ser.exportMesh(mesh.get(), stream); stream->close(); // Unload old mesh to force reload MeshManager::getSingleton().remove(mesh->getHandle()); mesh->unload(); mesh.reset(); Entity* e; AnimationState* animState; // software pose e = mSceneMgr->createEntity("test2", newName); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(150,0,0))->attachObject(e); animState = e->getAnimationState("poseanim"); animState->setEnabled(true); animState->setWeight(1.0f); mAnimations[0] = animState; // test hardware pose e = mSceneMgr->createEntity("test", newName); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); e->setMaterialName("Examples/HardwarePoseAnimation"); animState = e->getAnimationState("poseanim"); animState->setEnabled(true); animState->setWeight(1.0f); mAnimations[1] = animState; resMgr.deleteResource(newName, TRANSIENT_RESOURCE_GROUP); mCamera->setNearClipDistance(0.5); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 200; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); mCameraNode->setPosition(0,-200,-300); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); } //--------------------------------------------------------------------------- bool PlayPen_PoseAnimationWithoutNormals::frameStarted(const FrameEvent& evt) { mAnimations[0]->addTime(evt.timeSinceLastFrame); mAnimations[1]->addTime(evt.timeSinceLastFrame); return true; } //--------------------------------------------------------------------------- PlayPen_SceneNodeTracking::PlayPen_SceneNodeTracking() { mInfo["Title"] = "PlayPen_SceneNodeTracking"; mInfo["Description"] = "Testing scenenode tracking."; addScreenshotFrame(200); } //----------------------------------------------------------------------- bool PlayPen_SceneNodeTracking::frameStarted(const FrameEvent& evt) { mAnimState->addTime(evt.timeSinceLastFrame); return true; } //----------------------------------------------------------------------- void PlayPen_SceneNodeTracking::setupContent() { // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); // Create a skydome mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8); // Create a light Light* l = mSceneMgr->createLight("MainLight"); // Accept default settings: point light, white diffuse, just set position // NB I could attach the light to a SceneNode if I wanted it to move automatically with // other objects, but I don't mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(20,80,50))->attachObject(l); Entity *ent; // Define a floor plane mesh Plane p; p.normal = Vector3::UNIT_Y; p.d = 200; MeshManager::getSingleton().createPlane("FloorPlane", TRANSIENT_RESOURCE_GROUP, p,200000,200000,20,20,true,1,50,50,Vector3::UNIT_Z); // Create an entity (the floor) ent = mSceneMgr->createEntity("floor", "FloorPlane"); ent->setMaterialName("Examples/RustySteel"); // Attach to child of root node, better for culling (otherwise bounds are the combination of the 2) mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); // Add a head, give it it's own node SceneNode* headNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); ent = mSceneMgr->createEntity("head", "ogrehead.mesh"); headNode->attachObject(ent); // Add another head, give it it's own node SceneNode* headNode2 = mSceneMgr->getRootSceneNode()->createChildSceneNode(); ent = mSceneMgr->createEntity("head2", "ogrehead.mesh"); headNode2->attachObject(ent); // Make sure the head node tracks the root headNode->setAutoTracking(true, headNode2, Vector3::UNIT_Z); //headNode->setFixedYawAxis(true); // Create the camera node & attach camera //SceneNode* camNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); //camNode->attachObject(mCamera); // set up spline animation of node Animation* anim = mSceneMgr->createAnimation("CameraTrack", 10); // Spline it for nice curves anim->setInterpolationMode(Animation::IM_SPLINE); // Create a track to animate the head's node NodeAnimationTrack* track = anim->createNodeTrack(0, headNode); // Setup keyframes track->createNodeKeyFrame(0); // startposition TransformKeyFrame* key = track->createNodeKeyFrame(2.5); key->setTranslate(Vector3(500,500,-1000)); key = track->createNodeKeyFrame(5); key->setTranslate(Vector3(-1500,1000,-600)); key = track->createNodeKeyFrame(7.5); key->setTranslate(Vector3(0,-100,0)); key = track->createNodeKeyFrame(10); key->setTranslate(Vector3(0,0,0)); // Create a track to animate the second head's node track = anim->createNodeTrack(1, headNode2); // Setup keyframes track->createNodeKeyFrame(0); // startposition key = track->createNodeKeyFrame(2.5); key->setTranslate(Vector3(-500,600,-100)); key = track->createNodeKeyFrame(5); key->setTranslate(Vector3(800,200,-600)); key = track->createNodeKeyFrame(7.5); key->setTranslate(Vector3(200,-1000,0)); key = track->createNodeKeyFrame(10); key->setTranslate(Vector3(30,70,110)); // Create a new animation state to track this mAnimState = mSceneMgr->createAnimationState("CameraTrack"); mAnimState->setEnabled(true); // Put in a bit of fog for the hell of it //mSceneMgr->setFog(FOG_EXP, ColourValue::White, 0.0002); mCameraNode->setPosition(-300,600,2000); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- PlayPen_NonUniqueResourceNames::PlayPen_NonUniqueResourceNames() { mInfo["Title"] = "PlayPen_NonUniqueResourceNames"; mInfo["Description"] = "Testing resources without unique names (in different resource groups)."; addScreenshotFrame(50); } //----------------------------------------------------------------------- void PlayPen_NonUniqueResourceNames::setupContent() { // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); // Define the required skyplane Plane plane; // 5000 world units from the camera plane.d = 5000; // Above the camera, facing down plane.normal = -Vector3::UNIT_Y; // Create the plane 10000 units wide, tile the texture 3 times mSceneMgr->setSkyPlane(true, plane, "Examples/SpaceSkyPlane",10000,3); // Create a light Light* l = mSceneMgr->createLight("MainLight"); // Accept default settings: point light, white diffuse, just set position // NB I could attach the light to a SceneNode if I wanted it to move automatically with // other objects, but I don't mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(20,80,50))->attachObject(l); createMeshEntity("Model1", Vector3(10, 10, 10)); createMeshEntity("Model2", Vector3(-10, -10, -10)); mCameraNode->setPosition(100,0,-100); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); } //----------------------------------------------------------------------- void PlayPen_NonUniqueResourceNames::createMeshEntity(String group, Vector3 pos) { // Get path to test resources (ugly, but the only way I can think // of to consistently get the right path (since it's determined by // cmake build location) without explicitly defining the groups in // resources.cfg). const Ogre::ResourceGroupManager::LocationList& ll = Ogre::ResourceGroupManager::getSingleton().getResourceLocationList("Tests"); const Ogre::ResourceGroupManager::ResourceLocation* loc = &ll.front(); Ogre::String testResourcePath = loc->archive->getName(); Ogre::String meshFilePath = testResourcePath + "/" + group; Ogre::ResourceGroupManager& resMgr = Ogre::ResourceGroupManager::getSingleton(); String newGroup = meshFilePath; resMgr.createResourceGroup(group, false); resMgr.addResourceLocation(meshFilePath, "FileSystem", group); resMgr.initialiseResourceGroup(group); Ogre::MeshPtr newMesh = Ogre::MeshManager::getSingleton().load("UniqueModel.MESH", group); Entity *newEnt = mSceneMgr->createEntity(group, "UniqueModel.MESH", group); SceneNode* newNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); newNode->attachObject(newEnt); newNode->setPosition(pos); // I was getting an assertion on some part of the skeleton loading //AnimationState* aniState =newEnt->getAnimationState(newEnt->getMesh()->getSkeleton()->getAnimation(0)->getName()); //mAnimStateList.push_back(aniState); //aniState->setEnabled(true); //aniState->setLoop(true); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- PlayPen_16Textures::PlayPen_16Textures() { mInfo["Title"] = "PlayPen_16Textures"; mInfo["Description"] = "Tests applying 16 textures in a single material."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_16Textures::testCapabilities(const Ogre::RenderSystemCapabilities* caps) { if(caps->getNumTextureUnits() < 16) throw Ogre::Exception(999, "Needs 16 Texture Units to run", "testCapabilities"); } void PlayPen_16Textures::setupContent() { HighLevelGpuProgramPtr frag; if (StringUtil::match(Root::getSingleton().getRenderSystem()->getName(), "*GL 3+*")) { frag = HighLevelGpuProgramManager::getSingleton().createProgram("frag16", TRANSIENT_RESOURCE_GROUP, "glsl", GPT_FRAGMENT_PROGRAM); String source = " \ #version 130\n \ uniform sampler2D tex0; \ uniform sampler2D tex1; \ uniform sampler2D tex2; \ uniform sampler2D tex3; \ uniform sampler2D tex4; \ uniform sampler2D tex5; \ uniform sampler2D tex6; \ uniform sampler2D tex7; \ uniform sampler2D tex8; \ uniform sampler2D tex9; \ uniform sampler2D tex10; \ uniform sampler2D tex11; \ uniform sampler2D tex12; \ uniform sampler2D tex13; \ uniform sampler2D tex14; \ uniform sampler2D tex15; \ in vec4 ambientUV; \ out vec4 fragColour; \ void main() \ { \ fragColour = texture(tex15, ambientUV.xy); \ } \ "; frag->setSource(source); } else if (StringUtil::match(Root::getSingleton().getRenderSystem()->getName(), "*GL ES 2*")) { frag = HighLevelGpuProgramManager::getSingleton().createProgram("frag16", TRANSIENT_RESOURCE_GROUP, "glsles", GPT_FRAGMENT_PROGRAM); frag->setSource(" \ #version 100\n \ precision highp float; \ precision highp int; \ uniform sampler2D tex0; \ uniform sampler2D tex1; \ uniform sampler2D tex2; \ uniform sampler2D tex3; \ uniform sampler2D tex4; \ uniform sampler2D tex5; \ uniform sampler2D tex6; \ uniform sampler2D tex7; \ uniform sampler2D tex8; \ uniform sampler2D tex9; \ uniform sampler2D tex10; \ uniform sampler2D tex11; \ uniform sampler2D tex12; \ uniform sampler2D tex13; \ uniform sampler2D tex14; \ uniform sampler2D tex15; \ varying vec4 ambientUV; \ void main() \ { \ gl_FragColor = texture2D(tex15, ambientUV.xy); \ } \ "); } else if (StringUtil::match(Root::getSingleton().getRenderSystem()->getName(), "*GL*")) { frag = HighLevelGpuProgramManager::getSingleton().createProgram("frag16", TRANSIENT_RESOURCE_GROUP, "glsl", GPT_FRAGMENT_PROGRAM); frag->setSource(" \ uniform sampler2D tex0; \ uniform sampler2D tex1; \ uniform sampler2D tex2; \ uniform sampler2D tex3; \ uniform sampler2D tex4; \ uniform sampler2D tex5; \ uniform sampler2D tex6; \ uniform sampler2D tex7; \ uniform sampler2D tex8; \ uniform sampler2D tex9; \ uniform sampler2D tex10; \ uniform sampler2D tex11; \ uniform sampler2D tex12; \ uniform sampler2D tex13; \ uniform sampler2D tex14; \ uniform sampler2D tex15; \ void main() \ { \ gl_FragColor = texture2D(tex15, gl_TexCoord[0].xy); \ } \ "); } else // DirectX { frag = HighLevelGpuProgramManager::getSingleton().createProgram("frag16", TRANSIENT_RESOURCE_GROUP, "hlsl", GPT_FRAGMENT_PROGRAM); frag->setParameter("target", "ps_2_0"); frag->setParameter("entry_point", "main"); frag->setSource(" \ float4 main( \ float2 uv : TEXCOORD0, \ uniform sampler2D tex0 : register(s0), \ uniform sampler2D tex1 : register(s1), \ uniform sampler2D tex2 : register(s2), \ uniform sampler2D tex3 : register(s3), \ uniform sampler2D tex4 : register(s4), \ uniform sampler2D tex5 : register(s5), \ uniform sampler2D tex6 : register(s6), \ uniform sampler2D tex7 : register(s7), \ uniform sampler2D tex8 : register(s8), \ uniform sampler2D tex9 : register(s9), \ uniform sampler2D tex10 : register(s10), \ uniform sampler2D tex11 : register(s11), \ uniform sampler2D tex12 : register(s12), \ uniform sampler2D tex13 : register(s13), \ uniform sampler2D tex14 : register(s14), \ uniform sampler2D tex15 : register(s15) \ ) : COLOR \ { \ return tex2D(tex15, uv); \ } \ "); } frag->load(); MaterialPtr mat = MaterialManager::getSingleton().create("test16", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setVertexProgram("Ogre/BasicVertexPrograms/AmbientOneTextureWithUV"); p->setFragmentProgram(frag->getName()); // create 15 textures the same for (int i = 0; i < 15; ++i) { p->createTextureUnitState("Dirt.jpg"); } // create 16th texture differently p->createTextureUnitState("ogrelogo.png"); if (StringUtil::match(Root::getSingleton().getRenderSystem()->getName(), "*GL*")) { // map samplers GpuProgramParametersSharedPtr params = p->getFragmentProgramParameters(); for (int i = 0; i < 16; ++i) { params->setNamedConstant(String("tex") + StringConverter::toString(i), i); } } mat->load(); Entity* e = mSceneMgr->createEntity("1", "knot.mesh"); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mCameraNode->setPosition(0,0,250); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_2bppAlphaPVR::PlayPen_2bppAlphaPVR() { mInfo["Title"] = "PlayPen_2bppAlphaPVR"; mInfo["Description"] = "Tests 2bpp pvr w/ alpha."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_2bppAlphaPVR::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); MaterialPtr mat = MaterialManager::getSingleton().create("testpvr", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->setSceneBlending(SBT_TRANSPARENT_ALPHA); p->createTextureUnitState("ogreborderUp_pvr2a.pvr"); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- void PlayPen_2bppAlphaPVR::testCapabilities(const Ogre::RenderSystemCapabilities* caps) { Codec* codec = Codec::getCodec("pvr"); if (!codec) throw Ogre::Exception(999, "No support for PVR textures.", "testCapabilities"); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_2bppPVR::PlayPen_2bppPVR() { mInfo["Title"] = "PlayPen_2bppPVR"; mInfo["Description"] = "Tests 2 bpp pvr."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_2bppPVR::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); MaterialPtr mat = MaterialManager::getSingleton().create("testpvr", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->setSceneBlending(SBT_TRANSPARENT_ALPHA); p->createTextureUnitState("ogreborderUp_pvr2.pvr"); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- void PlayPen_2bppPVR::testCapabilities(const Ogre::RenderSystemCapabilities* caps) { Codec* codec = Codec::getCodec("pvr"); if (!codec) throw Ogre::Exception(999, "No support for PVR textures.", "testCapabilities"); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_2Spotlights::PlayPen_2Spotlights() { mInfo["Title"] = "PlayPen_2Spotlights"; mInfo["Description"] = "Tests 2 spotlights on one mesh."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_2Spotlights::setupContent() { SceneNode* mTestNode[5]; mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); Light* mLight = mSceneMgr->createLight("MainLight"); // Spotlight test mLight->setType(Light::LT_SPOTLIGHT); mLight->setDiffuseColour(1.0, 0.0, 0.8); mLight->setSpotlightRange(Degree(30), Degree(40)); mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mTestNode[0]->setPosition(800,600,0); mTestNode[0]->lookAt(Vector3(800,0,0), Node::TS_WORLD); mTestNode[0]->attachObject(mLight); mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mLight = mSceneMgr->createLight("AnotherLight"); // Spotlight test mLight->setType(Light::LT_SPOTLIGHT); mLight->setDiffuseColour(0, 1.0, 0.8); mLight->setSpotlightRange(Degree(30), Degree(40)); mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mTestNode[1]->setPosition(0,600,800); mTestNode[1]->lookAt(Vector3(0,0,800), Node::TS_WORLD); mTestNode[1]->attachObject(mLight); Plane plane( Vector3::UNIT_Y, -100); MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 3500,3500,100,100,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt; pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); mCameraNode->setPosition(-600,300,-600); mCameraNode->lookAt(Vector3(300, 0, 300), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_4bppAlphaPVR::PlayPen_4bppAlphaPVR() { mInfo["Title"] = "PlayPen_4bppAlphaPVR"; mInfo["Description"] = "Tests 4bpp pvr with alpha."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_4bppAlphaPVR::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); MaterialPtr mat = MaterialManager::getSingleton().create("testpvr", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->setSceneBlending(SBT_TRANSPARENT_ALPHA); p->createTextureUnitState("ogreborderUp_pvr4a.pvr"); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- void PlayPen_4bppAlphaPVR::testCapabilities(const Ogre::RenderSystemCapabilities* caps) { Codec* codec = Codec::getCodec("pvr"); if (!codec) throw Ogre::Exception(999, "No support for PVR textures.", "testCapabilities"); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_4bppPVR::PlayPen_4bppPVR() { mInfo["Title"] = "PlayPen_4bppPVR"; mInfo["Description"] = "Tests 4bpp pvr."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_4bppPVR::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); MaterialPtr mat = MaterialManager::getSingleton().create("testpvr", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->setSceneBlending(SBT_TRANSPARENT_ALPHA); p->createTextureUnitState("ogreborderUp_pvr4.pvr"); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- void PlayPen_4bppPVR::testCapabilities(const Ogre::RenderSystemCapabilities* caps) { Codec* codec = Codec::getCodec("pvr"); if (!codec) throw Ogre::Exception(999, "No support for PVR textures.", "testCapabilities"); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_AlphaToCoverage::PlayPen_AlphaToCoverage() { mInfo["Title"] = "PlayPen_AlphaToCoverage"; mInfo["Description"] = "Tests alpha to coverage support."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_AlphaToCoverage::setupContent() { MaterialPtr mat = MaterialManager::getSingleton().create( "testa2c", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setAlphaRejectSettings(CMPF_GREATER, 96); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->setAlphaToCoverageEnabled(true); TextureUnitState* t = p->createTextureUnitState("leaf.png"); t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); t->setColourOperation(LBO_ALPHA_BLEND); Entity *e = mSceneMgr->createEntity("PlaneA2C", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 0))->attachObject(e); mat = MaterialManager::getSingleton().create( "testnoa2c", TRANSIENT_RESOURCE_GROUP); p = mat->getTechnique(0)->getPass(0); p->setAlphaRejectSettings(CMPF_GREATER, 96); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->setAlphaToCoverageEnabled(false); t = p->createTextureUnitState("leaf.png"); t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); t->setColourOperation(LBO_ALPHA_BLEND); e = mSceneMgr->createEntity("PlaneNoA2C", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-100, 0, 0))->attachObject(e); mat = MaterialManager::getSingleton().create( "bg", TRANSIENT_RESOURCE_GROUP); p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); t = p->createTextureUnitState(); t->setColourOperationEx(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, ColourValue::White); e = mSceneMgr->createEntity("PlaneBg", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); e->setRenderQueueGroup(RENDER_QUEUE_BACKGROUND); SceneNode* s = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 0, -10)); s->setScale(5,5,5); s->attachObject(e); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_AttachObjectsToBones::PlayPen_AttachObjectsToBones() { mInfo["Title"] = "PlayPen_AttachObjectsToBones"; mInfo["Description"] = "Tests attaching objectes to bones."; addScreenshotFrame(120); } //---------------------------------------------------------------------------- void PlayPen_AttachObjectsToBones::setupContent() { Entity *ent; for (int i = 0; i < 12; ++i) { ent = mSceneMgr->createEntity("robot" + StringConverter::toString(i), "robot.mesh"); if (i % 2) { Entity* ent2 = mSceneMgr->createEntity("plane" + StringConverter::toString(i), "razor.mesh"); ent->attachObjectToBone("Joint8", ent2); } else { ParticleSystem* psys = mSceneMgr->createParticleSystem("psys" + StringConverter::toString(i), "Examples/PurpleFountain"); psys->getEmitter(0)->setTimeToLive(0.2); ent->attachObjectToBone("Joint15", psys); } // Add entity to the scene node mSceneMgr->getRootSceneNode()->createChildSceneNode( Vector3(0,0,(i*200)-(12*200/2)))->attachObject(ent); ent->getParentNode()->yaw(Degree(i * 45)); AnimationState* animState = ent->getAnimationState("Walk"); animState->setEnabled(true); mAnimStateList.push_back(animState); } // Give it a little ambience with lights Light* l; l = mSceneMgr->createLight("BlueLight"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200,-80,-100))->attachObject(l); l->setDiffuseColour(0.5, 0.5, 1.0); l = mSceneMgr->createLight("GreenLight"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,0,-100))->attachObject(l); l->setDiffuseColour(0.5, 1.0, 0.5); // Position the camera mCameraNode->setPosition(400,120,500); mCameraNode->lookAt(Vector3(-50, 50, 0), Node::TS_PARENT); mSceneMgr->setAmbientLight(ColourValue(1,1,1,1)); //mSceneMgr->showBoundingBoxes(true); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_BasicPlane::PlayPen_BasicPlane() { mInfo["Title"] = "PlayPen_BasicPlane"; mInfo["Description"] = "Tests basic planes."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_BasicPlane::setupContent() { // Create a point light OrientedLightPtr l = mSceneMgr->createLight("MainLight"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(-Vector3::UNIT_Y); Entity *ent; // Define a floor plane mesh Plane p(Vector3::UNIT_Y, -200); MeshManager::getSingleton().createPlane( "FloorPlane", TRANSIENT_RESOURCE_GROUP, p, 2000, 2000, 1, 1, true, 1, 5, 5, Vector3::UNIT_Z); // Create an entity (the floor) ent = mSceneMgr->createEntity("floor", "FloorPlane"); ent->setMaterialName("Examples/RustySteel"); // ent->setMaterialName("BaseWhiteNoLighting"); // ent->setMaterialName("BaseWhite"); mSceneMgr->getRootSceneNode()->attachObject(ent); Entity* sphereEnt = mSceneMgr->createEntity("ogre", "ogrehead.mesh"); SceneNode* mRootNode = mSceneMgr->getRootSceneNode(); SceneNode* node = mSceneMgr->createSceneNode(); node->attachObject(sphereEnt); mRootNode->addChild(node); //mCameraNode->lookAt(Vector3(1, 1, 1), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_BillboardAccurateFacing::PlayPen_BillboardAccurateFacing() { mInfo["Title"] = "PlayPen_BillboardAccurateFacing"; mInfo["Description"] = "Tests billboard facing."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_BillboardAccurateFacing::setupContent() { mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); OrientedLightPtr l = mSceneMgr->createLight("light1"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(Vector3(-1, -1, 0.5).normalisedCopy()); Plane plane(Vector3::UNIT_Y, -100); MeshManager::getSingleton().createPlane( "Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500, 1500, 10, 10, true, 1, 5, 5, Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); BillboardSet* bbs = mSceneMgr->createBillboardSet("1"); bbs->setDefaultDimensions(50, 50); bbs->createBillboard(-100, 25, 0); bbs->setBillboardType(BBT_ORIENTED_COMMON); bbs->setCommonDirection(Vector3::UNIT_Y); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(bbs); bbs = mSceneMgr->createBillboardSet("2"); bbs->setDefaultDimensions(50, 50); bbs->createBillboard(100, 25, 0); bbs->setUseAccurateFacing(true); bbs->setBillboardType(BBT_ORIENTED_COMMON); bbs->setCommonDirection(Vector3::UNIT_Y); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(bbs); mCameraNode->setPosition(200,120,300); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_BillboardChain::PlayPen_BillboardChain() { mInfo["Title"] = "PlayPen_BillboardChain"; mInfo["Description"] = "Tests billboard chains."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_BillboardChain::setupContent() { mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); Vector3 dir(-1, -1, 0.5); dir.normalise(); OrientedLightPtr l = mSceneMgr->createLight("light1"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(dir); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 100; MeshManager::getSingleton().createPlane( "Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); BillboardChain* chain = static_cast<BillboardChain*>( mSceneMgr->createMovableObject("1", "BillboardChain")); chain->setUseTextureCoords(true); chain->setUseVertexColours(false); BillboardChain::Element elem; elem.width = 10; elem.texCoord = 0; elem.position = Vector3(0,20,0); chain->addChainElement(0, elem); elem.position = Vector3(20,0,0); elem.texCoord = 1.0; chain->addChainElement(0, elem); elem.position = Vector3(40,10,0); elem.texCoord = 2.0; chain->addChainElement(0, elem); elem.position = Vector3(60,20,0); elem.texCoord = 3.0; chain->addChainElement(0, elem); elem.position = Vector3(80,40,0); elem.texCoord = 4.0; chain->addChainElement(0, elem); elem.position = Vector3(100,70,0); elem.texCoord = 5.0; chain->addChainElement(0, elem); // BillboardChain does not calculate normals, so result will be inconsistent. //chain->setMaterialName("Examples/ShowNormals"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(chain); mSceneMgr->showBoundingBoxes(true); mCameraNode->setPosition(-20,60,200); mCameraNode->lookAt(Vector3(60, 40, 0), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_BillboardOrigins::PlayPen_BillboardOrigins() { mInfo["Title"] = "PlayPen_BillboardOrigins"; mInfo["Description"] = "Tests setting billboard origins."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_BillboardOrigins::setupContent() { mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); // Billboards currently have no normals. // Vector3 dir(-1, -1, 0.5); // dir.normalise(); // Light* l = mSceneMgr->createLight("light1"); // l->setType(Light::LT_DIRECTIONAL); // l->setDirection(dir); BillboardSet* bbs = mSceneMgr->createBillboardSet("1"); bbs->setDefaultDimensions(50,50); bbs->createBillboard(0, 0, 0); bbs->setBillboardOrigin(BBO_TOP_LEFT); bbs->setMaterialName("2 - Default"); // bbs->setBillboardType(BBT_ORIENTED_COMMON); bbs->setCommonDirection(Vector3::UNIT_Y); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(bbs); bbs = mSceneMgr->createBillboardSet("2"); bbs->setDefaultDimensions(50,50); bbs->createBillboard(0, -10, 0); bbs->setBillboardOrigin(BBO_CENTER); bbs->setMaterialName("Examples/RustySteel"); // bbs->setBillboardType(BBT_ORIENTED_COMMON); bbs->setCommonDirection(Vector3::UNIT_Y); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(bbs); bbs = mSceneMgr->createBillboardSet("3"); bbs->setDefaultDimensions(50,50); bbs->createBillboard(0, -20, 0); bbs->setBillboardOrigin(BBO_BOTTOM_RIGHT); bbs->setMaterialName("Examples/OgreLogo"); // bbs->setBillboardType(BBT_ORIENTED_COMMON); bbs->setCommonDirection(Vector3::UNIT_Y); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(bbs); mCameraNode->setPosition(0,160,1); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_BillboardTextureCoords::PlayPen_BillboardTextureCoords() { mInfo["Title"] = "PlayPen_BillboardTextureCoords"; mInfo["Description"] = "Tests setting billboard texture coordinates."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_BillboardTextureCoords::setupContent() { mSceneMgr->setAmbientLight(ColourValue::White); BillboardSet* bbs = mSceneMgr->createBillboardSet("test"); BillboardSet* bbs2 = mSceneMgr->createBillboardSet("test2"); float xsegs = 3; float ysegs = 3; float width = 300; float height = 300; float gap = 20; // set up texture coords bbs->setTextureStacksAndSlices(ysegs, xsegs); bbs->setDefaultDimensions(width/xsegs, height/xsegs); bbs2->setDefaultDimensions(width/xsegs, height/xsegs); for (float y = 0; y < ysegs; ++y) { for (float x = 0; x < xsegs; ++x) { Vector3 midPoint; midPoint.x = (x * width / xsegs) + ((x-1) * gap); midPoint.y = (y * height / ysegs) + ((y-1) * gap); midPoint.z = 0; Billboard* bb = bbs->createBillboard(midPoint); bb->setTexcoordIndex((ysegs - y - 1)*xsegs + x); Billboard* bb2 = bbs2->createBillboard(midPoint); bb2->setTexcoordRect( FloatRect((x + 0) / xsegs, (ysegs - y - 1) / ysegs, (x + 1) / xsegs, (ysegs - y - 0) / ysegs)); } } bbs->setMaterialName("Examples/OgreLogo"); bbs2->setMaterialName("Examples/OgreLogo"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(bbs); mSceneMgr->getRootSceneNode() ->createChildSceneNode(Vector3(- (width + xsegs * gap), 0, 0)) ->attachObject(bbs2); mCameraNode->setPosition(-100,150,900); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_BlendDiffuseColour::PlayPen_BlendDiffuseColour() { mInfo["Title"] = "PlayPen_BlendDiffuseColour"; mInfo["Description"] = "Tests diffuse blending."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_BlendDiffuseColour::setupContent() { MaterialPtr mat = MaterialManager::getSingleton().create( "testBlendDiffuseColour", TRANSIENT_RESOURCE_GROUP); Pass* pass = mat->getTechnique(0)->getPass(0); // no lighting, it will mess up vertex colours pass->setLightingEnabled(false); // Make sure we pull in vertex colour as diffuse pass->setVertexColourTracking(TVC_DIFFUSE); // Base layer TextureUnitState* t = pass->createTextureUnitState("BeachStones.jpg"); // don't want to bring in vertex diffuse on base layer t->setColourOperation(LBO_REPLACE); // Second layer (lerp based on colour) t = pass->createTextureUnitState("terr_dirt-grass.jpg"); t->setColourOperationEx(LBX_BLEND_DIFFUSE_COLOUR); // third layer (lerp based on alpha) ManualObject* man = mSceneMgr->createManualObject("quad"); man->begin("testBlendDiffuseColour"); man->position(-100, 100, 0); man->textureCoord(0,0); man->colour(0, 0, 0); man->position(-100, -100, 0); man->textureCoord(0,1); man->colour(0.5, 0.5, 0.5); man->position(100, -100, 0); man->textureCoord(1,1); man->colour(1, 1, 1); man->position(100, 100, 0); man->textureCoord(1,0); man->colour(0.5, 0.5, 0.5); man->quad(0, 1, 2, 3); man->end(); mSceneMgr->getRootSceneNode()->attachObject(man); mCameraNode->setPosition(0,0,250); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_BlitSubTextures::PlayPen_BlitSubTextures() { mInfo["Title"] = "PlayPen_BlitSubTextures"; mInfo["Description"] = "Tests blitting textures onto on another."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_BlitSubTextures::setupContent() { TexturePtr src = TextureManager::getSingleton().load("ogrelogo.png", ASSETS_RESOURCE_GROUP); TexturePtr tex = TextureManager::getSingleton().createManual( "testblitdst", TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, 1024, 1024, 1, 0, src->getFormat()); Box srcBox; // This box should select from halfway through the head, to the // 'OG' part of the logo. srcBox.left = 376; srcBox.top = 379; srcBox.right = 376 + 224; srcBox.bottom = 379 + 278; srcBox.back = 1; srcBox.front = 0; // I was getting uninitialized memory written to the texture // buffer, so clear it explicitly. memset(tex->getBuffer()->lock( 0, tex->getBuffer()->getSizeInBytes(), HardwareBuffer::HBL_NORMAL), 0, tex->getBuffer()->getSizeInBytes()); tex->getBuffer()->unlock(); tex->getBuffer()->blit(src->getBuffer(), srcBox, srcBox); MaterialPtr mat = MaterialManager::getSingleton().create( "testblit", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->createTextureUnitState(tex->getName()); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Green); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_HardwareScaleBlit::PlayPen_HardwareScaleBlit() { mInfo["Title"] = "PlayPen_HardwareScaleBlit"; mInfo["Description"] = "Tests blitting texture with hardware scaling."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_HardwareScaleBlit::setupContent() { Image img; img.load("ogrelogo.png", ASSETS_RESOURCE_GROUP); TexturePtr tex = TextureManager::getSingleton().createManual( "testblitdst", TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, 64, 64, 1, 0, img.getFormat()); Box dstBox(0, 0, 64, 64); tex->getBuffer()->blitFromMemory(img.getPixelBox(), dstBox); MaterialPtr mat = MaterialManager::getSingleton().create( "testblit", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->createTextureUnitState(tex->getName()); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Green); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_Bsp::PlayPen_Bsp() { mInfo["Title"] = "PlayPen_Bsp"; mInfo["Description"] = "Tests BSP plugin."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_Bsp::setupContent() { // Load Quake3 locations from a file ConfigFile cf; cf.load(mFSLayer->getConfigFilePath("quakemap.cfg")); String quakePk3 = cf.getSetting("Archive"); String quakeLevel = cf.getSetting("Map"); //ResourceGroupManager::getSingleton().addResourceLocation(quakePk3, "Zip"); ResourceGroupManager::getSingleton().addResourceLocation( quakePk3, "Zip", ResourceGroupManager::getSingleton().getWorldResourceGroupName(), true); // Load world geometry //mSceneMgr->setWorldGeometry(quakeLevel); ResourceGroupManager& rgm = ResourceGroupManager::getSingleton(); rgm.linkWorldGeometryToResourceGroup(rgm.getWorldResourceGroupName(), quakeLevel, mSceneMgr); rgm.initialiseResourceGroup(rgm.getWorldResourceGroupName()); rgm.loadResourceGroup(rgm.getWorldResourceGroupName(), false); // modify camera for close work mCamera->setNearClipDistance(4); mCamera->setFarClipDistance(4000); // Also change position, and set Quake-type orientation // Get random player start point ViewPoint vp = mSceneMgr->getSuggestedViewpoint(true); mCameraNode->setPosition(vp.position); mCameraNode->pitch(Degree(90)); // Quake uses X/Y horizon, Z up mCameraNode->rotate(vp.orientation); // Don't yaw along variable axis, causes leaning mCameraNode->setFixedYawAxis(true, Vector3::UNIT_Z); mCameraNode->yaw(Ogre::Degree(-90.f)); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_BuildTangentOnAnimatedMesh::PlayPen_BuildTangentOnAnimatedMesh() { mInfo["Title"] = "PlayPen_BuildTangentOnAnimatedMesh"; mInfo["Description"] = "Tests building tangents for an animated mesh."; addScreenshotFrame(50); } //---------------------------------------------------------------------------- void PlayPen_BuildTangentOnAnimatedMesh::setupContent() { SceneNode* mTestNode[2]; Light* mLight = 0; //mSceneMgr->setShadowTextureSize(512); //mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_ADDITIVE); //mSceneMgr->setShadowFarDistance(1500); //mSceneMgr->setShadowColour(ColourValue(0.35, 0.35, 0.35)); //mSceneMgr->setShadowFarDistance(800); // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); mLight = mSceneMgr->createLight("MainLight"); /*/ // Directional test mLight->setType(Light::LT_DIRECTIONAL); Vector3 vec(-1,-1,0); vec.normalise(); mLight->setDirection(vec); /*/ // Point test mLight->setType(Light::LT_POINT); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 200, 0))->attachObject(mLight); //*/ MeshPtr pMesh = MeshManager::getSingleton().load("ninja.mesh", ASSETS_RESOURCE_GROUP/*, HardwareBuffer::HBU_DYNAMIC_WRITE_ONLY, HardwareBuffer::HBU_STATIC_WRITE_ONLY, true, true*/); //so we can still read it // Build tangent vectors, all our meshes use only 1 texture coordset unsigned short src, dest; if (!pMesh->suggestTangentVectorBuildParams(VES_TANGENT, src, dest)) { pMesh->buildTangentVectors(VES_TANGENT, src, dest); } Entity* pEnt = mSceneMgr->createEntity("Ninja", "ninja.mesh"); pEnt->getAnimationState("Walk")->setEnabled(true); mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mTestNode[1]->attachObject( pEnt ); mTestNode[1]->translate(-100,-100,0); Plane plane(Vector3::UNIT_Y, -100); MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt; pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); mCameraNode->setPosition(0,0,400); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ClearScene::PlayPen_ClearScene() { mInfo["Title"] = "PlayPen_ClearScene"; mInfo["Description"] = "Tests clearing a running scene."; addScreenshotFrame(25); } //---------------------------------------------------------------------------- bool PlayPen_ClearScene::isScreenshotFrame(int frame) { if(frame == 20) mSceneMgr->clearScene(); return VisualTest::isScreenshotFrame(frame); } //---------------------------------------------------------------------------- void PlayPen_ClearScene::setupContent() { mSceneMgr->setAmbientLight(ColourValue::White); // Define a floor plane mesh Plane p(Vector3::UNIT_Y, -200); MeshManager::getSingleton().createPlane("FloorPlane", TRANSIENT_RESOURCE_GROUP, p,200000,200000,20,20,true,1,50,50,Vector3::UNIT_Z); Entity* planeEnt; planeEnt = mSceneMgr->createEntity( "plane", "FloorPlane" ); planeEnt->setMaterialName("Examples/Rockwall"); mSceneMgr->getRootSceneNode()->attachObject(planeEnt); mCameraNode->setPosition(0,500,100); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_CompositorTechniqueSwitch::PlayPen_CompositorTechniqueSwitch() { mInfo["Title"] = "PlayPen_CompositorTechniqueSwitch"; mInfo["Description"] = "Tests switching compositor techniques rapidly."; addScreenshotFrame(15); } //---------------------------------------------------------------------------- void PlayPen_CompositorTechniqueSwitch::cleanupContent() { CompositorManager::getSingleton().removeCompositorChain(mViewport); } //---------------------------------------------------------------------------- bool PlayPen_CompositorTechniqueSwitch::frameStarted(const FrameEvent& evt) { mTimeUntilNextToggle -= evt.timeSinceLastFrame; if(mTimeUntilNextToggle <= 0.f) { ++mCompositorIndex; mCompositorIndex = mCompositorIndex % mCompositorSchemeList.size(); mCompositorToSwitch->setScheme(mCompositorSchemeList[mCompositorIndex]); mTimeUntilNextToggle = 0.1; } return true; } //---------------------------------------------------------------------------- void PlayPen_CompositorTechniqueSwitch::setupContent() { mTimeUntilNextToggle = 0.1f;// swap compositors every 10 frames CompositorManager& cmgr = CompositorManager::getSingleton(); CompositorPtr compositor = cmgr.create("testtechswitch", TRANSIENT_RESOURCE_GROUP); // technique 1 (Invert) CompositionTechnique* ctech1 = compositor->createTechnique(); CompositionTechnique::TextureDefinition* tdef = ctech1->createTextureDefinition("rt0"); tdef->formatList.push_back(PF_A8B8G8R8); tdef->width = tdef->height = 0; tdef->pooled = true; CompositionTargetPass* tpass = ctech1->createTargetPass(); tpass->setOutputName("rt0"); tpass->setInputMode(CompositionTargetPass::IM_PREVIOUS); CompositionTargetPass* tout = ctech1->getOutputTargetPass(); tout->setInputMode(CompositionTargetPass::IM_NONE); CompositionPass* pass = tout->createPass(CompositionPass::PT_RENDERQUAD); pass->setMaterialName("Ogre/Compositor/Invert"); pass->setInput(0, "rt0"); // technique 2 (Tiling) ctech1 = compositor->createTechnique(); ctech1->setSchemeName("Tiling"); tdef = ctech1->createTextureDefinition("rt0"); tdef->formatList.push_back(PF_A8B8G8R8); tdef->width = tdef->height = 0; tdef->pooled = true; tpass = ctech1->createTargetPass(); tpass->setOutputName("rt0"); tpass->setInputMode(CompositionTargetPass::IM_PREVIOUS); tout = ctech1->getOutputTargetPass(); tout->setInputMode(CompositionTargetPass::IM_NONE); pass = tout->createPass(CompositionPass::PT_RENDERQUAD); pass->setMaterialName("Ogre/Compositor/Tiling"); pass->setInput(0, "rt0"); compositor->load(); Entity* e = mSceneMgr->createEntity("1", "knot.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox", 1000); // enable compositor (should pick first technique) Viewport* vp = mWindow->getViewport(0); mCompositorToSwitch = cmgr.addCompositor(vp, compositor->getName()); mCompositorSchemeList.push_back(""); mCompositorSchemeList.push_back("Tiling"); cmgr.setCompositorEnabled(vp, compositor->getName(), true); mCameraNode->setPosition(0, 0, -300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); mCompositorIndex = 0; } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_CompositorTextureShadows::PlayPen_CompositorTextureShadows() { mInfo["Title"] = "PlayPen_CompositorTextureShadows"; mInfo["Description"] = "Tests applying a compositor to a texture shadow manager."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_CompositorTextureShadows::cleanupContent() { TexturePtr shadowTex = mSceneMgr->getShadowTexture(0); RenderTarget* shadowRtt = shadowTex->getBuffer()->getRenderTarget(); Viewport* vp = shadowRtt->getViewport(0); CompositorManager::getSingleton().removeCompositorChain(vp); clearDebugTextureOverlays(); } //---------------------------------------------------------------------------- void PlayPen_CompositorTextureShadows::setupContent() { SceneNode* mTestNode[10]; mSceneMgr->setShadowTextureSize(512); mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); mSceneMgr->setShadowFarDistance(1500); mSceneMgr->setShadowColour(ColourValue(0.35, 0.35, 0.35)); //mSceneMgr->setShadowFarDistance(800); // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); Light* mLight = mSceneMgr->createLight("MainLight"); /* // Directional test mLight->setType(Light::LT_DIRECTIONAL); Vector3 vec(-1,-1,0); vec.normalise(); mLight->setDirection(vec); */ // Spotlight test mLight->setType(Light::LT_SPOTLIGHT); mLight->setDiffuseColour(1.0, 1.0, 0.8); mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mTestNode[0]->setPosition(800,600,0); mTestNode[0]->lookAt(Vector3(0,0,0), Node::TS_WORLD); mTestNode[0]->attachObject(mLight); mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); Entity* pEnt; pEnt = mSceneMgr->createEntity( "1", "robot.mesh" ); //pEnt->setRenderingDistance(100); AnimationState* mAnimState = pEnt->getAnimationState("Walk"); mAnimState->setEnabled(true); mAnimStateList.push_back(mAnimState); //pEnt->setMaterialName("2 - Default"); mTestNode[1]->attachObject( pEnt ); mTestNode[1]->translate(0,-100,0); pEnt = mSceneMgr->createEntity( "3", "knot.mesh" ); mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200, 0, -200)); mTestNode[2]->attachObject( pEnt ); // Transparent object (can force cast shadows) pEnt = mSceneMgr->createEntity( "3.5", "knot.mesh" ); MaterialPtr tmat = MaterialManager::getSingleton().create("TestAlphaTransparency", TRANSIENT_RESOURCE_GROUP); tmat->setTransparencyCastsShadows(true); Pass* tpass = tmat->getTechnique(0)->getPass(0); tpass->setAlphaRejectSettings(CMPF_GREATER, 150); tpass->setSceneBlending(SBT_TRANSPARENT_ALPHA); tpass->createTextureUnitState("gras_02.png"); tpass->setCullingMode(CULL_NONE); pEnt->setMaterialName("TestAlphaTransparency"); mTestNode[3] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(350, 0, -200)); mTestNode[3]->attachObject( pEnt ); pEnt = mSceneMgr->createEntity( "4", "knot.mesh" ); mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 200)); mTestNode[2]->attachObject( pEnt ); mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 100; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt; pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); // Set up a debug panel to display the shadow addTextureShadowDebugOverlay(1, mSceneMgr); ParticleSystem* pSys2 = mSceneMgr->createParticleSystem("smoke", "Examples/Smoke"); mTestNode[4] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-300, -100, 200)); mTestNode[4]->attachObject(pSys2); TexturePtr shadowTex = mSceneMgr->getShadowTexture(0); RenderTarget* shadowRtt = shadowTex->getBuffer()->getRenderTarget(); Viewport* vp = shadowRtt->getViewport(0); // This originally used gaussian blur, but since compositor logic stuff has changed since the test // was originally written and I'm not especially familiar with it, I just swapped to a random // compositor (it still tests the required functionality) CompositorManager::getSingleton().addCompositor(vp, "Laplace"); CompositorManager::getSingleton().setCompositorEnabled( vp, "Laplace", true); mCameraNode->setPosition(400, 250, 350); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_CubeDDS::PlayPen_CubeDDS() { mInfo["Title"] = "PlayPen_CubeDDS"; mInfo["Description"] = "Tests DDS cubemaps."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_CubeDDS::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); MaterialPtr mat = MaterialManager::getSingleton().create("testcube", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); TextureUnitState* t = p->createTextureUnitState(); t->setTextureName("grace_cube.dds", TEX_TYPE_CUBE_MAP); t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); t->setEnvironmentMap(true, TextureUnitState::ENV_REFLECTION); Entity* e = mSceneMgr->createEntity("1", "sphere.mesh"); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mCameraNode->setPosition(300,0,0); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_CustomProjectionMatrix::PlayPen_CustomProjectionMatrix() { mInfo["Title"] = "PlayPen_CustomProjectionMatrix"; mInfo["Description"] = "Tests custom projection matrix."; } //---------------------------------------------------------------------------- void PlayPen_CustomProjectionMatrix::setupContent() { PlayPen_LotsAndLotsOfEntities::setupContent(); Matrix4 mat = mCamera->getProjectionMatrix(); mCamera->setCustomProjectionMatrix(true, mat); mat = mCamera->getProjectionMatrix(); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_DepthBias::PlayPen_DepthBias() { mInfo["Title"] = "PlayPen_DepthBias"; mInfo["Description"] = "Tests depth biasing."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_DepthBias::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); mSceneMgr->setAmbientLight(ColourValue::White); MaterialPtr mat = MaterialManager::getSingleton().create("mat1", TRANSIENT_RESOURCE_GROUP); // mat->setSceneBlending(SBT_TRANSPARENT_ALPHA); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->createTextureUnitState("BumpyMetal.jpg"); // t->setColourOperation(LBO_ALPHA_BLEND); const String meshName("cube.mesh"); Entity* entity = mSceneMgr->createEntity("base", meshName); entity->setMaterialName("mat1"); mSceneMgr->getRootSceneNode()->attachObject(entity); entity = mSceneMgr->createEntity("base2", meshName); entity->setMaterialName("Examples/SphereMappedRustySteel"); SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); n->setPosition(-30, 0, 0); n->yaw(Degree(45)); n->attachObject(entity); // for (size_t i = 0; i <= 6; ++i) for (size_t i = 0; i <= 3; ++i) { String name("decal"); name += StringConverter::toString(i); MaterialPtr pMat = MaterialManager::getSingleton().create(name, TRANSIENT_RESOURCE_GROUP); p = pMat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setAlphaRejectSettings(CMPF_GREATER_EQUAL, 128); p->setSceneBlending(SBT_TRANSPARENT_ALPHA); p->setDepthBias(i); p->createTextureUnitState(name + ".png"); // t->setColourOperation(LBO_ALPHA_BLEND); entity = mSceneMgr->createEntity(name, meshName); entity->setMaterialName(name); mSceneMgr->getRootSceneNode()->attachObject(entity); } mCameraNode->setPosition(0,0,200); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_DepthShadowMap::PlayPen_DepthShadowMap() { mInfo["Title"] = "PlayPen_DepthShadowMap"; mInfo["Description"] = "Tests depth shadowmapping."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_DepthShadowMap::setupContent() { mSceneMgr->setShadowTextureCount(1); mSceneMgr->setShadowTextureConfig(0, 1024, 1024, PF_FLOAT32_R); mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED); mSceneMgr->setShadowCasterRenderBackFaces(false); mSceneMgr->setShadowFarDistance(500); #ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM // Make this viewport work with shader generator scheme. mViewport->setMaterialScheme(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); RTShader::ShaderGenerator& rtShaderGen = RTShader::ShaderGenerator::getSingleton(); RTShader::RenderState* schemRenderState = rtShaderGen.getRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); auto subRenderState = rtShaderGen.createSubRenderState<RTShader::IntegratedPSSM3>(); schemRenderState->addTemplateSubRenderState(subRenderState); #endif mSceneMgr->setShadowTextureCasterMaterial( MaterialManager::getSingleton().getByName("PSSM/shadow_caster", "General")); // ground plane movablePlane.reset(new MovablePlane(Vector3::UNIT_Y, 0.f)); mSceneMgr->setShadowCameraSetup(PlaneOptimalShadowCameraSetup::create(movablePlane.get())); // Single light Light* l = mSceneMgr->createLight("l1"); l->setType(Light::LT_POINT); Vector3 pos(-150, 100, -50); mSceneMgr->getRootSceneNode()->createChildSceneNode(pos)->attachObject(l); MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, *movablePlane, 500,500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt; pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("Examples/Rockwall"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); // box ManualObject* man = mSceneMgr->createManualObject("box"); Real boxsize = 50; Real boxsizehalf = boxsize / 2.0; man->begin("BaseWhite"); man->position(-boxsizehalf, 0, boxsizehalf); man->normal(0, 0, 0); man->position(boxsizehalf, 0, boxsizehalf); man->normal(0, 0, 0); man->position(boxsizehalf, 0, -boxsizehalf); man->normal(0, 0, 0); man->position(-boxsizehalf, 0, -boxsizehalf); man->normal(0, 0, 0); man->position(-boxsizehalf, boxsize, boxsizehalf); man->normal(0, 0, 0); man->position(boxsizehalf, boxsize, boxsizehalf); man->normal(0, 0, 0); man->position(boxsizehalf, boxsize, -boxsizehalf); man->normal(0, 0, 0); man->position(-boxsizehalf, boxsize, -boxsizehalf); man->normal(0, 0, 0); man->quad(3, 2, 1, 0); man->quad(4, 5, 6, 7); man->quad(0, 1, 5, 4); man->quad(1, 2, 6, 5); man->quad(2, 3, 7, 6); man->quad(3, 0, 4, 7); man->end(); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(man); mCameraNode->setPosition(150, 100, 150); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); // Create RTT //TexturePtr rtt = TextureManager::getSingleton().createManual("rtt1", TRANSIENT_RESOURCE_GROUP, // TEX_TYPE_2D, 1024, 1024, 1, 0, PF_FLOAT32_R); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- Entity* pTexListenerPlaneEnt = 0;// yucky global... Camera* theCam = 0; class RefractionTextureListener : public RenderTargetListener { public: void preRenderTargetUpdate(const RenderTargetEvent& evt) { pTexListenerPlaneEnt->setVisible(false); } void postRenderTargetUpdate(const RenderTargetEvent& evt) { pTexListenerPlaneEnt->setVisible(true); } }; class ReflectionTextureListener : public RenderTargetListener { public: void preRenderTargetUpdate(const RenderTargetEvent& evt) { static Plane reflectPlane(Vector3::UNIT_Y, -100); pTexListenerPlaneEnt->setVisible(false); theCam->enableReflection(reflectPlane); } void postRenderTargetUpdate(const RenderTargetEvent& evt) { pTexListenerPlaneEnt->setVisible(true); theCam->disableReflection(); } }; PlayPen_Distortion::PlayPen_Distortion() { mInfo["Title"] = "PlayPen_Distortion"; mInfo["Description"] = "Tests distortion."; addScreenshotFrame(15); mRefractionListener = new RefractionTextureListener(); mReflectionListener = new ReflectionTextureListener(); } //---------------------------------------------------------------------------- PlayPen_Distortion::~PlayPen_Distortion() { delete mRefractionListener; delete mReflectionListener; } //---------------------------------------------------------------------------- void PlayPen_Distortion::cleanupContent() { TexturePtr rttTex = TextureManager::getSingleton().getByName("Refraction", TRANSIENT_RESOURCE_GROUP); rttTex->getBuffer()->getRenderTarget()->removeAllListeners(); rttTex->unload(); rttTex = TextureManager::getSingleton().getByName("Reflection", TRANSIENT_RESOURCE_GROUP); rttTex->getBuffer()->getRenderTarget()->removeAllListeners(); rttTex->unload(); } //---------------------------------------------------------------------------- void PlayPen_Distortion::setupContent() { theCam = mCamera; // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); // Create a point light OrientedLightPtr l = mSceneMgr->createLight("MainLight"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(-Vector3::UNIT_Y); Entity* pEnt; TexturePtr rttTex = TextureManager::getSingleton().createManual("Refraction", TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, 512, 512, 1, 0, PF_R8G8B8, TU_RENDERTARGET); { Viewport *v = rttTex->getBuffer()->getRenderTarget()->addViewport( mCamera ); MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction"); mat->getTechnique(0)->getPass(0)->getTextureUnitState(2)->setTextureName("Refraction"); v->setOverlaysEnabled(false); rttTex->getBuffer()->getRenderTarget()->addListener(mRefractionListener); } rttTex = TextureManager::getSingleton().createManual("Reflection", TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, 512, 512, 1, 0, PF_R8G8B8, TU_RENDERTARGET); { Viewport *v = rttTex->getBuffer()->getRenderTarget()->addViewport( mCamera ); MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/FresnelReflectionRefraction"); mat->getTechnique(0)->getPass(0)->getTextureUnitState(1)->setTextureName("Reflection"); v->setOverlaysEnabled(false); rttTex->getBuffer()->getRenderTarget()->addListener(mReflectionListener); } // Define a floor plane mesh Plane p(Vector3::UNIT_Y, -100); MeshManager::getSingleton().createPlane("WallPlane", TRANSIENT_RESOURCE_GROUP, p,1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); pTexListenerPlaneEnt = mSceneMgr->createEntity( "5", "WallPlane" ); pTexListenerPlaneEnt->setMaterialName("Examples/FresnelReflectionRefraction"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pTexListenerPlaneEnt); mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); for (int i = 0; i < 10; ++i) { pEnt = mSceneMgr->createEntity( "ogre" + StringConverter::toString(i), "ogrehead.mesh" ); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(i*100 - 500, -75, 0))->attachObject(pEnt); pEnt = mSceneMgr->createEntity( "knot" + StringConverter::toString(i), "knot.mesh" ); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(i*100 - 500, 140, 0))->attachObject(pEnt); } mCameraNode->setPosition(100,200,300); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_Dxt1Alpha::PlayPen_Dxt1Alpha() { mInfo["Title"] = "PlayPen_Dxt1Alpha"; mInfo["Description"] = "Tests dxt1 loading with alpha."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_Dxt1Alpha::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); MaterialPtr mat = MaterialManager::getSingleton().create("testdxt", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setSceneBlending(SBT_TRANSPARENT_ALPHA); p->setAlphaRejectSettings(CMPF_GREATER, 128); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->createTextureUnitState("gras_02_dxt1.dds"); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- PlayPen_AlphaTex::PlayPen_AlphaTex() { mInfo["Title"] = "PlayPen_AlphaTex"; mInfo["Description"] = "Tests alpha only texture."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_AlphaTex::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); TexturePtr tex = TextureManager::getSingleton().load("terrain.png", TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, 0, 1.0f, PF_A8); MaterialPtr mat = MaterialManager::getSingleton().create("test", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->setSceneBlending(SBT_TRANSPARENT_ALPHA); p->createTextureUnitState()->setTexture(tex); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mCameraNode->setPosition(0,0,-300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Green); } //---------------------------------------------------------------------------- PlayPen_Dxt1::PlayPen_Dxt1() { mInfo["Title"] = "PlayPen_Dxt1"; mInfo["Description"] = "Tests dxt1 loading."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_Dxt1::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); MaterialPtr mat = MaterialManager::getSingleton().create("testdxt", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->createTextureUnitState("BumpyMetal_dxt1.dds"); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mCameraNode->setPosition(0,0,-300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_Dxt1FromMemory::PlayPen_Dxt1FromMemory() { mInfo["Title"] = "PlayPen_Dxt1FromMemory"; mInfo["Description"] = "Tests dxt1 loading from memory."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_Dxt1FromMemory::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); DataStreamPtr stream = ResourceGroupManager::getSingleton().openResource("BumpyMetal_dxt1.dds", "Tests"); // manually load into image Image img; img.load(stream, "dds"); TextureManager::getSingleton().loadImage("testdxtfrommem", TRANSIENT_RESOURCE_GROUP, img); MaterialPtr mat = MaterialManager::getSingleton().create("testdxt", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->createTextureUnitState("testdxtfrommem"); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mCameraNode->setPosition(0,0,-300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_Dxt3::PlayPen_Dxt3() { mInfo["Title"] = "PlayPen_Dxt3"; mInfo["Description"] = "Tests dxt3 loading."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_Dxt3::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); MaterialPtr mat = MaterialManager::getSingleton().create("testdxt", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->setSceneBlending(SBT_TRANSPARENT_ALPHA); p->createTextureUnitState("ogreborderUp_dxt3.dds"); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_Dxt3FromMemory::PlayPen_Dxt3FromMemory() { mInfo["Title"] = "PlayPen_Dxt3FromMemory"; mInfo["Description"] = "Tests dxt3 loading from memory."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_Dxt3FromMemory::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); DataStreamPtr stream = ResourceGroupManager::getSingleton().openResource("ogreborderUp_dxt3.dds", "Tests"); // manually load into image Image img; img.load(stream, "dds"); TextureManager::getSingleton().loadImage("testdxtfrommem", TRANSIENT_RESOURCE_GROUP, img); MaterialPtr mat = MaterialManager::getSingleton().create("testdxt", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->setSceneBlending(SBT_TRANSPARENT_ALPHA); p->setAlphaRejectSettings(CMPF_GREATER, 128); mat->setReceiveShadows(false); TextureUnitState* t = p->createTextureUnitState("testdxtfrommem"); t->setTextureScale(0.5,0.5); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); n->setPosition(-50, 0, 35); n->yaw(Degree(90)); n->attachObject(e); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_Dxt5::PlayPen_Dxt5() { mInfo["Title"] = "PlayPen_Dxt5"; mInfo["Description"] = "Tests dxt5 loading."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_Dxt5::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); MaterialPtr mat = MaterialManager::getSingleton().create("testdxt", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->setSceneBlending(SBT_TRANSPARENT_ALPHA); p->createTextureUnitState("ogreborderUp_dxt5.dds"); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_FarFromOrigin::PlayPen_FarFromOrigin() { mInfo["Title"] = "PlayPen_FarFromOrigin"; mInfo["Description"] = "Tests rending far from the origin."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_FarFromOrigin::cleanupContent() { //clearDebugTextureOverlays(); } void PlayPen_FarFromOrigin::setupContent() { SceneNode* mTestNode[5]; mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); mSceneMgr->setShadowTextureSettings(1024, 2); Vector3 offset(100000, 0, 100000); //Vector3 offset(0, 0, 0); mSceneMgr->setAmbientLight(ColourValue(0.1, 0.1, 0.1)); // Directional test { OrientedLightPtr mLight = mSceneMgr->createLight("MainLight"); mLight->setType(Light::LT_DIRECTIONAL); Vector3 vec(-1, -1, 0); vec.normalise(); mLight->setDirection(vec); mLight->setDiffuseColour(0.5, 0.5, 1.0); } // Spotlight test auto mLight = mSceneMgr->createLight("SpotLight"); mLight->setType(Light::LT_SPOTLIGHT); mLight->setAttenuation(10000, 1, 0, 0); mLight->setDiffuseColour(1.0, 1.0, 0.5); mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mTestNode[0]->setPosition(offset + Vector3(-400,300,1000)); mTestNode[0]->lookAt(offset, Node::TS_WORLD); mTestNode[0]->attachObject(mLight); mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mTestNode[1]->setPosition(offset); Entity* pEnt; pEnt = mSceneMgr->createEntity( "1", "knot.mesh" ); mTestNode[1]->attachObject( pEnt ); mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 100; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 2500,2500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt; pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode(offset)->attachObject(pPlaneEnt); ParticleSystem* pSys2 = mSceneMgr->createParticleSystem("smoke", "Examples/Smoke"); mTestNode[4] = mSceneMgr->getRootSceneNode()->createChildSceneNode(offset + Vector3(-300, -100, 200)); mTestNode[4]->attachObject(pSys2); mCameraNode->setPosition(offset + Vector3(0, 1000, 500)); mCameraNode->lookAt(offset, Node::TS_PARENT); mCamera->setFarClipDistance(10000); mSceneMgr->setCameraRelativeRendering(true); mSceneMgr->setShadowCameraSetup(FocusedShadowCameraSetup::create()); //addTextureShadowDebugOverlay(1, mSceneMgr); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_Float128DDS::PlayPen_Float128DDS() { mInfo["Title"] = "PlayPen_Float128DDS"; mInfo["Description"] = "Tests 128bit floating point dds textures."; addScreenshotFrame(250); } //---------------------------------------------------------------------------- void PlayPen_Float128DDS::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); MaterialPtr mat = MaterialManager::getSingleton().create("testdds", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->setSceneBlending(SBT_TRANSPARENT_ALPHA); p->createTextureUnitState("ogreborderUp_float128.dds"); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_Float16DDS::PlayPen_Float16DDS() { mInfo["Title"] = "PlayPen_Float16DDS"; mInfo["Description"] = "Tests 16bit floating point dds textures."; addScreenshotFrame(250); } //---------------------------------------------------------------------------- void PlayPen_Float16DDS::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); MaterialPtr mat = MaterialManager::getSingleton().create("testdds", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->createTextureUnitState("BumpyMetal_float16.dds"); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_Float32DDS::PlayPen_Float32DDS() { mInfo["Title"] = "PlayPen_Float32DDS"; mInfo["Description"] = "Tests 32bit floating point dds textures."; addScreenshotFrame(250); } //---------------------------------------------------------------------------- void PlayPen_Float32DDS::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); MaterialPtr mat = MaterialManager::getSingleton().create("testdds", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->createTextureUnitState("BumpyMetal_float32.dds"); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_Float64DDS::PlayPen_Float64DDS() { mInfo["Title"] = "PlayPen_Float64DDS"; mInfo["Description"] = "Tests 64bit floating point dds textures."; addScreenshotFrame(250); } //---------------------------------------------------------------------------- void PlayPen_Float64DDS::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); MaterialPtr mat = MaterialManager::getSingleton().create("testdds", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); p->setSceneBlending(SBT_TRANSPARENT_ALPHA); p->createTextureUnitState("ogreborderUp_float64.dds"); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_GeometryShaders::PlayPen_GeometryShaders() { mInfo["Title"] = "PlayPen_GeometryShaders"; mInfo["Description"] = "Tests geometry shaders."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_GeometryShaders::testCapabilities(const Ogre::RenderSystemCapabilities* caps) { if(!caps->hasCapability(RSC_GEOMETRY_PROGRAM)) throw Ogre::Exception(999, "Video card doesn't support geometry shaders.", "testCapabilities"); } //---------------------------------------------------------------------------- void PlayPen_GeometryShaders::setupContent() { // Check capabilities const RenderSystemCapabilities* caps = Root::getSingleton().getRenderSystem()->getCapabilities(); if (!caps->hasCapability(RSC_GEOMETRY_PROGRAM)) { OGRE_EXCEPT(Ogre::Exception::ERR_NOT_IMPLEMENTED, "Your card does not support geometry programs, so cannot " "run this demo. Sorry!", "GeometryShading::createScene"); } int maxOutputVertices = caps->getGeometryProgramNumOutputVertices(); Ogre::LogManager::getSingleton().getDefaultLog()->stream() << "Num output vertices per geometry shader run : " << maxOutputVertices; Entity *ent = mSceneMgr->createEntity("head", "ogrehead.mesh"); // Set all of the material's sub entities to use the new material for (unsigned int i = 0; i < ent->getNumSubEntities(); i++) { ent->getSubEntity(i)->setMaterialName("Ogre/GPTest/Swizzle"); } // Add entity to the root scene node mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Green); mCameraNode->setPosition(20, 0, 100); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_InfiniteAAB::PlayPen_InfiniteAAB() { mInfo["Title"] = "PlayPen_InfiniteAAB"; mInfo["Description"] = "Tests finite/infinite AABBs."; addScreenshotFrame(15); } //---------------------------------------------------------------------------- void PlayPen_InfiniteAAB::setupContent() { // When using the BspSceneManager mSceneMgr->setWorldGeometry("ogretestmap.bsp"); // When using the TerrainSceneManager //mSceneMgr->setWorldGeometry("terrain.cfg"); AxisAlignedBox b1; // null assert( b1.isNull() ); AxisAlignedBox b2(Vector3::ZERO, 5.0 * Vector3::UNIT_SCALE); // finite assert( b2.isFinite() ); AxisAlignedBox b3; b3.setInfinite(); assert( b3.isInfinite() ); { // Create background material MaterialPtr material = MaterialManager::getSingleton().create("Background", "General"); material->getTechnique(0)->getPass(0)->createTextureUnitState("rockwall.tga"); material->getTechnique(0)->getPass(0)->setDepthCheckEnabled(false); material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false); material->getTechnique(0)->getPass(0)->setLightingEnabled(false); // Create left background rectangle // NOTE: Uses finite aab Rectangle2D* rect1 = new Rectangle2D(true); rect1->setCorners(-0.5, 0.1, -0.1, -0.1); // Hacky, set small bounding box, to show problem rect1->setBoundingBox(AxisAlignedBox(-10.0*Vector3::UNIT_SCALE, 10.0*Vector3::UNIT_SCALE)); rect1->setMaterial(material); rect1->setRenderQueueGroup(RENDER_QUEUE_OVERLAY - 1); SceneNode* node = mSceneMgr->getRootSceneNode()->createChildSceneNode("Background1"); node->attachObject(rect1); // Create right background rectangle // NOTE: Uses infinite aab Rectangle2D* rect2 = new Rectangle2D(true); rect2->setCorners(0.1, 0.1, 0.5, -0.1); AxisAlignedBox aabInf; aabInf.setInfinite(); rect2->setBoundingBox(aabInf); rect2->setMaterial(material); rect2->setRenderQueueGroup(RENDER_QUEUE_OVERLAY - 1); node = mSceneMgr->getRootSceneNode()->createChildSceneNode("Background2"); node->attachObject(rect2); // Create a manual object for 2D ManualObject* manual = mSceneMgr->createManualObject("manual"); manual->setUseIdentityProjection(true); manual->setUseIdentityView(true); manual->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_STRIP); manual->position(-0.2, -0.2, 0.0); manual->position( 0.2, -0.2, 0.0); manual->position( 0.2, 0.2, 0.0); manual->position(-0.2, 0.2, 0.0); manual->index(0); manual->index(1); manual->index(2); manual->index(3); manual->index(0); manual->end(); manual->setBoundingBox(aabInf); // Use infinite aab to always stay visible rect2->setRenderQueueGroup(RENDER_QUEUE_OVERLAY - 1); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(manual); } mSceneMgr->showBoundingBoxes(true); Entity* ent = mSceneMgr->createEntity("test", "ogrehead.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode( "test", 50.0 * Vector3::UNIT_X)->attachObject(ent); mCameraNode->setPosition(100,50,350); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_LightClipPlanes::PlayPen_LightClipPlanes() { mInfo["Title"] = "PlayPen_LightClipPlanes"; mInfo["Description"] = "Tests light clipping planes."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_LightClipPlanes::setupContent() { mSceneMgr->setAmbientLight(ColourValue::White); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 0; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 4500,4500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("Examples/GrassFloor"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(150,0,100))->attachObject(pPlaneEnt); Real lightRange = 1000; Real spotWidth = 300; ManualObject* debugSphere = mSceneMgr->createManualObject("debugSphere"); debugSphere->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_STRIP); for (int i = 0; i <= 20; ++i) { Vector3 basePos(spotWidth, 0, 0); Quaternion quat; quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Y); basePos = quat * basePos; debugSphere->position(basePos); } debugSphere->end(); Light* l = mSceneMgr->createLight("l1"); l->setAttenuation(lightRange, 1, 0, 0); SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100,0,0)); n->attachObject(debugSphere); /* SPOT LIGHT */ // match spot width to groud Real spotHeight = lightRange * 0.5; n = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100,spotHeight,0)); l->setType(Light::LT_SPOTLIGHT); Radian spotAngle = Math::ATan(spotWidth / spotHeight) * 2; l->setSpotlightOuterAngle(spotAngle); l->setSpotlightInnerAngle(spotAngle * 0.75); Vector3 dir(0, -1, 0); dir.normalise(); n->setDirection(dir); /* END SPOT LIGHT */ n->attachObject(l); // Modify the plane material so that it clips to the light // Normally you'd only clip a secondary pass but this is engineered so you // can actually see the scissoring effect MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/GrassFloor"); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightClipPlanesEnabled(true); //if (scissortoo) //p->setLightScissoringEnabled(true); mCameraNode->setPosition(0, 200, 300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_LightClipPlanesMoreLights::PlayPen_LightClipPlanesMoreLights() { mInfo["Title"] = "PlayPen_LightClipPlanesMoreLights"; mInfo["Description"] = "Tests light clip planes with more lights."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_LightClipPlanesMoreLights::setupContent() { mSceneMgr->setAmbientLight(ColourValue(0.3, 0.25, 0.2, 0)); mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE); mSceneMgr->setShadowTextureCount(3); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 0; MeshManager::getSingleton().createPlane( "Myplane", TRANSIENT_RESOURCE_GROUP, plane, 4500, 4500, 100, 100, true, 1, 5, 5, Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("Examples/GrassFloor"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); Real lightRange = 1000; Real spotWidth = 300; int numLights = 8; Real xoff = -numLights * spotWidth * 0.5; for (int i = 0; i < numLights; ++i) { Light* l = mSceneMgr->createLight("l" + StringConverter::toString(i)); l->setAttenuation(lightRange, 1, 0, 0); /* SPOT LIGHT */ // match spot width to groud Real spotHeight = lightRange * 0.5; SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3((spotWidth+50)*i + xoff,spotHeight,0)); l->setType(Light::LT_SPOTLIGHT); Radian spotAngle = Math::ATan(spotWidth / spotHeight) * 2; l->setSpotlightOuterAngle(spotAngle); l->setSpotlightInnerAngle(spotAngle * 0.75); Vector3 dir(0, -1, 0); dir.normalise(); n->setDirection(dir, Node::TS_WORLD); /* END SPOT LIGHT */ n->attachObject(l); Entity* e = mSceneMgr->createEntity("e" + StringConverter::toString(i), "robot.mesh"); SceneNode* en = n->createChildSceneNode(Vector3(0, -200, 0)); en->attachObject(e); } // Modify the plane material so that it clips to the light on the second pass, post ambient MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/GrassFloor"); Pass* p = mat->getTechnique(0)->getPass(0); String texname = p->getTextureUnitState(0)->getTextureName(); p->removeAllTextureUnitStates(); p->setIlluminationStage(IS_AMBIENT); p->setDiffuse(ColourValue::Black); p = mat->getTechnique(0)->createPass(); p->setIlluminationStage(IS_PER_LIGHT); p->setIteratePerLight(true, true); //TODO Shouldn't the case below also be tested? // p->setIteratePerLight(true, false); p->setAmbient(ColourValue::Black); p->setLightClipPlanesEnabled(true); p->setSceneBlending(SBT_ADD); //if (scissortoo) p->setLightScissoringEnabled(true); p = mat->getTechnique(0)->createPass(); p->setIlluminationStage(IS_DECAL); p->createTextureUnitState(texname); p->setLightingEnabled(false); p->setSceneBlending(SBT_MODULATE); mCameraNode->setPosition(0, 200, 300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_LightScissoring::PlayPen_LightScissoring() { mInfo["Title"] = "PlayPen_LightScissoring"; mInfo["Description"] = "Tests light scissoring."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_LightScissoring::setupContent() { mSceneMgr->setAmbientLight(ColourValue::White); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 0; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 4500,4500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("Examples/GrassFloor"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); Real lightRange = 100; ManualObject* debugSphere = mSceneMgr->createManualObject("debugSphere"); debugSphere->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_STRIP); for (int i = 0; i <= 20; ++i) { Vector3 basePos(lightRange, 0, 0); Quaternion quat; quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Y); basePos = quat * basePos; debugSphere->position(basePos); } for (int i = 0; i <= 20; ++i) { Vector3 basePos(lightRange, 0, 0); Quaternion quat; quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Z); basePos = quat * basePos; debugSphere->position(basePos); } debugSphere->end(); ManualObject* debugSphere2 = mSceneMgr->createManualObject("debugSphere2"); debugSphere2->begin("BaseWhiteNoLighting", RenderOperation::OT_LINE_STRIP); for (int i = 0; i <= 20; ++i) { Vector3 basePos(lightRange, 0, 0); Quaternion quat; quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Y); basePos = quat * basePos; debugSphere2->position(basePos); } for (int i = 0; i <= 20; ++i) { Vector3 basePos(lightRange, 0, 0); Quaternion quat; quat.FromAngleAxis(Radian(((float)i/(float)20)*Math::TWO_PI), Vector3::UNIT_Z); basePos = quat * basePos; debugSphere2->position(basePos); } debugSphere2->end(); Light* l = mSceneMgr->createLight("l1"); l->setAttenuation(lightRange, 1, 0, 0); SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,95,0)); n->attachObject(debugSphere); n->attachObject(l); Light* l2 = mSceneMgr->createLight("l2"); l2->setAttenuation(lightRange, 1, 0, 0); SceneNode* n2 = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100,50,0)); n2->attachObject(debugSphere2); n2->attachObject(l2); // Modify the plane material so that it clips to the light // Normally you'd only clip a secondary pass but this is engineered so you // can actually see the scissoring effect MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/GrassFloor"); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightScissoringEnabled(true); //if (cliptoo) p->setLightClipPlanesEnabled(true); mCameraNode->setPosition(0, 200, 300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_LiSPSM::PlayPen_LiSPSM() { mInfo["Title"] = "PlayPen_LiSPSM"; mInfo["Description"] = "Tests light-space shadow mapping camera setup."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_LiSPSM::cleanupContent() { clearDebugTextureOverlays(); } //---------------------------------------------------------------------------- void PlayPen_LiSPSM::setupContent() { SceneNode* mTestNode[10]; mSceneMgr->setShadowTextureSize(1024); mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); //FocusedShadowCameraSetup* lispsmSetup = new FocusedShadowCameraSetup(); LiSPSMShadowCameraSetup* lispsmSetup = new LiSPSMShadowCameraSetup(); lispsmSetup->setOptimalAdjustFactor(2); mSceneMgr->setShadowCameraSetup(ShadowCameraSetupPtr(lispsmSetup)); mSceneMgr->setShadowFarDistance(3000); mSceneMgr->setShadowColour(ColourValue(0.35, 0.35, 0.35)); mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); OrientedLightPtr mLight = mSceneMgr->createLight("MainLight"); mLight->setType(Light::LT_DIRECTIONAL); Vector3 vec(-1,-1,0); vec.normalise(); mLight->setDirection(vec); mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); Entity* pEnt; pEnt = mSceneMgr->createEntity( "1", "robot.mesh" ); //pEnt->setRenderingDistance(100); AnimationState* mAnimState = pEnt->getAnimationState("Walk"); mAnimState->setEnabled(true); mAnimStateList.push_back(mAnimState); //pEnt->setMaterialName("2 - Default"); mTestNode[1]->attachObject( pEnt ); mTestNode[1]->translate(0,-100,0); pEnt = mSceneMgr->createEntity( "3", "knot.mesh" ); mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200, 0, -200)); mTestNode[2]->attachObject( pEnt ); createRandomEntityClones(pEnt, 20, Vector3(-1000,0,-1000), Vector3(1000,0,1000), mSceneMgr); // Transparent object (can force cast shadows) pEnt = mSceneMgr->createEntity( "3.5", "knot.mesh" ); MaterialPtr tmat = MaterialManager::getSingleton().create( "TestAlphaTransparency", TRANSIENT_RESOURCE_GROUP); tmat->setTransparencyCastsShadows(true); Pass* tpass = tmat->getTechnique(0)->getPass(0); tpass->setAlphaRejectSettings(CMPF_GREATER, 150); tpass->setSceneBlending(SBT_TRANSPARENT_ALPHA); tpass->createTextureUnitState("gras_02.png"); tpass->setCullingMode(CULL_NONE); pEnt->setMaterialName("TestAlphaTransparency"); mTestNode[3] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(350, 0, -200)); mTestNode[3]->attachObject( pEnt ); pEnt = mSceneMgr->createEntity( "4", "knot.mesh" ); mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 200)); mTestNode[2]->attachObject( pEnt ); mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); MovablePlane movablePlane = MovablePlane(Vector3::UNIT_Y, 100); MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, movablePlane, 2500,2500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt; pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); addTextureShadowDebugOverlay(1, mSceneMgr); mCameraNode->setPosition(0, 1000, 500); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); mCamera->setFarClipDistance(10000); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- static void createRandomEntityClones(Entity* ent, size_t cloneCount, const Vector3& min, const Vector3& max, SceneManager* mgr) { Entity *cloneEnt; for (size_t n = 0; n < cloneCount; ++n) { // Create a new node under the root. SceneNode* node = mgr->createSceneNode(); // Random translate. Vector3 nodePos; nodePos.x = Math::RangeRandom(min.x, max.x); nodePos.y = Math::RangeRandom(min.y, max.y); nodePos.z = Math::RangeRandom(min.z, max.z); node->setPosition(nodePos); mgr->getRootSceneNode()->addChild(node); cloneEnt = ent->clone(ent->getName() + "_clone" + StringConverter::toString(n)); // Attach to new node. node->attachObject(cloneEnt); } } PlayPen_LotsAndLotsOfEntities::PlayPen_LotsAndLotsOfEntities() { mInfo["Title"] = "PlayPen_LotsAndLotsOfEntities"; mInfo["Description"] = "Tests setting up and rendering a lot of entities."; addScreenshotFrame(3);// only go a couple frames, this one is slow (and static) } //---------------------------------------------------------------------------- void PlayPen_LotsAndLotsOfEntities::setupContent() { // Set ambient light. mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); // Create a point light. OrientedLightPtr l = mSceneMgr->createLight("MainLight"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(-Vector3::UNIT_Y); // Create a set of random cubes. Entity* ent = mSceneMgr->createEntity("Cube", "cube.mesh"); ent->setMaterial(MaterialManager::getSingleton().getDefaultMaterial()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); createRandomEntityClones(ent, 3000, Vector3(-1000,-1000,-1000), Vector3(1000,1000,1000), mSceneMgr); //bool val = true; //mSceneMgr->setOption("ShowOctree", &val); mCameraNode->setPosition(0,0, -4000); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); // Enable the profiler. Profiler* prof = Profiler::getSingletonPtr(); if (prof) prof->setEnabled(true); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ManualBoneMovement::PlayPen_ManualBoneMovement() { mInfo["Title"] = "PlayPen_ManualBoneMovement"; mInfo["Description"] = "Tests manually controlling a skeletal animation bone."; addScreenshotFrame(50); } //---------------------------------------------------------------------------- bool PlayPen_ManualBoneMovement::frameStarted(const FrameEvent& evt) { mBone->yaw(Degree(evt.timeSinceLastFrame*100)); return true; } //---------------------------------------------------------------------------- void PlayPen_ManualBoneMovement::setupContent() { Entity *ent = mSceneMgr->createEntity("robot", "robot.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); mSceneMgr->setAmbientLight(ColourValue(0.8, 0.8, 0.8)); //ent->setMaterialName("Examples/Rocky"); SkeletonInstance* skel = ent->getSkeleton(); Animation* anim = skel->getAnimation("Walk"); mBone = skel->getBone("Joint10"); mBone->setManuallyControlled(true); anim->destroyNodeTrack(mBone->getHandle()); //AnimationState* animState = ent->getAnimationState("Walk"); //animState->setEnabled(true); mCameraNode->setPosition(100,50,200); mCameraNode->lookAt(Vector3(0, 25, 0), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ManualIlluminationStage::PlayPen_ManualIlluminationStage() { mInfo["Title"] = "PlayPen_ManualIlluminationStage"; mInfo["Description"] = "Tests manual illumination stages."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_ManualIlluminationStage::setupContent() { #ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM // Make this viewport work with shader generator scheme. mViewport->setMaterialScheme(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); #endif mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_ADDITIVE); mSceneMgr->setShadowDirectionalLightExtrusionDistance(1000); MaterialManager::getSingleton().setDefaultTextureFiltering(TFO_ANISOTROPIC); MaterialManager::getSingleton().setDefaultAnisotropy(5); // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.0, 0.0, 0.0)); Light* mLight = mSceneMgr->createLight("MainLight"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-400,400,-300))->attachObject(mLight); mLight->setDiffuseColour(0.9, 0.9, 1); mLight->setSpecularColour(0.9, 0.9, 1); mLight->setAttenuation(6000,1,0.001,0); mLight = mSceneMgr->createLight("Light2"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(300,200,100))->attachObject(mLight); mLight->setDiffuseColour(1, 0.6, 0.5); mLight->setSpecularColour(0.9, 0.9, 1); mLight->setAttenuation(6000,1,0.001,0); MeshPtr msh = MeshManager::getSingleton().load("knot.mesh", ASSETS_RESOURCE_GROUP); msh->buildTangentVectors(); Entity* pEnt = mSceneMgr->createEntity( "3.5", "knot.mesh" ); pEnt->setMaterialName("Examples/OffsetMapping/Specular"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject( pEnt ); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 100; MeshPtr planeMesh = MeshManager::getSingleton().createPlane( "Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500, 1500, 100, 100, true, 1, 15, 15, Vector3::UNIT_Z); planeMesh->buildTangentVectors(); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("Examples/OffsetMapping/Specular"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); mCameraNode->setPosition(180, 34, 223); mCameraNode->lookAt(Vector3(0, 50, 0), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ManualObject2D::PlayPen_ManualObject2D() { mInfo["Title"] = "PlayPen_ManualObject2D"; mInfo["Description"] = "Tests 2d manual objects."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_ManualObject2D::setupContent() { mSceneMgr->setAmbientLight(ColourValue::White); ManualObject* man = mSceneMgr->createManualObject("1"); man->begin("Examples/OgreLogo"); man->position( 0.0, 0.0, 0.0); man->textureCoord( 0, 1 ); man->normal(0, 0, 1); man->position( 0.1, 0.0, 0.0); man->textureCoord( 1, 1 ); man->normal(0, 0, 1); man->position( 0.1, 0.1, 0.0); man->textureCoord( 1, 0 ); man->normal(0, 0, 1); man->position( 0.0, 0.1, 0.0); man->textureCoord( 0, 0 ); man->normal(0, 0, 1); man->triangle( 0, 1, 2 ); man->triangle( 0, 2, 3 ); man->setRenderQueueGroup(RENDER_QUEUE_OVERLAY - 1); man->end(); man->setUseIdentityProjection(true); man->setUseIdentityView(true); man->setBoundingBox(AxisAlignedBox::EXTENT_INFINITE); SceneNode* sn = mSceneMgr->getRootSceneNode()->createChildSceneNode(); sn->setScale(5,5,1); sn->attachObject(man); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ManualObjectIndexed::PlayPen_ManualObjectIndexed() { mInfo["Title"] = "PlayPen_ManualObjectIndexed"; mInfo["Description"] = "Tests indexed manual objects."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_ManualObjectIndexed::setupContent() { mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); Vector3 dir(-1, -1, 0.5); dir.normalise(); OrientedLightPtr l = mSceneMgr->createLight("light1"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(dir); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 100; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); // Define a 40x40 plane, indexed //! [manual_plane_begin] Ogre::ManualObject* man = mSceneMgr->createManualObject("test"); man->begin("Examples/OgreLogo", Ogre::RenderOperation::OT_TRIANGLE_LIST); //! [manual_plane_begin] //! [manual_plane_vertices] man->position(-20, 20, 20); man->normal(0, 0, 1); man->textureCoord(0, 0); man->position(-20, -20, 20); man->normal(0, 0, 1); man->textureCoord(0, 1); man->position(20, -20, 20); man->normal(0, 0, 1); man->textureCoord(1, 1); man->position(20, 20, 20); man->normal(0, 0, 1); man->textureCoord(1, 0); //! [manual_plane_vertices] //! [manual_plane_faces] man->quad(0, 1, 2, 3); //! [manual_plane_faces] man->end(); man->begin("Examples/BumpyMetal"); // Define a 40x40 plane, indexed man->position(-20, 20, 20); man->normal(0, 1, 0); man->textureCoord(0, 0); man->position(20, 20, 20); man->normal(0, 1, 0); man->textureCoord(0, 1); man->position(20, 20, -20); man->normal(0, 1, 0); man->textureCoord(1, 1); man->position(-20, 20, -20); man->normal(0, 1, 0); man->textureCoord(1, 0); man->quad(0, 1, 2, 3); //! [manual_plane_end] man->end(); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(man); //! [manual_plane_end] mCameraNode->setPosition(100,100,100); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ManualObjectIndexedUpdateLarger::PlayPen_ManualObjectIndexedUpdateLarger() { mInfo["Title"] = "PlayPen_ManualObjectIndexedUpdateLarger"; mInfo["Description"] = "Tests updating indexed manual objects."; } //---------------------------------------------------------------------------- void PlayPen_ManualObjectIndexedUpdateLarger::setupContent() { PlayPen_ManualObjectIndexed::setupContent(); ManualObject* man = static_cast<ManualObject*>( mSceneMgr->getMovableObject("test", ManualObjectFactory::FACTORY_TYPE_NAME)); man->beginUpdate(0); // 1 quad larger man->position(-20, 20, 20); man->normal(0, 0, 1); man->textureCoord(0, 0); man->position(-20, -20, 20); man->normal(0, 0, 1); man->textureCoord(0, 1); man->position(20, -20, 20); man->normal(0, 0, 1); man->textureCoord(1, 1); man->position(20, 20, 20); man->normal(0, 0, 1); man->textureCoord(1, 0); man->position(-20, 40, 20); man->normal(0, 0, 1); man->textureCoord(0, 0); man->position(-20, 20, 20); man->normal(0, 0, 1); man->textureCoord(0, 1); man->position(20, 20, 20); man->normal(0, 0, 1); man->textureCoord(1, 1); man->position(20, 40, 20); man->normal(0, 0, 1); man->textureCoord(1, 0); man->quad(0, 1, 2, 3); man->quad(4, 5, 6, 7); man->end(); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ManualObjectIndexedUpdateSmaller::PlayPen_ManualObjectIndexedUpdateSmaller() { mInfo["Title"] = "PlayPen_ManualObjectIndexedUpdateSmaller"; mInfo["Description"] = "Tests updating indexed manual objects."; } //---------------------------------------------------------------------------- void PlayPen_ManualObjectIndexedUpdateSmaller::setupContent() { PlayPen_ManualObjectIndexed::setupContent(); ManualObject* man = static_cast<ManualObject*>( mSceneMgr->getMovableObject("test", ManualObjectFactory::FACTORY_TYPE_NAME)); man->beginUpdate(0); // 1 tri smaller man->position(-20, 20, 20); man->normal(0, 0, 1); man->textureCoord(0, 0); man->position(-20, -20, 20); man->normal(0, 0, 1); man->textureCoord(0, 1); man->position(20, -20, 20); man->normal(0, 0, 1); man->textureCoord(1, 1); man->triangle(0, 1, 2); man->end(); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ManualObjectNonIndexed::PlayPen_ManualObjectNonIndexed() { mInfo["Title"] = "PlayPen_ManualObjectNonIndexed"; mInfo["Description"] = "Tests non-indexed manual objects."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_ManualObjectNonIndexed::setupContent() { mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); Vector3 dir(-1, -1, 0.5); dir.normalise(); OrientedLightPtr l = mSceneMgr->createLight("light1"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(dir); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 100; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); ManualObject* man = static_cast<ManualObject*>( mSceneMgr->createMovableObject("test", ManualObjectFactory::FACTORY_TYPE_NAME)); man->begin("Examples/OgreLogo"); // Define a 40x40 plane, non-indexed man->position(-20, 20, 20); man->normal(0, 0, 1); man->textureCoord(0, 0); man->position(-20, -20, 20); man->normal(0, 0, 1); man->textureCoord(0, 1); man->position(20, 20, 20); man->normal(0, 0, 1); man->textureCoord(1, 0); man->position(-20, -20, 20); man->normal(0, 0, 1); man->textureCoord(0, 1); man->position(20, -20, 20); man->normal(0, 0, 1); man->textureCoord(1, 1); man->position(20, 20, 20); man->normal(0, 0, 1); man->textureCoord(1, 0); man->end(); man->begin("Examples/BumpyMetal"); // Define a 40x40 plane, non-indexed man->position(-20, 20, 20); man->normal(0, 1, 0); man->textureCoord(0, 0); man->position(20, 20, 20); man->normal(0, 1, 0); man->textureCoord(0, 1); man->position(20, 20, -20); man->normal(0, 1, 0); man->textureCoord(1, 1); man->position(20, 20, -20); man->normal(0, 1, 0); man->textureCoord(1, 1); man->position(-20, 20, -20); man->normal(0, 1, 0); man->textureCoord(1, 0); man->position(-20, 20, 20); man->normal(0, 1, 0); man->textureCoord(0, 0); man->end(); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(man); mCameraNode->setPosition(100,100,100); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ManualObjectNonIndexedUpdateLarger::PlayPen_ManualObjectNonIndexedUpdateLarger() { mInfo["Title"] = "PlayPen_ManualObjectNonIndexedUpdateLarger"; mInfo["Description"] = "Tests updating non-indexed manual objects."; } //---------------------------------------------------------------------------- void PlayPen_ManualObjectNonIndexedUpdateLarger::setupContent() { PlayPen_ManualObjectNonIndexed::setupContent(); ManualObject* man = static_cast<ManualObject*>( mSceneMgr->getMovableObject("test", ManualObjectFactory::FACTORY_TYPE_NAME)); // Redefine but make larger (2 more tri) man->beginUpdate(0); man->position(-20, 20, 20); man->normal(0, 0, 1); man->textureCoord(0, 0); man->position(-20, -20, 20); man->normal(0, 0, 1); man->textureCoord(0, 1); man->position(20, 20, 20); man->normal(0, 0, 1); man->textureCoord(1, 0); man->position(-20, -20, 20); man->normal(0, 0, 1); man->textureCoord(0, 1); man->position(20, -20, 20); man->normal(0, 0, 1); man->textureCoord(1, 1); man->position(20, 20, 20); man->normal(0, 0, 1); man->textureCoord(1, 0); man->position(-20, 40, 20); man->normal(0, 0, 1); man->textureCoord(0, 0); man->position(-20, 20, 20); man->normal(0, 0, 1); man->textureCoord(0, 1); man->position(20, 40, 20); man->normal(0, 0, 1); man->textureCoord(1, 0); man->position(-20, 20, 20); man->normal(0, 0, 1); man->textureCoord(0, 1); man->position(20, 20, 20); man->normal(0, 0, 1); man->textureCoord(1, 1); man->position(20, 40, 20); man->normal(0, 0, 1); man->textureCoord(1, 0); man->end(); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ManualObjectNonIndexedUpdateSmaller::PlayPen_ManualObjectNonIndexedUpdateSmaller() { mInfo["Title"] = "PlayPen_ManualObjectNonIndexedUpdateSmaller"; mInfo["Description"] = "Tests updating non-indexed manual objects."; } //---------------------------------------------------------------------------- void PlayPen_ManualObjectNonIndexedUpdateSmaller::setupContent() { PlayPen_ManualObjectNonIndexed::setupContent(); ManualObject* man = static_cast<ManualObject*>( mSceneMgr->getMovableObject("test", ManualObjectFactory::FACTORY_TYPE_NAME)); // Redefine but make smaller (one tri less) man->beginUpdate(0); man->position(-30, 30, 30); man->normal(0, 0, 1); man->textureCoord(0, 0); man->position(-30, -30, 30); man->normal(0, 0, 1); man->textureCoord(0, 1); man->position(90, 30, 30); man->normal(0, 0, 1); man->textureCoord(1, 0); man->end(); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_MaterialSchemes::PlayPen_MaterialSchemes() { mInfo["Title"] = "PlayPen_MaterialSchemes"; mInfo["Description"] = "Tests material scehemes in viewports."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_MaterialSchemes::setupContent() { Entity *ent = mSceneMgr->createEntity("robot", "robot.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); mSceneMgr->setAmbientLight(ColourValue(0.8, 0.8, 0.8)); MaterialPtr mat = MaterialManager::getSingleton().create("schemetest", TRANSIENT_RESOURCE_GROUP); // default scheme mat->getTechnique(0)->getPass(0)->createTextureUnitState("GreenSkin.jpg"); Technique* t = mat->createTechnique(); t->setSchemeName("newscheme"); t->createPass()->createTextureUnitState("rockwall.tga"); ent->setMaterialName("schemetest"); #ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM // force create shaders for non default scheme t->setSchemeName("newscheme_tmp"); RTShader::ShaderGenerator& rtShaderGen = RTShader::ShaderGenerator::getSingleton(); rtShaderGen.createShaderBasedTechnique(*mat, "newscheme_tmp", "newscheme"); rtShaderGen.validateMaterial("newscheme", mat->getName(), mat->getGroup()); #endif // create a second viewport using alternate scheme Viewport* vp = mWindow->addViewport(mCamera, 1, 0.75, 0, 0.25, 0.25); vp->setMaterialScheme("newscheme"); vp->setOverlaysEnabled(false); mCameraNode->setPosition(0,75,200); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_MaterialSchemesListener::PlayPen_MaterialSchemesListener() { mInfo["Title"] = "PlayPen_MaterialSchemesListener"; mInfo["Description"] = "Tests material scheme listener."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- class TestMatMgrListener : public MaterialManager::Listener { public: TestMatMgrListener() : mTech(0) {} Technique* mTech; Technique* handleSchemeNotFound(unsigned short schemeIndex, const String& schemeName, Material* originalMaterial, unsigned short lodIndex, const Renderable* rend) { return mTech; } }; TestMatMgrListener schemeListener; void PlayPen_MaterialSchemesListener::setupContent() { mSceneMgr->setAmbientLight(ColourValue(0.8, 0.8, 0.8)); Entity *ent = mSceneMgr->createEntity("robot", "robot.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); // create a second viewport using alternate scheme // notice it's not defined in a technique Viewport* vp = mWindow->addViewport(mCamera, 1, 0.75, 0, 0.25, 0.25); vp->setMaterialScheme("newscheme"); vp->setOverlaysEnabled(false); MaterialPtr mat = MaterialManager::getSingleton().create("schemetest", TRANSIENT_RESOURCE_GROUP); // default scheme mat->getTechnique(0)->getPass(0)->createTextureUnitState("GreenSkin.jpg"); schemeListener.mTech = mat->getTechnique(0); MaterialManager::getSingleton().addListener(&schemeListener); mCameraNode->setPosition(0, 75, 200); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_MaterialSchemesWithLOD::PlayPen_MaterialSchemesWithLOD() { mInfo["Title"] = "PlayPen_MaterialSchemesWithLOD"; mInfo["Description"] = "Tests material schemes with LODs."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_MaterialSchemesWithLOD::setupContent() { Entity *ent = mSceneMgr->createEntity("robot", "robot.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); mSceneMgr->setAmbientLight(ColourValue(0.8, 0.8, 0.8)); MaterialPtr mat = MaterialManager::getSingleton().create("schemetest", TRANSIENT_RESOURCE_GROUP); // default scheme mat->getTechnique(0)->getPass(0)->createTextureUnitState("GreenSkin.jpg"); // LOD 0, newscheme Technique* t = mat->createTechnique(); t->setSchemeName("newscheme"); t->createPass()->createTextureUnitState("rockwall.tga"); ent->setMaterialName("schemetest"); // LOD 1, default t = mat->createTechnique(); t->setLodIndex(1); t->createPass()->createTextureUnitState("Water02.jpg"); // LOD 1, newscheme t = mat->createTechnique(); t->setLodIndex(1); t->createPass()->createTextureUnitState("r2skin.jpg"); t->setSchemeName("newscheme"); Material::LodValueList ldl; //ldl.push_back(Math::Sqr(500.0f)); ldl.push_back(150.0f); mat->setLodLevels(ldl); ent->setMaterialName("schemetest"); // create a second viewport using alternate scheme Viewport* vp = mWindow->addViewport(mCamera, 1, 0.75, 0, 0.25, 0.25); vp->setMaterialScheme("newscheme"); vp->setOverlaysEnabled(false); mCameraNode->setPosition(0,90,250); //mCameraNode->lookAt(Vector3(Vector3(0, 0, 0)), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_MaterialSchemesWithMismatchedLOD::PlayPen_MaterialSchemesWithMismatchedLOD() { mInfo["Title"] = "PlayPen_MaterialSchemesWithMismatchedLOD"; mInfo["Description"] = "Tests material scehemes in viewports with mismatched LODs."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_MaterialSchemesWithMismatchedLOD::setupContent() { Entity *ent = mSceneMgr->createEntity("robot", "robot.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); mSceneMgr->setAmbientLight(ColourValue(0.8, 0.8, 0.8)); MaterialPtr mat = MaterialManager::getSingleton().create("schemetest", TRANSIENT_RESOURCE_GROUP); // default scheme mat->getTechnique(0)->getPass(0)->createTextureUnitState("GreenSkin.jpg"); // LOD 0, newscheme Technique* t = mat->createTechnique(); t->setSchemeName("newscheme"); t->createPass()->createTextureUnitState("rockwall.tga"); ent->setMaterialName("schemetest"); // LOD 1, default t = mat->createTechnique(); t->setLodIndex(1); t->createPass()->createTextureUnitState("Water02.jpg"); // LOD 2, default t = mat->createTechnique(); t->setLodIndex(2); t->createPass()->createTextureUnitState("clouds.jpg"); // LOD 1, newscheme t = mat->createTechnique(); t->setLodIndex(1); t->createPass()->createTextureUnitState("r2skin.jpg"); t->setSchemeName("newscheme"); // No LOD 2 for newscheme! Should fallback on LOD 1 Material::LodValueList ldl; //ldl.push_back(Math::Sqr(250.0f)); //ldl.push_back(Math::Sqr(500.0f)); ldl.push_back(150.0f); ldl.push_back(300.0f); mat->setLodLevels(ldl); ent->setMaterialName("schemetest"); // create a second viewport using alternate scheme Viewport* vp = mWindow->addViewport(mCamera, 1, 0.75, 0, 0.25, 0.25); vp->setMaterialScheme("newscheme"); vp->setOverlaysEnabled(false); mCameraNode->setPosition(0,90,350); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- /*PlayPen_MRTCompositorScript::PlayPen_MRTCompositorScript() { mInfo["Title"] = "PlayPen_MRTCompositorScript"; mInfo["Description"] = "Tests MRT compositor."; addScreenshotFrame(250); } //---------------------------------------------------------------------------- void PlayPen_MRTCompositorScript::setupContent() { Entity* e = mSceneMgr->createEntity("e1", "knot.mesh"); e->setMaterialName("Ogre/MRTtest/scene"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mCameraNode->setPosition(0, 0, -100); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); CompositorInstance* compInst = CompositorManager::getSingleton().addCompositor(mWindow->getViewport(0), "TestMRT"); CompositorManager::getSingleton().setCompositorEnabled(mWindow->getViewport(0), "TestMRT", true); // Set up debug panels for each of the MRT outputs String texName = compInst->getTextureInstanceName("mrt0", 0); addTextureDebugOverlay(TextureManager::getSingleton().getByName(texName), 0); texName = compInst->getTextureInstanceName("mrt0", 1); addTextureDebugOverlay(TextureManager::getSingleton().getByName(texName), 1); texName = compInst->getTextureInstanceName("mrt0", 2); addTextureDebugOverlay(TextureManager::getSingleton().getByName(texName), 2); texName = compInst->getTextureInstanceName("mrt0", 3); addTextureDebugOverlay(TextureManager::getSingleton().getByName(texName), 3); }*/ //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- /*PlayPen_MRT::PlayPen_MRT() { mInfo["Title"] = "PlayPen_MRT"; mInfo["Description"] = "Tests MRT."; addScreenshotFrame(250); } //---------------------------------------------------------------------------- void PlayPen_MRT::setupContent() { TexturePtr Tex[2]; MultiRenderTarget* mrtTex; Viewport* viewport = mWindow->getViewport(0); int width = viewport->getActualWidth(); int height = viewport->getActualHeight(); Tex[0] = TextureManager::getSingleton().createManual("diffusemap", TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, width,height,0,PF_R8G8B8A8,TU_RENDERTARGET); Tex[1] = TextureManager::getSingleton().createManual("normalmap",TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, width,height,0,PF_R8G8B8A8,TU_RENDERTARGET); // assert(Tex[0]->getFormat() == PF_FLOAT16_RGBA); mrtTex = Ogre::Root::getSingleton().getRenderSystem()->createMultiRenderTarget("MRT"); RenderTexture* rTex[2]; rTex[0] = Tex[0]->getBuffer()->getRenderTarget(); rTex[1] = Tex[1]->getBuffer()->getRenderTarget(); rTex[0]->setAutoUpdated(false); rTex[1]->setAutoUpdated(false); mrtTex->bindSurface(0, rTex[0]); mrtTex->bindSurface(1, rTex[1]); mrtTex->setAutoUpdated(true); Viewport *v = mrtTex->addViewport(mCamera); v->setMaterialScheme("MRT"); v->setClearEveryFrame(true); v->setOverlaysEnabled(false); v->setSkiesEnabled(false); v->setBackgroundColour(ColourValue(0,0,0,0)); // Create texture overlay here Overlay *debugOverlay = OverlayManager::getSingleton().create("Core/DebugOverlay"); MaterialPtr debugMat = MaterialManager::getSingleton().create("DebugRTTMat1", TRANSIENT_RESOURCE_GROUP); debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false); TextureUnitState *t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState("normalmap"); t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); OverlayContainer *debugPanel = (OverlayContainer *) (OverlayManager::getSingleton().createOverlayElement("Panel","DebugRTTPanel1")); debugPanel->_setPosition(0.8,0); debugPanel->_setDimensions(0.2,0.3); debugPanel->setMaterialName(debugMat->getName()); debugOverlay->add2D(debugPanel); debugMat = MaterialManager::getSingleton().create("DebugRTTMat2", TRANSIENT_RESOURCE_GROUP); debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false); t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState("diffusemap"); t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); debugPanel = (OverlayContainer *) (OverlayManager::getSingleton().createOverlayElement("Panel","DebugRTTPanel2")); debugPanel->_setPosition(0.8,0.3); debugPanel->_setDimensions(0.2,0.3); debugPanel->setMaterialName(debugMat->getName()); debugOverlay->add2D(debugPanel); // Create scene items // Create a material to render differently to MRT compared to main viewport MaterialPtr mat = MaterialManager::getSingleton().create("MRTTest", TRANSIENT_RESOURCE_GROUP); // normal technique (0), leave as default Technique* mrtTech = mat->createTechnique(); mrtTech->setSchemeName("MRT"); Pass* mrtPass = mrtTech->createPass(); mrtPass->setVertexProgram("DeferredShading/material/hlsl/vs"); mrtPass->setFragmentProgram("DeferredShading/material/hlsl/ps"); mrtPass->createTextureUnitState("rockwall.tga"); mat->load(); Entity* ent = mSceneMgr->createEntity("knot", "knot.mesh"); ent->setMaterialName("MRTTest"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); mCameraNode->setPosition(0, 0, 200); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); }*/ //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_MultiSceneManagersSimple::PlayPen_MultiSceneManagersSimple() { mInfo["Title"] = "PlayPen_MultiSceneManagersSimple"; mInfo["Description"] = "Tests multiple scene managers."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_MultiSceneManagersSimple::setupContent() { // Create a secondary scene manager with it's own camera SceneManager* sm2 = Root::getSingleton().createSceneManager(); Light* l = sm2->createLight("l2"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 50, -100))->attachObject(l); l->setDiffuseColour(ColourValue::Green); // l->setDiffuseColour(ColourValue::Red); sm2->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); // sm2->setAmbientLight(ColourValue(1, 1, 1)); Entity* ent = sm2->createEntity("knot2", "knot.mesh"); // Entity* ent = sm2->createEntity("head", "ogrehead.mesh"); sm2->getRootSceneNode()->createChildSceneNode()->attachObject(ent); Camera* camera2 = sm2->createCamera("cam2"); SceneNode* camNode2 = sm2->getRootSceneNode()->createChildSceneNode(); camNode2->attachObject(camera2); camNode2->setPosition(0, 0, -500); camNode2->lookAt(Vector3::ZERO, Node::TS_PARENT); Viewport* vp = mWindow->addViewport(camera2, 1, 0.67, 0, 0.33, 0.25); vp->setOverlaysEnabled(false); vp->setBackgroundColour(ColourValue(1,0,0)); // Use original SM for normal scene l = mSceneMgr->createLight("l"); // note same name, will work since different SM mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 50, -100))->attachObject(l); l->setDiffuseColour(ColourValue::Red); mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); ent = mSceneMgr->createEntity("head", "ogrehead.mesh"); // ent = mSceneMgr->createEntity("knot", "knot.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); mCameraNode->setPosition(0, 0, 500); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_MultiViewports::PlayPen_MultiViewports() { mInfo["Title"] = "PlayPen_MultiViewports"; mInfo["Description"] = "Tests multiple viewports."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_MultiViewports::setupContent() { SceneNode* mTestNode[3]; // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); // Create a point light OrientedLightPtr l = mSceneMgr->createLight("MainLight"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(-Vector3::UNIT_Y); Entity* pEnt = mSceneMgr->createEntity( "1", "knot.mesh" ); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-30,0,-50))->attachObject(pEnt); mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); pEnt = mSceneMgr->createEntity( "2", "ogrehead.mesh" ); mTestNode[0]->attachObject( pEnt ); mTestNode[0]->translate(0, 0, 200); Ogre::Frustum* frustum = new Frustum(); //frustum->setVisible(true); frustum->setFarClipDistance(5000); frustum->setNearClipDistance(100); mTestNode[0]->attachObject(frustum); Viewport* vp = mWindow->addViewport(mCamera, 1, 0.5, 0.5, 0.5, 0.5); vp->setOverlaysEnabled(false); vp->setBackgroundColour(ColourValue(1,0,0)); mCameraNode->setPosition(0,0,500); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_NegativeScale::PlayPen_NegativeScale() { mInfo["Title"] = "PlayPen_NegativeScale"; mInfo["Description"] = "Tests negative scaling."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_NegativeScale::setupContent() { mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); Light* l = mSceneMgr->createLight("l1"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(500, 500, 200))->attachObject(l); l->setDiffuseColour(ColourValue::White); //mSceneMgr->setFlipCullingOnNegativeScale(false); Entity *e = mSceneMgr->createEntity("1", "knot.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); // one reflection e = mSceneMgr->createEntity("2", "knot.mesh"); SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); n->translate(-200, 0, 0); n->scale(-1, 1, 1); n->attachObject(e); // three reflections - will need flipping e = mSceneMgr->createEntity("3", "knot.mesh"); n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); n->translate(200, 0, 0); n->scale(-1, -1, -1); n->attachObject(e); // two reflections - won't need flipping e = mSceneMgr->createEntity("4", "knot.mesh"); n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); n->translate(400, 0, 0); n->scale(-1, 1, -1); n->attachObject(e); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_NormalMapMirroredUVs::PlayPen_NormalMapMirroredUVs() { mInfo["Title"] = "PlayPen_NormalMapMirroredUVs"; mInfo["Description"] = "Tests mirrored UVs with normal mapping shader."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_NormalMapMirroredUVs::setupContent() { Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); // this mesh has been generated with 4-component tangents, including a parity in w Entity* e = mSceneMgr->createEntity("2", "testmirroreduvmesh.mesh"); e->setMaterialName("Examples/BumpMapping/MultiLightTangentParity"); // here's what it looks like without the parity // e->setMaterialName("Examples/BumpMapping/MultiLight"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); Light* l = mSceneMgr->createLight("3"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(1000,500,1000))->attachObject(l); mCameraNode->setPosition(0,200,50); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_Ortho::PlayPen_Ortho() { mInfo["Title"] = "PlayPen_Ortho"; mInfo["Description"] = "Tests orthographic rendering."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_Ortho::setupContent() { SceneNode* mTestNode[3]; // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.0, 0.0, 0.0)); // Create a point light Light* l = mSceneMgr->createLight("MainLight"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(800,600,0))->attachObject(l); mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mSceneMgr->getRootSceneNode()->createChildSceneNode(); Entity* pEnt = mSceneMgr->createEntity( "3", "knot.mesh" ); mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200, 0, -200)); mTestNode[1]->attachObject( pEnt ); pEnt = mSceneMgr->createEntity( "4", "knot.mesh" ); mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 200)); mTestNode[2]->attachObject( pEnt ); mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 100; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); mCameraNode->setFixedYawAxis(false); mCamera->setProjectionType(PT_ORTHOGRAPHIC); mCameraNode->setPosition(0,10000,0); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); mCamera->setNearClipDistance(1000); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_PointSprites::PlayPen_PointSprites() { mInfo["Title"] = "PlayPen_PointSprites"; mInfo["Description"] = "Tests point sprites."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_PointSprites::setupContent() { MaterialPtr mat = MaterialManager::getSingleton().create("spriteTest1", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setPointSpritesEnabled(true); p->createTextureUnitState("flare.png"); p->setLightingEnabled(false); p->setDepthWriteEnabled(false); p->setSceneBlending(SBT_ADD); p->setPointAttenuation(true); p->setPointSize(3); p->setVertexColourTracking(TVC_DIFFUSE); ManualObject* man = mSceneMgr->createManualObject("man"); man->begin("spriteTest1", RenderOperation::OT_POINT_LIST); for (size_t i = 0; i < 1000; ++i) { man->position(Math::SymmetricRandom() * 500, Math::SymmetricRandom() * 500, Math::SymmetricRandom() * 500); man->colour(Math::RangeRandom(0.5f, 1.0f), Math::RangeRandom(0.5f, 1.0f), Math::RangeRandom(0.5f, 1.0f)); } // for (size_t i = 0; i < 20; ++i) // { // for (size_t j = 0; j < 20; ++j) // { // for (size_t k = 0; k < 20; ++k) // { // if (rand()%10 == 0) // man->position(i * 30, j * 30, k * 30); // } // } // } man->end(); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(man); mCameraNode->setPosition(0,0,1000); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_Projection::PlayPen_Projection() { mInfo["Title"] = "PlayPen_Projection"; mInfo["Description"] = "Tests projection."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_Projection::setupContent() { SceneNode* mTestNode[3]; // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); // Create a point light OrientedLightPtr l = mSceneMgr->createLight("MainLight"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(-Vector3::UNIT_Y); Entity* pEnt; //pEnt = mSceneMgr->createEntity( "1", "knot.mesh" ); //mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-30,0,-50))->attachObject(pEnt); //pEnt->setMaterialName("Examples/OgreLogo"); // Define a floor plane mesh Plane p; p.normal = Vector3::UNIT_Z; p.d = 200; MeshManager::getSingleton().createPlane("WallPlane", TRANSIENT_RESOURCE_GROUP, p,1500,1500,1,1,true,1,5,5,Vector3::UNIT_Y); pEnt = mSceneMgr->createEntity( "5", "WallPlane" ); pEnt->setMaterialName("Examples/OgreLogo"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pEnt); mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); //pEnt = mSceneMgr->createEntity( "2", "ogrehead.mesh" ); //mTestNode[0]->attachObject( pEnt ); mTestNode[0]->translate(0, 0, 750); Ogre::Frustum* frustum = new Frustum(); frustum->setVisible(true); frustum->setFarClipDistance(5000); frustum->setNearClipDistance(200); frustum->setAspectRatio(1); frustum->setProjectionType(PT_ORTHOGRAPHIC); mTestNode[0]->attachObject(frustum); // Hook the frustum up to the material MaterialPtr mat = MaterialManager::getSingleton().getByName("Examples/OgreLogo"); TextureUnitState *t = mat->getTechnique(0)->getPass(0)->getTextureUnitState(0); t->setProjectiveTexturing(true, frustum); //t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ReflectedBillboards::PlayPen_ReflectedBillboards() { mInfo["Title"] = "PlayPen_ReflectedBillboards"; mInfo["Description"] = "Tests reflected billboards."; addScreenshotFrame(175); // needs to run for a bit so there are particles to be reflected... } //---------------------------------------------------------------------------- void PlayPen_ReflectedBillboards::setupContent() { Camera* reflectCam = 0; // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); // Create a light OrientedLightPtr l = mSceneMgr->createLight("MainLight"); l->setType(Light::LT_DIRECTIONAL); Vector3 dir(0.5, -1, 0); dir.normalise(); l->setDirection(dir); l->setDiffuseColour(1.0f, 1.0f, 0.8f); l->setSpecularColour(1.0f, 1.0f, 1.0f); // Create a prefab plane Plane plane; plane.d = 0; plane.normal = Vector3::UNIT_Y; MeshManager::getSingleton().createPlane("ReflectionPlane", TRANSIENT_RESOURCE_GROUP, plane, 2000, 2000, 1, 1, true, 1, 1, 1, Vector3::UNIT_Z); Entity* planeEnt = mSceneMgr->createEntity( "Plane", "ReflectionPlane" ); // Attach the rtt entity to the root of the scene SceneNode* rootNode = mSceneMgr->getRootSceneNode(); SceneNode* planeNode = rootNode->createChildSceneNode(); // Attach both the plane entity, and the plane definition planeNode->attachObject(planeEnt); mCameraNode->setPosition(-50, 100, 500); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); TexturePtr rttTex = TextureManager::getSingleton().createManual("RttTex", TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, 512, 512, 1, 0, PF_R8G8B8, TU_RENDERTARGET); { reflectCam = mSceneMgr->createCamera("ReflectCam"); reflectCam->setNearClipDistance(mCamera->getNearClipDistance()); reflectCam->setFarClipDistance(mCamera->getFarClipDistance()); reflectCam->setAspectRatio( (Real)mWindow->getViewport(0)->getActualWidth() / (Real)mWindow->getViewport(0)->getActualHeight()); SceneNode* reflectCamNode = rootNode->createChildSceneNode(); reflectCamNode->attachObject(reflectCam); reflectCamNode->setPosition(mCameraNode->getPosition()); reflectCamNode->setOrientation(mCameraNode->getOrientation()); Viewport *v = rttTex->getBuffer()->getRenderTarget()->addViewport( reflectCam ); v->setClearEveryFrame( true ); v->setBackgroundColour( ColourValue::Black ); MaterialPtr mat = MaterialManager::getSingleton().create("RttMat", TRANSIENT_RESOURCE_GROUP); mat->getTechnique(0)->getPass(0)->createTextureUnitState("RustedMetal.jpg"); TextureUnitState* t = mat->getTechnique(0)->getPass(0)->createTextureUnitState("RttTex"); // Blend with base texture t->setColourOperationEx(LBX_BLEND_MANUAL, LBS_TEXTURE, LBS_CURRENT, ColourValue::White, ColourValue::White, 0.25); t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); t->setProjectiveTexturing(true, reflectCam); // set up linked reflection reflectCam->enableReflection(plane); // Also clip reflectCam->enableCustomNearClipPlane(plane); } // Give the plane a texture planeEnt->setMaterialName("RttMat"); // point billboards ParticleSystem* pSys2 = mSceneMgr->createParticleSystem("fountain1", "Examples/Smoke"); // Point the fountain at an angle SceneNode* fNode = static_cast<SceneNode*>(rootNode->createChild()); fNode->attachObject(pSys2); // oriented_self billboards ParticleSystem* pSys3 = mSceneMgr->createParticleSystem("fountain2", "Examples/PurpleFountain"); // Point the fountain at an angle fNode = rootNode->createChildSceneNode(); fNode->translate(-200,-100,0); fNode->rotate(Vector3::UNIT_Z, Degree(-20)); fNode->attachObject(pSys3); // oriented_common billboards ParticleSystem* pSys4 = mSceneMgr->createParticleSystem("rain", "Examples/Rain"); SceneNode* rNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); rNode->translate(0,1000,0); rNode->attachObject(pSys4); // Fast-forward the rain so it looks more natural pSys4->fastForward(5); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ReinitialiseEntityAlteredMesh::PlayPen_ReinitialiseEntityAlteredMesh() { mInfo["Title"] = "PlayPen_ReinitialiseEntityAlteredMesh"; mInfo["Description"] = "Tests updating an entity while rendering."; addScreenshotFrame(100); mTimer = 0.5f; } //---------------------------------------------------------------------------- bool PlayPen_ReinitialiseEntityAlteredMesh::frameStarted(const FrameEvent& evt) { if(mTimer > 0.f) { mTimer -= evt.timeSinceLastFrame; if(mTimer <= 0.f) { // Change the mesh, add a new submesh. // Load another mesh. MeshPtr msh = MeshManager::getSingleton().load( "ogrehead.mesh", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); for (unsigned short e = 0; e < msh->getNumSubMeshes(); ++e) { SubMesh* sm = msh->getSubMesh(e); sm->clone("", mUpdate); } mTimer = -5.f; } } return true; } //---------------------------------------------------------------------------- void PlayPen_ReinitialiseEntityAlteredMesh::setupContent() { // test whether an Entity picks up that Mesh has changed // and therefore rebuild SubEntities mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); Light* l = mSceneMgr->createLight("l1"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(200, 300, 0))->attachObject(l); Ogre::MeshManager::getSingleton().load("knot.mesh", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME)->clone("knot_REINIT.mesh"); Entity* pEnt = mSceneMgr->createEntity("testEnt", "knot_REINIT.mesh"); mUpdate = pEnt->getMesh().get(); mSceneMgr->getRootSceneNode()->attachObject(pEnt); mCameraNode->setPosition(0,0,200); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ReloadResources::PlayPen_ReloadResources() { mInfo["Title"] = "PlayPen_ReloadResources"; mInfo["Description"] = "Tests unloading and reloading resources."; addScreenshotFrame(100); mReloadTimer = 0.5f; } //---------------------------------------------------------------------------- bool PlayPen_ReloadResources::frameStarted(const FrameEvent& evt) { if(mReloadTimer > 0.f) { mReloadTimer -= evt.timeSinceLastFrame; if(mReloadTimer <= 0.f) { // unload Entity* e = mSceneMgr->getEntity("1"); e->getParentSceneNode()->detachObject("1"); mSceneMgr->destroyAllEntities(); ResourceGroupManager::getSingleton().unloadResourceGroup("TestReload"); // reload e = mSceneMgr->createEntity("1", "UniqueModel.MESH"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mReloadTimer = -5.f; } } return true; } //---------------------------------------------------------------------------- void PlayPen_ReloadResources::setupContent() { mSceneMgr->setAmbientLight(ColourValue::White); // get path to test resources const Ogre::ResourceGroupManager::LocationList& ll = Ogre::ResourceGroupManager::getSingleton().getResourceLocationList("Tests"); const Ogre::ResourceGroupManager::ResourceLocation* loc = &ll.front(); Ogre::String testResourcePath = loc->archive->getName(); // add a new group // Ogre::String meshFilePath = testResourcePath + "/TestReload"; Ogre::String meshFilePath = testResourcePath + "/Model2"; Ogre::ResourceGroupManager& resMgr = Ogre::ResourceGroupManager::getSingleton(); String newGroup = meshFilePath; resMgr.createResourceGroup("TestReload", false); resMgr.addResourceLocation(meshFilePath, "FileSystem", "TestReload"); resMgr.initialiseResourceGroup("TestReload"); MeshManager& mmgr = MeshManager::getSingleton(); mmgr.load("UniqueModel.MESH", "TestReload"); Entity* e = mSceneMgr->createEntity("1", "UniqueModel.MESH"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mCameraNode->setPosition(0,0,200); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_RibbonTrail::PlayPen_RibbonTrail() { mInfo["Title"] = "PlayPen_RibbonTrail"; mInfo["Description"] = "Tests ribbon trail effect."; addScreenshotFrame(150); } //---------------------------------------------------------------------------- void PlayPen_RibbonTrail::setupContent() { mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); Vector3 dir(-1, -1, 0.5); dir.normalise(); OrientedLightPtr l = mSceneMgr->createLight("light1"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(dir); NameValuePairList pairList; pairList["numberOfChains"] = "2"; pairList["maxElements"] = "80"; RibbonTrail* trail = static_cast<RibbonTrail*>( mSceneMgr->createMovableObject("1", "RibbonTrail", &pairList)); trail->setMaterialName("Examples/LightRibbonTrail"); trail->setTrailLength(400); //mRibbonTrail = trail; mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(trail); // Create 3 nodes for trail to follow SceneNode* animNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); animNode->setPosition(0,20,0); Animation* anim = mSceneMgr->createAnimation("an1", 10); anim->setInterpolationMode(Animation::IM_SPLINE); NodeAnimationTrack* track = anim->createNodeTrack(1, animNode); TransformKeyFrame* kf = track->createNodeKeyFrame(0); kf->setTranslate(Vector3::ZERO); kf = track->createNodeKeyFrame(2); kf->setTranslate(Vector3(100, 0, 0)); kf = track->createNodeKeyFrame(4); kf->setTranslate(Vector3(200, 0, 300)); kf = track->createNodeKeyFrame(6); kf->setTranslate(Vector3(0, 20, 500)); kf = track->createNodeKeyFrame(8); kf->setTranslate(Vector3(-100, 10, 100)); kf = track->createNodeKeyFrame(10); kf->setTranslate(Vector3::ZERO); //testremoveNode = animNode; AnimationState* animState = mSceneMgr->createAnimationState("an1"); animState->setEnabled(true); mAnimStateList.push_back(animState); trail->addNode(animNode); trail->setInitialColour(0, 1.0, 0.8, 0); trail->setColourChange(0, 0.5, 0.5, 0.5, 0.5); trail->setInitialWidth(0, 5); // Add light Light* l2 = mSceneMgr->createLight("l2"); l2->setDiffuseColour(trail->getInitialColour(0)); animNode->attachObject(l2); // Add billboard BillboardSet* bbs = mSceneMgr->createBillboardSet("bb", 1); bbs->createBillboard(Vector3::ZERO, trail->getInitialColour(0)); bbs->setMaterialName("Examples/Flare"); animNode->attachObject(bbs); animNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); animNode->setPosition(-50,10,0); anim = mSceneMgr->createAnimation("an2", 10); anim->setInterpolationMode(Animation::IM_SPLINE); track = anim->createNodeTrack(1, animNode); kf = track->createNodeKeyFrame(0); kf->setTranslate(Vector3::ZERO); kf = track->createNodeKeyFrame(2); kf->setTranslate(Vector3(-100, 150, -30)); kf = track->createNodeKeyFrame(4); kf->setTranslate(Vector3(-200, 0, 40)); kf = track->createNodeKeyFrame(6); kf->setTranslate(Vector3(0, -150, 70)); kf = track->createNodeKeyFrame(8); kf->setTranslate(Vector3(50, 0, 30)); kf = track->createNodeKeyFrame(10); kf->setTranslate(Vector3::ZERO); animState = mSceneMgr->createAnimationState("an2"); animState->setEnabled(true); mAnimStateList.push_back(animState); trail->addNode(animNode); trail->setInitialColour(1, 0.0, 1.0, 0.4); trail->setColourChange(1, 0.5, 0.5, 0.5, 0.5); trail->setInitialWidth(1, 5); // Add light l2 = mSceneMgr->createLight("l3"); l2->setDiffuseColour(trail->getInitialColour(1)); animNode->attachObject(l2); // Add billboard bbs = mSceneMgr->createBillboardSet("bb2", 1); bbs->createBillboard(Vector3::ZERO, trail->getInitialColour(1)); bbs->setMaterialName("Examples/Flare"); animNode->attachObject(bbs); mCameraNode->setPosition(0,0,500); //mSceneMgr->showBoundingBoxes(true); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_SerialisedColour::PlayPen_SerialisedColour() { mInfo["Title"] = "PlayPen_SerialisedColour"; mInfo["Description"] = "Tests serializing mesh color."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_SerialisedColour::setupContent() { mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); Vector3 dir(-1, -1, 0.5); dir.normalise(); OrientedLightPtr l = mSceneMgr->createLight("light1"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(dir); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 100; MeshManager::getSingleton().createPlane( "Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500, 1500, 10, 10, true, 1, 5, 5, Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); ManualObject* man = static_cast<ManualObject*>( mSceneMgr->createMovableObject("test", ManualObjectFactory::FACTORY_TYPE_NAME)); MaterialPtr mat = MaterialManager::getSingleton().create( "AmbientVertexColourTracking", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setVertexColourTracking(TVC_AMBIENT); p->setLightingEnabled(false); man->begin("AmbientVertexColourTracking"); //TODO Define a 40x40 plane, non-indexed // Define a 40x40 plane, indexed man->position(-20, 20, 20); man->colour(1, 0, 0); man->position(-20, -20, 20); man->colour(1, 0, 0); man->position(20, -20, 20); man->colour(1, 0, 0); man->position(20, 20, 20); man->colour(1, 0, 0); man->quad(0, 1, 2, 3); man->end(); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(man); MeshPtr mesh = man->convertToMesh("colourtest.mesh"); MeshSerializer ms; ms.exportMesh(mesh.get(), "colourtest.mesh"); Entity* c = mSceneMgr->createEntity("1", "colourtest.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(c); mCameraNode->setPosition(0,0,120); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ShadowLod::PlayPen_ShadowLod() { mInfo["Title"] = "PlayPen_ShadowLod"; mInfo["Description"] = "Tests whether LOD is based on shadow cam or main cam."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_ShadowLod::cleanupContent() { clearDebugTextureOverlays(); } //---------------------------------------------------------------------------- void PlayPen_ShadowLod::setupContent() { SceneNode* mTestNode[10]; // Test that LOD is based on main camera, not shadow camera mSceneMgr->setShadowTextureSize(1024); mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); //FocusedShadowCameraSetup* lispsmSetup = new FocusedShadowCameraSetup(); //LiSPSMShadowCameraSetup* lispsmSetup = new LiSPSMShadowCameraSetup(); //lispsmSetup->setOptimalAdjustFactor(1.5); //mSceneMgr->setShadowCameraSetup(ShadowCameraSetupPtr(lispsmSetup)); mSceneMgr->setShadowColour(ColourValue(0.35, 0.35, 0.35)); // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); // Directional test if (false) { OrientedLightPtr mLight = mSceneMgr->createLight("MainLight"); mLight->setType(Light::LT_DIRECTIONAL); Vector3 vec(-1,-1,0); vec.normalise(); mLight->setDirection(vec); } // Spotlight test else { Light* mLight = mSceneMgr->createLight("MainLight"); mLight->setType(Light::LT_SPOTLIGHT); mLight->setAttenuation(10000, 1, 0, 0); mLight->setDiffuseColour(1.0, 1.0, 0.8); mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mTestNode[0]->setPosition(400,300,0); mTestNode[0]->lookAt(Vector3(0,0,0), Node::TS_WORLD); mTestNode[0]->attachObject(mLight); } mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); Entity* pEnt; pEnt = mSceneMgr->createEntity( "1", "knot.mesh" ); // rendering distance should also be based on main cam //pEnt->setRenderingDistance(100); //pEnt->setMaterialName("2 - Default"); mTestNode[1]->attachObject( pEnt ); //mTestNode[1]->translate(0,-100,0); /* pEnt = mSceneMgr->createEntity( "3", "knot.mesh" ); mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200, 0, -200)); mTestNode[2]->attachObject( pEnt ); createRandomEntityClones(pEnt, 20, Vector3(-1000,0,-1000), Vector3(1000,0,1000)); // Transparent object (can force cast shadows) pEnt = mSceneMgr->createEntity( "3.5", "knot.mesh" ); MaterialPtr tmat = MaterialManager::getSingleton().create("TestAlphaTransparency", TRANSIENT_RESOURCE_GROUP); tmat->setTransparencyCastsShadows(true); Pass* tpass = tmat->getTechnique(0)->getPass(0); tpass->setAlphaRejectSettings(CMPF_GREATER, 150); tpass->setSceneBlending(SBT_TRANSPARENT_ALPHA); tpass->createTextureUnitState("gras_02.png"); tpass->setCullingMode(CULL_NONE); pEnt->setMaterialName("TestAlphaTransparency"); mTestNode[3] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(350, 0, -200)); mTestNode[3]->attachObject( pEnt ); MeshPtr msh = MeshManager::getSingleton().load("knot.mesh", TRANSIENT_RESOURCE_GROUP); msh->buildTangentVectors(VES_TANGENT, 0, 0); pEnt = mSceneMgr->createEntity( "4", "knot.mesh" ); //pEnt->setMaterialName("Examples/BumpMapping/MultiLightSpecular"); mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 200)); mTestNode[2]->attachObject( pEnt ); mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); */ MovablePlane movablePlane(Vector3::UNIT_Y, 100); MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, movablePlane, 2500,2500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt; pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); if (SHADOWTYPE_TEXTURE_MODULATIVE & SHADOWDETAILTYPE_INTEGRATED) { pPlaneEnt->setMaterialName("Examples/Plane/IntegratedShadows"); } else { pPlaneEnt->setMaterialName("2 - Default"); } pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); addTextureShadowDebugOverlay(1, mSceneMgr); /* ParticleSystem* pSys2 = mSceneMgr->createParticleSystem("smoke", "Examples/Smoke"); mTestNode[4] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-300, -100, 200)); mTestNode[4]->attachObject(pSys2); */ mCameraNode->setPosition(0, 1000, 500); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); mCamera->setFarClipDistance(10000); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_SkeletalAnimation::PlayPen_SkeletalAnimation() { mInfo["Title"] = "PlayPen_SkeletalAnimation"; mInfo["Description"] = "Tests skeletal animation."; addScreenshotFrame(100); } //---------------------------------------------------------------------------- void PlayPen_SkeletalAnimation::setupContent() { // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); //mWindow->getViewport(0)->setBackgroundColour(ColourValue::White); Entity *ent = mSceneMgr->createEntity("robot", "robot.mesh"); //ent->setDisplaySkeleton(true); // Uncomment the below to test software skinning ent->setMaterialName("Examples/Rocky"); // Add entity to the scene node mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); Ogre::AnimationState* mAnimState = ent->getAnimationState("Walk"); mAnimState->setEnabled(true); // Give it a little ambience with lights Light* l; l = mSceneMgr->createLight("BlueLight"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200,-80,-100))->attachObject(l); l->setDiffuseColour(0.5, 0.5, 1.0); l = mSceneMgr->createLight("GreenLight"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,0,-100))->attachObject(l); l->setDiffuseColour(0.5, 1.0, 0.5); // Position the camera mCameraNode->setPosition(200,50,0); mCameraNode->lookAt(Vector3(0, 50, 0), Node::TS_PARENT); // Report whether hardware skinning is enabled or not /*Technique* t = ent->getSubEntity(0)->getTechnique(); Pass* p = t->getPass(0); OverlayElement* guiDbg = OverlayManager::getSingleton().getOverlayElement("Core/DebugText"); if (p->hasVertexProgram() && p->getVertexProgram()->isSkeletalAnimationIncluded()) { guiDbg->setCaption("Hardware skinning is enabled"); } else { guiDbg->setCaption("Software skinning is enabled"); }*/ mAnimStateList.push_back(mAnimState); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_SkeletonAnimationOptimise::PlayPen_SkeletonAnimationOptimise() { mInfo["Title"] = "PlayPen_SkeletonAnimationOptimise"; mInfo["Description"] = "Tests skeletal animation with hardware and software."; addScreenshotFrame(100); } //---------------------------------------------------------------------------- void PlayPen_SkeletonAnimationOptimise::setupContent() { SceneNode* mTestNode[5]; mSceneMgr->setShadowTextureSize(512); mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); mSceneMgr->setShadowFarDistance(1500); mSceneMgr->setShadowColour(ColourValue(0.35, 0.35, 0.35)); //mSceneMgr->setShadowFarDistance(800); // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); Light* mLight = mSceneMgr->createLight("MainLight"); /*/ // Directional test mLight->setType(Light::LT_DIRECTIONAL); Vector3 vec(-1,-1,0); vec.normalise(); mLight->setDirection(vec); /*/ // Point test mLight->setType(Light::LT_POINT); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 200, 0))->attachObject(mLight); //*/ Entity* pEnt; // Hardware animation pEnt = mSceneMgr->createEntity( "1", "robot.mesh" ); AnimationState* a = pEnt->getAnimationState("Walk"); a->setEnabled(true); mAnimStateList.push_back(a); mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mTestNode[0]->attachObject( pEnt ); mTestNode[0]->translate(+100,-100,0); // Software animation pEnt = mSceneMgr->createEntity( "2", "robot.mesh" ); pEnt->setMaterialName("BaseWhite"); a = pEnt->getAnimationState("Walk"); a->setEnabled(true); mAnimStateList.push_back(a); mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mTestNode[1]->attachObject( pEnt ); mTestNode[1]->translate(-100,-100,0); Plane plane(Vector3::UNIT_Y, -100); MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt; pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); mCameraNode->setPosition(0,0,300); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_SpotlightViewProj::PlayPen_SpotlightViewProj() { mInfo["Title"] = "PlayPen_SpotlightViewProj"; mInfo["Description"] = "Tests spotlight camera projection."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_SpotlightViewProj::setupContent() { SceneNode* mTestNode[10]; bool worldViewProj = true; // Define programs that use spotlight projection String vpStr; vpStr = "void vp(float4 position : POSITION,\n" "out float4 oPosition : POSITION,\n" "out float4 oUV : TEXCOORD0,\n"; if (!worldViewProj) { vpStr += "uniform float4x4 world,\n" "uniform float4x4 spotlightViewProj,\n"; } else { vpStr += "uniform float4x4 spotlightWorldViewProj,\n"; } vpStr += "uniform float4x4 worldViewProj)\n" "{\n" " oPosition = mul(worldViewProj, position);\n"; if (worldViewProj) { vpStr += " oUV = mul(spotlightWorldViewProj, position);\n"; } else { vpStr += " float4 worldPos = mul(world, position);\n" " oUV = mul(spotlightViewProj, worldPos);\n"; } vpStr += "}\n"; String fpStr = "void fp(\n" "float4 uv : TEXCOORD0,\n" "uniform sampler2D tex : register(s0),\n" "out float4 oColor : COLOR)\n" "{\n" " uv = uv / uv.w;\n" " oColor = tex2D(tex, uv.xy);\n" "}\n"; HighLevelGpuProgramPtr vp = HighLevelGpuProgramManager::getSingleton() .createProgram("testvp", TRANSIENT_RESOURCE_GROUP, "cg", GPT_VERTEX_PROGRAM); vp->setSource(vpStr); vp->setParameter("profiles", "vs_1_1 arbvp1 glslv"); vp->setParameter("entry_point", "vp"); vp->load(); HighLevelGpuProgramPtr fp = HighLevelGpuProgramManager::getSingleton() .createProgram("testfp", TRANSIENT_RESOURCE_GROUP, "cg", GPT_FRAGMENT_PROGRAM); fp->setSource(fpStr); fp->setParameter("profiles", "ps_2_0 arbfp1 glslf"); fp->setParameter("entry_point", "fp"); fp->load(); MaterialPtr mat = MaterialManager::getSingleton().create("TestSpotlightProj", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setVertexProgram("testvp"); p->getVertexProgramParameters()->setNamedAutoConstant( "worldViewProj", GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX); if (worldViewProj) { p->getVertexProgramParameters()->setNamedAutoConstant( "spotlightWorldViewProj", GpuProgramParameters::ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX); } else { p->getVertexProgramParameters()->setNamedAutoConstant( "world", GpuProgramParameters::ACT_WORLD_MATRIX); p->getVertexProgramParameters()->setNamedAutoConstant( "spotlightViewProj", GpuProgramParameters::ACT_SPOTLIGHT_VIEWPROJ_MATRIX); } p->setFragmentProgram("testfp"); p->createTextureUnitState("ogrelogo.png"); Entity* pEnt; // Define a plane mesh, use the above material Plane plane; plane.normal = Vector3::UNIT_Z; plane.d = 200; MeshManager::getSingleton().createPlane("WallPlane", TRANSIENT_RESOURCE_GROUP, plane,1500,1500,100,100,true,1,5,5,Vector3::UNIT_Y); pEnt = mSceneMgr->createEntity( "5", "WallPlane" ); pEnt->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pEnt); mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mTestNode[0]->translate(0, 0, 750); Light* spot = mSceneMgr->createLight("l1"); spot->setType(Light::LT_SPOTLIGHT); mTestNode[0]->attachObject(spot); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_SRGBtexture::PlayPen_SRGBtexture() { mInfo["Title"] = "PlayPen_SRGBtexture"; mInfo["Description"] = "Tests sRGB textures."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_SRGBtexture::setupContent() { // NOTE: enable flag only turns on SRGB for texture sampling, you may // need to configure the window for the reverse conversion for consistency! MaterialPtr mat = MaterialManager::getSingleton().create("testsrgb", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setLightingEnabled(false); p->setCullingMode(CULL_NONE); TextureUnitState* t = p->createTextureUnitState("ogrelogo.png"); t->setHardwareGammaEnabled(true); Entity *e = mSceneMgr->createEntity("Plane", SceneManager::PT_PLANE); e->setMaterialName(mat->getName()); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mWindow->getViewport(0)->setBackgroundColour(ColourValue::Red); mCameraNode->setPosition(0,0,300); mCameraNode->lookAt(Vector3::ZERO, Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_StaticGeometry::PlayPen_StaticGeometry() { mInfo["Title"] = "PlayPen_StaticGeometry"; mInfo["Description"] = "Tests static geometry."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_StaticGeometry::setupContent() { // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0, 0, 0)); // Create a point light Light* l = mSceneMgr->createLight("MainLight"); l->setDiffuseColour(0.4, 0.4, 0.4); l->setSpecularColour(ColourValue::White); SceneNode* animNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); Animation* anim = mSceneMgr->createAnimation("an1", 20); anim->setInterpolationMode(Animation::IM_SPLINE); NodeAnimationTrack* track = anim->createNodeTrack(1, animNode); TransformKeyFrame* kf = track->createNodeKeyFrame(0); kf->setTranslate(Vector3(2300, 600, 2300)); kf = track->createNodeKeyFrame(5); kf->setTranslate(Vector3(-2300, 600, 2300)); kf = track->createNodeKeyFrame(10); kf->setTranslate(Vector3(-2300, 600, -2300)); kf = track->createNodeKeyFrame(15); kf->setTranslate(Vector3(2300, 600, -2300)); kf = track->createNodeKeyFrame(20); kf->setTranslate(Vector3(2300, 600, 2300)); //animNode->attachObject(l); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 600, 0))->attachObject(l); l->setAttenuation(10000, 1, 0, 0); AnimationState* animState = mSceneMgr->createAnimationState("an1"); animState->setEnabled(true); mAnimStateList.push_back(animState); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 0; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 4500,4500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("Examples/GrassFloor"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); Vector3 min(-2000,30,-2000); Vector3 max(2000,30,2000); MeshPtr msh = MeshManager::getSingleton().load("ogrehead.mesh", ASSETS_RESOURCE_GROUP); msh->buildTangentVectors(); Entity* e = mSceneMgr->createEntity("1", "ogrehead.mesh"); e->setMaterialName("Examples/BumpMapping/MultiLightSpecular"); StaticGeometry* s = mSceneMgr->createStaticGeometry("bing"); s->setCastShadows(true); s->setRegionDimensions(Vector3(500,500,500)); for (int i = 0; i < 10; ++i) { Vector3 pos; pos.x = Math::RangeRandom(min.x, max.x); pos.y = Math::RangeRandom(min.y, max.y); pos.z = Math::RangeRandom(min.z, max.z); s->addEntity(e, pos); Entity* e2 = e->clone("clone" + StringConverter::toString(i)); mSceneMgr->getRootSceneNode()->createChildSceneNode(pos+Vector3(0,60,0))->attachObject(e2); } s->build(); mCamera->setLodBias(0.5); mCameraNode->setPosition(0,400,1200); mCameraNode->setDirection(0,-0.3f,-1.2f); //mTestNode[0] = s->getRegionIterator().getNext()->getParentSceneNode(); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_StaticGeometryWithLOD::PlayPen_StaticGeometryWithLOD() { mInfo["Title"] = "PlayPen_StaticGeometryWithLOD"; mInfo["Description"] = "Tests static geometry with LODs."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_StaticGeometryWithLOD::setupContent() { //if (stencilShadows) //{ // mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); //} // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0, 0, 0)); // Create a point light Light* l = mSceneMgr->createLight("MainLight"); l->setDiffuseColour(0.4, 0.4, 0.4); l->setSpecularColour(ColourValue::White); SceneNode* animNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); Animation* anim = mSceneMgr->createAnimation("an1", 20); anim->setInterpolationMode(Animation::IM_SPLINE); NodeAnimationTrack* track = anim->createNodeTrack(1, animNode); TransformKeyFrame* kf = track->createNodeKeyFrame(0); kf->setTranslate(Vector3(2300, 600, 2300)); kf = track->createNodeKeyFrame(5); kf->setTranslate(Vector3(-2300, 600, 2300)); kf = track->createNodeKeyFrame(10); kf->setTranslate(Vector3(-2300, 600, -2300)); kf = track->createNodeKeyFrame(15); kf->setTranslate(Vector3(2300, 600, -2300)); kf = track->createNodeKeyFrame(20); kf->setTranslate(Vector3(2300, 600, 2300)); //animNode->attachObject(l); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 600, 0))->attachObject(l); l->setAttenuation(10000, 1, 0, 0); AnimationState* animState = mSceneMgr->createAnimationState("an1"); animState->setEnabled(true); mAnimStateList.push_back(animState); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 0; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 4500,4500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("Examples/GrassFloor"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); Vector3 min(-2000,30,-2000); Vector3 max(2000,30,2000); MeshPtr msh = MeshManager::getSingleton().load("knot.mesh", ASSETS_RESOURCE_GROUP); Entity* e = mSceneMgr->createEntity("1", msh->getName()); StaticGeometry* s = mSceneMgr->createStaticGeometry("bing"); s->setCastShadows(true); s->setRegionDimensions(Vector3(500,500,500)); for (int i = 0; i < 10; ++i) { Vector3 pos; pos.x = Math::RangeRandom(min.x, max.x); pos.y = Math::RangeRandom(min.y, max.y); pos.z = Math::RangeRandom(min.z, max.z); s->addEntity(e, pos); } s->build(); mCamera->setLodBias(0.5); mCameraNode->setPosition(0,400,1200); mCameraNode->setDirection(0,-0.3f,-1.2f); //mTestNode[0] = s->getRegionIterator().getNext()->getParentSceneNode(); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- // render queues #define RENDER_QUEUE_OUTLINE_GLOW_OBJECTS RENDER_QUEUE_MAIN + 1 #define RENDER_QUEUE_OUTLINE_GLOW_GLOWS RENDER_QUEUE_MAIN + 2 #define RENDER_QUEUE_FULL_GLOW_ALPHA_GLOW RENDER_QUEUE_MAIN + 3 #define RENDER_QUEUE_FULL_GLOW_GLOW RENDER_QUEUE_MAIN + 4 #define LAST_STENCIL_OP_RENDER_QUEUE RENDER_QUEUE_FULL_GLOW_GLOW // stencil values #define STENCIL_VALUE_FOR_OUTLINE_GLOW 1 #define STENCIL_VALUE_FOR_FULL_GLOW 2 #define STENCIL_FULL_MASK 0xFFFFFFFF // a Render queue listener to change the stencil mode class StencilOpQueueListener : public Ogre::RenderQueueListener { public: void renderQueueStarted(Ogre::uint8 queueGroupId, const Ogre::String& invocation, bool& skipThisInvocation) { StencilState stencil; stencil.enabled = true; stencil.compareOp = CMPF_ALWAYS_PASS; stencil.referenceValue = STENCIL_VALUE_FOR_OUTLINE_GLOW; stencil.depthStencilPassOp = SOP_REPLACE; RenderSystem* rendersys = Root::getSingleton().getRenderSystem(); switch (queueGroupId) { default: return; case RENDER_QUEUE_OUTLINE_GLOW_OBJECTS: // outline glow object rendersys->clearFrameBuffer(Ogre::FBT_STENCIL); break; case RENDER_QUEUE_OUTLINE_GLOW_GLOWS: // outline glow stencil.compareOp = CMPF_NOT_EQUAL; break; case RENDER_QUEUE_FULL_GLOW_ALPHA_GLOW: // full glow - alpha glow stencil.referenceValue = STENCIL_VALUE_FOR_FULL_GLOW; break; case RENDER_QUEUE_FULL_GLOW_GLOW: // full glow - glow stencil.compareOp = CMPF_EQUAL; stencil.referenceValue = STENCIL_VALUE_FOR_FULL_GLOW; break; } rendersys->setStencilState(stencil); } virtual void renderQueueEnded(Ogre::uint8 queueGroupId, const Ogre::String& invocation, bool& repeatThisInvocation) { if ( queueGroupId == LAST_STENCIL_OP_RENDER_QUEUE ) { Root::getSingleton().getRenderSystem()->setStencilCheckEnabled(false); } } }; //--------------------------------------------------------------------------- PlayPen_StencilGlow::PlayPen_StencilGlow() :mStencilListener(0) { mInfo["Title"] = "PlayPen_StencilGlow"; mInfo["Description"] = "Tests stencil glow effect."; addScreenshotFrame(100); } //--------------------------------------------------------------------------- PlayPen_StencilGlow::~PlayPen_StencilGlow() { if(mStencilListener) delete mStencilListener; } //--------------------------------------------------------------------------- void PlayPen_StencilGlow::setupContent(void) { // test media Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Tests"); // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); // Create a point light Light* l = mSceneMgr->createLight("MainLight"); // Accept default settings: point light, white diffuse, just set position // NB I could attach the light to a SceneNode if I wanted it to move automatically with // other objects, but I don't mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(20,80,50))->attachObject(l); // outline glow entity Entity *outlineGlowEntity = mSceneMgr->createEntity("outlineGlow", "ogrehead.mesh"); outlineGlowEntity->setRenderQueueGroup(RENDER_QUEUE_OUTLINE_GLOW_OBJECTS); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(outlineGlowEntity); // outline glow entity actual glow Ogre::Entity* actualOutlineGlowEntity = outlineGlowEntity->clone(outlineGlowEntity->getName() + "_glow"); actualOutlineGlowEntity->setRenderQueueGroup(RENDER_QUEUE_OUTLINE_GLOW_GLOWS); actualOutlineGlowEntity->setMaterialName("glow"); Ogre::SceneNode* actualOutlineGlowNode = outlineGlowEntity->getParentSceneNode()->createChildSceneNode("outlineGlowNode"); actualOutlineGlowNode->attachObject(actualOutlineGlowEntity); // normal entity Entity *normalOgreEntity = mSceneMgr->createEntity("normalOgreEntity", "ogrehead.mesh"); Ogre::SceneNode* normalOgreNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); normalOgreNode->attachObject(normalOgreEntity); normalOgreNode->setPosition(80, 0, 0); // full glow entity Entity *fullGlowEntity = mSceneMgr->createEntity("fullGlowEntity", "ogrehead.mesh"); Ogre::SceneNode* fullGlowNode = mSceneMgr->getRootSceneNode()->createChildSceneNode(); fullGlowNode->attachObject(fullGlowEntity); fullGlowNode->setPosition(-80, 0, 0); // full glow alpha glow Ogre::Entity* alphaFullGlowEntity = fullGlowEntity->clone(fullGlowEntity->getName() + "_alphaGlow"); alphaFullGlowEntity->setRenderQueueGroup(RENDER_QUEUE_FULL_GLOW_ALPHA_GLOW); alphaFullGlowEntity->setMaterialName("alpha_glow"); Ogre::SceneNode* alphaFullGlowNode = fullGlowEntity->getParentSceneNode()->createChildSceneNode("fullGlowAlphaNode"); alphaFullGlowNode->attachObject(alphaFullGlowEntity); // full glow alpha glow Ogre::Entity* glowFullGlowEntity = fullGlowEntity->clone(fullGlowEntity->getName() + "_glow"); glowFullGlowEntity->setRenderQueueGroup(RENDER_QUEUE_FULL_GLOW_GLOW); glowFullGlowEntity->setMaterialName("no_depth_check_glow"); Ogre::SceneNode* glowFullGlowNode = fullGlowEntity->getParentSceneNode()->createChildSceneNode("fullGlowGlowNode"); glowFullGlowNode->attachObject(glowFullGlowEntity); mCameraNode->setPosition(0,0,200); mCameraNode->setDirection(0,0,-1); mStencilListener = new StencilOpQueueListener(); mSceneMgr->addRenderQueueListener(mStencilListener); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_StencilShadows::PlayPen_StencilShadows() { mInfo["Title"] = "PlayPen_StencilShadows"; mInfo["Description"] = "Tests stencil shadows."; addScreenshotFrame(20); } //---------------------------------------------------------------------------- void PlayPen_StencilShadows::setupContent() { SceneNode* mTestNode[10]; mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); //mSceneMgr->setShowDebugShadows(true); mSceneMgr->setShadowDirectionalLightExtrusionDistance(1000); //mSceneMgr->setShadowColour(ColourValue(0.4, 0.25, 0.25)); //mSceneMgr->setShadowFarDistance(800); // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.0, 0.0, 0.0)); // Point light //if(pointLight) { Light* mLight = mSceneMgr->createLight("MainLight"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-400, 400, -300))->attachObject(mLight); mLight->setDiffuseColour(0.9, 0.9, 1); mLight->setSpecularColour(0.9, 0.9, 1); mLight->setAttenuation(6000, 1, 0.001, 0); } // Directional light //if (directionalLight) { OrientedLightPtr mLight = mSceneMgr->createLight("Light2"); Vector3 dir(-1, -1, 0); dir.normalise(); mLight->setType(Light::LT_DIRECTIONAL); mLight->setDirection(dir); mLight->setDiffuseColour(1, 1, 0.8); mLight->setSpecularColour(1, 1, 1); } mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); // Hardware skin Entity* pEnt; pEnt = mSceneMgr->createEntity( "1", "robot.mesh" ); AnimationState* anim = pEnt->getAnimationState("Walk"); anim->setEnabled(true); mAnimStateList.push_back(anim); mTestNode[0]->attachObject( pEnt ); // Software skin pEnt = mSceneMgr->createEntity( "12", "robot.mesh" ); anim = pEnt->getAnimationState("Walk"); anim->setEnabled(true); mAnimStateList.push_back(anim); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 0))->attachObject(pEnt); pEnt->setMaterialName("Examples/Rocky"); // test object //pEnt = mSceneMgr->createEntity("tst", "building.mesh"); //mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(300, 0, 0))->attachObject(pEnt); // Does not receive shadows pEnt = mSceneMgr->createEntity( "3", "knot.mesh" ); pEnt->setMaterialName("Examples/EnvMappedRustySteel"); MaterialPtr mat2 = MaterialManager::getSingleton().getByName("Examples/SphereMappedRustySteel"); mat2->setReceiveShadows(false); mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200, 0, -200)); mTestNode[2]->attachObject( pEnt ); // Transparent object pEnt = mSceneMgr->createEntity( "3.5", "knot.mesh" ); pEnt->setMaterialName("Examples/TransparentTest"); MaterialPtr mat3 = MaterialManager::getSingleton().getByName("Examples/TransparentTest"); pEnt->setCastShadows(false); mTestNode[3] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(350, 0, -200)); mTestNode[3]->attachObject( pEnt ); // User test /* pEnt = mSceneMgr->createEntity( "3.6", "ogre_male_endCaps.mesh" ); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 0, 100))->attachObject( pEnt ); */ MeshPtr msh = MeshManager::getSingleton().load("knot.mesh", ASSETS_RESOURCE_GROUP); unsigned short src, dest; if (!msh->suggestTangentVectorBuildParams(VES_TANGENT, src, dest)) { msh->buildTangentVectors(VES_TANGENT, src, dest); } pEnt = mSceneMgr->createEntity( "4", "knot.mesh" ); pEnt->setMaterialName("Examples/BumpMapping/MultiLightSpecular"); mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 200)); mTestNode[2]->attachObject( pEnt ); // controller based material pEnt = mSceneMgr->createEntity( "432", "knot.mesh" ); pEnt->setMaterialName("Examples/TextureEffect2"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 200, 200))->attachObject( pEnt ); ParticleSystem* pSys2 = mSceneMgr->createParticleSystem("smoke", "Examples/Smoke"); mTestNode[4] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-300, -100, 200)); mTestNode[4]->attachObject(pSys2); mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 100; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); //mCameraNode->setPosition(180, 34, 223); //mCamera->setOrientation(Quaternion(0.7265, -0.2064, 0.6304, 0.1791)); mCameraNode->setPosition(0,0,400); mCameraNode->setDirection(0,0,-1); // Create a render texture /* TexturePtr rtt = TextureManager::getSingleton().createManual("rtt0", TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, 512, 512, 0, PF_R8G8B8, TU_RENDERTARGET); rtt->getBuffer()->getRenderTarget()->addViewport(mCamera); // Create an overlay showing the rtt MaterialPtr debugMat = MaterialManager::getSingleton().create( "DebugRTT", TRANSIENT_RESOURCE_GROUP); debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false); TextureUnitState *t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState("rtt0"); t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); OverlayContainer* debugPanel = (OverlayContainer*) (OverlayManager::getSingleton().createOverlayElement("Panel", "Ogre/DebugShadowPanel")); debugPanel->_setPosition(0.6, 0); debugPanel->_setDimensions(0.4, 0.6); debugPanel->setMaterialName("DebugRTT"); Overlay* debugOverlay = OverlayManager::getSingleton().getByName("Core/DebugOverlay"); debugOverlay->add2D(debugPanel);*/ } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_StencilShadowsMixedOpSubMeshes::PlayPen_StencilShadowsMixedOpSubMeshes() { mInfo["Title"] = "PlayPen_StencilShadowsMixedOpSubMeshes"; mInfo["Description"] = "Tests mixed operation submeshes."; addScreenshotFrame(20); } //---------------------------------------------------------------------------- void PlayPen_StencilShadowsMixedOpSubMeshes::setupContent() { mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_MODULATIVE); //mSceneMgr->setShadowTechnique(SHADOWTYPE_STENCIL_ADDITIVE); //mSceneMgr->setShowDebugShadows(true); mSceneMgr->setShadowDirectionalLightExtrusionDistance(1000); //mSceneMgr->setShadowFarDistance(800); // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.0, 0.0, 0.0)); Light* mLight; // Point light //if(pointLight) //{ mLight = mSceneMgr->createLight("MainLight"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-400,400,-300))->attachObject(mLight); mLight->setDiffuseColour(0.9, 0.9, 1); mLight->setSpecularColour(0.9, 0.9, 1); mLight->setAttenuation(6000,1,0.001,0); //} // Directional light //if (directionalLight) //{ /*mLight = mSceneMgr->createLight("Light2"); Vector3 dir(-1,-1,0); dir.normalise(); mLight->setType(Light::LT_DIRECTIONAL); mLight->setDirection(dir); mLight->setDiffuseColour(1, 1, 0.8); mLight->setSpecularColour(1, 1, 1);*/ //} mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 100; MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500,1500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("2 - Default"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); //mCameraNode->setPosition(180, 34, 223); //mCamera->setOrientation(Quaternion(0.7265, -0.2064, 0.6304, 0.1791)); ManualObject* man = mSceneMgr->createManualObject("testMO_"); man->begin("2 - Default"); man->position(0, 200, 0); man->position(0, 50, 100); man->position(100, 50, -100); man->position(-100, 50, -100); man->triangle(0, 1, 2); man->triangle(0, 2, 3); man->triangle(0, 3, 1); man->end(); man->begin("2 - Default", RenderOperation::OT_LINE_STRIP); man->position(0, 200, 0); man->position(50, 250, 0); man->position(200, 300, 0); man->index(0); man->index(1); man->index(2); man->end(); MeshPtr msh = man->convertToMesh("testMO.mesh_2"); Entity* e = mSceneMgr->createEntity("34", "testMO.mesh_2"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(e); mCameraNode->setPosition(100,320,600); mCameraNode->lookAt(Vector3(0, 120, 0), Node::TS_PARENT); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_SubEntityVisibility::PlayPen_SubEntityVisibility() { mInfo["Title"] = "PlayPen_SubEntityVisibility"; mInfo["Description"] = "Tests sub entity visibility settings."; addScreenshotFrame(250); } //---------------------------------------------------------------------------- void PlayPen_SubEntityVisibility::setupContent() { SceneNode* mTestNode[5]; // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); // Create a point light OrientedLightPtr l = mSceneMgr->createLight("MainLight"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(-Vector3::UNIT_Y); mTestNode[0] = (SceneNode*)mSceneMgr->getRootSceneNode()->createChild(); Entity* pEnt = mSceneMgr->createEntity( "1", "ogrehead.mesh" ); mTestNode[0]->attachObject( pEnt ); pEnt->getSubEntity(1)->setVisible(false); mCameraNode->setPosition(0,0,125); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_SuppressedShadows::PlayPen_SuppressedShadows() { mInfo["Title"] = "PlayPen_SuppressedShadows"; mInfo["Description"] = "Tests suppressing shadows for a viewport."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_SuppressedShadows::setupContent() { mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); // Setup lighting mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); OrientedLightPtr light = mSceneMgr->createLight("MainLight"); light->setType(Light::LT_DIRECTIONAL); Vector3 dir(-1, -1, 0.5); dir.normalise(); light->setDirection(dir); // Create a skydome //mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8); // Create a floor plane mesh Plane plane(Vector3::UNIT_Y, 0.0); MeshManager::getSingleton().createPlane( "FloorPlane", TRANSIENT_RESOURCE_GROUP, plane, 200000, 200000, 20, 20, true, 1, 500, 500, Vector3::UNIT_Z); // Add a floor to the scene Entity* entity = mSceneMgr->createEntity("floor", "FloorPlane"); entity->setMaterialName("Examples/RustySteel"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(entity); entity->setCastShadows(false); // Add the mandatory ogre head entity = mSceneMgr->createEntity("head", "ogrehead.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0.0, 10.0, 0.0))->attachObject(entity); // Position and orient the camera mCameraNode->setPosition(-100.0, 50.0, 90.0); mCameraNode->lookAt(Vector3(0.0, 10.0, -35.0), Node::TS_PARENT); // Add an additional viewport on top of the other one Viewport* pip = mWindow->addViewport(mCamera, 1, 0.7, 0.0, 0.3, 0.3); // Create a render queue invocation sequence for the pip viewport RenderQueueInvocationSequence* invocationSequence = mRoot->createRenderQueueInvocationSequence("pip"); // Add an invocation to the sequence RenderQueueInvocation* invocation = invocationSequence->add(RENDER_QUEUE_MAIN, "main"); // Disable render state changes and shadows for that invocation //invocation->setSuppressRenderStateChanges(true); invocation->setSuppressShadows(true); // Set the render queue invocation sequence for the pip viewport pip->setRenderQueueInvocationSequenceName("pip"); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_TextureShadows::PlayPen_TextureShadows() { mInfo["Title"] = "PlayPen_TextureShadows"; mInfo["Description"] = "Tests texture shadows."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_TextureShadows::cleanupContent() { clearDebugTextureOverlays(); } //---------------------------------------------------------------------------- void PlayPen_TextureShadows::setupContent() { SceneNode* mTestNode[10]; mSceneMgr->setShadowTextureSize(1024); mSceneMgr->setShadowTextureCount(1); //mSceneMgr->setShadowTechnique(tech); mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); //FocusedShadowCameraSetup* lispsmSetup = new FocusedShadowCameraSetup(); //LiSPSMShadowCameraSetup* lispsmSetup = new LiSPSMShadowCameraSetup(); //lispsmSetup->setOptimalAdjustFactor(1.5); //mSceneMgr->setShadowCameraSetup(ShadowCameraSetupPtr(lispsmSetup)); mSceneMgr->setShadowFarDistance(1000); mSceneMgr->setShadowColour(ColourValue(0.35, 0.35, 0.35)); //mSceneMgr->setShadowFarDistance(800); // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); OrientedLightPtr mLight = mSceneMgr->createLight("MainLight"); // Directional test //if (directional) //{ mLight->setType(Light::LT_DIRECTIONAL); Vector3 vec(-1,-1,0); vec.normalise(); mLight->setDirection(vec); //} // Spotlight test /*else { mLight->setType(Light::LT_SPOTLIGHT); mLight->setAttenuation(1500, 1, 0, 0); mLight->setDiffuseColour(1.0, 1.0, 0.8); mTestNode[0] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); mTestNode[0]->setPosition(800,600,0); mTestNode[0]->lookAt(Vector3(0,0,0), Node::TS_WORLD, Vector3::UNIT_Z); mTestNode[0]->attachObject(mLight); }*/ mTestNode[1] = mSceneMgr->getRootSceneNode()->createChildSceneNode(); Entity* pEnt; pEnt = mSceneMgr->createEntity( "1", "robot.mesh" ); //pEnt->setRenderingDistance(100); AnimationState* mAnimState = pEnt->getAnimationState("Walk"); mAnimState->setEnabled(true); mAnimStateList.push_back(mAnimState); //pEnt->setMaterialName("2 - Default"); mTestNode[1]->attachObject( pEnt ); mTestNode[1]->translate(0,-100,0); Quaternion quat2; quat2.FromAngleAxis(Degree(360), Vector3::UNIT_Y); pEnt = mSceneMgr->createEntity( "3", "knot.mesh" ); mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-200, 0, -200)); mTestNode[2]->attachObject( pEnt ); createRandomEntityClones(pEnt, 20, Vector3(-1000,0,-1000), Vector3(1000,0,1000), mSceneMgr); // Transparent object (can force cast shadows) pEnt = mSceneMgr->createEntity( "3.5", "knot.mesh" ); MaterialPtr tmat = MaterialManager::getSingleton().create("TestAlphaTransparency", TRANSIENT_RESOURCE_GROUP); tmat->setTransparencyCastsShadows(true); Pass* tpass = tmat->getTechnique(0)->getPass(0); tpass->setAlphaRejectSettings(CMPF_GREATER, 150); tpass->setSceneBlending(SBT_TRANSPARENT_ALPHA); tpass->createTextureUnitState("gras_02.png"); tpass->setCullingMode(CULL_NONE); pEnt->setMaterialName("TestAlphaTransparency"); mTestNode[3] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(350, 0, -200)); mTestNode[3]->attachObject( pEnt ); pEnt = mSceneMgr->createEntity( "4", "knot.mesh" ); mTestNode[2] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(100, 0, 200)); mTestNode[2]->attachObject( pEnt ); mSceneMgr->setSkyBox(true, "Examples/CloudyNoonSkyBox"); MovablePlane movablePlane(Vector3::UNIT_Y, 100); MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, movablePlane, 2500,2500,10,10,true,1,5,5,Vector3::UNIT_Z); Entity* pPlaneEnt; pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); if (SHADOWTYPE_TEXTURE_ADDITIVE & SHADOWDETAILTYPE_INTEGRATED) { pPlaneEnt->setMaterialName("Examples/Plane/IntegratedShadows"); } else { pPlaneEnt->setMaterialName("2 - Default"); } pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); addTextureShadowDebugOverlay(1,mSceneMgr); /* ParticleSystem* pSys2 = mSceneMgr->createParticleSystem("smoke", "Examples/Smoke"); mTestNode[4] = mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(-300, -100, 200)); mTestNode[4]->attachObject(pSys2); */ mCameraNode->setPosition(0, 1000, 500); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); mCamera->setFarClipDistance(10000); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_TextureShadowsCustomCasterMat::PlayPen_TextureShadowsCustomCasterMat() { mInfo["Title"] = "PlayPen_TextureShadowsCustomCasterMat"; mInfo["Description"] = "Tests texture shadows with a custom caster material."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_TextureShadowsCustomCasterMat::setupContent() { PlayPen_TextureShadows::setupContent(); String customCasterMatVp = "void customCasterVp(float4 position : POSITION,\n" "out float4 oPosition : POSITION,\n" "uniform float4x4 worldViewProj)\n" "{\n" " oPosition = mul(worldViewProj, position);\n" "}\n"; String customCasterMatFp = "void customCasterFp(\n" "out float4 oColor : COLOR)\n" "{\n" " oColor = float4(1,1,0,1); // just a test\n" "}\n"; HighLevelGpuProgramPtr vp = HighLevelGpuProgramManager::getSingleton() .createProgram("CustomShadowCasterVp", TRANSIENT_RESOURCE_GROUP, "cg", GPT_VERTEX_PROGRAM); vp->setSource(customCasterMatVp); vp->setParameter("profiles", "vs_1_1 arbvp1 glslv"); vp->setParameter("entry_point", "customCasterVp"); vp->load(); HighLevelGpuProgramPtr fp = HighLevelGpuProgramManager::getSingleton() .createProgram("CustomShadowCasterFp", TRANSIENT_RESOURCE_GROUP, "cg", GPT_FRAGMENT_PROGRAM); fp->setSource(customCasterMatFp); fp->setParameter("profiles", "ps_1_1 arbfp1 glslf"); fp->setParameter("entry_point", "customCasterFp"); fp->load(); MaterialPtr mat = MaterialManager::getSingleton().create("CustomShadowCaster", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setVertexProgram("CustomShadowCasterVp"); p->getVertexProgramParameters()->setNamedAutoConstant( "worldViewProj", GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX); p->setFragmentProgram("CustomShadowCasterFp"); mSceneMgr->setShadowTextureCasterMaterial(mat); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_TextureShadowsCustomReceiverMat::PlayPen_TextureShadowsCustomReceiverMat() { mInfo["Title"] = "PlayPen_TextureShadowsCustomReceiverMat"; mInfo["Description"] = "Tests texture shadows with a custom receiver material."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_TextureShadowsCustomReceiverMat::setupContent() { PlayPen_TextureShadows::setupContent(); String customReceiverMatVp = "void customReceiverVp(float4 position : POSITION,\n" "out float4 oPosition : POSITION,\n" "out float2 oUV : TEXCOORD0,\n" "uniform float4x4 texViewProj,\n" "uniform float4x4 worldViewProj)\n" "{\n" " oPosition = mul(worldViewProj, position);\n" " float4 suv = mul(texViewProj, position);\n" " oUV = suv.xy / suv.w;\n" "}\n"; String customReceiverMatFp = "void customReceiverFp(\n" "float2 uv : TEXCOORD0,\n" "uniform sampler2D shadowTex : register(s0),\n" "out float4 oColor : COLOR)\n" "{\n" " float4 shadow = tex2D(shadowTex, uv);\n" " oColor = shadow * float4(1,0,1,1); // just a test\n" "}\n"; HighLevelGpuProgramPtr vp = HighLevelGpuProgramManager::getSingleton() .createProgram("CustomShadowReceiverVp", TRANSIENT_RESOURCE_GROUP, "cg", GPT_VERTEX_PROGRAM); vp->setSource(customReceiverMatVp); vp->setParameter("profiles", "vs_1_1 arbvp1 glslv"); vp->setParameter("entry_point", "customReceiverVp"); vp->load(); HighLevelGpuProgramPtr fp = HighLevelGpuProgramManager::getSingleton() .createProgram("CustomShadowReceiverFp", TRANSIENT_RESOURCE_GROUP, "cg", GPT_FRAGMENT_PROGRAM); fp->setSource(customReceiverMatFp); fp->setParameter("profiles", "ps_1_1 arbfp1 glslf"); fp->setParameter("entry_point", "customReceiverFp"); fp->load(); MaterialPtr mat = MaterialManager::getSingleton().create("CustomShadowReceiver", TRANSIENT_RESOURCE_GROUP); Pass* p = mat->getTechnique(0)->getPass(0); p->setVertexProgram("CustomShadowReceiverVp"); p->getVertexProgramParameters()->setNamedAutoConstant( "worldViewProj", GpuProgramParameters::ACT_WORLDVIEWPROJ_MATRIX); p->getVertexProgramParameters()->setNamedAutoConstant( "texViewProj", GpuProgramParameters::ACT_TEXTURE_VIEWPROJ_MATRIX); p->setFragmentProgram("CustomShadowReceiverFp"); p->createTextureUnitState(); // shadow texture will populate mSceneMgr->setShadowTextureReceiverMaterial(mat); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_TextureShadowsIntegrated::PlayPen_TextureShadowsIntegrated() { mInfo["Title"] = "PlayPen_TextureShadowsIntegrated"; mInfo["Description"] = "Tests integrated texture shadows."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_TextureShadowsIntegrated::cleanupContent() { clearDebugTextureOverlays(); } //---------------------------------------------------------------------------- void PlayPen_TextureShadowsIntegrated::setupContent() { mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_ADDITIVE_INTEGRATED); //mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); MaterialManager::getSingleton().setDefaultTextureFiltering(TFO_ANISOTROPIC); MaterialManager::getSingleton().setDefaultAnisotropy(5); mSceneMgr->setShadowTextureSettings(1024, 2); mSceneMgr->setAmbientLight(ColourValue::Black); Light* l = mSceneMgr->createLight("Spot1"); l->setType(Light::LT_SPOTLIGHT); l->setAttenuation(5000,1,0,0); l->setSpotlightRange(Degree(30),Degree(45),1.0f); SceneNode* lightNode1 = mSceneMgr->getRootSceneNode()->createChildSceneNode(); lightNode1->attachObject(l); lightNode1->setPosition(400, 250, 500); lightNode1->lookAt(Vector3(0,-200,0), Node::TS_WORLD); l->setDiffuseColour(0.7, 0.7, 0.5); l = mSceneMgr->createLight("Spot2"); l->setAttenuation(5000,1,0,0); /* // spotlight */ l->setType(Light::LT_SPOTLIGHT); l->setSpotlightRange(Degree(30),Degree(45),1.0f); /**/ // point SceneNode* lightNode2 = mSceneMgr->getRootSceneNode()->createChildSceneNode(); lightNode2->attachObject(l); lightNode2->setPosition(-500, 200, 500); lightNode2->lookAt(Vector3(0,-200,0), Node::TS_WORLD); /* // directional l->setType(Light::LT_DIRECTIONAL); Vector3 dir(0.5, -1, 0.5); dir.normalise(); l->setDirection(dir); */ l->setDiffuseColour(1, 0.2, 0.2); /* // Test spot 3 l = mSceneMgr->createLight("Spot3"); l->setType(Light::LT_SPOTLIGHT); l->setAttenuation(5000,1,0,0); l->setSpotlightRange(Degree(30),Degree(45),1.0f); SceneNode* lightNode3 = mSceneMgr->getRootSceneNode()->createChildSceneNode(); lightNode3->attachObject(l); lightNode3->setPosition(700, 250, 500); lightNode3->lookAt(Vector3(0,-200,0), Node::TS_WORLD); l->setDiffuseColour(0.0, 0.7, 1.0); */ // Create a basic plane to have something in the scene to look at Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 100; MeshPtr msh = MeshManager::getSingleton().createPlane("Myplane_IS", TRANSIENT_RESOURCE_GROUP, plane, 4500,4500,100,100,true,1,40,40,Vector3::UNIT_Z); msh->buildTangentVectors(VES_TANGENT); Entity* pPlaneEnt; pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane_IS" ); //pPlaneEnt->setMaterialName("Examples/OffsetMapping/Specular"); pPlaneEnt->setMaterialName("Examples/OffsetMapping/IntegratedShadows"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); pPlaneEnt = mSceneMgr->createEntity( "plane2", "Myplane_IS" ); //pPlaneEnt->setMaterialName("Examples/OffsetMapping/Specular"); pPlaneEnt->setMaterialName("Examples/OffsetMapping/IntegratedShadows"); pPlaneEnt->setCastShadows(false); SceneNode* n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); n->roll(Degree(90)); n->translate(100,0,0); //n->attachObject(pPlaneEnt); pPlaneEnt = mSceneMgr->createEntity( "plane3", "Myplane_IS" ); //pPlaneEnt->setMaterialName("Examples/OffsetMapping/Specular"); pPlaneEnt->setMaterialName("Examples/OffsetMapping/IntegratedShadows"); pPlaneEnt->setCastShadows(false); n = mSceneMgr->getRootSceneNode()->createChildSceneNode(); n->pitch(Degree(90)); n->yaw(Degree(-90)); n->translate(0,0,-100); n->attachObject(pPlaneEnt); mCameraNode->setPosition(-50, 500, 1000); mCameraNode->lookAt(Vector3(Vector3(-50, -100, 0)), Node::TS_PARENT); Entity* ent = mSceneMgr->createEntity("athene", "athene.mesh"); ent->setMaterialName("Examples/Athene/NormalMapped"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,-20,0))->attachObject(ent); addTextureShadowDebugOverlay(2, mSceneMgr); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_TextureShadowsIntegratedPSSM::PlayPen_TextureShadowsIntegratedPSSM() { mInfo["Title"] = "PlayPen_TextureShadowsIntegratedPSSM"; mInfo["Description"] = "Tests integrated parallel split shadow mapping."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_TextureShadowsIntegratedPSSM::cleanupContent() { clearDebugTextureOverlays(); } //---------------------------------------------------------------------------- void PlayPen_TextureShadowsIntegratedPSSM::setupContent() { mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE_INTEGRATED); // 3 textures per directional light mSceneMgr->setShadowTextureCountPerLightType(Ogre::Light::LT_DIRECTIONAL, 3); mSceneMgr->setShadowTextureSettings(512, 3, PF_FLOAT32_R); mSceneMgr->setShadowTextureSelfShadow(true); // Set up caster material - this is just a standard depth/shadow map caster mSceneMgr->setShadowTextureCasterMaterial( MaterialManager::getSingleton().getByName("PSSM/shadow_caster", "General")); // shadow camera setup PSSMShadowCameraSetup* pssmSetup = new PSSMShadowCameraSetup(); pssmSetup->calculateSplitPoints(3, 40, mCamera->getFarClipDistance()); pssmSetup->setSplitPadding(80); pssmSetup->setOptimalAdjustFactor(0, 2); pssmSetup->setOptimalAdjustFactor(1, 1); pssmSetup->setOptimalAdjustFactor(2, 0.5); mSceneMgr->setShadowCameraSetup(ShadowCameraSetupPtr(pssmSetup)); mSceneMgr->setAmbientLight(ColourValue(0.3, 0.3, 0.3)); OrientedLightPtr l = mSceneMgr->createLight("Dir"); l->setType(Light::LT_DIRECTIONAL); Vector3 dir(0.3, -1, 0.2); dir.normalise(); l->setDirection(dir); // Create a basic plane to have something in the scene to look at Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 100; MeshPtr msh = MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 4500,4500,100,100,true,1,40,40,Vector3::UNIT_Z); msh->buildTangentVectors(VES_TANGENT); Entity* pPlaneEnt; pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("Examples/BumpyMetal"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); mCameraNode->setPosition(-50, 500, 1000); mCameraNode->lookAt(Vector3(Vector3(-50, -100, 0)), Node::TS_PARENT); Entity* ent = mSceneMgr->createEntity("knot", "knot.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,0,0))->attachObject(ent); createRandomEntityClones(ent, 20, Vector3(-1000,0,-1000), Vector3(1000,0,1000), mSceneMgr); #ifdef OGRE_BUILD_COMPONENT_RTSHADERSYSTEM // Make this viewport work with shader generator scheme. mViewport->setMaterialScheme(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); RTShader::ShaderGenerator& rtShaderGen = RTShader::ShaderGenerator::getSingleton(); RTShader::RenderState* schemRenderState = rtShaderGen.getRenderState(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME); auto subRenderState = rtShaderGen.createSubRenderState<RTShader::IntegratedPSSM3>(); subRenderState->setSplitPoints(pssmSetup->getSplitPoints()); schemRenderState->addTemplateSubRenderState(subRenderState); #endif addTextureShadowDebugOverlay(3, mSceneMgr); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_TextureShadowsTransparentCaster::PlayPen_TextureShadowsTransparentCaster() { mInfo["Title"] = "PlayPen_TextureShadowsTransparentCaster"; mInfo["Description"] = "Tests transparent shadow casters."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_TextureShadowsTransparentCaster::setupContent() { mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); mSceneMgr->setShadowCameraSetup(FocusedShadowCameraSetup::create()); mSceneMgr->setShadowTextureSettings(1024, 1, PF_L8); // New depth shadow mapping String CUSTOM_ROCKWALL_MATERIAL("Examples/Rockwall"); mSceneMgr->setShadowDirLightTextureOffset(0.2); mSceneMgr->setShadowFarDistance(500); // Create a basic plane to have something in the scene to look at Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 100; MeshPtr msh = MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 4500,4500,100,100,true,1,40,40,Vector3::UNIT_Z); Entity* pPlaneEnt; pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName(CUSTOM_ROCKWALL_MATERIAL); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); // Reorient the plane and create a plane mesh for the test planes plane.normal = Vector3::UNIT_X; MeshManager::getSingleton().createPlane("Test_Plane", TRANSIENT_RESOURCE_GROUP, plane, 50.0, 50.0); const String GRASSMAT("Examples/GrassBlades"); // Add test plane entities to the scene Entity* entity = mSceneMgr->createEntity("GrassBlades0", "Test_Plane"); entity->setMaterialName(GRASSMAT); mSceneMgr->getRootSceneNode()->createChildSceneNode( Vector3(0.0, -100.0+25.0, 0.0))->attachObject(entity); entity = mSceneMgr->createEntity("GrassBlades1", "Test_Plane"); entity->setMaterialName(GRASSMAT); mSceneMgr->getRootSceneNode()->createChildSceneNode( Vector3(0.0, -100.0+25.0, -20.0))->attachObject(entity); entity = mSceneMgr->createEntity("GrassBlades2", "Test_Plane"); entity->setMaterialName(GRASSMAT); mSceneMgr->getRootSceneNode()->createChildSceneNode( Vector3(0.0, -100.0+25.0, -40.0))->attachObject(entity); // Add test plane entities to the scene, shadowed partially by athene mesh entity = mSceneMgr->createEntity("GrassBlades3", "Test_Plane"); entity->setMaterialName(GRASSMAT); mSceneMgr->getRootSceneNode()->createChildSceneNode( Vector3(-80.0, -100.0+25.0, 0.0))->attachObject(entity); entity = mSceneMgr->createEntity("GrassBlades4", "Test_Plane"); entity->setMaterialName(GRASSMAT); mSceneMgr->getRootSceneNode()->createChildSceneNode( Vector3(-130.0, -100.0+25.0, -20.0))->attachObject(entity); entity = mSceneMgr->createEntity("GrassBlades5", "Test_Plane"); entity->setMaterialName(GRASSMAT); mSceneMgr->getRootSceneNode()->createChildSceneNode( Vector3(-180.0, -100.0+25.0, -40.0))->attachObject(entity); // Add test plane entities to the scene, one after another entity = mSceneMgr->createEntity("GrassBlades6", "Test_Plane"); entity->setMaterialName(GRASSMAT); mSceneMgr->getRootSceneNode()->createChildSceneNode( Vector3(-260.0, -100.0+25.0, 0.0))->attachObject(entity); entity = mSceneMgr->createEntity("GrassBlades7", "Test_Plane"); entity->setMaterialName(GRASSMAT); mSceneMgr->getRootSceneNode()->createChildSceneNode( Vector3(-260.0, -100.0+25.0, -10.0))->attachObject(entity); entity = mSceneMgr->createEntity("GrassBlades8", "Test_Plane"); entity->setMaterialName(GRASSMAT); mSceneMgr->getRootSceneNode()->createChildSceneNode( Vector3(-260.0, -100.0+25.0, -20.0))->attachObject(entity); // Add test plane entities to the scene, alone with other material const String GRASSMAT_CUSTOM_DEFAULT_CUSTOM("Examples/GrassBlades"); const String GRASSMAT_CUSTOM_NOSPECIAL_CUSTOM("Examples/GrassBlades"); const String GRASSMAT_ORIG("Examples/GrassBlades"); entity = mSceneMgr->createEntity("GrassBlades9", "Test_Plane"); entity->setMaterialName(GRASSMAT_CUSTOM_DEFAULT_CUSTOM); mSceneMgr->getRootSceneNode()->createChildSceneNode( Vector3(-80.0, -100.0+25.0, -80.0))->attachObject(entity); entity = mSceneMgr->createEntity("GrassBlades10", "Test_Plane"); entity->setMaterialName(GRASSMAT_CUSTOM_NOSPECIAL_CUSTOM); mSceneMgr->getRootSceneNode()->createChildSceneNode( Vector3(-130.0, -100.0+25.0, -90.0))->attachObject(entity); entity = mSceneMgr->createEntity("GrassBlades11", "Test_Plane"); entity->setMaterialName(GRASSMAT_ORIG); mSceneMgr->getRootSceneNode()->createChildSceneNode( Vector3(-180.0, -100.0+25.0, -90.0))->attachObject(entity); Entity* ent = mSceneMgr->createEntity("athene", "athene.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0,-20,-20))->attachObject(ent); // Position and orient the camera mCameraNode->setPosition(100,50,150); mCameraNode->lookAt(Vector3(-50, -25, 0), Node::TS_PARENT); OrientedLightPtr l = mSceneMgr->createLight("Dir1"); l->setType(Light::LT_DIRECTIONAL); Vector3 dir1(-2.5, -0.7, -0.5); dir1.normalise(); l->setDirection(dir1); l->setDiffuseColour(1.0, 1.0, 1.0); mSceneMgr->setAmbientLight(ColourValue(0.0, 0.0, 0.2)); //addTextureShadowDebugOverlay(1, mSceneMgr); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_TransparencyMipMaps::PlayPen_TransparencyMipMaps() { mInfo["Title"] = "PlayPen_TransparencyMipMaps"; mInfo["Description"] = "Tests transparent materials with mipmaps."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_TransparencyMipMaps::setupContent() { MaterialPtr mat = MaterialManager::getSingleton().create("test", TRANSIENT_RESOURCE_GROUP); // known png with alpha Pass* pass = mat->getTechnique(0)->getPass(0); pass->createTextureUnitState("sdk_logo.png"); pass->setSceneBlending(SBT_TRANSPARENT_ALPHA); // alpha blend pass->setDepthWriteEnabled(false); // alpha reject //pass->setDepthWriteEnabled(true); //pass->setAlphaRejectSettings(CMPF_LESS, 128); // Define a floor plane mesh Plane p; p.normal = Vector3::UNIT_Y; p.d = 200; MeshManager::getSingleton().createPlane("FloorPlane", TRANSIENT_RESOURCE_GROUP, p,2000,2000,1,1,true,1,5,5,Vector3::UNIT_Z); // Create an entity (the floor) Entity* ent = mSceneMgr->createEntity("floor", "FloorPlane"); ent->setMaterialName("test"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8); mSceneMgr->setAmbientLight(ColourValue::White); { Real alphaLevel = 0.5f; MaterialPtr alphamat = MaterialManager::getSingleton().create("testy", TRANSIENT_RESOURCE_GROUP); Pass* alphaPass = alphamat->getTechnique(0)->getPass(0); alphaPass->setSceneBlending(SBT_TRANSPARENT_ALPHA); alphaPass->setDepthWriteEnabled(false); TextureUnitState* t = alphaPass->createTextureUnitState(); t->setAlphaOperation(LBX_SOURCE1, LBS_MANUAL, LBS_CURRENT, alphaLevel); ent = mSceneMgr->createEntity("asd", "ogrehead.mesh"); ent->setMaterialName("testy"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(ent); } mCameraNode->setPosition(0,0,1000); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_VertexTexture::PlayPen_VertexTexture() { mInfo["Title"] = "PlayPen_VertexTexture"; mInfo["Description"] = "Tests vertex texture rendering (DX only)."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_VertexTexture::setupContent() { //TODO DirectX only right now - add OpenGL. Light* l = mSceneMgr->createLight("MainLight"); l->setType(Light::LT_POINT); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0, 200, 0))->attachObject(l); // Create single-channel floating point texture, no mips TexturePtr tex = TextureManager::getSingleton().createManual( "vertexTexture", TRANSIENT_RESOURCE_GROUP, TEX_TYPE_2D, 128, 128, 0, PF_FLOAT32_R); float* pData = static_cast<float*>( tex->getBuffer()->lock(HardwareBuffer::HBL_DISCARD)); // write concentric circles into the texture for (int y = -64; y < 64; ++y) { for (int x = -64; x < 64; ++x) { float val = Math::Sqrt(x*x + y*y); // repeat every 20 pixels val = val * Math::TWO_PI / 20.0f; *pData++ = Math::Sin(val); } } tex->getBuffer()->unlock(); String progSource = "#include <HLSL_SM4Support.hlsl>\n" "SAMPLER2D(heightmap, 1);\n" "void main(\n" "float4 pos : POSITION,\n" "float2 uv1 : TEXCOORD0,\n" "uniform float4x4 world, \n" "uniform float4x4 viewProj,\n" "uniform float heightscale,\n" "out float4 oPos : POSITION,\n" "out float2 oUv1 : TEXCOORD0,\n" "out float4 col : COLOR)\n" "{\n" "oPos = mul(world, pos);\n" "// tex2Dlod since no mip\n" "float4 t = float4(0,0,0,0);\n" "t.xy = uv1.xy;\n" "float height = tex2Dlod(heightmap, t);\n" "oPos.y = oPos.y + (height * heightscale);\n" "oPos = mul(viewProj, oPos);\n" "oUv1 = uv1;\n" "col = float4(1,1,1,1);\n" "}\n"; HighLevelGpuProgramPtr prog = HighLevelGpuProgramManager::getSingleton().createProgram( "TestVertexTextureFetch", TRANSIENT_RESOURCE_GROUP, "hlsl", GPT_VERTEX_PROGRAM); prog->setSource(progSource); prog->setParameter("target", "vs_3_0"); prog->setVertexTextureFetchRequired(true); prog->setParameter("entry_point", "main"); prog->load(); MaterialPtr mat = MaterialManager::getSingleton().create("TestVertexTexture", TRANSIENT_RESOURCE_GROUP); Pass* pass = mat->getTechnique(0)->getPass(0); pass->setLightingEnabled(false); pass->setVertexProgram("TestVertexTextureFetch"); pass->setFragmentProgram("Ogre/BasicFragmentPrograms/DiffuseOneTextureHLSL"); GpuProgramParametersSharedPtr vp = pass->getVertexProgramParameters(); vp->setNamedAutoConstant("world", GpuProgramParameters::ACT_WORLD_MATRIX); vp->setNamedAutoConstant("viewProj", GpuProgramParameters::ACT_VIEWPROJ_MATRIX); vp->setNamedConstant("heightscale", 30.0f); // regular texture pass->createTextureUnitState("BumpyMetal.jpg"); // vertex texture TextureUnitState* t = pass->createTextureUnitState("vertexTexture"); t->setBindingType(TextureUnitState::BT_VERTEX); Plane plane; plane.normal = Vector3::UNIT_Y; plane.d = 100; // 128 x 128 segment plane MeshManager::getSingleton().createPlane("Myplane", TRANSIENT_RESOURCE_GROUP, plane, 1500,1500,128,128,true,1,1,1,Vector3::UNIT_Z); Entity* pPlaneEnt; pPlaneEnt = mSceneMgr->createEntity( "plane", "Myplane" ); pPlaneEnt->setMaterialName("TestVertexTexture"); pPlaneEnt->setCastShadows(false); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(pPlaneEnt); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_ViewportNoShadows::PlayPen_ViewportNoShadows() { mInfo["Title"] = "PlayPen_ViewportNoShadows"; mInfo["Description"] = "Tests disabling shadows for a viewport."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_ViewportNoShadows::setupContent() { mSceneMgr->setShadowTechnique(SHADOWTYPE_TEXTURE_MODULATIVE); // Setup lighting mSceneMgr->setAmbientLight(ColourValue(0.2, 0.2, 0.2)); OrientedLightPtr light = mSceneMgr->createLight("MainLight"); light->setType(Light::LT_DIRECTIONAL); Vector3 dir(-1, -1, 0.5); dir.normalise(); light->setDirection(dir); // Create a skydome //mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8); // Create a floor plane mesh Plane plane(Vector3::UNIT_Y, 0.0); MeshManager::getSingleton().createPlane( "FloorPlane", TRANSIENT_RESOURCE_GROUP, plane, 200000, 200000, 20, 20, true, 1, 500, 500, Vector3::UNIT_Z); // Add a floor to the scene Entity* entity = mSceneMgr->createEntity("floor", "FloorPlane"); entity->setMaterialName("Examples/RustySteel"); mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(entity); entity->setCastShadows(false); // Add the mandatory ogre head entity = mSceneMgr->createEntity("head", "ogrehead.mesh"); mSceneMgr->getRootSceneNode()->createChildSceneNode(Vector3(0.0, 10.0, 0.0))->attachObject(entity); // Position and orient the camera mCameraNode->setPosition(-100.0, 50.0, 90.0); mCameraNode->lookAt(Vector3(0.0, 10.0, -35.0), Node::TS_WORLD); // Add an additional viewport on top of the other one Viewport* pip = mWindow->addViewport(mCamera, 1, 0.7, 0.0, 0.3, 0.3); pip->setShadowsEnabled(false); } //---------------------------------------------------------------------------- //---------------------------------------------------------------------------- PlayPen_WindowedViewportMode::PlayPen_WindowedViewportMode() { mInfo["Title"] = "PlayPen_WindowedViewportMode"; mInfo["Description"] = "Tests windowed viewport."; addScreenshotFrame(10); } //---------------------------------------------------------------------------- void PlayPen_WindowedViewportMode::setupContent() { Ogre::SceneNode* mTestNode[5]; // Set ambient light mSceneMgr->setAmbientLight(ColourValue(0.5, 0.5, 0.5)); // Create a point light OrientedLightPtr l = mSceneMgr->createLight("MainLight"); l->setType(Light::LT_DIRECTIONAL); l->setDirection(-Vector3::UNIT_Y); mTestNode[0] = (SceneNode*)mSceneMgr->getRootSceneNode()->createChild(); Entity* pEnt = mSceneMgr->createEntity( "1", "ogrehead.mesh" ); mTestNode[0]->attachObject( pEnt ); mCamera->setWindow(0,0,0.5,0.5); mCameraNode->setPosition(0,0,125); } PlayPen_BillboardText::PlayPen_BillboardText() { mInfo["Title"] = "PlayPen_BillboardText"; mInfo["Description"] = "Tests setting billboard text"; addScreenshotFrame(1); } //---------------------------------------------------------------------------- void PlayPen_BillboardText::setupContent() { BillboardSet* bbs = mSceneMgr->createBillboardSet(); auto font = FontManager::getSingleton().getByName("DejaVu/SerifCondensedItalic", "Tests"); font->putText(bbs, "The quick brown Fox\njumps over the", 10); font->putText(bbs, "Lazy Dog", 15, ColourValue::Blue); mSceneMgr->getRootSceneNode() ->createChildSceneNode(bbs->getBoundingBox().getHalfSize()*Vector3(-1, 1, 0)) ->attachObject(bbs); mCameraNode->setPosition(0,0,160); mCameraNode->lookAt(Vector3(0, 0, 0), Node::TS_PARENT); } //----------------------------------------------------------------------- //----------------------------------------------------------------------- void addTextureDebugOverlay(const Ogre::String& texname, size_t i) { Ogre::Overlay* debugOverlay = Ogre::OverlayManager::getSingleton().getByName("Core/DebugOverlay"); if(!debugOverlay) debugOverlay = Ogre::OverlayManager::getSingleton().create("Core/DebugOverlay"); debugOverlay->show(); // Set up a debug panel to display the shadow Ogre::MaterialPtr debugMat = Ogre::MaterialManager::getSingleton().create( "Ogre/DebugTexture" + Ogre::StringConverter::toString(i), "VisualTestTransient"); debugMat->getTechnique(0)->getPass(0)->setLightingEnabled(false); Ogre::TextureUnitState *t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState(texname); t->setTextureAddressingMode(Ogre::TextureUnitState::TAM_CLAMP); //t = debugMat->getTechnique(0)->getPass(0)->createTextureUnitState("spot_shadow_fade.png"); //t->setTextureAddressingMode(TextureUnitState::TAM_CLAMP); //t->setColourOperation(LBO_ADD); Ogre::OverlayContainer* debugPanel = (Ogre::OverlayContainer*) (Ogre::OverlayManager::getSingleton().createOverlayElement("Panel", "Ogre/DebugTexPanel" + Ogre::StringConverter::toString(i))); debugPanel->_setPosition(0.8, i*0.25); debugPanel->_setDimensions(0.2, 0.24); debugPanel->setMaterialName(debugMat->getName()); debugOverlay->add2D(debugPanel); } //----------------------------------------------------------------------- void clearDebugTextureOverlays() { Ogre::Overlay* debugOverlay = Ogre::OverlayManager::getSingleton().getByName("Core/DebugOverlay"); if(debugOverlay) Ogre::OverlayManager::getSingleton().destroy("Core/DebugOverlay"); //debugOverlay->hide(); for(int i = 0; i < 10; ++i) { if(Ogre::OverlayManager::getSingleton().hasOverlayElement( "Ogre/DebugTexPanel" + Ogre::StringConverter::toString(i))) { OverlayManager::getSingleton().destroyOverlayElement( "Ogre/DebugTexPanel" + Ogre::StringConverter::toString(i)); MaterialManager::getSingleton().remove("Ogre/DebugTexture" + StringConverter::toString(i), "VisualTestTransient"); } } } //----------------------------------------------------------------------- void addTextureDebugOverlay(Ogre::TexturePtr tex, size_t i) { addTextureDebugOverlay(tex->getName(), i); } //----------------------------------------------------------------------- void addTextureShadowDebugOverlay(size_t num, Ogre::SceneManager* mgr) { for (size_t i = 0; i < num; ++i) { Ogre::TexturePtr shadowTex = mgr->getShadowTexture(i); addTextureDebugOverlay(shadowTex, i); } } //-----------------------------------------------------------------------
// Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-734707. All Rights // reserved. See files LICENSE and NOTICE for details. // // This file is part of CEED, a collection of benchmarks, miniapps, software // libraries and APIs for efficient high-order finite element and spectral // element discretizations for exascale applications. For more information and // source code availability see http://github.com/ceed. // // The CEED research is supported by the Exascale Computing Project 17-SC-20-SC, // a collaborative effort of two U.S. Department of Energy organizations (Office // of Science and the National Nuclear Security Administration) responsible for // the planning and preparation of a capable exascale ecosystem, including // software, applications, hardware, advanced system engineering and early // testbed platforms, in support of the nation's exascale computing imperative. // // __ __ // / / ____ ____ / /_ ____ _____ // / / / __ `/ __ `/ __ \/ __ \/ ___/ // / /___/ /_/ / /_/ / / / / /_/ (__ ) // /_____/\__,_/\__, /_/ /_/\____/____/ // /____/ // // High-order Lagrangian Hydrodynamics Miniapp // // RAJA version // // Laghos(LAGrangian High-Order Solver) is a miniapp that solves the // time-dependent Euler equation of compressible gas dynamics in a moving // Lagrangian frame using unstructured high-order finite element spatial // discretization and explicit high-order time-stepping. Laghos is based on the // numerical algorithm described in the following article: // // V. Dobrev, Tz. Kolev and R. Rieben, "High-order curvilinear finite element // methods for Lagrangian hydrodynamics", SIAM Journal on Scientific // Computing, (34) 2012, pp.B606–B641, https://doi.org/10.1137/120864672. // // Sample runs: // mpirun -np 8 laghos -p 0 -m data/square01_quad.mesh -rs 3 -tf 0.75 // mpirun -np 8 laghos -p 0 -m data/square01_tri.mesh -rs 1 -tf 0.75 // mpirun -np 8 laghos -p 0 -m data/cube01_hex.mesh -rs 1 -tf 2.0 // mpirun -np 8 laghos -p 1 -m data/square01_quad.mesh -rs 3 -tf 0.8 // mpirun -np 8 laghos -p 1 -m data/square01_quad.mesh -rs 0 -tf 0.8 -ok 7 -ot 6 // mpirun -np 8 laghos -p 1 -m data/cube01_hex.mesh -rs 2 -tf 0.6 // mpirun -np 8 laghos -p 2 -m data/segment01.mesh -rs 5 -tf 0.2 // mpirun -np 8 laghos -p 3 -m data/rectangle01_quad.mesh -rs 2 -tf 2.5 // mpirun -np 8 laghos -p 3 -m data/box01_hex.mesh -rs 1 -tf 2.5 // // Test problems: // p = 0 --> Taylor-Green vortex (smooth problem). // p = 1 --> Sedov blast. // p = 2 --> 1D Sod shock tube. // p = 3 --> Triple point. #include "laghos_solver.hpp" #include <memory> #include <iostream> #include <fstream> #include <sys/time.h> using namespace std; using namespace mfem; using namespace mfem::hydrodynamics; // Choice for the problem setup. int problem = 0; void display_banner(ostream & os); int main(int argc, char *argv[]) { // Initialize MPI. MPI_Session mpi(argc, argv); int myid = mpi.WorldRank(); // Print the banner. if (mpi.Root()) { display_banner(cout); } // Parse command-line options. const char *mesh_file = "../data/square01_quad.mesh"; int rs_levels = 0; int rp_levels = 0; int order_v = 2; int order_e = 1; int ode_solver_type = 4; double t_final = 0.5; double cfl = 0.5; double cg_tol = 1e-8; int cg_max_iter = 300; int max_tsteps = -1; bool p_assembly = true; bool visualization = false; int vis_steps = 5; bool visit = false; bool gfprint = false; bool cuda = false; bool hip = false; bool uvm = false; bool aware = false; bool hcpo = false; // do Host Conforming Prolongation Operation bool sync = false; const char *basename = "results/Laghos"; OptionsParser args(argc, argv); // Standard Options ********************************************************* args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to use."); args.AddOption(&rs_levels, "-rs", "--refine-serial", "Number of times to refine the mesh uniformly in serial."); args.AddOption(&rp_levels, "-rp", "--refine-parallel", "Number of times to refine the mesh uniformly in parallel."); args.AddOption(&problem, "-p", "--problem", "Problem setup to use."); args.AddOption(&order_v, "-ok", "--order-kinematic", "Order (degree) of the kinematic finite element space."); args.AddOption(&order_e, "-ot", "--order-thermo", "Order (degree) of the thermodynamic finite element space."); args.AddOption(&ode_solver_type, "-s", "--ode-solver", "ODE solver: 1 - Forward Euler,\n\t" " 2 - RK2 SSP, 3 - RK3 SSP, 4 - RK4, 6 - RK6."); args.AddOption(&t_final, "-tf", "--t-final", "Final time; start time is 0."); args.AddOption(&cfl, "-cfl", "--cfl", "CFL-condition number."); args.AddOption(&cg_tol, "-cgt", "--cg-tol", "Relative CG tolerance (velocity linear solve)."); args.AddOption(&cg_max_iter, "-cgm", "--cg-max-steps", "Maximum number of CG iterations (velocity linear solve)."); args.AddOption(&max_tsteps, "-ms", "--max-steps", "Maximum number of steps (negative means no restriction)."); args.AddOption(&p_assembly, "-pa", "--partial-assembly", "-fa", "--full-assembly", "Activate 1D tensor-based assembly (partial assembly)."); args.AddOption(&visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.AddOption(&vis_steps, "-vs", "--visualization-steps", "Visualize every n-th timestep."); args.AddOption(&visit, "-visit", "--visit", "-no-visit", "--no-visit", "Enable or disable VisIt visualization."); args.AddOption(&gfprint, "-print", "--print", "-no-print", "--no-print", "Enable or disable result output (files in mfem format)."); args.AddOption(&basename, "-k", "--outputfilename", "Name of the visit dump files"); // RAJA Options ************************************************************* args.AddOption(&cuda, "-cuda", "--cuda", "-no-cuda", "--no-cuda", "Enable or disable CUDA kernels if you are using RAJA."); args.AddOption(&hip, "-hip", "--hip", "-no-hip", "--no-hip", "Enable or disable HIP kernels if you are using RAJA."); // CUDA Options ************************************************************* args.AddOption(&uvm, "-uvm", "--uvm", "-no-uvm", "--no-uvm", "Enable or disable Unified Memory."); args.AddOption(&aware, "-aware", "--aware", "-no-aware", "--no-aware", "Enable or disable MPI GPU Aware (GPUDirect)."); args.AddOption(&hcpo, "-hcpo", "--hcpo", "-not-hcpo", "--no-hcpo", "Enable or disable Host Conforming Prolongation Operations,\n" "\twhich transfers ALL the data to the host before communications."); args.AddOption(&sync, "-sync", "--sync", "-no-sync", "--no-sync", "Enable or disable Enforced Kernel Synchronization."); args.Parse(); if (!args.Good()) { if (mpi.Root()) { args.PrintUsage(cout); } return 1; } if (mpi.Root()) { args.PrintOptions(cout); } // CUDA set device & options // ************************************************************************** rconfig::Get().Setup(mpi.WorldRank(),mpi.WorldSize(), cuda,hip,uvm,aware,hcpo,sync); // Read the serial mesh from the given mesh file on all processors. // Refine the mesh in serial to increase the resolution. Mesh *mesh = new Mesh(mesh_file, 1, 1); const int dim = mesh->Dimension(); for (int lev = 0; lev < rs_levels; lev++) { mesh->UniformRefinement(); } if (p_assembly && dim == 1) { p_assembly = false; if (mpi.Root()) { cout << "Laghos does not support PA in 1D. Switching to FA." << endl; } } // Parallel partitioning of the mesh. // ************************************************************************** ParMesh *pmesh = NULL; const int num_tasks = mpi.WorldSize(); const int partitions = floor(pow(num_tasks, 1.0 / dim) + 1e-2); int *nxyz = new int[dim]; int product = 1; for (int d = 0; d < dim; d++) { nxyz[d] = partitions; product *= partitions; } if (product == num_tasks) { if (myid == 0) { printf("\033[32m[laghos] \033[32;1mCartesian\033[m\033[32m partitioning will be used\033[m\n"); } int *partitioning = mesh->CartesianPartitioning(nxyz); pmesh = new ParMesh(MPI_COMM_WORLD, *mesh, partitioning); delete[] partitioning; } else { if (myid == 0) { printf("\033[32m[laghos] Non-Cartesian partitioning through METIS will be used\033[m\n"); #ifndef MFEM_USE_METIS cout << "MFEM was built without METIS. " << "Adjust the number of tasks to use a Cartesian split." << endl; #endif } #ifndef MFEM_USE_METIS return 1; #endif pmesh = new ParMesh(MPI_COMM_WORLD, *mesh); } delete [] nxyz; delete mesh; // ************************************************************************** // We need at least some elements in each partition for now #ifdef MFEM_USE_MPI int global_pmesh_NE; const int pmesh_NE=pmesh->GetNE(); MPI_Allreduce(&pmesh_NE,&global_pmesh_NE,1,MPI_INT,MPI_MIN,pmesh->GetComm()); if (global_pmesh_NE==0) { printf("[Laghos] ERROR: pmesh->GetNE()==0!"); return 1; } else { printf("\033[32m[laghos] pmesh->GetNE()=%d\033[m\n",global_pmesh_NE); } assert(pmesh->GetNE()>0); #endif // Refine the mesh further in parallel to increase the resolution. for (int lev = 0; lev < rp_levels; lev++) { pmesh->UniformRefinement(); } // Define the parallel finite element spaces. We use: // - H1 (Gauss-Lobatto, continuous) for position and velocity. // - L2 (Bernstein, discontinuous) for specific internal energy. L2_FECollection L2FEC(order_e, dim, BasisType::Positive); H1_FECollection H1FEC(order_v, dim); RajaFiniteElementSpace L2FESpace(pmesh, &L2FEC); RajaFiniteElementSpace H1FESpace(pmesh, &H1FEC, pmesh->Dimension()); // Boundary conditions: all tests use v.n = 0 on the boundary, // and we assume that the boundaries are straight. Array<int> essential_tdofs; { Array<int> ess_bdr(pmesh->bdr_attributes.Max()), tdofs1d; for (int d = 0; d < pmesh->Dimension(); d++) { // Attributes 1/2/3 correspond to fixed-x/y/z boundaries, i.e., we must // enforce v_x/y/z = 0 for the velocity components. ess_bdr = 0; ess_bdr[d] = 1; H1FESpace.GetEssentialTrueDofs(ess_bdr, tdofs1d, d); essential_tdofs.Append(tdofs1d); } } // Define the explicit ODE solver used for time integration. RajaODESolver *ode_solver = NULL; switch (ode_solver_type) { case 1: ode_solver = new RajaForwardEulerSolver; break; case 2: ode_solver = new RajaRK2Solver(0.5); break; case 3: ode_solver = new RajaRK3SSPSolver; break; case 4: ode_solver = new RajaRK4Solver; break; case 6: ode_solver = new RajaRK6Solver; break; default: if (myid == 0) { cout << "Unknown ODE solver type: " << ode_solver_type << '\n'; } delete pmesh; MPI_Finalize(); return 3; } HYPRE_Int glob_size_l2 = L2FESpace.GlobalTrueVSize(); HYPRE_Int glob_size_h1 = H1FESpace.GlobalTrueVSize(); if (mpi.Root()) { cout << "Number of kinematic (position, velocity) dofs: " << glob_size_h1 << endl; cout << "Number of specific internal energy dofs: " << glob_size_l2 << endl<< endl; } int Vsize_l2 = L2FESpace.GetVSize(); int Vsize_h1 = H1FESpace.GetVSize(); // The monolithic BlockVector stores unknown fields as: // - 0 -> position // - 1 -> velocity // - 2 -> specific internal energy Array<int> true_offset(4); true_offset[0] = 0; true_offset[1] = true_offset[0] + Vsize_h1; true_offset[2] = true_offset[1] + Vsize_h1; true_offset[3] = true_offset[2] + Vsize_l2; RajaVector S(true_offset[3]); // Define GridFunction objects for the position, velocity and specific // internal energy. There is no function for the density, as we can always // compute the density values given the current mesh position, using the // property of pointwise mass conservation. ParGridFunction x_gf(&H1FESpace); ParGridFunction v_gf(&H1FESpace); ParGridFunction e_gf(&L2FESpace); RajaGridFunction d_x_gf(H1FESpace, S.GetRange(true_offset[0], true_offset[1])); RajaGridFunction d_v_gf(H1FESpace, S.GetRange(true_offset[1], true_offset[2])); RajaGridFunction d_e_gf(L2FESpace, S.GetRange(true_offset[2], true_offset[3])); // Initialize x_gf using the starting mesh coordinates. This also links the // mesh positions to the values in x_gf. pmesh->SetNodalGridFunction(&x_gf); d_x_gf = x_gf; // Initialize the velocity. VectorFunctionCoefficient v_coeff(pmesh->Dimension(), v0); v_gf.ProjectCoefficient(v_coeff); d_v_gf = v_gf; // Initialize density and specific internal energy values. We interpolate in // a non-positive basis to get the correct values at the dofs. Then we do an // L2 projection to the positive basis in which we actually compute. The goal // is to get a high-order representation of the initial condition. Note that // this density is a temporary function and it will not be updated during the // time evolution. ParGridFunction rho(&L2FESpace); FunctionCoefficient rho_coeff(hydrodynamics::rho0); L2_FECollection l2_fec(order_e, pmesh->Dimension()); RajaFiniteElementSpace l2_fes(pmesh, &l2_fec); ParGridFunction l2_rho(&l2_fes), l2_e(&l2_fes); l2_rho.ProjectCoefficient(rho_coeff); rho.ProjectGridFunction(l2_rho); RajaGridFunction d_rho(L2FESpace); d_rho = rho; if (problem == 1) { // For the Sedov test, we use a delta function at the origin. DeltaCoefficient e_coeff(0, 0, 0.25); l2_e.ProjectCoefficient(e_coeff); } else { FunctionCoefficient e_coeff(e0); l2_e.ProjectCoefficient(e_coeff); } e_gf.ProjectGridFunction(l2_e); d_e_gf = e_gf; Coefficient *material_pcf = new FunctionCoefficient(hydrodynamics::gamma); // Piecewise constant ideal gas coefficient over the Lagrangian mesh. The // gamma values are projected on a function that stays constant on the moving // mesh. /*L2_FECollection mat_fec(0, pmesh->Dimension()); RajaFiniteElementSpace mat_fes(pmesh, &mat_fec); ParGridFunction mat_gf(&mat_fes); FunctionCoefficient mat_coeff(hydrodynamics::gamma); mat_gf.ProjectCoefficient(mat_coeff); GridFunctionCoefficient *mat_gf_coeff = new GridFunctionCoefficient(&mat_gf); RajaGridFunction d_mat_gf_coeff(mat_fes); d_mat_gf_coeff=mat_gf_coeff;*/ // Additional details, depending on the problem. int source = 0; bool visc=false; switch (problem) { case 0: if (pmesh->Dimension() == 2) { source = 1; } visc = false; break; case 1: visc = true; break; case 2: visc = true; break; case 3: visc = true; break; default: MFEM_ABORT("Wrong problem specification!"); } LagrangianHydroOperator oper(S.Size(), H1FESpace, L2FESpace, essential_tdofs, d_rho, source, cfl, material_pcf, visc, p_assembly, cg_tol, cg_max_iter); socketstream vis_rho, vis_v, vis_e; char vishost[] = "localhost"; int visport = 19916; ParGridFunction rho_gf; if (visualization || visit) { oper.ComputeDensity(rho_gf); } if (visualization) { // Make sure all MPI ranks have sent their 'v' solution before initiating // another set of GLVis connections (one from each rank): MPI_Barrier(pmesh->GetComm()); vis_rho.precision(8); vis_v.precision(8); vis_e.precision(8); int Wx = 0, Wy = 0; // window position const int Ww = 350, Wh = 350; // window size int offx = Ww+10; // window offsets VisualizeField(vis_rho, vishost, visport, rho_gf, "Density", Wx, Wy, Ww, Wh); Wx += offx; VisualizeField(vis_v, vishost, visport, v_gf, "Velocity", Wx, Wy, Ww, Wh); Wx += offx; VisualizeField(vis_e, vishost, visport, e_gf, "Specific Internal Energy", Wx, Wy, Ww, Wh); } // Save data for VisIt visualization VisItDataCollection visit_dc(basename, pmesh); if (visit) { visit_dc.RegisterField("Density", &rho_gf); visit_dc.RegisterField("Velocity", &v_gf); visit_dc.RegisterField("Specific Internal Energy", &e_gf); visit_dc.SetCycle(0); visit_dc.SetTime(0.0); visit_dc.Save(); } // Perform time-integration (looping over the time iterations, ti, with a // time-step dt). The object oper is of type LagrangianHydroOperator that // defines the Mult() method that used by the time integrators. ode_solver->Init(oper); oper.ResetTimeStepEstimate(); double t = 0.0, dt = oper.GetTimeStepEstimate(S), t_old; bool last_step = false; int steps = 0; RajaVector S_old(S); for (int ti = 1; !last_step; ti++) { if (t + dt >= t_final) { dt = t_final - t; last_step = true; } if (steps == max_tsteps) { last_step = true; } S_old = S; t_old = t; oper.ResetTimeStepEstimate(); // S is the vector of dofs, t is the current time, // and dt is the time step to advance. ode_solver->Step(S, t, dt); steps++; // Make sure that the mesh corresponds to the new solution state. x_gf = d_x_gf; pmesh->NewNodes(x_gf, false); // Adaptive time step control. const double dt_est = oper.GetTimeStepEstimate(S); if (dt_est < dt) { // Repeat (solve again) with a decreased time step - decrease of the // time estimate suggests appearance of oscillations. dt *= 0.85; if (dt < numeric_limits<double>::epsilon()) { MFEM_ABORT("The time step crashed!"); } t = t_old; S = S_old; oper.ResetQuadratureData(); if (mpi.Root()) { cout << "Repeating step " << ti << endl; } ti--; continue; } else if (dt_est > 1.25 * dt) { dt *= 1.02; } if (last_step || (ti % vis_steps) == 0) { double loc_norm = d_e_gf * d_e_gf, tot_norm; MPI_Allreduce(&loc_norm, &tot_norm, 1, MPI_DOUBLE, MPI_SUM, pmesh->GetComm()); if (mpi.Root()) { cout << fixed; cout << "step " << setw(5) << ti << ",\tt = " << setw(5) << setprecision(4) << t << ",\tdt = " << setw(5) << setprecision(6) << dt << ",\t|e| = " << setprecision(10) << sqrt(tot_norm) << endl; } // Make sure all ranks have sent their 'v' solution before initiating // another set of GLVis connections (one from each rank): MPI_Barrier(pmesh->GetComm()); if (visualization || visit || gfprint) { oper.ComputeDensity(rho_gf); } if (visualization) { int Wx = 0, Wy = 0; // window position int Ww = 350, Wh = 350; // window size int offx = Ww+10; // window offsets VisualizeField(vis_rho, vishost, visport, rho_gf, "Density", Wx, Wy, Ww, Wh); Wx += offx; VisualizeField(vis_v, vishost, visport, v_gf, "Velocity", Wx, Wy, Ww, Wh); Wx += offx; VisualizeField(vis_e, vishost, visport, e_gf, "Specific Internal Energy", Wx, Wy, Ww,Wh); Wx += offx; } if (visit) { visit_dc.SetCycle(ti); visit_dc.SetTime(t); visit_dc.Save(); } if (gfprint) { ostringstream mesh_name, rho_name, v_name, e_name; mesh_name << basename << "_" << ti << "_mesh." << setfill('0') << setw(6) << myid; rho_name << basename << "_" << ti << "_rho." << setfill('0') << setw(6) << myid; v_name << basename << "_" << ti << "_v." << setfill('0') << setw(6) << myid; e_name << basename << "_" << ti << "_e." << setfill('0') << setw(6) << myid; ofstream mesh_ofs(mesh_name.str().c_str()); mesh_ofs.precision(8); pmesh->Print(mesh_ofs); mesh_ofs.close(); ofstream rho_ofs(rho_name.str().c_str()); rho_ofs.precision(8); rho_gf.Save(rho_ofs); rho_ofs.close(); ofstream v_ofs(v_name.str().c_str()); v_ofs.precision(8); v_gf.Save(v_ofs); v_ofs.close(); ofstream e_ofs(e_name.str().c_str()); e_ofs.precision(8); e_gf.Save(e_ofs); e_ofs.close(); } } } switch (ode_solver_type) { case 2: steps *= 2; break; case 3: steps *= 3; break; case 4: steps *= 4; break; case 6: steps *= 6; } oper.PrintTimingData(mpi.Root(), steps); if (visualization) { vis_v.close(); vis_e.close(); } // Free the used memory. delete ode_solver; delete pmesh; delete material_pcf; return 0; } namespace mfem { namespace hydrodynamics { double rho0(const Vector &x) { switch (problem) { case 0: return 1.0; case 1: return 1.0; case 2: if (x(0) < 0.5) { return 1.0; } else { return 0.1; } case 3: if (x(0) > 1.0 && x(1) <= 1.5) { return 1.0; } else { return 0.125; } default: MFEM_ABORT("Bad number given for problem id!"); return 0.0; } } double gamma(const Vector &x) { switch (problem) { case 0: return 5./3.; case 1: return 1.4; case 2: return 1.4; case 3: if (x(0) > 1.0 && x(1) <= 1.5) { return 1.4; } else { return 1.5; } default: MFEM_ABORT("Bad number given for problem id!"); return 0.0; } } void v0(const Vector &x, Vector &v) { switch (problem) { case 0: v(0) = sin(M_PI*x(0)) * cos(M_PI*x(1)); v(1) = -cos(M_PI*x(0)) * sin(M_PI*x(1)); if (x.Size() == 3) { v(0) *= cos(M_PI*x(2)); v(1) *= cos(M_PI*x(2)); v(2) = 0.0; } break; case 1: v = 0.0; break; case 2: v = 0.0; break; case 3: v = 0.0; break; default: MFEM_ABORT("Bad number given for problem id!"); } } double e0(const Vector &x) { switch (problem) { case 0: { const double denom = 2.0 / 3.0; // (5/3 - 1) * density. double val; if (x.Size() == 2) { val = 1.0 + (cos(2*M_PI*x(0)) + cos(2*M_PI*x(1))) / 4.0; } else { val = 100.0 + ((cos(2*M_PI*x(2)) + 2) * (cos(2*M_PI*x(0)) + cos(2*M_PI*x(1))) - 2) / 16.0; } return val/denom; } case 1: return 0.0; // This case in initialized in main(). case 2: if (x(0) < 0.5) { return 1.0 / rho0(x) / (gamma(x) - 1.0); } else { return 0.1 / rho0(x) / (gamma(x) - 1.0); } case 3: if (x(0) > 1.0) { return 0.1 / rho0(x) / (gamma(x) - 1.0); } else { return 1.0 / rho0(x) / (gamma(x) - 1.0); } default: MFEM_ABORT("Bad number given for problem id!"); return 0.0; } } } // namespace hydrodynamics } // namespace mfem void display_banner(ostream & os) { os << endl << " __ __ " << endl << " / / ____ ____ / /_ ____ _____ " << endl << " / / / __ `/ __ `/ __ \\/ __ \\/ ___/ " << endl << " / /___/ /_/ / /_/ / / / / /_/ (__ ) " << endl << " /_____/\\__,_/\\__, /_/ /_/\\____/____/ " << endl << " /____/ " << endl << endl; }
#include "cl_util.h" #include "MessageHandler.h" namespace msghandler { namespace { //Enables more precise debugging than the engine's debug code since we've got our own handlers in addition to the engine hooks. static cvar_t* msghandler_debug = nullptr; } void Initialize() { //Wipe any previously registered handlers so registrations get to the engine during a soft restart MessageHandlers().Clear(); msghandler_debug = CVAR_CREATE( "msghandler_debug", "0", 0 ); } int MsgFunc_MessageHandlers( const char* pszName, int iSize, void* pBuf ) { return MessageHandlers().Invoke( pszName, iSize, pBuf ); } } bool CMessageHandlers::Invoke( const char* pszName, int iSize, void* pBuf ) { auto index = m_MessageHandlers.Find( pszName ); if( index != m_MessageHandlers.InvalidIndex() ) { auto& handler = m_MessageHandlers.Element( index ); if( msghandler::msghandler_debug->value ) { Con_Printf( "msghandler: Dispatching message \"%s\", size %d\n", pszName, iSize ); } return ( *handler )( pszName, iSize, pBuf ); } if( m_pFallbackHandlers ) return m_pFallbackHandlers->Invoke( pszName, iSize, pBuf ); if( msghandler::msghandler_debug->value ) { Con_Printf( "msghandler: Couldn't find handler for message \"%s\", size %d\n", pszName, iSize ); } return false; } void CMessageHandlers::SetFallbackHandlers( CMessageHandlers* pFallbackHandlers ) { //Null it out in case there's a problem. m_pFallbackHandlers = nullptr; if( pFallbackHandlers ) { for( auto pHandlers = pFallbackHandlers; pHandlers; pHandlers = pHandlers->GetFallbackHandlers() ) { if( pHandlers == this ) { //This can cause infinite recursion. ASSERT( false ); Con_Printf( "Tried to add a fallback message handler that was set to fall back to this handler!\n" ); return; } } } m_pFallbackHandlers = pFallbackHandlers; } void CMessageHandlers::HookMessage( const char* pszName ) { gEngfuncs.pfnHookUserMsg( pszName, &msghandler::MsgFunc_MessageHandlers ); }
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 Metrological * * 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 "../VolumeControlPlatform.h" #include "../Module.h" #include "audio_if.h" namespace WPEFramework { namespace Plugin { namespace { constexpr float kMinVolume = 0.0; constexpr float kMaxVolume = 1.0; class VolumeControlPlatformAMLogic : public VolumeControlPlatform { public: VolumeControlPlatformAMLogic( VolumeControlPlatform::VolumeChangedCallback&& volumeChanged, VolumeControlPlatform::MutedChangedCallback&& mutedChanged) : _volumeChanged(std::move(volumeChanged)) , _muteChanged(std::move(mutedChanged)) , _device(nullptr) { audio_hw_load_interface(&_device); if(_device != nullptr && _device->init_check(_device) == 0){ SYSLOG(Logging::Startup, (_T("Initialized audio_client interface."))); } else { SYSLOG(Logging::Startup, (_T("Failed to initialize audio_client interface."))); _device = nullptr; } } ~VolumeControlPlatformAMLogic() override { if (_device != nullptr) { audio_hw_unload_interface(_device); } } uint32_t Muted(bool muted) override { uint32_t errorCode = Core::ERROR_NONE; if (_device != nullptr) { int error = _device->set_master_mute(_device, muted); if (error != 0) { TRACE(Trace::Error, (_T("Could not set master to mute."))); errorCode = Core::ERROR_GENERAL; } else { // _muteChanged(); } } else { errorCode = Core::ERROR_GENERAL; } return errorCode; } bool Muted() const override { bool mute = false; if (_device != nullptr) { _device->get_master_mute(_device, &mute); } else { TRACE(Trace::Error, (_T("Cannot query mute property. Device uninitialized."))); } return mute; } uint32_t Volume(uint8_t volume) override { uint32_t errorCode = Core::ERROR_NONE; // Map the input volume to [0,1] range with saturation. float scaledVolume = static_cast<float>(volume) / 100; scaledVolume = std::max(std::min(scaledVolume, kMaxVolume), kMinVolume); if (_device != nullptr) { int error = _device->set_master_volume(_device, scaledVolume); if (error != 0) { TRACE(Trace::Error, (_T("\nCould not set master volume <%d>"), error)); errorCode = Core::ERROR_GENERAL; } else { _volumeChanged(); } } else { errorCode = Core::ERROR_GENERAL; } return errorCode; } uint8_t Volume() const override { float volume = .0; if (_device != nullptr) { _device->get_master_volume(_device, &volume); } else { TRACE(Trace::Error, (_T("\nCannot query volume. Device uninitialized."))); } return static_cast<uint8_t>(volume * 100); } private: VolumeControlPlatform::VolumeChangedCallback _volumeChanged; VolumeControlPlatform::MutedChangedCallback&& _muteChanged; audio_hw_device_t* _device; }; } // static std::unique_ptr<VolumeControlPlatform> VolumeControlPlatform::Create( VolumeControlPlatform::VolumeChangedCallback&& volumeChanged, VolumeControlPlatform::MutedChangedCallback&& mutedChanged) { return std::unique_ptr<VolumeControlPlatform>(new VolumeControlPlatformAMLogic(std::move(volumeChanged), std::move(mutedChanged))); } } // namespace Plugin } // namespace WPEFramework
/* -*- mode: c++; c-basic-indent: 4; indent-tabs-mode: nil -*- this file is part of rcssserver3D Fri May 9 2003 Copyright (C) 2002,2003 Koblenz University Copyright (C) 2003 RoboCup Soccer Server 3D Maintenance Group $Id$ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "soccerinputlogplayer.h" void CLASS(SoccerInputLogPlayer)::DefineClass() { DEFINE_BASECLASS(kerosin/InputItem); }
/***************************** Copyright 2011 Rafael Muñoz Salinas. 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 Rafael Muñoz Salinas ''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 Rafael Muñoz Salinas OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Rafael Muñoz Salinas. ********************************/ #include <iostream> #include <fstream> #include <sstream> #ifdef __APPLE__ #include <GLUT/glut.h> #elif _MSC_VER //http://social.msdn.microsoft.com/Forums/eu/vcgeneral/thread/7d6e6fa5-afc2-4370-9a1f-991a76ccb5b7 #include <windows.h> #include <GL/gl.h> #include <GL/glut.h> #else #include <GL/gl.h> #include <GL/glut.h> #endif #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "aruco.h" #include "boarddetector.h" #include "common.h" using namespace cv; using namespace aruco; string TheInputVideo,TheIntrinsicFile,TheBoardConfigFile; bool The3DInfoAvailable=false; float TheMarkerSize=-1; MarkerDetector MDetector; VideoCapture TheVideoCapturer; vector<Marker> TheMarkers; //board BoardDetector TheBoardDetector; pair<Board,float> TheBoardDetected; //the board and its probabilit BoardConfiguration TheBoardConfig; Mat TheInputImage,TheUndInputImage,TheResizedImage; CameraParameters TheCameraParams; Size TheGlWindowSize; bool TheCaptureFlag=true; void vDrawScene(); void vIdle(); void vResize( GLsizei iWidth, GLsizei iHeight ); void vMouse(int b,int s,int x,int y); /************************************ * * * * ************************************/ bool readArguments ( int argc,char **argv ) { if (argc!=5) { cerr<<"Invalid number of arguments"<<endl; cerr<<"Usage: (in.avi|live) boardConfig.yml intrinsics.yml size "<<endl; return false; } TheInputVideo=argv[1]; TheBoardConfigFile=argv[2]; TheIntrinsicFile=argv[3]; TheMarkerSize=atof(argv[4]); return true; } /************************************ * * * * ************************************/ int main(int argc,char **argv) { try { if (readArguments (argc,argv)==false) return 0; //read board configuration TheBoardConfig.readFromFile(TheBoardConfigFile); //Open video input source if (TheInputVideo=="") //read from camera TheVideoCapturer.open(0); else TheVideoCapturer.open(TheInputVideo); if (!TheVideoCapturer.isOpened()) { cerr<<"Could not open video"<<endl; return -1; } //read first image TheVideoCapturer>>TheInputImage; //read camera paramters if passed TheCameraParams.readFromXMLFile(TheIntrinsicFile); TheCameraParams.resize( TheInputImage.size()); glutInit(&argc, argv); glutInitWindowPosition( 0, 0); glutInitWindowSize(TheInputImage.size().width,TheInputImage.size().height); glutInitDisplayMode( GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE ); glutCreateWindow( "AruCo" ); glutDisplayFunc( vDrawScene ); glutIdleFunc( vIdle ); glutReshapeFunc( vResize ); glutMouseFunc(vMouse); glClearColor( 0.0, 0.0, 0.0, 1.0 ); glClearDepth( 1.0 ); TheGlWindowSize=TheInputImage.size(); vResize(TheGlWindowSize.width,TheGlWindowSize.height); glutMainLoop(); } catch (std::exception &ex) { cout<<"Exception :"<<ex.what()<<endl; } } /************************************ * * * * ************************************/ void vMouse(int b,int s,int x,int y) { if (b==GLUT_LEFT_BUTTON && s==GLUT_DOWN) { TheCaptureFlag=!TheCaptureFlag; } } /************************************ * * * * ************************************/ void axis(float size) { glColor3f (1,0,0 ); glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, 0.0f); // origin of the line glVertex3f(size,0.0f, 0.0f); // ending point of the line glEnd( ); glColor3f ( 0,1,0 ); glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, 0.0f); // origin of the line glVertex3f( 0.0f,size, 0.0f); // ending point of the line glEnd( ); glColor3f (0,0,1 ); glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, 0.0f); // origin of the line glVertex3f(0.0f, 0.0f, size); // ending point of the line glEnd( ); } /************************************ * * * * ************************************/ void vDrawScene() { if (TheResizedImage.rows==0) //prevent from going on until the image is initialized return; ///clear glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); ///draw image in the buffer glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, TheGlWindowSize.width, 0, TheGlWindowSize.height, -1.0, 1.0); glViewport(0, 0, TheGlWindowSize.width , TheGlWindowSize.height); glDisable(GL_TEXTURE_2D); glPixelZoom( 1, -1); glRasterPos3f( 0, TheGlWindowSize.height - 0.5, -1.0 ); glDrawPixels ( TheGlWindowSize.width , TheGlWindowSize.height , GL_RGB , GL_UNSIGNED_BYTE , TheResizedImage.ptr(0) ); ///Set the appropriate projection matrix so that rendering is done in a enrvironment //like the real camera (without distorsion) glMatrixMode(GL_PROJECTION); double proj_matrix[16]; TheCameraParams.glGetProjectionMatrix(TheInputImage.size(),TheGlWindowSize,proj_matrix,0.05,10); glLoadIdentity(); glLoadMatrixd(proj_matrix); glLineWidth(2); //now, for each marker, double modelview_matrix[16]; /* for (unsigned int m=0;m<TheMarkers.size();m++) { TheMarkers[m].glGetModelViewMatrix(modelview_matrix); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glLoadMatrixd(modelview_matrix); // axis(TheMarkerSize); glColor3f(1,0.4,0.4); glTranslatef(0, TheMarkerSize/2,0); glPushMatrix(); glutWireCube( TheMarkerSize ); glPopMatrix(); }*/ //If the board is detected with enough probability if (TheBoardDetected.second>0.3) { TheBoardDetected.first.glGetModelViewMatrix(modelview_matrix); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glLoadMatrixd(modelview_matrix); glColor3f(0,1,0); axis(TheMarkerSize); if(TheBoardDetector.isYPerpendicular()) glTranslatef(0,TheMarkerSize/2,0); else glTranslatef(0,0,TheMarkerSize/2); glPushMatrix(); glutWireCube( TheMarkerSize ); glPopMatrix(); } glutSwapBuffers(); } /************************************ * * * * ************************************/ void vIdle() { if (TheCaptureFlag) { //capture image TheVideoCapturer.grab(); TheVideoCapturer.retrieve( TheInputImage); TheUndInputImage.create(TheInputImage.size(),CV_8UC3); //by deafult, opencv works in BGR, so we must convert to RGB because OpenGL in windows preffer cv::cvtColor(TheInputImage,TheInputImage,CV_BGR2RGB); //remove distorion in image cv::undistort(TheInputImage,TheUndInputImage, TheCameraParams.CameraMatrix,TheCameraParams.Distorsion); //detect markers MDetector.detect(TheUndInputImage,TheMarkers); //Detection of the board TheBoardDetected.second=TheBoardDetector.detect( TheMarkers, TheBoardConfig,TheBoardDetected.first, TheCameraParams,TheMarkerSize); //chekc the speed by calculating the mean speed of all iterations //resize the image to the size of the GL window cv::resize(TheUndInputImage,TheResizedImage,TheGlWindowSize); } glutPostRedisplay(); } /************************************ * * * * ************************************/ void vResize( GLsizei iWidth, GLsizei iHeight ) { TheGlWindowSize=Size(iWidth,iHeight); //not all sizes are allowed. OpenCv images have padding at the end of each line in these that are not aligned to 4 bytes if (iWidth*3%4!=0) { iWidth+=iWidth*3%4;//resize to avoid padding vResize(iWidth,TheGlWindowSize.height); } else { //resize the image to the size of the GL window if (TheUndInputImage.rows!=0) cv::resize(TheUndInputImage,TheResizedImage,TheGlWindowSize); } }
// Copyright (c) 2018 Kosi Nwabueze // // This software is released under the MIT License. // https://opensource.org/licenses/MIT #pragma once namespace wd { /** * @brief Represent an event that can circulate in an event loop and can be polled for. * */ struct Event { /** * @brief The type of event that has been triggered. * */ enum EventType { // Window events Close, Resize, Move, // General mouse events MouseDrag, MouseDown, MouseRelease, }; struct MoveEvent { float x; float y; }; struct ResizeEvent { float width; float height; }; struct MouseEvent { enum { None = 0, CTRL = 1 << 0, SHIFT = 1 << 1, LEFT = 1 << 2, RIGHT = 1 << 3, MIDDLE = 1 << 4 }; float x; float y; unsigned int mod; }; EventType type; union { ResizeEvent size; MoveEvent position; MouseEvent mouse; }; }; } // namespace wd
/****************************************************************************** * * Copyright (C) 2003-2014 Broadcom Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ /****************************************************************************** * * This file contains the action functions for device manager state * machine. * ******************************************************************************/ #define LOG_TAG "bt_bta_dm" #include <base/bind.h> #include <base/callback.h> #include <base/logging.h> #include <string.h> #include "bt_common.h" #include "bt_target.h" #include "bt_types.h" #include "bta_api.h" #include "bta_dm_api.h" #include "bta_dm_co.h" #include "bta_dm_int.h" #include "bta_sys.h" #include "btcore/include/bdaddr.h" #include "btm_api.h" #include "btm_int.h" #include "btu.h" #include "gap_api.h" /* For GAP_BleReadPeerPrefConnParams */ #include "l2c_api.h" #include "osi/include/log.h" #include "osi/include/osi.h" #include "sdp_api.h" #include "utl.h" #if (GAP_INCLUDED == TRUE) #include "gap_api.h" #endif static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, uint8_t* p_eir, uint16_t eir_len); static void bta_dm_inq_cmpl_cb(void* p_result); static void bta_dm_service_search_remname_cback(BD_ADDR bd_addr, DEV_CLASS dc, BD_NAME bd_name); static void bta_dm_remname_cback(tBTM_REMOTE_DEV_NAME* p_remote_name); static void bta_dm_find_services(BD_ADDR bd_addr); static void bta_dm_discover_next_device(void); static void bta_dm_sdp_callback(uint16_t sdp_status); static uint8_t bta_dm_authorize_cback(BD_ADDR bd_addr, DEV_CLASS dev_class, BD_NAME bd_name, uint8_t* service_name, uint8_t service_id, bool is_originator); static uint8_t bta_dm_pin_cback(BD_ADDR bd_addr, DEV_CLASS dev_class, BD_NAME bd_name, bool min_16_digit); static uint8_t bta_dm_new_link_key_cback(BD_ADDR bd_addr, DEV_CLASS dev_class, BD_NAME bd_name, LINK_KEY key, uint8_t key_type); static uint8_t bta_dm_authentication_complete_cback(BD_ADDR bd_addr, DEV_CLASS dev_class, BD_NAME bd_name, int result); static void bta_dm_local_name_cback(BD_ADDR bd_addr); static bool bta_dm_check_av(uint16_t event); static void bta_dm_bl_change_cback(tBTM_BL_EVENT_DATA* p_data); static void bta_dm_policy_cback(tBTA_SYS_CONN_STATUS status, uint8_t id, uint8_t app_id, BD_ADDR peer_addr); /* Extended Inquiry Response */ #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE) static uint8_t bta_dm_sp_cback(tBTM_SP_EVT event, tBTM_SP_EVT_DATA* p_data); #endif static void bta_dm_set_eir(char* local_name); static void bta_dm_eir_search_services(tBTM_INQ_RESULTS* p_result, tBTA_SERVICE_MASK* p_services_to_search, tBTA_SERVICE_MASK* p_services_found); static void bta_dm_search_timer_cback(void* data); static void bta_dm_disable_conn_down_timer_cback(void* data); static void bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status, uint8_t id, uint8_t app_id, BD_ADDR peer_addr); static void bta_dm_adjust_roles(bool delay_role_switch); static char* bta_dm_get_remname(void); static void bta_dm_bond_cancel_complete_cback(tBTM_STATUS result); static bool bta_dm_read_remote_device_name(BD_ADDR bd_addr, tBT_TRANSPORT transport); static void bta_dm_discover_device(BD_ADDR remote_bd_addr); static void bta_dm_sys_hw_cback(tBTA_SYS_HW_EVT status); static void bta_dm_disable_search_and_disc(void); static uint8_t bta_dm_ble_smp_cback(tBTM_LE_EVT event, BD_ADDR bda, tBTM_LE_EVT_DATA* p_data); static void bta_dm_ble_id_key_cback(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key); static void bta_dm_gattc_register(void); static void btm_dm_start_gatt_discovery(BD_ADDR bd_addr); static void bta_dm_cancel_gatt_discovery(BD_ADDR bd_addr); static void bta_dm_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data); extern tBTA_DM_CONTRL_STATE bta_dm_pm_obtain_controller_state(void); #if (BLE_VND_INCLUDED == TRUE) static void bta_dm_ctrl_features_rd_cmpl_cback(tBTM_STATUS result); #endif #ifndef BTA_DM_BLE_ADV_CHNL_MAP #define BTA_DM_BLE_ADV_CHNL_MAP \ (BTM_BLE_ADV_CHNL_37 | BTM_BLE_ADV_CHNL_38 | BTM_BLE_ADV_CHNL_39) #endif /* Disable timer interval (in milliseconds) */ #ifndef BTA_DM_DISABLE_TIMER_MS #define BTA_DM_DISABLE_TIMER_MS 5000 #endif /* Disable timer retrial interval (in milliseconds) */ #ifndef BTA_DM_DISABLE_TIMER_RETRIAL_MS #define BTA_DM_DISABLE_TIMER_RETRIAL_MS 1500 #endif /* Disable connection down timer (in milliseconds) */ #ifndef BTA_DM_DISABLE_CONN_DOWN_TIMER_MS #define BTA_DM_DISABLE_CONN_DOWN_TIMER_MS 1000 #endif /* Switch delay timer (in milliseconds) */ #ifndef BTA_DM_SWITCH_DELAY_TIMER_MS #define BTA_DM_SWITCH_DELAY_TIMER_MS 500 #endif static void bta_dm_reset_sec_dev_pending(BD_ADDR remote_bd_addr); static void bta_dm_remove_sec_dev_entry(BD_ADDR remote_bd_addr); static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, uint8_t* p_eir, uint16_t eir_len); static void bta_dm_observe_cmpl_cb(void* p_result); static void bta_dm_delay_role_switch_cback(void* data); static void bta_dm_disable_timer_cback(void* data); const uint16_t bta_service_id_to_uuid_lkup_tbl[BTA_MAX_SERVICE_ID] = { UUID_SERVCLASS_PNP_INFORMATION, /* Reserved */ UUID_SERVCLASS_SERIAL_PORT, /* BTA_SPP_SERVICE_ID */ UUID_SERVCLASS_DIALUP_NETWORKING, /* BTA_DUN_SERVICE_ID */ UUID_SERVCLASS_AUDIO_SOURCE, /* BTA_A2DP_SOURCE_SERVICE_ID */ UUID_SERVCLASS_LAN_ACCESS_USING_PPP, /* BTA_LAP_SERVICE_ID */ UUID_SERVCLASS_HEADSET, /* BTA_HSP_HS_SERVICE_ID */ UUID_SERVCLASS_HF_HANDSFREE, /* BTA_HFP_HS_SERVICE_ID */ UUID_SERVCLASS_OBEX_OBJECT_PUSH, /* BTA_OPP_SERVICE_ID */ UUID_SERVCLASS_OBEX_FILE_TRANSFER, /* BTA_FTP_SERVICE_ID */ UUID_SERVCLASS_CORDLESS_TELEPHONY, /* BTA_CTP_SERVICE_ID */ UUID_SERVCLASS_INTERCOM, /* BTA_ICP_SERVICE_ID */ UUID_SERVCLASS_IRMC_SYNC, /* BTA_SYNC_SERVICE_ID */ UUID_SERVCLASS_DIRECT_PRINTING, /* BTA_BPP_SERVICE_ID */ UUID_SERVCLASS_IMAGING_RESPONDER, /* BTA_BIP_SERVICE_ID */ UUID_SERVCLASS_PANU, /* BTA_PANU_SERVICE_ID */ UUID_SERVCLASS_NAP, /* BTA_NAP_SERVICE_ID */ UUID_SERVCLASS_GN, /* BTA_GN_SERVICE_ID */ UUID_SERVCLASS_SAP, /* BTA_SAP_SERVICE_ID */ UUID_SERVCLASS_AUDIO_SINK, /* BTA_A2DP_SERVICE_ID */ UUID_SERVCLASS_AV_REMOTE_CONTROL, /* BTA_AVRCP_SERVICE_ID */ UUID_SERVCLASS_HUMAN_INTERFACE, /* BTA_HID_SERVICE_ID */ UUID_SERVCLASS_VIDEO_SINK, /* BTA_VDP_SERVICE_ID */ UUID_SERVCLASS_PBAP_PSE, /* BTA_PBAP_SERVICE_ID */ UUID_SERVCLASS_HEADSET_AUDIO_GATEWAY, /* BTA_HSP_SERVICE_ID */ UUID_SERVCLASS_AG_HANDSFREE, /* BTA_HFP_SERVICE_ID */ UUID_SERVCLASS_MESSAGE_ACCESS, /* BTA_MAP_SERVICE_ID */ UUID_SERVCLASS_MESSAGE_NOTIFICATION, /* BTA_MN_SERVICE_ID */ UUID_SERVCLASS_HDP_PROFILE, /* BTA_HDP_SERVICE_ID */ UUID_SERVCLASS_PBAP_PCE, /* BTA_PCE_SERVICE_ID */ UUID_PROTOCOL_ATT /* BTA_GATT_SERVICE_ID */ }; /* * NOTE : The number of element in bta_service_id_to_btm_srv_id_lkup_tbl should * be matching with * the value BTA_MAX_SERVICE_ID in bta_api.h * * i.e., If you add new Service ID for BTA, the correct security ID of * the new service * from Security service definitions (btm_api.h) should be added to * this lookup table. */ const uint32_t bta_service_id_to_btm_srv_id_lkup_tbl[BTA_MAX_SERVICE_ID] = { 0, /* Reserved */ BTM_SEC_SERVICE_SERIAL_PORT, /* BTA_SPP_SERVICE_ID */ BTM_SEC_SERVICE_DUN, /* BTA_DUN_SERVICE_ID */ BTM_SEC_SERVICE_AVDTP, /* BTA_AUDIO_SOURCE_SERVICE_ID */ BTM_SEC_SERVICE_LAN_ACCESS, /* BTA_LAP_SERVICE_ID */ BTM_SEC_SERVICE_HEADSET_AG, /* BTA_HSP_SERVICE_ID */ BTM_SEC_SERVICE_AG_HANDSFREE, /* BTA_HFP_SERVICE_ID */ BTM_SEC_SERVICE_OBEX, /* BTA_OPP_SERVICE_ID */ BTM_SEC_SERVICE_OBEX_FTP, /* BTA_FTP_SERVICE_ID */ BTM_SEC_SERVICE_CORDLESS, /* BTA_CTP_SERVICE_ID */ BTM_SEC_SERVICE_INTERCOM, /* BTA_ICP_SERVICE_ID */ BTM_SEC_SERVICE_IRMC_SYNC, /* BTA_SYNC_SERVICE_ID */ BTM_SEC_SERVICE_BPP_JOB, /* BTA_BPP_SERVICE_ID */ BTM_SEC_SERVICE_BIP, /* BTA_BIP_SERVICE_ID */ BTM_SEC_SERVICE_BNEP_PANU, /* BTA_PANU_SERVICE_ID */ BTM_SEC_SERVICE_BNEP_NAP, /* BTA_NAP_SERVICE_ID */ BTM_SEC_SERVICE_BNEP_GN, /* BTA_GN_SERVICE_ID */ BTM_SEC_SERVICE_SAP, /* BTA_SAP_SERVICE_ID */ BTM_SEC_SERVICE_AVDTP, /* BTA_A2DP_SERVICE_ID */ BTM_SEC_SERVICE_AVCTP, /* BTA_AVRCP_SERVICE_ID */ BTM_SEC_SERVICE_HIDH_SEC_CTRL, /* BTA_HID_SERVICE_ID */ BTM_SEC_SERVICE_AVDTP, /* BTA_VDP_SERVICE_ID */ BTM_SEC_SERVICE_PBAP, /* BTA_PBAP_SERVICE_ID */ BTM_SEC_SERVICE_HEADSET, /* BTA_HSP_HS_SERVICE_ID */ BTM_SEC_SERVICE_HF_HANDSFREE, /* BTA_HFP_HS_SERVICE_ID */ BTM_SEC_SERVICE_MAP, /* BTA_MAP_SERVICE_ID */ BTM_SEC_SERVICE_MAP, /* BTA_MN_SERVICE_ID */ BTM_SEC_SERVICE_HDP_SNK, /* BTA_HDP_SERVICE_ID */ BTM_SEC_SERVICE_PBAP, /* BTA_PCE_SERVICE_ID */ BTM_SEC_SERVICE_ATT /* BTA_GATT_SERVICE_ID */ }; /* bta security callback */ const tBTM_APPL_INFO bta_security = {&bta_dm_authorize_cback, &bta_dm_pin_cback, &bta_dm_new_link_key_cback, &bta_dm_authentication_complete_cback, &bta_dm_bond_cancel_complete_cback, #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE) &bta_dm_sp_cback, #else NULL, #endif &bta_dm_ble_smp_cback, &bta_dm_ble_id_key_cback}; #define MAX_DISC_RAW_DATA_BUF (4096) uint8_t g_disc_raw_data_buf[MAX_DISC_RAW_DATA_BUF]; extern DEV_CLASS local_device_default_class; extern fixed_queue_t* btu_bta_alarm_queue; /******************************************************************************* * * Function bta_dm_enable * * Description Initialises the BT device manager * * * Returns void * ******************************************************************************/ void bta_dm_enable(tBTA_DM_MSG* p_data) { tBTA_DM_ENABLE enable_event; /* if already in use, return an error */ if (bta_dm_cb.is_bta_dm_active == true) { APPL_TRACE_WARNING("%s Device already started by another application", __func__); memset(&enable_event, 0, sizeof(tBTA_DM_ENABLE)); enable_event.status = BTA_FAILURE; if (p_data->enable.p_sec_cback != NULL) p_data->enable.p_sec_cback(BTA_DM_ENABLE_EVT, (tBTA_DM_SEC*)&enable_event); return; } /* first, register our callback to SYS HW manager */ bta_sys_hw_register(BTA_SYS_HW_BLUETOOTH, bta_dm_sys_hw_cback); /* make sure security callback is saved - if no callback, do not erase the previous one, it could be an error recovery mechanism */ if (p_data->enable.p_sec_cback != NULL) bta_dm_cb.p_sec_cback = p_data->enable.p_sec_cback; /* notify BTA DM is now active */ bta_dm_cb.is_bta_dm_active = true; /* send a message to BTA SYS */ tBTA_SYS_HW_MSG* sys_enable_event = (tBTA_SYS_HW_MSG*)osi_malloc(sizeof(tBTA_SYS_HW_MSG)); sys_enable_event->hdr.event = BTA_SYS_API_ENABLE_EVT; sys_enable_event->hw_module = BTA_SYS_HW_BLUETOOTH; bta_sys_sendmsg(sys_enable_event); } /******************************************************************************* * * Function bta_dm_init_cb * * Description Initializes the bta_dm_cb control block * * * Returns void * ******************************************************************************/ void bta_dm_init_cb(void) { memset(&bta_dm_cb, 0, sizeof(bta_dm_cb)); bta_dm_cb.disable_timer = alarm_new("bta_dm.disable_timer"); bta_dm_cb.switch_delay_timer = alarm_new("bta_dm.switch_delay_timer"); for (size_t i = 0; i < BTA_DM_NUM_PM_TIMER; i++) { for (size_t j = 0; j < BTA_DM_PM_MODE_TIMER_MAX; j++) { bta_dm_cb.pm_timer[i].timer[j] = alarm_new("bta_dm.pm_timer"); } } } /******************************************************************************* * * Function bta_dm_deinit_cb * * Description De-initializes the bta_dm_cb control block * * * Returns void * ******************************************************************************/ void bta_dm_deinit_cb(void) { /* * TODO: Should alarm_free() the bta_dm_cb timers during graceful * shutdown. */ alarm_free(bta_dm_cb.disable_timer); alarm_free(bta_dm_cb.switch_delay_timer); for (size_t i = 0; i < BTA_DM_NUM_PM_TIMER; i++) { for (size_t j = 0; j < BTA_DM_PM_MODE_TIMER_MAX; j++) { alarm_free(bta_dm_cb.pm_timer[i].timer[j]); } } memset(&bta_dm_cb, 0, sizeof(bta_dm_cb)); } /******************************************************************************* * * Function bta_dm_sys_hw_cback * * Description callback register to SYS to get HW status updates * * * Returns void * ******************************************************************************/ static void bta_dm_sys_hw_cback(tBTA_SYS_HW_EVT status) { DEV_CLASS dev_class; tBTA_DM_SEC_CBACK* temp_cback; uint8_t key_mask = 0; BT_OCTET16 er; tBTA_BLE_LOCAL_ID_KEYS id_key; APPL_TRACE_DEBUG("%s with event: %i", __func__, status); /* On H/W error evt, report to the registered DM application callback */ if (status == BTA_SYS_HW_ERROR_EVT) { if (bta_dm_cb.p_sec_cback != NULL) bta_dm_cb.p_sec_cback(BTA_DM_HW_ERROR_EVT, NULL); return; } if (status == BTA_SYS_HW_OFF_EVT) { if (bta_dm_cb.p_sec_cback != NULL) bta_dm_cb.p_sec_cback(BTA_DM_DISABLE_EVT, NULL); /* reinitialize the control block */ bta_dm_deinit_cb(); /* hw is ready, go on with BTA DM initialization */ alarm_free(bta_dm_search_cb.search_timer); alarm_free(bta_dm_search_cb.gatt_close_timer); memset(&bta_dm_search_cb, 0, sizeof(bta_dm_search_cb)); /* unregister from SYS */ bta_sys_hw_unregister(BTA_SYS_HW_BLUETOOTH); /* notify BTA DM is now unactive */ bta_dm_cb.is_bta_dm_active = false; } else if (status == BTA_SYS_HW_ON_EVT) { /* FIXME: We should not unregister as the SYS shall invoke this callback on * a H/W error. * We need to revisit when this platform has more than one BLuetooth H/W * chip */ // bta_sys_hw_unregister( BTA_SYS_HW_BLUETOOTH); /* save security callback */ temp_cback = bta_dm_cb.p_sec_cback; /* make sure the control block is properly initialized */ bta_dm_init_cb(); /* and retrieve the callback */ bta_dm_cb.p_sec_cback = temp_cback; bta_dm_cb.is_bta_dm_active = true; /* hw is ready, go on with BTA DM initialization */ alarm_free(bta_dm_search_cb.search_timer); alarm_free(bta_dm_search_cb.gatt_close_timer); memset(&bta_dm_search_cb, 0, sizeof(bta_dm_search_cb)); /* * TODO: Should alarm_free() the bta_dm_search_cb timers during * graceful shutdown. */ bta_dm_search_cb.search_timer = alarm_new("bta_dm_search.search_timer"); bta_dm_search_cb.gatt_close_timer = alarm_new("bta_dm_search.gatt_close_timer"); memset(&bta_dm_conn_srvcs, 0, sizeof(bta_dm_conn_srvcs)); memset(&bta_dm_di_cb, 0, sizeof(tBTA_DM_DI_CB)); memcpy(dev_class, p_bta_dm_cfg->dev_class, sizeof(dev_class)); BTM_SetDeviceClass(dev_class); /* load BLE local information: ID keys, ER if available */ bta_dm_co_ble_load_local_keys(&key_mask, er, &id_key); if (key_mask & BTA_BLE_LOCAL_KEY_TYPE_ER) { BTM_BleLoadLocalKeys(BTA_BLE_LOCAL_KEY_TYPE_ER, (tBTM_BLE_LOCAL_KEYS*)&er); } if (key_mask & BTA_BLE_LOCAL_KEY_TYPE_ID) { BTM_BleLoadLocalKeys(BTA_BLE_LOCAL_KEY_TYPE_ID, (tBTM_BLE_LOCAL_KEYS*)&id_key); } bta_dm_search_cb.conn_id = BTA_GATT_INVALID_CONN_ID; BTM_SecRegister((tBTM_APPL_INFO*)&bta_security); BTM_SetDefaultLinkSuperTout(p_bta_dm_cfg->link_timeout); BTM_WritePageTimeout(p_bta_dm_cfg->page_timeout); bta_dm_cb.cur_policy = p_bta_dm_cfg->policy_settings; BTM_SetDefaultLinkPolicy(bta_dm_cb.cur_policy); BTM_RegBusyLevelNotif(bta_dm_bl_change_cback, NULL, BTM_BL_UPDATE_MASK | BTM_BL_ROLE_CHG_MASK); #if (BLE_VND_INCLUDED == TRUE) BTM_BleReadControllerFeatures(bta_dm_ctrl_features_rd_cmpl_cback); #else /* If VSC multi adv commands are available, advertising will be initialized * when capabilities are read. If they are not avaliable, initialize * advertising here */ btm_ble_adv_init(); #endif /* Earlier, we used to invoke BTM_ReadLocalAddr which was just copying the bd_addr from the control block and invoking the callback which was sending the DM_ENABLE_EVT. But then we have a few HCI commands being invoked above which were still in progress when the ENABLE_EVT was sent. So modified this to fetch the local name which forces the DM_ENABLE_EVT to be sent only after all the init steps are complete */ BTM_ReadLocalDeviceNameFromController( (tBTM_CMPL_CB*)bta_dm_local_name_cback); bta_sys_rm_register((tBTA_SYS_CONN_CBACK*)bta_dm_rm_cback); /* initialize bluetooth low power manager */ bta_dm_init_pm(); bta_sys_policy_register((tBTA_SYS_CONN_CBACK*)bta_dm_policy_cback); bta_dm_gattc_register(); } else APPL_TRACE_DEBUG(" --- ignored event"); } /******************************************************************************* * * Function bta_dm_disable * * Description Disables the BT device manager * * * Returns void * ******************************************************************************/ void bta_dm_disable(UNUSED_ATTR tBTA_DM_MSG* p_data) { /* Set l2cap idle timeout to 0 (so BTE immediately disconnects ACL link after * last channel is closed) */ L2CA_SetIdleTimeoutByBdAddr((uint8_t*)BT_BD_ANY, 0, BT_TRANSPORT_BR_EDR); L2CA_SetIdleTimeoutByBdAddr((uint8_t*)BT_BD_ANY, 0, BT_TRANSPORT_LE); /* disable all active subsystems */ bta_sys_disable(BTA_SYS_HW_BLUETOOTH); BTM_SetDiscoverability(BTM_NON_DISCOVERABLE, 0, 0); BTM_SetConnectability(BTM_NON_CONNECTABLE, 0, 0); bta_dm_disable_pm(); bta_dm_disable_search_and_disc(); bta_dm_cb.disabling = true; BTM_BleClearBgConnDev(); if (BTM_GetNumAclLinks() == 0) { #if (BTA_DISABLE_DELAY > 0) /* If BTA_DISABLE_DELAY is defined and greater than zero, then delay the * shutdown by * BTA_DISABLE_DELAY milliseconds */ APPL_TRACE_WARNING("%s BTA_DISABLE_DELAY set to %d ms", __func__, BTA_DISABLE_DELAY); alarm_set_on_queue(bta_dm_cb.disable_timer, BTA_DISABLE_DELAY, bta_dm_disable_conn_down_timer_cback, NULL, btu_bta_alarm_queue); #else bta_dm_disable_conn_down_timer_cback(NULL); #endif } else { alarm_set_on_queue(bta_dm_cb.disable_timer, BTA_DM_DISABLE_TIMER_MS, bta_dm_disable_timer_cback, UINT_TO_PTR(0), btu_bta_alarm_queue); } } /******************************************************************************* * * Function bta_dm_disable_timer_cback * * Description Called if the disable timer expires * Used to close ACL connections which are still active * * * * Returns void * ******************************************************************************/ static void bta_dm_disable_timer_cback(void* data) { uint8_t i; tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR; bool trigger_disc = false; uint32_t param = PTR_TO_UINT(data); APPL_TRACE_EVENT("%s trial %u", __func__, param); if (BTM_GetNumAclLinks() && (param == 0)) { for (i = 0; i < bta_dm_cb.device_list.count; i++) { transport = bta_dm_cb.device_list.peer_device[i].transport; btm_remove_acl(bta_dm_cb.device_list.peer_device[i].peer_bdaddr, transport); trigger_disc = true; } /* Retrigger disable timer in case ACL disconnect failed, DISABLE_EVT still need to be sent out to avoid jave layer disable timeout */ if (trigger_disc) { alarm_set_on_queue( bta_dm_cb.disable_timer, BTA_DM_DISABLE_TIMER_RETRIAL_MS, bta_dm_disable_timer_cback, UINT_TO_PTR(1), btu_bta_alarm_queue); } } else { bta_dm_cb.disabling = false; bta_sys_remove_uuid(UUID_SERVCLASS_PNP_INFORMATION); bta_dm_cb.p_sec_cback(BTA_DM_DISABLE_EVT, NULL); } } /******************************************************************************* * * Function bta_dm_set_dev_name * * Description Sets local device name * * * Returns void * ******************************************************************************/ void bta_dm_set_dev_name(tBTA_DM_MSG* p_data) { BTM_SetLocalDeviceName((char*)p_data->set_name.name); bta_dm_set_eir((char*)p_data->set_name.name); } /******************************************************************************* * * Function bta_dm_set_visibility * * Description Sets discoverability, connectability and pairability * * * Returns void * ******************************************************************************/ void bta_dm_set_visibility(tBTA_DM_MSG* p_data) { uint16_t window, interval; uint16_t le_disc_mode = BTM_BleReadDiscoverability(); uint16_t le_conn_mode = BTM_BleReadConnectability(); uint16_t disc_mode = BTM_ReadDiscoverability(&window, &interval); uint16_t conn_mode = BTM_ReadConnectability(&window, &interval); /* set modes for Discoverability and connectability if not ignore */ if (p_data->set_visibility.disc_mode != (BTA_DM_IGNORE | BTA_DM_LE_IGNORE)) { if ((p_data->set_visibility.disc_mode & BTA_DM_LE_IGNORE) == BTA_DM_LE_IGNORE) p_data->set_visibility.disc_mode = ((p_data->set_visibility.disc_mode & ~BTA_DM_LE_IGNORE) | le_disc_mode); if ((p_data->set_visibility.disc_mode & BTA_DM_IGNORE) == BTA_DM_IGNORE) p_data->set_visibility.disc_mode = ((p_data->set_visibility.disc_mode & ~BTA_DM_IGNORE) | disc_mode); BTM_SetDiscoverability(p_data->set_visibility.disc_mode, bta_dm_cb.inquiry_scan_window, bta_dm_cb.inquiry_scan_interval); } if (p_data->set_visibility.conn_mode != (BTA_DM_IGNORE | BTA_DM_LE_IGNORE)) { if ((p_data->set_visibility.conn_mode & BTA_DM_LE_IGNORE) == BTA_DM_LE_IGNORE) p_data->set_visibility.conn_mode = ((p_data->set_visibility.conn_mode & ~BTA_DM_LE_IGNORE) | le_conn_mode); if ((p_data->set_visibility.conn_mode & BTA_DM_IGNORE) == BTA_DM_IGNORE) p_data->set_visibility.conn_mode = ((p_data->set_visibility.conn_mode & ~BTA_DM_IGNORE) | conn_mode); BTM_SetConnectability(p_data->set_visibility.conn_mode, bta_dm_cb.page_scan_window, bta_dm_cb.page_scan_interval); } /* Send False or True if not ignore */ if (p_data->set_visibility.pair_mode != BTA_DM_IGNORE) { if (p_data->set_visibility.pair_mode == BTA_DM_NON_PAIRABLE) bta_dm_cb.disable_pair_mode = true; else bta_dm_cb.disable_pair_mode = false; } /* Send False or True if not ignore */ if (p_data->set_visibility.conn_paired_only != BTA_DM_IGNORE) { if (p_data->set_visibility.conn_paired_only == BTA_DM_CONN_ALL) bta_dm_cb.conn_paired_only = false; else bta_dm_cb.conn_paired_only = true; } /* Change mode if either mode is not ignore */ if (p_data->set_visibility.pair_mode != BTA_DM_IGNORE || p_data->set_visibility.conn_paired_only != BTA_DM_IGNORE) BTM_SetPairableMode((bool)(!(bta_dm_cb.disable_pair_mode)), bta_dm_cb.conn_paired_only); } /******************************************************************************* * * Function bta_dm_process_remove_device * * Description Removes device, Disconnects ACL link if required. *** ******************************************************************************/ void bta_dm_process_remove_device(BD_ADDR bd_addr) { /* need to remove all pending background connection before unpair */ BTA_GATTC_CancelOpen(0, bd_addr, false); BTM_SecDeleteDevice(bd_addr); /* remove all cached GATT information */ bt_bdaddr_t tmp_addr; memcpy(tmp_addr.address, bd_addr, BD_ADDR_LEN); BTA_GATTC_Refresh(tmp_addr); if (bta_dm_cb.p_sec_cback) { tBTA_DM_SEC sec_event; bdcpy(sec_event.link_down.bd_addr, bd_addr); /* No connection, set status to success (acl disc code not valid) */ sec_event.link_down.status = HCI_SUCCESS; bta_dm_cb.p_sec_cback(BTA_DM_DEV_UNPAIRED_EVT, &sec_event); } } /******************************************************************************* * * Function bta_dm_remove_device * * Description Removes device, disconnects ACL link if required. *** ******************************************************************************/ void bta_dm_remove_device(tBTA_DM_MSG* p_data) { tBTA_DM_API_REMOVE_DEVICE* p_dev = &p_data->remove_dev; bool continue_delete_other_dev = false; if (p_dev == NULL) return; BD_ADDR other_address; bdcpy(other_address, p_dev->bd_addr); /* If ACL exists for the device in the remove_bond message*/ bool continue_delete_dev = false; uint8_t other_transport = BT_TRANSPORT_INVALID; if (BTM_IsAclConnectionUp(p_dev->bd_addr, BT_TRANSPORT_LE) || BTM_IsAclConnectionUp(p_dev->bd_addr, BT_TRANSPORT_BR_EDR)) { APPL_TRACE_DEBUG("%s: ACL Up count %d", __func__, bta_dm_cb.device_list.count); continue_delete_dev = false; /* Take the link down first, and mark the device for removal when * disconnected */ for (int i = 0; i < bta_dm_cb.device_list.count; i++) { if (!bdcmp(bta_dm_cb.device_list.peer_device[i].peer_bdaddr, p_dev->bd_addr)) { uint8_t transport = BT_TRANSPORT_BR_EDR; transport = bta_dm_cb.device_list.peer_device[i].transport; bta_dm_cb.device_list.peer_device[i].conn_state = BTA_DM_UNPAIRING; btm_remove_acl(p_dev->bd_addr, transport); APPL_TRACE_DEBUG("%s:transport = %d", __func__, bta_dm_cb.device_list.peer_device[i].transport); /* save the other transport to check if device is connected on * other_transport */ if (bta_dm_cb.device_list.peer_device[i].transport == BT_TRANSPORT_LE) other_transport = BT_TRANSPORT_BR_EDR; else other_transport = BT_TRANSPORT_LE; break; } } } else { continue_delete_dev = true; } // If it is DUMO device and device is paired as different address, unpair that // device // if different address if ((other_transport && (BTM_ReadConnectedTransportAddress(other_address, other_transport))) || (!other_transport && (BTM_ReadConnectedTransportAddress(other_address, BT_TRANSPORT_BR_EDR) || BTM_ReadConnectedTransportAddress(other_address, BT_TRANSPORT_LE)))) { continue_delete_other_dev = false; /* Take the link down first, and mark the device for removal when * disconnected */ for (int i = 0; i < bta_dm_cb.device_list.count; i++) { if (!bdcmp(bta_dm_cb.device_list.peer_device[i].peer_bdaddr, other_address)) { bta_dm_cb.device_list.peer_device[i].conn_state = BTA_DM_UNPAIRING; btm_remove_acl(other_address, bta_dm_cb.device_list.peer_device[i].transport); break; } } } else { APPL_TRACE_DEBUG("%s: continue to delete the other dev ", __func__); continue_delete_other_dev = true; } /* Delete the device mentioned in the msg */ if (continue_delete_dev) bta_dm_process_remove_device(p_dev->bd_addr); /* Delete the other paired device too */ BD_ADDR dummy_bda = {0}; if (continue_delete_other_dev && (bdcmp(other_address, dummy_bda) != 0)) bta_dm_process_remove_device(other_address); } /******************************************************************************* * * Function bta_dm_add_device * * Description This function adds a Link Key to an security database entry. * It is normally called during host startup to restore all * required information stored in the NVRAM. *** ******************************************************************************/ void bta_dm_add_device(tBTA_DM_MSG* p_data) { tBTA_DM_API_ADD_DEVICE* p_dev = &p_data->add_dev; uint8_t* p_dc = NULL; uint8_t* p_lc = NULL; uint32_t trusted_services_mask[BTM_SEC_SERVICE_ARRAY_SIZE]; uint8_t index = 0; uint8_t btm_mask_index = 0; memset(trusted_services_mask, 0, sizeof(trusted_services_mask)); /* If not all zeros, the device class has been specified */ if (p_dev->dc_known) p_dc = (uint8_t*)p_dev->dc; if (p_dev->link_key_known) p_lc = (uint8_t*)p_dev->link_key; if (p_dev->is_trusted) { /* covert BTA service mask to BTM mask */ while (p_dev->tm && (index < BTA_MAX_SERVICE_ID)) { if (p_dev->tm & (uint32_t)(1 << index)) { btm_mask_index = bta_service_id_to_btm_srv_id_lkup_tbl[index] / BTM_SEC_ARRAY_BITS; trusted_services_mask[btm_mask_index] |= (uint32_t)(1 << (bta_service_id_to_btm_srv_id_lkup_tbl[index] - (uint32_t)(btm_mask_index * 32))); p_dev->tm &= (uint32_t)(~(1 << index)); } index++; } } if (!BTM_SecAddDevice(p_dev->bd_addr, p_dc, p_dev->bd_name, p_dev->features, trusted_services_mask, p_lc, p_dev->key_type, p_dev->io_cap, p_dev->pin_length)) { APPL_TRACE_ERROR("BTA_DM: Error adding device %08x%04x", (p_dev->bd_addr[0] << 24) + (p_dev->bd_addr[1] << 16) + (p_dev->bd_addr[2] << 8) + p_dev->bd_addr[3], (p_dev->bd_addr[4] << 8) + p_dev->bd_addr[5]); } } /******************************************************************************* * * Function bta_dm_close_acl * * Description This function forces to close the connection to a remote * device and optionaly remove the device from security * database if required. *** ******************************************************************************/ void bta_dm_close_acl(tBTA_DM_MSG* p_data) { tBTA_DM_API_REMOVE_ACL* p_remove_acl = &p_data->remove_acl; uint8_t index; APPL_TRACE_DEBUG("bta_dm_close_acl"); if (BTM_IsAclConnectionUp(p_remove_acl->bd_addr, p_remove_acl->transport)) { for (index = 0; index < bta_dm_cb.device_list.count; index++) { if (!bdcmp(bta_dm_cb.device_list.peer_device[index].peer_bdaddr, p_remove_acl->bd_addr)) break; } if (index != bta_dm_cb.device_list.count) { if (p_remove_acl->remove_dev) bta_dm_cb.device_list.peer_device[index].remove_dev_pending = true; } else { APPL_TRACE_ERROR("unknown device, remove ACL failed"); } /* Disconnect the ACL link */ btm_remove_acl(p_remove_acl->bd_addr, p_remove_acl->transport); } /* if to remove the device from security database ? do it now */ else if (p_remove_acl->remove_dev) { if (!BTM_SecDeleteDevice(p_remove_acl->bd_addr)) { APPL_TRACE_ERROR("delete device from security database failed."); } /* need to remove all pending background connection if any */ BTA_GATTC_CancelOpen(0, p_remove_acl->bd_addr, false); /* remove all cached GATT information */ bt_bdaddr_t tmp_addr; memcpy(tmp_addr.address, p_remove_acl->bd_addr, BD_ADDR_LEN); BTA_GATTC_Refresh(tmp_addr); } /* otherwise, no action needed */ } /******************************************************************************* * * Function bta_dm_remove_all_acl * * Description This function forces to close all the ACL links specified by * link type *** ******************************************************************************/ void bta_dm_remove_all_acl(tBTA_DM_MSG* p_data) { const tBTA_DM_LINK_TYPE link_type = p_data->remove_all_acl.link_type; tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR; APPL_TRACE_DEBUG("%s link type = %d", __func__, link_type); for (uint8_t i = 0; i < bta_dm_cb.device_list.count; i++) { BD_ADDR addr = {0}; bdcpy(addr, bta_dm_cb.device_list.peer_device[i].peer_bdaddr); transport = bta_dm_cb.device_list.peer_device[i].transport; if ((link_type == BTA_DM_LINK_TYPE_ALL) || ((link_type == BTA_DM_LINK_TYPE_LE) && (transport == BT_TRANSPORT_LE)) || ((link_type == BTA_DM_LINK_TYPE_BR_EDR) && (transport == BT_TRANSPORT_BR_EDR))) { /* Disconnect the ACL link */ btm_remove_acl(addr, transport); } } } /******************************************************************************* * * Function bta_dm_bond * * Description Bonds with peer device * * * Returns void * ******************************************************************************/ void bta_dm_bond(tBTA_DM_MSG* p_data) { tBTM_STATUS status; tBTA_DM_SEC sec_event; char* p_name; if (p_data->bond.transport == BTA_TRANSPORT_UNKNOWN) status = BTM_SecBond(p_data->bond.bd_addr, 0, NULL, 0); else status = BTM_SecBondByTransport(p_data->bond.bd_addr, p_data->bond.transport, 0, NULL, 0); if (bta_dm_cb.p_sec_cback && (status != BTM_CMD_STARTED)) { memset(&sec_event, 0, sizeof(tBTA_DM_SEC)); bdcpy(sec_event.auth_cmpl.bd_addr, p_data->bond.bd_addr); p_name = BTM_SecReadDevName(p_data->bond.bd_addr); if (p_name != NULL) { memcpy(sec_event.auth_cmpl.bd_name, p_name, (BD_NAME_LEN - 1)); sec_event.auth_cmpl.bd_name[BD_NAME_LEN - 1] = 0; } /* taken care of by memset [above] sec_event.auth_cmpl.key_present = false; sec_event.auth_cmpl.success = false; */ sec_event.auth_cmpl.fail_reason = HCI_ERR_ILLEGAL_COMMAND; if (status == BTM_SUCCESS) { sec_event.auth_cmpl.success = true; } else { /* delete this device entry from Sec Dev DB */ bta_dm_remove_sec_dev_entry(p_data->bond.bd_addr); } bta_dm_cb.p_sec_cback(BTA_DM_AUTH_CMPL_EVT, &sec_event); } } /******************************************************************************* * * Function bta_dm_bond_cancel * * Description Cancels bonding with a peer device * * * Returns void * ******************************************************************************/ void bta_dm_bond_cancel(tBTA_DM_MSG* p_data) { tBTM_STATUS status; tBTA_DM_SEC sec_event; APPL_TRACE_EVENT(" bta_dm_bond_cancel "); status = BTM_SecBondCancel(p_data->bond_cancel.bd_addr); if (bta_dm_cb.p_sec_cback && (status != BTM_CMD_STARTED && status != BTM_SUCCESS)) { sec_event.bond_cancel_cmpl.result = BTA_FAILURE; bta_dm_cb.p_sec_cback(BTA_DM_BOND_CANCEL_CMPL_EVT, &sec_event); } } /******************************************************************************* * * Function bta_dm_pin_reply * * Description Send the pin_reply to a request from BTM * * * Returns void * ******************************************************************************/ void bta_dm_pin_reply(tBTA_DM_MSG* p_data) { uint32_t trusted_mask[BTM_SEC_SERVICE_ARRAY_SIZE]; uint32_t* current_trusted_mask; current_trusted_mask = BTM_ReadTrustedMask(p_data->pin_reply.bd_addr); if (current_trusted_mask) { memcpy(trusted_mask, current_trusted_mask, sizeof(trusted_mask)); } else { memset(trusted_mask, 0, sizeof(trusted_mask)); } if (p_data->pin_reply.accept) { BTM_PINCodeReply(p_data->pin_reply.bd_addr, BTM_SUCCESS, p_data->pin_reply.pin_len, p_data->pin_reply.p_pin, trusted_mask); } else { BTM_PINCodeReply(p_data->pin_reply.bd_addr, BTM_NOT_AUTHORIZED, 0, NULL, trusted_mask); } } /******************************************************************************* * * Function bta_dm_policy_cback * * Description process the link policy changes * * Returns void * ******************************************************************************/ static void bta_dm_policy_cback(tBTA_SYS_CONN_STATUS status, uint8_t id, uint8_t app_id, BD_ADDR peer_addr) { tBTA_DM_PEER_DEVICE* p_dev = NULL; uint16_t policy = app_id; uint32_t mask = (uint32_t)(1 << id); if (peer_addr) p_dev = bta_dm_find_peer_device(peer_addr); APPL_TRACE_DEBUG(" bta_dm_policy_cback cmd:%d, policy:0x%x", status, policy); switch (status) { case BTA_SYS_PLCY_SET: if (!p_dev) return; /* restore the default link policy */ p_dev->link_policy |= policy; BTM_SetLinkPolicy(p_dev->peer_bdaddr, &(p_dev->link_policy)); break; case BTA_SYS_PLCY_CLR: if (!p_dev) return; /* clear the policy from the default link policy */ p_dev->link_policy &= (~policy); BTM_SetLinkPolicy(p_dev->peer_bdaddr, &(p_dev->link_policy)); if (policy & (HCI_ENABLE_SNIFF_MODE | HCI_ENABLE_PARK_MODE)) { /* if clearing sniff/park, wake the link */ bta_dm_pm_active(p_dev->peer_bdaddr); } break; case BTA_SYS_PLCY_DEF_SET: /* want to restore/set the role switch policy */ bta_dm_cb.role_policy_mask &= ~mask; if (0 == bta_dm_cb.role_policy_mask) { /* if nobody wants to insist on the role */ bta_dm_cb.cur_policy |= HCI_ENABLE_MASTER_SLAVE_SWITCH; BTM_SetDefaultLinkPolicy(bta_dm_cb.cur_policy); } break; case BTA_SYS_PLCY_DEF_CLR: /* want to remove the role switch policy */ bta_dm_cb.role_policy_mask |= mask; bta_dm_cb.cur_policy &= ~HCI_ENABLE_MASTER_SLAVE_SWITCH; BTM_SetDefaultLinkPolicy(bta_dm_cb.cur_policy); break; } } /******************************************************************************* * * Function bta_dm_confirm * * Description Send the user confirm request reply in response to a * request from BTM * * Returns void * ******************************************************************************/ void bta_dm_confirm(tBTA_DM_MSG* p_data) { tBTM_STATUS res = BTM_NOT_AUTHORIZED; if (p_data->confirm.accept == true) res = BTM_SUCCESS; BTM_ConfirmReqReply(res, p_data->confirm.bd_addr); } /******************************************************************************* * * Function bta_dm_loc_oob * * Description Retrieve the OOB data from the local LM * * Returns void * ******************************************************************************/ void bta_dm_loc_oob(UNUSED_ATTR tBTA_DM_MSG* p_data) { BTM_ReadLocalOobData(); } /******************************************************************************* * * Function bta_dm_ci_io_req_act * * Description respond to the IO capabilities request from BTM * * Returns void * ******************************************************************************/ void bta_dm_ci_io_req_act(tBTA_DM_MSG* p_data) { tBTM_AUTH_REQ auth_req = BTM_AUTH_AP_NO; if (p_data->ci_io_req.auth_req) auth_req = BTM_AUTH_AP_YES; BTM_IoCapRsp(p_data->ci_io_req.bd_addr, p_data->ci_io_req.io_cap, p_data->ci_io_req.oob_data, auth_req); } /******************************************************************************* * * Function bta_dm_ci_rmt_oob_act * * Description respond to the OOB data request for the remote device from * BTM * * * Returns void * ******************************************************************************/ void bta_dm_ci_rmt_oob_act(tBTA_DM_MSG* p_data) { tBTM_STATUS res = BTM_NOT_AUTHORIZED; if (p_data->ci_rmt_oob.accept == true) res = BTM_SUCCESS; BTM_RemoteOobDataReply(res, p_data->ci_rmt_oob.bd_addr, p_data->ci_rmt_oob.c, p_data->ci_rmt_oob.r); } /******************************************************************************* * * Function bta_dm_search_start * * Description Starts an inquiry * * * Returns void * ******************************************************************************/ void bta_dm_search_start(tBTA_DM_MSG* p_data) { tBTM_INQUIRY_CMPL result; size_t len = sizeof(tBT_UUID) * p_data->search.num_uuid; bta_dm_gattc_register(); APPL_TRACE_DEBUG("%s avoid_scatter=%d", __func__, p_bta_dm_cfg->avoid_scatter); if (p_bta_dm_cfg->avoid_scatter && (p_data->search.rs_res == BTA_DM_RS_NONE) && bta_dm_check_av(BTA_DM_API_SEARCH_EVT)) { memcpy(&bta_dm_cb.search_msg, &p_data->search, sizeof(tBTA_DM_API_SEARCH)); return; } BTM_ClearInqDb(NULL); /* save search params */ bta_dm_search_cb.p_search_cback = p_data->search.p_cback; bta_dm_search_cb.services = p_data->search.services; osi_free_and_reset((void**)&bta_dm_search_cb.p_srvc_uuid); if ((bta_dm_search_cb.num_uuid = p_data->search.num_uuid) != 0 && p_data->search.p_uuid != NULL) { bta_dm_search_cb.p_srvc_uuid = (tBT_UUID*)osi_malloc(len); memcpy(bta_dm_search_cb.p_srvc_uuid, p_data->search.p_uuid, len); } result.status = BTM_StartInquiry((tBTM_INQ_PARMS*)&p_data->search.inq_params, bta_dm_inq_results_cb, (tBTM_CMPL_CB*)bta_dm_inq_cmpl_cb); APPL_TRACE_EVENT("%s status=%d", __func__, result.status); if (result.status != BTM_CMD_STARTED) { result.num_resp = 0; bta_dm_inq_cmpl_cb((void*)&result); } } /******************************************************************************* * * Function bta_dm_search_cancel * * Description Cancels an ongoing search for devices * * * Returns void * ******************************************************************************/ void bta_dm_search_cancel(UNUSED_ATTR tBTA_DM_MSG* p_data) { tBTA_DM_MSG* p_msg; if (BTM_IsInquiryActive()) { if (BTM_CancelInquiry() == BTM_SUCCESS) { bta_dm_search_cancel_notify(NULL); p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG)); p_msg->hdr.event = BTA_DM_SEARCH_CMPL_EVT; p_msg->hdr.layer_specific = BTA_DM_API_DISCOVER_EVT; bta_sys_sendmsg(p_msg); } else { /* flag a search cancel is pending */ bta_dm_search_cb.cancel_pending = true; } } /* If no Service Search going on then issue cancel remote name in case it is active */ else if (!bta_dm_search_cb.name_discover_done) { BTM_CancelRemoteDeviceName(); p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG)); p_msg->hdr.event = BTA_DM_SEARCH_CMPL_EVT; p_msg->hdr.layer_specific = BTA_DM_API_DISCOVER_EVT; bta_sys_sendmsg(p_msg); } else { p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG)); p_msg->hdr.event = BTA_DM_INQUIRY_CMPL_EVT; p_msg->hdr.layer_specific = BTA_DM_API_DISCOVER_EVT; bta_sys_sendmsg(p_msg); } if (bta_dm_search_cb.gatt_disc_active) { bta_dm_cancel_gatt_discovery(bta_dm_search_cb.peer_bdaddr); } } /******************************************************************************* * * Function bta_dm_discover * * Description Discovers services on a remote device * * * Returns void * ******************************************************************************/ void bta_dm_discover(tBTA_DM_MSG* p_data) { size_t len = sizeof(tBT_UUID) * p_data->discover.num_uuid; APPL_TRACE_EVENT("%s services_to_search=0x%04X, sdp_search=%d", __func__, p_data->discover.services, p_data->discover.sdp_search); /* save the search condition */ bta_dm_search_cb.services = p_data->discover.services; bta_dm_gattc_register(); osi_free_and_reset((void**)&bta_dm_search_cb.p_srvc_uuid); if ((bta_dm_search_cb.num_uuid = p_data->discover.num_uuid) != 0 && p_data->discover.p_uuid != NULL) { bta_dm_search_cb.p_srvc_uuid = (tBT_UUID*)osi_malloc(len); memcpy(bta_dm_search_cb.p_srvc_uuid, p_data->discover.p_uuid, len); } bta_dm_search_cb.uuid_to_search = bta_dm_search_cb.num_uuid; bta_dm_search_cb.p_search_cback = p_data->discover.p_cback; bta_dm_search_cb.sdp_search = p_data->discover.sdp_search; bta_dm_search_cb.services_to_search = bta_dm_search_cb.services; bta_dm_search_cb.service_index = 0; bta_dm_search_cb.services_found = 0; bta_dm_search_cb.peer_name[0] = 0; bta_dm_search_cb.sdp_search = p_data->discover.sdp_search; bta_dm_search_cb.p_btm_inq_info = BTM_InqDbRead(p_data->discover.bd_addr); bta_dm_search_cb.transport = p_data->discover.transport; bta_dm_search_cb.name_discover_done = false; memcpy(&bta_dm_search_cb.uuid, &p_data->discover.uuid, sizeof(tSDP_UUID)); bta_dm_discover_device(p_data->discover.bd_addr); } /******************************************************************************* * * Function bta_dm_di_disc_cmpl * * Description Sends event to application when DI discovery complete * * Returns void * ******************************************************************************/ void bta_dm_di_disc_cmpl(tBTA_DM_MSG* p_data) { tBTA_DM_DI_DISC_CMPL di_disc; memset(&di_disc, 0, sizeof(tBTA_DM_DI_DISC_CMPL)); bdcpy(di_disc.bd_addr, bta_dm_search_cb.peer_bdaddr); if ((p_data->hdr.offset == SDP_SUCCESS) || (p_data->hdr.offset == SDP_DB_FULL)) { di_disc.num_record = SDP_GetNumDiRecords(bta_dm_di_cb.p_di_db); } else di_disc.result = BTA_FAILURE; bta_dm_di_cb.p_di_db = NULL; bta_dm_search_cb.p_search_cback(BTA_DM_DI_DISC_CMPL_EVT, (tBTA_DM_SEARCH*)&di_disc); } /******************************************************************************* * * Function bta_dm_di_disc_callback * * Description This function queries a remote device for DI information. * * * Returns void * ******************************************************************************/ static void bta_dm_di_disc_callback(uint16_t result) { tBTA_DM_MSG* p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG)); p_msg->hdr.event = BTA_DM_SEARCH_CMPL_EVT; p_msg->hdr.layer_specific = BTA_DM_API_DI_DISCOVER_EVT; p_msg->hdr.offset = result; bta_sys_sendmsg(p_msg); } /******************************************************************************* * * Function bta_dm_disable_search_and_disc * * Description Cancels an ongoing search or discovery for devices in case * of a Bluetooth disable * * * Returns void * ******************************************************************************/ static void bta_dm_disable_search_and_disc(void) { tBTA_DM_DI_DISC_CMPL di_disc; if (bta_dm_search_cb.state != BTA_DM_SEARCH_IDLE) bta_dm_search_cancel(NULL); if (bta_dm_di_cb.p_di_db != NULL) { memset(&di_disc, 0, sizeof(tBTA_DM_DI_DISC_CMPL)); bdcpy(di_disc.bd_addr, bta_dm_search_cb.peer_bdaddr); di_disc.result = BTA_FAILURE; bta_dm_di_cb.p_di_db = NULL; bta_dm_search_cb.p_search_cback(BTA_DM_DI_DISC_CMPL_EVT, NULL); } } /******************************************************************************* * * Function bta_dm_di_disc * * Description This function queries a remote device for DI information. * * * Returns void * ******************************************************************************/ void bta_dm_di_disc(tBTA_DM_MSG* p_data) { uint16_t result = BTA_FAILURE; bta_dm_search_cb.p_search_cback = p_data->di_disc.p_cback; bdcpy(bta_dm_search_cb.peer_bdaddr, p_data->di_disc.bd_addr); bta_dm_di_cb.p_di_db = p_data->di_disc.p_sdp_db; bta_dm_search_cb.p_sdp_db = (tSDP_DISCOVERY_DB*)osi_malloc(BTA_DM_SDP_DB_SIZE); if (SDP_DiDiscover(bta_dm_search_cb.peer_bdaddr, p_data->di_disc.p_sdp_db, p_data->di_disc.len, bta_dm_di_disc_callback) == SDP_SUCCESS) { result = BTA_SUCCESS; } if (result == BTA_FAILURE) { tBTA_DM_MSG* p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG)); p_msg->hdr.event = BTA_DM_SEARCH_CMPL_EVT; p_msg->hdr.layer_specific = BTA_DM_API_DI_DISCOVER_EVT; p_data->hdr.offset = result; bta_sys_sendmsg(p_msg); } } /******************************************************************************* * * Function bta_dm_read_remote_device_name * * Description Initiate to get remote device name * * Returns true if started to get remote name * ******************************************************************************/ static bool bta_dm_read_remote_device_name(BD_ADDR bd_addr, tBT_TRANSPORT transport) { tBTM_STATUS btm_status; APPL_TRACE_DEBUG("bta_dm_read_remote_device_name"); bdcpy(bta_dm_search_cb.peer_bdaddr, bd_addr); bta_dm_search_cb.peer_name[0] = 0; btm_status = BTM_ReadRemoteDeviceName(bta_dm_search_cb.peer_bdaddr, (tBTM_CMPL_CB*)bta_dm_remname_cback, transport); if (btm_status == BTM_CMD_STARTED) { APPL_TRACE_DEBUG( "bta_dm_read_remote_device_name: BTM_ReadRemoteDeviceName is started"); return (true); } else if (btm_status == BTM_BUSY) { APPL_TRACE_DEBUG( "bta_dm_read_remote_device_name: BTM_ReadRemoteDeviceName is busy"); /* Remote name discovery is on going now so BTM cannot notify through * "bta_dm_remname_cback" */ /* adding callback to get notified that current reading remore name done */ BTM_SecAddRmtNameNotifyCallback(&bta_dm_service_search_remname_cback); return (true); } else { APPL_TRACE_WARNING( "bta_dm_read_remote_device_name: BTM_ReadRemoteDeviceName returns " "0x%02X", btm_status); return (false); } } /******************************************************************************* * * Function bta_dm_inq_cmpl * * Description Process the inquiry complete event from BTM * * Returns void * ******************************************************************************/ void bta_dm_inq_cmpl(tBTA_DM_MSG* p_data) { tBTA_DM_SEARCH data; APPL_TRACE_DEBUG("bta_dm_inq_cmpl"); data.inq_cmpl.num_resps = p_data->inq_cmpl.num; bta_dm_search_cb.p_search_cback(BTA_DM_INQ_CMPL_EVT, &data); bta_dm_search_cb.p_btm_inq_info = BTM_InqDbFirst(); if (bta_dm_search_cb.p_btm_inq_info != NULL) { /* start name and service discovery from the first device on inquiry result */ bta_dm_search_cb.name_discover_done = false; bta_dm_search_cb.peer_name[0] = 0; bta_dm_discover_device( bta_dm_search_cb.p_btm_inq_info->results.remote_bd_addr); } else { tBTA_DM_MSG* p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG)); /* no devices, search complete */ bta_dm_search_cb.services = 0; p_msg->hdr.event = BTA_DM_SEARCH_CMPL_EVT; p_msg->hdr.layer_specific = BTA_DM_API_DISCOVER_EVT; bta_sys_sendmsg(p_msg); } } /******************************************************************************* * * Function bta_dm_rmt_name * * Description Process the remote name result from BTM * * Returns void * ******************************************************************************/ void bta_dm_rmt_name(tBTA_DM_MSG* p_data) { APPL_TRACE_DEBUG("bta_dm_rmt_name"); if (p_data->rem_name.result.disc_res.bd_name[0] && bta_dm_search_cb.p_btm_inq_info) { bta_dm_search_cb.p_btm_inq_info->appl_knows_rem_name = true; } bta_dm_discover_device(bta_dm_search_cb.peer_bdaddr); } /******************************************************************************* * * Function bta_dm_disc_rmt_name * * Description Process the remote name result from BTM when application * wants to find the name for a bdaddr * * Returns void * ******************************************************************************/ void bta_dm_disc_rmt_name(tBTA_DM_MSG* p_data) { tBTM_INQ_INFO* p_btm_inq_info; APPL_TRACE_DEBUG("bta_dm_disc_rmt_name"); p_btm_inq_info = BTM_InqDbRead(p_data->rem_name.result.disc_res.bd_addr); if (p_btm_inq_info) { if (p_data->rem_name.result.disc_res.bd_name[0]) { p_btm_inq_info->appl_knows_rem_name = true; } } bta_dm_discover_device(p_data->rem_name.result.disc_res.bd_addr); } /******************************************************************************* * * Function bta_dm_sdp_result * * Description Process the discovery result from sdp * * Returns void * ******************************************************************************/ void bta_dm_sdp_result(tBTA_DM_MSG* p_data) { tSDP_DISC_REC* p_sdp_rec = NULL; tBTA_DM_MSG* p_msg; bool scn_found = false; uint16_t service = 0xFFFF; tSDP_PROTOCOL_ELEM pe; tBT_UUID* p_uuid = bta_dm_search_cb.p_srvc_uuid; tBTA_DM_SEARCH result; tBT_UUID service_uuid; uint32_t num_uuids = 0; uint8_t uuid_list[32][MAX_UUID_SIZE]; // assuming a max of 32 services if ((p_data->sdp_event.sdp_result == SDP_SUCCESS) || (p_data->sdp_event.sdp_result == SDP_NO_RECS_MATCH) || (p_data->sdp_event.sdp_result == SDP_DB_FULL)) { APPL_TRACE_DEBUG("sdp_result::0x%x", p_data->sdp_event.sdp_result); do { p_sdp_rec = NULL; if (bta_dm_search_cb.service_index == (BTA_USER_SERVICE_ID + 1)) { p_sdp_rec = SDP_FindServiceUUIDInDb(bta_dm_search_cb.p_sdp_db, &bta_dm_search_cb.uuid, p_sdp_rec); if (p_sdp_rec && SDP_FindProtocolListElemInRec( p_sdp_rec, UUID_PROTOCOL_RFCOMM, &pe)) { bta_dm_search_cb.peer_scn = (uint8_t)pe.params[0]; scn_found = true; } } else { service = bta_service_id_to_uuid_lkup_tbl[bta_dm_search_cb.service_index - 1]; p_sdp_rec = SDP_FindServiceInDb(bta_dm_search_cb.p_sdp_db, service, p_sdp_rec); } /* finished with BR/EDR services, now we check the result for GATT based * service UUID */ if (bta_dm_search_cb.service_index == BTA_MAX_SERVICE_ID) { if (bta_dm_search_cb.uuid_to_search != 0 && p_uuid != NULL) { p_uuid += (bta_dm_search_cb.num_uuid - bta_dm_search_cb.uuid_to_search); /* only support 16 bits UUID for now */ service = p_uuid->uu.uuid16; } /* all GATT based services */ do { /* find a service record, report it */ p_sdp_rec = SDP_FindServiceInDb(bta_dm_search_cb.p_sdp_db, 0, p_sdp_rec); if (p_sdp_rec) { if (SDP_FindServiceUUIDInRec(p_sdp_rec, &service_uuid)) { /* send result back to app now, one by one */ bdcpy(result.disc_ble_res.bd_addr, bta_dm_search_cb.peer_bdaddr); strlcpy((char*)result.disc_ble_res.bd_name, bta_dm_get_remname(), BD_NAME_LEN); result.disc_ble_res.service.len = service_uuid.len; result.disc_ble_res.service.uu.uuid16 = service_uuid.uu.uuid16; bta_dm_search_cb.p_search_cback(BTA_DM_DISC_BLE_RES_EVT, &result); } } if (bta_dm_search_cb.uuid_to_search > 0) break; } while (p_sdp_rec); } else { /* SDP_DB_FULL means some records with the required attributes were received */ if (((p_data->sdp_event.sdp_result == SDP_DB_FULL) && bta_dm_search_cb.services != BTA_ALL_SERVICE_MASK) || (p_sdp_rec != NULL)) { if (service != UUID_SERVCLASS_PNP_INFORMATION) { uint16_t tmp_svc = 0xFFFF; bta_dm_search_cb.services_found |= (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK( bta_dm_search_cb.service_index - 1)); tmp_svc = bta_service_id_to_uuid_lkup_tbl[bta_dm_search_cb.service_index - 1]; /* Add to the list of UUIDs */ sdpu_uuid16_to_uuid128(tmp_svc, uuid_list[num_uuids]); num_uuids++; } } } if (bta_dm_search_cb.services == BTA_ALL_SERVICE_MASK && bta_dm_search_cb.services_to_search == 0) { if (bta_dm_search_cb.service_index == BTA_BLE_SERVICE_ID && bta_dm_search_cb.uuid_to_search > 0) bta_dm_search_cb.uuid_to_search--; if (bta_dm_search_cb.uuid_to_search == 0 || bta_dm_search_cb.service_index != BTA_BLE_SERVICE_ID) bta_dm_search_cb.service_index++; } else /* regular one service per search or PNP search */ break; } while (bta_dm_search_cb.service_index <= BTA_MAX_SERVICE_ID); APPL_TRACE_DEBUG("%s services_found = %04x", __func__, bta_dm_search_cb.services_found); /* Collect the 128-bit services here and put them into the list */ if (bta_dm_search_cb.services == BTA_ALL_SERVICE_MASK) { p_sdp_rec = NULL; do { tBT_UUID temp_uuid; /* find a service record, report it */ p_sdp_rec = SDP_FindServiceInDb_128bit(bta_dm_search_cb.p_sdp_db, p_sdp_rec); if (p_sdp_rec) { if (SDP_FindServiceUUIDInRec_128bit(p_sdp_rec, &temp_uuid)) { memcpy(uuid_list[num_uuids], temp_uuid.uu.uuid128, MAX_UUID_SIZE); num_uuids++; } } } while (p_sdp_rec); } /* if there are more services to search for */ if (bta_dm_search_cb.services_to_search) { /* Free up the p_sdp_db before checking the next one */ bta_dm_free_sdp_db(NULL); bta_dm_find_services(bta_dm_search_cb.peer_bdaddr); } else { /* callbacks */ /* start next bd_addr if necessary */ BTM_SecDeleteRmtNameNotifyCallback(&bta_dm_service_search_remname_cback); p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG)); p_msg->hdr.event = BTA_DM_DISCOVERY_RESULT_EVT; p_msg->disc_result.result.disc_res.result = BTA_SUCCESS; p_msg->disc_result.result.disc_res.p_raw_data = NULL; p_msg->disc_result.result.disc_res.raw_data_size = 0; p_msg->disc_result.result.disc_res.num_uuids = num_uuids; p_msg->disc_result.result.disc_res.p_uuid_list = NULL; if (num_uuids > 0) { p_msg->disc_result.result.disc_res.p_uuid_list = (uint8_t*)osi_malloc(num_uuids * MAX_UUID_SIZE); memcpy(p_msg->disc_result.result.disc_res.p_uuid_list, uuid_list, num_uuids * MAX_UUID_SIZE); } // Copy the raw_data to the discovery result structure if (bta_dm_search_cb.p_sdp_db != NULL && bta_dm_search_cb.p_sdp_db->raw_used != 0 && bta_dm_search_cb.p_sdp_db->raw_data != NULL) { APPL_TRACE_DEBUG("%s raw_data used = 0x%x raw_data_ptr = 0x%x", __func__, bta_dm_search_cb.p_sdp_db->raw_used, bta_dm_search_cb.p_sdp_db->raw_data); p_msg->disc_result.result.disc_res.p_raw_data = (uint8_t*)osi_malloc(bta_dm_search_cb.p_sdp_db->raw_used); memcpy(p_msg->disc_result.result.disc_res.p_raw_data, bta_dm_search_cb.p_sdp_db->raw_data, bta_dm_search_cb.p_sdp_db->raw_used); p_msg->disc_result.result.disc_res.raw_data_size = bta_dm_search_cb.p_sdp_db->raw_used; bta_dm_search_cb.p_sdp_db->raw_data = NULL; // no need to free this - it is a global assigned. bta_dm_search_cb.p_sdp_db->raw_used = 0; bta_dm_search_cb.p_sdp_db->raw_size = 0; } else { APPL_TRACE_DEBUG("%s raw data size is 0 or raw_data is null!!", __func__); } /* Done with p_sdp_db. Free it */ bta_dm_free_sdp_db(NULL); p_msg->disc_result.result.disc_res.services = bta_dm_search_cb.services_found; // Piggy back the SCN over result field if (scn_found) { p_msg->disc_result.result.disc_res.result = (3 + bta_dm_search_cb.peer_scn); p_msg->disc_result.result.disc_res.services |= BTA_USER_SERVICE_MASK; APPL_TRACE_EVENT(" Piggy back the SCN over result field SCN=%d", bta_dm_search_cb.peer_scn); } bdcpy(p_msg->disc_result.result.disc_res.bd_addr, bta_dm_search_cb.peer_bdaddr); strlcpy((char*)p_msg->disc_result.result.disc_res.bd_name, bta_dm_get_remname(), BD_NAME_LEN); bta_sys_sendmsg(p_msg); } } else { /* conn failed. No need for timer */ if (p_data->sdp_event.sdp_result == SDP_CONN_FAILED || p_data->sdp_event.sdp_result == SDP_CONN_REJECTED || p_data->sdp_event.sdp_result == SDP_SECURITY_ERR) bta_dm_search_cb.wait_disc = false; /* not able to connect go to next device */ if (bta_dm_search_cb.p_sdp_db) osi_free_and_reset((void**)&bta_dm_search_cb.p_sdp_db); BTM_SecDeleteRmtNameNotifyCallback(&bta_dm_service_search_remname_cback); p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG)); p_msg->hdr.event = BTA_DM_DISCOVERY_RESULT_EVT; p_msg->disc_result.result.disc_res.result = BTA_FAILURE; p_msg->disc_result.result.disc_res.services = bta_dm_search_cb.services_found; bdcpy(p_msg->disc_result.result.disc_res.bd_addr, bta_dm_search_cb.peer_bdaddr); strlcpy((char*)p_msg->disc_result.result.disc_res.bd_name, bta_dm_get_remname(), BD_NAME_LEN); bta_sys_sendmsg(p_msg); } } /******************************************************************************* * * Function bta_dm_search_cmpl * * Description Sends event to application * * Returns void * ******************************************************************************/ void bta_dm_search_cmpl(tBTA_DM_MSG* p_data) { APPL_TRACE_EVENT("%s", __func__); osi_free_and_reset((void**)&bta_dm_search_cb.p_srvc_uuid); if (p_data->hdr.layer_specific == BTA_DM_API_DI_DISCOVER_EVT) bta_dm_di_disc_cmpl(p_data); else bta_dm_search_cb.p_search_cback(BTA_DM_DISC_CMPL_EVT, NULL); } /******************************************************************************* * * Function bta_dm_disc_result * * Description Service discovery result when discovering services on a * device * * Returns void * ******************************************************************************/ void bta_dm_disc_result(tBTA_DM_MSG* p_data) { APPL_TRACE_EVENT("%s", __func__); /* if any BR/EDR service discovery has been done, report the event */ if ((bta_dm_search_cb.services & ((BTA_ALL_SERVICE_MASK | BTA_USER_SERVICE_MASK) & ~BTA_BLE_SERVICE_MASK))) bta_dm_search_cb.p_search_cback(BTA_DM_DISC_RES_EVT, &p_data->disc_result.result); tBTA_DM_MSG* p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG)); /* send a message to change state */ p_msg->hdr.event = BTA_DM_SEARCH_CMPL_EVT; p_msg->hdr.layer_specific = BTA_DM_API_DISCOVER_EVT; bta_sys_sendmsg(p_msg); } /******************************************************************************* * * Function bta_dm_search_result * * Description Service discovery result while searching for devices * * Returns void * ******************************************************************************/ void bta_dm_search_result(tBTA_DM_MSG* p_data) { APPL_TRACE_DEBUG("%s searching:0x%04x, result:0x%04x", __func__, bta_dm_search_cb.services, p_data->disc_result.result.disc_res.services); /* call back if application wants name discovery or found services that * application is searching */ if ((!bta_dm_search_cb.services) || ((bta_dm_search_cb.services) && (p_data->disc_result.result.disc_res.services))) { bta_dm_search_cb.p_search_cback(BTA_DM_DISC_RES_EVT, &p_data->disc_result.result); } /* if searching did not initiate to create link */ if (!bta_dm_search_cb.wait_disc) { /* if service searching is done with EIR, don't search next device */ if (bta_dm_search_cb.p_btm_inq_info) bta_dm_discover_next_device(); } else { /* wait until link is disconnected or timeout */ bta_dm_search_cb.sdp_results = true; alarm_set_on_queue(bta_dm_search_cb.search_timer, 1000 * (L2CAP_LINK_INACTIVITY_TOUT + 1), bta_dm_search_timer_cback, NULL, btu_bta_alarm_queue); } } /******************************************************************************* * * Function bta_dm_search_timer_cback * * Description Called when ACL disconnect time is over * * * Returns void * ******************************************************************************/ static void bta_dm_search_timer_cback(UNUSED_ATTR void* data) { APPL_TRACE_EVENT("%s", __func__); bta_dm_search_cb.wait_disc = false; /* proceed with next device */ bta_dm_discover_next_device(); } /******************************************************************************* * * Function bta_dm_free_sdp_db * * Description Frees SDP data base * * Returns void * ******************************************************************************/ void bta_dm_free_sdp_db(UNUSED_ATTR tBTA_DM_MSG* p_data) { osi_free_and_reset((void**)&bta_dm_search_cb.p_sdp_db); } /******************************************************************************* * * Function bta_dm_queue_search * * Description Queues search command while search is being cancelled * * Returns void * ******************************************************************************/ void bta_dm_queue_search(tBTA_DM_MSG* p_data) { osi_free(bta_dm_search_cb.p_search_queue); bta_dm_search_cb.p_search_queue = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_API_SEARCH)); memcpy(bta_dm_search_cb.p_search_queue, p_data, sizeof(tBTA_DM_API_SEARCH)); } /******************************************************************************* * * Function bta_dm_queue_disc * * Description Queues discovery command while search is being cancelled * * Returns void * ******************************************************************************/ void bta_dm_queue_disc(tBTA_DM_MSG* p_data) { osi_free(bta_dm_search_cb.p_search_queue); bta_dm_search_cb.p_search_queue = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_API_DISCOVER)); memcpy(bta_dm_search_cb.p_search_queue, p_data, sizeof(tBTA_DM_API_DISCOVER)); } /******************************************************************************* * * Function bta_dm_search_clear_queue * * Description Clears the queue if API search cancel is called * * Returns void * ******************************************************************************/ void bta_dm_search_clear_queue(UNUSED_ATTR tBTA_DM_MSG* p_data) { osi_free_and_reset((void**)&bta_dm_search_cb.p_search_queue); } /******************************************************************************* * * Function bta_dm_search_cancel_cmpl * * Description Search cancel is complete * * Returns void * ******************************************************************************/ void bta_dm_search_cancel_cmpl(UNUSED_ATTR tBTA_DM_MSG* p_data) { if (bta_dm_search_cb.p_search_queue) { bta_sys_sendmsg(bta_dm_search_cb.p_search_queue); bta_dm_search_cb.p_search_queue = NULL; } } /******************************************************************************* * * Function bta_dm_search_cancel_transac_cmpl * * Description Current Service Discovery or remote name procedure is * completed after search cancellation * * Returns void * ******************************************************************************/ void bta_dm_search_cancel_transac_cmpl(UNUSED_ATTR tBTA_DM_MSG* p_data) { osi_free_and_reset((void**)&bta_dm_search_cb.p_sdp_db); bta_dm_search_cancel_notify(NULL); } /******************************************************************************* * * Function bta_dm_search_cancel_notify * * Description Notify application that search has been cancelled * * Returns void * ******************************************************************************/ void bta_dm_search_cancel_notify(UNUSED_ATTR tBTA_DM_MSG* p_data) { if (bta_dm_search_cb.p_search_cback) { bta_dm_search_cb.p_search_cback(BTA_DM_SEARCH_CANCEL_CMPL_EVT, NULL); } if (!bta_dm_search_cb.name_discover_done) { BTM_CancelRemoteDeviceName(); } if (bta_dm_search_cb.gatt_disc_active) { bta_dm_cancel_gatt_discovery(bta_dm_search_cb.peer_bdaddr); } } /******************************************************************************* * * Function bta_dm_find_services * * Description Starts discovery on a device * * Returns void * ******************************************************************************/ static void bta_dm_find_services(BD_ADDR bd_addr) { tSDP_UUID uuid; memset(&uuid, 0, sizeof(tSDP_UUID)); while (bta_dm_search_cb.service_index < BTA_MAX_SERVICE_ID) { if (bta_dm_search_cb.services_to_search & (tBTA_SERVICE_MASK)( BTA_SERVICE_ID_TO_SERVICE_MASK(bta_dm_search_cb.service_index))) { bta_dm_search_cb.p_sdp_db = (tSDP_DISCOVERY_DB*)osi_malloc(BTA_DM_SDP_DB_SIZE); APPL_TRACE_DEBUG("bta_dm_search_cb.services = %04x***********", bta_dm_search_cb.services); /* try to search all services by search based on L2CAP UUID */ if (bta_dm_search_cb.services == BTA_ALL_SERVICE_MASK) { LOG_INFO(LOG_TAG, "%s services_to_search=%08x", __func__, bta_dm_search_cb.services_to_search); if (bta_dm_search_cb.services_to_search & BTA_RES_SERVICE_MASK) { uuid.uu.uuid16 = bta_service_id_to_uuid_lkup_tbl[0]; bta_dm_search_cb.services_to_search &= ~BTA_RES_SERVICE_MASK; } else { uuid.uu.uuid16 = UUID_PROTOCOL_L2CAP; bta_dm_search_cb.services_to_search = 0; } } else { /* for LE only profile */ if (bta_dm_search_cb.service_index == BTA_BLE_SERVICE_ID) { if (bta_dm_search_cb.uuid_to_search > 0 && bta_dm_search_cb.p_srvc_uuid) { memcpy(&uuid, (const void*)(bta_dm_search_cb.p_srvc_uuid + bta_dm_search_cb.num_uuid - bta_dm_search_cb.uuid_to_search), sizeof(tBT_UUID)); bta_dm_search_cb.uuid_to_search--; } else { uuid.uu.uuid16 = bta_service_id_to_uuid_lkup_tbl[bta_dm_search_cb.service_index]; } /* last one? clear the BLE service bit if all discovery has been done */ if (bta_dm_search_cb.uuid_to_search == 0) bta_dm_search_cb.services_to_search &= (tBTA_SERVICE_MASK)(~(BTA_SERVICE_ID_TO_SERVICE_MASK( bta_dm_search_cb.service_index))); } else { /* remove the service from services to be searched */ bta_dm_search_cb.services_to_search &= (tBTA_SERVICE_MASK)(~( BTA_SERVICE_ID_TO_SERVICE_MASK(bta_dm_search_cb.service_index))); uuid.uu.uuid16 = bta_service_id_to_uuid_lkup_tbl[bta_dm_search_cb.service_index]; } } if (uuid.len == 0) uuid.len = LEN_UUID_16; if (bta_dm_search_cb.service_index == BTA_USER_SERVICE_ID) { memcpy(&uuid, &bta_dm_search_cb.uuid, sizeof(tSDP_UUID)); } LOG_INFO(LOG_TAG, "%s search UUID = %04x", __func__, uuid.uu.uuid16); SDP_InitDiscoveryDb(bta_dm_search_cb.p_sdp_db, BTA_DM_SDP_DB_SIZE, 1, &uuid, 0, NULL); memset(g_disc_raw_data_buf, 0, sizeof(g_disc_raw_data_buf)); bta_dm_search_cb.p_sdp_db->raw_data = g_disc_raw_data_buf; bta_dm_search_cb.p_sdp_db->raw_size = MAX_DISC_RAW_DATA_BUF; if (!SDP_ServiceSearchAttributeRequest(bd_addr, bta_dm_search_cb.p_sdp_db, &bta_dm_sdp_callback)) { /* * If discovery is not successful with this device, then * proceed with the next one. */ osi_free_and_reset((void**)&bta_dm_search_cb.p_sdp_db); bta_dm_search_cb.service_index = BTA_MAX_SERVICE_ID; } else { if ((bta_dm_search_cb.service_index == BTA_BLE_SERVICE_ID && bta_dm_search_cb.uuid_to_search == 0) || bta_dm_search_cb.service_index != BTA_BLE_SERVICE_ID) bta_dm_search_cb.service_index++; return; } } bta_dm_search_cb.service_index++; } /* no more services to be discovered */ if (bta_dm_search_cb.service_index >= BTA_MAX_SERVICE_ID) { tBTA_DM_MSG* p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG)); /* initialize the data structure - includes p_raw_data and raw_data_size */ memset(&(p_msg->disc_result.result), 0, sizeof(tBTA_DM_DISC_RES)); p_msg->hdr.event = BTA_DM_DISCOVERY_RESULT_EVT; p_msg->disc_result.result.disc_res.services = bta_dm_search_cb.services_found; bdcpy(p_msg->disc_result.result.disc_res.bd_addr, bta_dm_search_cb.peer_bdaddr); strlcpy((char*)p_msg->disc_result.result.disc_res.bd_name, bta_dm_get_remname(), BD_NAME_LEN); bta_sys_sendmsg(p_msg); } } /******************************************************************************* * * Function bta_dm_discover_next_device * * Description Starts discovery on the next device in Inquiry data base * * Returns void * ******************************************************************************/ static void bta_dm_discover_next_device(void) { APPL_TRACE_DEBUG("bta_dm_discover_next_device"); /* searching next device on inquiry result */ bta_dm_search_cb.p_btm_inq_info = BTM_InqDbNext(bta_dm_search_cb.p_btm_inq_info); if (bta_dm_search_cb.p_btm_inq_info != NULL) { bta_dm_search_cb.name_discover_done = false; bta_dm_search_cb.peer_name[0] = 0; bta_dm_discover_device( bta_dm_search_cb.p_btm_inq_info->results.remote_bd_addr); } else { tBTA_DM_MSG* p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG)); /* no devices, search complete */ bta_dm_search_cb.services = 0; p_msg->hdr.event = BTA_DM_SEARCH_CMPL_EVT; p_msg->hdr.layer_specific = BTA_DM_API_DISCOVER_EVT; bta_sys_sendmsg(p_msg); } } /******************************************************************************* * * Function bta_dm_discover_device * * Description Starts name and service discovery on the device * * Returns void * ******************************************************************************/ static void bta_dm_discover_device(BD_ADDR remote_bd_addr) { tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR; if (bta_dm_search_cb.transport == BTA_TRANSPORT_UNKNOWN) { tBT_DEVICE_TYPE dev_type; tBLE_ADDR_TYPE addr_type; BTM_ReadDevInfo(remote_bd_addr, &dev_type, &addr_type); if (dev_type == BT_DEVICE_TYPE_BLE || addr_type == BLE_ADDR_RANDOM) transport = BT_TRANSPORT_LE; } else { transport = bta_dm_search_cb.transport; } /* Reset transport state for next discovery */ bta_dm_search_cb.transport = BTA_TRANSPORT_UNKNOWN; APPL_TRACE_DEBUG("%s BDA:0x%02X%02X%02X%02X%02X%02X", __func__, remote_bd_addr[0], remote_bd_addr[1], remote_bd_addr[2], remote_bd_addr[3], remote_bd_addr[4], remote_bd_addr[5]); bdcpy(bta_dm_search_cb.peer_bdaddr, remote_bd_addr); APPL_TRACE_DEBUG( "%s name_discover_done = %d p_btm_inq_info 0x%x state = %d, transport=%d", __func__, bta_dm_search_cb.name_discover_done, bta_dm_search_cb.p_btm_inq_info, bta_dm_search_cb.state, transport); if (bta_dm_search_cb.p_btm_inq_info) { APPL_TRACE_DEBUG("%s appl_knows_rem_name %d", __func__, bta_dm_search_cb.p_btm_inq_info->appl_knows_rem_name); } if ((bta_dm_search_cb.p_btm_inq_info) && (bta_dm_search_cb.p_btm_inq_info->results.device_type == BT_DEVICE_TYPE_BLE) && (bta_dm_search_cb.state == BTA_DM_SEARCH_ACTIVE)) { /* Do not perform RNR for LE devices at inquiry complete*/ bta_dm_search_cb.name_discover_done = true; } /* if name discovery is not done and application needs remote name */ if ((!bta_dm_search_cb.name_discover_done) && ((bta_dm_search_cb.p_btm_inq_info == NULL) || (bta_dm_search_cb.p_btm_inq_info && (!bta_dm_search_cb.p_btm_inq_info->appl_knows_rem_name)))) { if (bta_dm_read_remote_device_name(bta_dm_search_cb.peer_bdaddr, transport) == true) return; /* starting name discovery failed */ bta_dm_search_cb.name_discover_done = true; } /* if application wants to discover service */ if (bta_dm_search_cb.services) { /* initialize variables */ bta_dm_search_cb.service_index = 0; bta_dm_search_cb.services_found = 0; bta_dm_search_cb.services_to_search = bta_dm_search_cb.services; bta_dm_search_cb.uuid_to_search = bta_dm_search_cb.num_uuid; if ((bta_dm_search_cb.p_btm_inq_info != NULL) && bta_dm_search_cb.services != BTA_USER_SERVICE_MASK && (bta_dm_search_cb.sdp_search == false)) { /* check if EIR provides the information of supported services */ bta_dm_eir_search_services(&bta_dm_search_cb.p_btm_inq_info->results, &bta_dm_search_cb.services_to_search, &bta_dm_search_cb.services_found); } /* if seaching with EIR is not completed */ if (bta_dm_search_cb.services_to_search) { /* check whether connection already exists to the device if connection exists, we don't have to wait for ACL link to go down to start search on next device */ if (BTM_IsAclConnectionUp(bta_dm_search_cb.peer_bdaddr, BT_TRANSPORT_BR_EDR)) bta_dm_search_cb.wait_disc = false; else bta_dm_search_cb.wait_disc = true; if (bta_dm_search_cb.p_btm_inq_info) { APPL_TRACE_DEBUG( "%s p_btm_inq_info 0x%x results.device_type 0x%x " "services_to_search 0x%x", __func__, bta_dm_search_cb.p_btm_inq_info, bta_dm_search_cb.p_btm_inq_info->results.device_type, bta_dm_search_cb.services_to_search); } if (transport == BT_TRANSPORT_LE) { if (bta_dm_search_cb.services_to_search & BTA_BLE_SERVICE_MASK) { // set the raw data buffer here memset(g_disc_raw_data_buf, 0, sizeof(g_disc_raw_data_buf)); bta_dm_search_cb.p_ble_rawdata = g_disc_raw_data_buf; bta_dm_search_cb.ble_raw_size = MAX_DISC_RAW_DATA_BUF; bta_dm_search_cb.ble_raw_used = 0; /* start GATT for service discovery */ btm_dm_start_gatt_discovery(bta_dm_search_cb.peer_bdaddr); return; } } else { bta_dm_search_cb.sdp_results = false; bta_dm_find_services(bta_dm_search_cb.peer_bdaddr); return; } } } /* name discovery and service discovery are done for this device */ tBTA_DM_MSG* p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG)); p_msg->hdr.event = BTA_DM_DISCOVERY_RESULT_EVT; /* initialize the data structure - includes p_raw_data and raw_data_size */ memset(&(p_msg->disc_result.result), 0, sizeof(tBTA_DM_DISC_RES)); p_msg->disc_result.result.disc_res.result = BTA_SUCCESS; p_msg->disc_result.result.disc_res.services = bta_dm_search_cb.services_found; bdcpy(p_msg->disc_result.result.disc_res.bd_addr, bta_dm_search_cb.peer_bdaddr); strlcpy((char*)p_msg->disc_result.result.disc_res.bd_name, (char*)bta_dm_search_cb.peer_name, BD_NAME_LEN); bta_sys_sendmsg(p_msg); } /******************************************************************************* * * Function bta_dm_sdp_callback * * Description Callback from sdp with discovery status * * Returns void * ******************************************************************************/ static void bta_dm_sdp_callback(uint16_t sdp_status) { tBTA_DM_SDP_RESULT* p_msg = (tBTA_DM_SDP_RESULT*)osi_malloc(sizeof(tBTA_DM_SDP_RESULT)); p_msg->hdr.event = BTA_DM_SDP_RESULT_EVT; p_msg->sdp_result = sdp_status; bta_sys_sendmsg(p_msg); } /******************************************************************************* * * Function bta_dm_inq_results_cb * * Description Inquiry results callback from BTM * * Returns void * ******************************************************************************/ static void bta_dm_inq_results_cb(tBTM_INQ_RESULTS* p_inq, uint8_t* p_eir, uint16_t eir_len) { tBTA_DM_SEARCH result; tBTM_INQ_INFO* p_inq_info; uint16_t service_class; bdcpy(result.inq_res.bd_addr, p_inq->remote_bd_addr); memcpy(result.inq_res.dev_class, p_inq->dev_class, DEV_CLASS_LEN); BTM_COD_SERVICE_CLASS(service_class, p_inq->dev_class); result.inq_res.is_limited = (service_class & BTM_COD_SERVICE_LMTD_DISCOVER) ? true : false; result.inq_res.rssi = p_inq->rssi; result.inq_res.ble_addr_type = p_inq->ble_addr_type; result.inq_res.inq_result_type = p_inq->inq_result_type; result.inq_res.device_type = p_inq->device_type; result.inq_res.flag = p_inq->flag; /* application will parse EIR to find out remote device name */ result.inq_res.p_eir = p_eir; result.inq_res.eir_len = eir_len; p_inq_info = BTM_InqDbRead(p_inq->remote_bd_addr); if (p_inq_info != NULL) { /* initialize remt_name_not_required to false so that we get the name by * default */ result.inq_res.remt_name_not_required = false; } if (bta_dm_search_cb.p_search_cback) bta_dm_search_cb.p_search_cback(BTA_DM_INQ_RES_EVT, &result); if (p_inq_info) { /* application indicates if it knows the remote name, inside the callback copy that to the inquiry data base*/ if (result.inq_res.remt_name_not_required) p_inq_info->appl_knows_rem_name = true; } } /******************************************************************************* * * Function bta_dm_inq_cmpl_cb * * Description Inquiry complete callback from BTM * * Returns void * ******************************************************************************/ static void bta_dm_inq_cmpl_cb(void* p_result) { tBTA_DM_MSG* p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG)); APPL_TRACE_DEBUG("%s", __func__); if (bta_dm_search_cb.cancel_pending == false) { p_msg->inq_cmpl.hdr.event = BTA_DM_INQUIRY_CMPL_EVT; p_msg->inq_cmpl.num = ((tBTM_INQUIRY_CMPL*)p_result)->num_resp; } else { bta_dm_search_cb.cancel_pending = false; bta_dm_search_cancel_notify(NULL); p_msg->hdr.event = BTA_DM_SEARCH_CMPL_EVT; p_msg->hdr.layer_specific = BTA_DM_API_DISCOVER_EVT; } bta_sys_sendmsg(p_msg); } /******************************************************************************* * * Function bta_dm_service_search_remname_cback * * Description Remote name call back from BTM during service discovery * * Returns void * ******************************************************************************/ static void bta_dm_service_search_remname_cback(BD_ADDR bd_addr, UNUSED_ATTR DEV_CLASS dc, BD_NAME bd_name) { tBTM_REMOTE_DEV_NAME rem_name; tBTM_STATUS btm_status; APPL_TRACE_DEBUG("bta_dm_service_search_remname_cback name=<%s>", bd_name); /* if this is what we are looking for */ if (!bdcmp(bta_dm_search_cb.peer_bdaddr, bd_addr)) { rem_name.length = strlen((char*)bd_name); if (rem_name.length > (BD_NAME_LEN - 1)) { rem_name.length = (BD_NAME_LEN - 1); rem_name.remote_bd_name[(BD_NAME_LEN - 1)] = 0; } strlcpy((char*)rem_name.remote_bd_name, (char*)bd_name, BD_NAME_LEN); rem_name.status = BTM_SUCCESS; bta_dm_remname_cback(&rem_name); } else { /* get name of device */ btm_status = BTM_ReadRemoteDeviceName(bta_dm_search_cb.peer_bdaddr, (tBTM_CMPL_CB*)bta_dm_remname_cback, BT_TRANSPORT_BR_EDR); if (btm_status == BTM_BUSY) { /* wait for next chance(notification of remote name discovery done) */ APPL_TRACE_DEBUG( "bta_dm_service_search_remname_cback: BTM_ReadRemoteDeviceName is " "busy"); } else if (btm_status != BTM_CMD_STARTED) { /* if failed to start getting remote name then continue */ APPL_TRACE_WARNING( "bta_dm_service_search_remname_cback: BTM_ReadRemoteDeviceName " "returns 0x%02X", btm_status); rem_name.length = 0; rem_name.remote_bd_name[0] = 0; rem_name.status = btm_status; bta_dm_remname_cback(&rem_name); } } } /******************************************************************************* * * Function bta_dm_remname_cback * * Description Remote name complete call back from BTM * * Returns void * ******************************************************************************/ static void bta_dm_remname_cback(tBTM_REMOTE_DEV_NAME* p_remote_name) { APPL_TRACE_DEBUG("bta_dm_remname_cback len = %d name=<%s>", p_remote_name->length, p_remote_name->remote_bd_name); /* remote name discovery is done but it could be failed */ bta_dm_search_cb.name_discover_done = true; strlcpy((char*)bta_dm_search_cb.peer_name, (char*)p_remote_name->remote_bd_name, BD_NAME_LEN); BTM_SecDeleteRmtNameNotifyCallback(&bta_dm_service_search_remname_cback); if (bta_dm_search_cb.transport == BT_TRANSPORT_LE) { GAP_BleReadPeerPrefConnParams(bta_dm_search_cb.peer_bdaddr); } tBTA_DM_REM_NAME* p_msg = (tBTA_DM_REM_NAME*)osi_malloc(sizeof(tBTA_DM_REM_NAME)); bdcpy(p_msg->result.disc_res.bd_addr, bta_dm_search_cb.peer_bdaddr); strlcpy((char*)p_msg->result.disc_res.bd_name, (char*)p_remote_name->remote_bd_name, BD_NAME_LEN); p_msg->hdr.event = BTA_DM_REMT_NAME_EVT; bta_sys_sendmsg(p_msg); } /******************************************************************************* * * Function bta_dm_authorize_cback * * Description cback requesting authorization * * Returns void * ******************************************************************************/ static uint8_t bta_dm_authorize_cback(BD_ADDR bd_addr, DEV_CLASS dev_class, BD_NAME bd_name, UNUSED_ATTR uint8_t* service_name, uint8_t service_id, UNUSED_ATTR bool is_originator) { tBTA_DM_SEC sec_event; uint8_t index = 1; bdcpy(sec_event.authorize.bd_addr, bd_addr); memcpy(sec_event.authorize.dev_class, dev_class, DEV_CLASS_LEN); strlcpy((char*)sec_event.authorize.bd_name, (char*)bd_name, BD_NAME_LEN); #if (BTA_JV_INCLUDED == TRUE) sec_event.authorize.service = service_id; #endif while (index < BTA_MAX_SERVICE_ID) { /* get the BTA service id corresponding to BTM id */ if (bta_service_id_to_btm_srv_id_lkup_tbl[index] == service_id) { sec_event.authorize.service = index; break; } index++; } /* if supported service callback otherwise not authorized */ if (bta_dm_cb.p_sec_cback && (index < BTA_MAX_SERVICE_ID #if (BTA_JV_INCLUDED == TRUE) /* pass through JV service ID */ || (service_id >= BTA_FIRST_JV_SERVICE_ID && service_id <= BTA_LAST_JV_SERVICE_ID) #endif )) { bta_dm_cb.p_sec_cback(BTA_DM_AUTHORIZE_EVT, &sec_event); return BTM_CMD_STARTED; } else { return BTM_NOT_AUTHORIZED; } } /******************************************************************************* * * Function bta_dm_pinname_cback * * Description Callback requesting pin_key * * Returns void * ******************************************************************************/ static void bta_dm_pinname_cback(void* p_data) { tBTM_REMOTE_DEV_NAME* p_result = (tBTM_REMOTE_DEV_NAME*)p_data; tBTA_DM_SEC sec_event; uint32_t bytes_to_copy; tBTA_DM_SEC_EVT event = bta_dm_cb.pin_evt; if (BTA_DM_SP_CFM_REQ_EVT == event) { /* Retrieved saved device class and bd_addr */ bdcpy(sec_event.cfm_req.bd_addr, bta_dm_cb.pin_bd_addr); BTA_COPY_DEVICE_CLASS(sec_event.cfm_req.dev_class, bta_dm_cb.pin_dev_class); if (p_result && p_result->status == BTM_SUCCESS) { bytes_to_copy = (p_result->length < (BD_NAME_LEN - 1)) ? p_result->length : (BD_NAME_LEN - 1); memcpy(sec_event.cfm_req.bd_name, p_result->remote_bd_name, bytes_to_copy); sec_event.pin_req.bd_name[BD_NAME_LEN - 1] = 0; } else /* No name found */ sec_event.cfm_req.bd_name[0] = 0; sec_event.key_notif.passkey = bta_dm_cb.num_val; /* get PIN code numeric number */ /* 1 additional event data fields for this event */ sec_event.cfm_req.just_works = bta_dm_cb.just_works; } else { /* Retrieved saved device class and bd_addr */ bdcpy(sec_event.pin_req.bd_addr, bta_dm_cb.pin_bd_addr); BTA_COPY_DEVICE_CLASS(sec_event.pin_req.dev_class, bta_dm_cb.pin_dev_class); if (p_result && p_result->status == BTM_SUCCESS) { bytes_to_copy = (p_result->length < (BD_NAME_LEN - 1)) ? p_result->length : (BD_NAME_LEN - 1); memcpy(sec_event.pin_req.bd_name, p_result->remote_bd_name, bytes_to_copy); sec_event.pin_req.bd_name[BD_NAME_LEN - 1] = 0; } else /* No name found */ sec_event.pin_req.bd_name[0] = 0; event = bta_dm_cb.pin_evt; sec_event.key_notif.passkey = bta_dm_cb.num_val; /* get PIN code numeric number */ } if (bta_dm_cb.p_sec_cback) bta_dm_cb.p_sec_cback(event, &sec_event); } /******************************************************************************* * * Function bta_dm_pin_cback * * Description Callback requesting pin_key * * Returns void * ******************************************************************************/ static uint8_t bta_dm_pin_cback(BD_ADDR bd_addr, DEV_CLASS dev_class, BD_NAME bd_name, bool min_16_digit) { tBTA_DM_SEC sec_event; if (!bta_dm_cb.p_sec_cback) return BTM_NOT_AUTHORIZED; /* If the device name is not known, save bdaddr and devclass and initiate a * name request */ if (bd_name[0] == 0) { bta_dm_cb.pin_evt = BTA_DM_PIN_REQ_EVT; bdcpy(bta_dm_cb.pin_bd_addr, bd_addr); BTA_COPY_DEVICE_CLASS(bta_dm_cb.pin_dev_class, dev_class); if ((BTM_ReadRemoteDeviceName(bd_addr, bta_dm_pinname_cback, BT_TRANSPORT_BR_EDR)) == BTM_CMD_STARTED) return BTM_CMD_STARTED; APPL_TRACE_WARNING( " bta_dm_pin_cback() -> Failed to start Remote Name Request "); } bdcpy(sec_event.pin_req.bd_addr, bd_addr); BTA_COPY_DEVICE_CLASS(sec_event.pin_req.dev_class, dev_class); strlcpy((char*)sec_event.pin_req.bd_name, (char*)bd_name, BD_NAME_LEN); sec_event.pin_req.min_16_digit = min_16_digit; bta_dm_cb.p_sec_cback(BTA_DM_PIN_REQ_EVT, &sec_event); return BTM_CMD_STARTED; } /******************************************************************************* * * Function bta_dm_new_link_key_cback * * Description Callback from BTM to notify new link key * * Returns void * ******************************************************************************/ static uint8_t bta_dm_new_link_key_cback(BD_ADDR bd_addr, UNUSED_ATTR DEV_CLASS dev_class, BD_NAME bd_name, LINK_KEY key, uint8_t key_type) { tBTA_DM_SEC sec_event; tBTA_DM_AUTH_CMPL* p_auth_cmpl; uint8_t event; memset(&sec_event, 0, sizeof(tBTA_DM_SEC)); /* Not AMP Key type */ if (key_type != HCI_LKEY_TYPE_AMP_WIFI && key_type != HCI_LKEY_TYPE_AMP_UWB) { event = BTA_DM_AUTH_CMPL_EVT; p_auth_cmpl = &sec_event.auth_cmpl; bdcpy(p_auth_cmpl->bd_addr, bd_addr); memcpy(p_auth_cmpl->bd_name, bd_name, (BD_NAME_LEN - 1)); p_auth_cmpl->bd_name[BD_NAME_LEN - 1] = 0; p_auth_cmpl->key_present = true; p_auth_cmpl->key_type = key_type; p_auth_cmpl->success = true; memcpy(p_auth_cmpl->key, key, LINK_KEY_LEN); sec_event.auth_cmpl.fail_reason = HCI_SUCCESS; // Report the BR link key based on the BR/EDR address and type BTM_ReadDevInfo(bd_addr, &sec_event.auth_cmpl.dev_type, &sec_event.auth_cmpl.addr_type); if (bta_dm_cb.p_sec_cback) bta_dm_cb.p_sec_cback(event, &sec_event); // Setting remove_dev_pending flag to false, where it will avoid deleting // the // security device record when the ACL connection link goes down in case of // reconnection. if (bta_dm_cb.device_list.count) bta_dm_reset_sec_dev_pending(p_auth_cmpl->bd_addr); } else { APPL_TRACE_WARNING("%s() Received AMP Key", __func__); } return BTM_CMD_STARTED; } /******************************************************************************* * * Function bta_dm_authentication_complete_cback * * Description Authentication complete callback from BTM * * Returns void * ******************************************************************************/ static uint8_t bta_dm_authentication_complete_cback( BD_ADDR bd_addr, UNUSED_ATTR DEV_CLASS dev_class, BD_NAME bd_name, int result) { tBTA_DM_SEC sec_event; if (result != BTM_SUCCESS) { memset(&sec_event, 0, sizeof(tBTA_DM_SEC)); bdcpy(sec_event.auth_cmpl.bd_addr, bd_addr); memcpy(sec_event.auth_cmpl.bd_name, bd_name, (BD_NAME_LEN - 1)); sec_event.auth_cmpl.bd_name[BD_NAME_LEN - 1] = 0; // Report the BR link key based on the BR/EDR address and type BTM_ReadDevInfo(bd_addr, &sec_event.auth_cmpl.dev_type, &sec_event.auth_cmpl.addr_type); sec_event.auth_cmpl.fail_reason = (uint8_t)result; if (bta_dm_cb.p_sec_cback) bta_dm_cb.p_sec_cback(BTA_DM_AUTH_CMPL_EVT, &sec_event); if (result == HCI_ERR_AUTH_FAILURE || result == HCI_ERR_KEY_MISSING || result == HCI_ERR_HOST_REJECT_SECURITY || result == HCI_ERR_ENCRY_MODE_NOT_ACCEPTABLE) { bdstr_t bd_addr_str; APPL_TRACE_WARNING("%s deleting %s - result: 0x%02x", __func__, bdaddr_to_string((bt_bdaddr_t*)bd_addr, bd_addr_str, sizeof(bd_addr_str)), result); bta_dm_remove_sec_dev_entry(bd_addr); } } return BTM_SUCCESS; } #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE) /******************************************************************************* * * Function bta_dm_sp_cback * * Description simple pairing callback from BTM * * Returns void * ******************************************************************************/ static uint8_t bta_dm_sp_cback(tBTM_SP_EVT event, tBTM_SP_EVT_DATA* p_data) { tBTM_STATUS status = BTM_CMD_STARTED; tBTA_DM_SEC sec_event; tBTA_DM_SEC_EVT pin_evt = BTA_DM_SP_KEY_NOTIF_EVT; APPL_TRACE_EVENT("bta_dm_sp_cback: %d", event); if (!bta_dm_cb.p_sec_cback) return BTM_NOT_AUTHORIZED; /* TODO_SP */ switch (event) { case BTM_SP_IO_REQ_EVT: /* translate auth_req */ bta_dm_co_io_req(p_data->io_req.bd_addr, &p_data->io_req.io_cap, &p_data->io_req.oob_data, &p_data->io_req.auth_req, p_data->io_req.is_orig); APPL_TRACE_EVENT("io mitm: %d oob_data:%d", p_data->io_req.auth_req, p_data->io_req.oob_data); break; case BTM_SP_IO_RSP_EVT: bta_dm_co_io_rsp(p_data->io_rsp.bd_addr, p_data->io_rsp.io_cap, p_data->io_rsp.oob_data, p_data->io_rsp.auth_req); break; case BTM_SP_CFM_REQ_EVT: pin_evt = BTA_DM_SP_CFM_REQ_EVT; bta_dm_cb.just_works = sec_event.cfm_req.just_works = p_data->cfm_req.just_works; sec_event.cfm_req.loc_auth_req = p_data->cfm_req.loc_auth_req; sec_event.cfm_req.rmt_auth_req = p_data->cfm_req.rmt_auth_req; sec_event.cfm_req.loc_io_caps = p_data->cfm_req.loc_io_caps; sec_event.cfm_req.rmt_io_caps = p_data->cfm_req.rmt_io_caps; /* continue to next case */ /* Passkey entry mode, mobile device with output capability is very unlikely to receive key request, so skip this event */ /*case BTM_SP_KEY_REQ_EVT: */ case BTM_SP_KEY_NOTIF_EVT: bta_dm_cb.num_val = sec_event.key_notif.passkey = p_data->key_notif.passkey; if (BTM_SP_CFM_REQ_EVT == event) { /* Due to the switch case falling through below to BTM_SP_KEY_NOTIF_EVT, call remote name request using values from cfm_req */ if (p_data->cfm_req.bd_name[0] == 0) { bta_dm_cb.pin_evt = pin_evt; bdcpy(bta_dm_cb.pin_bd_addr, p_data->cfm_req.bd_addr); BTA_COPY_DEVICE_CLASS(bta_dm_cb.pin_dev_class, p_data->cfm_req.dev_class); if ((BTM_ReadRemoteDeviceName( p_data->cfm_req.bd_addr, bta_dm_pinname_cback, BT_TRANSPORT_BR_EDR)) == BTM_CMD_STARTED) return BTM_CMD_STARTED; APPL_TRACE_WARNING( " bta_dm_sp_cback() -> Failed to start Remote Name Request "); } else { /* Due to the switch case falling through below to BTM_SP_KEY_NOTIF_EVT, copy these values into key_notif from cfm_req */ bdcpy(sec_event.key_notif.bd_addr, p_data->cfm_req.bd_addr); BTA_COPY_DEVICE_CLASS(sec_event.key_notif.dev_class, p_data->cfm_req.dev_class); strlcpy((char*)sec_event.key_notif.bd_name, (char*)p_data->cfm_req.bd_name, BD_NAME_LEN); } } if (BTM_SP_KEY_NOTIF_EVT == event) { /* If the device name is not known, save bdaddr and devclass and initiate a name request with values from key_notif */ if (p_data->key_notif.bd_name[0] == 0) { bta_dm_cb.pin_evt = pin_evt; bdcpy(bta_dm_cb.pin_bd_addr, p_data->key_notif.bd_addr); BTA_COPY_DEVICE_CLASS(bta_dm_cb.pin_dev_class, p_data->key_notif.dev_class); if ((BTM_ReadRemoteDeviceName( p_data->key_notif.bd_addr, bta_dm_pinname_cback, BT_TRANSPORT_BR_EDR)) == BTM_CMD_STARTED) return BTM_CMD_STARTED; APPL_TRACE_WARNING( " bta_dm_sp_cback() -> Failed to start Remote Name Request "); } else { bdcpy(sec_event.key_notif.bd_addr, p_data->key_notif.bd_addr); BTA_COPY_DEVICE_CLASS(sec_event.key_notif.dev_class, p_data->key_notif.dev_class); strlcpy((char*)sec_event.key_notif.bd_name, (char*)p_data->key_notif.bd_name, BD_NAME_LEN); sec_event.key_notif.bd_name[BD_NAME_LEN - 1] = 0; } } bta_dm_cb.p_sec_cback(pin_evt, &sec_event); break; case BTM_SP_LOC_OOB_EVT: bta_dm_co_loc_oob((bool)(p_data->loc_oob.status == BTM_SUCCESS), p_data->loc_oob.c, p_data->loc_oob.r); break; case BTM_SP_RMT_OOB_EVT: /* If the device name is not known, save bdaddr and devclass and initiate * a name request */ if (p_data->rmt_oob.bd_name[0] == 0) { bta_dm_cb.pin_evt = BTA_DM_SP_RMT_OOB_EVT; bdcpy(bta_dm_cb.pin_bd_addr, p_data->rmt_oob.bd_addr); BTA_COPY_DEVICE_CLASS(bta_dm_cb.pin_dev_class, p_data->rmt_oob.dev_class); if ((BTM_ReadRemoteDeviceName(p_data->rmt_oob.bd_addr, bta_dm_pinname_cback, BT_TRANSPORT_BR_EDR)) == BTM_CMD_STARTED) return BTM_CMD_STARTED; APPL_TRACE_WARNING( " bta_dm_sp_cback() -> Failed to start Remote Name Request "); } bdcpy(sec_event.rmt_oob.bd_addr, p_data->rmt_oob.bd_addr); BTA_COPY_DEVICE_CLASS(sec_event.rmt_oob.dev_class, p_data->rmt_oob.dev_class); strlcpy((char*)sec_event.rmt_oob.bd_name, (char*)p_data->rmt_oob.bd_name, BD_NAME_LEN); bta_dm_cb.p_sec_cback(BTA_DM_SP_RMT_OOB_EVT, &sec_event); bta_dm_co_rmt_oob(p_data->rmt_oob.bd_addr); break; case BTM_SP_COMPLT_EVT: /* do not report this event - handled by link_key_callback or * auth_complete_callback */ break; case BTM_SP_KEYPRESS_EVT: memcpy(&sec_event.key_press, &p_data->key_press, sizeof(tBTM_SP_KEYPRESS)); bta_dm_cb.p_sec_cback(BTA_DM_SP_KEYPRESS_EVT, &sec_event); break; case BTM_SP_UPGRADE_EVT: bta_dm_co_lk_upgrade(p_data->upgrade.bd_addr, &p_data->upgrade.upgrade); break; default: status = BTM_NOT_AUTHORIZED; break; } APPL_TRACE_EVENT("dm status: %d", status); return status; } #endif /******************************************************************************* * * Function bta_dm_local_name_cback * * Description Callback from btm after local name is read * * * Returns void * ******************************************************************************/ static void bta_dm_local_name_cback(UNUSED_ATTR uint8_t* p_name) { tBTA_DM_SEC sec_event; sec_event.enable.status = BTA_SUCCESS; if (bta_dm_cb.p_sec_cback) bta_dm_cb.p_sec_cback(BTA_DM_ENABLE_EVT, &sec_event); } /******************************************************************************* * * Function bta_dm_bl_change_cback * * Description Callback from btm when acl connection goes up or down * * * Returns void * ******************************************************************************/ static void bta_dm_bl_change_cback(tBTM_BL_EVENT_DATA* p_data) { tBTA_DM_ACL_CHANGE* p_msg = (tBTA_DM_ACL_CHANGE*)osi_malloc(sizeof(tBTA_DM_ACL_CHANGE)); p_msg->event = p_data->event; p_msg->is_new = false; switch (p_msg->event) { case BTM_BL_CONN_EVT: p_msg->is_new = true; bdcpy(p_msg->bd_addr, p_data->conn.p_bda); p_msg->transport = p_data->conn.transport; p_msg->handle = p_data->conn.handle; break; case BTM_BL_DISCN_EVT: bdcpy(p_msg->bd_addr, p_data->discn.p_bda); p_msg->transport = p_data->discn.transport; p_msg->handle = p_data->discn.handle; break; case BTM_BL_UPDATE_EVT: p_msg->busy_level = p_data->update.busy_level; p_msg->busy_level_flags = p_data->update.busy_level_flags; break; case BTM_BL_ROLE_CHG_EVT: p_msg->new_role = p_data->role_chg.new_role; p_msg->hci_status = p_data->role_chg.hci_status; bdcpy(p_msg->bd_addr, p_data->role_chg.p_bda); break; case BTM_BL_COLLISION_EVT: bdcpy(p_msg->bd_addr, p_data->conn.p_bda); break; } p_msg->hdr.event = BTA_DM_ACL_CHANGE_EVT; bta_sys_sendmsg(p_msg); } /******************************************************************************* * * Function bta_dm_rs_cback * * Description Receives the role switch complete event * * Returns * ******************************************************************************/ static void bta_dm_rs_cback(UNUSED_ATTR tBTM_ROLE_SWITCH_CMPL* p1) { APPL_TRACE_WARNING("bta_dm_rs_cback:%d", bta_dm_cb.rs_event); if (bta_dm_cb.rs_event == BTA_DM_API_SEARCH_EVT) { bta_dm_cb.search_msg.rs_res = BTA_DM_RS_OK; /* do not care about the result for now */ bta_dm_cb.rs_event = 0; bta_dm_search_start((tBTA_DM_MSG*)&bta_dm_cb.search_msg); } } /******************************************************************************* * * Function bta_dm_check_av * * Description This function checks if AV is active * if yes, make sure the AV link is master * * Returns bool - true, if switch is in progress * ******************************************************************************/ static bool bta_dm_check_av(uint16_t event) { bool avoid_roleswitch = false; bool switching = false; uint8_t i; tBTA_DM_PEER_DEVICE* p_dev; #if (BTA_DM_AVOID_A2DP_ROLESWITCH_ON_INQUIRY == TRUE) /* avoid role switch upon inquiry if a2dp is actively streaming as it introduces an audioglitch due to FW scheduling delays (unavoidable) */ if (event == BTA_DM_API_SEARCH_EVT) { avoid_roleswitch = true; } #endif APPL_TRACE_WARNING("bta_dm_check_av:%d", bta_dm_cb.cur_av_count); if (bta_dm_cb.cur_av_count) { for (i = 0; i < bta_dm_cb.device_list.count; i++) { p_dev = &bta_dm_cb.device_list.peer_device[i]; APPL_TRACE_WARNING("[%d]: state:%d, info:x%x, avoid_rs %d", i, p_dev->conn_state, p_dev->info, avoid_roleswitch); if ((p_dev->conn_state == BTA_DM_CONNECTED) && (p_dev->info & BTA_DM_DI_AV_ACTIVE) && (avoid_roleswitch == false)) { /* make master and take away the role switch policy */ if (BTM_CMD_STARTED == BTM_SwitchRole(p_dev->peer_bdaddr, HCI_ROLE_MASTER, (tBTM_CMPL_CB*)bta_dm_rs_cback)) { /* the role switch command is actually sent */ bta_dm_cb.rs_event = event; switching = true; } /* else either already master or can not switch for some reasons */ bta_dm_policy_cback(BTA_SYS_PLCY_CLR, 0, HCI_ENABLE_MASTER_SLAVE_SWITCH, p_dev->peer_bdaddr); break; } } } return switching; } /******************************************************************************* * * Function bta_dm_acl_change * * Description Process BTA_DM_ACL_CHANGE_EVT * * * Returns void * ******************************************************************************/ void bta_dm_acl_change(tBTA_DM_MSG* p_data) { uint8_t i; uint8_t* p; tBTA_DM_SEC conn; bool is_new = p_data->acl_change.is_new; BD_ADDR_PTR p_bda = p_data->acl_change.bd_addr; bool need_policy_change = false; bool issue_unpair_cb = false; tBTA_DM_PEER_DEVICE* p_dev; memset(&conn, 0, sizeof(tBTA_DM_SEC)); switch (p_data->acl_change.event) { case BTM_BL_UPDATE_EVT: /* busy level update */ if (bta_dm_cb.p_sec_cback) { conn.busy_level.level = p_data->acl_change.busy_level; conn.busy_level.level_flags = p_data->acl_change.busy_level_flags; bta_dm_cb.p_sec_cback(BTA_DM_BUSY_LEVEL_EVT, &conn); } return; case BTM_BL_ROLE_CHG_EVT: /* role change event */ p_dev = bta_dm_find_peer_device(p_bda); if (p_dev) { APPL_TRACE_DEBUG( "bta_dm_acl_change role chg info:x%x new_role:%d dev count:%d", p_dev->info, p_data->acl_change.new_role, bta_dm_cb.device_list.count); if (p_dev->info & BTA_DM_DI_AV_ACTIVE) { /* there's AV activity on this link */ if (p_data->acl_change.new_role == HCI_ROLE_SLAVE && bta_dm_cb.device_list.count > 1 && p_data->acl_change.hci_status == HCI_SUCCESS) { /* more than one connections and the AV connection is role switched * to slave * switch it back to master and remove the switch policy */ BTM_SwitchRole(p_bda, BTM_ROLE_MASTER, NULL); need_policy_change = true; } else if (p_bta_dm_cfg->avoid_scatter && (p_data->acl_change.new_role == HCI_ROLE_MASTER)) { /* if the link updated to be master include AV activities, remove * the switch policy */ need_policy_change = true; } if (need_policy_change) { bta_dm_policy_cback(BTA_SYS_PLCY_CLR, 0, HCI_ENABLE_MASTER_SLAVE_SWITCH, p_dev->peer_bdaddr); } } else { /* there's AV no activity on this link and role switch happened * check if AV is active * if so, make sure the AV link is master */ bta_dm_check_av(0); } bta_sys_notify_role_chg(p_data->acl_change.bd_addr, p_data->acl_change.new_role, p_data->acl_change.hci_status); bdcpy(conn.role_chg.bd_addr, p_bda); conn.role_chg.new_role = (uint8_t)p_data->acl_change.new_role; if (bta_dm_cb.p_sec_cback) bta_dm_cb.p_sec_cback(BTA_DM_ROLE_CHG_EVT, (tBTA_DM_SEC*)&conn); } return; } /* Collision report from Stack: Notify profiles */ if (p_data->acl_change.event == BTM_BL_COLLISION_EVT) { bta_sys_notify_collision(p_bda); return; } if (is_new) { for (i = 0; i < bta_dm_cb.device_list.count; i++) { if (!bdcmp(bta_dm_cb.device_list.peer_device[i].peer_bdaddr, p_bda) && bta_dm_cb.device_list.peer_device[i].conn_handle == p_data->acl_change.handle) break; } if (i == bta_dm_cb.device_list.count) { if (bta_dm_cb.device_list.count < BTA_DM_NUM_PEER_DEVICE) { bdcpy(bta_dm_cb.device_list.peer_device[bta_dm_cb.device_list.count] .peer_bdaddr, p_bda); bta_dm_cb.device_list.peer_device[bta_dm_cb.device_list.count] .link_policy = bta_dm_cb.cur_policy; bta_dm_cb.device_list.count++; bta_dm_cb.device_list.peer_device[i].conn_handle = p_data->acl_change.handle; if (p_data->acl_change.transport == BT_TRANSPORT_LE) bta_dm_cb.device_list.le_count++; } else { APPL_TRACE_ERROR("%s max active connection reached, no resources", __func__); return; } } bta_dm_cb.device_list.peer_device[i].conn_state = BTA_DM_CONNECTED; bta_dm_cb.device_list.peer_device[i].pref_role = BTA_ANY_ROLE; bdcpy(conn.link_up.bd_addr, p_bda); bta_dm_cb.device_list.peer_device[i].info = BTA_DM_DI_NONE; conn.link_up.link_type = p_data->acl_change.transport; bta_dm_cb.device_list.peer_device[i].transport = p_data->acl_change.transport; if (((NULL != (p = BTM_ReadLocalFeatures())) && HCI_SNIFF_SUB_RATE_SUPPORTED(p)) && ((NULL != (p = BTM_ReadRemoteFeatures(p_bda))) && HCI_SNIFF_SUB_RATE_SUPPORTED(p))) { /* both local and remote devices support SSR */ bta_dm_cb.device_list.peer_device[i].info = BTA_DM_DI_USE_SSR; } APPL_TRACE_WARNING("%s info: 0x%x", __func__, bta_dm_cb.device_list.peer_device[i].info); if (bta_dm_cb.p_sec_cback) bta_dm_cb.p_sec_cback(BTA_DM_LINK_UP_EVT, (tBTA_DM_SEC*)&conn); } else { for (i = 0; i < bta_dm_cb.device_list.count; i++) { if (bdcmp(bta_dm_cb.device_list.peer_device[i].peer_bdaddr, p_bda) || bta_dm_cb.device_list.peer_device[i].transport != p_data->acl_change.transport) continue; if (bta_dm_cb.device_list.peer_device[i].conn_state == BTA_DM_UNPAIRING) { if (BTM_SecDeleteDevice( bta_dm_cb.device_list.peer_device[i].peer_bdaddr)) issue_unpair_cb = true; APPL_TRACE_DEBUG("%s: Unpairing: issue unpair CB = %d ", __func__, issue_unpair_cb); } conn.link_down.is_removed = bta_dm_cb.device_list.peer_device[i].remove_dev_pending; // Iterate to the one before the last when shrinking the list, // otherwise we memcpy garbage data into the record. // Then clear out the last item in the list since we are shrinking. for (; i < bta_dm_cb.device_list.count - 1; i++) { memcpy(&bta_dm_cb.device_list.peer_device[i], &bta_dm_cb.device_list.peer_device[i + 1], sizeof(bta_dm_cb.device_list.peer_device[i])); } if (bta_dm_cb.device_list.count > 0) { int clear_index = bta_dm_cb.device_list.count - 1; memset(&bta_dm_cb.device_list.peer_device[clear_index], 0, sizeof(bta_dm_cb.device_list.peer_device[clear_index])); } break; } if (bta_dm_cb.device_list.count) bta_dm_cb.device_list.count--; if ((p_data->acl_change.transport == BT_TRANSPORT_LE) && (bta_dm_cb.device_list.le_count)) bta_dm_cb.device_list.le_count--; conn.link_down.link_type = p_data->acl_change.transport; if (bta_dm_search_cb.wait_disc && !bdcmp(bta_dm_search_cb.peer_bdaddr, p_bda)) { bta_dm_search_cb.wait_disc = false; if (bta_dm_search_cb.sdp_results) { APPL_TRACE_EVENT(" timer stopped "); alarm_cancel(bta_dm_search_cb.search_timer); bta_dm_discover_next_device(); } } if (bta_dm_cb.disabling) { if (!BTM_GetNumAclLinks()) { /* * Start a timer to make sure that the profiles * get the disconnect event. */ alarm_set_on_queue( bta_dm_cb.disable_timer, BTA_DM_DISABLE_CONN_DOWN_TIMER_MS, bta_dm_disable_conn_down_timer_cback, NULL, btu_bta_alarm_queue); } } if (conn.link_down.is_removed) { BTM_SecDeleteDevice(p_bda); /* need to remove all pending background connection */ BTA_GATTC_CancelOpen(0, p_bda, false); /* remove all cached GATT information */ bt_bdaddr_t tmp_addr; memcpy(tmp_addr.address, p_bda, BD_ADDR_LEN); BTA_GATTC_Refresh(tmp_addr); } bdcpy(conn.link_down.bd_addr, p_bda); conn.link_down.status = (uint8_t)btm_get_acl_disc_reason_code(); if (bta_dm_cb.p_sec_cback) { bta_dm_cb.p_sec_cback(BTA_DM_LINK_DOWN_EVT, &conn); if (issue_unpair_cb) bta_dm_cb.p_sec_cback(BTA_DM_DEV_UNPAIRED_EVT, &conn); } } bta_dm_adjust_roles(true); } /******************************************************************************* * * Function bta_dm_disable_conn_down_timer_cback * * Description Sends disable event to application * * * Returns void * ******************************************************************************/ static void bta_dm_disable_conn_down_timer_cback(UNUSED_ATTR void* data) { tBTA_SYS_HW_MSG* sys_enable_event = (tBTA_SYS_HW_MSG*)osi_malloc(sizeof(tBTA_SYS_HW_MSG)); /* disable the power managment module */ bta_dm_disable_pm(); /* register our callback to SYS HW manager */ bta_sys_hw_register(BTA_SYS_HW_BLUETOOTH, bta_dm_sys_hw_cback); /* send a message to BTA SYS */ sys_enable_event->hdr.event = BTA_SYS_API_DISABLE_EVT; sys_enable_event->hw_module = BTA_SYS_HW_BLUETOOTH; bta_sys_sendmsg(sys_enable_event); bta_dm_cb.disabling = false; } /******************************************************************************* * * Function bta_dm_rm_cback * * Description Role management callback from sys * * * Returns void * ******************************************************************************/ static void bta_dm_rm_cback(tBTA_SYS_CONN_STATUS status, uint8_t id, uint8_t app_id, BD_ADDR peer_addr) { uint8_t j; tBTA_PREF_ROLES role; tBTA_DM_PEER_DEVICE* p_dev; p_dev = bta_dm_find_peer_device(peer_addr); if (status == BTA_SYS_CONN_OPEN) { if (p_dev) { /* Do not set to connected if we are in the middle of unpairing. When AV * stream is * started it fakes out a SYS_CONN_OPEN to potentially trigger a role * switch command. * But this should not be done if we are in the middle of unpairing. */ if (p_dev->conn_state != BTA_DM_UNPAIRING) p_dev->conn_state = BTA_DM_CONNECTED; for (j = 1; j <= p_bta_dm_rm_cfg[0].app_id; j++) { if (((p_bta_dm_rm_cfg[j].app_id == app_id) || (p_bta_dm_rm_cfg[j].app_id == BTA_ALL_APP_ID)) && (p_bta_dm_rm_cfg[j].id == id)) { role = p_bta_dm_rm_cfg[j].cfg; if (role > p_dev->pref_role) p_dev->pref_role = role; break; } } } } if ((BTA_ID_AV == id) || (BTA_ID_AVK == id)) { if (status == BTA_SYS_CONN_BUSY) { if (p_dev) p_dev->info |= BTA_DM_DI_AV_ACTIVE; /* AV calls bta_sys_conn_open with the A2DP stream count as app_id */ if (BTA_ID_AV == id) bta_dm_cb.cur_av_count = bta_dm_get_av_count(); } else if (status == BTA_SYS_CONN_IDLE) { if (p_dev) p_dev->info &= ~BTA_DM_DI_AV_ACTIVE; /* get cur_av_count from connected services */ if (BTA_ID_AV == id) bta_dm_cb.cur_av_count = bta_dm_get_av_count(); } APPL_TRACE_WARNING("bta_dm_rm_cback:%d, status:%d", bta_dm_cb.cur_av_count, status); } /* Don't adjust roles for each busy/idle state transition to avoid excessive switch requests when individual profile busy/idle status changes */ if ((status != BTA_SYS_CONN_BUSY) && (status != BTA_SYS_CONN_IDLE)) bta_dm_adjust_roles(false); } /******************************************************************************* * * Function bta_dm_delay_role_switch_cback * * Description Callback from btm to delay a role switch * * Returns void * ******************************************************************************/ static void bta_dm_delay_role_switch_cback(UNUSED_ATTR void* data) { APPL_TRACE_EVENT("%s: initiating Delayed RS", __func__); bta_dm_adjust_roles(false); } /******************************************************************************* * * Function bta_dm_reset_sec_dev_pending * * Description Setting the remove device pending status to false from * security device DB, when the link key notification * event comes. * * Returns void * ******************************************************************************/ static void bta_dm_reset_sec_dev_pending(BD_ADDR remote_bd_addr) { for (size_t i = 0; i < bta_dm_cb.device_list.count; i++) { if (bdcmp(bta_dm_cb.device_list.peer_device[i].peer_bdaddr, remote_bd_addr) == 0) { bta_dm_cb.device_list.peer_device[i].remove_dev_pending = false; return; } } } /******************************************************************************* * * Function bta_dm_remove_sec_dev_entry * * Description Removes device entry from Security device DB if ACL connection with * remtoe device does not exist, else schedule for dev entry removal upon ACL close * * Returns void * ******************************************************************************/ static void bta_dm_remove_sec_dev_entry(BD_ADDR remote_bd_addr) { if (BTM_IsAclConnectionUp(remote_bd_addr, BT_TRANSPORT_LE) || BTM_IsAclConnectionUp(remote_bd_addr, BT_TRANSPORT_BR_EDR)) { APPL_TRACE_DEBUG( "%s ACL is not down. Schedule for Dev Removal when ACL closes", __func__); BTM_SecClearSecurityFlags(remote_bd_addr); for (int i = 0; i < bta_dm_cb.device_list.count; i++) { if (!bdcmp(bta_dm_cb.device_list.peer_device[i].peer_bdaddr, remote_bd_addr)) { bta_dm_cb.device_list.peer_device[i].remove_dev_pending = TRUE; break; } } } else { BTM_SecDeleteDevice(remote_bd_addr); /* need to remove all pending background connection */ BTA_GATTC_CancelOpen(0, remote_bd_addr, false); /* remove all cached GATT information */ bt_bdaddr_t tmp_addr; memcpy(tmp_addr.address, remote_bd_addr, BD_ADDR_LEN); BTA_GATTC_Refresh(tmp_addr); } } /******************************************************************************* * * Function bta_dm_adjust_roles * * Description Adjust roles * * * Returns void * ******************************************************************************/ static void bta_dm_adjust_roles(bool delay_role_switch) { uint8_t i; bool set_master_role = false; uint8_t br_count = bta_dm_cb.device_list.count - bta_dm_cb.device_list.le_count; if (br_count) { /* the configuration is no scatternet * or AV connection exists and there are more than one ACL link */ if ((p_bta_dm_rm_cfg[0].cfg == BTA_DM_NO_SCATTERNET) || (bta_dm_cb.cur_av_count && br_count > 1)) { L2CA_SetDesireRole(HCI_ROLE_MASTER); set_master_role = true; } for (i = 0; i < bta_dm_cb.device_list.count; i++) { if (bta_dm_cb.device_list.peer_device[i].conn_state == BTA_DM_CONNECTED && bta_dm_cb.device_list.peer_device[i].transport == BT_TRANSPORT_BR_EDR) { if (!set_master_role && (bta_dm_cb.device_list.peer_device[i].pref_role != BTA_ANY_ROLE) && (p_bta_dm_rm_cfg[0].cfg == BTA_DM_PARTIAL_SCATTERNET)) { L2CA_SetDesireRole(HCI_ROLE_MASTER); set_master_role = true; } if ((bta_dm_cb.device_list.peer_device[i].pref_role == BTA_MASTER_ROLE_ONLY) || (br_count > 1)) { /* Initiating immediate role switch with certain remote devices has caused issues due to role switch colliding with link encryption setup and causing encryption (and in turn the link) to fail . These device . Firmware versions are stored in a blacklist and role switch with these devices are delayed to avoid the collision with link encryption setup */ if (bta_dm_cb.device_list.peer_device[i].pref_role != BTA_SLAVE_ROLE_ONLY && delay_role_switch == false) { BTM_SwitchRole(bta_dm_cb.device_list.peer_device[i].peer_bdaddr, HCI_ROLE_MASTER, NULL); } else { alarm_set_on_queue( bta_dm_cb.switch_delay_timer, BTA_DM_SWITCH_DELAY_TIMER_MS, bta_dm_delay_role_switch_cback, NULL, btu_bta_alarm_queue); } } } } if (!set_master_role) { L2CA_SetDesireRole(L2CAP_DESIRED_LINK_ROLE); } } else { L2CA_SetDesireRole(L2CAP_DESIRED_LINK_ROLE); } } /******************************************************************************* * * Function bta_dm_get_remname * * Description Returns a pointer to the remote name stored in the DM * control block if it exists, or from the BTM memory. * * Returns char * - Pointer to the remote device name ******************************************************************************/ static char* bta_dm_get_remname(void) { char* p_name = (char*)bta_dm_search_cb.peer_name; char* p_temp; /* If the name isn't already stored, try retrieving from BTM */ if (*p_name == '\0') { p_temp = BTM_SecReadDevName(bta_dm_search_cb.peer_bdaddr); if (p_temp != NULL) p_name = p_temp; } return p_name; } /******************************************************************************* * * Function bta_dm_bond_cancel_complete_cback * * Description Authentication complete callback from BTM * * Returns void * ******************************************************************************/ static void bta_dm_bond_cancel_complete_cback(tBTM_STATUS result) { tBTA_DM_SEC sec_event; if (result == BTM_SUCCESS) sec_event.bond_cancel_cmpl.result = BTA_SUCCESS; else sec_event.bond_cancel_cmpl.result = BTA_FAILURE; if (bta_dm_cb.p_sec_cback) { bta_dm_cb.p_sec_cback(BTA_DM_BOND_CANCEL_CMPL_EVT, &sec_event); } } /******************************************************************************* * * Function find_utf8_char_boundary * * Description This function checks a UTF8 string |utf8str| starting at * |offset|, moving backwards and returns the offset of the * next valid UTF8 character boundary found. * * Returns Offset of UTF8 character boundary * ******************************************************************************/ static size_t find_utf8_char_boundary(const char* utf8str, size_t offset) { CHECK(utf8str); CHECK(offset > 0); while (--offset) { uint8_t ch = (uint8_t)utf8str[offset]; if ((ch & 0x80) == 0x00) // ASCII return offset + 1; if ((ch & 0xC0) == 0xC0) // Multi-byte sequence start return offset; } return 0; } /******************************************************************************* * * Function bta_dm_set_eir * * Description This function creates EIR tagged data and writes it to * controller. * * Returns None * ******************************************************************************/ static void bta_dm_set_eir(char* local_name) { uint8_t* p; uint8_t* p_length; #if (BTA_EIR_CANNED_UUID_LIST != TRUE) uint8_t* p_type; uint8_t max_num_uuid; #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0) uint8_t custom_uuid_idx; #endif // BTA_EIR_SERVER_NUM_CUSTOM_UUID #endif // BTA_EIR_CANNED_UUID_LIST #if (BTM_EIR_DEFAULT_FEC_REQUIRED == FALSE) uint8_t free_eir_length = HCI_EXT_INQ_RESPONSE_LEN; #else // BTM_EIR_DEFAULT_FEC_REQUIRED uint8_t free_eir_length = HCI_DM5_PACKET_SIZE; #endif // BTM_EIR_DEFAULT_FEC_REQUIRED uint8_t num_uuid; uint8_t data_type; uint8_t local_name_len; /* wait until complete to disable */ if (alarm_is_scheduled(bta_dm_cb.disable_timer)) return; #if (BTA_EIR_CANNED_UUID_LIST != TRUE) /* if local name is not provided, get it from controller */ if (local_name == NULL) { if (BTM_ReadLocalDeviceName(&local_name) != BTM_SUCCESS) { APPL_TRACE_ERROR("Fail to read local device name for EIR"); } } #endif // BTA_EIR_CANNED_UUID_LIST /* Allocate a buffer to hold HCI command */ BT_HDR* p_buf = (BT_HDR*)osi_malloc(BTM_CMD_BUF_SIZE); p = (uint8_t*)p_buf + BTM_HCI_EIR_OFFSET; memset(p, 0x00, HCI_EXT_INQ_RESPONSE_LEN); APPL_TRACE_DEBUG("BTA is generating EIR"); if (local_name) local_name_len = strlen(local_name); else local_name_len = 0; data_type = BTM_EIR_COMPLETE_LOCAL_NAME_TYPE; /* if local name is longer than minimum length of shortened name */ /* check whether it needs to be shortened or not */ if (local_name_len > p_bta_dm_eir_cfg->bta_dm_eir_min_name_len) { /* get number of UUID 16-bit list */ #if (BTA_EIR_CANNED_UUID_LIST == TRUE) num_uuid = p_bta_dm_eir_cfg->bta_dm_eir_uuid16_len / LEN_UUID_16; #else // BTA_EIR_CANNED_UUID_LIST max_num_uuid = (free_eir_length - 2) / LEN_UUID_16; data_type = BTM_GetEirSupportedServices(bta_dm_cb.eir_uuid, &p, max_num_uuid, &num_uuid); p = (uint8_t*)p_buf + BTM_HCI_EIR_OFFSET; /* reset p */ #endif // BTA_EIR_CANNED_UUID_LIST /* if UUID doesn't fit remaing space, shorten local name */ if (local_name_len > (free_eir_length - 4 - num_uuid * LEN_UUID_16)) { local_name_len = find_utf8_char_boundary( local_name, p_bta_dm_eir_cfg->bta_dm_eir_min_name_len); APPL_TRACE_WARNING("%s local name is shortened (%d)", __func__, local_name_len); data_type = BTM_EIR_SHORTENED_LOCAL_NAME_TYPE; } else { data_type = BTM_EIR_COMPLETE_LOCAL_NAME_TYPE; } } UINT8_TO_STREAM(p, local_name_len + 1); UINT8_TO_STREAM(p, data_type); if (local_name != NULL) { memcpy(p, local_name, local_name_len); p += local_name_len; } free_eir_length -= local_name_len + 2; #if (BTA_EIR_CANNED_UUID_LIST == TRUE) /* if UUID list is provided as static data in configuration */ if ((p_bta_dm_eir_cfg->bta_dm_eir_uuid16_len > 0) && (p_bta_dm_eir_cfg->bta_dm_eir_uuid16)) { if (free_eir_length > LEN_UUID_16 + 2) { free_eir_length -= 2; if (free_eir_length >= p_bta_dm_eir_cfg->bta_dm_eir_uuid16_len) { num_uuid = p_bta_dm_eir_cfg->bta_dm_eir_uuid16_len / LEN_UUID_16; data_type = BTM_EIR_COMPLETE_16BITS_UUID_TYPE; } else /* not enough room for all UUIDs */ { APPL_TRACE_WARNING("BTA EIR: UUID 16-bit list is truncated"); num_uuid = free_eir_length / LEN_UUID_16; data_type = BTM_EIR_MORE_16BITS_UUID_TYPE; } UINT8_TO_STREAM(p, num_uuid * LEN_UUID_16 + 1); UINT8_TO_STREAM(p, data_type); memcpy(p, p_bta_dm_eir_cfg->bta_dm_eir_uuid16, num_uuid * LEN_UUID_16); p += num_uuid * LEN_UUID_16; free_eir_length -= num_uuid * LEN_UUID_16; } } #else /* (BTA_EIR_CANNED_UUID_LIST == TRUE) */ /* if UUID list is dynamic */ if (free_eir_length >= 2) { p_length = p++; p_type = p++; num_uuid = 0; max_num_uuid = (free_eir_length - 2) / LEN_UUID_16; data_type = BTM_GetEirSupportedServices(bta_dm_cb.eir_uuid, &p, max_num_uuid, &num_uuid); if (data_type == BTM_EIR_MORE_16BITS_UUID_TYPE) { APPL_TRACE_WARNING("BTA EIR: UUID 16-bit list is truncated"); } #if (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0) else { for (custom_uuid_idx = 0; custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID; custom_uuid_idx++) { if (bta_dm_cb.custom_uuid[custom_uuid_idx].len == LEN_UUID_16) { if (num_uuid < max_num_uuid) { UINT16_TO_STREAM(p, bta_dm_cb.custom_uuid[custom_uuid_idx].uu.uuid16); num_uuid++; } else { data_type = BTM_EIR_MORE_16BITS_UUID_TYPE; APPL_TRACE_WARNING("BTA EIR: UUID 16-bit list is truncated"); break; } } } } #endif /* (BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0) */ UINT8_TO_STREAM(p_length, num_uuid * LEN_UUID_16 + 1); UINT8_TO_STREAM(p_type, data_type); free_eir_length -= num_uuid * LEN_UUID_16 + 2; } #endif /* (BTA_EIR_CANNED_UUID_LIST == TRUE) */ #if (BTA_EIR_CANNED_UUID_LIST != TRUE && BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0) /* Adding 32-bit UUID list */ if (free_eir_length >= 2) { p_length = p++; p_type = p++; num_uuid = 0; data_type = BTM_EIR_COMPLETE_32BITS_UUID_TYPE; max_num_uuid = (free_eir_length - 2) / LEN_UUID_32; for (custom_uuid_idx = 0; custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID; custom_uuid_idx++) { if (bta_dm_cb.custom_uuid[custom_uuid_idx].len == LEN_UUID_32) { if (num_uuid < max_num_uuid) { UINT32_TO_STREAM(p, bta_dm_cb.custom_uuid[custom_uuid_idx].uu.uuid32); num_uuid++; } else { data_type = BTM_EIR_MORE_32BITS_UUID_TYPE; APPL_TRACE_WARNING("BTA EIR: UUID 32-bit list is truncated"); break; } } } UINT8_TO_STREAM(p_length, num_uuid * LEN_UUID_32 + 1); UINT8_TO_STREAM(p_type, data_type); free_eir_length -= num_uuid * LEN_UUID_32 + 2; } /* Adding 128-bit UUID list */ if (free_eir_length >= 2) { p_length = p++; p_type = p++; num_uuid = 0; data_type = BTM_EIR_COMPLETE_128BITS_UUID_TYPE; max_num_uuid = (free_eir_length - 2) / LEN_UUID_128; for (custom_uuid_idx = 0; custom_uuid_idx < BTA_EIR_SERVER_NUM_CUSTOM_UUID; custom_uuid_idx++) { if (bta_dm_cb.custom_uuid[custom_uuid_idx].len == LEN_UUID_128) { if (num_uuid < max_num_uuid) { ARRAY16_TO_STREAM(p, bta_dm_cb.custom_uuid[custom_uuid_idx].uu.uuid128); num_uuid++; } else { data_type = BTM_EIR_MORE_128BITS_UUID_TYPE; APPL_TRACE_WARNING("BTA EIR: UUID 128-bit list is truncated"); break; } } } UINT8_TO_STREAM(p_length, num_uuid * LEN_UUID_128 + 1); UINT8_TO_STREAM(p_type, data_type); free_eir_length -= num_uuid * LEN_UUID_128 + 2; } #endif /* ( BTA_EIR_CANNED_UUID_LIST != TRUE \ )&&(BTA_EIR_SERVER_NUM_CUSTOM_UUID > 0) */ /* if Flags are provided in configuration */ if ((p_bta_dm_eir_cfg->bta_dm_eir_flag_len > 0) && (p_bta_dm_eir_cfg->bta_dm_eir_flags) && (free_eir_length >= p_bta_dm_eir_cfg->bta_dm_eir_flag_len + 2)) { UINT8_TO_STREAM(p, p_bta_dm_eir_cfg->bta_dm_eir_flag_len + 1); UINT8_TO_STREAM(p, BTM_EIR_FLAGS_TYPE); memcpy(p, p_bta_dm_eir_cfg->bta_dm_eir_flags, p_bta_dm_eir_cfg->bta_dm_eir_flag_len); p += p_bta_dm_eir_cfg->bta_dm_eir_flag_len; free_eir_length -= p_bta_dm_eir_cfg->bta_dm_eir_flag_len + 2; } /* if Manufacturer Specific are provided in configuration */ if ((p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len > 0) && (p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec) && (free_eir_length >= p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len + 2)) { p_length = p; UINT8_TO_STREAM(p, p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len + 1); UINT8_TO_STREAM(p, BTM_EIR_MANUFACTURER_SPECIFIC_TYPE); memcpy(p, p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec, p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len); p += p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len; free_eir_length -= p_bta_dm_eir_cfg->bta_dm_eir_manufac_spec_len + 2; } else { p_length = NULL; } /* if Inquiry Tx Resp Power compiled */ if ((p_bta_dm_eir_cfg->bta_dm_eir_inq_tx_power) && (free_eir_length >= 3)) { UINT8_TO_STREAM(p, 2); /* Length field */ UINT8_TO_STREAM(p, BTM_EIR_TX_POWER_LEVEL_TYPE); UINT8_TO_STREAM(p, *(p_bta_dm_eir_cfg->bta_dm_eir_inq_tx_power)); free_eir_length -= 3; } if (free_eir_length) UINT8_TO_STREAM(p, 0); /* terminator of significant part */ BTM_WriteEIR(p_buf); } /******************************************************************************* * * Function bta_dm_eir_search_services * * Description This function searches services in received EIR * * Returns None * ******************************************************************************/ static void bta_dm_eir_search_services(tBTM_INQ_RESULTS* p_result, tBTA_SERVICE_MASK* p_services_to_search, tBTA_SERVICE_MASK* p_services_found) { tBTA_SERVICE_MASK service_index = 0; tBTM_EIR_SEARCH_RESULT result; APPL_TRACE_DEBUG( "BTA searching services in EIR of BDA:0x%02X%02X%02X%02X%02X%02X", p_result->remote_bd_addr[0], p_result->remote_bd_addr[1], p_result->remote_bd_addr[2], p_result->remote_bd_addr[3], p_result->remote_bd_addr[4], p_result->remote_bd_addr[5]); APPL_TRACE_DEBUG(" with services_to_search=0x%08X", *p_services_to_search); /* always do GATT based service discovery by SDP instead of from EIR */ /* if GATT based service is also to be put in EIR, need to modify this */ while (service_index < (BTA_MAX_SERVICE_ID - 1)) { if (*p_services_to_search & (tBTA_SERVICE_MASK)(BTA_SERVICE_ID_TO_SERVICE_MASK(service_index))) { result = BTM_HasInquiryEirService( p_result, bta_service_id_to_uuid_lkup_tbl[service_index]); /* Searching for HSP v1.2 only device */ if ((result != BTM_EIR_FOUND) && (bta_service_id_to_uuid_lkup_tbl[service_index] == UUID_SERVCLASS_HEADSET)) { result = BTM_HasInquiryEirService(p_result, UUID_SERVCLASS_HEADSET_HS); } if (result == BTM_EIR_FOUND) { /* If Plug and Play service record, need to check to see if Broadcom * stack */ /* However, EIR data doesn't have EXT_BRCM_VERSION so just skip it */ if (bta_service_id_to_uuid_lkup_tbl[service_index] != UUID_SERVCLASS_PNP_INFORMATION) { *p_services_found |= (tBTA_SERVICE_MASK)( BTA_SERVICE_ID_TO_SERVICE_MASK(service_index)); /* remove the service from services to be searched */ *p_services_to_search &= (tBTA_SERVICE_MASK)( ~(BTA_SERVICE_ID_TO_SERVICE_MASK(service_index))); } } else if (result == BTM_EIR_NOT_FOUND) { /* remove the service from services to be searched */ *p_services_to_search &= (tBTA_SERVICE_MASK)( ~(BTA_SERVICE_ID_TO_SERVICE_MASK(service_index))); } } service_index++; } APPL_TRACE_ERROR( "BTA EIR search result, services_to_search=0x%08X, services_found=0x%08X", *p_services_to_search, *p_services_found); } #if (BTA_EIR_CANNED_UUID_LIST != TRUE) /******************************************************************************* * * Function bta_dm_eir_update_uuid * * Description This function adds or removes service UUID in EIR database. * * Returns None * ******************************************************************************/ void bta_dm_eir_update_uuid(uint16_t uuid16, bool adding) { /* if this UUID is not advertised in EIR */ if (!BTM_HasEirService(p_bta_dm_eir_cfg->uuid_mask, uuid16)) return; if (adding) { APPL_TRACE_EVENT("Adding UUID=0x%04X into EIR", uuid16); BTM_AddEirService(bta_dm_cb.eir_uuid, uuid16); } else { APPL_TRACE_EVENT("Removing UUID=0x%04X from EIR", uuid16); BTM_RemoveEirService(bta_dm_cb.eir_uuid, uuid16); } bta_dm_set_eir(NULL); APPL_TRACE_EVENT("bta_dm_eir_update_uuid UUID bit mask=0x%08X %08X", bta_dm_cb.eir_uuid[1], bta_dm_cb.eir_uuid[0]); } #endif /******************************************************************************* * * Function bta_dm_enable_test_mode * * Description enable test mode * * * Returns void * ******************************************************************************/ void bta_dm_enable_test_mode(UNUSED_ATTR tBTA_DM_MSG* p_data) { BTM_EnableTestMode(); } /******************************************************************************* * * Function bta_dm_disable_test_mode * * Description disable test mode * * * Returns void * ******************************************************************************/ void bta_dm_disable_test_mode(UNUSED_ATTR tBTA_DM_MSG* p_data) { BTM_DeviceReset(NULL); } /******************************************************************************* * * Function bta_dm_execute_callback * * Description Just execute a generic call back in the context of the * BTU/BTA tack * * * Returns void * ******************************************************************************/ void bta_dm_execute_callback(tBTA_DM_MSG* p_data) { /* sanity check */ if (p_data->exec_cback.p_exec_cback == NULL) { return; } p_data->exec_cback.p_exec_cback(p_data->exec_cback.p_param); } /******************************************************************************* * * Function bta_dm_encrypt_cback * * Description link encryption complete callback. * * Returns None * ******************************************************************************/ void bta_dm_encrypt_cback(BD_ADDR bd_addr, tBT_TRANSPORT transport, UNUSED_ATTR void* p_ref_data, tBTM_STATUS result) { tBTA_STATUS bta_status = BTA_SUCCESS; tBTA_DM_ENCRYPT_CBACK* p_callback = NULL; uint8_t i; for (i = 0; i < bta_dm_cb.device_list.count; i++) { if (bdcmp(bta_dm_cb.device_list.peer_device[i].peer_bdaddr, bd_addr) == 0 && bta_dm_cb.device_list.peer_device[i].conn_state == BTA_DM_CONNECTED) break; } if (i < bta_dm_cb.device_list.count) { p_callback = bta_dm_cb.device_list.peer_device[i].p_encrypt_cback; bta_dm_cb.device_list.peer_device[i].p_encrypt_cback = NULL; } switch (result) { case BTM_SUCCESS: break; case BTM_WRONG_MODE: bta_status = BTA_WRONG_MODE; break; case BTM_NO_RESOURCES: bta_status = BTA_NO_RESOURCES; break; case BTM_BUSY: bta_status = BTA_BUSY; break; default: bta_status = BTA_FAILURE; break; } APPL_TRACE_DEBUG("bta_dm_encrypt_cback status =%d p_callback=0x%x", bta_status, p_callback); if (p_callback) { (*p_callback)(bd_addr, transport, bta_status); } } /******************************************************************************* * * Function bta_dm_set_encryption * * Description This function to encrypt the link * * Returns None * ******************************************************************************/ void bta_dm_set_encryption(tBTA_DM_MSG* p_data) { uint8_t i; APPL_TRACE_DEBUG("bta_dm_set_encryption"); // todo if (!p_data->set_encryption.p_callback) { APPL_TRACE_ERROR("bta_dm_set_encryption callback is not provided"); return; } for (i = 0; i < bta_dm_cb.device_list.count; i++) { if (bdcmp(bta_dm_cb.device_list.peer_device[i].peer_bdaddr, p_data->set_encryption.bd_addr) == 0 && bta_dm_cb.device_list.peer_device[i].conn_state == BTA_DM_CONNECTED) break; } if (i < bta_dm_cb.device_list.count) { if (bta_dm_cb.device_list.peer_device[i].p_encrypt_cback) { APPL_TRACE_ERROR("earlier enc was not done for same device"); (*p_data->set_encryption.p_callback)(p_data->set_encryption.bd_addr, p_data->set_encryption.transport, BTA_BUSY); return; } if (BTM_SetEncryption(p_data->set_encryption.bd_addr, p_data->set_encryption.transport, bta_dm_encrypt_cback, NULL, p_data->set_encryption.sec_act) == BTM_CMD_STARTED) { bta_dm_cb.device_list.peer_device[i].p_encrypt_cback = p_data->set_encryption.p_callback; } } } bool bta_dm_check_if_only_hd_connected(BD_ADDR peer_addr) { APPL_TRACE_DEBUG("%s: count(%d)", __func__, bta_dm_conn_srvcs.count); for (uint8_t j = 0; j < bta_dm_conn_srvcs.count; j++) { // Check if profiles other than hid are connected if ((bta_dm_conn_srvcs.conn_srvc[j].id != BTA_ID_HD) && !bdcmp(bta_dm_conn_srvcs.conn_srvc[j].peer_bdaddr, peer_addr)) { APPL_TRACE_DEBUG("%s: Another profile (id=%d) is connected", __func__, bta_dm_conn_srvcs.conn_srvc[j].id); return false; } } return true; } /******************************************************************************* * * Function bta_dm_observe_results_cb * * Description Callback for BLE Observe result * * * Returns void * ******************************************************************************/ static void bta_dm_observe_results_cb(tBTM_INQ_RESULTS* p_inq, uint8_t* p_eir, uint16_t eir_len) { tBTA_DM_SEARCH result; tBTM_INQ_INFO* p_inq_info; APPL_TRACE_DEBUG("bta_dm_observe_results_cb"); bdcpy(result.inq_res.bd_addr, p_inq->remote_bd_addr); result.inq_res.rssi = p_inq->rssi; result.inq_res.ble_addr_type = p_inq->ble_addr_type; result.inq_res.inq_result_type = p_inq->inq_result_type; result.inq_res.device_type = p_inq->device_type; result.inq_res.flag = p_inq->flag; result.inq_res.ble_evt_type = p_inq->ble_evt_type; result.inq_res.ble_primary_phy = p_inq->ble_primary_phy; result.inq_res.ble_secondary_phy = p_inq->ble_secondary_phy; result.inq_res.ble_advertising_sid = p_inq->ble_advertising_sid; result.inq_res.ble_tx_power = p_inq->ble_tx_power; result.inq_res.ble_periodic_adv_int = p_inq->ble_periodic_adv_int; /* application will parse EIR to find out remote device name */ result.inq_res.p_eir = p_eir; result.inq_res.eir_len = eir_len; p_inq_info = BTM_InqDbRead(p_inq->remote_bd_addr); if (p_inq_info != NULL) { /* initialize remt_name_not_required to false so that we get the name by * default */ result.inq_res.remt_name_not_required = false; } if (bta_dm_search_cb.p_scan_cback) bta_dm_search_cb.p_scan_cback(BTA_DM_INQ_RES_EVT, &result); if (p_inq_info) { /* application indicates if it knows the remote name, inside the callback copy that to the inquiry data base*/ if (result.inq_res.remt_name_not_required) p_inq_info->appl_knows_rem_name = true; } } /******************************************************************************* * * Function bta_dm_observe_cmpl_cb * * Description Callback for BLE Observe complete * * * Returns void * ******************************************************************************/ static void bta_dm_observe_cmpl_cb(void* p_result) { tBTA_DM_SEARCH data; APPL_TRACE_DEBUG("bta_dm_observe_cmpl_cb"); data.inq_cmpl.num_resps = ((tBTM_INQUIRY_CMPL*)p_result)->num_resp; if (bta_dm_search_cb.p_scan_cback) { bta_dm_search_cb.p_scan_cback(BTA_DM_INQ_CMPL_EVT, &data); } } /******************************************************************************* * * Function bta_dm_ble_smp_cback * * Description Callback for BLE SMP * * * Returns void * ******************************************************************************/ static uint8_t bta_dm_ble_smp_cback(tBTM_LE_EVT event, BD_ADDR bda, tBTM_LE_EVT_DATA* p_data) { tBTM_STATUS status = BTM_SUCCESS; tBTA_DM_SEC sec_event; char* p_name = NULL; if (!bta_dm_cb.p_sec_cback) return BTM_NOT_AUTHORIZED; memset(&sec_event, 0, sizeof(tBTA_DM_SEC)); switch (event) { case BTM_LE_IO_REQ_EVT: #if (BTM_LOCAL_IO_CAPS != BTM_IO_CAP_NONE) bta_dm_co_ble_io_req( bda, &p_data->io_req.io_cap, &p_data->io_req.oob_data, &p_data->io_req.auth_req, &p_data->io_req.max_key_size, &p_data->io_req.init_keys, &p_data->io_req.resp_keys); #endif APPL_TRACE_EVENT("io mitm: %d oob_data:%d", p_data->io_req.auth_req, p_data->io_req.oob_data); break; case BTM_LE_SEC_REQUEST_EVT: bdcpy(sec_event.ble_req.bd_addr, bda); p_name = BTM_SecReadDevName(bda); if (p_name != NULL) strlcpy((char*)sec_event.ble_req.bd_name, p_name, BD_NAME_LEN); else sec_event.ble_req.bd_name[0] = 0; bta_dm_cb.p_sec_cback(BTA_DM_BLE_SEC_REQ_EVT, &sec_event); break; case BTM_LE_KEY_NOTIF_EVT: bdcpy(sec_event.key_notif.bd_addr, bda); p_name = BTM_SecReadDevName(bda); if (p_name != NULL) strlcpy((char*)sec_event.key_notif.bd_name, p_name, BD_NAME_LEN); else sec_event.key_notif.bd_name[0] = 0; sec_event.key_notif.passkey = p_data->key_notif; bta_dm_cb.p_sec_cback(BTA_DM_BLE_PASSKEY_NOTIF_EVT, &sec_event); break; case BTM_LE_KEY_REQ_EVT: bdcpy(sec_event.ble_req.bd_addr, bda); bta_dm_cb.p_sec_cback(BTA_DM_BLE_PASSKEY_REQ_EVT, &sec_event); break; case BTM_LE_OOB_REQ_EVT: bdcpy(sec_event.ble_req.bd_addr, bda); bta_dm_cb.p_sec_cback(BTA_DM_BLE_OOB_REQ_EVT, &sec_event); break; case BTM_LE_NC_REQ_EVT: bdcpy(sec_event.key_notif.bd_addr, bda); strlcpy((char*)sec_event.key_notif.bd_name, bta_dm_get_remname(), (BD_NAME_LEN)); sec_event.key_notif.passkey = p_data->key_notif; bta_dm_cb.p_sec_cback(BTA_DM_BLE_NC_REQ_EVT, &sec_event); break; case BTM_LE_SC_OOB_REQ_EVT: bdcpy(sec_event.ble_req.bd_addr, bda); bta_dm_cb.p_sec_cback(BTA_DM_BLE_SC_OOB_REQ_EVT, &sec_event); break; case BTM_LE_KEY_EVT: bdcpy(sec_event.ble_key.bd_addr, bda); sec_event.ble_key.key_type = p_data->key.key_type; sec_event.ble_key.p_key_value = p_data->key.p_key_value; bta_dm_cb.p_sec_cback(BTA_DM_BLE_KEY_EVT, &sec_event); break; case BTM_LE_COMPLT_EVT: bdcpy(sec_event.auth_cmpl.bd_addr, bda); BTM_ReadDevInfo(bda, &sec_event.auth_cmpl.dev_type, &sec_event.auth_cmpl.addr_type); p_name = BTM_SecReadDevName(bda); if (p_name != NULL) strlcpy((char*)sec_event.auth_cmpl.bd_name, p_name, (BD_NAME_LEN)); else sec_event.auth_cmpl.bd_name[0] = 0; if (p_data->complt.reason != 0) { sec_event.auth_cmpl.fail_reason = BTA_DM_AUTH_CONVERT_SMP_CODE(((uint8_t)p_data->complt.reason)); /* delete this device entry from Sec Dev DB */ bta_dm_remove_sec_dev_entry(bda); } else { sec_event.auth_cmpl.success = true; } if (bta_dm_cb.p_sec_cback) { // bta_dm_cb.p_sec_cback(BTA_DM_AUTH_CMPL_EVT, &sec_event); bta_dm_cb.p_sec_cback(BTA_DM_BLE_AUTH_CMPL_EVT, &sec_event); } break; default: status = BTM_NOT_AUTHORIZED; break; } return status; } /******************************************************************************* * * Function bta_dm_ble_id_key_cback * * Description Callback for BLE local ID keys * * * Returns void * ******************************************************************************/ static void bta_dm_ble_id_key_cback(uint8_t key_type, tBTM_BLE_LOCAL_KEYS* p_key) { uint8_t evt; tBTA_DM_SEC dm_key; switch (key_type) { case BTM_BLE_KEY_TYPE_ID: case BTM_BLE_KEY_TYPE_ER: if (bta_dm_cb.p_sec_cback) { memcpy(&dm_key.ble_id_keys, p_key, sizeof(tBTM_BLE_LOCAL_KEYS)); evt = (key_type == BTM_BLE_KEY_TYPE_ID) ? BTA_DM_BLE_LOCAL_IR_EVT : BTA_DM_BLE_LOCAL_ER_EVT; bta_dm_cb.p_sec_cback(evt, &dm_key); } break; default: APPL_TRACE_DEBUG("Unknown key type %d", key_type); break; } return; } /******************************************************************************* * * Function bta_dm_add_blekey * * Description This function adds an BLE Key to an security database entry. * This function shall only be called AFTER BTA_DmAddBleDevice * has been called. * It is normally called during host startup to restore all * required information stored in the NVRAM. * * Parameters: * ******************************************************************************/ void bta_dm_add_blekey(tBTA_DM_MSG* p_data) { if (!BTM_SecAddBleKey(p_data->add_ble_key.bd_addr, (tBTM_LE_KEY_VALUE*)&p_data->add_ble_key.blekey, p_data->add_ble_key.key_type)) { APPL_TRACE_ERROR( "BTA_DM: Error adding BLE Key for device %08x%04x", (p_data->add_ble_key.bd_addr[0] << 24) + (p_data->add_ble_key.bd_addr[1] << 16) + (p_data->add_ble_key.bd_addr[2] << 8) + p_data->add_ble_key.bd_addr[3], (p_data->add_ble_key.bd_addr[4] << 8) + p_data->add_ble_key.bd_addr[5]); } } /******************************************************************************* * * Function bta_dm_add_ble_device * * Description This function adds an BLE device to an security database * entry. * It is normally called during host startup to restore all * required information stored in the NVRAM. * * Parameters: * ******************************************************************************/ void bta_dm_add_ble_device(tBTA_DM_MSG* p_data) { if (!BTM_SecAddBleDevice(p_data->add_ble_device.bd_addr, NULL, p_data->add_ble_device.dev_type, p_data->add_ble_device.addr_type)) { APPL_TRACE_ERROR("BTA_DM: Error adding BLE Device for device %08x%04x", (p_data->add_ble_device.bd_addr[0] << 24) + (p_data->add_ble_device.bd_addr[1] << 16) + (p_data->add_ble_device.bd_addr[2] << 8) + p_data->add_ble_device.bd_addr[3], (p_data->add_ble_device.bd_addr[4] << 8) + p_data->add_ble_device.bd_addr[5]); } } /******************************************************************************* * * Function bta_dm_add_ble_device * * Description This function adds an BLE device to an security database * entry. * It is normally called during host startup to restore all * required information stored in the NVRAM. * * Parameters: * ******************************************************************************/ void bta_dm_ble_passkey_reply(tBTA_DM_MSG* p_data) { if (p_data->pin_reply.accept) { BTM_BlePasskeyReply(p_data->ble_passkey_reply.bd_addr, BTM_SUCCESS, p_data->ble_passkey_reply.passkey); } else { BTM_BlePasskeyReply(p_data->ble_passkey_reply.bd_addr, BTM_NOT_AUTHORIZED, p_data->ble_passkey_reply.passkey); } } /******************************************************************************* * * Function bta_dm_ble_confirm_reply * * Description This is response to SM numeric comparison request submitted * to application. * * Parameters: * ******************************************************************************/ void bta_dm_ble_confirm_reply(tBTA_DM_MSG* p_data) { if (p_data->confirm.accept) { BTM_BleConfirmReply(p_data->confirm.bd_addr, BTM_SUCCESS); } else { BTM_BleConfirmReply(p_data->ble_passkey_reply.bd_addr, BTM_NOT_AUTHORIZED); } } /******************************************************************************* * * Function bta_dm_security_grant * * Description This function grant SMP security request access. * * Parameters: * ******************************************************************************/ void bta_dm_security_grant(tBTA_DM_MSG* p_data) { BTM_SecurityGrant(p_data->ble_sec_grant.bd_addr, p_data->ble_sec_grant.res); } /******************************************************************************* * * Function bta_dm_ble_set_bg_conn_type * * Description This function set the BLE background connection type * * Parameters: * ******************************************************************************/ void bta_dm_ble_set_bg_conn_type(tBTA_DM_MSG* p_data) { BTM_BleStartAutoConn(); } /******************************************************************************* * * Function bta_dm_ble_set_conn_params * * Description This function set the preferred connection parameters. * * Parameters: * ******************************************************************************/ void bta_dm_ble_set_conn_params(tBTA_DM_MSG* p_data) { BTM_BleSetPrefConnParams(p_data->ble_set_conn_params.peer_bda, p_data->ble_set_conn_params.conn_int_min, p_data->ble_set_conn_params.conn_int_max, p_data->ble_set_conn_params.slave_latency, p_data->ble_set_conn_params.supervision_tout); } /******************************************************************************* * * Function bta_dm_ble_set_conn_scan_params * * Description This function set the preferred connection scan parameters. * * Parameters: * ******************************************************************************/ void bta_dm_ble_set_conn_scan_params(tBTA_DM_MSG* p_data) { BTM_BleSetConnScanParams(p_data->ble_set_conn_scan_params.scan_int, p_data->ble_set_conn_scan_params.scan_window); } /******************************************************************************* * * Function bta_dm_ble_update_conn_params * * Description This function update LE connection parameters. * * Parameters: * ******************************************************************************/ void bta_dm_ble_update_conn_params(tBTA_DM_MSG* p_data) { if (!L2CA_UpdateBleConnParams(p_data->ble_update_conn_params.bd_addr, p_data->ble_update_conn_params.min_int, p_data->ble_update_conn_params.max_int, p_data->ble_update_conn_params.latency, p_data->ble_update_conn_params.timeout)) { APPL_TRACE_ERROR("Update connection parameters failed!"); } } #if (BLE_PRIVACY_SPT == TRUE) /******************************************************************************* * * Function bta_dm_ble_config_local_privacy * * Description This function set the local device LE privacy settings. * * Parameters: * ******************************************************************************/ void bta_dm_ble_config_local_privacy(tBTA_DM_MSG* p_data) { BTM_BleConfigPrivacy(p_data->ble_local_privacy.privacy_enable); } #endif /******************************************************************************* * * Function bta_dm_ble_observe * * Description This function set the preferred connection scan parameters. * * Parameters: * ******************************************************************************/ void bta_dm_ble_observe(tBTA_DM_MSG* p_data) { tBTM_STATUS status; if (p_data->ble_observe.start) { /*Save the callback to be called when a scan results are available */ bta_dm_search_cb.p_scan_cback = p_data->ble_observe.p_cback; status = BTM_BleObserve(true, p_data->ble_observe.duration, bta_dm_observe_results_cb, bta_dm_observe_cmpl_cb); if (status != BTM_CMD_STARTED) { tBTA_DM_SEARCH data; APPL_TRACE_WARNING(" %s BTM_BleObserve failed. status %d", __func__, status); data.inq_cmpl.num_resps = 0; if (bta_dm_search_cb.p_scan_cback) { bta_dm_search_cb.p_scan_cback(BTA_DM_INQ_CMPL_EVT, &data); } } } else { bta_dm_search_cb.p_scan_cback = NULL; BTM_BleObserve(false, 0, NULL, NULL); } } /******************************************************************************* * * Function bta_dm_ble_set_adv_params * * Description This function set the adv parameters. * * Parameters: * ******************************************************************************/ void bta_dm_ble_set_adv_params(uint16_t adv_int_min, uint16_t adv_int_max, tBLE_BD_ADDR* p_dir_bda) { BTM_BleSetAdvParams(adv_int_min, adv_int_max, p_dir_bda, BTA_DM_BLE_ADV_CHNL_MAP); } /******************************************************************************* * * Function bta_dm_ble_set_data_length * * Description This function set the maximum transmission packet size * * Parameters * ******************************************************************************/ void bta_dm_ble_set_data_length(tBTA_DM_MSG* p_data) { if (BTM_SetBleDataLength(p_data->ble_set_data_length.remote_bda, p_data->ble_set_data_length.tx_data_length) != BTM_SUCCESS) { APPL_TRACE_ERROR("%s failed", __func__); } } /******************************************************************************* * * Function bta_ble_enable_scan_cmpl * * Description ADV payload filtering enable / disable complete callback * * * Returns None * ******************************************************************************/ static void bta_ble_energy_info_cmpl(tBTM_BLE_TX_TIME_MS tx_time, tBTM_BLE_RX_TIME_MS rx_time, tBTM_BLE_IDLE_TIME_MS idle_time, tBTM_BLE_ENERGY_USED energy_used, tBTM_STATUS status) { tBTA_STATUS st = (status == BTM_SUCCESS) ? BTA_SUCCESS : BTA_FAILURE; tBTA_DM_CONTRL_STATE ctrl_state = 0; if (BTA_SUCCESS == st) ctrl_state = bta_dm_pm_obtain_controller_state(); if (bta_dm_cb.p_energy_info_cback) bta_dm_cb.p_energy_info_cback(tx_time, rx_time, idle_time, energy_used, ctrl_state, st); } /******************************************************************************* * * Function bta_dm_ble_get_energy_info * * Description This function obtains the energy info * * Parameters: * ******************************************************************************/ void bta_dm_ble_get_energy_info(tBTA_DM_MSG* p_data) { tBTM_STATUS btm_status = 0; bta_dm_cb.p_energy_info_cback = p_data->ble_energy_info.p_energy_info_cback; btm_status = BTM_BleGetEnergyInfo(bta_ble_energy_info_cmpl); if (BTM_CMD_STARTED != btm_status) bta_ble_energy_info_cmpl(0, 0, 0, 0, btm_status); } #ifndef BTA_DM_GATT_CLOSE_DELAY_TOUT #define BTA_DM_GATT_CLOSE_DELAY_TOUT 1000 #endif /******************************************************************************* * * Function bta_dm_gattc_register * * Description Register with GATTC in DM if BLE is needed. * * * Returns void * ******************************************************************************/ static void bta_dm_gattc_register(void) { if (bta_dm_search_cb.client_if == BTA_GATTS_INVALID_IF) { BTA_GATTC_AppRegister(bta_dm_gattc_callback, base::Bind([](uint8_t client_id, uint8_t status) { if (status == BTA_GATT_OK) bta_dm_search_cb.client_if = client_id; else bta_dm_search_cb.client_if = BTA_GATTS_INVALID_IF; })); } } /******************************************************************************* * * Function btm_dm_start_disc_gatt_services * * Description This function starts a GATT service search request. * * Parameters: * ******************************************************************************/ static void btm_dm_start_disc_gatt_services(uint16_t conn_id) { tBT_UUID* p_uuid = bta_dm_search_cb.p_srvc_uuid + bta_dm_search_cb.num_uuid - bta_dm_search_cb.uuid_to_search; p_uuid = bta_dm_search_cb.p_srvc_uuid + bta_dm_search_cb.num_uuid - bta_dm_search_cb.uuid_to_search; /* always search for all services */ BTA_GATTC_ServiceSearchRequest(conn_id, p_uuid); } /******************************************************************************* * * Function bta_dm_gatt_disc_result * * Description This function process the GATT service search result. * * Parameters: * ******************************************************************************/ static void bta_dm_gatt_disc_result(tBTA_GATT_ID service_id) { tBTA_DM_SEARCH result; /* * This logic will not work for gatt case. We are checking against the * bluetooth profiles here * just copy the GATTID in raw data field and send it across. */ if (bta_dm_search_cb.ble_raw_used + sizeof(tBTA_GATT_ID) < bta_dm_search_cb.ble_raw_size) { APPL_TRACE_DEBUG( "ADDING BLE SERVICE uuid=0x%x, ble_ptr = 0x%x, ble_raw_used = 0x%x", service_id.uuid.uu.uuid16, bta_dm_search_cb.p_ble_rawdata, bta_dm_search_cb.ble_raw_used); if (bta_dm_search_cb.p_ble_rawdata) { memcpy((bta_dm_search_cb.p_ble_rawdata + bta_dm_search_cb.ble_raw_used), &service_id, sizeof(service_id)); bta_dm_search_cb.ble_raw_used += sizeof(service_id); } else { APPL_TRACE_ERROR("p_ble_rawdata is NULL"); } } else { APPL_TRACE_ERROR( "%s out of room to accomodate more service ids ble_raw_size = %d " "ble_raw_used = %d", __func__, bta_dm_search_cb.ble_raw_size, bta_dm_search_cb.ble_raw_used); } LOG_INFO(LOG_TAG, "%s service_id_uuid_len=%d ", __func__, service_id.uuid.len); if (bta_dm_search_cb.state != BTA_DM_SEARCH_IDLE) { /* send result back to app now, one by one */ bdcpy(result.disc_ble_res.bd_addr, bta_dm_search_cb.peer_bdaddr); strlcpy((char*)result.disc_ble_res.bd_name, bta_dm_get_remname(), BD_NAME_LEN); memcpy(&result.disc_ble_res.service, &service_id.uuid, sizeof(tBT_UUID)); bta_dm_search_cb.p_search_cback(BTA_DM_DISC_BLE_RES_EVT, &result); } } /******************************************************************************* * * Function bta_dm_gatt_disc_complete * * Description This function process the GATT service search complete. * * Parameters: * ******************************************************************************/ static void bta_dm_gatt_disc_complete(uint16_t conn_id, tBTA_GATT_STATUS status) { APPL_TRACE_DEBUG("%s conn_id = %d", __func__, conn_id); if (bta_dm_search_cb.uuid_to_search > 0) bta_dm_search_cb.uuid_to_search--; if (status == BTA_GATT_OK && bta_dm_search_cb.uuid_to_search > 0) { btm_dm_start_disc_gatt_services(conn_id); } else { tBTA_DM_MSG* p_msg = (tBTA_DM_MSG*)osi_malloc(sizeof(tBTA_DM_MSG)); bta_dm_search_cb.uuid_to_search = 0; /* no more services to be discovered */ p_msg->hdr.event = BTA_DM_DISCOVERY_RESULT_EVT; p_msg->disc_result.result.disc_res.result = (status == BTA_GATT_OK) ? BTA_SUCCESS : BTA_FAILURE; APPL_TRACE_DEBUG("%s service found: 0x%08x", __func__, bta_dm_search_cb.services_found); p_msg->disc_result.result.disc_res.services = bta_dm_search_cb.services_found; p_msg->disc_result.result.disc_res.num_uuids = 0; p_msg->disc_result.result.disc_res.p_uuid_list = NULL; bdcpy(p_msg->disc_result.result.disc_res.bd_addr, bta_dm_search_cb.peer_bdaddr); strlcpy((char*)p_msg->disc_result.result.disc_res.bd_name, bta_dm_get_remname(), BD_NAME_LEN); p_msg->disc_result.result.disc_res.device_type |= BT_DEVICE_TYPE_BLE; if (bta_dm_search_cb.ble_raw_used > 0) { p_msg->disc_result.result.disc_res.p_raw_data = (uint8_t*)osi_malloc(bta_dm_search_cb.ble_raw_used); memcpy(p_msg->disc_result.result.disc_res.p_raw_data, bta_dm_search_cb.p_ble_rawdata, bta_dm_search_cb.ble_raw_used); p_msg->disc_result.result.disc_res.raw_data_size = bta_dm_search_cb.ble_raw_used; } else { p_msg->disc_result.result.disc_res.p_raw_data = NULL; bta_dm_search_cb.p_ble_rawdata = 0; } bta_sys_sendmsg(p_msg); if (conn_id != BTA_GATT_INVALID_CONN_ID) { /* start a GATT channel close delay timer */ bta_sys_start_timer(bta_dm_search_cb.gatt_close_timer, BTA_DM_GATT_CLOSE_DELAY_TOUT, BTA_DM_DISC_CLOSE_TOUT_EVT, 0); bdcpy(bta_dm_search_cb.pending_close_bda, bta_dm_search_cb.peer_bdaddr); } bta_dm_search_cb.gatt_disc_active = false; } } /******************************************************************************* * * Function bta_dm_close_gatt_conn * * Description This function close the GATT connection after delay *timeout. * * Parameters: * ******************************************************************************/ void bta_dm_close_gatt_conn(UNUSED_ATTR tBTA_DM_MSG* p_data) { if (bta_dm_search_cb.conn_id != BTA_GATT_INVALID_CONN_ID) BTA_GATTC_Close(bta_dm_search_cb.conn_id); memset(bta_dm_search_cb.pending_close_bda, 0, BD_ADDR_LEN); bta_dm_search_cb.conn_id = BTA_GATT_INVALID_CONN_ID; } /******************************************************************************* * * Function btm_dm_start_gatt_discovery * * Description This is GATT initiate the service search by open a GATT * connection first. * * Parameters: * ******************************************************************************/ void btm_dm_start_gatt_discovery(BD_ADDR bd_addr) { bta_dm_search_cb.gatt_disc_active = true; /* connection is already open */ if (bdcmp(bta_dm_search_cb.pending_close_bda, bd_addr) == 0 && bta_dm_search_cb.conn_id != BTA_GATT_INVALID_CONN_ID) { memset(bta_dm_search_cb.pending_close_bda, 0, BD_ADDR_LEN); alarm_cancel(bta_dm_search_cb.gatt_close_timer); btm_dm_start_disc_gatt_services(bta_dm_search_cb.conn_id); } else { if (BTM_IsAclConnectionUp(bd_addr, BT_TRANSPORT_LE)) { BTA_GATTC_Open(bta_dm_search_cb.client_if, bd_addr, true, BTA_GATT_TRANSPORT_LE, true); } else { BTA_GATTC_Open(bta_dm_search_cb.client_if, bd_addr, true, BTA_GATT_TRANSPORT_LE, false); } } } /******************************************************************************* * * Function bta_dm_cancel_gatt_discovery * * Description This is GATT cancel the GATT service search. * * Parameters: * ******************************************************************************/ static void bta_dm_cancel_gatt_discovery(BD_ADDR bd_addr) { if (bta_dm_search_cb.conn_id == BTA_GATT_INVALID_CONN_ID) { BTA_GATTC_CancelOpen(bta_dm_search_cb.client_if, bd_addr, true); } bta_dm_gatt_disc_complete(bta_dm_search_cb.conn_id, (tBTA_GATT_STATUS)BTA_GATT_ERROR); } /******************************************************************************* * * Function bta_dm_proc_open_evt * * Description process BTA_GATTC_OPEN_EVT in DM. * * Parameters: * ******************************************************************************/ void bta_dm_proc_open_evt(tBTA_GATTC_OPEN* p_data) { uint8_t* p1; uint8_t* p2; p1 = bta_dm_search_cb.peer_bdaddr; p2 = p_data->remote_bda; APPL_TRACE_DEBUG( "DM Search state= %d search_cb.peer_dbaddr: [%08x%04x] connected_bda= " "[%08x%04x] ", bta_dm_search_cb.state, ((p1[0]) << 24) + ((p1[1]) << 16) + ((p1[2]) << 8) + (p1[3]), ((p1[4]) << 8) + p1[5], ((p2[0]) << 24) + ((p2[1]) << 16) + ((p2[2]) << 8) + (p2[3]), ((p2[4]) << 8) + p2[5]); APPL_TRACE_DEBUG("BTA_GATTC_OPEN_EVT conn_id = %d client_if=%d status = %d", p_data->conn_id, p_data->client_if, p_data->status); bta_dm_search_cb.conn_id = p_data->conn_id; if (p_data->status == BTA_GATT_OK) { btm_dm_start_disc_gatt_services(p_data->conn_id); } else { bta_dm_gatt_disc_complete(BTA_GATT_INVALID_CONN_ID, p_data->status); } } /******************************************************************************* * * Function bta_dm_gattc_callback * * Description This is GATT client callback function used in DM. * * Parameters: * ******************************************************************************/ static void bta_dm_gattc_callback(tBTA_GATTC_EVT event, tBTA_GATTC* p_data) { APPL_TRACE_DEBUG("bta_dm_gattc_callback event = %d", event); switch (event) { case BTA_GATTC_OPEN_EVT: bta_dm_proc_open_evt(&p_data->open); break; case BTA_GATTC_SEARCH_RES_EVT: bta_dm_gatt_disc_result(p_data->srvc_res.service_uuid); break; case BTA_GATTC_SEARCH_CMPL_EVT: if (bta_dm_search_cb.state != BTA_DM_SEARCH_IDLE) bta_dm_gatt_disc_complete(p_data->search_cmpl.conn_id, p_data->search_cmpl.status); break; case BTA_GATTC_CLOSE_EVT: APPL_TRACE_DEBUG("BTA_GATTC_CLOSE_EVT reason = %d", p_data->close.reason); /* in case of disconnect before search is completed */ if ((bta_dm_search_cb.state != BTA_DM_SEARCH_IDLE) && (bta_dm_search_cb.state != BTA_DM_SEARCH_ACTIVE) && !memcmp(p_data->close.remote_bda, bta_dm_search_cb.peer_bdaddr, BD_ADDR_LEN)) { bta_dm_gatt_disc_complete((uint16_t)BTA_GATT_INVALID_CONN_ID, (tBTA_GATT_STATUS)BTA_GATT_ERROR); } break; default: break; } } #if (BLE_VND_INCLUDED == TRUE) /******************************************************************************* * * Function bta_dm_ctrl_features_rd_cmpl_cback * * Description callback to handle controller feature read complete * * Parameters: * ******************************************************************************/ static void bta_dm_ctrl_features_rd_cmpl_cback(tBTM_STATUS result) { APPL_TRACE_DEBUG("%s status = %d ", __func__, result); if (result == BTM_SUCCESS) { if (bta_dm_cb.p_sec_cback) bta_dm_cb.p_sec_cback(BTA_DM_LE_FEATURES_READ, NULL); } else { APPL_TRACE_ERROR("%s Ctrl BLE feature read failed: status :%d", __func__, result); } } #endif /* BLE_VND_INCLUDED */
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <builders/ie_const_layer.hpp> #include <builders/ie_input_layer.hpp> #include <builders/ie_network_builder.hpp> #include <details/caseless.hpp> #include <limits> #include <map> #include <memory> #include <shape_infer/ie_reshaper.hpp> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include "blob_factory.hpp" #include "graph_tools.hpp" #include "ie_cnn_layer_builder.h" #include "ie_profiling.hpp" using namespace InferenceEngine; /****************************************************************************** Network builder ******************************************************************************/ Builder::Network::Network(const std::string& name): Builder::Network(Context(), name) {} Builder::Network::Network(const INetwork& network): Builder::Network(Context(), network) {} Builder::Network::Network(const ICNNNetwork& network): Builder::Network(Context(), network) {} Builder::Network::Network(const Context& ieContext, const std::string& name) { parameters["name"] = name; parameters["context"] = ieContext; parameters["version"] = 3; parameters["layers"] = std::vector<Layer::Ptr>(); parameters["connections"] = std::vector<Connection>(); } Builder::Network::Network(const Context& ieContext, const INetwork& network): Network(ieContext, network.getName()) { for (const auto& layer : network) { parameters["layers"].as<std::vector<Layer::Ptr>>().push_back(std::make_shared<Layer>(layer)); const auto layerConnections = network.getLayerConnections(layer->getId()); for (const auto& connection : layerConnections) { bool found = false; for (const auto& con : parameters["connections"].as<std::vector<Connection>>()) { if (con == connection) { found = true; break; } } if (!found) { parameters["connections"].as<std::vector<Connection>>().push_back(connection); } } } } Builder::Network::Network(const Context& ieContext, const ICNNNetwork& network): Network(ieContext, network.getName()) { parameters["version"] = 0; auto allInputs = CNNNetGetAllInputLayers(network); InputsDataMap inputs; network.getInputsInfo(inputs); if (inputs.empty() && allInputs.empty()) THROW_IE_EXCEPTION << "Cannot create graph! No inputs for the topology " << network.getName(); std::unordered_map<std::string, idx_t> name2id; std::unordered_set<Data*> dataPtrs; std::vector<CNNLayerPtr> queueLayers; auto createGenericFromCNNLayer = [&](const CNNLayerPtr& cnnLayer) { for (const auto& data : cnnLayer->insData) { auto lockedData = data.lock(); if (!lockedData) continue; if (dataPtrs.find(lockedData.get()) == dataPtrs.end()) { dataPtrs.insert(lockedData.get()); } } for (const auto& data : cnnLayer->outData) { if (dataPtrs.find(data.get()) == dataPtrs.end()) { dataPtrs.insert(data.get()); } } std::map<std::string, Blob::Ptr> blobs = cnnLayer->blobs; size_t inputsCount(0); for (const auto& data : cnnLayer->insData) { auto lockedData = data.lock(); if (!lockedData) continue; inputsCount++; } const auto layer = builderFromCNNLayer(cnnLayer); idx_t layerId = addLayer(layer); if (blobs.find("weights") != blobs.end()) { idx_t constLayerId = addLayer(ConstLayer("weights").setData(blobs["weights"])); connect({constLayerId}, {layerId, inputsCount++}); } if (blobs.find("biases") != blobs.end()) { if (blobs.find("weights") == blobs.end()) ++inputsCount; idx_t constLayerId = addLayer(ConstLayer("biases").setData(blobs["biases"])); connect({constLayerId}, {layerId, inputsCount++}); } for (const auto& it : blobs) { if (it.first == "weights" || it.first == "biases") continue; idx_t constLayerId = addLayer(ConstLayer(it.first).setData(it.second)); connect({constLayerId}, {layerId, inputsCount++}); } name2id[layer.getName()] = layerId; return layerId; }; auto addPreProcessFor = [&](const InputInfo::Ptr& inputInfo) { auto inputLayer = getLayer(name2id[inputInfo->name()]); if (inputLayer->getType().empty() && inputLayer->getName().empty()) return; inputLayer->getParameters()["preProcess"] = inputInfo->getPreProcess(); }; for (auto input : inputs) { auto inputLayer = input.second->getInputData()->getCreatorLayer().lock(); if (dataPtrs.find(input.second->getInputData().get()) == dataPtrs.end()) { dataPtrs.insert(input.second->getInputData().get()); } if (!inputLayer) { // For v1 parser inputLayer.reset(new CNNLayer( {input.second->getInputData()->getName(), "Input", input.second->getInputData()->getPrecision()})); inputLayer->outData.push_back(input.second->getInputData()); } const auto layer = InputLayer(inputLayer->name).setPort(Port(inputLayer->outData[0]->getTensorDesc().getDims())); name2id[layer.getName()] = addLayer(layer); for (const auto& nlayer : input.second->getInputData()->getInputTo()) { queueLayers.push_back(nlayer.second); } } for (auto input : allInputs) { auto isRealInput = std::find_if(std::begin(inputs), std::end(inputs), [&](InputsDataMap::value_type& inputInfo) { return inputInfo.second->getInputData()->getName() == input->name; }); if (isRealInput != std::end(inputs)) { continue; } details::CaselessEq<std::string> eq; CNNLayerPtr cnnLayer = input; if (eq(input->type, "Memory")) { auto memoryId = input->GetParamAsString("id"); cnnLayer.reset(new CNNLayer({input->name + "/id=" + memoryId, "MemoryInput", input->precision})); cnnLayer->params = input->params; cnnLayer->outData = input->outData; } createGenericFromCNNLayer(cnnLayer); size_t count_out = 0; for (auto&& outData : input->outData) { for (auto&& nlayer : outData->getInputTo()) { queueLayers.push_back(nlayer.second); } count_out++; } } while (!queueLayers.empty()) { auto cnnLayerPtr = *queueLayers.begin(); if (name2id.find(cnnLayerPtr->name) == name2id.end()) { createGenericFromCNNLayer(cnnLayerPtr); for (auto&& outData : cnnLayerPtr->outData) { for (auto&& nlayer : outData->getInputTo()) { queueLayers.push_back(nlayer.second); } } } queueLayers.erase(queueLayers.begin()); } std::map<std::string, DataPtr> output; network.getOutputsInfo(output); for (auto it = output.begin(); it != output.end(); it++) { CNNLayerPtr creator = (*it).second->getCreatorLayer().lock(); if (name2id.find(creator->name) == name2id.end()) THROW_IE_EXCEPTION << "Cannot find output layer " << creator->name; auto lastLayer = getLayer(name2id[creator->name]); if (lastLayer->getName() == "" && lastLayer->getType().empty()) THROW_IE_EXCEPTION << "Cannot find output layer " << creator->name; std::string name = "out_" + lastLayer->getName(); CNNLayerPtr cnnOutLayer(new CNNLayer({name, "Output", creator->outData[0]->getPrecision()})); cnnOutLayer->insData.push_back((*it).second); idx_t outLayerId = createGenericFromCNNLayer(cnnOutLayer); idx_t inIdx(0); for (size_t i = 0; i < creator->outData.size(); i++) { if (creator->outData[i] == (*it).second) { inIdx = i; break; } } parameters["connections"].as<std::vector<Connection>>().push_back( Connection({lastLayer->getId(), inIdx}, {outLayerId})); } for (const auto dataPtr : dataPtrs) { auto cnnInputLayer = dataPtr->getCreatorLayer().lock(); idx_t inIdx(0); if (!cnnInputLayer) { // For v1 parser cnnInputLayer.reset(new CNNLayer({dataPtr->getName(), "Input", dataPtr->getPrecision()})); } else { for (size_t i = 0; i < cnnInputLayer->outData.size(); i++) { if (cnnInputLayer->outData[i].get() == dataPtr) { inIdx = i; break; } } } for (const auto& it : dataPtr->getInputTo()) { if (name2id.find(cnnInputLayer->name) == name2id.end() || name2id.find(it.second->name) == name2id.end()) THROW_IE_EXCEPTION << "Cannot create connections between nodes: " << cnnInputLayer->name << " -> " << it.second->name; idx_t outIdx(0); for (size_t i = 0; i < it.second->insData.size(); i++) { const auto lockedData = it.second->insData[i].lock(); if (lockedData && lockedData.get() == dataPtr) { outIdx = i; break; } } parameters["connections"].as<std::vector<Connection>>().push_back( Connection({name2id[cnnInputLayer->name], inIdx}, {name2id[it.second->name], outIdx})); } } for (const auto& input : inputs) { addPreProcessFor(input.second); } } const std::vector<Builder::Layer::Ptr>& Builder::Network::getLayers() const { return parameters.at("layers").as<std::vector<Layer::Ptr>>(); } std::vector<Builder::Layer::Ptr>& Builder::Network::getLayers() { return parameters["layers"].as<std::vector<Layer::Ptr>>(); } idx_t Builder::Network::addLayer(const std::vector<PortInfo>& inputs, const Layer& layer) { IE_PROFILING_AUTO_SCOPE(Builder::Network::addLayer) auto layer_id = addLayer(layer); for (size_t i = 0; i < inputs.size(); i++) { connect({inputs[i].layerId(), inputs[i].portId()}, {layer_id, i}); } return layer_id; } idx_t Builder::Network::addLayer(const Layer& layer) { auto getAvailableId = [&](idx_t defaultId) { if (defaultId == (std::numeric_limits<idx_t>::max)()) defaultId = 0; auto it = parameters["layers"].as<std::vector<Layer::Ptr>>().begin(); while (it != parameters["layers"].as<std::vector<Layer::Ptr>>().end()) { for (it = parameters["layers"].as<std::vector<Layer::Ptr>>().begin(); it != parameters["layers"].as<std::vector<Layer::Ptr>>().end(); it++) { if ((*it)->getId() == defaultId) { defaultId++; break; } } } return defaultId; }; auto generateAvailableName = [&](const std::string& name, idx_t id) { const std::string idName = "id" + std::to_string(id); std::string generatedName(name); if (generatedName.empty()) generatedName = idName; bool nameIsUnique(false); while (!nameIsUnique) { nameIsUnique = true; for (const auto& layer : parameters["layers"].as<std::vector<Layer::Ptr>>()) { if (generatedName == layer->getName()) { nameIsUnique = false; generatedName += "_" + idName; } } } return generatedName; }; idx_t generatedId = getAvailableId(layer.getId()); const auto name = generateAvailableName(layer.getName(), generatedId); parameters["layers"].as<std::vector<Layer::Ptr>>().emplace_back(std::make_shared<Layer>(generatedId, layer)); parameters["layers"] .as<std::vector<Layer::Ptr>>()[parameters["layers"].as<std::vector<Layer::Ptr>>().size() - 1] ->setName(name); return generatedId; } void Builder::Network::connect(const PortInfo& input, const PortInfo& output) { const auto mergePortData = [&]() -> bool { const auto blobEqualOrEmpty = [](const Blob::Ptr& ref, const Blob::Ptr& test) -> bool { return (ref->size() == test->size() || test->size() == 0) && (!memcmp(ref->cbuffer(), test->cbuffer(), test->byteSize())) && (ref->getTensorDesc().getPrecision() == test->getTensorDesc().getPrecision() || test->getTensorDesc().getPrecision() == Precision::UNSPECIFIED) && (ref->getTensorDesc().getLayout() == test->getTensorDesc().getLayout() || test->getTensorDesc().getLayout() == Layout::ANY) && (ref->getTensorDesc().getDims() == test->getTensorDesc().getDims() || test->getTensorDesc().getDims().empty()) && (ref->cbuffer().as<char*>() == test->cbuffer().as<char*>() || test->cbuffer() == nullptr); }; const auto srcPortData = getLayer(input.layerId())->getOutputPorts()[input.portId()].getData(); const auto dstPortData = getLayer(output.layerId())->getInputPorts()[output.portId()].getData(); if (srcPortData == dstPortData) return true; if (srcPortData->getParameters() != dstPortData->getParameters() && !srcPortData->getParameters().empty() && !dstPortData->getParameters().empty()) return false; size_t srcDataCount(0), dstDataCount(0); if (!srcPortData->getParameters().empty()) srcDataCount++; if (!dstPortData->getParameters().empty()) dstDataCount++; const auto srcBlb = srcPortData->getData(); const auto dstBlb = dstPortData->getData(); if (srcBlb == dstBlb || (srcBlb->size() == dstBlb->size() && srcBlb->getTensorDesc() == dstBlb->getTensorDesc() && ((srcBlb->cbuffer().as<char*>() == dstBlb->cbuffer().as<char*>()) || (srcBlb->cbuffer() != nullptr && dstBlb->cbuffer() != nullptr && !memcmp(srcBlb->cbuffer(), dstBlb->cbuffer(), dstBlb->byteSize()))))) { srcDataCount++; dstDataCount++; } else if (blobEqualOrEmpty(srcBlb, dstBlb)) { srcDataCount++; } else if (blobEqualOrEmpty(dstBlb, srcBlb)) { dstDataCount++; } else { return false; } if (dstDataCount > srcDataCount) { // Change source and all src destination data for (const auto& connection : getLayerConnections(input.layerId())) { if (connection.from() != input) continue; getLayer(connection.to().layerId())->getInputPorts()[connection.to().portId()].setData(dstPortData); } getLayer(input.layerId())->getOutputPorts()[input.portId()].setData(dstPortData); } else { // Change destination data getLayer(output.layerId())->getInputPorts()[output.portId()].setData(srcPortData); } return true; }; if (!mergePortData()) THROW_IE_EXCEPTION << "Cannot connect two ports with different data!"; parameters["connections"].as<std::vector<Connection>>().emplace_back(input, output); } void Builder::Network::removeLayer(idx_t layerId) { auto it = parameters["layers"].as<std::vector<Layer::Ptr>>().begin(); for (; it != parameters["layers"].as<std::vector<Layer::Ptr>>().end(); it++) { if ((*it)->getId() == layerId) { break; } } if (it != parameters["layers"].as<std::vector<Layer::Ptr>>().end()) parameters["layers"].as<std::vector<Layer::Ptr>>().erase(it); } void Builder::Network::disconnect(const Connection& connection) { auto it = parameters["connections"].as<std::vector<Connection>>().begin(); for (; it != parameters["connections"].as<std::vector<Connection>>().end(); it++) { if (connection == *it) break; } if (it != parameters["connections"].as<std::vector<Connection>>().end()) parameters["connections"].as<std::vector<Connection>>().erase(it); try { auto layer = getLayer(connection.to().layerId()); layer->getInputPorts()[connection.to().portId()].setData(std::make_shared<PortData>()); } catch (InferenceEngine::details::InferenceEngineException& ex) { } } const INetwork::CPtr Builder::Network::build() { validate(); InferenceEngine::Builder::Network::Ptr network = std::make_shared<InferenceEngine::Builder::Network>(static_cast<const INetwork&>(*this)); return network; } void Builder::Network::validate() { // Check that all ports are connected for (const auto& layer : getLayers()) { std::vector<bool> existInCon(layer->getInputPorts().size()); for (size_t i = 0; i < layer->getInputPorts().size(); i++) { if (layer->getInputPorts()[i].getParameters().find("type") != layer->getInputPorts()[i].getParameters().end()) existInCon[i] = true; } std::vector<bool> existOutCon(layer->getOutputPorts().size()); const auto layerConnections = getLayerConnections(layer->getId()); for (const auto& connection : layerConnections) { if (connection.from().layerId() == layer->getId()) { existOutCon[connection.from().portId()] = true; getLayer(connection.to().layerId()); } if (connection.to().layerId() == layer->getId()) { existInCon[connection.to().portId()] = true; getLayer(connection.from().layerId()); } } bool allPortsConnected = true; for (const auto& cons : {existInCon, existOutCon}) { for (const auto& existCon : cons) { allPortsConnected = allPortsConnected && existCon; } } if (!allPortsConnected) THROW_IE_EXCEPTION << "Not all ports of layer " << layer->getName() << " were connected!"; } // Check all layers for (const auto& connection : getConnections()) { if (!getLayer(connection.to().layerId())) THROW_IE_EXCEPTION << "Cannot find layer with id: " << connection.to().layerId(); if (!getLayer(connection.from().layerId())) THROW_IE_EXCEPTION << "Cannot find layer with id: " << connection.from().layerId(); } std::map<std::string, SizeVector> inputShapes; for (const auto& input : getInputs()) inputShapes[input->getName()] = input->getOutputPorts()[0].shape(); ShapeInfer::Reshaper reshaper(this); ResponseDesc resp; StatusCode sts = reshaper.run(inputShapes, &resp); // Not all implementations may be registered if all shapes were read from IR. if (sts == NOT_FOUND) { bool allShapesLooksGood = true; for (const auto& connection : getConnections()) { if (getLayer(connection.from().layerId())->getOutputPorts()[connection.from().portId()].shape() != getLayer(connection.to().layerId())->getInputPorts()[connection.to().portId()].shape() || getLayer(connection.to().layerId())->getInputPorts()[connection.to().portId()].shape().empty()) { allShapesLooksGood = false; break; } } if (allShapesLooksGood) sts = OK; } if (sts != OK) THROW_IE_EXCEPTION << resp.msg; // Check all parameters for (const auto& layer : getLayers()) { try { layer->build(); } catch (InferenceEngine::details::InferenceEngineException& ex) { THROW_IE_EXCEPTION << "Cannot build layer " << layer->getName() << ": " << ex.what(); } catch (std::bad_cast& ex) { THROW_IE_EXCEPTION << "Cannot build layer " << layer->getName() << ": " << ex.what(); } } } Builder::Network::operator const INetwork::CPtr() { return build(); } const ILayer::CPtr Builder::Network::getLayer(idx_t layerId) const noexcept { try { for (auto& layer : getLayers()) { if (layer->getId() == layerId) return layer->build(); } } catch (...) { } return nullptr; } Builder::Layer::Ptr Builder::Network::getLayer(idx_t layerId) { for (auto& layer : getLayers()) { if (layer->getId() == layerId) return layer; } THROW_IE_EXCEPTION << "Cannot find layer with id: " << layerId; } const std::string& Builder::Network::getName() const noexcept { static std::string errName; try { return parameters.at("name"); } catch (...) { return errName; } } const Context& Builder::Network::getContext() const noexcept { static Context errCtx; try { return parameters.at("context"); } catch (...) { return errCtx; } } Context& Builder::Network::getContext() noexcept { static Context errCtx; try { return parameters.at("context"); } catch (...) { return errCtx; } } Builder::Network::const_iterator Builder::Network::begin() const noexcept { try { return Network::const_iterator(this); } catch (...) { return Network::const_iterator(this, true); } } Builder::Network::const_iterator Builder::Network::end() const noexcept { return Network::const_iterator(this, true); } size_t Builder::Network::size() const noexcept { return static_cast<size_t>(std::distance(std::begin(*this), std::end(*this))); } Builder::Network::iterator Builder::Network::begin() { return Network::iterator(this); } Builder::Network::iterator Builder::Network::end() { return Network::iterator(this, true); } const std::vector<ILayer::CPtr> Builder::Network::getInputs() const noexcept { std::vector<ILayer::CPtr> inputs; try { for (const auto& layer : parameters.at("layers").as<std::vector<Layer::Ptr>>()) { bool isInputLayer = true; for (const auto& connection : getLayerConnections(layer->getId())) { if (connection.to().layerId() == layer->getId()) { isInputLayer = false; break; } } if (isInputLayer) { inputs.push_back(layer->build()); } } } catch (...) { } return inputs; } std::vector<Builder::Layer::Ptr> Builder::Network::getInputs() { std::vector<Builder::Layer::Ptr> inputs; for (auto& layer : parameters.at("layers").as<std::vector<Layer::Ptr>>()) { bool isInputLayer = true; for (const auto& connection : getLayerConnections(layer->getId())) { if (connection.to().layerId() == layer->getId()) { isInputLayer = false; break; } } if (isInputLayer) { inputs.push_back(layer); } } return inputs; } const std::vector<ILayer::CPtr> Builder::Network::getOutputs() const noexcept { std::vector<ILayer::CPtr> outputs; try { for (const auto& layer : parameters.at("layers").as<std::vector<Layer::Ptr>>()) { bool isOutputLayer = true; for (const auto& connection : getLayerConnections(layer->getId())) { if (connection.from().layerId() == layer->getId()) { isOutputLayer = false; break; } } if (isOutputLayer) { outputs.push_back(layer->build()); } } } catch (...) { } return outputs; } std::vector<Builder::Layer::Ptr> Builder::Network::getOutputs() { std::vector<Builder::Layer::Ptr> outputs; for (auto& layer : parameters.at("layers").as<std::vector<Layer::Ptr>>()) { bool isOutputLayer = true; for (const auto& connection : getLayerConnections(layer->getId())) { if (connection.from().layerId() == layer->getId()) { isOutputLayer = false; break; } } if (isOutputLayer) { outputs.push_back(layer); } } return outputs; } const std::vector<Connection>& Builder::Network::getConnections() const { return parameters.at("connections").as<std::vector<Connection>>(); } const std::vector<Connection> Builder::Network::getLayerConnections(idx_t layerId) const noexcept { std::vector<Connection> layerConnections; try { for (const auto connection : parameters.at("connections").as<std::vector<Connection>>()) { if (connection.from().layerId() == layerId || connection.to().layerId() == layerId) layerConnections.push_back(connection); } } catch (...) { } return layerConnections; }
// // Created by sebas on 7/10/19. // #include "GameLoop.h" #include "../servicios/Locator.h" #include "../eventos/ActualizarYSerializarMapa.h" #include <unistd.h> void GameLoop::loop() { const size_t MS_PER_FRAME = 1.0 / Locator::configuracion()->getIntValue("/fps") * 1000 * 1000; // Microsegundos. while (Locator::usuarios()->hayJugadoresConectados()) { Locator::eventos()->push(new ActualizarYSerializarMapa(Locator::mapa())); usleep(MS_PER_FRAME); } Locator::logger()->log(INFO, "Todos los usuarios se desconectaron voluntariamente."); }
#include <bits/stdc++.h> const int DIV = 1000000007; using namespace std; using ll = long long; using ar = array<array<ll, 8>, 8>; void mult (ar &l, ar &m, ar &n) { for (int i = 0; i < 8; ++i) { for (int j = 0; j < 8; ++j) { for (int k = 0; k < 8; ++k) { l[i][j] += m[i][k] * n[k][j]; } } } } int main() { ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr); int d; cin >> d; /* 1. 정보과학관 2. 전산관 3. 미래관 4. 신양관 5. 진리관 6. 환경직기념관 7. 학생회관 8. 형남공학관 */ ar arr = {{ {0, 1, 1, 0, 0, 0, 0, 0}, {1, 0, 1, 1, 0, 0, 0, 0}, {1, 1, 0, 1, 0, 1, 0, 0}, {0, 1, 1, 0, 1, 1, 0, 0}, {0, 0, 0, 1, 0, 1, 1, 0}, {0, 0, 1, 1, 1, 0, 0, 1}, {0, 0, 0, 0, 1, 0, 0, 1}, {0, 0, 0, 0, 0, 1, 1, 0} }}, arr2 = arr; vector<ll> v; while(d > 1) { v.emplace_back(d); d = d & 1 ? --d : d / 2; } for (int t = v.size() - 1; t >= 0; --t) { ar res = {{0}}; v[t] & 1 ? mult(res, arr, arr2) : mult(res, arr2, arr2); for (int i = 0; i < 64; ++i) { arr2[i/8][i%8] = res[i/8][i%8] % DIV; } } cout << arr2[0][0]; }
#include "IOSGLContext.h" std::unique_ptr<GLContext> GLContext::_glcontext = nullptr; void GLContext::initGLContext() { if (_glcontext == nullptr) { _glcontext.reset(new IOSGLContext()); } } GLContext* GLContext::getGLContext() { if (_glcontext == nullptr) { initGLContext(); } return _glcontext.get(); } void GLContext::deleteGLContext() { _glcontext.reset(nullptr); }
// Copyright (c) 2018 Microsoft Corporation // Licensed under the MIT license. // Author: Paul Koch <code@koch.ninja> #include "precompiled_header_cpp.hpp" #include <cmath> #include <immintrin.h> // SIMD. Do not include in precompiled_header_cpp.hpp! #include "ebm_native.h" #include "logging.h" #include "common_c.h" #include "bridge_c.h" #include "zones.h" #include "common_cpp.hpp" #include "bridge_cpp.hpp" #include "Registration.hpp" #include "Loss.hpp" namespace DEFINED_ZONE_NAME { #ifndef DEFINED_ZONE_NAME #error DEFINED_ZONE_NAME must be defined #endif // DEFINED_ZONE_NAME struct Sse_32_Operators final { constexpr static size_t countPackedItems = 4; // the number of Unpacked items in a Packed structure typedef float Unpacked; typedef __m128 Packed; private: Packed m_data; INLINE_ALWAYS Sse_32_Operators(const Packed & data) noexcept : m_data(data) { } public: ATTRIBUTE_WARNING_DISABLE_UNINITIALIZED_MEMBER INLINE_ALWAYS Sse_32_Operators() noexcept { } INLINE_ALWAYS Sse_32_Operators(const float data) noexcept : m_data(_mm_set1_ps(static_cast<Unpacked>(data))) { } INLINE_ALWAYS Sse_32_Operators(const double data) noexcept : m_data(_mm_set1_ps(static_cast<Unpacked>(data))) { } INLINE_ALWAYS Sse_32_Operators(const int data) noexcept : m_data(_mm_set1_ps(static_cast<Unpacked>(data))) { } INLINE_ALWAYS Sse_32_Operators operator+ (const Sse_32_Operators & other) const noexcept { return Sse_32_Operators(_mm_add_ps(m_data, other.m_data)); } INLINE_ALWAYS Sse_32_Operators operator- (const Sse_32_Operators & other) const noexcept { return Sse_32_Operators(_mm_sub_ps(m_data, other.m_data)); } INLINE_ALWAYS Sse_32_Operators operator* (const Sse_32_Operators & other) const noexcept { return Sse_32_Operators(_mm_mul_ps(m_data, other.m_data)); } INLINE_ALWAYS Sse_32_Operators operator/ (const Sse_32_Operators & other) const noexcept { return Sse_32_Operators(_mm_div_ps(m_data, other.m_data)); } INLINE_ALWAYS bool IsAnyEqual(const Sse_32_Operators & other) const noexcept { return !!_mm_movemask_ps(_mm_cmpeq_ps(m_data, other.m_data)); } INLINE_ALWAYS bool IsAnyInf() const noexcept { return !!_mm_movemask_ps(_mm_cmpeq_ps(_mm_andnot_ps(_mm_set1_ps(Unpacked { -0.0 }), m_data), _mm_set1_ps(std::numeric_limits<Unpacked>::infinity()))); } INLINE_ALWAYS bool IsAnyNaN() const noexcept { // use the fact that a != a always yields false, except when both are NaN in IEEE 754 where it's true return !!_mm_movemask_ps(_mm_cmpneq_ps(m_data, m_data)); } INLINE_ALWAYS Sse_32_Operators Sqrt() const noexcept { // TODO: consider making a fast approximation of this return Sse_32_Operators(_mm_sqrt_ss(m_data)); } template<template <typename, typename, ptrdiff_t, ptrdiff_t, bool> class TExecute, typename TLoss, typename TFloat, ptrdiff_t cCompilerScores, ptrdiff_t cCompilerPack, bool bHessian> INLINE_RELEASE_TEMPLATED static ErrorEbmType ApplyTraining(const Loss * const pLoss, ApplyTrainingData * const pData) { // this allows us to switch execution onto GPU, FPGA, or other local computation ExecuteApplyTraining<TExecute, TLoss, TFloat, cCompilerScores, cCompilerPack, bHessian>( pLoss, pData->m_cRuntimeScores, pData->m_cRuntimePack ); return Error_None; } template<template <typename, typename, ptrdiff_t, ptrdiff_t, bool> class TExecute, typename TLoss, typename TFloat, ptrdiff_t cCompilerScores, ptrdiff_t cCompilerPack, bool bHessian> INLINE_RELEASE_TEMPLATED static ErrorEbmType ApplyValidation(const Loss * const pLoss, ApplyValidationData * const pData) { // this allows us to switch execution onto GPU, FPGA, or other local computation ExecuteApplyValidation<TExecute, TLoss, TFloat, cCompilerScores, cCompilerPack, bHessian>( pLoss, pData->m_cRuntimeScores, pData->m_cRuntimePack, &pData->m_metricOut ); return Error_None; } }; static_assert(std::is_standard_layout<Sse_32_Operators>::value, "This allows offsetof, memcpy, memset, inter-language, GPU and cross-machine use where needed"); #if !(defined(__GNUC__) && __GNUC__ < 5) static_assert(std::is_trivially_copyable<Sse_32_Operators>::value, "This allows offsetof, memcpy, memset, inter-language, GPU and cross-machine use where needed"); #endif // !(defined(__GNUC__) && __GNUC__ < 5) // FIRST, define the RegisterLoss function that we'll be calling from our registrations. This is a static // function, so we can have duplicate named functions in other files and they'll refer to different functions template<template <typename> class TRegistrable, typename... Args> static INLINE_ALWAYS std::shared_ptr<const Registration> RegisterLoss(const char * const sRegistrationName, const Args...args) { return Register<TRegistrable, Sse_32_Operators>(sRegistrationName, args...); } // now include all our special loss registrations which will use the RegisterLoss function we defined above! #include "loss_registrations.hpp" INTERNAL_IMPORT_EXPORT_BODY ErrorEbmType CreateLoss_Sse_32( const Config * const pConfig, const char * const sLoss, const char * const sLossEnd, LossWrapper * const pLossWrapperOut ) { return Loss::CreateLoss(&RegisterLosses, pConfig, sLoss, sLossEnd, pLossWrapperOut); } INTERNAL_IMPORT_EXPORT_BODY ErrorEbmType CreateMetric_Sse_32( const Config * const pConfig, const char * const sMetric, const char * const sMetricEnd // MetricWrapper * const pMetricWrapperOut, ) { UNUSED(pConfig); UNUSED(sMetric); UNUSED(sMetricEnd); return Error_UnexpectedInternal; } } // DEFINED_ZONE_NAME
// Mark Stankus 1999 (c) // Lean.hpp #ifndef INCLUDED_LEAN_H #define INCLUDED_LEAN_H #include "AttainableMap.hpp" #include "AlwaysTrue.hpp" void Lean(AttainableMap<AlwaysTrue> &); #endif
/*++ Copyright (c) 2015 Microsoft Corporation --*/ #include "qe/qe_cmd.h" #include "qe/qe.h" #include "cmd_context/cmd_context.h" #include "cmd_context/parametric_cmd.h" class qe_cmd : public parametric_cmd { expr * m_target; public: qe_cmd(char const* name = "elim-quantifiers"):parametric_cmd(name) {} char const * get_usage() const override { return "<term> (<keyword> <value>)*"; } char const * get_main_descr() const override { return "apply quantifier elimination to the supplied expression"; } void init_pdescrs(cmd_context & ctx, param_descrs & p) override { insert_timeout(p); p.insert("print", CPK_BOOL, "(default: true) print the simplified term."); p.insert("print_statistics", CPK_BOOL, "(default: false) print statistics."); } ~qe_cmd() override { } void prepare(cmd_context & ctx) override { parametric_cmd::prepare(ctx); m_target = nullptr; } cmd_arg_kind next_arg_kind(cmd_context & ctx) const override { if (m_target == nullptr) return CPK_EXPR; return parametric_cmd::next_arg_kind(ctx); } void set_next_arg(cmd_context & ctx, expr * arg) override { m_target = arg; } void execute(cmd_context & ctx) override { proof_ref pr(ctx.m()); qe::simplify_rewriter_star qe(ctx.m()); expr_ref result(ctx.m()); qe(m_target, result, pr); if (m_params.get_bool("print", true)) { ctx.display(ctx.regular_stream(), result); ctx.regular_stream() << std::endl; } if (m_params.get_bool("print_statistics", false)) { statistics st; qe.collect_statistics(st); st.display(ctx.regular_stream()); } } }; void install_qe_cmd(cmd_context & ctx, char const * cmd_name) { ctx.insert(alloc(qe_cmd, cmd_name)); }
#include <btcb/lib/utility.hpp> #include <pthread.h> void btcb::thread_role::set_name (std::string thread_name) { pthread_setname_np (pthread_self (), thread_name.c_str ()); }
/* Copyright (c) 2010-2016, Mathieu Labbe - IntRoLab - Universite de Sherbrooke 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 Universite de Sherbrooke nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "rtabmap/core/Rtabmap.h" #include "rtabmap/core/Version.h" #include "rtabmap/core/Features2d.h" #include "rtabmap/core/Optimizer.h" #include "rtabmap/core/Graph.h" #include "rtabmap/core/Signature.h" #include "rtabmap/core/EpipolarGeometry.h" #include "rtabmap/core/Memory.h" #include "rtabmap/core/VWDictionary.h" #include "rtabmap/core/BayesFilter.h" #include "rtabmap/core/Compression.h" #include "rtabmap/core/RegistrationInfo.h" #include <rtabmap/utilite/ULogger.h> #include <rtabmap/utilite/UFile.h> #include <rtabmap/utilite/UTimer.h> #include <rtabmap/utilite/UConversion.h> #include <rtabmap/utilite/UMath.h> #include <rtabmap/utilite/UProcessInfo.h> #include <pcl/search/kdtree.h> #include <pcl/filters/crop_box.h> #include <pcl/io/pcd_io.h> #include <pcl/common/common.h> #include <pcl/TextureMesh.h> #include <stdlib.h> #include <set> #define LOG_F "LogF.txt" #define LOG_I "LogI.txt" #define GRAPH_FILE_NAME "Graph.dot" // // // // ======================================================= // MAIN LOOP, see method "void Rtabmap::process();" below. // ======================================================= // // // namespace rtabmap { Rtabmap::Rtabmap() : _publishStats(Parameters::defaultRtabmapPublishStats()), _publishLastSignatureData(Parameters::defaultRtabmapPublishLastSignature()), _publishPdf(Parameters::defaultRtabmapPublishPdf()), _publishLikelihood(Parameters::defaultRtabmapPublishLikelihood()), _publishRAMUsage(Parameters::defaultRtabmapPublishRAMUsage()), _computeRMSE(Parameters::defaultRtabmapComputeRMSE()), _saveWMState(Parameters::defaultRtabmapSaveWMState()), _maxTimeAllowed(Parameters::defaultRtabmapTimeThr()), // 700 ms _maxMemoryAllowed(Parameters::defaultRtabmapMemoryThr()), // 0=inf _loopThr(Parameters::defaultRtabmapLoopThr()), _loopRatio(Parameters::defaultRtabmapLoopRatio()), _maxLoopClosureDistance(Parameters::defaultRGBDMaxLoopClosureDistance()), _verifyLoopClosureHypothesis(Parameters::defaultVhEpEnabled()), _maxRetrieved(Parameters::defaultRtabmapMaxRetrieved()), _maxLocalRetrieved(Parameters::defaultRGBDMaxLocalRetrieved()), _rawDataKept(Parameters::defaultMemImageKept()), _statisticLogsBufferedInRAM(Parameters::defaultRtabmapStatisticLogsBufferedInRAM()), _statisticLogged(Parameters::defaultRtabmapStatisticLogged()), _statisticLoggedHeaders(Parameters::defaultRtabmapStatisticLoggedHeaders()), _rgbdSlamMode(Parameters::defaultRGBDEnabled()), _rgbdLinearUpdate(Parameters::defaultRGBDLinearUpdate()), _rgbdAngularUpdate(Parameters::defaultRGBDAngularUpdate()), _rgbdLinearSpeedUpdate(Parameters::defaultRGBDLinearSpeedUpdate()), _rgbdAngularSpeedUpdate(Parameters::defaultRGBDAngularSpeedUpdate()), _newMapOdomChangeDistance(Parameters::defaultRGBDNewMapOdomChangeDistance()), _neighborLinkRefining(Parameters::defaultRGBDNeighborLinkRefining()), _proximityByTime(Parameters::defaultRGBDProximityByTime()), _proximityBySpace(Parameters::defaultRGBDProximityBySpace()), _scanMatchingIdsSavedInLinks(Parameters::defaultRGBDScanMatchingIdsSavedInLinks()), _localRadius(Parameters::defaultRGBDLocalRadius()), _localImmunizationRatio(Parameters::defaultRGBDLocalImmunizationRatio()), _proximityMaxGraphDepth(Parameters::defaultRGBDProximityMaxGraphDepth()), _proximityMaxPaths(Parameters::defaultRGBDProximityMaxPaths()), _proximityMaxNeighbors(Parameters::defaultRGBDProximityPathMaxNeighbors()), _proximityFilteringRadius(Parameters::defaultRGBDProximityPathFilteringRadius()), _proximityRawPosesUsed(Parameters::defaultRGBDProximityPathRawPosesUsed()), _proximityAngle(Parameters::defaultRGBDProximityAngle()*M_PI/180.0f), _databasePath(""), _optimizeFromGraphEnd(Parameters::defaultRGBDOptimizeFromGraphEnd()), _optimizationMaxError(Parameters::defaultRGBDOptimizeMaxError()), _startNewMapOnLoopClosure(Parameters::defaultRtabmapStartNewMapOnLoopClosure()), _startNewMapOnGoodSignature(Parameters::defaultRtabmapStartNewMapOnGoodSignature()), _goalReachedRadius(Parameters::defaultRGBDGoalReachedRadius()), _goalsSavedInUserData(Parameters::defaultRGBDGoalsSavedInUserData()), _pathStuckIterations(Parameters::defaultRGBDPlanStuckIterations()), _pathLinearVelocity(Parameters::defaultRGBDPlanLinearVelocity()), _pathAngularVelocity(Parameters::defaultRGBDPlanAngularVelocity()), _savedLocalizationIgnored(Parameters::defaultRGBDSavedLocalizationIgnored()), _loopCovLimited(Parameters::defaultRGBDLoopCovLimited()), _loopGPS(Parameters::defaultRtabmapLoopGPS()), _maxOdomCacheSize(Parameters::defaultRGBDMaxOdomCacheSize()), _loopClosureHypothesis(0,0.0f), _highestHypothesis(0,0.0f), _lastProcessTime(0.0), _someNodesHaveBeenTransferred(false), _distanceTravelled(0.0f), _epipolarGeometry(0), _bayesFilter(0), _graphOptimizer(0), _memory(0), _foutFloat(0), _foutInt(0), _wDir(""), _mapCorrection(Transform::getIdentity()), _lastLocalizationNodeId(0), _currentSessionHasGPS(false), _pathStatus(0), _pathCurrentIndex(0), _pathGoalIndex(0), _pathTransformToGoal(Transform::getIdentity()), _pathStuckCount(0), _pathStuckDistance(0.0f) { } Rtabmap::~Rtabmap() { UDEBUG(""); this->close(); } void Rtabmap::setupLogFiles(bool overwrite) { flushStatisticLogs(); // Log files if(_foutFloat) { fclose(_foutFloat); _foutFloat = 0; } if(_foutInt) { fclose(_foutInt); _foutInt = 0; } if(_statisticLogged && !_wDir.empty()) { std::string attributes = "a+"; // append to log files if(overwrite) { // If a file with the same name already exists // its content is erased and the file is treated // as a new empty file. attributes = "w"; } bool addLogFHeader = overwrite || !UFile::exists(_wDir+"/"+LOG_F); bool addLogIHeader = overwrite || !UFile::exists(_wDir+"/"+LOG_I); #ifdef _MSC_VER fopen_s(&_foutFloat, (_wDir+"/"+LOG_F).c_str(), attributes.c_str()); fopen_s(&_foutInt, (_wDir+"/"+LOG_I).c_str(), attributes.c_str()); #else _foutFloat = fopen((_wDir+"/"+LOG_F).c_str(), attributes.c_str()); _foutInt = fopen((_wDir+"/"+LOG_I).c_str(), attributes.c_str()); #endif // add header (column identification) if(_statisticLoggedHeaders && addLogFHeader && _foutFloat) { fprintf(_foutFloat, "Column headers:\n"); fprintf(_foutFloat, " 1-Total iteration time (s)\n"); fprintf(_foutFloat, " 2-Memory update time (s)\n"); fprintf(_foutFloat, " 3-Retrieval time (s)\n"); fprintf(_foutFloat, " 4-Likelihood time (s)\n"); fprintf(_foutFloat, " 5-Posterior time (s)\n"); fprintf(_foutFloat, " 6-Hypothesis selection time (s)\n"); fprintf(_foutFloat, " 7-Hypothesis validation time (s)\n"); fprintf(_foutFloat, " 8-Transfer time (s)\n"); fprintf(_foutFloat, " 9-Statistics creation time (s)\n"); fprintf(_foutFloat, " 10-Loop closure hypothesis value\n"); fprintf(_foutFloat, " 11-NAN\n"); fprintf(_foutFloat, " 12-NAN\n"); fprintf(_foutFloat, " 13-NAN\n"); fprintf(_foutFloat, " 14-NAN\n"); fprintf(_foutFloat, " 15-NAN\n"); fprintf(_foutFloat, " 16-Virtual place hypothesis\n"); fprintf(_foutFloat, " 17-Join trash time (s)\n"); fprintf(_foutFloat, " 18-Weight Update (rehearsal) similarity\n"); fprintf(_foutFloat, " 19-Empty trash time (s)\n"); fprintf(_foutFloat, " 20-Retrieval database access time (s)\n"); fprintf(_foutFloat, " 21-Add loop closure link time (s)\n"); fprintf(_foutFloat, " 22-Memory cleanup time (s)\n"); fprintf(_foutFloat, " 23-Scan matching (odometry correction) time (s)\n"); fprintf(_foutFloat, " 24-Local time loop closure detection time (s)\n"); fprintf(_foutFloat, " 25-Local space loop closure detection time (s)\n"); fprintf(_foutFloat, " 26-Map optimization (s)\n"); } if(_statisticLoggedHeaders && addLogIHeader && _foutInt) { fprintf(_foutInt, "Column headers:\n"); fprintf(_foutInt, " 1-Loop closure ID\n"); fprintf(_foutInt, " 2-Highest loop closure hypothesis\n"); fprintf(_foutInt, " 3-Locations transferred\n"); fprintf(_foutInt, " 4-NAN\n"); fprintf(_foutInt, " 5-Words extracted from the last image\n"); fprintf(_foutInt, " 6-Vocabulary size\n"); fprintf(_foutInt, " 7-Working memory size\n"); fprintf(_foutInt, " 8-Is loop closure hypothesis rejected?\n"); fprintf(_foutInt, " 9-NAN\n"); fprintf(_foutInt, " 10-NAN\n"); fprintf(_foutInt, " 11-Locations retrieved\n"); fprintf(_foutInt, " 12-Retrieval location ID\n"); fprintf(_foutInt, " 13-Unique words extraced from last image\n"); fprintf(_foutInt, " 14-Retrieval ID\n"); fprintf(_foutInt, " 15-Non-null likelihood values\n"); fprintf(_foutInt, " 16-Weight Update ID\n"); fprintf(_foutInt, " 17-Is last location merged through Weight Update?\n"); fprintf(_foutInt, " 18-Local graph size\n"); fprintf(_foutInt, " 19-Sensor data id\n"); fprintf(_foutInt, " 20-Indexed words\n"); fprintf(_foutInt, " 21-Index memory usage (KB)\n"); } ULOGGER_DEBUG("Log file (int)=%s", (_wDir+"/"+LOG_I).c_str()); ULOGGER_DEBUG("Log file (float)=%s", (_wDir+"/"+LOG_F).c_str()); } else { if(_statisticLogged) { UWARN("Working directory is not set, log disabled!"); } UDEBUG("Log disabled!"); } } void Rtabmap::flushStatisticLogs() { if(_foutFloat && _bufferedLogsF.size()) { UDEBUG("_bufferedLogsF.size=%d", _bufferedLogsF.size()); for(std::list<std::string>::iterator iter = _bufferedLogsF.begin(); iter!=_bufferedLogsF.end(); ++iter) { fprintf(_foutFloat, "%s", iter->c_str()); } _bufferedLogsF.clear(); } if(_foutInt && _bufferedLogsI.size()) { UDEBUG("_bufferedLogsI.size=%d", _bufferedLogsI.size()); for(std::list<std::string>::iterator iter = _bufferedLogsI.begin(); iter!=_bufferedLogsI.end(); ++iter) { fprintf(_foutInt, "%s", iter->c_str()); } _bufferedLogsI.clear(); } } void Rtabmap::init(const ParametersMap & parameters, const std::string & databasePath) { UDEBUG("path=%s", databasePath.c_str()); ParametersMap::const_iterator iter; if((iter=parameters.find(Parameters::kRtabmapWorkingDirectory())) != parameters.end()) { this->setWorkingDirectory(iter->second.c_str()); } _databasePath = databasePath; if(!_databasePath.empty()) { UASSERT(UFile::getExtension(_databasePath).compare("db") == 0); UINFO("Using database \"%s\".", _databasePath.c_str()); } else { UWARN("Using empty database. Mapping session will not be saved unless it is closed with an output database path."); } bool newDatabase = _databasePath.empty() || !UFile::exists(_databasePath); // If not exist, create a memory if(!_memory) { _memory = new Memory(parameters); _memory->init(_databasePath, false, parameters, true); } // Parse all parameters this->parseParameters(parameters); Transform lastPose; _optimizedPoses = _memory->loadOptimizedPoses(&lastPose); UINFO("Loaded optimizedPoses=%d lastPose=%s", _optimizedPoses.size(), lastPose.prettyPrint().c_str()); if(!_optimizedPoses.empty()) { if(!_savedLocalizationIgnored) { _lastLocalizationPose = lastPose; } std::map<int, Transform> tmp; // Get just the links _memory->getMetricConstraints(uKeysSet(_optimizedPoses), tmp, _constraints, false, true); } if(_databasePath.empty()) { _statisticLogged = false; } setupLogFiles(newDatabase); } void Rtabmap::init(const std::string & configFile, const std::string & databasePath) { // fill ctrl struct with values from the configuration file ParametersMap param;// = Parameters::defaultParameters; if(!configFile.empty()) { ULOGGER_DEBUG("Read parameters from = %s", configFile.c_str()); Parameters::readINI(configFile, param); } this->init(param, databasePath); } void Rtabmap::close(bool databaseSaved, const std::string & ouputDatabasePath) { UINFO("databaseSaved=%d", databaseSaved?1:0); _highestHypothesis = std::make_pair(0,0.0f); _loopClosureHypothesis = std::make_pair(0,0.0f); _lastProcessTime = 0.0; _someNodesHaveBeenTransferred = false; _constraints.clear(); _mapCorrection.setIdentity(); _mapCorrectionBackup.setNull(); _lastLocalizationNodeId = 0; _odomCachePoses.clear(); _odomCacheConstraints.clear(); _distanceTravelled = 0.0f; this->clearPath(0); _gpsGeocentricCache.clear(); _currentSessionHasGPS = false; flushStatisticLogs(); if(_foutFloat) { fclose(_foutFloat); _foutFloat = 0; } if(_foutInt) { fclose(_foutInt); _foutInt = 0; } if(_epipolarGeometry) { delete _epipolarGeometry; _epipolarGeometry = 0; } if(_memory) { if(databaseSaved) { _memory->saveOptimizedPoses(_optimizedPoses, _lastLocalizationPose); } _memory->close(databaseSaved, true, ouputDatabasePath); delete _memory; _memory = 0; } _optimizedPoses.clear(); _lastLocalizationPose.setNull(); if(_bayesFilter) { delete _bayesFilter; _bayesFilter = 0; } if(_graphOptimizer) { delete _graphOptimizer; _graphOptimizer = 0; } _databasePath.clear(); parseParameters(Parameters::getDefaultParameters()); // reset to default parameters _parameters.clear(); } void Rtabmap::parseParameters(const ParametersMap & parameters) { uInsert(_parameters, parameters); // place this before changing working directory Parameters::parse(parameters, Parameters::kRtabmapStatisticLogsBufferedInRAM(), _statisticLogsBufferedInRAM); Parameters::parse(parameters, Parameters::kRtabmapStatisticLogged(), _statisticLogged); Parameters::parse(parameters, Parameters::kRtabmapStatisticLoggedHeaders(), _statisticLoggedHeaders); ULOGGER_DEBUG(""); ParametersMap::const_iterator iter; if((iter=parameters.find(Parameters::kRtabmapWorkingDirectory())) != parameters.end()) { this->setWorkingDirectory(iter->second.c_str()); } Parameters::parse(parameters, Parameters::kRtabmapPublishStats(), _publishStats); Parameters::parse(parameters, Parameters::kRtabmapPublishLastSignature(), _publishLastSignatureData); Parameters::parse(parameters, Parameters::kRtabmapPublishPdf(), _publishPdf); Parameters::parse(parameters, Parameters::kRtabmapPublishLikelihood(), _publishLikelihood); Parameters::parse(parameters, Parameters::kRtabmapPublishRAMUsage(), _publishRAMUsage); Parameters::parse(parameters, Parameters::kRtabmapComputeRMSE(), _computeRMSE); Parameters::parse(parameters, Parameters::kRtabmapSaveWMState(), _saveWMState); Parameters::parse(parameters, Parameters::kRtabmapTimeThr(), _maxTimeAllowed); Parameters::parse(parameters, Parameters::kRtabmapMemoryThr(), _maxMemoryAllowed); Parameters::parse(parameters, Parameters::kRtabmapLoopThr(), _loopThr); Parameters::parse(parameters, Parameters::kRtabmapLoopRatio(), _loopRatio); Parameters::parse(parameters, Parameters::kRGBDMaxLoopClosureDistance(), _maxLoopClosureDistance); Parameters::parse(parameters, Parameters::kVhEpEnabled(), _verifyLoopClosureHypothesis); Parameters::parse(parameters, Parameters::kRtabmapMaxRetrieved(), _maxRetrieved); Parameters::parse(parameters, Parameters::kRGBDMaxLocalRetrieved(), _maxLocalRetrieved); Parameters::parse(parameters, Parameters::kMemImageKept(), _rawDataKept); Parameters::parse(parameters, Parameters::kRGBDEnabled(), _rgbdSlamMode); Parameters::parse(parameters, Parameters::kRGBDLinearUpdate(), _rgbdLinearUpdate); Parameters::parse(parameters, Parameters::kRGBDAngularUpdate(), _rgbdAngularUpdate); Parameters::parse(parameters, Parameters::kRGBDLinearSpeedUpdate(), _rgbdLinearSpeedUpdate); Parameters::parse(parameters, Parameters::kRGBDAngularSpeedUpdate(), _rgbdAngularSpeedUpdate); Parameters::parse(parameters, Parameters::kRGBDNewMapOdomChangeDistance(), _newMapOdomChangeDistance); Parameters::parse(parameters, Parameters::kRGBDNeighborLinkRefining(), _neighborLinkRefining); Parameters::parse(parameters, Parameters::kRGBDProximityByTime(), _proximityByTime); Parameters::parse(parameters, Parameters::kRGBDProximityBySpace(), _proximityBySpace); Parameters::parse(parameters, Parameters::kRGBDScanMatchingIdsSavedInLinks(), _scanMatchingIdsSavedInLinks); Parameters::parse(parameters, Parameters::kRGBDLocalRadius(), _localRadius); Parameters::parse(parameters, Parameters::kRGBDLocalImmunizationRatio(), _localImmunizationRatio); Parameters::parse(parameters, Parameters::kRGBDProximityMaxGraphDepth(), _proximityMaxGraphDepth); Parameters::parse(parameters, Parameters::kRGBDProximityMaxPaths(), _proximityMaxPaths); Parameters::parse(parameters, Parameters::kRGBDProximityPathMaxNeighbors(), _proximityMaxNeighbors); Parameters::parse(parameters, Parameters::kRGBDProximityPathFilteringRadius(), _proximityFilteringRadius); Parameters::parse(parameters, Parameters::kRGBDProximityPathRawPosesUsed(), _proximityRawPosesUsed); if(Parameters::parse(parameters, Parameters::kRGBDProximityAngle(), _proximityAngle)) { _proximityAngle *= M_PI/180.0f; } Parameters::parse(parameters, Parameters::kRGBDOptimizeFromGraphEnd(), _optimizeFromGraphEnd); Parameters::parse(parameters, Parameters::kRGBDOptimizeMaxError(), _optimizationMaxError); if(_optimizationMaxError > 0.0 && _optimizationMaxError < 1.0) { UWARN("RGBD/OptimizeMaxError (value=%f) is smaller than 1.0, setting to default %f " "instead (for backward compatibility issues when this parameter was previously " "an absolute error value).", _optimizationMaxError, Parameters::defaultRGBDOptimizeMaxError()); _optimizationMaxError = Parameters::defaultRGBDOptimizeMaxError(); } Parameters::parse(parameters, Parameters::kRtabmapStartNewMapOnLoopClosure(), _startNewMapOnLoopClosure); Parameters::parse(parameters, Parameters::kRtabmapStartNewMapOnGoodSignature(), _startNewMapOnGoodSignature); Parameters::parse(parameters, Parameters::kRGBDGoalReachedRadius(), _goalReachedRadius); Parameters::parse(parameters, Parameters::kRGBDGoalsSavedInUserData(), _goalsSavedInUserData); Parameters::parse(parameters, Parameters::kRGBDPlanStuckIterations(), _pathStuckIterations); Parameters::parse(parameters, Parameters::kRGBDPlanLinearVelocity(), _pathLinearVelocity); Parameters::parse(parameters, Parameters::kRGBDPlanAngularVelocity(), _pathAngularVelocity); Parameters::parse(parameters, Parameters::kRGBDSavedLocalizationIgnored(), _savedLocalizationIgnored); Parameters::parse(parameters, Parameters::kRGBDLoopCovLimited(), _loopCovLimited); Parameters::parse(parameters, Parameters::kRtabmapLoopGPS(), _loopGPS); Parameters::parse(parameters, Parameters::kRGBDMaxOdomCacheSize(), _maxOdomCacheSize); UASSERT(_rgbdLinearUpdate >= 0.0f); UASSERT(_rgbdAngularUpdate >= 0.0f); UASSERT(_rgbdLinearSpeedUpdate >= 0.0f); UASSERT(_rgbdAngularSpeedUpdate >= 0.0f); // By default, we create our strategies if they are not already created. // If they already exists, we check the parameters if a change is requested // Graph optimizer Optimizer::Type optimizerType = Optimizer::kTypeUndef; if((iter=parameters.find(Parameters::kOptimizerStrategy())) != parameters.end()) { optimizerType = (Optimizer::Type)std::atoi((*iter).second.c_str()); } if(optimizerType!=Optimizer::kTypeUndef) { UDEBUG("new detector strategy %d", int(optimizerType)); if(_graphOptimizer) { delete _graphOptimizer; _graphOptimizer = 0; } _graphOptimizer = Optimizer::create(optimizerType, _parameters); } else if(_graphOptimizer) { _graphOptimizer->parseParameters(parameters); } else { optimizerType = (Optimizer::Type)Parameters::defaultOptimizerStrategy(); _graphOptimizer = Optimizer::create(optimizerType, parameters); } if(_memory) { _memory->parseParameters(parameters); } if(!_epipolarGeometry) { _epipolarGeometry = new EpipolarGeometry(_parameters); } else { _epipolarGeometry->parseParameters(parameters); } // Bayes filter, create one if not exists if(!_bayesFilter) { _bayesFilter = new BayesFilter(_parameters); } else { _bayesFilter->parseParameters(parameters); } } int Rtabmap::getLastLocationId() const { int id = 0; if(_memory) { id = _memory->getLastSignatureId(); } return id; } std::list<int> Rtabmap::getWM() const { std::list<int> mem; if(_memory) { mem = uKeysList(_memory->getWorkingMem()); mem.remove(-1);// Ignore the virtual signature (if here) } return mem; } int Rtabmap::getWMSize() const { if(_memory) { return (int)_memory->getWorkingMem().size()-1; // remove virtual place } return 0; } std::map<int, int> Rtabmap::getWeights() const { std::map<int, int> weights; if(_memory) { weights = _memory->getWeights(); weights.erase(-1);// Ignore the virtual signature (if here) } return weights; } std::set<int> Rtabmap::getSTM() const { if(_memory) { return _memory->getStMem(); } return std::set<int>(); } int Rtabmap::getSTMSize() const { if(_memory) { return (int)_memory->getStMem().size(); } return 0; } int Rtabmap::getTotalMemSize() const { if(_memory) { const Signature * s =_memory->getLastWorkingSignature(); if(s) { return s->id(); } } return 0; } std::multimap<int, cv::KeyPoint> Rtabmap::getWords(int locationId) const { if(_memory) { const Signature * s = _memory->getSignature(locationId); if(s) { return s->getWords(); } } return std::multimap<int, cv::KeyPoint>(); } bool Rtabmap::isInSTM(int locationId) const { if(_memory) { return _memory->isInSTM(locationId); } return false; } bool Rtabmap::isIDsGenerated() const { if(_memory) { return _memory->isIDsGenerated(); } return Parameters::defaultMemGenerateIds(); } const Statistics & Rtabmap::getStatistics() const { return statistics_; } /* bool Rtabmap::getMetricData(int locationId, cv::Mat & rgb, cv::Mat & depth, float & depthConstant, Transform & pose, Transform & localTransform) const { if(_memory) { const Signature * s = _memory->getSignature(locationId); if(s && _optimizedPoses.find(s->id()) != _optimizedPoses.end()) { rgb = s->getImage(); depth = s->getDepth(); depthConstant = s->getDepthConstant(); pose = _optimizedPoses.at(s->id()); localTransform = s->getLocalTransform(); return true; } } return false; } */ Transform Rtabmap::getPose(int locationId) const { return uValue(_optimizedPoses, locationId, Transform()); } void Rtabmap::setInitialPose(const Transform & initialPose) { if(_memory) { if(!_memory->isIncremental()) { _lastLocalizationPose = initialPose; _lastLocalizationNodeId = 0; _odomCachePoses.clear(); _odomCacheConstraints.clear(); _mapCorrection.setIdentity(); _mapCorrectionBackup.setNull(); if(_memory->getLastWorkingSignature()->id() && _optimizedPoses.empty()) { cv::Mat covariance; this->optimizeCurrentMap(_memory->getLastWorkingSignature()->id(), false, _optimizedPoses, covariance, &_constraints); } } else { UWARN("Initial pose can only be set in localization mode (%s=false), ignoring it...", Parameters::kMemIncrementalMemory().c_str()); } } } int Rtabmap::triggerNewMap() { int mapId = -1; if(_memory) { if(!_memory->isIncremental()) { UWARN("Memory is not incremental (%s=false), ignoring creating a new map as we " "should be already processing new nodes in a new session.", Parameters::kMemIncrementalMemory().c_str()); return mapId; } std::map<int, int> reducedIds; mapId = _memory->incrementMapId(&reducedIds); UINFO("New map triggered, new map = %d", mapId); _optimizedPoses.clear(); _constraints.clear(); _lastLocalizationNodeId = 0; _odomCachePoses.clear(); _odomCacheConstraints.clear(); if(_bayesFilter) { _bayesFilter->reset(); } //Verify if there are nodes that were merged through graph reduction if(reducedIds.size() && _path.size()) { for(unsigned int i=0; i<_path.size(); ++i) { std::map<int, int>::const_iterator iter = reducedIds.find(_path[i].first); if(iter!= reducedIds.end()) { // change path ID to loop closure ID _path[i].first = iter->second; } } } } return mapId; } bool Rtabmap::labelLocation(int id, const std::string & label) { if(_memory) { if(id > 0) { return _memory->labelSignature(id, label); } else if(_memory->getLastWorkingSignature()) { return _memory->labelSignature(_memory->getLastWorkingSignature()->id(), label); } else { UERROR("Last signature is null! Cannot set label \"%s\"", label.c_str()); } } return false; } bool Rtabmap::setUserData(int id, const cv::Mat & data) { if(_memory) { if(id > 0) { return _memory->setUserData(id, data); } else if(_memory->getLastWorkingSignature()) { return _memory->setUserData(_memory->getLastWorkingSignature()->id(), data); } else { UERROR("Last signature is null! Cannot set user data!"); } } return false; } void Rtabmap::generateDOTGraph(const std::string & path, int id, int margin) { if(_memory) { _memory->joinTrashThread(); // make sure the trash is flushed if(id > 0) { std::map<int, int> ids = _memory->getNeighborsId(id, margin, -1, false); if(ids.size() > 0) { ids.insert(std::pair<int,int>(id, 0)); std::set<int> idsSet; for(std::map<int, int>::iterator iter = ids.begin(); iter!=ids.end(); ++iter) { idsSet.insert(idsSet.end(), iter->first); } _memory->generateGraph(path, idsSet); } else { UERROR("No neighbors found for signature %d.", id); } } else { _memory->generateGraph(path); } } } void Rtabmap::exportPoses(const std::string & path, bool optimized, bool global, int format) { if(_memory && _memory->getLastWorkingSignature()) { std::map<int, Transform> poses; std::multimap<int, Link> constraints; if(optimized) { cv::Mat covariance; this->optimizeCurrentMap(_memory->getLastWorkingSignature()->id(), global, poses, covariance, &constraints); } else { std::map<int, int> ids = _memory->getNeighborsId(_memory->getLastWorkingSignature()->id(), 0, global?-1:0, true); _memory->getMetricConstraints(uKeysSet(ids), poses, constraints, global); } std::map<int, double> stamps; if(format == 1) { for(std::map<int, Transform>::iterator iter=poses.begin(); iter!=poses.end(); ++iter) { Transform o,g; int m, w; std::string l; double stamp = 0.0; std::vector<float> v; GPS gps; EnvSensors sensors; _memory->getNodeInfo(iter->first, o, m, w, l, stamp, g, v, gps, sensors, true); stamps.insert(std::make_pair(iter->first, stamp)); } } graph::exportPoses(path, format, poses, constraints, stamps, _parameters); } } void Rtabmap::resetMemory() { UDEBUG(""); _highestHypothesis = std::make_pair(0,0.0f); _loopClosureHypothesis = std::make_pair(0,0.0f); _lastProcessTime = 0.0; _someNodesHaveBeenTransferred = false; _optimizedPoses.clear(); _constraints.clear(); _mapCorrection.setIdentity(); _mapCorrectionBackup.setNull(); _lastLocalizationPose.setNull(); _lastLocalizationNodeId = 0; _odomCachePoses.clear(); _odomCacheConstraints.clear(); _distanceTravelled = 0.0f; this->clearPath(0); if(_memory) { _memory->init(_databasePath, true, _parameters, true); if(_memory->getLastWorkingSignature()) { cv::Mat covariance; optimizeCurrentMap(_memory->getLastWorkingSignature()->id(), false, _optimizedPoses, covariance, &_constraints); } if(_bayesFilter) { _bayesFilter->reset(); } } else { UERROR("RTAB-Map is not initialized. No memory to reset..."); } this->setupLogFiles(true); } class NearestPathKey { public: NearestPathKey(float l, int i) : likelihood(l), id(i){} bool operator<(const NearestPathKey & k) const { if(likelihood < k.likelihood) { return true; } else if(likelihood == k.likelihood && id < k.id) { return true; } return false; } float likelihood; int id; }; //============================================================ // MAIN LOOP //============================================================ bool Rtabmap::process( const cv::Mat & image, int id, const std::map<std::string, float> & externalStats) { return this->process(SensorData(image, id), Transform()); } bool Rtabmap::process( const SensorData & data, Transform odomPose, float odomLinearVariance, float odomAngularVariance, const std::vector<float> & odomVelocity, const std::map<std::string, float> & externalStats) { if(!odomPose.isNull()) { UASSERT(odomLinearVariance>0.0f); UASSERT(odomAngularVariance>0.0f); } cv::Mat covariance = cv::Mat::eye(6,6,CV_64FC1); covariance.at<double>(0,0) = odomLinearVariance; covariance.at<double>(1,1) = odomLinearVariance; covariance.at<double>(2,2) = odomLinearVariance; covariance.at<double>(3,3) = odomAngularVariance; covariance.at<double>(4,4) = odomAngularVariance; covariance.at<double>(5,5) = odomAngularVariance; return process(data, odomPose, covariance, odomVelocity, externalStats); } bool Rtabmap::process( const SensorData & data, Transform odomPose, const cv::Mat & odomCovariance, const std::vector<float> & odomVelocity, const std::map<std::string, float> & externalStats) { UDEBUG(""); //============================================================ // Initialization //============================================================ UTimer timer; UTimer timerTotal; double timeMemoryUpdate = 0; double timeNeighborLinkRefining = 0; double timeProximityByTimeDetection = 0; double timeProximityBySpaceVisualDetection = 0; double timeProximityBySpaceDetection = 0; double timeCleaningNeighbors = 0; double timeReactivations = 0; double timeAddLoopClosureLink = 0; double timeMapOptimization = 0; double timeRetrievalDbAccess = 0; double timeLikelihoodCalculation = 0; double timePosteriorCalculation = 0; double timeHypothesesCreation = 0; double timeHypothesesValidation = 0; double timeRealTimeLimitReachedProcess = 0; double timeMemoryCleanup = 0; double timeEmptyingTrash = 0; double timeFinalizingStatistics = 0; double timeJoiningTrash = 0; double timeStatsCreation = 0; float hypothesisRatio = 0.0f; // Only used for statistics bool rejectedHypothesis = false; std::map<int, float> rawLikelihood; std::map<int, float> adjustedLikelihood; std::map<int, float> likelihood; std::map<int, int> weights; std::map<int, float> posterior; std::list<std::pair<int, float> > reactivateHypotheses; std::map<int, int> childCount; std::set<int> signaturesRetrieved; int proximityDetectionsInTimeFound = 0; const Signature * signature = 0; const Signature * sLoop = 0; _loopClosureHypothesis = std::make_pair(0,0.0f); std::pair<int, float> lastHighestHypothesis = _highestHypothesis; _highestHypothesis = std::make_pair(0,0.0f); std::set<int> immunizedLocations; statistics_ = Statistics(); // reset for(std::map<std::string, float>::const_iterator iter=externalStats.begin(); iter!=externalStats.end(); ++iter) { statistics_.addStatistic(iter->first, iter->second); } //============================================================ // Wait for an image... //============================================================ ULOGGER_INFO("getting data..."); timer.start(); timerTotal.start(); UASSERT_MSG(_memory, "RTAB-Map is not initialized!"); UASSERT_MSG(_bayesFilter, "RTAB-Map is not initialized!"); UASSERT_MSG(_graphOptimizer, "RTAB-Map is not initialized!"); //============================================================ // If RGBD SLAM is enabled, a pose must be set. //============================================================ bool fakeOdom = false; if(_rgbdSlamMode) { if(!_memory->isIncremental() && !odomPose.isNull()) { if(!_mapCorrectionBackup.isNull()) { _mapCorrection = _mapCorrectionBackup; _mapCorrectionBackup.setNull(); } else if(_optimizedPoses.size() && _mapCorrection.isIdentity() && !_lastLocalizationPose.isNull() && _lastLocalizationNodeId == 0) { // Localization mode if(!_optimizeFromGraphEnd) { //set map->odom so that odom is moved back to last saved localization _mapCorrection = _lastLocalizationPose * odomPose.inverse(); std::map<int, Transform> nodesOnly(_optimizedPoses.lower_bound(1), _optimizedPoses.end()); _lastLocalizationNodeId = graph::findNearestNode(nodesOnly, _lastLocalizationPose); UWARN("Update map correction based on last localization saved in database! correction = %s, nearest id = %d of last pose = %s, odom = %s", _mapCorrection.prettyPrint().c_str(), _lastLocalizationNodeId, _lastLocalizationPose.prettyPrint().c_str(), odomPose.prettyPrint().c_str()); } else { //move optimized poses accordingly to last saved localization Transform mapCorrectionInv = odomPose * _lastLocalizationPose.inverse(); for(std::map<int, Transform>::iterator iter=_optimizedPoses.begin(); iter!=_optimizedPoses.end(); ++iter) { iter->second = mapCorrectionInv * iter->second; } } } } if(odomPose.isNull()) { if(_memory->isIncremental()) { UERROR("RGB-D SLAM mode is enabled, memory is incremental but no odometry is provided. " "Image %d is ignored!", data.id()); return false; } else // fake localization { if(_lastLocalizationPose.isNull()) { _lastLocalizationPose = Transform::getIdentity(); } fakeOdom = true; odomPose = _mapCorrection.inverse() * _lastLocalizationPose; } } else if(_memory->isIncremental()) // only in mapping mode { // Detect if the odometry is reset. If yes, trigger a new map. if(_memory->getLastWorkingSignature()) { const Transform & lastPose = _memory->getLastWorkingSignature()->getPose(); // use raw odometry // look for identity if(!lastPose.isIdentity() && odomPose.isIdentity()) { int mapId = triggerNewMap(); UWARN("Odometry is reset (identity pose detected). Increment map id to %d!", mapId); } else if(_newMapOdomChangeDistance > 0.0) { // look for large change Transform lastPoseToNewPose = lastPose.inverse() * odomPose; float x,y,z, roll,pitch,yaw; lastPoseToNewPose.getTranslationAndEulerAngles(x,y,z, roll,pitch,yaw); if((x*x + y*y + z*z) > _newMapOdomChangeDistance*_newMapOdomChangeDistance) { int mapId = triggerNewMap(); UWARN("Odometry is reset (large odometry change detected > %f). A new map (%d) is created! Last pose = %s, new pose = %s", _newMapOdomChangeDistance, mapId, lastPose.prettyPrint().c_str(), odomPose.prettyPrint().c_str()); } } } } } //============================================================ // Memory Update : Location creation + Add to STM + Weight Update (Rehearsal) //============================================================ ULOGGER_INFO("Updating memory..."); if(_rgbdSlamMode) { if(!_memory->update(data, odomPose, odomCovariance, odomVelocity, &statistics_)) { return false; } } else { if(!_memory->update(data, Transform(), cv::Mat(), std::vector<float>(), &statistics_)) { return false; } } signature = _memory->getLastWorkingSignature(); _currentSessionHasGPS = _currentSessionHasGPS || signature->sensorData().gps().stamp() > 0.0; if(!signature) { UFATAL("Not supposed to be here...last signature is null?!?"); } ULOGGER_INFO("Processing signature %d w=%d map=%d", signature->id(), signature->getWeight(), signature->mapId()); timeMemoryUpdate = timer.ticks(); ULOGGER_INFO("timeMemoryUpdate=%fs", timeMemoryUpdate); //============================================================ // Metric //============================================================ bool smallDisplacement = false; bool tooFastMovement = false; std::list<int> signaturesRemoved; if(_rgbdSlamMode) { statistics_.addStatistic(Statistics::kMemoryOdometry_variance_lin(), odomCovariance.empty()?1.0f:(float)odomCovariance.at<double>(0,0)); statistics_.addStatistic(Statistics::kMemoryOdometry_variance_ang(), odomCovariance.empty()?1.0f:(float)odomCovariance.at<double>(5,5)); //Verify if there was a rehearsal int rehearsedId = (int)uValue(statistics_.data(), Statistics::kMemoryRehearsal_merged(), 0.0f); if(rehearsedId > 0) { _optimizedPoses.erase(rehearsedId); } else if(signature->getWeight() >= 0) { if(_rgbdLinearUpdate > 0.0f || _rgbdAngularUpdate > 0.0f) { //============================================================ // Minimum displacement required to add to Memory //============================================================ const std::multimap<int, Link> & links = signature->getLinks(); if(links.size() && links.begin()->second.type() == Link::kNeighbor) { // don't do this if there are intermediate nodes const Signature * s = _memory->getSignature(links.begin()->second.to()); UASSERT(s!=0); if(s->getWeight() >= 0) { float x,y,z, roll,pitch,yaw; links.begin()->second.transform().getTranslationAndEulerAngles(x,y,z, roll,pitch,yaw); bool isMoving = fabs(x) > _rgbdLinearUpdate || fabs(y) > _rgbdLinearUpdate || fabs(z) > _rgbdLinearUpdate || (_rgbdAngularUpdate>0.0f && ( fabs(roll) > _rgbdAngularUpdate || fabs(pitch) > _rgbdAngularUpdate || fabs(yaw) > _rgbdAngularUpdate)); if(!isMoving) { // This will disable global loop closure detection, only retrieval will be done. // The location will also be deleted at the end. smallDisplacement = true; } } } } if(odomVelocity.size() == 6) { // This will disable global loop closure detection, only retrieval will be done. // The location will also be deleted at the end. tooFastMovement = (_rgbdLinearSpeedUpdate>0.0f && uMax3(fabs(odomVelocity[0]), fabs(odomVelocity[1]), fabs(odomVelocity[2])) > _rgbdLinearSpeedUpdate) || (_rgbdAngularSpeedUpdate>0.0f && uMax3(fabs(odomVelocity[3]), fabs(odomVelocity[4]), fabs(odomVelocity[5])) > _rgbdAngularSpeedUpdate); } } // Update optimizedPoses with the newly added node Transform newPose; if(_neighborLinkRefining && signature->getLinks().size() && signature->getLinks().begin()->second.type() == Link::kNeighbor && _memory->isIncremental() && // ignore pose matching in localization mode rehearsedId == 0) // don't do it if rehearsal happened { int oldId = signature->getLinks().begin()->first; const Signature * oldS = _memory->getSignature(oldId); UASSERT(oldS != 0); if(signature->getWeight() >= 0 && oldS->getWeight()>=0) // ignore intermediate nodes { Transform guess = signature->getLinks().begin()->second.transform().inverse(); if(smallDisplacement) { if(signature->getLinks().begin()->second.transVariance() == 1) { // set small variance UDEBUG("Set small variance. The robot is not moving."); _memory->updateLink(Link(oldId, signature->id(), signature->getLinks().begin()->second.type(), guess, cv::Mat::eye(6,6,CV_64FC1)*1000)); } } else { //============================================================ // Refine neighbor links //============================================================ UINFO("Odometry refining: guess = %s", guess.prettyPrint().c_str()); RegistrationInfo info; Transform t = _memory->computeTransform(oldId, signature->id(), guess, &info); if(!t.isNull()) { UINFO("Odometry refining: update neighbor link (%d->%d, variance:lin=%f, ang=%f) from %s to %s", oldId, signature->id(), info.covariance.at<double>(0,0), info.covariance.at<double>(5,5), guess.prettyPrint().c_str(), t.prettyPrint().c_str()); UASSERT(info.covariance.at<double>(0,0) > 0.0 && info.covariance.at<double>(5,5) > 0.0); _memory->updateLink(Link(oldId, signature->id(), signature->getLinks().begin()->second.type(), t, info.covariance.inv())); if(_optimizeFromGraphEnd) { // update all previous nodes // Normally _mapCorrection should be identity, but if _optimizeFromGraphEnd // parameters just changed state, we should put back all poses without map correction. Transform u = guess * t.inverse(); std::map<int, Transform>::iterator jter = _optimizedPoses.find(oldId); UASSERT(jter!=_optimizedPoses.end()); Transform up = jter->second * u * jter->second.inverse(); Transform mapCorrectionInv = _mapCorrection.inverse(); for(std::map<int, Transform>::iterator iter=_optimizedPoses.begin(); iter!=_optimizedPoses.end(); ++iter) { iter->second = mapCorrectionInv * up * iter->second; } } } else { UINFO("Odometry refining rejected: %s", info.rejectedMsg.c_str()); if(!info.covariance.empty() && info.covariance.at<double>(0,0) > 0.0 && info.covariance.at<double>(0,0) != 1.0 && info.covariance.at<double>(5,5) > 0.0 && info.covariance.at<double>(5,5) != 1.0) { std::cout << info.covariance << std::endl; _memory->updateLink(Link(oldId, signature->id(), signature->getLinks().begin()->second.type(), guess, (info.covariance*100.0).inv())); } } statistics_.addStatistic(Statistics::kNeighborLinkRefiningAccepted(), !t.isNull()?1.0f:0); statistics_.addStatistic(Statistics::kNeighborLinkRefiningInliers(), info.inliers); statistics_.addStatistic(Statistics::kNeighborLinkRefiningICP_inliers_ratio(), info.icpInliersRatio); statistics_.addStatistic(Statistics::kNeighborLinkRefiningICP_rotation(), info.icpRotation); statistics_.addStatistic(Statistics::kNeighborLinkRefiningICP_translation(), info.icpTranslation); statistics_.addStatistic(Statistics::kNeighborLinkRefiningICP_complexity(), info.icpStructuralComplexity); statistics_.addStatistic(Statistics::kNeighborLinkRefiningPts(), signature->sensorData().laserScanRaw().size()); } timeNeighborLinkRefining = timer.ticks(); ULOGGER_INFO("timeOdometryRefining=%fs", timeNeighborLinkRefining); UASSERT(oldS->hasLink(signature->id())); UASSERT(uContains(_optimizedPoses, oldId)); statistics_.addStatistic(Statistics::kNeighborLinkRefiningVariance(), oldS->getLinks().find(signature->id())->second.transVariance()); newPose = _optimizedPoses.at(oldId) * oldS->getLinks().find(signature->id())->second.transform(); _mapCorrection = newPose * signature->getPose().inverse(); if(_mapCorrection.getNormSquared() > 0.001f && _optimizeFromGraphEnd) { UERROR("Map correction should be identity when optimizing from the last node. T=%s NewPose=%s OldPose=%s", _mapCorrection.prettyPrint().c_str(), newPose.prettyPrint().c_str(), signature->getPose().prettyPrint().c_str()); } } else { UWARN("Neighbor link refining is activated but there are intermediate nodes, aborting refining..."); } } else { newPose = _mapCorrection * signature->getPose(); } UDEBUG("Added pose %s (odom=%s)", newPose.prettyPrint().c_str(), signature->getPose().prettyPrint().c_str()); // Update Poses and Constraints _optimizedPoses.insert(std::make_pair(signature->id(), newPose)); if(_memory->isIncremental() && signature->getWeight() >= 0) { for(std::map<int, Link>::const_iterator iter = signature->getLandmarks().begin(); iter!=signature->getLandmarks().end(); ++iter) { if(_optimizedPoses.find(iter->first) == _optimizedPoses.end()) { _optimizedPoses.insert(std::make_pair(iter->first, newPose*iter->second.transform())); } _constraints.insert(std::make_pair(iter->first, iter->second.inverse())); } } if(signature->getLinks().size() && signature->getLinks().begin()->second.type() == Link::kNeighbor) { // link should be old to new UASSERT_MSG(signature->id() > signature->getLinks().begin()->second.to(), "Only forward links should be added."); Link tmp = signature->getLinks().begin()->second.inverse(); _distanceTravelled += tmp.transform().getNorm(); // if the previous node is an intermediate node, remove it from the local graph if(_constraints.size() && _constraints.rbegin()->second.to() == signature->getLinks().begin()->second.to()) { const Signature * s = _memory->getSignature(signature->getLinks().begin()->second.to()); UASSERT(s!=0); if(s->getWeight() == -1) { tmp = _constraints.rbegin()->second.merge(tmp, tmp.type()); _optimizedPoses.erase(s->id()); _constraints.erase(--_constraints.end()); } } _constraints.insert(std::make_pair(tmp.from(), tmp)); } // Localization mode stuff _lastLocalizationPose = newPose; // keep in cache the latest corrected pose if(!_memory->isIncremental()) { if(_optimizationMaxError <= 0.0f || _maxOdomCacheSize <= 0) { _odomCachePoses.clear(); _odomCacheConstraints.clear(); } else if(!_odomCachePoses.empty()) { if((int)_odomCachePoses.size() > _maxOdomCacheSize) { UWARN("Odometry poses cached for localization verification reached the " "maximum numbers of %d, clearing the buffer. The next localization " "won't be verified! Set %s to 0 if you want to disable the localization verification.", _maxOdomCacheSize, Parameters::kRGBDMaxOdomCacheSize().c_str()); _odomCachePoses.clear(); _odomCacheConstraints.clear(); } else { _odomCacheConstraints.insert( std::make_pair(signature->id(), Link(signature->id(), _odomCacheConstraints.rbegin()->first, Link::kNeighbor, signature->getPose().inverse() * _odomCachePoses.rbegin()->second, odomCovariance.inv()))); _odomCachePoses.insert(std::make_pair(signature->id(), signature->getPose())); // keep odometry poses } } } //============================================================ // Reduced graph //============================================================ //Verify if there are nodes that were merged through graph reduction if(statistics_.reducedIds().size()) { for(unsigned int i=0; i<_path.size(); ++i) { std::map<int, int>::const_iterator iter = statistics_.reducedIds().find(_path[i].first); if(iter!= statistics_.reducedIds().end()) { // change path ID to loop closure ID _path[i].first = iter->second; } } for(std::map<int, int>::const_iterator iter=statistics_.reducedIds().begin(); iter!=statistics_.reducedIds().end(); ++iter) { int erased = (int)_optimizedPoses.erase(iter->first); if(erased) { for(std::multimap<int, Link>::iterator jter = _constraints.begin(); jter!=_constraints.end();) { if(jter->second.from() == iter->first || jter->second.to() == iter->first) { _constraints.erase(jter++); } else { ++jter; } } } } } //============================================================ // Local loop closure in TIME //============================================================ if(_proximityByTime && rehearsedId == 0 && // don't do it if rehearsal happened _memory->isIncremental() && // don't do it in localization mode signature->getWeight()>=0) { const std::set<int> & stm = _memory->getStMem(); for(std::set<int>::const_reverse_iterator iter = stm.rbegin(); iter!=stm.rend(); ++iter) { if(*iter != signature->id() && signature->getLinks().find(*iter) == signature->getLinks().end() && _memory->getSignature(*iter)->mapId() == signature->mapId() && _memory->getSignature(*iter)->getWeight()>=0) { std::string rejectedMsg; UDEBUG("Check local transform between %d and %d", signature->id(), *iter); RegistrationInfo info; Transform guess; if(_optimizedPoses.find(*iter) != _optimizedPoses.end()) { guess = _optimizedPoses.at(*iter).inverse() * newPose; } // For proximity by time, correspondences should be already enough precise, so don't recompute them Transform transform = _memory->computeTransform(*iter, signature->id(), guess, &info, true); if(!transform.isNull()) { transform = transform.inverse(); UDEBUG("Add local loop closure in TIME (%d->%d) %s", signature->id(), *iter, transform.prettyPrint().c_str()); // Add a loop constraint UASSERT(info.covariance.at<double>(0,0) > 0.0 && info.covariance.at<double>(5,5) > 0.0); if(_memory->addLink(Link(signature->id(), *iter, Link::kLocalTimeClosure, transform, getInformation(info.covariance)))) { ++proximityDetectionsInTimeFound; UINFO("Local loop closure found between %d and %d with t=%s", *iter, signature->id(), transform.prettyPrint().c_str()); } else { UWARN("Cannot add local loop closure between %d and %d ?!?", *iter, signature->id()); } } else { UINFO("Local loop closure (time) between %d and %d rejected: %s", *iter, signature->id(), rejectedMsg.c_str()); } } } } } timeProximityByTimeDetection = timer.ticks(); UINFO("timeProximityByTimeDetection=%fs", timeProximityByTimeDetection); //============================================================ // Bayes filter update //============================================================ int previousId = signature->getLinks().size() && signature->getLinks().begin()->first!=signature->id()?signature->getLinks().begin()->first:0; // Not a bad signature, not an intermediate node, not a small displacement unless the previous signature didn't have a loop closure, not too fast movement if(!signature->isBadSignature() && signature->getWeight()>=0 && (!smallDisplacement || _memory->getLoopClosureLinks(previousId, false).size() == 0) && !tooFastMovement) { // If the working memory is empty, don't do the detection. It happens when it // is the first time the detector is started (there needs some images to // fill the short-time memory before a signature is added to the working memory). if(_memory->getWorkingMem().size()) { //============================================================ // Likelihood computation // Get the likelihood of the new signature // with all images contained in the working memory + reactivated. //============================================================ ULOGGER_INFO("computing likelihood..."); std::list<int> signaturesToCompare; GPS originGPS; Transform originOffsetENU = Transform::getIdentity(); if(_loopGPS) { originGPS = signature->sensorData().gps(); if(originGPS.stamp() == 0.0 && _currentSessionHasGPS) { UTimer tmpT; if(_optimizedPoses.size() && _memory->isIncremental()) { //Search for latest node having GPS linked to current signature not too far. std::map<int, float> nearestIds = graph::getNodesInRadius(signature->id(), _optimizedPoses, _localRadius); for(std::map<int, float>::reverse_iterator iter=nearestIds.rbegin(); iter!=nearestIds.rend() && iter->first>0; ++iter) { const Signature * s = _memory->getSignature(iter->first); UASSERT(s!=0); if(s->sensorData().gps().stamp() > 0.0) { originGPS = s->sensorData().gps(); const Transform & sPose = _optimizedPoses.at(s->id()); Transform localToENU(0,0,(float)((-(originGPS.bearing()-90))*M_PI/180.0) - sPose.theta()); originOffsetENU = localToENU * (sPose.rotation()*(sPose.inverse()*_optimizedPoses.at(signature->id()))); break; } } } //else if(!_memory->isIncremental()) // TODO, how can we estimate current GPS position in localization? //{ //} } if(originGPS.stamp() > 0.0) { // no need to save it if it is in localization mode _gpsGeocentricCache.insert(std::make_pair(signature->id(), std::make_pair(originGPS.toGeodeticCoords().toGeocentric_WGS84(), originOffsetENU))); } } for(std::map<int, double>::const_iterator iter=_memory->getWorkingMem().begin(); iter!=_memory->getWorkingMem().end(); ++iter) { if(iter->first > 0) { const Signature * s = _memory->getSignature(iter->first); UASSERT(s!=0); if(s->getWeight() != -1) // ignore intermediate nodes { bool accept = true; if(originGPS.stamp()>0.0) { std::map<int, std::pair<cv::Point3d, Transform> >::iterator cacheIter = _gpsGeocentricCache.find(s->id()); if(cacheIter == _gpsGeocentricCache.end()) { GPS gps = s->sensorData().gps(); Transform offsetENU = Transform::getIdentity(); if(gps.stamp()==0.0) { _memory->getGPS(s->id(), gps, offsetENU, false); } if(gps.stamp() > 0.0) { cacheIter = _gpsGeocentricCache.insert( std::make_pair(s->id(), std::make_pair(gps.toGeodeticCoords().toGeocentric_WGS84(), offsetENU))).first; } } if(cacheIter != _gpsGeocentricCache.end()) { std::map<int, std::pair<cv::Point3d, Transform> >::iterator originIter = _gpsGeocentricCache.find(signature->id()); UASSERT(originIter != _gpsGeocentricCache.end()); cv::Point3d relativePose = GeodeticCoords::Geocentric_WGS84ToENU_WGS84(cacheIter->second.first, originIter->second.first, originGPS.toGeodeticCoords()); const double & error = originGPS.error(); const Transform & offsetENU = cacheIter->second.second; relativePose.x += offsetENU.x() - originOffsetENU.x(); relativePose.y += offsetENU.y() - originOffsetENU.y(); relativePose.z += offsetENU.z() - originOffsetENU.z(); // ignore altitude if difference is under GPS error if(relativePose.z>error) { relativePose.z -= error; } else if(relativePose.z < -error) { relativePose.z += error; } else { relativePose.z = 0; } accept = uNormSquared(relativePose.x, relativePose.y, relativePose.z) < _localRadius*_localRadius; } } if(accept) { signaturesToCompare.push_back(iter->first); } } } else { // virtual signature should be added signaturesToCompare.push_back(iter->first); } } rawLikelihood = _memory->computeLikelihood(signature, signaturesToCompare); // Adjust the likelihood (with mean and std dev) likelihood = rawLikelihood; this->adjustLikelihood(likelihood); timeLikelihoodCalculation = timer.ticks(); ULOGGER_INFO("timeLikelihoodCalculation=%fs",timeLikelihoodCalculation); //============================================================ // Apply the Bayes filter // Posterior = Likelihood x Prior //============================================================ ULOGGER_INFO("getting posterior..."); // Compute the posterior posterior = _bayesFilter->computePosterior(_memory, likelihood); timePosteriorCalculation = timer.ticks(); ULOGGER_INFO("timePosteriorCalculation=%fs",timePosteriorCalculation); // For statistics, copy weights if(_publishStats && (_publishLikelihood || _publishPdf)) { weights = _memory->getWeights(); } //============================================================ // Select the highest hypothesis //============================================================ ULOGGER_INFO("creating hypotheses..."); if(posterior.size()) { for(std::map<int, float>::const_reverse_iterator iter = posterior.rbegin(); iter != posterior.rend(); ++iter) { if(iter->first > 0 && iter->second > _highestHypothesis.second) { _highestHypothesis = *iter; } } // With the virtual place, use sum of LC probabilities (1 - virtual place hypothesis). _highestHypothesis.second = 1-posterior.begin()->second; } timeHypothesesCreation = timer.ticks(); ULOGGER_INFO("Highest hypothesis=%d, value=%f, timeHypothesesCreation=%fs", _highestHypothesis.first, _highestHypothesis.second, timeHypothesesCreation); if(_highestHypothesis.first > 0) { float loopThr = _loopThr; if((_startNewMapOnLoopClosure || !_memory->isIncremental()) && graph::filterLinks(signature->getLinks(), Link::kSelfRefLink).size() == 0 && // alone in the current map _memory->getWorkingMem().size()>1 && // should have an old map (beside virtual signature) (int)_memory->getWorkingMem().size()<=_memory->getMaxStMemSize() && _rgbdSlamMode) { // If the map is very small (under STM size) and we need to find // a loop closure before continuing the map or localizing, // use the best hypothesis directly. loopThr = 0.0f; } // Loop closure Threshold // When _loopThr=0, accept loop closure if the hypothesis is over // the virtual (new) place hypothesis. if(_highestHypothesis.second >= loopThr) { rejectedHypothesis = true; if(posterior.size() <= 2 && loopThr>0.0f) { // Ignore loop closure if there is only one loop closure hypothesis UDEBUG("rejected hypothesis: single hypothesis"); } else if(_verifyLoopClosureHypothesis && !_epipolarGeometry->check(signature, _memory->getSignature(_highestHypothesis.first))) { UWARN("rejected hypothesis: by epipolar geometry"); } else if(_loopRatio > 0.0f && lastHighestHypothesis.second && _highestHypothesis.second < _loopRatio*lastHighestHypothesis.second) { UWARN("rejected hypothesis: not satisfying hypothesis ratio (%f < %f * %f)", _highestHypothesis.second, _loopRatio, lastHighestHypothesis.second); } else if(_loopRatio > 0.0f && lastHighestHypothesis.second == 0) { UWARN("rejected hypothesis: last closure hypothesis is null (loop ratio is on)"); } else { _loopClosureHypothesis = _highestHypothesis; rejectedHypothesis = false; } timeHypothesesValidation = timer.ticks(); ULOGGER_INFO("timeHypothesesValidation=%fs",timeHypothesesValidation); } else if(_highestHypothesis.second < _loopRatio*lastHighestHypothesis.second) { // Used for Precision-Recall computation. // When analyzing logs, it's convenient to know // if the hypothesis would be rejected if T_loop would be lower. rejectedHypothesis = true; UDEBUG("rejected hypothesis: under loop ratio %f < %f", _highestHypothesis.second, _loopRatio*lastHighestHypothesis.second); } //for statistic... hypothesisRatio = _loopClosureHypothesis.second>0?_highestHypothesis.second/_loopClosureHypothesis.second:0; } } // if(_memory->getWorkingMemSize()) }// !isBadSignature else if(!signature->isBadSignature() && (smallDisplacement || tooFastMovement)) { _highestHypothesis = lastHighestHypothesis; } //============================================================ // Before retrieval, make sure the trash has finished //============================================================ _memory->joinTrashThread(); timeEmptyingTrash = _memory->getDbSavingTime(); timeJoiningTrash = timer.ticks(); ULOGGER_INFO("Time emptying memory trash = %fs, joining (actual overhead) = %fs", timeEmptyingTrash, timeJoiningTrash); //============================================================ // RETRIEVAL 1/3 : Loop closure neighbors reactivation //============================================================ int retrievalId = _highestHypothesis.first; std::list<int> reactivatedIds; double timeGetNeighborsTimeDb = 0.0; double timeGetNeighborsSpaceDb = 0.0; int immunizedGlobally = 0; int immunizedLocally = 0; int maxLocalLocationsImmunized = 0; if(_maxTimeAllowed != 0 || _maxMemoryAllowed != 0) { // with memory management, we have to immunize some nodes maxLocalLocationsImmunized = _localImmunizationRatio * float(_memory->getWorkingMem().size()); } // no need to do retrieval or immunization of locations if memory management // is disabled and all nodes are in WM if(!(_memory->allNodesInWM() && maxLocalLocationsImmunized == 0)) { if(retrievalId > 0) { //Load neighbors ULOGGER_INFO("Retrieving locations... around id=%d", retrievalId); int neighborhoodSize = (int)_bayesFilter->getPredictionLC().size()-1; UASSERT(neighborhoodSize >= 0); ULOGGER_DEBUG("margin=%d maxRetieved=%d", neighborhoodSize, _maxRetrieved); UTimer timeGetN; unsigned int nbLoadedFromDb = 0; std::set<int> reactivatedIdsSet; std::map<int, int> neighbors; int nbDirectNeighborsInDb = 0; // priority in time // Direct neighbors TIME ULOGGER_DEBUG("In TIME"); neighbors = _memory->getNeighborsId(retrievalId, neighborhoodSize, _maxRetrieved, true, true, false, true, std::set<int>(), &timeGetNeighborsTimeDb); ULOGGER_DEBUG("neighbors of %d in time = %d", retrievalId, (int)neighbors.size()); //Priority to locations near in time (direct neighbor) then by space (loop closure) bool firstPassDone = false; // just to avoid checking to STM after the first pass int m = 0; while(m < neighborhoodSize) { std::set<int> idsSorted; for(std::map<int, int>::iterator iter=neighbors.begin(); iter!=neighbors.end();) { if(!firstPassDone && _memory->isInSTM(iter->first)) { neighbors.erase(iter++); } else if(iter->second == m) { if(reactivatedIdsSet.find(iter->first) == reactivatedIdsSet.end()) { idsSorted.insert(iter->first); reactivatedIdsSet.insert(iter->first); if(m == 1 && _memory->getSignature(iter->first) == 0) { ++nbDirectNeighborsInDb; } //immunized locations in the neighborhood from being transferred if(immunizedLocations.insert(iter->first).second) { ++immunizedGlobally; } //UDEBUG("nt=%d m=%d immunized=1", iter->first, iter->second); } neighbors.erase(iter++); } else { ++iter; } } firstPassDone = true; reactivatedIds.insert(reactivatedIds.end(), idsSorted.rbegin(), idsSorted.rend()); ++m; } // neighbors SPACE, already added direct neighbors will be ignored ULOGGER_DEBUG("In SPACE"); neighbors = _memory->getNeighborsId(retrievalId, neighborhoodSize, _maxRetrieved, true, false, false, false, std::set<int>(), &timeGetNeighborsSpaceDb); ULOGGER_DEBUG("neighbors of %d in space = %d", retrievalId, (int)neighbors.size()); firstPassDone = false; m = 0; while(m < neighborhoodSize) { std::set<int> idsSorted; for(std::map<int, int>::iterator iter=neighbors.begin(); iter!=neighbors.end();) { if(!firstPassDone && _memory->isInSTM(iter->first)) { neighbors.erase(iter++); } else if(iter->second == m) { if(reactivatedIdsSet.find(iter->first) == reactivatedIdsSet.end()) { idsSorted.insert(iter->first); reactivatedIdsSet.insert(iter->first); if(m == 1 && _memory->getSignature(iter->first) == 0) { ++nbDirectNeighborsInDb; } //UDEBUG("nt=%d m=%d", iter->first, iter->second); } neighbors.erase(iter++); } else { ++iter; } } firstPassDone = true; reactivatedIds.insert(reactivatedIds.end(), idsSorted.rbegin(), idsSorted.rend()); ++m; } ULOGGER_INFO("neighborhoodSize=%d, " "reactivatedIds.size=%d, " "nbLoadedFromDb=%d, " "nbDirectNeighborsInDb=%d, " "time=%fs (%fs %fs)", neighborhoodSize, reactivatedIds.size(), (int)nbLoadedFromDb, nbDirectNeighborsInDb, timeGetN.ticks(), timeGetNeighborsTimeDb, timeGetNeighborsSpaceDb); } } //============================================================ // RETRIEVAL 2/3 : Update planned path and get next nodes to retrieve //============================================================ std::list<int> retrievalLocalIds; if(_rgbdSlamMode) { // Priority on locations on the planned path if(_path.size()) { updateGoalIndex(); float distanceSoFar = 0.0f; // immunize all nodes after current node and // retrieve nodes after current node in the maximum radius from the current node for(unsigned int i=_pathCurrentIndex; i<_path.size(); ++i) { if(_localRadius > 0.0f && i != _pathCurrentIndex) { distanceSoFar += _path[i-1].second.getDistance(_path[i].second); } if(distanceSoFar <= _localRadius) { if(_memory->getSignature(_path[i].first) != 0) { if(immunizedLocations.insert(_path[i].first).second) { ++immunizedLocally; } UDEBUG("Path immunization: node %d (dist=%fm)", _path[i].first, distanceSoFar); } else if(retrievalLocalIds.size() < _maxLocalRetrieved) { UINFO("retrieval of node %d on path (dist=%fm)", _path[i].first, distanceSoFar); retrievalLocalIds.push_back(_path[i].first); // retrieved locations are automatically immunized } } else { UDEBUG("Stop on node %d (dist=%fm > %fm)", _path[i].first, distanceSoFar, _localRadius); break; } } } if(!(_memory->allNodesInWM() && maxLocalLocationsImmunized == 0)) { // immunize the path from the nearest local location to the current location if(immunizedLocally < maxLocalLocationsImmunized && _memory->isIncremental()) // Can only work in mapping mode { std::map<int ,Transform> poses; // remove poses from STM for(std::map<int, Transform>::iterator iter=_optimizedPoses.begin(); iter!=_optimizedPoses.end(); ++iter) { if(iter->first > 0 && !_memory->isInSTM(iter->first)) { poses.insert(*iter); } } int nearestId = graph::findNearestNode(poses, _optimizedPoses.at(signature->id())); if(nearestId > 0 && (_localRadius==0 || _optimizedPoses.at(signature->id()).getDistance(_optimizedPoses.at(nearestId)) < _localRadius)) { std::multimap<int, int> links; for(std::multimap<int, Link>::iterator iter=_constraints.begin(); iter!=_constraints.end(); ++iter) { if(uContains(_optimizedPoses, iter->second.from()) && uContains(_optimizedPoses, iter->second.to())) { links.insert(std::make_pair(iter->second.from(), iter->second.to())); links.insert(std::make_pair(iter->second.to(), iter->second.from())); // <-> } } std::list<std::pair<int, Transform> > path = graph::computePath(_optimizedPoses, links, nearestId, signature->id()); if(path.size() == 0) { UWARN("Could not compute a path between %d and %d", nearestId, signature->id()); } else { for(std::list<std::pair<int, Transform> >::iterator iter=path.begin(); iter!=path.end(); ++iter) { if(iter->first>0) { if(immunizedLocally >= maxLocalLocationsImmunized) { // set 20 to avoid this warning when starting mapping if(maxLocalLocationsImmunized > 20 && _someNodesHaveBeenTransferred) { UWARN("Could not immunize the whole local path (%d) between " "%d and %d (max location immunized=%d). You may want " "to increase RGBD/LocalImmunizationRatio (current=%f (%d of WM=%d)) " "to be able to immunize longer paths.", (int)path.size(), nearestId, signature->id(), maxLocalLocationsImmunized, _localImmunizationRatio, maxLocalLocationsImmunized, (int)_memory->getWorkingMem().size()); } break; } else if(!_memory->isInSTM(iter->first)) { if(immunizedLocations.insert(iter->first).second) { ++immunizedLocally; } //UDEBUG("local node %d on path immunized=1", iter->first); } } } } } } // retrieval based on the nodes close the the nearest pose in WM // immunize closest nodes std::map<int, float> nearNodes = graph::getNodesInRadius(signature->id(), _optimizedPoses, _localRadius); // sort by distance std::multimap<float, int> nearNodesByDist; for(std::map<int, float>::iterator iter=nearNodes.lower_bound(1); iter!=nearNodes.end(); ++iter) { nearNodesByDist.insert(std::make_pair(iter->second, iter->first)); } UINFO("near nodes=%d, max local immunized=%d, ratio=%f WM=%d", (int)nearNodesByDist.size(), maxLocalLocationsImmunized, _localImmunizationRatio, (int)_memory->getWorkingMem().size()); for(std::multimap<float, int>::iterator iter=nearNodesByDist.begin(); iter!=nearNodesByDist.end() && (retrievalLocalIds.size() < _maxLocalRetrieved || immunizedLocally < maxLocalLocationsImmunized); ++iter) { const Signature * s = _memory->getSignature(iter->second); if(s!=0) { // If there is a change of direction, better to be retrieving // ALL nearest signatures than only newest neighbors const std::multimap<int, Link> & links = s->getLinks(); for(std::multimap<int, Link>::const_reverse_iterator jter=links.rbegin(); jter!=links.rend() && retrievalLocalIds.size() < _maxLocalRetrieved; ++jter) { if(_memory->getSignature(jter->first) == 0) { UINFO("retrieval of node %d on local map", jter->first); retrievalLocalIds.push_back(jter->first); } } if(!_memory->isInSTM(s->id()) && immunizedLocally < maxLocalLocationsImmunized) { if(immunizedLocations.insert(s->id()).second) { ++immunizedLocally; } //UDEBUG("local node %d (%f m) immunized=1", iter->second, iter->first); } } } // well, if the maximum retrieved is not reached, look for neighbors in database if(retrievalLocalIds.size() < _maxLocalRetrieved) { std::set<int> retrievalLocalIdsSet(retrievalLocalIds.begin(), retrievalLocalIds.end()); for(std::list<int>::iterator iter=retrievalLocalIds.begin(); iter!=retrievalLocalIds.end() && retrievalLocalIds.size() < _maxLocalRetrieved; ++iter) { std::map<int, int> ids = _memory->getNeighborsId(*iter, 2, _maxLocalRetrieved - (unsigned int)retrievalLocalIds.size() + 1, true, false); for(std::map<int, int>::reverse_iterator jter=ids.rbegin(); jter!=ids.rend() && retrievalLocalIds.size() < _maxLocalRetrieved; ++jter) { if(_memory->getSignature(jter->first) == 0 && retrievalLocalIdsSet.find(jter->first) == retrievalLocalIdsSet.end()) { UINFO("retrieval of node %d on local map", jter->first); retrievalLocalIds.push_back(jter->first); retrievalLocalIdsSet.insert(jter->first); } } } } // update Age of the close signatures (oldest the farthest) for(std::multimap<float, int>::reverse_iterator iter=nearNodesByDist.rbegin(); iter!=nearNodesByDist.rend(); ++iter) { _memory->updateAge(iter->second); } // insert them first to make sure they are loaded. reactivatedIds.insert(reactivatedIds.begin(), retrievalLocalIds.begin(), retrievalLocalIds.end()); } //============================================================ // RETRIEVAL 3/3 : Load signatures from the database //============================================================ if(reactivatedIds.size()) { // Not important if the loop closure hypothesis don't have all its neighbors loaded, // only a loop closure link is added... signaturesRetrieved = _memory->reactivateSignatures( reactivatedIds, _maxRetrieved+(unsigned int)retrievalLocalIds.size(), // add path retrieved timeRetrievalDbAccess); ULOGGER_INFO("retrieval of %d (db time = %fs)", (int)signaturesRetrieved.size(), timeRetrievalDbAccess); timeRetrievalDbAccess += timeGetNeighborsTimeDb + timeGetNeighborsSpaceDb; UINFO("total timeRetrievalDbAccess=%fs", timeRetrievalDbAccess); // Immunize just retrieved signatures immunizedLocations.insert(signaturesRetrieved.begin(), signaturesRetrieved.end()); } timeReactivations = timer.ticks(); ULOGGER_INFO("timeReactivations=%fs", timeReactivations); } //============================================================= // Update loop closure links // (updated: place this after retrieval to be sure that neighbors of the loop closure are in RAM) //============================================================= std::list<std::pair<int, int> > loopClosureLinksAdded; int loopClosureVisualInliers = 0; // for statistics int loopClosureVisualMatches = 0; float loopClosureLinearVariance = 0.0f; float loopClosureAngularVariance = 0.0f; float loopClosureVisualInliersMeanDist = 0; float loopClosureVisualInliersDistribution = 0; if(_loopClosureHypothesis.first>0) { //Compute transform if metric data are present Transform transform; RegistrationInfo info; info.covariance = cv::Mat::eye(6,6,CV_64FC1); if(_rgbdSlamMode) { transform = _memory->computeTransform(_loopClosureHypothesis.first, signature->id(), Transform(), &info); loopClosureVisualInliersMeanDist = info.inliersMeanDistance; loopClosureVisualInliersDistribution = info.inliersDistribution; loopClosureVisualInliers = info.inliers; loopClosureVisualMatches = info.matches; rejectedHypothesis = transform.isNull(); if(rejectedHypothesis) { UWARN("Rejected loop closure %d -> %d: %s", _loopClosureHypothesis.first, signature->id(), info.rejectedMsg.c_str()); } else if(_maxLoopClosureDistance>0.0f && transform.getNorm() > _maxLoopClosureDistance) { rejectedHypothesis = true; UWARN("Rejected localization %d -> %d because distance to map (%fm) is over %s=%fm.", _loopClosureHypothesis.first, signature->id(), transform.getNorm(), Parameters::kRGBDMaxLoopClosureDistance().c_str(), _maxLoopClosureDistance); } else { transform = transform.inverse(); } } if(!rejectedHypothesis) { // Make the new one the parent of the old one UASSERT(info.covariance.at<double>(0,0) > 0.0 && info.covariance.at<double>(5,5) > 0.0); cv::Mat information = getInformation(info.covariance); loopClosureLinearVariance = 1.0/information.at<double>(0,0); loopClosureAngularVariance = 1.0/information.at<double>(5,5); rejectedHypothesis = !_memory->addLink(Link(signature->id(), _loopClosureHypothesis.first, Link::kGlobalClosure, transform, information)); if(!rejectedHypothesis) { loopClosureLinksAdded.push_back(std::make_pair(signature->id(), _loopClosureHypothesis.first)); } } if(rejectedHypothesis) { _loopClosureHypothesis.first = 0; } } timeAddLoopClosureLink = timer.ticks(); ULOGGER_INFO("timeAddLoopClosureLink=%fs", timeAddLoopClosureLink); //============================================================ // Landmark //============================================================ int landmarkDetected = 0; std::set<int> landmarkDetectedNodesRef; if(!signature->getLandmarks().empty()) { for(std::map<int, Link>::const_iterator iter=signature->getLandmarks().begin(); iter!=signature->getLandmarks().end(); ++iter) { if(uContains(_memory->getLandmarksInvertedIndex(), iter->first) && _memory->getLandmarksInvertedIndex().find(iter->first)->second.size()>1) { landmarkDetected = iter->first; landmarkDetectedNodesRef = _memory->getLandmarksInvertedIndex().find(iter->first)->second; UINFO("Landmark %d observed again! Seen the first time by node %d.", -iter->first, *landmarkDetectedNodesRef.begin()); break; } } } int proximityDetectionsAddedVisually = 0; int proximityDetectionsAddedByICPOnly = 0; int lastProximitySpaceClosureId = 0; int proximitySpacePaths = 0; int localVisualPathsChecked = 0; int localScanPathsChecked = 0; if(_proximityBySpace && _localRadius > 0 && _rgbdSlamMode && signature->getWeight() >= 0) // not an intermediate node { if(_graphOptimizer->iterations() == 0) { UWARN("Cannot do local loop closure detection in space if graph optimization is disabled!"); } else if(_memory->isIncremental() || (_loopClosureHypothesis.first == 0 && landmarkDetected == 0)) { // In localization mode, no need to check local loop // closures if we are already localized by a global closure. // don't do it if it is a small displacement unless the previous signature didn't have a loop closure // don't do it if there is a too fast movement if((!smallDisplacement || _memory->getLoopClosureLinks(previousId, false).size() == 0) && !tooFastMovement) { //============================================================ // LOCAL LOOP CLOSURE SPACE //============================================================ // // 1) compare visually with nearest locations // UDEBUG("Proximity detection (local loop closure in SPACE using matching images, local radius=%fm)", _localRadius); std::map<int, float> nearestIds; if(_memory->isIncremental() && _proximityMaxGraphDepth > 0) { nearestIds = _memory->getNeighborsIdRadius(signature->id(), _localRadius, _optimizedPoses, _proximityMaxGraphDepth); } else { nearestIds = graph::getNodesInRadius(signature->id(), _optimizedPoses, _localRadius); } UDEBUG("nearestIds=%d/%d", (int)nearestIds.size(), (int)_optimizedPoses.size()); std::map<int, Transform> nearestPoses; for(std::map<int, float>::iterator iter=nearestIds.lower_bound(1); iter!=nearestIds.end(); ++iter) { if(_memory->getStMem().find(iter->first) == _memory->getStMem().end()) { nearestPoses.insert(std::make_pair(iter->first, _optimizedPoses.at(iter->first))); } } UDEBUG("nearestPoses=%d", (int)nearestPoses.size()); // segment poses by paths, only one detection per path, landmarks are ignored std::map<int, std::map<int, Transform> > nearestPathsNotSorted = getPaths(nearestPoses, _optimizedPoses.at(signature->id()), _proximityMaxGraphDepth); UDEBUG("got %d paths", (int)nearestPathsNotSorted.size()); // sort nearest paths by highest likelihood (if two have same likelihood, sort by id) std::map<NearestPathKey, std::map<int, Transform> > nearestPaths; for(std::map<int, std::map<int, Transform> >::const_iterator iter=nearestPathsNotSorted.begin();iter!=nearestPathsNotSorted.end(); ++iter) { const std::map<int, Transform> & path = iter->second; float highestLikelihood = 0.0f; for(std::map<int, Transform>::const_iterator jter=path.begin(); jter!=path.end(); ++jter) { float v = uValue(likelihood, jter->first, 0.0f); if(v > highestLikelihood) { highestLikelihood = v; } } nearestPaths.insert(std::make_pair(NearestPathKey(highestLikelihood, iter->first), path)); } UDEBUG("nearestPaths=%d proximityMaxPaths=%d", (int)nearestPaths.size(), _proximityMaxPaths); float proximityFilteringRadius = _proximityFilteringRadius; if(_maxLoopClosureDistance>0.0f && (proximityFilteringRadius <= 0.0f || _maxLoopClosureDistance<proximityFilteringRadius)) { proximityFilteringRadius = _maxLoopClosureDistance; } for(std::map<NearestPathKey, std::map<int, Transform> >::const_reverse_iterator iter=nearestPaths.rbegin(); iter!=nearestPaths.rend() && (_memory->isIncremental() || lastProximitySpaceClosureId == 0) && (_proximityMaxPaths <= 0 || localVisualPathsChecked < _proximityMaxPaths); ++iter) { std::map<int, Transform> path = iter->second; UASSERT(path.size()); //find the nearest pose on the path looking in the same direction path.insert(std::make_pair(signature->id(), _optimizedPoses.at(signature->id()))); path = graph::getPosesInRadius(signature->id(), path, _localRadius, _proximityAngle); //take the one with highest likelihood if not null int nearestId = 0; if(iter->first.likelihood > 0.0f && path.find(iter->first.id)!=path.end()) { nearestId = iter->first.id; } else { nearestId = rtabmap::graph::findNearestNode(path, _optimizedPoses.at(signature->id())); } if(nearestId > 0) { // nearest pose must not be linked to current location and enough close if(!signature->hasLink(nearestId) && (proximityFilteringRadius <= 0.0f || _optimizedPoses.at(signature->id()).getDistanceSquared(_optimizedPoses.at(nearestId)) < proximityFilteringRadius*proximityFilteringRadius)) { ++localVisualPathsChecked; RegistrationInfo info; // guess is null to make sure visual correspondences are globally computed Transform transform = _memory->computeTransform(nearestId, signature->id(), Transform(), &info); if(!transform.isNull()) { transform = transform.inverse(); if(proximityFilteringRadius <= 0 || transform.getNormSquared() <= proximityFilteringRadius*proximityFilteringRadius) { UINFO("[Visual] Add local loop closure in SPACE (%d->%d) %s", signature->id(), nearestId, transform.prettyPrint().c_str()); UASSERT(info.covariance.at<double>(0,0) > 0.0 && info.covariance.at<double>(5,5) > 0.0); cv::Mat information = getInformation(info.covariance); _memory->addLink(Link(signature->id(), nearestId, Link::kGlobalClosure, transform, information)); loopClosureLinksAdded.push_back(std::make_pair(signature->id(), nearestId)); if(_loopClosureHypothesis.first == 0) { if(proximityDetectionsAddedVisually == 0) { loopClosureVisualInliersMeanDist = info.inliersMeanDistance; loopClosureVisualInliersDistribution = info.inliersDistribution; } ++proximityDetectionsAddedVisually; lastProximitySpaceClosureId = nearestId; loopClosureVisualInliers = info.inliers; loopClosureVisualMatches = info.matches; loopClosureLinearVariance = 1.0/information.at<double>(0,0); loopClosureAngularVariance = 1.0/information.at<double>(5,5); } } else { UWARN("Ignoring local loop closure with %d because resulting " "transform is too large!? (%fm > %fm)", nearestId, transform.getNorm(), proximityFilteringRadius); } } } } } timeProximityBySpaceVisualDetection = timer.ticks(); ULOGGER_INFO("timeProximityBySpaceVisualDetection=%fs", timeProximityBySpaceVisualDetection); // // 2) compare locally with nearest locations by scan matching // UDEBUG("Proximity detection (local loop closure in SPACE with scan matching)"); if( _proximityMaxNeighbors <= 0) { UDEBUG("Proximity by scan matching is disabled (%s=%d).", Parameters::kRGBDProximityPathMaxNeighbors().c_str(), _proximityMaxNeighbors); } else if(!signature->sensorData().laserScanCompressed().isEmpty() && (_memory->isIncremental() || lastProximitySpaceClosureId == 0)) { // In localization mode, no need to check local loop // closures if we are already localized by at least one // local visual closure above. proximitySpacePaths = (int)nearestPaths.size(); for(std::map<NearestPathKey, std::map<int, Transform> >::const_reverse_iterator iter=nearestPaths.rbegin(); iter!=nearestPaths.rend() && (_memory->isIncremental() || lastProximitySpaceClosureId == 0) && (_proximityMaxPaths <= 0 || localScanPathsChecked < _proximityMaxPaths); ++iter) { std::map<int, Transform> path = iter->second; // should contain only nodes (no landmarks) UASSERT(path.size()); UASSERT(path.begin()->first > 0); //find the nearest pose on the path int nearestId = rtabmap::graph::findNearestNode(path, _optimizedPoses.at(signature->id())); UASSERT(nearestId > 0); //UDEBUG("Path %d (size=%d) distance=%fm", nearestId, (int)path.size(), _optimizedPoses.at(signature->id()).getDistance(_optimizedPoses.at(nearestId))); // nearest pose must be close and not linked to current location if(!signature->hasLink(nearestId)) { if(_proximityMaxNeighbors < _proximityMaxGraphDepth || _proximityMaxGraphDepth == 0) { std::map<int, Transform> filteredPath; int i=0; std::map<int, Transform>::iterator nearestIdIter = path.find(nearestId); // "_proximityMaxNeighbors-1" means that if _proximityMaxNeighbors=1, // only nearest node on the path is taken (no scan merging). Useful to find // proximity detection between only 2 nodes with 360x360 lidar scans. for(std::map<int, Transform>::iterator iter=nearestIdIter; iter!=path.end() && i<=_proximityMaxNeighbors-1; ++iter, ++i) { filteredPath.insert(*iter); } i=1; for(std::map<int, Transform>::reverse_iterator iter(nearestIdIter); iter!=path.rend() && i<=_proximityMaxNeighbors-1; ++iter, ++i) { filteredPath.insert(*iter); } path = filteredPath; } // Assemble scans in the path and do ICP only std::map<int, Transform> optimizedLocalPath; if(_proximityRawPosesUsed) { //optimize the path's poses locally cv::Mat covariance; path = optimizeGraph(nearestId, uKeysSet(path), std::map<int, Transform>(), false, covariance); // transform local poses in optimized graph referential UASSERT(uContains(path, nearestId)); Transform t = _optimizedPoses.at(nearestId) * path.at(nearestId).inverse(); for(std::map<int, Transform>::iterator jter=path.lower_bound(1); jter!=path.end(); ++jter) { optimizedLocalPath.insert(std::make_pair(jter->first, t * jter->second)); } } else { optimizedLocalPath = path; } std::map<int, Transform> filteredPath; if(optimizedLocalPath.size() > 2 && proximityFilteringRadius > 0.0f) { // path filtering filteredPath = graph::radiusPosesFiltering(optimizedLocalPath, proximityFilteringRadius, 0, true); // make sure the current pose is still here filteredPath.insert(*optimizedLocalPath.find(nearestId)); } else { filteredPath = optimizedLocalPath; } if(filteredPath.size() > 0) { // add current node to poses filteredPath.insert(std::make_pair(signature->id(), _optimizedPoses.at(signature->id()))); //The nearest will be the reference for a loop closure transform if(signature->getLinks().find(nearestId) == signature->getLinks().end()) { ++localScanPathsChecked; RegistrationInfo info; Transform transform = _memory->computeIcpTransformMulti(signature->id(), nearestId, filteredPath, &info); if(!transform.isNull()) { UINFO("[Scan matching] Add local loop closure in SPACE (%d->%d) %s", signature->id(), nearestId, transform.prettyPrint().c_str()); cv::Mat scanMatchingIds; if(_scanMatchingIdsSavedInLinks) { std::stringstream stream; stream << "SCANS:"; for(std::map<int, Transform>::iterator iter=optimizedLocalPath.begin(); iter!=optimizedLocalPath.end(); ++iter) { if(iter != optimizedLocalPath.begin()) { stream << ";"; } stream << uNumber2Str(iter->first); } std::string scansStr = stream.str(); scanMatchingIds = cv::Mat(1, int(scansStr.size()+1), CV_8SC1, (void *)scansStr.c_str()); scanMatchingIds = compressData2(scanMatchingIds); // compressed } // set Identify covariance for laser scan matching only UASSERT(info.covariance.at<double>(0,0) > 0.0 && info.covariance.at<double>(5,5) > 0.0); _memory->addLink(Link(signature->id(), nearestId, Link::kLocalSpaceClosure, transform, getInformation(info.covariance)/100.0, scanMatchingIds)); loopClosureLinksAdded.push_back(std::make_pair(signature->id(), nearestId)); ++proximityDetectionsAddedByICPOnly; // no local loop closure added visually if(proximityDetectionsAddedVisually == 0 && _loopClosureHypothesis.first == 0) { lastProximitySpaceClosureId = nearestId; } } else { UINFO("Local scan matching rejected: %s", info.rejectedMsg.c_str()); } } } } else { //UDEBUG("Path %d ignored", nearestId); } } } } } } timeProximityBySpaceDetection = timer.ticks(); ULOGGER_INFO("timeProximityBySpaceDetection=%fs", timeProximityBySpaceDetection); //============================================================ // Add virtual links if a path is activated //============================================================ if(_path.size()) { // Add a virtual loop closure link to keep the path linked to local map if( signature->id() != _path[_pathCurrentIndex].first && !signature->hasLink(_path[_pathCurrentIndex].first)) { UASSERT(uContains(_optimizedPoses, signature->id())); UASSERT_MSG(uContains(_optimizedPoses, _path[_pathCurrentIndex].first), uFormat("id=%d", _path[_pathCurrentIndex].first).c_str()); Transform virtualLoop = _optimizedPoses.at(signature->id()).inverse() * _optimizedPoses.at(_path[_pathCurrentIndex].first); if(_localRadius == 0.0f || virtualLoop.getNorm() < _localRadius) { _memory->addLink(Link(signature->id(), _path[_pathCurrentIndex].first, Link::kVirtualClosure, virtualLoop, cv::Mat::eye(6,6,CV_64FC1)*0.01)); // set high variance } else { UERROR("Virtual link larger than local radius (%fm > %fm). Aborting the plan!", virtualLoop.getNorm(), _localRadius); this->clearPath(-1); } } } //============================================================ // Optimize map graph //============================================================ float maxLinearError = 0.0f; float maxLinearErrorRatio = 0.0f; float maxAngularError = 0.0f; float maxAngularErrorRatio = 0.0f; double optimizationError = 0.0; int optimizationIterations = 0; cv::Mat localizationCovariance; if(_rgbdSlamMode && (_loopClosureHypothesis.first>0 || lastProximitySpaceClosureId>0 || // can be different map of the current one statistics_.reducedIds().size() || (signature->hasLink(signature->id(), Link::kPosePrior) && !_graphOptimizer->priorsIgnored()) || // prior edge (signature->hasLink(signature->id(), Link::kGravity) && _graphOptimizer->gravitySigma()>0.0f) || // gravity edge proximityDetectionsInTimeFound>0 || landmarkDetected!=0 || signaturesRetrieved.size()) // can be different map of the current one && (_memory->isIncremental() || graph::filterLinks(signature->getLinks(), Link::kSelfRefLink).size())) // In localization mode, the new node should be linked { UASSERT(uContains(_optimizedPoses, signature->id())); //used in localization mode: filter virtual links std::multimap<int, Link> localizationLinks = graph::filterLinks(signature->getLinks(), Link::kVirtualClosure); localizationLinks = graph::filterLinks(localizationLinks, Link::kSelfRefLink); if(landmarkDetected!=0 && !_memory->isIncremental() && _optimizedPoses.find(landmarkDetected)!=_optimizedPoses.end()) { UASSERT(uContains(signature->getLandmarks(), landmarkDetected)); localizationLinks.insert(std::make_pair(landmarkDetected, signature->getLandmarks().at(landmarkDetected))); } // Note that in localization mode, we don't re-optimize the graph // if: // 1- there are no signatures retrieved, // 2- we are relocalizing on a node already in the optimized graph if(!_memory->isIncremental() && signaturesRetrieved.size() == 0 && localizationLinks.size() && uContains(_optimizedPoses, localizationLinks.begin()->first)) { bool rejectLocalization = false; if(!_odomCachePoses.empty() && _optimizationMaxError > 0.0f) { // Verify if the new localization is valid by checking if there is // not too much deformation in odometry poses since previous localization std::map<int, Transform>::iterator iter = _optimizedPoses.find(_odomCacheConstraints.find(_odomCachePoses.begin()->first)->second.to()); Transform optPoseRefA; Transform optPoseRefB; if(iter != _optimizedPoses.end()) { optPoseRefA = iter->second * _odomCacheConstraints.find(_odomCachePoses.begin()->first)->second.transform().inverse(); } iter = _optimizedPoses.find(localizationLinks.begin()->first); if(iter != _optimizedPoses.end()) { optPoseRefB = iter->second * localizationLinks.begin()->second.transform().inverse(); } if(optPoseRefA.isNull() || optPoseRefB.isNull()) { UWARN("Both optimized pose references are null! Flushing cached odometry poses. Localization won't be verified."); _odomCachePoses.clear(); _constraints.clear(); } else { std::multimap<int, Link> constraints = _odomCacheConstraints; constraints.erase(_odomCachePoses.begin()->first); constraints.insert(std::make_pair(_odomCachePoses.begin()->first, Link(_odomCachePoses.begin()->first, signature->id(), Link::kVirtualClosure, optPoseRefA.inverse() * optPoseRefB, cv::Mat::eye(6,6,CV_64FC1)*100))); std::map<int, Transform> optPoses = _graphOptimizer->optimize(signature->id(), _odomCachePoses, constraints); if(optPoses.empty()) { UWARN("Optimization failed, rejecting localization!"); rejectLocalization = true; } else { UINFO("Compute max graph errors..."); const Link * maxLinearLink = 0; const Link * maxAngularLink = 0; graph::computeMaxGraphErrors( optPoses, constraints, maxLinearErrorRatio, maxAngularErrorRatio, maxLinearError, maxAngularError, &maxLinearLink, &maxAngularLink); if(maxLinearLink == 0 && maxAngularLink==0) { UWARN("Could not compute graph errors! Wrong loop closures could be accepted!"); } if(maxLinearLink) { UINFO("Max optimization linear error = %f m (link %d->%d, var=%f, ratio error/std=%f)", maxLinearError, maxLinearLink->from(), maxLinearLink->to(), maxLinearLink->transVariance(), maxLinearError/sqrt(maxLinearLink->transVariance())); if(maxLinearErrorRatio > _optimizationMaxError) { UWARN("Rejecting localization (%d <-> %d) in this " "iteration because a wrong loop closure has been " "detected after graph optimization, resulting in " "a maximum graph error ratio of %f (edge %d->%d, type=%d, abs error=%f m, stddev=%f). The " "maximum error ratio parameter \"%s\" is %f of std deviation.", loopClosureLinksAdded.front().first, loopClosureLinksAdded.front().second, maxLinearErrorRatio, maxLinearLink->from(), maxLinearLink->to(), maxLinearLink->type(), maxLinearError, sqrt(maxLinearLink->transVariance()), Parameters::kRGBDOptimizeMaxError().c_str(), _optimizationMaxError); rejectLocalization = true; } } if(maxAngularLink) { UINFO("Max optimization angular error = %f deg (link %d->%d, var=%f, ratio error/std=%f)", maxAngularError*180.0f/CV_PI, maxAngularLink->from(), maxAngularLink->to(), maxAngularLink->rotVariance(), maxAngularError/sqrt(maxAngularLink->rotVariance())); if(maxAngularErrorRatio > _optimizationMaxError) { UWARN("Rejecting localization (%d <-> %d) in this " "iteration because a wrong loop closure has been " "detected after graph optimization, resulting in " "a maximum graph error ratio of %f (edge %d->%d, type=%d, abs error=%f deg, stddev=%f). The " "maximum error ratio parameter \"%s\" is %f of std deviation.", loopClosureLinksAdded.front().first, loopClosureLinksAdded.front().second, maxAngularErrorRatio, maxAngularLink->from(), maxAngularLink->to(), maxAngularLink->type(), maxAngularError*180.0f/CV_PI, sqrt(maxAngularLink->rotVariance()), Parameters::kRGBDOptimizeMaxError().c_str(), _optimizationMaxError); rejectLocalization = true; } } } } } if(!rejectLocalization) { // If there are no signatures retrieved, we don't // need to re-optimize the graph. Just update the last // position if OptimizeFromGraphEnd=false or transform the // whole graph if OptimizeFromGraphEnd=true UINFO("Localization without map optimization"); if(_optimizeFromGraphEnd) { // update all previous nodes // Normally _mapCorrection should be identity, but if _optimizeFromGraphEnd // parameters just changed state, we should put back all poses without map correction. Transform oldPose = _optimizedPoses.at(localizationLinks.begin()->first); Transform mapCorrectionInv = _mapCorrection.inverse(); Transform u = signature->getPose() * localizationLinks.begin()->second.transform(); if(_graphOptimizer->isSlam2d()) { // in case of 3d landmarks, transform constraint to 2D u = u.to3DoF(); } else if(_graphOptimizer->gravitySigma() > 0) { // Adjust transform with gravity Transform transform = localizationLinks.begin()->second.transform(); int loopId = localizationLinks.begin()->first; if(loopId < 0) { //For landmarks, use transform against other node looking the landmark // (because we don't assume that landmarks are aligned with gravity) int landmarkId = loopId; UASSERT(!landmarkDetectedNodesRef.empty()); loopId = *landmarkDetectedNodesRef.begin(); const Signature * loopS = _memory->getSignature(loopId); transform = transform * loopS->getLandmarks().at(landmarkId).transform().inverse(); UASSERT(_optimizedPoses.find(loopId) != _optimizedPoses.end()); oldPose = _optimizedPoses.at(loopId); } const Signature * loopS = _memory->getSignature(loopId); UASSERT(loopS !=0); std::multimap<int, Link>::const_iterator iterGravityLoop = graph::findLink(loopS->getLinks(), loopS->id(), loopS->id(), false, Link::kGravity); std::multimap<int, Link>::const_iterator iterGravitySign = graph::findLink(signature->getLinks(), signature->id(), signature->id(), false, Link::kGravity); if(iterGravityLoop!=loopS->getLinks().end() && iterGravitySign!=signature->getLinks().end()) { float roll,pitch,yaw; iterGravityLoop->second.transform().getEulerAngles(roll, pitch, yaw); Transform targetRotation = iterGravitySign->second.transform().rotation()*transform.rotation(); targetRotation = Transform(0,0,0,roll,pitch,targetRotation.theta()); Transform error = transform.rotation().inverse() * iterGravitySign->second.transform().rotation().inverse() * targetRotation; transform *= error; u = signature->getPose() * transform; } else { UWARN("Gravity link not found for %d and/or %d, localization won't be corrected with gravity.", loopId, signature->id()); } } Transform up = u * oldPose.inverse(); for(std::map<int, Transform>::iterator iter=_optimizedPoses.begin(); iter!=_optimizedPoses.end(); ++iter) { iter->second = mapCorrectionInv * up * iter->second; } _optimizedPoses.at(signature->id()) = signature->getPose(); } else { Transform newPose = _optimizedPoses.at(localizationLinks.begin()->first) * localizationLinks.begin()->second.transform().inverse(); if(_graphOptimizer->isSlam2d()) { // in case of 3d landmarks, transform constraint to 2D newPose = newPose.to3DoF(); } else if(_graphOptimizer->gravitySigma() > 0) { // Adjust transform with gravity Transform transform = localizationLinks.begin()->second.transform(); int loopId = localizationLinks.begin()->first; if(loopId < 0) { //For landmarks, use transform against other node looking the landmark // (because we don't assume that landmarks are aligned with gravity) int landmarkId = loopId; UASSERT(!landmarkDetectedNodesRef.empty()); loopId = *landmarkDetectedNodesRef.begin(); const Signature * loopS = _memory->getSignature(loopId); transform = transform * loopS->getLandmarks().at(landmarkId).transform().inverse(); } const Signature * loopS = _memory->getSignature(loopId); UASSERT(loopS !=0); std::multimap<int, Link>::const_iterator iterGravityLoop = graph::findLink(loopS->getLinks(), loopS->id(), loopS->id(), false, Link::kGravity); std::multimap<int, Link>::const_iterator iterGravitySign = graph::findLink(signature->getLinks(), signature->id(), signature->id(), false, Link::kGravity); if(iterGravityLoop!=loopS->getLinks().end() && iterGravitySign!=signature->getLinks().end()) { float roll,pitch,yaw; iterGravityLoop->second.transform().getEulerAngles(roll, pitch, yaw); Transform targetRotation = iterGravitySign->second.transform().rotation()*transform.rotation(); targetRotation = Transform(0,0,0,roll,pitch,targetRotation.theta()); Transform error = transform.rotation().inverse() * iterGravitySign->second.transform().rotation().inverse() * targetRotation; transform *= error; newPose = _optimizedPoses.at(loopId) * transform.inverse(); } else { UWARN("Gravity link not found for %d and/or %d, localization won't be corrected with gravity.", loopId, signature->id()); } } _optimizedPoses.at(signature->id()) = newPose; } localizationCovariance = localizationLinks.begin()->second.infMatrix().inv(); _odomCachePoses.clear(); _odomCacheConstraints.clear(); if(_optimizationMaxError > 0.0f && _maxOdomCacheSize > 0) { _odomCachePoses.insert(std::make_pair(signature->id(), signature->getPose())); _odomCacheConstraints.insert(std::make_pair(signature->id(), localizationLinks.begin()->second)); } } else { _loopClosureHypothesis.first = 0; lastProximitySpaceClosureId = 0; rejectedHypothesis = true; } } else { UINFO("Update map correction"); std::map<int, Transform> poses = _optimizedPoses; // if _optimizeFromGraphEnd parameter just changed state, don't use optimized poses as guess float normMapCorrection = _mapCorrection.getNormSquared(); // use distance for identity detection if((normMapCorrection > 0.000001f && _optimizeFromGraphEnd) || (normMapCorrection < 0.000001f && !_optimizeFromGraphEnd)) { for(std::multimap<int, Link>::iterator iter=_constraints.begin(); iter!=_constraints.end(); ++iter) { if( iter->second.type() != Link::kNeighbor && iter->second.type() != Link::kVirtualClosure && iter->second.type() != Link::kLandmark && iter->second.type() != Link::kGravity && iter->second.type() != Link::kPosePrior) { UWARN("Optimization: clearing guess poses as %s may have changed state, now %s (normMapCorrection=%f)", Parameters::kRGBDOptimizeFromGraphEnd().c_str(), _optimizeFromGraphEnd?"true":"false", normMapCorrection); poses.clear(); break; } } } std::multimap<int, Link> constraints; cv::Mat covariance; optimizeCurrentMap(signature->id(), false, poses, covariance, &constraints, &optimizationError, &optimizationIterations); // Check added loop closures have broken the graph // (in case of wrong loop closures). bool updateConstraints = true; if(poses.empty()) { UWARN("Graph optimization failed! Rejecting last loop closures added."); for(std::list<std::pair<int, int> >::iterator iter=loopClosureLinksAdded.begin(); iter!=loopClosureLinksAdded.end(); ++iter) { _memory->removeLink(iter->first, iter->second); UWARN("Loop closure %d->%d rejected!", iter->first, iter->second); } updateConstraints = false; _loopClosureHypothesis.first = 0; lastProximitySpaceClosureId = 0; rejectedHypothesis = true; } else if(_memory->isIncremental() && // FIXME: not tested in localization mode, so do it only in mapping mode _optimizationMaxError > 0.0f && loopClosureLinksAdded.size() && optimizationIterations > 0 && constraints.size()) { UINFO("Compute max graph errors..."); const Link * maxLinearLink = 0; const Link * maxAngularLink = 0; graph::computeMaxGraphErrors( poses, constraints, maxLinearErrorRatio, maxAngularErrorRatio, maxLinearError, maxAngularError, &maxLinearLink, &maxAngularLink); if(maxLinearLink == 0 && maxAngularLink==0) { UWARN("Could not compute graph errors! Wrong loop closures could be accepted!"); } bool reject = false; if(maxLinearLink) { UINFO("Max optimization linear error = %f m (link %d->%d, var=%f, ratio error/std=%f)", maxLinearError, maxLinearLink->from(), maxLinearLink->to(), maxLinearLink->transVariance(), maxLinearError/sqrt(maxLinearLink->transVariance())); if(maxLinearErrorRatio > _optimizationMaxError) { UWARN("Rejecting all added loop closures (%d, first is %d <-> %d) in this " "iteration because a wrong loop closure has been " "detected after graph optimization, resulting in " "a maximum graph error ratio of %f (edge %d->%d, type=%d, abs error=%f m, stddev=%f). The " "maximum error ratio parameter \"%s\" is %f of std deviation.", (int)loopClosureLinksAdded.size(), loopClosureLinksAdded.front().first, loopClosureLinksAdded.front().second, maxLinearErrorRatio, maxLinearLink->from(), maxLinearLink->to(), maxLinearLink->type(), maxLinearError, sqrt(maxLinearLink->transVariance()), Parameters::kRGBDOptimizeMaxError().c_str(), _optimizationMaxError); reject = true; } } if(maxAngularLink) { UINFO("Max optimization angular error = %f deg (link %d->%d, var=%f, ratio error/std=%f)", maxAngularError*180.0f/CV_PI, maxAngularLink->from(), maxAngularLink->to(), maxAngularLink->rotVariance(), maxAngularError/sqrt(maxAngularLink->rotVariance())); if(maxAngularErrorRatio > _optimizationMaxError) { UWARN("Rejecting all added loop closures (%d, first is %d <-> %d) in this " "iteration because a wrong loop closure has been " "detected after graph optimization, resulting in " "a maximum graph error ratio of %f (edge %d->%d, type=%d, abs error=%f deg, stddev=%f). The " "maximum error ratio parameter \"%s\" is %f of std deviation.", (int)loopClosureLinksAdded.size(), loopClosureLinksAdded.front().first, loopClosureLinksAdded.front().second, maxAngularErrorRatio, maxAngularLink->from(), maxAngularLink->to(), maxAngularLink->type(), maxAngularError*180.0f/CV_PI, sqrt(maxAngularLink->rotVariance()), Parameters::kRGBDOptimizeMaxError().c_str(), _optimizationMaxError); reject = true; } } if(reject) { for(std::list<std::pair<int, int> >::iterator iter=loopClosureLinksAdded.begin(); iter!=loopClosureLinksAdded.end(); ++iter) { _memory->removeLink(iter->first, iter->second); UWARN("Loop closure %d->%d rejected!", iter->first, iter->second); } updateConstraints = false; _loopClosureHypothesis.first = 0; lastProximitySpaceClosureId = 0; rejectedHypothesis = true; } } if(updateConstraints) { UINFO("Updated local map (old size=%d, new size=%d)", (int)_optimizedPoses.size(), (int)poses.size()); _optimizedPoses = poses; _constraints = constraints; localizationCovariance = covariance; } } // Update map correction, it should be identify when optimizing from the last node UASSERT(_optimizedPoses.find(signature->id()) != _optimizedPoses.end()); if(fakeOdom && _mapCorrectionBackup.isNull()) { _mapCorrectionBackup = _mapCorrection; } _mapCorrection = _optimizedPoses.at(signature->id()) * signature->getPose().inverse(); _lastLocalizationPose = _optimizedPoses.at(signature->id()); // update if(_mapCorrection.getNormSquared() > 0.001f && _optimizeFromGraphEnd) { bool hasPrior = signature->hasLink(signature->id()); if(!_graphOptimizer->priorsIgnored()) { for(std::multimap<int, Link>::reverse_iterator iter=_constraints.rbegin(); !hasPrior && iter!=_constraints.rend(); ++iter) { if(iter->second.type() == Link::kPosePrior) { hasPrior = true; } } } if((!hasPrior || _graphOptimizer->priorsIgnored()) && _graphOptimizer->gravitySigma()==0.0f) { UERROR("Map correction should be identity when optimizing from the last node. T=%s", _mapCorrection.prettyPrint().c_str()); } } } int newLocId = _loopClosureHypothesis.first>0?_loopClosureHypothesis.first:lastProximitySpaceClosureId>0?lastProximitySpaceClosureId:0; _lastLocalizationNodeId = newLocId!=0?newLocId:_lastLocalizationNodeId; if(newLocId==0 && landmarkDetected!=0) { std::map<int, std::set<int> >::const_iterator iter = _memory->getLandmarksInvertedIndex().find(landmarkDetected); if(iter!=_memory->getLandmarksInvertedIndex().end()) { if(iter->second.size() && *iter->second.begin()!=signature->id()) { _lastLocalizationNodeId = *iter->second.begin(); } } } timeMapOptimization = timer.ticks(); ULOGGER_INFO("timeMapOptimization=%fs", timeMapOptimization); //============================================================ // Prepare statistics //============================================================ // Data used for the statistics event and for the log files int dictionarySize = 0; int refWordsCount = 0; int refUniqueWordsCount = 0; int lcHypothesisReactivated = 0; float rehearsalValue = uValue(statistics_.data(), Statistics::kMemoryRehearsal_sim(), 0.0f); int rehearsalMaxId = (int)uValue(statistics_.data(), Statistics::kMemoryRehearsal_merged(), 0.0f); sLoop = _memory->getSignature(_loopClosureHypothesis.first?_loopClosureHypothesis.first:lastProximitySpaceClosureId?lastProximitySpaceClosureId:_highestHypothesis.first); if(sLoop) { lcHypothesisReactivated = sLoop->isSaved()?1.0f:0.0f; } dictionarySize = (int)_memory->getVWDictionary()->getVisualWords().size(); refWordsCount = (int)signature->getWords().size(); refUniqueWordsCount = (int)uUniqueKeys(signature->getWords()).size(); // Posterior is empty if a bad signature is detected float vpHypothesis = posterior.size()?posterior.at(Memory::kIdVirtual):0.0f; // prepare statistics if(_loopClosureHypothesis.first || _publishStats) { ULOGGER_INFO("sending stats..."); statistics_.setRefImageId(_memory->getLastSignatureId()); // Use last id from Memory (in case of rehearsal) statistics_.setRefImageMapId(signature->mapId()); statistics_.setStamp(data.stamp()); if(_loopClosureHypothesis.first != Memory::kIdInvalid) { statistics_.setLoopClosureId(_loopClosureHypothesis.first); statistics_.setLoopClosureMapId(_memory->getMapId(_loopClosureHypothesis.first)); ULOGGER_INFO("Loop closure detected! With id=%d", _loopClosureHypothesis.first); } if(_publishStats) { ULOGGER_INFO("send all stats..."); statistics_.setExtended(1); statistics_.addStatistic(Statistics::kLoopAccepted_hypothesis_id(), _loopClosureHypothesis.first); statistics_.addStatistic(Statistics::kLoopHighest_hypothesis_id(), _highestHypothesis.first); statistics_.addStatistic(Statistics::kLoopHighest_hypothesis_value(), _highestHypothesis.second); statistics_.addStatistic(Statistics::kLoopHypothesis_reactivated(), lcHypothesisReactivated); statistics_.addStatistic(Statistics::kLoopVp_hypothesis(), vpHypothesis); statistics_.addStatistic(Statistics::kLoopReactivate_id(), retrievalId); statistics_.addStatistic(Statistics::kLoopHypothesis_ratio(), hypothesisRatio); statistics_.addStatistic(Statistics::kLoopVisual_inliers(), loopClosureVisualInliers); statistics_.addStatistic(Statistics::kLoopVisual_matches(), loopClosureVisualMatches); statistics_.addStatistic(Statistics::kLoopLinear_variance(), loopClosureLinearVariance); statistics_.addStatistic(Statistics::kLoopAngular_variance(), loopClosureAngularVariance); statistics_.addStatistic(Statistics::kLoopLast_id(), _memory->getLastGlobalLoopClosureId()); statistics_.addStatistic(Statistics::kLoopOptimization_max_error(), maxLinearError); statistics_.addStatistic(Statistics::kLoopOptimization_max_error_ratio(), maxLinearErrorRatio); statistics_.addStatistic(Statistics::kLoopOptimization_error(), optimizationError); statistics_.addStatistic(Statistics::kLoopOptimization_iterations(), optimizationIterations); statistics_.addStatistic(Statistics::kLoopLandmark_detected(), -landmarkDetected); statistics_.addStatistic(Statistics::kLoopLandmark_detected_node_ref(), landmarkDetectedNodesRef.empty()?0:*landmarkDetectedNodesRef.begin()); statistics_.addStatistic(Statistics::kLoopVisual_inliers_mean_dist(), loopClosureVisualInliersMeanDist); statistics_.addStatistic(Statistics::kLoopVisual_inliers_distribution(), loopClosureVisualInliersDistribution); statistics_.addStatistic(Statistics::kProximityTime_detections(), proximityDetectionsInTimeFound); statistics_.addStatistic(Statistics::kProximitySpace_detections_added_visually(), proximityDetectionsAddedVisually); statistics_.addStatistic(Statistics::kProximitySpace_detections_added_icp_only(), proximityDetectionsAddedByICPOnly); statistics_.addStatistic(Statistics::kProximitySpace_paths(), proximitySpacePaths); statistics_.addStatistic(Statistics::kProximitySpace_visual_paths_checked(), localVisualPathsChecked); statistics_.addStatistic(Statistics::kProximitySpace_scan_paths_checked(), localScanPathsChecked); statistics_.addStatistic(Statistics::kProximitySpace_last_detection_id(), lastProximitySpaceClosureId); statistics_.setProximityDetectionId(lastProximitySpaceClosureId); statistics_.setProximityDetectionMapId(_memory->getMapId(lastProximitySpaceClosureId)); if(_loopClosureHypothesis.first || lastProximitySpaceClosureId) { // Loop closure transform UASSERT(sLoop); std::multimap<int, Link>::const_iterator loopIter = sLoop->getLinks().find(signature->id()); UASSERT(loopIter!=sLoop->getLinks().end()); UINFO("Set loop closure transform = %s", loopIter->second.transform().prettyPrint().c_str()); statistics_.setLoopClosureTransform(loopIter->second.transform()); // if ground truth exists, compute localization error if(!sLoop->getGroundTruthPose().isNull() && !signature->getGroundTruthPose().isNull()) { Transform transformGT = sLoop->getGroundTruthPose().inverse() * signature->getGroundTruthPose(); Transform error = loopIter->second.transform().inverse() * transformGT; statistics_.addStatistic(Statistics::kGtLocalization_linear_error(), error.getNorm()); statistics_.addStatistic(Statistics::kGtLocalization_angular_error(), error.getAngle(1,0,0)*180/M_PI); } // Map correction (/map -> /odom) statistics_.addStatistic(Statistics::kLoopMap_correction_norm(), _mapCorrection.getNorm()); float roll,pitch,yaw; _mapCorrection.getEulerAngles(roll, pitch, yaw); statistics_.addStatistic(Statistics::kLoopMap_correction_roll(), roll*180/M_PI); statistics_.addStatistic(Statistics::kLoopMap_correction_pitch(), pitch*180/M_PI); statistics_.addStatistic(Statistics::kLoopMap_correction_yaw(), yaw*180/M_PI); } statistics_.setMapCorrection(_mapCorrection); UINFO("Set map correction = %s", _mapCorrection.prettyPrint().c_str()); statistics_.setLocalizationCovariance(localizationCovariance); statistics_.setProximityDetectionId(lastProximitySpaceClosureId); // timings... statistics_.addStatistic(Statistics::kTimingMemory_update(), timeMemoryUpdate*1000); statistics_.addStatistic(Statistics::kTimingNeighbor_link_refining(), timeNeighborLinkRefining*1000); statistics_.addStatistic(Statistics::kTimingProximity_by_time(), timeProximityByTimeDetection*1000); statistics_.addStatistic(Statistics::kTimingProximity_by_space_visual(), timeProximityBySpaceVisualDetection*1000); statistics_.addStatistic(Statistics::kTimingProximity_by_space(), timeProximityBySpaceDetection*1000); statistics_.addStatistic(Statistics::kTimingReactivation(), timeReactivations*1000); statistics_.addStatistic(Statistics::kTimingAdd_loop_closure_link(), timeAddLoopClosureLink*1000); statistics_.addStatistic(Statistics::kTimingMap_optimization(), timeMapOptimization*1000); statistics_.addStatistic(Statistics::kTimingLikelihood_computation(), timeLikelihoodCalculation*1000); statistics_.addStatistic(Statistics::kTimingPosterior_computation(), timePosteriorCalculation*1000); statistics_.addStatistic(Statistics::kTimingHypotheses_creation(), timeHypothesesCreation*1000); statistics_.addStatistic(Statistics::kTimingHypotheses_validation(), timeHypothesesValidation*1000); statistics_.addStatistic(Statistics::kTimingCleaning_neighbors(), timeCleaningNeighbors*1000); // retrieval statistics_.addStatistic(Statistics::kMemorySignatures_retrieved(), (float)signaturesRetrieved.size()); // Surf specific parameters statistics_.addStatistic(Statistics::kKeypointDictionary_size(), dictionarySize); statistics_.addStatistic(Statistics::kKeypointIndexed_words(), _memory->getVWDictionary()->getIndexedWordsCount()); statistics_.addStatistic(Statistics::kKeypointIndex_memory_usage(), _memory->getVWDictionary()->getIndexMemoryUsed()); //Epipolar geometry constraint statistics_.addStatistic(Statistics::kLoopRejectedHypothesis(), rejectedHypothesis?1.0f:0); statistics_.addStatistic(Statistics::kMemorySmall_movement(), smallDisplacement?1.0f:0); statistics_.addStatistic(Statistics::kMemoryDistance_travelled(), _distanceTravelled); statistics_.addStatistic(Statistics::kMemoryFast_movement(), tooFastMovement?1.0f:0); if(_publishRAMUsage) { statistics_.addStatistic(Statistics::kMemoryRAM_usage(), UProcessInfo::getMemoryUsage()/(1024*1024)); } if(_publishLikelihood || _publishPdf) { // Child count by parent signature on the root of the memory ... for statistics statistics_.setWeights(weights); if(_publishPdf) { statistics_.setPosterior(posterior); } if(_publishLikelihood) { statistics_.setLikelihood(likelihood); statistics_.setRawLikelihood(rawLikelihood); } } statistics_.setLabels(_memory->getAllLabels()); // Path if(_path.size()) { statistics_.setLocalPath(this->getPathNextNodes()); statistics_.setCurrentGoalId(this->getPathCurrentGoalId()); } } timeStatsCreation = timer.ticks(); ULOGGER_INFO("Time creating stats = %f...", timeStatsCreation); } Signature lastSignatureData(signature->id()); Transform lastSignatureLocalizedPose; if(_optimizedPoses.find(signature->id()) != _optimizedPoses.end() && graph::filterLinks(signature->getLinks(), Link::kSelfRefLink).size()) { // only if localized set it lastSignatureLocalizedPose = _optimizedPoses.at(signature->id()); } if(_publishLastSignatureData) { lastSignatureData = *signature; } if(!_rawDataKept) { _memory->removeRawData(signature->id(), true, !_neighborLinkRefining && !_proximityBySpace, true); } // remove last signature if the memory is not incremental or is a bad signature (if bad signatures are ignored) int signatureRemoved = _memory->cleanup(); if(signatureRemoved) { signaturesRemoved.push_back(signatureRemoved); } // If this option activated, add new nodes only if there are linked with a previous map. // Used when rtabmap is first started, it will wait a // global loop closure detection before starting the new map, // otherwise it deletes the current node. if(signatureRemoved != lastSignatureData.id()) { if(_startNewMapOnLoopClosure && _memory->isIncremental() && // only in mapping mode graph::filterLinks(signature->getLinks(), Link::kSelfRefLink).size() == 0 && // alone in the current map (landmarkDetected == 0 || rejectedHypothesis) && // if we re not seeing a landmark from a previous map _memory->getWorkingMem().size()>=2) // The working memory should not be empty (beside virtual signature) { UWARN("Ignoring location %d because a global loop closure is required before starting a new map!", signature->id()); signaturesRemoved.push_back(signature->id()); _memory->deleteLocation(signature->id()); } else if(_startNewMapOnGoodSignature && (signature->getLandmarks().empty() && signature->isBadSignature()) && graph::filterLinks(signature->getLinks(), Link::kSelfRefLink).size() == 0) // alone in the current map { UWARN("Ignoring location %d because a good signature (with enough features or with a landmark detected) is required before starting a new map!", signature->id()); signaturesRemoved.push_back(signature->id()); _memory->deleteLocation(signature->id()); } else if((smallDisplacement || tooFastMovement) && _loopClosureHypothesis.first == 0 && lastProximitySpaceClosureId == 0) { // Don't delete the location if a loop closure is detected UINFO("Ignoring location %d because the displacement is too small! (d=%f a=%f)", signature->id(), _rgbdLinearUpdate, _rgbdAngularUpdate); // If there is a too small displacement, remove the node signaturesRemoved.push_back(signature->id()); _memory->deleteLocation(signature->id()); } else { _memory->saveLocationData(signature->id()); } } else if(!_memory->isIncremental() && (smallDisplacement || tooFastMovement) && _loopClosureHypothesis.first == 0 && lastProximitySpaceClosureId == 0) { _odomCachePoses.erase(signatureRemoved); _odomCacheConstraints.erase(signatureRemoved); } // Pass this point signature should not be used, since it could have been transferred... signature = 0; timeMemoryCleanup = timer.ticks(); ULOGGER_INFO("timeMemoryCleanup = %fs... %d signatures removed", timeMemoryCleanup, (int)signaturesRemoved.size()); //============================================================ // TRANSFER //============================================================ // If time allowed for the detection exceeds the limit of // real-time, move the oldest signature with less frequency // entry (from X oldest) from the short term memory to the // long term memory. //============================================================ double totalTime = timerTotal.ticks(); ULOGGER_INFO("Total time processing = %fs...", totalTime); if((_maxTimeAllowed != 0 && totalTime*1000>_maxTimeAllowed) || (_maxMemoryAllowed != 0 && _memory->getWorkingMem().size() > _maxMemoryAllowed)) { ULOGGER_INFO("Removing old signatures because time limit is reached %f>%f or memory is reached %d>%d...", totalTime*1000, _maxTimeAllowed, _memory->getWorkingMem().size(), _maxMemoryAllowed); immunizedLocations.insert(_lastLocalizationNodeId); // keep the latest localization in working memory std::list<int> transferred = _memory->forget(immunizedLocations); signaturesRemoved.insert(signaturesRemoved.end(), transferred.begin(), transferred.end()); if(!_someNodesHaveBeenTransferred && transferred.size()) { _someNodesHaveBeenTransferred = true; // only used to hide a warning on close nodes immunization } } _lastProcessTime = totalTime; // cleanup cached gps values for(std::list<int>::iterator iter=signaturesRemoved.begin(); iter!=signaturesRemoved.end() && _gpsGeocentricCache.size(); ++iter) { _gpsGeocentricCache.erase(*iter); } //Remove optimized poses from signatures transferred if(signaturesRemoved.size() && (_optimizedPoses.size() || _constraints.size())) { //refresh the local map because some transferred nodes may have broken the tree int id = 0; if(!_memory->isIncremental() && (_lastLocalizationNodeId > 0 || _path.size())) { if(_path.size()) { // priority on node on the path UASSERT(_pathCurrentIndex < _path.size()); UASSERT_MSG(uContains(_optimizedPoses, _path.at(_pathCurrentIndex).first), uFormat("id=%d", _path.at(_pathCurrentIndex).first).c_str()); id = _path.at(_pathCurrentIndex).first; UDEBUG("Refresh local map from %d", id); } else { if(uContains(_optimizedPoses, _lastLocalizationNodeId)) { id = _lastLocalizationNodeId; UDEBUG("Refresh local map from %d", id); } else { _lastLocalizationNodeId = 0; } } } else if(_memory->isIncremental() && _optimizedPoses.size() && _memory->getLastWorkingSignature()) { id = _memory->getLastWorkingSignature()->id(); UDEBUG("Refresh local map from %d", id); } UDEBUG("id=%d _optimizedPoses=%d", id, (int)_optimizedPoses.size()); if(id > 0) { if(_lastLocalizationNodeId != 0) { _lastLocalizationNodeId = id; } UASSERT_MSG(_memory->getSignature(id) != 0, uFormat("id=%d", id).c_str()); if(signaturesRemoved.size() == 1 && signaturesRemoved.front() == lastSignatureData.id()) { UDEBUG("Detected that only last signature has been removed"); int lastId = signaturesRemoved.front(); _optimizedPoses.erase(lastId); for(std::multimap<int, Link>::iterator iter=_constraints.find(lastId); iter!=_constraints.end() && iter->first==lastId;++iter) { iter->second.to(); std::multimap<int, Link>::iterator jter = graph::findLink(_constraints, iter->second.to(), iter->second.from(), false); if(jter != _constraints.end()) { _constraints.erase(jter); } } _constraints.erase(lastId); } else { std::map<int, int> ids = _memory->getNeighborsId(id, 0, 0, true); for(std::map<int, Transform>::iterator iter=_optimizedPoses.begin(); iter!=_optimizedPoses.end();) { if(iter->first > 0 && !uContains(ids, iter->first)) { UDEBUG("Removed %d from local map", iter->first); UASSERT(iter->first != _lastLocalizationNodeId); _optimizedPoses.erase(iter++); } else { ++iter; } } for(std::multimap<int, Link>::iterator iter=_constraints.begin(); iter!=_constraints.end();) { if(iter->first > 0 && (!uContains(ids, iter->second.from()) || !uContains(ids, iter->second.to()))) { _constraints.erase(iter++); } else { ++iter; } } } } else { _optimizedPoses.clear(); _constraints.clear(); } } // just some verifications to make sure that planning path is still in the local map! if(_path.size()) { UASSERT(_pathCurrentIndex < _path.size()); UASSERT(_pathGoalIndex < _path.size()); UASSERT_MSG(uContains(_optimizedPoses, _path.at(_pathCurrentIndex).first), uFormat("local map size=%d, id=%d", (int)_optimizedPoses.size(), _path.at(_pathCurrentIndex).first).c_str()); UASSERT_MSG(uContains(_optimizedPoses, _path.at(_pathGoalIndex).first), uFormat("local map size=%d, id=%d", (int)_optimizedPoses.size(), _path.at(_pathGoalIndex).first).c_str()); } timeRealTimeLimitReachedProcess = timer.ticks(); ULOGGER_INFO("Time limit reached processing = %f...", timeRealTimeLimitReachedProcess); //============================================================== // Finalize statistics and log files //============================================================== int localGraphSize = 0; if(_publishStats) { statistics_.addStatistic(Statistics::kTimingStatistics_creation(), timeStatsCreation*1000); statistics_.addStatistic(Statistics::kTimingTotal(), totalTime*1000); statistics_.addStatistic(Statistics::kTimingForgetting(), timeRealTimeLimitReachedProcess*1000); statistics_.addStatistic(Statistics::kTimingJoining_trash(), timeJoiningTrash*1000); statistics_.addStatistic(Statistics::kTimingEmptying_trash(), timeEmptyingTrash*1000); statistics_.addStatistic(Statistics::kTimingMemory_cleanup(), timeMemoryCleanup*1000); // Transfer statistics_.addStatistic(Statistics::kMemorySignatures_removed(), signaturesRemoved.size()); statistics_.addStatistic(Statistics::kMemoryImmunized_globally(), immunizedGlobally); statistics_.addStatistic(Statistics::kMemoryImmunized_locally(), immunizedLocally); statistics_.addStatistic(Statistics::kMemoryImmunized_locally_max(), maxLocalLocationsImmunized); // place after transfer because the memory/local graph may have changed statistics_.addStatistic(Statistics::kMemoryWorking_memory_size(), _memory->getWorkingMem().size()); statistics_.addStatistic(Statistics::kMemoryShort_time_memory_size(), _memory->getStMem().size()); statistics_.addStatistic(Statistics::kMemoryDatabase_memory_used(), _memory->getDatabaseMemoryUsed()); // Set local graph std::map<int, Transform> poses; std::multimap<int, Link> constraints; if(!_rgbdSlamMode) { UDEBUG(""); // no optimization on appearance-only mode, create a local graph std::map<int, int> ids = _memory->getNeighborsId(lastSignatureData.id(), 0, 0, true); _memory->getMetricConstraints(uKeysSet(ids), poses, constraints, false); } else // RGBD-SLAM mode { poses = _optimizedPoses; constraints = _constraints; } UDEBUG(""); if(_publishLastSignatureData) { UINFO("Adding data %d [%d] (rgb/left=%d depth/right=%d)", lastSignatureData.id(), lastSignatureData.mapId(), lastSignatureData.sensorData().imageRaw().empty()?0:1, lastSignatureData.sensorData().depthOrRightRaw().empty()?0:1); statistics_.setLastSignatureData(lastSignatureData); } else { // only copy node info Signature nodeInfo( lastSignatureData.id(), lastSignatureData.mapId(), lastSignatureData.getWeight(), lastSignatureData.getStamp(), lastSignatureData.getLabel(), lastSignatureData.getPose(), lastSignatureData.getGroundTruthPose()); const std::vector<float> & v = lastSignatureData.getVelocity(); if(v.size() == 6) { nodeInfo.setVelocity(v[0], v[1], v[2], v[3], v[4], v[5]); } nodeInfo.sensorData().setGPS(lastSignatureData.sensorData().gps()); nodeInfo.sensorData().setEnvSensors(lastSignatureData.sensorData().envSensors()); statistics_.setLastSignatureData(nodeInfo); } UDEBUG(""); localGraphSize = (int)poses.size(); if(!lastSignatureLocalizedPose.isNull()) { poses.insert(std::make_pair(lastSignatureData.id(), lastSignatureLocalizedPose)); // in case we are in localization } statistics_.setPoses(poses); statistics_.setConstraints(constraints); statistics_.addStatistic(Statistics::kMemoryLocal_graph_size(), poses.size()); if(_computeRMSE && _memory->getGroundTruths().size()) { UDEBUG("Computing RMSE..."); float translational_rmse = 0.0f; float translational_mean = 0.0f; float translational_median = 0.0f; float translational_std = 0.0f; float translational_min = 0.0f; float translational_max = 0.0f; float rotational_rmse = 0.0f; float rotational_mean = 0.0f; float rotational_median = 0.0f; float rotational_std = 0.0f; float rotational_min = 0.0f; float rotational_max = 0.0f; graph::calcRMSE( _memory->getGroundTruths(), poses, translational_rmse, translational_mean, translational_median, translational_std, translational_min, translational_max, rotational_rmse, rotational_mean, rotational_median, rotational_std, rotational_min, rotational_max); statistics_.addStatistic(Statistics::kGtTranslational_rmse(), translational_rmse); statistics_.addStatistic(Statistics::kGtTranslational_mean(), translational_mean); statistics_.addStatistic(Statistics::kGtTranslational_median(), translational_median); statistics_.addStatistic(Statistics::kGtTranslational_std(), translational_std); statistics_.addStatistic(Statistics::kGtTranslational_min(), translational_min); statistics_.addStatistic(Statistics::kGtTranslational_max(), translational_max); statistics_.addStatistic(Statistics::kGtRotational_rmse(), rotational_rmse); statistics_.addStatistic(Statistics::kGtRotational_mean(), rotational_mean); statistics_.addStatistic(Statistics::kGtRotational_median(), rotational_median); statistics_.addStatistic(Statistics::kGtRotational_std(), rotational_std); statistics_.addStatistic(Statistics::kGtRotational_min(), rotational_min); statistics_.addStatistic(Statistics::kGtRotational_max(), rotational_max); UDEBUG("Computing RMSE...done!"); } if(_saveWMState && _memory->isIncremental()) { std::vector<int> ids = uKeys(_memory->getWorkingMem()); if(_memory->getStMem().size()) { ids.resize(ids.size() + _memory->getStMem().size()); for(std::set<int>::const_iterator iter=_memory->getStMem().begin(); iter!=_memory->getStMem().end(); ++iter) { ids.push_back(*iter); } } statistics_.setWmState(ids); } UDEBUG(""); } //Save statistics to database if(_memory->isIncremental()) { _memory->saveStatistics(statistics_); } //Start trashing UDEBUG("Empty trash..."); _memory->emptyTrash(); // Log info... // TODO : use a specific class which will handle the RtabmapEvent if(_foutFloat && _foutInt) { UDEBUG("Logging..."); std::string logF = uFormat("%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f\n", totalTime, timeMemoryUpdate, timeReactivations, timeLikelihoodCalculation, timePosteriorCalculation, timeHypothesesCreation, timeHypothesesValidation, timeRealTimeLimitReachedProcess, timeStatsCreation, _highestHypothesis.second, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, vpHypothesis, timeJoiningTrash, rehearsalValue, timeEmptyingTrash, timeRetrievalDbAccess, timeAddLoopClosureLink, timeMemoryCleanup, timeNeighborLinkRefining, timeProximityByTimeDetection, timeProximityBySpaceDetection, timeMapOptimization); std::string logI = uFormat("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n", _loopClosureHypothesis.first, _highestHypothesis.first, (int)signaturesRemoved.size(), 0, refWordsCount, dictionarySize, int(_memory->getWorkingMem().size()), rejectedHypothesis?1:0, 0, 0, int(signaturesRetrieved.size()), lcHypothesisReactivated, refUniqueWordsCount, retrievalId, 0, rehearsalMaxId, rehearsalMaxId>0?1:0, localGraphSize, data.id(), _memory->getVWDictionary()->getIndexedWordsCount(), _memory->getVWDictionary()->getIndexMemoryUsed()); if(_statisticLogsBufferedInRAM) { _bufferedLogsF.push_back(logF); _bufferedLogsI.push_back(logI); } else { if(_foutFloat) { fprintf(_foutFloat, "%s", logF.c_str()); } if(_foutInt) { fprintf(_foutInt, "%s", logI.c_str()); } } UINFO("Time logging = %f...", timer.ticks()); //ULogger::flush(); } timeFinalizingStatistics = timer.ticks(); UDEBUG("End process, timeFinalizingStatistics=%fs", timeFinalizingStatistics); if(_publishStats) { statistics_.addStatistic(Statistics::kTimingFinalizing_statistics(), timeFinalizingStatistics*1000); } return true; } // SETTERS void Rtabmap::setTimeThreshold(float maxTimeAllowed) { //must be positive, 0 mean inf time allowed (no time limit) _maxTimeAllowed = maxTimeAllowed; if(_maxTimeAllowed < 0) { ULOGGER_WARN("maxTimeAllowed < 0, then setting it to 0 (inf)."); _maxTimeAllowed = 0; } else if(_maxTimeAllowed > 0.0f && _maxTimeAllowed < 1.0f) { ULOGGER_WARN("Time threshold set to %fms, it is not in seconds!", _maxTimeAllowed); } } void Rtabmap::setWorkingDirectory(std::string path) { if(!path.empty() && UDirectory::exists(path)) { ULOGGER_DEBUG("Comparing new working directory path \"%s\" with \"%s\"", path.c_str(), _wDir.c_str()); if(path.compare(_wDir) != 0) { if (_foutFloat || _foutInt) { UWARN("Working directory has been changed from \"%s\" with \"%s\", new log files will be created.", path.c_str(), _wDir.c_str()); } _wDir = path; setupLogFiles(); } } else if(path.empty()) { _wDir.clear(); setupLogFiles(); } else { ULOGGER_ERROR("Directory \"%s\" doesn't exist!", path.c_str()); } } void Rtabmap::rejectLastLoopClosure() { if(_memory && _memory->getStMem().find(getLastLocationId())!=_memory->getStMem().end()) { std::multimap<int, Link> links = _memory->getLinks(getLastLocationId(), false); bool linksRemoved = false; for(std::multimap<int, Link>::iterator iter = links.begin(); iter!=links.end(); ++iter) { if(iter->second.type() == Link::kGlobalClosure || iter->second.type() == Link::kLocalSpaceClosure || iter->second.type() == Link::kLocalTimeClosure || iter->second.type() == Link::kUserClosure) { _memory->removeLink(iter->second.from(), iter->second.to()); std::multimap<int, Link>::iterator jter = graph::findLink(_constraints, iter->second.from(), iter->second.to(), true); if(jter!=_constraints.end()) { _constraints.erase(jter); // second time if link is also inverted jter = graph::findLink(_constraints, iter->second.from(), iter->second.to(), true); if(jter!=_constraints.end()) { _constraints.erase(jter); } } linksRemoved = true; } } if(linksRemoved) { _loopClosureHypothesis.first = 0; // we have to re-optimize the graph without the rejected links if(_memory->isIncremental() && _optimizedPoses.size()) { UINFO("Update graph"); std::map<int, Transform> poses = _optimizedPoses; std::multimap<int, Link> constraints; cv::Mat covariance; optimizeCurrentMap(getLastLocationId(), false, poses, covariance, &constraints); if(poses.empty()) { UWARN("Graph optimization failed after removing loop closure links from last location!"); } else { UINFO("Updated local map (old size=%d, new size=%d)", (int)_optimizedPoses.size(), (int)poses.size()); _optimizedPoses = poses; _constraints = constraints; _mapCorrection = _optimizedPoses.at(_memory->getLastWorkingSignature()->id()) * _memory->getLastWorkingSignature()->getPose().inverse(); } } } } } void Rtabmap::deleteLastLocation() { if(_memory && _memory->getStMem().size()) { int lastId = *_memory->getStMem().rbegin(); _memory->deleteLocation(lastId); // we have to re-optimize the graph without the deleted location if(_memory->isIncremental() && _optimizedPoses.size()) { UINFO("Update graph"); _optimizedPoses.erase(lastId); std::map<int, Transform> poses = _optimizedPoses; //remove all constraints with last localization id for(std::multimap<int, Link>::iterator iter=_constraints.begin(); iter!=_constraints.end();) { if(iter->second.from() == lastId || iter->second.to() == lastId) { _constraints.erase(iter++); } else { ++iter; } } if(poses.empty()) { _mapCorrection.setIdentity(); } else { std::multimap<int, Link> constraints; cv::Mat covariance; optimizeCurrentMap(_memory->getLastWorkingSignature()->id(), false, poses, covariance, &constraints); if(poses.empty()) { UWARN("Graph optimization failed after deleting the last location!"); } else { _optimizedPoses = poses; _constraints = constraints; _mapCorrection = _optimizedPoses.at(_memory->getLastWorkingSignature()->id()) * _memory->getLastWorkingSignature()->getPose().inverse(); } } } } } void Rtabmap::setOptimizedPoses(const std::map<int, Transform> & poses) { _optimizedPoses = poses; } void Rtabmap::dumpData() const { UDEBUG(""); if(_memory) { if(this->getWorkingDir().empty()) { UERROR("Working directory not set."); } else { _memory->dumpMemory(this->getWorkingDir()); } } } // fromId must be in _memory and in _optimizedPoses // Get poses in front of the robot, return optimized poses std::map<int, Transform> Rtabmap::getForwardWMPoses( int fromId, int maxNearestNeighbors, float radius, int maxGraphDepth // 0 means ignore ) const { std::map<int, Transform> poses; if(_memory && fromId > 0) { UDEBUG(""); const Signature * fromS = _memory->getSignature(fromId); UASSERT(fromS != 0); UASSERT(_optimizedPoses.find(fromId) != _optimizedPoses.end()); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); cloud->resize(_optimizedPoses.size()); std::vector<int> ids(_optimizedPoses.size()); int oi = 0; const std::set<int> & stm = _memory->getStMem(); //get distances std::map<int, float> foundIds; if(_memory->isIncremental()) { foundIds = _memory->getNeighborsIdRadius(fromId, radius, _optimizedPoses, maxGraphDepth); } else { foundIds = graph::getNodesInRadius(fromId, _optimizedPoses, radius); } float radiusSqrd = radius * radius; for(std::map<int, Transform>::const_iterator iter = _optimizedPoses.begin(); iter!=_optimizedPoses.end(); ++iter) { if(iter->first != fromId) { if(stm.find(iter->first) == stm.end() && uContains(foundIds, iter->first) && (radiusSqrd==0 || foundIds.at(iter->first) <= radiusSqrd)) { (*cloud)[oi] = pcl::PointXYZ(iter->second.x(), iter->second.y(), iter->second.z()); ids[oi++] = iter->first; } } } cloud->resize(oi); ids.resize(oi); Transform fromT = _optimizedPoses.at(fromId); if(cloud->size()) { //if(cloud->size()) //{ // pcl::io::savePCDFile("radiusPoses.pcd", *cloud); // UWARN("Saved radiusPoses.pcd"); //} //filter poses in front of the fromId float x,y,z, roll,pitch,yaw; fromT.getTranslationAndEulerAngles(x,y,z, roll,pitch,yaw); pcl::CropBox<pcl::PointXYZ> cropbox; cropbox.setInputCloud(cloud); cropbox.setMin(Eigen::Vector4f(-1, -radius, -999999, 0)); cropbox.setMax(Eigen::Vector4f(radius, radius, 999999, 0)); cropbox.setRotation(Eigen::Vector3f(roll, pitch, yaw)); cropbox.setTranslation(Eigen::Vector3f(x, y, z)); cropbox.setRotation(Eigen::Vector3f(roll,pitch,yaw)); pcl::IndicesPtr indices(new std::vector<int>()); cropbox.filter(*indices); //if(indices->size()) //{ // pcl::io::savePCDFile("radiusCrop.pcd", *cloud, *indices); // UWARN("Saved radiusCrop.pcd"); //} if(indices->size()) { pcl::search::KdTree<pcl::PointXYZ>::Ptr kdTree(new pcl::search::KdTree<pcl::PointXYZ>); kdTree->setInputCloud(cloud, indices); std::vector<int> ind; std::vector<float> dist; pcl::PointXYZ pt(fromT.x(), fromT.y(), fromT.z()); kdTree->radiusSearch(pt, radius, ind, dist, maxNearestNeighbors); //pcl::PointCloud<pcl::PointXYZ> inliers; for(unsigned int i=0; i<ind.size(); ++i) { if(ind[i] >=0) { Transform tmp = _optimizedPoses.find(ids[ind[i]])->second; //inliers.push_back(pcl::PointXYZ(tmp.x(), tmp.y(), tmp.z())); UDEBUG("Inlier %d: %s", ids[ind[i]], tmp.prettyPrint().c_str()); poses.insert(std::make_pair(ids[ind[i]], tmp)); } } //if(inliers.size()) //{ // pcl::io::savePCDFile("radiusInliers.pcd", inliers); //} //if(nearestId >0) //{ // pcl::PointCloud<pcl::PointXYZ> c; // Transform ct = _optimizedPoses.find(nearestId)->second; // c.push_back(pcl::PointXYZ(ct.x(), ct.y(), ct.z())); // pcl::io::savePCDFile("radiusNearestPt.pcd", c); //} } } } return poses; } std::map<int, std::map<int, Transform> > Rtabmap::getPaths(const std::map<int, Transform> & posesIn, const Transform & target, int maxGraphDepth) const { std::map<int, std::map<int, Transform> > paths; std::set<int> nodesSet; std::map<int, Transform> poses; for(std::map<int, Transform>::const_iterator iter=posesIn.lower_bound(1); iter!=posesIn.end(); ++iter) { nodesSet.insert(iter->first); poses.insert(*iter); } if(_memory && nodesSet.size() && !target.isNull()) { double e0=0,e1=0,e2=0,e3=0,e4=0; UTimer t; e0 = t.ticks(); // Segment poses connected only by neighbor links while(poses.size()) { std::map<int, Transform> path; // select nearest pose and iterate neighbors from there int nearestId = rtabmap::graph::findNearestNode(poses, target); e1+=t.ticks(); if(nearestId == 0) { UWARN("Nearest id of %s in %d poses is 0 !? Returning empty path.", target.prettyPrint().c_str(), (int)poses.size()); break; } std::map<int, int> ids = _memory->getNeighborsId(nearestId, maxGraphDepth, 0, true, true, true, true, nodesSet); e2+=t.ticks(); for(std::map<int, int>::iterator iter=ids.begin(); iter!=ids.end(); ++iter) { std::map<int, Transform>::iterator jter = poses.find(iter->first); if(jter != poses.end()) { bool valid = path.empty(); if(!valid) { // make sure it has a neighbor added to path std::multimap<int, Link> links = _memory->getNeighborLinks(iter->first); for(std::multimap<int, Link>::iterator kter=links.begin(); kter!=links.end() && !valid; ++kter) { valid = path.find(kter->first) != path.end(); } } if(valid) { //UDEBUG("%d <- %d", nearestId, jter->first); path.insert(*jter); poses.erase(jter); } } } e3+=t.ticks(); if (path.size()) { if (maxGraphDepth > 0 && !_memory->isGraphReduced() && (int)path.size() > maxGraphDepth * 2 + 1) { UWARN("%s=Off but path(%d) > maxGraphDepth(%d)*2+1, nearestId=%d ids=%d. Is reduce graph activated before?", Parameters::kMemReduceGraph().c_str(), (int)path.size(), maxGraphDepth, nearestId, (int)ids.size()); } paths.insert(std::make_pair(nearestId, path)); } else { UWARN(uFormat("path.size()=0!? nearestId=%d ids=%d, aborting...", (int)path.size(), nearestId, (int)ids.size()).c_str()); break; } e4+=t.ticks(); } UDEBUG("e0=%fs e1=%fs e2=%fs e3=%fs e4=%fs", e0, e1, e2, e3, e4); } return paths; } void Rtabmap::optimizeCurrentMap( int id, bool lookInDatabase, std::map<int, Transform> & optimizedPoses, cv::Mat & covariance, std::multimap<int, Link> * constraints, double * error, int * iterationsDone) const { //Optimize the map UINFO("Optimize map: around location %d", id); if(_memory && id > 0) { UTimer timer; std::map<int, int> ids = _memory->getNeighborsId(id, 0, lookInDatabase?-1:0, true, false); if(!_optimizeFromGraphEnd && ids.size() > 1) { id = ids.begin()->first; } UINFO("get %d ids time %f s", (int)ids.size(), timer.ticks()); std::map<int, Transform> poses = Rtabmap::optimizeGraph(id, uKeysSet(ids), optimizedPoses, lookInDatabase, covariance, constraints, error, iterationsDone); UINFO("optimize time %f s", timer.ticks()); if(poses.size()) { optimizedPoses = poses; if(_memory->getSignature(id) && uContains(optimizedPoses, id)) { Transform t = optimizedPoses.at(id) * _memory->getSignature(id)->getPose().inverse(); UINFO("Correction (from node %d) %s", id, t.prettyPrint().c_str()); } } else { UWARN("Failed to optimize the graph! returning empty optimized poses..."); optimizedPoses.clear(); if(constraints) { constraints->clear(); } } } } std::map<int, Transform> Rtabmap::optimizeGraph( int fromId, const std::set<int> & ids, const std::map<int, Transform> & guessPoses, bool lookInDatabase, cv::Mat & covariance, std::multimap<int, Link> * constraints, double * error, int * iterationsDone) const { UTimer timer; std::map<int, Transform> optimizedPoses; std::map<int, Transform> poses; std::multimap<int, Link> edgeConstraints; UDEBUG("ids=%d", (int)ids.size()); _memory->getMetricConstraints(ids, poses, edgeConstraints, lookInDatabase, !_graphOptimizer->landmarksIgnored()); UINFO("get constraints (ids=%d, %d poses, %d edges) time %f s", (int)ids.size(), (int)poses.size(), (int)edgeConstraints.size(), timer.ticks()); if(_graphOptimizer->iterations() > 0) { for(std::map<int, Transform>::iterator iter=poses.begin(); iter!=poses.end(); ++iter) { // Apply guess poses (if some) std::map<int, Transform>::const_iterator foundGuess = guessPoses.find(iter->first); if(foundGuess!=guessPoses.end()) { iter->second = foundGuess->second; } } } UASSERT(_graphOptimizer!=0); if(_graphOptimizer->iterations() == 0) { // Optimization disabled! Return not optimized poses. optimizedPoses = poses; if(constraints) { *constraints = edgeConstraints; } } else { bool hasLandmarks = edgeConstraints.begin()->first < 0; if(poses.size() != guessPoses.size() || hasLandmarks) { UDEBUG("recompute poses using only links (robust to multi-session)"); std::map<int, Transform> posesOut; std::multimap<int, Link> edgeConstraintsOut; _graphOptimizer->getConnectedGraph(fromId, poses, edgeConstraints, posesOut, edgeConstraintsOut); optimizedPoses = _graphOptimizer->optimize(fromId, posesOut, edgeConstraintsOut, covariance, 0, error, iterationsDone); if(constraints) { *constraints = edgeConstraintsOut; } } else { UDEBUG("use input guess poses"); optimizedPoses = _graphOptimizer->optimize(fromId, poses, edgeConstraints, covariance, 0, error, iterationsDone); if(constraints) { *constraints = edgeConstraints; } } if(!poses.empty() && optimizedPoses.empty()) { UWARN("Optimization has failed (poses=%d, guess=%d, links=%d)...", (int)poses.size(), (int)guessPoses.size(), (int)edgeConstraints.size()); } } UINFO("Optimization time %f s", timer.ticks()); return optimizedPoses; } void Rtabmap::adjustLikelihood(std::map<int, float> & likelihood) const { ULOGGER_DEBUG("likelihood.size()=%d", likelihood.size()); UTimer timer; timer.start(); if(likelihood.size()==0) { return; } // Use only non-null values (ignore virtual place) std::list<float> values; bool likelihoodNullValuesIgnored = true; for(std::map<int, float>::iterator iter = ++likelihood.begin(); iter!=likelihood.end(); ++iter) { if((iter->second >= 0 && !likelihoodNullValuesIgnored) || (iter->second > 0 && likelihoodNullValuesIgnored)) { values.push_back(iter->second); } } UDEBUG("values.size=%d", values.size()); float mean = uMean(values); float stdDev = std::sqrt(uVariance(values, mean)); //Adjust likelihood with mean and standard deviation (see Angeli phd) float epsilon = 0.0001; float max = 0.0f; int maxId = 0; for(std::map<int, float>::iterator iter=++likelihood.begin(); iter!= likelihood.end(); ++iter) { float value = iter->second; if(value > mean+stdDev && mean) { iter->second = (value-(stdDev-epsilon))/mean; if(value > max) { max = value; maxId = iter->first; } } else if(value == 1.0f && stdDev == 0) { iter->second = 1.0f; if(value > max) { max = value; maxId = iter->first; } } else { iter->second = 1.0f; } } if(stdDev > epsilon && max) { likelihood.begin()->second = mean/stdDev + 1.0f; } else { likelihood.begin()->second = 2.0f; //2 * std dev } double time = timer.ticks(); UDEBUG("mean=%f, stdDev=%f, max=%f, maxId=%d, time=%fs", mean, stdDev, max, maxId, time); } void Rtabmap::dumpPrediction() const { if(_memory && _bayesFilter) { if(this->getWorkingDir().empty()) { UERROR("Working directory not set."); return; } std::list<int> signaturesToCompare; for(std::map<int, double>::const_iterator iter=_memory->getWorkingMem().begin(); iter!=_memory->getWorkingMem().end(); ++iter) { if(iter->first > 0) { const Signature * s = _memory->getSignature(iter->first); UASSERT(s!=0); if(s->getWeight() != -1) // ignore intermediate nodes { signaturesToCompare.push_back(iter->first); } } else { // virtual signature should be added signaturesToCompare.push_back(iter->first); } } cv::Mat prediction = _bayesFilter->generatePrediction(_memory, uListToVector(signaturesToCompare)); FILE* fout = 0; std::string fileName = this->getWorkingDir() + "/DumpPrediction.txt"; #ifdef _MSC_VER fopen_s(&fout, fileName.c_str(), "w"); #else fout = fopen(fileName.c_str(), "w"); #endif if(fout) { for(int i=0; i<prediction.rows; ++i) { for(int j=0; j<prediction.cols; ++j) { fprintf(fout, "%f ",((float*)prediction.data)[j + i*prediction.cols]); } fprintf(fout, "\n"); } fclose(fout); } } else { UWARN("Memory and/or the Bayes filter are not created"); } } void Rtabmap::get3DMap( std::map<int, Signature> & signatures, std::map<int, Transform> & poses, std::multimap<int, Link> & constraints, bool optimized, bool global) const { UDEBUG(""); if(_memory && _memory->getLastWorkingSignature()) { if(_rgbdSlamMode) { if(optimized) { poses = _optimizedPoses; // guess cv::Mat covariance; this->optimizeCurrentMap(_memory->getLastWorkingSignature()->id(), global, poses, covariance, &constraints); } else { std::map<int, int> ids = _memory->getNeighborsId(_memory->getLastWorkingSignature()->id(), 0, global?-1:0, true); _memory->getMetricConstraints(uKeysSet(ids), poses, constraints, global); } } else { // no optimization on appearance-only mode std::map<int, int> ids = _memory->getNeighborsId(_memory->getLastWorkingSignature()->id(), 0, global?-1:0, true); _memory->getMetricConstraints(uKeysSet(ids), poses, constraints, global); } // Get data std::set<int> ids = uKeysSet(_memory->getWorkingMem()); // WM //remove virtual signature ids.erase(Memory::kIdVirtual); ids.insert(_memory->getStMem().begin(), _memory->getStMem().end()); // STM + WM if(global) { ids = _memory->getAllSignatureIds(); // STM + WM + LTM } for(std::set<int>::iterator iter = ids.begin(); iter!=ids.end(); ++iter) { Transform odomPoseLocal; int weight = -1; int mapId = -1; std::string label; double stamp = 0; Transform groundTruth; std::vector<float> velocity; GPS gps; EnvSensors sensors; _memory->getNodeInfo(*iter, odomPoseLocal, mapId, weight, label, stamp, groundTruth, velocity, gps, sensors, true); SensorData data = _memory->getNodeData(*iter); data.setId(*iter); std::multimap<int, cv::KeyPoint> words; std::multimap<int, cv::Point3f> words3; std::multimap<int, cv::Mat> wordsDescriptors; _memory->getNodeWords(*iter, words, words3, wordsDescriptors); signatures.insert(std::make_pair(*iter, Signature(*iter, mapId, weight, stamp, label, odomPoseLocal, groundTruth, data))); signatures.at(*iter).setWords(words); signatures.at(*iter).setWords3(words3); signatures.at(*iter).setWordsDescriptors(wordsDescriptors); if(velocity.size()==6) { signatures.at(*iter).setVelocity(velocity[0], velocity[1], velocity[2], velocity[3], velocity[4], velocity[5]); } signatures.at(*iter).sensorData().setGPS(gps); signatures.at(*iter).sensorData().setEnvSensors(sensors); } } else if(_memory && (_memory->getStMem().size() || _memory->getWorkingMem().size() > 1)) { UERROR("Last working signature is null!?"); } else if(_memory == 0) { UWARN("Memory not initialized..."); } } void Rtabmap::getGraph( std::map<int, Transform> & poses, std::multimap<int, Link> & constraints, bool optimized, bool global, std::map<int, Signature> * signatures) { if(_memory && _memory->getLastWorkingSignature()) { if(_rgbdSlamMode) { if(optimized) { poses = _optimizedPoses; // guess cv::Mat covariance; this->optimizeCurrentMap(_memory->getLastWorkingSignature()->id(), global, poses, covariance, &constraints); } else { std::map<int, int> ids = _memory->getNeighborsId(_memory->getLastWorkingSignature()->id(), 0, global?-1:0, true); _memory->getMetricConstraints(uKeysSet(ids), poses, constraints, global); } } else { // no optimization on appearance-only mode std::map<int, int> ids = _memory->getNeighborsId(_memory->getLastWorkingSignature()->id(), 0, global?-1:0, true); _memory->getMetricConstraints(uKeysSet(ids), poses, constraints, global); } if(signatures) { for(std::map<int, Transform>::iterator iter=poses.lower_bound(1); iter!=poses.end(); ++iter) { Transform odomPoseLocal; int weight = -1; int mapId = -1; std::string label; double stamp = 0; Transform groundTruth; std::vector<float> velocity; GPS gps; EnvSensors sensors; _memory->getNodeInfo(iter->first, odomPoseLocal, mapId, weight, label, stamp, groundTruth, velocity, gps, sensors, global); signatures->insert(std::make_pair(iter->first, Signature(iter->first, mapId, weight, stamp, label, odomPoseLocal, groundTruth))); std::multimap<int, cv::KeyPoint> words; std::multimap<int, cv::Point3f> words3; std::multimap<int, cv::Mat> wordsDescriptors; _memory->getNodeWords(iter->first, words, words3, wordsDescriptors); signatures->at(iter->first).setWords(words); signatures->at(iter->first).setWords3(words3); signatures->at(iter->first).setWordsDescriptors(wordsDescriptors); std::vector<CameraModel> models; StereoCameraModel stereoModel; _memory->getNodeCalibration(iter->first, models, stereoModel); signatures->at(iter->first).sensorData().setCameraModels(models); signatures->at(iter->first).sensorData().setStereoCameraModel(stereoModel); if(!velocity.empty()) { signatures->at(iter->first).setVelocity(velocity[0], velocity[1], velocity[2], velocity[3], velocity[4], velocity[5]); } signatures->at(iter->first).sensorData().setGPS(gps); signatures->at(iter->first).sensorData().setEnvSensors(sensors); } } } else if(_memory && (_memory->getStMem().size() || _memory->getWorkingMem().size())) { UERROR("Last working signature is null!?"); } else if(_memory == 0) { UWARN("Memory not initialized..."); } } int Rtabmap::detectMoreLoopClosures( float clusterRadius, float clusterAngle, int iterations, bool intraSession, bool interSession, const ProgressState * processState) { UASSERT(iterations>0); if(_graphOptimizer->iterations() <= 0) { UERROR("Cannot detect more loop closures if graph optimization iterations = 0"); return -1; } if(!_rgbdSlamMode) { UERROR("Detecting more loop closures can be done only in RGBD-SLAM mode."); return -1; } if(!intraSession && !interSession) { UERROR("Intra and/or inter session argument should be true."); return -1; } std::list<Link> loopClosuresAdded; std::multimap<int, int> checkedLoopClosures; std::map<int, Transform> posesToCheckLoopClosures; std::map<int, Transform> poses; std::multimap<int, Link> links; std::map<int, Signature> signatures; this->getGraph(poses, links, true, true, &signatures); std::map<int, int> mapIds; UDEBUG("remove all invalid or intermediate nodes, fill mapIds"); for(std::map<int, Transform>::iterator iter=poses.begin(); iter!=poses.end();++iter) { if(iter->first > 0) { if(signatures.at(iter->first).getWeight() >= 0) { posesToCheckLoopClosures.insert(*iter); mapIds.insert(std::make_pair(iter->first, signatures.at(iter->first).mapId())); } } } for(int n=0; n<iterations; ++n) { UINFO("Looking for more loop closures, clustering poses... (iteration=%d/%d, radius=%f m angle=%f rad)", n+1, iterations, clusterRadius, clusterAngle); std::multimap<int, int> clusters = graph::radiusPosesClustering( posesToCheckLoopClosures, clusterRadius, clusterAngle); UINFO("Looking for more loop closures, clustering poses... found %d clusters.", (int)clusters.size()); int i=0; std::set<int> addedLinks; for(std::multimap<int, int>::iterator iter=clusters.begin(); iter!= clusters.end(); ++iter, ++i) { if(processState && processState->isCanceled()) { return -1; break; } int from = iter->first; int to = iter->second; if(iter->first < iter->second) { from = iter->second; to = iter->first; } int mapIdFrom = uValue(mapIds, from, 0); int mapIdTo = uValue(mapIds, to, 0); if((interSession && mapIdFrom != mapIdTo) || (intraSession && mapIdFrom == mapIdTo)) { if(rtabmap::graph::findLink(checkedLoopClosures, from, to) == checkedLoopClosures.end()) { // only add new links and one per cluster per iteration if(addedLinks.find(from) == addedLinks.end() && addedLinks.find(to) == addedLinks.end() && rtabmap::graph::findLink(links, from, to) == links.end()) { checkedLoopClosures.insert(std::make_pair(from, to)); UASSERT(signatures.find(from) != signatures.end()); UASSERT(signatures.find(to) != signatures.end()); RegistrationInfo info; // use signatures instead of IDs because some signatures may not be in WM Transform t = _memory->computeTransform(signatures.at(from), signatures.at(to), Transform(), &info); if(!t.isNull()) { bool updateConstraints = true; if(_optimizationMaxError > 0.0f) { //optimize the graph to see if the new constraint is globally valid int fromId = from; int mapId = signatures.at(from).mapId(); // use first node of the map containing from for(std::map<int, Signature>::iterator ster=signatures.begin(); ster!=signatures.end(); ++ster) { if(ster->second.mapId() == mapId) { fromId = ster->first; break; } } std::multimap<int, Link> linksIn = links; linksIn.insert(std::make_pair(from, Link(from, to, Link::kUserClosure, t, getInformation(info.covariance)))); const Link * maxLinearLink = 0; const Link * maxAngularLink = 0; float maxLinearError = 0.0f; float maxAngularError = 0.0f; float maxLinearErrorRatio = 0.0f; float maxAngularErrorRatio = 0.0f; std::map<int, Transform> optimizedPoses; std::multimap<int, Link> links; UASSERT(poses.find(fromId) != poses.end()); UASSERT_MSG(poses.find(from) != poses.end(), uFormat("id=%d poses=%d links=%d", from, (int)poses.size(), (int)links.size()).c_str()); UASSERT_MSG(poses.find(to) != poses.end(), uFormat("id=%d poses=%d links=%d", to, (int)poses.size(), (int)links.size()).c_str()); _graphOptimizer->getConnectedGraph(fromId, poses, linksIn, optimizedPoses, links); UASSERT(optimizedPoses.find(fromId) != optimizedPoses.end()); UASSERT_MSG(optimizedPoses.find(from) != optimizedPoses.end(), uFormat("id=%d poses=%d links=%d", from, (int)optimizedPoses.size(), (int)links.size()).c_str()); UASSERT_MSG(optimizedPoses.find(to) != optimizedPoses.end(), uFormat("id=%d poses=%d links=%d", to, (int)optimizedPoses.size(), (int)links.size()).c_str()); UASSERT(graph::findLink(links, from, to) != links.end()); optimizedPoses = _graphOptimizer->optimize(fromId, optimizedPoses, links); std::string msg; if(optimizedPoses.size()) { graph::computeMaxGraphErrors( optimizedPoses, links, maxLinearErrorRatio, maxAngularErrorRatio, maxLinearError, maxAngularError, &maxLinearLink, &maxAngularLink); if(maxLinearLink) { UINFO("Max optimization linear error = %f m (link %d->%d)", maxLinearError, maxLinearLink->from(), maxLinearLink->to()); if(maxLinearErrorRatio > _optimizationMaxError) { msg = uFormat("Rejecting edge %d->%d because " "graph error is too large after optimization (%f m for edge %d->%d with ratio %f > std=%f m). " "\"%s\" is %f.", from, to, maxLinearError, maxLinearLink->from(), maxLinearLink->to(), maxLinearErrorRatio, sqrt(maxLinearLink->transVariance()), Parameters::kRGBDOptimizeMaxError().c_str(), _optimizationMaxError); } } else if(maxAngularLink) { UINFO("Max optimization angular error = %f deg (link %d->%d)", maxAngularError*180.0f/M_PI, maxAngularLink->from(), maxAngularLink->to()); if(maxAngularErrorRatio > _optimizationMaxError) { msg = uFormat("Rejecting edge %d->%d because " "graph error is too large after optimization (%f deg for edge %d->%d with ratio %f > std=%f deg). " "\"%s\" is %f m.", from, to, maxAngularError*180.0f/M_PI, maxAngularLink->from(), maxAngularLink->to(), maxAngularErrorRatio, sqrt(maxAngularLink->rotVariance()), Parameters::kRGBDOptimizeMaxError().c_str(), _optimizationMaxError); } } } else { msg = uFormat("Rejecting edge %d->%d because graph optimization has failed!", from, to); } if(!msg.empty()) { UWARN("%s", msg.c_str()); updateConstraints = false; } } if(updateConstraints) { addedLinks.insert(from); addedLinks.insert(to); cv::Mat inf = getInformation(info.covariance); links.insert(std::make_pair(from, Link(from, to, Link::kUserClosure, t, inf))); loopClosuresAdded.push_back(Link(from, to, Link::kUserClosure, t, inf)); std::string msg = uFormat("Iteration %d/%d: Added loop closure %d->%d! (%d/%d)", n+1, iterations, from, to, i+1, (int)clusters.size()); UINFO(msg.c_str()); if(processState) { UINFO(msg.c_str()); if(!processState->callback(msg)) { return -1; } } } } } } } } if(processState) { std::string msg = uFormat("Iteration %d/%d: Detected %d total loop closures!", n+1, iterations, (int)addedLinks.size()/2); UINFO(msg.c_str()); if(!processState->callback(msg)) { return -1; } } else { UINFO("Iteration %d/%d: Detected %d total loop closures!", n+1, iterations, (int)addedLinks.size()/2); } if(addedLinks.size() == 0) { break; } UINFO("Optimizing graph with new links (%d nodes, %d constraints)...", (int)poses.size(), (int)links.size()); int fromId = _optimizeFromGraphEnd?poses.rbegin()->first:poses.begin()->first; poses = _graphOptimizer->optimize(fromId, poses, links, 0); if(poses.size() == 0) { UERROR("Optimization failed! Rejecting all loop closures..."); loopClosuresAdded.clear(); return -1; } UINFO("Optimizing graph with new links... done!"); } UINFO("Total added %d loop closures.", (int)loopClosuresAdded.size()); if(loopClosuresAdded.size()) { for(std::list<Link>::iterator iter=loopClosuresAdded.begin(); iter!=loopClosuresAdded.end(); ++iter) { _memory->addLink(*iter, true); } // Update optimized poses for(std::map<int, Transform>::iterator iter=_optimizedPoses.begin(); iter!=_optimizedPoses.end(); ++iter) { std::map<int, Transform>::iterator jter = poses.find(iter->first); if(jter != poses.end()) { iter->second = jter->second; } } std::map<int, Transform> tmp; // Update also the links if some have been added in WM _memory->getMetricConstraints(uKeysSet(_optimizedPoses), tmp, _constraints, false); // This will force rtabmap_ros to regenerate the global occupancy grid if there was one _memory->save2DMap(cv::Mat(), 0, 0, 0); } return (int)loopClosuresAdded.size(); } int Rtabmap::refineLinks() { if(!_rgbdSlamMode) { UERROR("Refining links can be done only in RGBD-SLAM mode."); return -1; } std::list<Link> linksRefined; std::map<int, Transform> poses; std::multimap<int, Link> links; std::map<int, Signature> signatures; this->getGraph(poses, links, false, true, &signatures); int i=0; for(std::multimap<int, Link>::iterator iter=links.lower_bound(1); iter!= links.end(); ++iter) { int from = iter->second.from(); int to = iter->second.to(); UASSERT(signatures.find(from) != signatures.end()); UASSERT(signatures.find(to) != signatures.end()); RegistrationInfo info; // use signatures instead of IDs because some signatures may not be in WM Transform t = _memory->computeTransform(signatures.at(from), signatures.at(to), iter->second.transform(), &info); if(!t.isNull()) { linksRefined.push_back(Link(from, to, iter->second.type(), t, info.covariance.inv())); UINFO("Refined link %d->%d! (%d/%d)", from, to, ++i, (int)links.size()); } } UINFO("Total refined %d links.", (int)linksRefined.size()); if(linksRefined.size()) { for(std::list<Link>::iterator iter=linksRefined.begin(); iter!=linksRefined.end(); ++iter) { _memory->updateLink(*iter, true); } } return (int)linksRefined.size(); } cv::Mat Rtabmap::getInformation(const cv::Mat & covariance) const { cv::Mat information = covariance.inv(); if(_loopCovLimited) { const std::vector<double> & odomMaxInf = _memory->getOdomMaxInf(); if(odomMaxInf.size() == 6) { for(int i=0; i<6; ++i) { if(information.at<double>(i,i) > odomMaxInf[i]) { information.at<double>(i,i) = odomMaxInf[i]; } } } } return information; } void Rtabmap::clearPath(int status) { UINFO("status=%d", status); _pathStatus = status; _path.clear(); _pathCurrentIndex=0; _pathGoalIndex = 0; _pathTransformToGoal.setIdentity(); _pathUnreachableNodes.clear(); _pathStuckCount = 0; _pathStuckDistance = 0.0f; if(_memory) { _memory->removeAllVirtualLinks(); } } // return true if path is updated bool Rtabmap::computePath(int targetNode, bool global) { this->clearPath(0); if(targetNode>0) { UINFO("Planning a path to node %d (global=%d)", targetNode, global?1:0); } else { UINFO("Planning a path to landmark %d (global=%d)", -targetNode, global?1:0); } if(!_rgbdSlamMode) { UWARN("A path can only be computed in RGBD-SLAM mode"); return false; } UTimer totalTimer; UTimer timer; Transform transformToLandmark = Transform::getIdentity(); // No need to optimize the graph if(_memory) { int currentNode = 0; if(_memory->isIncremental()) { if(!_memory->getLastWorkingSignature()) { UWARN("Working memory is empty... cannot compute a path"); return false; } currentNode = _memory->getLastWorkingSignature()->id(); } else { if(_lastLocalizationPose.isNull() || _optimizedPoses.empty()) { UWARN("Last localization pose is null... cannot compute a path"); return false; } if(_optimizedPoses.begin()->first < 0) { std::map<int, Transform> poses(_optimizedPoses.lower_bound(1), _optimizedPoses.end()); currentNode = graph::findNearestNode(poses, _lastLocalizationPose); } else { currentNode = graph::findNearestNode(_optimizedPoses, _lastLocalizationPose); } } if(currentNode && targetNode) { std::list<std::pair<int, Transform> > path = graph::computePath( currentNode, targetNode, _memory, global, false, _pathLinearVelocity, _pathAngularVelocity); //transform in current referential Transform t = uValue(_optimizedPoses, currentNode, Transform::getIdentity()); _path.resize(path.size()); int oi = 0; for(std::list<std::pair<int, Transform> >::iterator iter=path.begin(); iter!=path.end();++iter) { if(iter->first > 0) { // just keep nodes in the path _path[oi].first = iter->first; _path[oi++].second = t * iter->second; } } _path.resize(oi); if(!_path.empty() && !path.empty() && path.rbegin()->first < 0) { transformToLandmark = _path.back().second.inverse() * t * path.rbegin()->second; } } else if(currentNode == 0) { UWARN("We should be localized before planning."); } } UINFO("Total planning time = %fs (%d nodes, %f m long)", totalTimer.ticks(), (int)_path.size(), graph::computePathLength(_path)); if(_path.size() == 0) { _path.clear(); UWARN("Cannot compute a path!"); return false; } else { UINFO("Path generated! Size=%d", (int)_path.size()); if(ULogger::level() == ULogger::kInfo) { std::stringstream stream; for(unsigned int i=0; i<_path.size(); ++i) { stream << _path[i].first; if(i+1 < _path.size()) { stream << " "; } } UINFO("Path = [%s]", stream.str().c_str()); } if(_goalsSavedInUserData) { // set goal to latest signature std::string goalStr = uFormat("GOAL:%d", targetNode); // use label is exist if(_memory->getSignature(targetNode)) { if(!_memory->getSignature(targetNode)->getLabel().empty()) { goalStr = std::string("GOAL:")+_memory->getSignature(targetNode)->getLabel(); } } else if(global) { std::map<int, std::string> labels = _memory->getAllLabels(); std::map<int, std::string>::iterator iter = labels.find(targetNode); if(iter != labels.end() && !iter->second.empty()) { goalStr = std::string("GOAL:")+labels.at(targetNode); } } setUserData(0, cv::Mat(1, int(goalStr.size()+1), CV_8SC1, (void *)goalStr.c_str()).clone()); } _pathTransformToGoal = transformToLandmark; updateGoalIndex(); return _path.size() || _pathStatus > 0; } return false; } bool Rtabmap::computePath(const Transform & targetPose, float tolerance) { this->clearPath(0); UINFO("Planning a path to pose %s ", targetPose.prettyPrint().c_str()); if(tolerance < 0.0f) { tolerance = _localRadius; } std::list<std::pair<int, Transform> > pathPoses; if(!_rgbdSlamMode) { UWARN("This method can only be used in RGBD-SLAM mode"); return false; } //Find the nearest node UTimer timer; std::map<int, Transform> nodes = _optimizedPoses; std::multimap<int, int> links; for(std::map<int, Transform>::iterator iter=nodes.upper_bound(0); iter!=nodes.end(); ++iter) { const Signature * s = _memory->getSignature(iter->first); UASSERT(s); for(std::map<int, Link>::const_iterator jter=s->getLinks().begin(); jter!=s->getLinks().end(); ++jter) { // only add links for which poses are in "nodes" if(jter->second.from() != jter->second.to() && uContains(nodes, jter->second.to())) { links.insert(std::make_pair(jter->second.from(), jter->second.to())); //links.insert(std::make_pair(jter->second.to(), jter->second.from())); // <-> (commented: already added when iterating in nodes) } } } UINFO("Time getting links = %fs", timer.ticks()); int currentNode = 0; if(_memory->isIncremental()) { if(!_memory->getLastWorkingSignature()) { UWARN("Working memory is empty... cannot compute a path"); return false; } currentNode = _memory->getLastWorkingSignature()->id(); } else { if(_lastLocalizationPose.isNull() || _optimizedPoses.empty()) { UWARN("Last localization pose is null... cannot compute a path"); return false; } if(_optimizedPoses.begin()->first < 0) { std::map<int, Transform> poses(_optimizedPoses.lower_bound(1), _optimizedPoses.end()); currentNode = graph::findNearestNode(poses, _lastLocalizationPose); } else { currentNode = graph::findNearestNode(_optimizedPoses, _lastLocalizationPose); } } int nearestId; if(!_lastLocalizationPose.isNull() && _lastLocalizationPose.getDistance(targetPose) < tolerance) { // target can be reached from the current node nearestId = currentNode; } else { nearestId = rtabmap::graph::findNearestNode(nodes, targetPose); } UINFO("Nearest node found=%d ,%fs", nearestId, timer.ticks()); if(nearestId > 0) { if(tolerance != 0.0f && targetPose.getDistance(nodes.at(nearestId)) > tolerance) { UWARN("Cannot plan farther than %f m from the graph! (distance=%f m from node %d)", tolerance, targetPose.getDistance(nodes.at(nearestId)), nearestId); } else { UINFO("Computing path from location %d to %d", currentNode, nearestId); UTimer timer; _path = uListToVector(rtabmap::graph::computePath(nodes, links, currentNode, nearestId)); UINFO("A* time = %fs", timer.ticks()); if(_path.size() == 0) { UWARN("Cannot compute a path!"); } else { UINFO("Path generated! Size=%d", (int)_path.size()); if(ULogger::level() == ULogger::kInfo) { std::stringstream stream; for(unsigned int i=0; i<_path.size(); ++i) { stream << _path[i].first; if(i+1 < _path.size()) { stream << " "; } } UINFO("Path = [%s]", stream.str().c_str()); } UASSERT(uContains(nodes, _path.back().first)); _pathTransformToGoal = nodes.at(_path.back().first).inverse() * targetPose; updateGoalIndex(); return true; } } } else { UWARN("Nearest node not found in graph (size=%d) for pose %s", (int)nodes.size(), targetPose.prettyPrint().c_str()); } return false; } std::vector<std::pair<int, Transform> > Rtabmap::getPathNextPoses() const { std::vector<std::pair<int, Transform> > poses; if(_path.size()) { UASSERT(_pathCurrentIndex < _path.size() && _pathGoalIndex < _path.size()); poses.resize(_pathGoalIndex-_pathCurrentIndex+1); int oi=0; for(unsigned int i=_pathCurrentIndex; i<=_pathGoalIndex; ++i) { std::map<int, Transform>::const_iterator iter = _optimizedPoses.find(_path[i].first); if(iter != _optimizedPoses.end()) { poses[oi++] = *iter; } else { break; } } poses.resize(oi); } return poses; } std::vector<int> Rtabmap::getPathNextNodes() const { std::vector<int> ids; if(_path.size()) { UASSERT(_pathCurrentIndex < _path.size() && _pathGoalIndex < _path.size()); ids.resize(_pathGoalIndex-_pathCurrentIndex+1); int oi = 0; for(unsigned int i=_pathCurrentIndex; i<=_pathGoalIndex; ++i) { std::map<int, Transform>::const_iterator iter = _optimizedPoses.find(_path[i].first); if(iter != _optimizedPoses.end()) { ids[oi++] = iter->first; } else { break; } } ids.resize(oi); } return ids; } int Rtabmap::getPathCurrentGoalId() const { if(_path.size()) { UASSERT(_pathGoalIndex <= _path.size()); return _path[_pathGoalIndex].first; } return 0; } void Rtabmap::updateGoalIndex() { if(!_rgbdSlamMode) { UWARN("This method can on be used in RGBD-SLAM mode!"); return; } if( _memory && _path.size()) { // remove all previous virtual links for(unsigned int i=0; i<_pathCurrentIndex && i<_path.size(); ++i) { const Signature * s = _memory->getSignature(_path[i].first); if(s) { _memory->removeVirtualLinks(s->id()); } } // for the current index, only keep the newest virtual link // This will make sure that the path is still connected even // if the new signature is removed (e.g., because of a small displacement) UASSERT(_pathCurrentIndex < _path.size()); const Signature * currentIndexS = _memory->getSignature(_path[_pathCurrentIndex].first); UASSERT_MSG(currentIndexS != 0, uFormat("_path[%d].first=%d", _pathCurrentIndex, _path[_pathCurrentIndex].first).c_str()); std::multimap<int, Link> links = currentIndexS->getLinks(); // make a copy bool latestVirtualLinkFound = false; for(std::multimap<int, Link>::reverse_iterator iter=links.rbegin(); iter!=links.rend(); ++iter) { if(iter->second.type() == Link::kVirtualClosure) { if(latestVirtualLinkFound) { _memory->removeLink(currentIndexS->id(), iter->first); } else { latestVirtualLinkFound = true; } } } // Make sure the next signatures on the path are linked together float distanceSoFar = 0.0f; for(unsigned int i=_pathCurrentIndex+1; i<_path.size(); ++i) { if(i>0) { if(_localRadius > 0.0f) { distanceSoFar += _path[i-1].second.getDistance(_path[i].second); } if(distanceSoFar <= _localRadius) { if(_path[i].first != _path[i-1].first) { const Signature * s = _memory->getSignature(_path[i].first); if(s) { if(!s->hasLink(_path[i-1].first) && _memory->getSignature(_path[i-1].first) != 0) { Transform virtualLoop = _path[i].second.inverse() * _path[i-1].second; _memory->addLink(Link(_path[i].first, _path[i-1].first, Link::kVirtualClosure, virtualLoop, cv::Mat::eye(6,6,CV_64FC1)*0.01)); // on the optimized path UINFO("Added Virtual link between %d and %d", _path[i-1].first, _path[i].first); } } } } else { break; } } } UDEBUG("current node = %d current goal = %d", _path[_pathCurrentIndex].first, _path[_pathGoalIndex].first); Transform currentPose; if(_memory->isIncremental()) { if(_memory->getLastWorkingSignature() == 0 || !uContains(_optimizedPoses, _memory->getLastWorkingSignature()->id())) { UERROR("Last node is null in memory or not in optimized poses. Aborting the plan..."); this->clearPath(-1); return; } currentPose = _optimizedPoses.at(_memory->getLastWorkingSignature()->id()); } else { if(_lastLocalizationPose.isNull()) { UERROR("Last localization pose is null. Aborting the plan..."); this->clearPath(-1); return; } currentPose = _lastLocalizationPose; } int goalId = _path.back().first; if(uContains(_optimizedPoses, goalId)) { //use local position to know if the goal is reached float d = currentPose.getDistance(_optimizedPoses.at(goalId)*_pathTransformToGoal); if(d < _goalReachedRadius) { UINFO("Goal %d reached!", goalId); this->clearPath(1); } } if(_path.size()) { //Always check if the farthest node is accessible in local map (max to local space radius if set) unsigned int goalIndex = _pathCurrentIndex; float distanceFromCurrentNode = 0.0f; bool sameGoalIndex = false; for(unsigned int i=_pathCurrentIndex+1; i<_path.size(); ++i) { if(uContains(_optimizedPoses, _path[i].first)) { if(_localRadius > 0.0f) { distanceFromCurrentNode = _path[_pathCurrentIndex].second.getDistance(_path[i].second); } if((goalIndex == _pathCurrentIndex && i == _path.size()-1) || _pathUnreachableNodes.find(i) == _pathUnreachableNodes.end()) { if(distanceFromCurrentNode <= _localRadius) { goalIndex = i; } else { break; } } } else { break; } } UASSERT(_pathGoalIndex < _path.size() && goalIndex < _path.size()); if(_pathGoalIndex != goalIndex) { UINFO("Updated current goal from %d to %d (%d/%d)", (int)_path[_pathGoalIndex].first, _path[goalIndex].first, (int)goalIndex+1, (int)_path.size()); _pathGoalIndex = goalIndex; } else { sameGoalIndex = true; } // update nearest pose in the path unsigned int nearestNodeIndex = 0; float distance = -1.0f; bool sameCurrentIndex = false; UASSERT(_pathGoalIndex < _path.size() && _pathGoalIndex >= 0); for(unsigned int i=_pathCurrentIndex; i<=_pathGoalIndex; ++i) { std::map<int, Transform>::iterator iter = _optimizedPoses.find(_path[i].first); if(iter != _optimizedPoses.end()) { float d = currentPose.getDistanceSquared(iter->second); if(distance == -1.0f || distance > d) { distance = d; nearestNodeIndex = i; } } } if(distance < 0) { UERROR("The nearest pose on the path not found! Aborting the plan..."); this->clearPath(-1); } else { UDEBUG("Nearest node = %d", _path[nearestNodeIndex].first); } if(distance >= 0 && nearestNodeIndex != _pathCurrentIndex) { _pathCurrentIndex = nearestNodeIndex; _pathUnreachableNodes.erase(nearestNodeIndex); // if we are on it, it is reachable } else { sameCurrentIndex = true; } bool isStuck = false; if(sameGoalIndex && sameCurrentIndex && _pathStuckIterations>0) { float distanceToCurrentGoal = 0.0f; std::map<int, Transform>::iterator iter = _optimizedPoses.find(_path[_pathGoalIndex].first); if(iter != _optimizedPoses.end()) { if(_pathGoalIndex == _pathCurrentIndex && _pathGoalIndex == _path.size()-1) { distanceToCurrentGoal = currentPose.getDistanceSquared(iter->second*_pathTransformToGoal); } else { distanceToCurrentGoal = currentPose.getDistanceSquared(iter->second); } } if(distanceToCurrentGoal > 0.0f) { if(distanceToCurrentGoal >= _pathStuckDistance) { // we are not approaching the goal isStuck = true; if(_pathStuckDistance == 0.0f) { _pathStuckDistance = distanceToCurrentGoal; } } } else { // no nodes available, cannot plan isStuck = true; } } if(isStuck && ++_pathStuckCount > _pathStuckIterations) { UWARN("Current goal %d not reached since %d iterations (\"RGBD/PlanStuckIterations\"=%d), mark that node as unreachable.", _path[_pathGoalIndex].first, _pathStuckCount, _pathStuckIterations); _pathStuckCount = 0; _pathStuckDistance = 0.0; _pathUnreachableNodes.insert(_pathGoalIndex); // select previous reachable one while(_pathUnreachableNodes.find(_pathGoalIndex) != _pathUnreachableNodes.end()) { if(_pathGoalIndex == 0 || --_pathGoalIndex <= _pathCurrentIndex) { // plan failed! UERROR("No upcoming nodes on the path are reachable! Aborting the plan..."); this->clearPath(-1); return; } } } else if(!isStuck) { _pathStuckCount = 0; _pathStuckDistance = 0.0; } } } } } // namespace rtabmap
/* Sirikata Network Utilities * StreamListener.hpp * * Copyright (c) 2009, Daniel Reiter Horn * 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 Sirikata nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SIRIKATA_StreamListener_HPP__ #define SIRIKATA_StreamListener_HPP__ namespace Sirikata { namespace Network { /** * This class waits on a service and listens for incoming connections * It calls the callback whenever such connections are encountered */ class SIRIKATA_EXPORT StreamListener { protected: StreamListener(){} public: ///subclasses will expose these methods with similar arguments + protocol specific args virtual bool listen( const Address&addy, const Stream::SubstreamCallback&newStreamCallback)=0; ///returns thea name of the computer followed by a colon and then the service being listened on virtual String listenAddressName()const=0; ///returns thea name of the computer followed by a colon and then the service being listened on virtual Address listenAddress()const=0; ///stops listening virtual void close()=0; virtual ~StreamListener(){}; }; } } #endif
//===- ICF.cpp ------------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // ICF is short for Identical Code Folding. This is a size optimization to // identify and merge two or more read-only sections (typically functions) // that happened to have the same contents. It usually reduces output size // by a few percent. // // In ICF, two sections are considered identical if they have the same // section flags, section data, and relocations. Relocations are tricky, // because two relocations are considered the same if they have the same // relocation types, values, and if they point to the same sections *in // terms of ICF*. // // Here is an example. If foo and bar defined below are compiled to the // same machine instructions, ICF can and should merge the two, although // their relocations point to each other. // // void foo() { bar(); } // void bar() { foo(); } // // If you merge the two, their relocations point to the same section and // thus you know they are mergeable, but how do you know they are // mergeable in the first place? This is not an easy problem to solve. // // What we are doing in LLD is to partition sections into equivalence // classes. Sections in the same equivalence class when the algorithm // terminates are considered identical. Here are details: // // 1. First, we partition sections using their hash values as keys. Hash // values contain section types, section contents and numbers of // relocations. During this step, relocation targets are not taken into // account. We just put sections that apparently differ into different // equivalence classes. // // 2. Next, for each equivalence class, we visit sections to compare // relocation targets. Relocation targets are considered equivalent if // their targets are in the same equivalence class. Sections with // different relocation targets are put into different equivalence // clases. // // 3. If we split an equivalence class in step 2, two relocations // previously target the same equivalence class may now target // different equivalence classes. Therefore, we repeat step 2 until a // convergence is obtained. // // 4. For each equivalence class C, pick an arbitrary section in C, and // merge all the other sections in C with it. // // For small programs, this algorithm needs 3-5 iterations. For large // programs such as Chromium, it takes more than 20 iterations. // // This algorithm was mentioned as an "optimistic algorithm" in [1], // though gold implements a different algorithm than this. // // We parallelize each step so that multiple threads can work on different // equivalence classes concurrently. That gave us a large performance // boost when applying ICF on large programs. For example, MSVC link.exe // or GNU gold takes 10-20 seconds to apply ICF on Chromium, whose output // size is about 1.5 GB, but LLD can finish it in less than 2 seconds on a // 2.8 GHz 40 core machine. Even without threading, LLD's ICF is still // faster than MSVC or gold though. // // [1] Safe ICF: Pointer Safe and Unwinding aware Identical Code Folding // in the Gold Linker // http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/36912.pdf // //===----------------------------------------------------------------------===// #include "ICF.h" #include "Config.h" #include "SymbolTable.h" #include "Symbols.h" #include "SyntheticSections.h" #include "Writer.h" #include "lld/Common/Threads.h" #include "llvm/ADT/Hashing.h" #include "llvm/BinaryFormat/ELF.h" #include "llvm/Object/ELF.h" #include <algorithm> #include <atomic> using namespace lld; using namespace lld::elf; using namespace llvm; using namespace llvm::ELF; using namespace llvm::object; namespace { template <class ELFT> class ICF { public: void run(); private: void segregate(size_t Begin, size_t End, bool Constant); template <class RelTy> bool constantEq(const InputSection *A, ArrayRef<RelTy> RelsA, const InputSection *B, ArrayRef<RelTy> RelsB); template <class RelTy> bool variableEq(const InputSection *A, ArrayRef<RelTy> RelsA, const InputSection *B, ArrayRef<RelTy> RelsB); bool equalsConstant(const InputSection *A, const InputSection *B); bool equalsVariable(const InputSection *A, const InputSection *B); size_t findBoundary(size_t Begin, size_t End); void forEachClassRange(size_t Begin, size_t End, std::function<void(size_t, size_t)> Fn); void forEachClass(std::function<void(size_t, size_t)> Fn); std::vector<InputSection *> Sections; // We repeat the main loop while `Repeat` is true. std::atomic<bool> Repeat; // The main loop counter. int Cnt = 0; // We have two locations for equivalence classes. On the first iteration // of the main loop, Class[0] has a valid value, and Class[1] contains // garbage. We read equivalence classes from slot 0 and write to slot 1. // So, Class[0] represents the current class, and Class[1] represents // the next class. On each iteration, we switch their roles and use them // alternately. // // Why are we doing this? Recall that other threads may be working on // other equivalence classes in parallel. They may read sections that we // are updating. We cannot update equivalence classes in place because // it breaks the invariance that all possibly-identical sections must be // in the same equivalence class at any moment. In other words, the for // loop to update equivalence classes is not atomic, and that is // observable from other threads. By writing new classes to other // places, we can keep the invariance. // // Below, `Current` has the index of the current class, and `Next` has // the index of the next class. If threading is enabled, they are either // (0, 1) or (1, 0). // // Note on single-thread: if that's the case, they are always (0, 0) // because we can safely read the next class without worrying about race // conditions. Using the same location makes this algorithm converge // faster because it uses results of the same iteration earlier. int Current = 0; int Next = 0; }; } // Returns a hash value for S. Note that the information about // relocation targets is not included in the hash value. template <class ELFT> static uint32_t getHash(InputSection *S) { return hash_combine(S->Flags, S->getSize(), S->NumRelocations, S->Data); } // Returns true if section S is subject of ICF. static bool isEligible(InputSection *S) { if (!S->Live || S->KeepUnique || !(S->Flags & SHF_ALLOC)) return false; // Don't merge writable sections. .data.rel.ro sections are marked as writable // but are semantically read-only. if ((S->Flags & SHF_WRITE) && S->Name != ".data.rel.ro" && !S->Name.startswith(".data.rel.ro.")) return false; // Don't merge read only data sections unless // --ignore-data-address-equality was passed. if (!(S->Flags & SHF_EXECINSTR) && !Config->IgnoreDataAddressEquality) return false; // Don't merge synthetic sections as their Data member is not valid and empty. // The Data member needs to be valid for ICF as it is used by ICF to determine // the equality of section contents. if (isa<SyntheticSection>(S)) return false; // .init and .fini contains instructions that must be executed to initialize // and finalize the process. They cannot and should not be merged. if (S->Name == ".init" || S->Name == ".fini") return false; // A user program may enumerate sections named with a C identifier using // __start_* and __stop_* symbols. We cannot ICF any such sections because // that could change program semantics. if (isValidCIdentifier(S->Name)) return false; return true; } // Split an equivalence class into smaller classes. template <class ELFT> void ICF<ELFT>::segregate(size_t Begin, size_t End, bool Constant) { // This loop rearranges sections in [Begin, End) so that all sections // that are equal in terms of equals{Constant,Variable} are contiguous // in [Begin, End). // // The algorithm is quadratic in the worst case, but that is not an // issue in practice because the number of the distinct sections in // each range is usually very small. while (Begin < End) { // Divide [Begin, End) into two. Let Mid be the start index of the // second group. auto Bound = std::stable_partition(Sections.begin() + Begin + 1, Sections.begin() + End, [&](InputSection *S) { if (Constant) return equalsConstant(Sections[Begin], S); return equalsVariable(Sections[Begin], S); }); size_t Mid = Bound - Sections.begin(); // Now we split [Begin, End) into [Begin, Mid) and [Mid, End) by // updating the sections in [Begin, Mid). We use Mid as an equivalence // class ID because every group ends with a unique index. for (size_t I = Begin; I < Mid; ++I) Sections[I]->Class[Next] = Mid; // If we created a group, we need to iterate the main loop again. if (Mid != End) Repeat = true; Begin = Mid; } } // Compare two lists of relocations. template <class ELFT> template <class RelTy> bool ICF<ELFT>::constantEq(const InputSection *SecA, ArrayRef<RelTy> RA, const InputSection *SecB, ArrayRef<RelTy> RB) { if (RA.size() != RB.size()) return false; for (size_t I = 0; I < RA.size(); ++I) { if (RA[I].r_offset != RB[I].r_offset || RA[I].getType(Config->IsMips64EL) != RB[I].getType(Config->IsMips64EL)) return false; uint64_t AddA = getAddend<ELFT>(RA[I]); uint64_t AddB = getAddend<ELFT>(RB[I]); Symbol &SA = SecA->template getFile<ELFT>()->getRelocTargetSym(RA[I]); Symbol &SB = SecB->template getFile<ELFT>()->getRelocTargetSym(RB[I]); if (&SA == &SB) { if (AddA == AddB) continue; return false; } auto *DA = dyn_cast<Defined>(&SA); auto *DB = dyn_cast<Defined>(&SB); if (!DA || !DB) return false; // Relocations referring to absolute symbols are constant-equal if their // values are equal. if (!DA->Section && !DB->Section && DA->Value + AddA == DB->Value + AddB) continue; if (!DA->Section || !DB->Section) return false; if (DA->Section->kind() != DB->Section->kind()) return false; // Relocations referring to InputSections are constant-equal if their // section offsets are equal. if (isa<InputSection>(DA->Section)) { if (DA->Value + AddA == DB->Value + AddB) continue; return false; } // Relocations referring to MergeInputSections are constant-equal if their // offsets in the output section are equal. auto *X = dyn_cast<MergeInputSection>(DA->Section); if (!X) return false; auto *Y = cast<MergeInputSection>(DB->Section); if (X->getParent() != Y->getParent()) return false; uint64_t OffsetA = SA.isSection() ? X->getOffset(AddA) : X->getOffset(DA->Value) + AddA; uint64_t OffsetB = SB.isSection() ? Y->getOffset(AddB) : Y->getOffset(DB->Value) + AddB; if (OffsetA != OffsetB) return false; } return true; } // Compare "non-moving" part of two InputSections, namely everything // except relocation targets. template <class ELFT> bool ICF<ELFT>::equalsConstant(const InputSection *A, const InputSection *B) { if (A->NumRelocations != B->NumRelocations || A->Flags != B->Flags || A->getSize() != B->getSize() || A->Data != B->Data) return false; // If two sections have different output sections, we cannot merge them. // FIXME: This doesn't do the right thing in the case where there is a linker // script. We probably need to move output section assignment before ICF to // get the correct behaviour here. if (getOutputSectionName(A) != getOutputSectionName(B)) return false; if (A->AreRelocsRela) return constantEq(A, A->template relas<ELFT>(), B, B->template relas<ELFT>()); return constantEq(A, A->template rels<ELFT>(), B, B->template rels<ELFT>()); } // Compare two lists of relocations. Returns true if all pairs of // relocations point to the same section in terms of ICF. template <class ELFT> template <class RelTy> bool ICF<ELFT>::variableEq(const InputSection *SecA, ArrayRef<RelTy> RA, const InputSection *SecB, ArrayRef<RelTy> RB) { assert(RA.size() == RB.size()); for (size_t I = 0; I < RA.size(); ++I) { // The two sections must be identical. Symbol &SA = SecA->template getFile<ELFT>()->getRelocTargetSym(RA[I]); Symbol &SB = SecB->template getFile<ELFT>()->getRelocTargetSym(RB[I]); if (&SA == &SB) continue; auto *DA = cast<Defined>(&SA); auto *DB = cast<Defined>(&SB); // We already dealt with absolute and non-InputSection symbols in // constantEq, and for InputSections we have already checked everything // except the equivalence class. if (!DA->Section) continue; auto *X = dyn_cast<InputSection>(DA->Section); if (!X) continue; auto *Y = cast<InputSection>(DB->Section); // Ineligible sections are in the special equivalence class 0. // They can never be the same in terms of the equivalence class. if (X->Class[Current] == 0) return false; if (X->Class[Current] != Y->Class[Current]) return false; }; return true; } // Compare "moving" part of two InputSections, namely relocation targets. template <class ELFT> bool ICF<ELFT>::equalsVariable(const InputSection *A, const InputSection *B) { if (A->AreRelocsRela) return variableEq(A, A->template relas<ELFT>(), B, B->template relas<ELFT>()); return variableEq(A, A->template rels<ELFT>(), B, B->template rels<ELFT>()); } template <class ELFT> size_t ICF<ELFT>::findBoundary(size_t Begin, size_t End) { uint32_t Class = Sections[Begin]->Class[Current]; for (size_t I = Begin + 1; I < End; ++I) if (Class != Sections[I]->Class[Current]) return I; return End; } // Sections in the same equivalence class are contiguous in Sections // vector. Therefore, Sections vector can be considered as contiguous // groups of sections, grouped by the class. // // This function calls Fn on every group within [Begin, End). template <class ELFT> void ICF<ELFT>::forEachClassRange(size_t Begin, size_t End, std::function<void(size_t, size_t)> Fn) { while (Begin < End) { size_t Mid = findBoundary(Begin, End); Fn(Begin, Mid); Begin = Mid; } } // Call Fn on each equivalence class. template <class ELFT> void ICF<ELFT>::forEachClass(std::function<void(size_t, size_t)> Fn) { // If threading is disabled or the number of sections are // too small to use threading, call Fn sequentially. if (!ThreadsEnabled || Sections.size() < 1024) { forEachClassRange(0, Sections.size(), Fn); ++Cnt; return; } Current = Cnt % 2; Next = (Cnt + 1) % 2; // Shard into non-overlapping intervals, and call Fn in parallel. // The sharding must be completed before any calls to Fn are made // so that Fn can modify the Chunks in its shard without causing data // races. const size_t NumShards = 256; size_t Step = Sections.size() / NumShards; size_t Boundaries[NumShards + 1]; Boundaries[0] = 0; Boundaries[NumShards] = Sections.size(); parallelForEachN(1, NumShards, [&](size_t I) { Boundaries[I] = findBoundary((I - 1) * Step, Sections.size()); }); parallelForEachN(1, NumShards + 1, [&](size_t I) { if (Boundaries[I - 1] < Boundaries[I]) forEachClassRange(Boundaries[I - 1], Boundaries[I], Fn); }); ++Cnt; } static void print(const Twine &S) { if (Config->PrintIcfSections) message(S); } // The main function of ICF. template <class ELFT> void ICF<ELFT>::run() { // Collect sections to merge. for (InputSectionBase *Sec : InputSections) if (auto *S = dyn_cast<InputSection>(Sec)) if (isEligible(S)) Sections.push_back(S); // Initially, we use hash values to partition sections. parallelForEach(Sections, [&](InputSection *S) { // Set MSB to 1 to avoid collisions with non-hash IDs. S->Class[0] = getHash<ELFT>(S) | (1 << 31); }); // From now on, sections in Sections vector are ordered so that sections // in the same equivalence class are consecutive in the vector. std::stable_sort(Sections.begin(), Sections.end(), [](InputSection *A, InputSection *B) { return A->Class[0] < B->Class[0]; }); // Compare static contents and assign unique IDs for each static content. forEachClass([&](size_t Begin, size_t End) { segregate(Begin, End, true); }); // Split groups by comparing relocations until convergence is obtained. do { Repeat = false; forEachClass( [&](size_t Begin, size_t End) { segregate(Begin, End, false); }); } while (Repeat); log("ICF needed " + Twine(Cnt) + " iterations"); // Merge sections by the equivalence class. forEachClassRange(0, Sections.size(), [&](size_t Begin, size_t End) { if (End - Begin == 1) return; print("selected section " + toString(Sections[Begin])); for (size_t I = Begin + 1; I < End; ++I) { print(" removing identical section " + toString(Sections[I])); Sections[Begin]->replace(Sections[I]); // At this point we know sections merged are fully identical and hence // we want to remove duplicate implicit dependencies such as link order // and relocation sections. for (InputSection *IS : Sections[I]->DependentSections) IS->Live = false; } }); } // ICF entry point function. template <class ELFT> void elf::doIcf() { ICF<ELFT>().run(); } template void elf::doIcf<ELF32LE>(); template void elf::doIcf<ELF32BE>(); template void elf::doIcf<ELF64LE>(); template void elf::doIcf<ELF64BE>();
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 5 End-User License Agreement and JUCE 5 Privacy Policy (both updated and effective as of the 27th April 2017). End User License Agreement: www.juce.com/juce-5-licence Privacy Policy: www.juce.com/juce-5-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { #if JUCE_IOS struct AppInactivityCallback // NB: this is a duplicate of an internal declaration in juce_core { virtual ~AppInactivityCallback() {} virtual void appBecomingInactive() = 0; }; extern Array<AppInactivityCallback*> appBecomingInactiveCallbacks; // On iOS, all GL calls will crash when the app is running in the background, so // this prevents them from happening (which some messy locking behaviour) struct iOSBackgroundProcessCheck : public AppInactivityCallback { iOSBackgroundProcessCheck() { isBackgroundProcess(); appBecomingInactiveCallbacks.add (this); } ~iOSBackgroundProcessCheck() { appBecomingInactiveCallbacks.removeAllInstancesOf (this); } bool isBackgroundProcess() { const bool b = Process::isForegroundProcess(); isForeground.set (b ? 1 : 0); return ! b; } void appBecomingInactive() override { int counter = 2000; while (--counter > 0 && isForeground.get() != 0) Thread::sleep (1); } private: Atomic<int> isForeground; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (iOSBackgroundProcessCheck) }; #endif //============================================================================== class OpenGLContext::CachedImage : public CachedComponentImage, private ThreadPoolJob { public: CachedImage (OpenGLContext& c, Component& comp, const OpenGLPixelFormat& pixFormat, void* contextToShare) : ThreadPoolJob ("OpenGL Rendering"), context (c), component (comp) { nativeContext = new NativeContext (component, pixFormat, contextToShare, c.useMultisampling, c.versionRequired); if (nativeContext->createdOk()) context.nativeContext = nativeContext; else nativeContext = nullptr; } ~CachedImage() { stop(); } //============================================================================== void start() { if (nativeContext != nullptr) { renderThread = new ThreadPool (1); resume(); } } void stop() { if (renderThread != nullptr) { // make sure everything has finished executing destroying.set (1); if (workQueue.size() > 0) { if (! renderThread->contains (this)) resume(); while (workQueue.size() != 0) Thread::sleep (20); } pause(); renderThread = nullptr; } hasInitialised = false; } //============================================================================== void pause() { signalJobShouldExit(); messageManagerLock.abort(); if (renderThread != nullptr) { repaintEvent.signal(); renderThread->removeJob (this, true, -1); } } void resume() { if (renderThread != nullptr) renderThread->addJob (this, false); } //============================================================================== void paint (Graphics&) override {} bool invalidateAll() override { validArea.clear(); triggerRepaint(); return false; } bool invalidate (const Rectangle<int>& area) override { validArea.subtract (area * scale); triggerRepaint(); return false; } void releaseResources() override { stop(); } void triggerRepaint() { needsUpdate = 1; repaintEvent.signal(); } //============================================================================== bool ensureFrameBufferSize() { auto fbW = cachedImageFrameBuffer.getWidth(); auto fbH = cachedImageFrameBuffer.getHeight(); if (fbW != viewportArea.getWidth() || fbH != viewportArea.getHeight() || ! cachedImageFrameBuffer.isValid()) { if (! cachedImageFrameBuffer.initialise (context, viewportArea.getWidth(), viewportArea.getHeight())) return false; validArea.clear(); JUCE_CHECK_OPENGL_ERROR } return true; } void clearRegionInFrameBuffer (const RectangleList<int>& list) { glClearColor (0, 0, 0, 0); glEnable (GL_SCISSOR_TEST); auto previousFrameBufferTarget = OpenGLFrameBuffer::getCurrentFrameBufferTarget(); cachedImageFrameBuffer.makeCurrentRenderingTarget(); auto imageH = cachedImageFrameBuffer.getHeight(); for (auto& r : list) { glScissor (r.getX(), imageH - r.getBottom(), r.getWidth(), r.getHeight()); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); } glDisable (GL_SCISSOR_TEST); context.extensions.glBindFramebuffer (GL_FRAMEBUFFER, previousFrameBufferTarget); JUCE_CHECK_OPENGL_ERROR } bool renderFrame() { MessageManager::Lock::ScopedTryLockType mmLock (messageManagerLock, false); const bool isUpdating = needsUpdate.compareAndSetBool (0, 1); if (context.renderComponents && isUpdating) { // This avoids hogging the message thread when doing intensive rendering. if (lastMMLockReleaseTime + 1 >= Time::getMillisecondCounter()) Thread::sleep (2); while (! shouldExit()) { doWorkWhileWaitingForLock (false); if (mmLock.retryLock ()) break; } if (shouldExit()) return false; updateViewportSize (false); } if (! context.makeActive()) return false; NativeContext::Locker locker (*nativeContext); JUCE_CHECK_OPENGL_ERROR doWorkWhileWaitingForLock (true); if (context.renderer != nullptr) { glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight()); context.currentRenderScale = scale; context.renderer->renderOpenGL(); clearGLError(); bindVertexArray(); } if (context.renderComponents) { if (isUpdating) { paintComponent(); if (! hasInitialised) return false; messageManagerLock.exit(); lastMMLockReleaseTime = Time::getMillisecondCounter(); } glViewport (0, 0, viewportArea.getWidth(), viewportArea.getHeight()); drawComponentBuffer(); } context.swapBuffers(); OpenGLContext::deactivateCurrentContext(); return true; } void updateViewportSize (bool canTriggerUpdate) { if (auto* peer = component.getPeer()) { lastScreenBounds = component.getTopLevelComponent()->getScreenBounds(); auto newScale = Desktop::getInstance().getDisplays() .getDisplayContaining (lastScreenBounds.getCentre()).scale; auto newArea = peer->getComponent().getLocalArea (&component, component.getLocalBounds()) .withZeroOrigin() * newScale; if (scale != newScale || viewportArea != newArea) { scale = newScale; viewportArea = newArea; if (canTriggerUpdate) invalidateAll(); } } } void bindVertexArray() noexcept { #if JUCE_OPENGL3 if (vertexArrayObject != 0) context.extensions.glBindVertexArray (vertexArrayObject); #endif } void checkViewportBounds() { auto screenBounds = component.getTopLevelComponent()->getScreenBounds(); if (lastScreenBounds != screenBounds) updateViewportSize (true); } void paintComponent() { // you mustn't set your own cached image object when attaching a GL context! jassert (get (component) == this); if (! ensureFrameBufferSize()) return; RectangleList<int> invalid (viewportArea); invalid.subtract (validArea); validArea = viewportArea; if (! invalid.isEmpty()) { clearRegionInFrameBuffer (invalid); { ScopedPointer<LowLevelGraphicsContext> g (createOpenGLGraphicsContext (context, cachedImageFrameBuffer)); g->clipToRectangleList (invalid); g->addTransform (AffineTransform::scale ((float) scale)); paintOwner (*g); JUCE_CHECK_OPENGL_ERROR } if (! context.isActive()) context.makeActive(); } JUCE_CHECK_OPENGL_ERROR } void drawComponentBuffer() { #if ! JUCE_ANDROID glEnable (GL_TEXTURE_2D); clearGLError(); #endif #if JUCE_WINDOWS // some stupidly old drivers are missing this function, so try to at least avoid a crash here, // but if you hit this assertion you may want to have your own version check before using the // component rendering stuff on such old drivers. jassert (context.extensions.glActiveTexture != nullptr); if (context.extensions.glActiveTexture != nullptr) #endif context.extensions.glActiveTexture (GL_TEXTURE0); glBindTexture (GL_TEXTURE_2D, cachedImageFrameBuffer.getTextureID()); bindVertexArray(); const Rectangle<int> cacheBounds (cachedImageFrameBuffer.getWidth(), cachedImageFrameBuffer.getHeight()); context.copyTexture (cacheBounds, cacheBounds, cacheBounds.getWidth(), cacheBounds.getHeight(), false); glBindTexture (GL_TEXTURE_2D, 0); JUCE_CHECK_OPENGL_ERROR } void paintOwner (LowLevelGraphicsContext& llgc) { Graphics g (llgc); #if JUCE_ENABLE_REPAINT_DEBUGGING #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE) #endif { g.saveState(); } #endif JUCE_TRY { component.paintEntireComponent (g, false); } JUCE_CATCH_EXCEPTION #if JUCE_ENABLE_REPAINT_DEBUGGING #ifdef JUCE_IS_REPAINT_DEBUGGING_ACTIVE if (JUCE_IS_REPAINT_DEBUGGING_ACTIVE) #endif { // enabling this code will fill all areas that get repainted with a colour overlay, to show // clearly when things are being repainted. g.restoreState(); static Random rng; g.fillAll (Colour ((uint8) rng.nextInt (255), (uint8) rng.nextInt (255), (uint8) rng.nextInt (255), (uint8) 0x50)); } #endif } void handleResize() { updateViewportSize (true); #if JUCE_MAC if (hasInitialised) { [nativeContext->view update]; renderFrame(); } #endif } //============================================================================== JobStatus runJob() override { { // Allow the message thread to finish setting-up the context before using it.. MessageManager::Lock::ScopedTryLockType mmLock (messageManagerLock, false); do { if (shouldExit()) return ThreadPoolJob::jobHasFinished; } while (! mmLock.retryLock ()); } initialiseOnThread(); hasInitialised = true; while (! shouldExit()) { #if JUCE_IOS if (backgroundProcessCheck.isBackgroundProcess()) { repaintEvent.wait (300); continue; } #endif if (shouldExit()) break; if (! renderFrame()) repaintEvent.wait (5); // failed to render, so avoid a tight fail-loop. else if (! context.continuousRepaint && ! shouldExit()) repaintEvent.wait (-1); } hasInitialised = false; context.makeActive(); shutdownOnThread(); OpenGLContext::deactivateCurrentContext(); return ThreadPoolJob::jobHasFinished; } void initialiseOnThread() { // On android, this can get called twice, so drop any previous state.. associatedObjectNames.clear(); associatedObjects.clear(); cachedImageFrameBuffer.release(); context.makeActive(); nativeContext->initialiseOnRenderThread (context); #if JUCE_ANDROID // On android the context may be created in initialiseOnRenderThread // and we therefore need to call makeActive again context.makeActive(); #endif context.extensions.initialise(); #if JUCE_OPENGL3 if (OpenGLShaderProgram::getLanguageVersion() > 1.2) { context.extensions.glGenVertexArrays (1, &vertexArrayObject); bindVertexArray(); } #endif glViewport (0, 0, component.getWidth(), component.getHeight()); nativeContext->setSwapInterval (1); #if ! JUCE_OPENGL_ES JUCE_CHECK_OPENGL_ERROR shadersAvailable = OpenGLShaderProgram::getLanguageVersion() > 0; clearGLError(); #endif if (context.renderer != nullptr) context.renderer->newOpenGLContextCreated(); } void shutdownOnThread() { if (context.renderer != nullptr) context.renderer->openGLContextClosing(); #if JUCE_OPENGL3 if (vertexArrayObject != 0) context.extensions.glDeleteVertexArrays (1, &vertexArrayObject); #endif associatedObjectNames.clear(); associatedObjects.clear(); cachedImageFrameBuffer.release(); nativeContext->shutdownOnRenderThread(); } //============================================================================== struct BlockingWorker : public OpenGLContext::AsyncWorker { BlockingWorker (OpenGLContext::AsyncWorker::Ptr && workerToUse) : originalWorker (static_cast<OpenGLContext::AsyncWorker::Ptr&&> (workerToUse)) {} void operator() (OpenGLContext& calleeContext) { if (originalWorker != nullptr) (*originalWorker) (calleeContext); finishedSignal.signal(); } void block() noexcept { finishedSignal.wait(); } OpenGLContext::AsyncWorker::Ptr originalWorker; WaitableEvent finishedSignal; }; bool doWorkWhileWaitingForLock (bool contextIsAlreadyActive) { bool contextActivated = false; for (OpenGLContext::AsyncWorker::Ptr work = workQueue.removeAndReturn (0); work != nullptr && (! shouldExit()); work = workQueue.removeAndReturn (0)) { if ((! contextActivated) && (! contextIsAlreadyActive)) { if (! context.makeActive()) break; contextActivated = true; } NativeContext::Locker locker (*nativeContext); (*work) (context); clearGLError(); } if (contextActivated) OpenGLContext::deactivateCurrentContext(); return shouldExit(); } void execute (OpenGLContext::AsyncWorker::Ptr workerToUse, bool shouldBlock, bool calledFromDestructor = false) { if (calledFromDestructor || destroying.get() == 0) { BlockingWorker* blocker = (shouldBlock ? new BlockingWorker (static_cast<OpenGLContext::AsyncWorker::Ptr&&> (workerToUse)) : nullptr); OpenGLContext::AsyncWorker::Ptr worker = (blocker != nullptr ? blocker : static_cast<OpenGLContext::AsyncWorker::Ptr&&> (workerToUse)); workQueue.add (worker); messageManagerLock.abort(); context.triggerRepaint(); if (blocker != nullptr) blocker->block(); } else { jassertfalse; // you called execute AFTER you detached your openglcontext } } //============================================================================== static CachedImage* get (Component& c) noexcept { return dynamic_cast<CachedImage*> (c.getCachedComponentImage()); } //============================================================================== friend class NativeContext; ScopedPointer<NativeContext> nativeContext; OpenGLContext& context; Component& component; OpenGLFrameBuffer cachedImageFrameBuffer; RectangleList<int> validArea; Rectangle<int> viewportArea, lastScreenBounds; double scale = 1.0; #if JUCE_OPENGL3 GLuint vertexArrayObject = 0; #endif StringArray associatedObjectNames; ReferenceCountedArray<ReferenceCountedObject> associatedObjects; WaitableEvent canPaintNowFlag, finishedPaintingFlag, repaintEvent; #if JUCE_OPENGL_ES bool shadersAvailable = true; #else bool shadersAvailable = false; #endif bool hasInitialised = false; Atomic<int> needsUpdate { 1 }, destroying; uint32 lastMMLockReleaseTime = 0; ScopedPointer<ThreadPool> renderThread; ReferenceCountedArray<OpenGLContext::AsyncWorker, CriticalSection> workQueue; MessageManager::Lock messageManagerLock; #if JUCE_IOS iOSBackgroundProcessCheck backgroundProcessCheck; #endif JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CachedImage) }; //============================================================================== class OpenGLContext::Attachment : public ComponentMovementWatcher, private Timer { public: Attachment (OpenGLContext& c, Component& comp) : ComponentMovementWatcher (&comp), context (c) { if (canBeAttached (comp)) attach(); } ~Attachment() { detach(); } void detach() { auto& comp = *getComponent(); stop(); comp.setCachedComponentImage (nullptr); context.nativeContext = nullptr; } void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) override { auto& comp = *getComponent(); if (isAttached (comp) != canBeAttached (comp)) componentVisibilityChanged(); if (comp.getWidth() > 0 && comp.getHeight() > 0 && context.nativeContext != nullptr) { if (auto* c = CachedImage::get (comp)) c->handleResize(); if (auto* peer = comp.getTopLevelComponent()->getPeer()) context.nativeContext->updateWindowPosition (peer->getAreaCoveredBy (comp)); } } void componentPeerChanged() override { detach(); componentVisibilityChanged(); } void componentVisibilityChanged() override { auto& comp = *getComponent(); if (canBeAttached (comp)) { if (isAttached (comp)) comp.repaint(); // (needed when windows are un-minimised) else attach(); } else { detach(); } } #if JUCE_DEBUG || JUCE_LOG_ASSERTIONS void componentBeingDeleted (Component& c) override { /* You must call detach() or delete your OpenGLContext to remove it from a component BEFORE deleting the component that it is using! */ jassertfalse; ComponentMovementWatcher::componentBeingDeleted (c); } #endif void update() { auto& comp = *getComponent(); if (canBeAttached (comp)) start(); else stop(); } private: OpenGLContext& context; bool canBeAttached (const Component& comp) noexcept { return (! context.overrideCanAttach) && comp.getWidth() > 0 && comp.getHeight() > 0 && isShowingOrMinimised (comp); } static bool isShowingOrMinimised (const Component& c) { if (! c.isVisible()) return false; if (auto* p = c.getParentComponent()) return isShowingOrMinimised (*p); return c.getPeer() != nullptr; } static bool isAttached (const Component& comp) noexcept { return comp.getCachedComponentImage() != nullptr; } void attach() { auto& comp = *getComponent(); auto* newCachedImage = new CachedImage (context, comp, context.openGLPixelFormat, context.contextToShareWith); comp.setCachedComponentImage (newCachedImage); start(); } void stop() { stopTimer(); auto& comp = *getComponent(); #if JUCE_MAC [[(NSView*) comp.getWindowHandle() window] disableScreenUpdatesUntilFlush]; #endif if (auto* oldCachedImage = CachedImage::get (comp)) oldCachedImage->stop(); // (must stop this before detaching it from the component) } void start() { auto& comp = *getComponent(); if (auto* cachedImage = CachedImage::get (comp)) { cachedImage->start(); // (must wait until this is attached before starting its thread) cachedImage->updateViewportSize (true); startTimer (400); } } void timerCallback() override { if (auto* cachedImage = CachedImage::get (*getComponent())) cachedImage->checkViewportBounds(); } }; //============================================================================== OpenGLContext::OpenGLContext() { } OpenGLContext::~OpenGLContext() { detach(); } void OpenGLContext::setRenderer (OpenGLRenderer* rendererToUse) noexcept { // This method must not be called when the context has already been attached! // Call it before attaching your context, or use detach() first, before calling this! jassert (nativeContext == nullptr); renderer = rendererToUse; } void OpenGLContext::setComponentPaintingEnabled (bool shouldPaintComponent) noexcept { // This method must not be called when the context has already been attached! // Call it before attaching your context, or use detach() first, before calling this! jassert (nativeContext == nullptr); renderComponents = shouldPaintComponent; } void OpenGLContext::setContinuousRepainting (bool shouldContinuouslyRepaint) noexcept { continuousRepaint = shouldContinuouslyRepaint; triggerRepaint(); } void OpenGLContext::setPixelFormat (const OpenGLPixelFormat& preferredPixelFormat) noexcept { // This method must not be called when the context has already been attached! // Call it before attaching your context, or use detach() first, before calling this! jassert (nativeContext == nullptr); openGLPixelFormat = preferredPixelFormat; } void OpenGLContext::setTextureMagnificationFilter (OpenGLContext::TextureMagnificationFilter magFilterMode) noexcept { texMagFilter = magFilterMode; } void OpenGLContext::setNativeSharedContext (void* nativeContextToShareWith) noexcept { // This method must not be called when the context has already been attached! // Call it before attaching your context, or use detach() first, before calling this! jassert (nativeContext == nullptr); contextToShareWith = nativeContextToShareWith; } void OpenGLContext::setMultisamplingEnabled (bool b) noexcept { // This method must not be called when the context has already been attached! // Call it before attaching your context, or use detach() first, before calling this! jassert (nativeContext == nullptr); useMultisampling = b; } void OpenGLContext::setOpenGLVersionRequired (OpenGLVersion v) noexcept { versionRequired = v; } void OpenGLContext::attachTo (Component& component) { component.repaint(); if (getTargetComponent() != &component) { detach(); attachment = new Attachment (*this, component); } } void OpenGLContext::detach() { if (auto* a = attachment.get()) { a->detach(); // must detach before nulling our pointer attachment = nullptr; } nativeContext = nullptr; } bool OpenGLContext::isAttached() const noexcept { return nativeContext != nullptr; } Component* OpenGLContext::getTargetComponent() const noexcept { return attachment != nullptr ? attachment->getComponent() : nullptr; } OpenGLContext* OpenGLContext::getContextAttachedTo (Component& c) noexcept { if (auto* ci = CachedImage::get (c)) return &(ci->context); return nullptr; } static ThreadLocalValue<OpenGLContext*> currentThreadActiveContext; OpenGLContext* OpenGLContext::getCurrentContext() { return currentThreadActiveContext.get(); } bool OpenGLContext::makeActive() const noexcept { auto& current = currentThreadActiveContext.get(); if (nativeContext != nullptr && nativeContext->makeActive()) { current = const_cast<OpenGLContext*> (this); return true; } current = nullptr; return false; } bool OpenGLContext::isActive() const noexcept { return nativeContext != nullptr && nativeContext->isActive(); } void OpenGLContext::deactivateCurrentContext() { NativeContext::deactivateCurrentContext(); currentThreadActiveContext.get() = nullptr; } void OpenGLContext::triggerRepaint() { if (auto* cachedImage = getCachedImage()) cachedImage->triggerRepaint(); } void OpenGLContext::swapBuffers() { if (nativeContext != nullptr) nativeContext->swapBuffers(); } unsigned int OpenGLContext::getFrameBufferID() const noexcept { return nativeContext != nullptr ? nativeContext->getFrameBufferID() : 0; } bool OpenGLContext::setSwapInterval (int numFramesPerSwap) { return nativeContext != nullptr && nativeContext->setSwapInterval (numFramesPerSwap); } int OpenGLContext::getSwapInterval() const { return nativeContext != nullptr ? nativeContext->getSwapInterval() : 0; } void* OpenGLContext::getRawContext() const noexcept { return nativeContext != nullptr ? nativeContext->getRawContext() : nullptr; } OpenGLContext::CachedImage* OpenGLContext::getCachedImage() const noexcept { if (auto* comp = getTargetComponent()) return CachedImage::get (*comp); return nullptr; } bool OpenGLContext::areShadersAvailable() const { auto* c = getCachedImage(); return c != nullptr && c->shadersAvailable; } ReferenceCountedObject* OpenGLContext::getAssociatedObject (const char* name) const { jassert (name != nullptr); auto* c = getCachedImage(); // This method must only be called from an openGL rendering callback. jassert (c != nullptr && nativeContext != nullptr); jassert (getCurrentContext() != nullptr); const int index = c->associatedObjectNames.indexOf (name); return index >= 0 ? c->associatedObjects.getUnchecked (index) : nullptr; } void OpenGLContext::setAssociatedObject (const char* name, ReferenceCountedObject* newObject) { jassert (name != nullptr); if (auto* c = getCachedImage()) { // This method must only be called from an openGL rendering callback. jassert (nativeContext != nullptr); jassert (getCurrentContext() != nullptr); const int index = c->associatedObjectNames.indexOf (name); if (index >= 0) { if (newObject != nullptr) { c->associatedObjects.set (index, newObject); } else { c->associatedObjectNames.remove (index); c->associatedObjects.remove (index); } } else if (newObject != nullptr) { c->associatedObjectNames.add (name); c->associatedObjects.add (newObject); } } } void OpenGLContext::setImageCacheSize (size_t newSize) noexcept { imageCacheMaxSize = newSize; } size_t OpenGLContext::getImageCacheSize() const noexcept { return imageCacheMaxSize; } void OpenGLContext::execute (OpenGLContext::AsyncWorker::Ptr workerToUse, bool shouldBlock) { if (auto* c = getCachedImage()) c->execute (static_cast<OpenGLContext::AsyncWorker::Ptr&&> (workerToUse), shouldBlock); else jassertfalse; // You must have attached the context to a component } void OpenGLContext::overrideCanBeAttached (bool newCanAttach) { if (overrideCanAttach != newCanAttach) { overrideCanAttach = newCanAttach; if (auto* a = attachment.get()) a->update(); } } //============================================================================== struct DepthTestDisabler { DepthTestDisabler() noexcept { glGetBooleanv (GL_DEPTH_TEST, &wasEnabled); if (wasEnabled) glDisable (GL_DEPTH_TEST); } ~DepthTestDisabler() noexcept { if (wasEnabled) glEnable (GL_DEPTH_TEST); } GLboolean wasEnabled; }; //============================================================================== void OpenGLContext::copyTexture (const Rectangle<int>& targetClipArea, const Rectangle<int>& anchorPosAndTextureSize, const int contextWidth, const int contextHeight, bool flippedVertically) { if (contextWidth <= 0 || contextHeight <= 0) return; JUCE_CHECK_OPENGL_ERROR glBlendFunc (GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glEnable (GL_BLEND); DepthTestDisabler depthDisabler; if (areShadersAvailable()) { struct OverlayShaderProgram : public ReferenceCountedObject { OverlayShaderProgram (OpenGLContext& context) : program (context), builder (program), params (program) {} static const OverlayShaderProgram& select (OpenGLContext& context) { static const char programValueID[] = "juceGLComponentOverlayShader"; OverlayShaderProgram* program = static_cast<OverlayShaderProgram*> (context.getAssociatedObject (programValueID)); if (program == nullptr) { program = new OverlayShaderProgram (context); context.setAssociatedObject (programValueID, program); } program->program.use(); return *program; } struct ProgramBuilder { ProgramBuilder (OpenGLShaderProgram& prog) { prog.addVertexShader (OpenGLHelpers::translateVertexShaderToV3 ( "attribute " JUCE_HIGHP " vec2 position;" "uniform " JUCE_HIGHP " vec2 screenSize;" "uniform " JUCE_HIGHP " float textureBounds[4];" "uniform " JUCE_HIGHP " vec2 vOffsetAndScale;" "varying " JUCE_HIGHP " vec2 texturePos;" "void main()" "{" JUCE_HIGHP " vec2 scaled = position / (0.5 * screenSize.xy);" "gl_Position = vec4 (scaled.x - 1.0, 1.0 - scaled.y, 0, 1.0);" "texturePos = (position - vec2 (textureBounds[0], textureBounds[1])) / vec2 (textureBounds[2], textureBounds[3]);" "texturePos = vec2 (texturePos.x, vOffsetAndScale.x + vOffsetAndScale.y * texturePos.y);" "}")); prog.addFragmentShader (OpenGLHelpers::translateFragmentShaderToV3 ( "uniform sampler2D imageTexture;" "varying " JUCE_HIGHP " vec2 texturePos;" "void main()" "{" "gl_FragColor = texture2D (imageTexture, texturePos);" "}")); prog.link(); } }; struct Params { Params (OpenGLShaderProgram& prog) : positionAttribute (prog, "position"), screenSize (prog, "screenSize"), imageTexture (prog, "imageTexture"), textureBounds (prog, "textureBounds"), vOffsetAndScale (prog, "vOffsetAndScale") {} void set (const float targetWidth, const float targetHeight, const Rectangle<float>& bounds, bool flipVertically) const { const GLfloat m[] = { bounds.getX(), bounds.getY(), bounds.getWidth(), bounds.getHeight() }; textureBounds.set (m, 4); imageTexture.set (0); screenSize.set (targetWidth, targetHeight); vOffsetAndScale.set (flipVertically ? 0.0f : 1.0f, flipVertically ? 1.0f : -1.0f); } OpenGLShaderProgram::Attribute positionAttribute; OpenGLShaderProgram::Uniform screenSize, imageTexture, textureBounds, vOffsetAndScale; }; OpenGLShaderProgram program; ProgramBuilder builder; Params params; }; auto left = (GLshort) targetClipArea.getX(); auto top = (GLshort) targetClipArea.getY(); auto right = (GLshort) targetClipArea.getRight(); auto bottom = (GLshort) targetClipArea.getBottom(); const GLshort vertices[] = { left, bottom, right, bottom, left, top, right, top }; auto& program = OverlayShaderProgram::select (*this); program.params.set ((float) contextWidth, (float) contextHeight, anchorPosAndTextureSize.toFloat(), flippedVertically); GLuint vertexBuffer = 0; extensions.glGenBuffers (1, &vertexBuffer); extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer); extensions.glBufferData (GL_ARRAY_BUFFER, sizeof (vertices), vertices, GL_STATIC_DRAW); auto index = (GLuint) program.params.positionAttribute.attributeID; extensions.glVertexAttribPointer (index, 2, GL_SHORT, GL_FALSE, 4, 0); extensions.glEnableVertexAttribArray (index); JUCE_CHECK_OPENGL_ERROR glDrawArrays (GL_TRIANGLE_STRIP, 0, 4); extensions.glBindBuffer (GL_ARRAY_BUFFER, 0); extensions.glUseProgram (0); extensions.glDisableVertexAttribArray (index); extensions.glDeleteBuffers (1, &vertexBuffer); } else { jassert (attachment == nullptr); // Running on an old graphics card! } JUCE_CHECK_OPENGL_ERROR } #if JUCE_ANDROID EGLDisplay OpenGLContext::NativeContext::display = EGL_NO_DISPLAY; EGLDisplay OpenGLContext::NativeContext::config; void OpenGLContext::NativeContext::surfaceCreated (jobject holder) { ignoreUnused (holder); if (auto* cachedImage = CachedImage::get (component)) { if (auto* pool = cachedImage->renderThread.get()) { if (! pool->contains (cachedImage)) { cachedImage->resume(); cachedImage->context.triggerRepaint(); } } } } void OpenGLContext::NativeContext::surfaceDestroyed (jobject holder) { ignoreUnused (holder); // unlike the name suggests this will be called just before the // surface is destroyed. We need to pause the render thread. if (auto* cachedImage = CachedImage::get (component)) { cachedImage->pause(); if (auto* threadPool = cachedImage->renderThread.get()) threadPool->waitForJobToFinish (cachedImage, -1); } } #endif } // namespace juce
// 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 "sky/scheduler/timer.h" #include <cstdlib> #include "base/bind.h" #include "base/tracked_objects.h" namespace sky { // We're willing to slop around 1/4 of a tick duration to avoid trashing our // client with irregular ticks. static const int64 kTickSlop = 4; Timer::Client::~Client() { } Timer::Timer(Client* client, scoped_refptr<base::SingleThreadTaskRunner> task_runner) : client_(client), task_runner_(task_runner), enabled_(false), weak_factory_(this) { DCHECK(client_); } Timer::~Timer() { } void Timer::SetEnabled(bool enabled) { enabled_ = enabled; if (enabled_ && current_target_.is_null()) ScheduleNextTick(base::TimeTicks::Now()); } void Timer::SetInterval(const TimeInterval& interval) { interval_ = interval; // We don't have a tick scheduled, so there's no need to reschedule it. if (current_target_.is_null()) return; base::TimeTicks now = base::TimeTicks::Now(); base::TimeTicks new_target = NextTickTarget(now); base::TimeDelta delta = base::TimeDelta::FromInternalValue( std::abs((new_target - current_target_).ToInternalValue())); if (delta * kTickSlop < interval_.duration) return; current_target_ = base::TimeTicks(); weak_factory_.InvalidateWeakPtrs(); PostTickTask(now, new_target); } base::TimeTicks Timer::NextTickTarget(base::TimeTicks now) { base::TimeTicks target = interval_.NextAfter(now); // If we're targeting a time that's too soon since the last tick, we push out // the target to the next tick. if ((target - last_tick_) * kTickSlop < interval_.duration) target += interval_.duration; return target; } void Timer::ScheduleNextTick(base::TimeTicks now) { PostTickTask(now, NextTickTarget(now)); } void Timer::PostTickTask(base::TimeTicks now, base::TimeTicks target) { DCHECK(current_target_.is_null()); current_target_ = target; task_runner_->PostDelayedTask( FROM_HERE, base::Bind(&Timer::OnTimerFired, weak_factory_.GetWeakPtr()), current_target_ - now); } void Timer::OnTimerFired() { current_target_ = base::TimeTicks(); if (!enabled_) return; base::TimeTicks now = base::TimeTicks::Now(); ScheduleNextTick(now); last_tick_ = now; client_->OnTimerTick(now); // We might be deleted here. } }
// List.cpp - Implementation of List ADT using Array #include "List.h" // header file // constructor List::List() { size = 0; } // add an item to the back of the list (append) bool List::add(ItemType item) { bool success = size < MAX_SIZE; if (success) { items[size] = item; // add to the end of the list size++; // increase the size by 1 } return success; } // add an item at a specified position in the list (insert) bool List::add(int index, ItemType item) { bool success = (index >= 0) && (index <= size) && (size < MAX_SIZE); if (success) { // make room for the item by shifting all items at // positions >= index toward the end of the // List (no shift if index == size + 1) for (int pos = size; pos >= index; pos--) items[pos] = items[pos - 1]; // insert the item items[index] = item; size++; // increase the size by 1 } return success; } // remove an item at a specified position in the list void List::remove(int index) { bool success = (index >= 0) && (index < size); if (success) { // delete item by shifting all items at positions > // index toward the beginning of the list // (no shift if index == size) for (int pos = index; pos < size; pos++) items[pos] = items[pos + 1]; size--; // decrease the size by 1 } } // get an item at a specified position of the list (retrieve) ItemType List::get(int index) { bool success = (index >= 0) && (index < size); if (success) return items[index]; else return -1; } // check if the list is empty bool List::isEmpty() { return size == 0; } // check the size of the list int List::getLength() { return size; } // display the items in the list void List::print() { for (int a = 0; a < size; a++) { cout << items[a] << endl; } cout << "" << endl; } void List::replace(int index, ItemType item) { bool success = (index >= 0) && (index <= size) && (size < MAX_SIZE); if (success) { items[index] = item; } }
#include<iostream> #include<vector> #include<fstream> #include<algorithm> #include<cstdlib> using namespace std; #define ll long long int main() { // freopen("out.txt","w", stdout); vector<ll> v; ll t, p, l, k = 0; cin >> t; while (t--) { cin >> p >> l; ll b; b = p - l; k++; cout << "Case " << k << ": "; if (!p && !l) { cout << "1"; } else if (b < l) { cout << "impossible"; } else { int u = 0; for (ll i = 1; i * i <= b; i++) { if (b % i == 0) { if (i != b / i) { v.push_back(i); v.push_back(b / i); } else v.push_back(i); } } sort(v.begin(), v.end()); for (ll i = 0; i < v.size(); i++) { if (v[i] > l) { u = 1; cout << v[i]; if (i != v.size() - 1) { cout << " "; } } } if (u == 0) { cout << "impossible"; } } cout << endl; v.clear(); } return 0; }
// Copyright (c) 2019, NVIDIA CORPORATION. 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 "dali/pipeline/util/copy_with_stride.h" #include <cstring> #include <cassert> #include "dali/core/static_switch.h" #include "dali/core/util.h" namespace dali { inline void CopyVec(uint8 *output, const uint8 *input, size_t elems, size_t in_stride, size_t item_size) { for (size_t i = 0; i < elems; ++i) { for (size_t j = 0; j < item_size; j++) *output++ = input[j]; input += in_stride; } } template <size_t item_size> inline void CopyVecStatic(uint8 *output, const uint8 *input, size_t elems, size_t in_stride) { for (size_t i = 0; i < elems; ++i) { for (size_t j = 0; j < item_size; j++) output[j] = input[j]; output += item_size; input += in_stride; } } inline void CopyWithStrideHelper(void *output, const void *input, const Index *in_strides, const Index *out_strides, const Index *shape, Index ndim, Index dim, Index deepest_contiguous) { auto out_ptr = reinterpret_cast<uint8*>(output); auto in_ptr = reinterpret_cast<const uint8*>(input); const auto item_size = out_strides[ndim - 1]; if (dim == deepest_contiguous) { std::memcpy(out_ptr, in_ptr, volume(shape + dim, shape + ndim)*item_size); return; } if (dim == ndim - 1) { VALUE_SWITCH(item_size, elem_size, (1, 2, 3, 4, 5, 6, 7, 8, 12, 16), (CopyVecStatic<elem_size>(out_ptr, in_ptr, shape[ndim - 1], in_strides[ndim - 1])), (CopyVec(out_ptr, in_ptr, shape[ndim - 1], in_strides[ndim - 1], item_size))); return; } const auto out_stride = out_strides[dim]; const auto in_stride = in_strides[dim]; const auto n = shape[dim]; for (Index i = 0; i < n; ++i) { CopyWithStrideHelper(out_ptr, in_ptr, in_strides, out_strides, shape, ndim, dim + 1, deepest_contiguous); out_ptr += out_stride; in_ptr += in_stride; } } inline Index DeepestContiguous(const Index *in_strides, const Index *shape, int ndim, size_t item_size) { ssize_t dim_prod = 1; for (int i = ndim-1; i >= 0; --i) { if (in_strides[i] != dim_prod*static_cast<Index>(item_size)) { return i+1; } dim_prod *= shape[i]; } return 0; } template <> void CopyWithStride<CPUBackend>(void *output, const void *input, const Index *in_strides, const Index *shape, int ndim, size_t item_size, cudaStream_t) { assert(ndim >= 0); if (!in_strides) { std::memcpy(output, input, item_size * volume(shape, shape + ndim)); return; } std::vector<Index> out_strides(ndim); out_strides.back() = item_size; for (int i = ndim - 2; i >= 0; --i) { out_strides[i] = out_strides[i + 1] * shape[i + 1]; } auto deepest_contiguous = DeepestContiguous(in_strides, shape, ndim, item_size); CopyWithStrideHelper(output, input, in_strides, out_strides.data(), shape, ndim, 0, deepest_contiguous); } } // namespace dali
#include <bits/stdc++.h> using namespace std; #define f(i, a, b) for (int i=a; i<b; i++) #define fp(i, a, b) for (long long int i=a; i>=b; i--) #define input(arr1,n1) f(i,0,n1) {cin>>arr1[i];} #define TC(t) while (t--) #define FASTIO ios_base::sync_with_stdio(false);cin.tie(NULL) void readFile() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } class node{ public: int data; node* next; //constructor node(int val){ data=val; next=NULL; } }; void insertAtTail(node* &head, int val){ node* temp=head; node* n=new node(val); if(head==NULL){ head=n; return; } while(temp->next){ temp=temp->next; } temp->next=n; } void display(node* head){ node* temp=head; while(temp){ cout<<temp->data<<"->"; temp=temp->next; } cout<<"NULL"<<endl; } node* mergeInBtw(node* &head1,int a,int b,node* &head2){ node* temp=head1,*start,*end; int count=0; while(temp){ if(count+1==a) start=temp; if(count==b) end=temp->next; temp=temp->next; count++; } start->next=head2; while(head2->next){ head2=head2->next; } head2->next=end; return head1; } int main() { readFile(); FASTIO; node* head1=NULL; node* head2=NULL; int n,m; cin>>n>>m; int a[n],b[m]; input(a,n); input(b,m); int x,y; cin>>x>>y; f(i,0,n){ insertAtTail(head1,a[i]); } display(head1); f(i,0,m){ insertAtTail(head2,b[i]); } display(head2); node* newHead=mergeInBtw(head1,x,y,head2); display(newHead); return 0; }
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/pinpoint/model/DeleteCampaignResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Pinpoint::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; DeleteCampaignResult::DeleteCampaignResult() { } DeleteCampaignResult::DeleteCampaignResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } DeleteCampaignResult& DeleteCampaignResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { const JsonValue& jsonValue = result.GetPayload(); if(jsonValue.ValueExists("CampaignResponse")) { m_campaignResponse = jsonValue.GetObject("CampaignResponse"); } return *this; }
// MineView.Draw.cpp: Mine rendering // #include "stdafx.h" #include "winuser.h" #include "dle-xp.h" #include "dlcDoc.h" #include "mineview.h" #include "PaletteManager.h" #include "TextureManager.h" #include "global.h" #include "FileManager.h" #include "ModelManager.h" #include <math.h> #include <time.h> extern short nDbgSeg, nDbgSide; extern int nDbgVertex; #define MODEL_DISPLAY_LIMIT 300.0 // max. distance from viewer at which 3D models and icons are rendered instead of angled arrows //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ void CMineView::CalcSegDist (void) { CHECKMINE; static short segRef [SEGMENT_LIMIT]; for (CSegmentIterator si; si; si++) si->Index () = -1; segRef [0] = current->SegmentId (); current->Segment ()->Index () = 0; int i = 1, h = 0, j = 0; int segCount = segmentManager.Count (); for (short nDist = 1; (j < segCount) && (h < i); nDist++) { for (h = i; j < h; j++) { CSegment* segI = segmentManager.Segment (segRef [j]); for (short nSide = 0; nSide < 6; nSide++) { short nChild = segI->ChildId (nSide); if (nChild < 0) continue; CSegment* segJ = segmentManager.Segment (nChild); if (segJ->Index () != -1) continue; segJ->Index () = nDist; segRef [i++] = nChild; } } } } //------------------------------------------------------------------------------ void CMineView::DrawMineCenter (void) { if (Renderer ().Perspective ()) return; CViewMatrix* viewMatrix = ViewMatrix (); if (m_nMineCenter == 1) { Renderer ().SelectPen (penWhite + 1); int nScale = int (20.0 * Scale ().v.y) + 1; CVertex v = viewMatrix->Origin (); viewMatrix->Transform (v.m_view, v); v.Project (viewMatrix); Renderer ().BeginRender (true); Renderer ().MoveTo (v.m_screen.x, v.m_screen.y - nScale); Renderer ().LineTo (v.m_screen.x, v.m_screen.y + nScale); Renderer ().MoveTo (v.m_screen.x - nScale, v.m_screen.y); Renderer ().LineTo (v.m_screen.x + nScale, v.m_screen.y); Renderer ().EndRender (); } else if (m_nMineCenter == 2) { // draw a globe // 5 circles around each axis at angles of 30, 60, 90, 120, and 150 // each circle has 18 points CVertex v, center, circles [3][120 / 30 + 1][360 / 15 + 1]; int h, i, j, m, n; Renderer ().BeginRender (); for (i = -60, m = 0; i <= 60; i += 30, m++) { for (j = 0, n = 0; j <= 360; j += 15, n++) { double sini = sin (Radians (i)); double cosi = cos (Radians (i)); double sinj = sin (Radians (j)); double cosj = cos (Radians (j)); double scale = 5 * cosi; v.Set (scale * cosj, scale * sinj, 5 * sini); v += viewMatrix->Origin (); if (!m_nRenderer) v -= viewMatrix->m_data [0].m_translate; viewMatrix->Transform (v.m_view, v); v.Project (viewMatrix); circles [0][m][n] = v; v.Set (scale * cosj, 5 * sini, scale * sinj); v += viewMatrix->Origin (); if (!m_nRenderer) v -= viewMatrix->m_data [0].m_translate; viewMatrix->Transform (v.m_view, v); v.Project (viewMatrix); circles [1][m][n] = v; v.Set (5 * sini, scale * cosj, scale * sinj); v += viewMatrix->Origin (); if (!m_nRenderer) v -= viewMatrix->m_data [0].m_translate; viewMatrix->Transform (v.m_view, v); v.Project (viewMatrix); circles [2][m][n] = v; } } center = ViewMatrix ()->Origin (); viewMatrix->Transform (center.m_view, center); Renderer ().EndRender (); ePenColor penColors [3] = {penGreen, penGray, penGold}; Renderer ().BeginRender (true); for (h = 0; h < 3; h++) { Renderer ().SelectPen (penColors [h] + 1, 2); for (i = -60, m = 0; i <= 60; i += 30, m++) { for (j = 0, n = 0; j <= 360; j += 15, n++) { CVertex v = circles [h][m][n]; if (j == 0) Renderer ().MoveTo (v.m_screen.x, v.m_screen.y); else if (m_nRenderer ? (v.m_view.v.z < center.m_view.v.z) : (v.m_screen.z <= 0)) Renderer ().LineTo (v.m_screen.x, v.m_screen.y); else Renderer ().MoveTo (v.m_screen.x, v.m_screen.y); } } } Renderer ().EndRender (); } } //---------------------------------------------------------------------------- // DrawWireFrame //---------------------------------------------------------------------------- void CMineView::DrawWireFrame (bool bSparse) { CHECKMINE; CalcSegDist (); Renderer ().BeginRender (Renderer ().Type () == 0); Renderer ().SelectPen (penGray + 1); CSegment* pSegment = segmentManager.Segment (0); short segCount = segmentManager.Count (); if (m_nRenderer) glDepthFunc (GL_LEQUAL); for (short nSegment = 0; nSegment < segCount; nSegment++, pSegment++) DrawSegmentWireFrame (pSegment, bSparse); Renderer ().EndRender (); if (Visible (current->Segment ())) { DrawCurrentSegment (current->Segment (), bSparse); } } //---------------------------------------------------------------------------- static CFaceListEntry faceRenderList [SEGMENT_LIMIT * 6]; void SortFaces (int left, int right) { CFaceListEntry m = faceRenderList [(left + right) / 2]; int l = left, r = right; do { while ((faceRenderList [l].m_zMax > m.m_zMax) || ((faceRenderList [l].m_zMax == m.m_zMax) && (faceRenderList [l].m_zMin > m.m_zMin))) l++; while ((faceRenderList [r].m_zMax < m.m_zMax) || ((faceRenderList [l].m_zMax == m.m_zMax) && (faceRenderList [l].m_zMin < m.m_zMin))) r--; if (l <= r) { if (l < r) Swap (faceRenderList [l], faceRenderList [r]); l++; r--; } } while (l < r); if (l < right) SortFaces (l, right); if (left < r) SortFaces (left, r); } //---------------------------------------------------------------------------- void CMineView::DrawTexturedSegments (void) { CHECKMINE; if (!textureManager.Available ()) return; // Draw Segments () short segCount = segmentManager.Count (); int faceCount = 0; CSegment* pSegment = segmentManager.Segment (0); for (short nSegment = 0; nSegment < segCount; nSegment++, pSegment++) { if (!Visible (pSegment)) continue; CSide* pSide = pSegment->Side (0); for (short nSide = 0; nSide < 6; nSide++, pSide++) { #ifdef _DEBUG if ((nSegment == nDbgSeg) && ((nDbgSide < 0) || (nSide == nDbgSide))) nDbgSeg = nDbgSeg; #endif #ifdef _DEBUG if (pSegment->m_info.bTunnel) continue; #endif if (pSegment->ChildId (nSide) != -1) { // not a solid side CWall* pWall = pSide->Wall (); if (pWall == null) // no wall either continue; if (pWall->Type () == WALL_OPEN) // invisible wall continue; if ((pWall->Type () == WALL_CLOAKED) && (pWall->Info ().cloakValue == 0)) // invisible cloaked wall continue; } if (!FaceIsVisible (pSegment, pSide)) continue; if (pSide->Shape () > SIDE_SHAPE_TRIANGLE) continue; long zMin = -LONG_MIN, zMax = LONG_MIN; for (ushort nVertex = 0; nVertex < 4; nVertex++) { long z = vertexManager [pSegment->m_info.vertexIds [pSide->VertexIdIndex (nVertex)]].m_screen.z; if (zMin > z) zMin = z; if (zMax < z) zMax = z; } faceRenderList [faceCount].m_nSegment = nSegment; faceRenderList [faceCount].m_nSide = nSide; faceRenderList [faceCount].m_zMin = zMin; faceRenderList [faceCount].m_zMax = zMax; CWall* pWall = pSide->Wall (); faceRenderList [faceCount].m_bTransparent = pSegment->m_info.bTunnel || textureManager.Textures (pSide->BaseTex ())->Transparent () || ((pWall != null) && (pWall->Alpha () < 255)); ++faceCount; } } if (!faceCount) return; if (faceCount > 1) SortFaces (0, faceCount - 1); CalcSegDist (); Renderer ().RenderFaces (faceRenderList, faceCount, Renderer ().IsRTTSupported ()); } //-------------------------------------------------------------------------- // DrawSegment () //-------------------------------------------------------------------------- bool CMineView::InRange (short *pv, short i) { for (; i; i--, pv++) { if ((*pv <= MAX_VERTEX) && !vertexManager [*pv].InRange (m_viewMax.x, m_viewMax.y, Renderer ().Type ())) return false; } return true; } //-------------------------------------------------------------------------- void CMineView::DrawSegmentHighlighted (short nSegment, short nSide, short nLine, short nPoint) { CHECKMINE; CSegment *pSegment = segmentManager.Segment (nSegment); CSide* pSide = pSegment->Side (nSide); short xMax = ViewWidth () * 2; short yMax = ViewHeight () * 2; if (!Visible (pSegment)) return; // draw the segment's wire frame if (pSegment->IsTagged ()) Renderer ().SelectPen (penGold + 1, 2.0f); else Renderer ().SelectPen (((nSegment == current->SegmentId ()) || (nSegment == nearest->m_nSegment)) ? SelectMode (eSelectSegment) ? penRed + 1 : penWhite + 1 : penGray + 1, 2); DrawSegmentWireFrame (pSegment); // draw the current side's outline int i; if (!Renderer ().Ortho ()) i = 4; else { for (i = 0; i < 4; i++) if (!vertexManager [pSegment->m_info.vertexIds [pSide->VertexIdIndex (i)]].InRange (xMax, yMax, Renderer ().Type ())) break; } if (i == 4) { Renderer ().SelectPen (((nSegment == current->SegmentId ()) || (nSegment == nearest->m_nSegment)) ? SelectMode (eSelectSide) ? penRed + 1 : penGreen + 1 : penDkGreen + 1, 2); short nVertices = pSide->VertexCount (); for (i = 0; i < nVertices; i++) DrawLine (pSegment, pSide->VertexIdIndex (i), pSide->VertexIdIndex (i + 1)); } // draw the current line short i1 = pSide->VertexIdIndex (nLine); short i2 = pSide->VertexIdIndex (nLine + 1); if (!Renderer ().Ortho () || (vertexManager [pSegment->m_info.vertexIds [i1]].InRange (xMax, yMax, Renderer ().Type ()) && vertexManager [pSegment->m_info.vertexIds [i2]].InRange (xMax, yMax, Renderer ().Type ()))) { Renderer ().SelectPen (((nSegment == current->SegmentId ()) || (nSegment == nearest->m_nSegment)) ? SelectMode (eSelectLine) ? penRed + 1 : penGold + 1 : penMedCyan + 1, 2); DrawLine (pSegment, i1, i2); } // draw a circle around the current vertex Renderer ().SelectObject ((HBRUSH) GetStockObject (NULL_BRUSH)); Renderer ().SelectPen (((nSegment == current->SegmentId ()) || (nSegment == nearest->m_nSegment)) ? SelectMode (eSelectPoint) ? penRed + 1 : penGold + 1 : penMedCyan + 1, 2); i = pSegment->m_info.vertexIds [pSide->VertexIdIndex (nPoint)]; if (vertexManager [i].InRange (xMax, yMax, Renderer ().Type ())) Renderer ().Ellipse (vertexManager [i], 4, 4); } //-------------------------------------------------------------------------- void CMineView::DrawSegmentPartial (CSegment *pSegment) { RenderSegmentWireFrame (pSegment, true); } //-------------------------------------------------------------------------- void QSortLineRef (POINT *lineRef, short left, short right) { int m = lineRef [(left + right) / 2].y; short l = left, r = right; do { while (lineRef [l].y < m) l++; while (lineRef [r].y > m) r--; if (l <= r) { if (l < r) { POINT h = lineRef [l]; lineRef [l] = lineRef [r]; lineRef [r] = h; } l++; r--; } } while (l < r); if (l < right) QSortLineRef (lineRef, l, right); if (left < r) QSortLineRef (lineRef, left, r); } //-------------------------------------------------------------------------- void CMineView::DrawSparseSegmentWireFrame (CSegment *pSegment) { bool bOrtho = Renderer ().Ortho (); CEdgeList edgeList; int nEdges = pSegment->BuildEdgeList (edgeList, true); for (short nSide = 0; nSide < 6; nSide++) { if (pSegment->ChildId (nSide) >= 0) continue; CSide* pSide = pSegment->Side (nSide); CPoint side [4], line [2]; ubyte v [2]; int i, j; for (i = 0; i < 4; i++) { side [i].x = vertexManager [pSegment->m_info.vertexIds [pSide->VertexIdIndex (i)]].m_screen.x; side [i].y = vertexManager [pSegment->m_info.vertexIds [pSide->VertexIdIndex (i)]].m_screen.y; } CDoubleVector a,b; a.v.x = (double) (side [1].x - side [0].x); a.v.y = (double) (side [1].y - side [0].y); b.v.x = (double) (side [3].x - side [0].x); b.v.y = (double) (side [3].y - side [0].y); if (a.v.x * b.v.y < a.v.y * b.v.x) Renderer ().SelectPen (penWhite + 1); else Renderer ().SelectPen (penGray + 1); // draw each line of the current side separately // only draw if there is no childP segment of the current segment with a common side for (i = 0; i < 4; i++) { for (j = 0; j < 2; j++) { line [j] = side [(i+j)%4]; v [j] = pSide->VertexIdIndex ((i+j)%4); } // Using the sparse edge list: if a neighboring side is 0xff, it's joined to another cube, // so don't render this line ubyte side1, side2; edgeList.Find (0, side1, side2, v [0], v [1]); if (side1 == 0xff || side2 == 0xff) continue; CVertex& v1 = vertexManager [pSegment->m_info.vertexIds [v [0]]]; CVertex& v2 = vertexManager [pSegment->m_info.vertexIds [v [1]]]; if (!bOrtho) { Renderer ().MoveTo (v1); Renderer ().LineTo (v2); } else { Renderer ().MoveTo (v1.m_screen.x, v1.m_screen.y); Renderer ().LineTo (v2.m_screen.x, v2.m_screen.y); } } } } //-------------------------------------------------------------------------- void CMineView::RenderSegmentWireFrame (CSegment *pSegment, bool bSparse, bool bTagged) { int bOrtho = Renderer ().Ortho (); if (bOrtho) { if (!Visible (pSegment)) return; } else if (!bSparse) { if ((pSegment == current->Segment ()) || (pSegment == other->Segment ())) glDisable (GL_DEPTH_TEST); else glEnable (GL_DEPTH_TEST); glLineWidth (ViewOption (eViewTexturedWireFrame) ? 3.0f : 2.0f); } CEdgeList edgeList; ushort* vertexIds = pSegment->m_info.vertexIds; short xMax = ViewWidth (), yMax = ViewHeight (); int nType = Renderer ().Type (); ePenColor pen; float penWeight; bool bSegmentIsTagged = pSegment->IsTagged (); bool bSideTagged [2] = {false, false}; bool bFullWireFrame = !bTagged || bSegmentIsTagged || (m_viewOption != eViewTextured); #ifdef _DEBUG if (segmentManager.Index (pSegment) == nDbgSeg) nDbgSeg = nDbgSeg; #endif Renderer ().GetPen (pen, penWeight); for (int i = 0, j = pSegment->BuildEdgeList (edgeList); i < j; i++) { ubyte i1, i2, side1, side2; edgeList.Get (i, side1, side2, i1, i2); if (!bSegmentIsTagged) { bSideTagged [0] = bSideTagged [1]; bSideTagged [1] = pSegment->IsTagged (short (side1)) || pSegment->IsTagged (short (side2)); if (bSideTagged [0] != bSideTagged [1]) { if (bSideTagged [1]) Renderer ().SelectPen (penOrange + 1, ViewOption (eViewTexturedWireFrame) ? 3.0f : 2.0f); else Renderer ().SelectPen (pen + 1, penWeight); } } if (!(bFullWireFrame || bSideTagged [1])) continue; CVertex& v1 = vertexManager [vertexIds [i1]]; CVertex& v2 = vertexManager [vertexIds [i2]]; if (!bOrtho) { Renderer ().MoveTo (v1); Renderer ().LineTo (v2); } else { //if (v1.InRange (xMax, yMax, nType) && v2.InRange (xMax, yMax, nType)) { Renderer ().MoveTo (v1.m_screen.x, v1.m_screen.y); Renderer ().LineTo (v2.m_screen.x, v2.m_screen.y); } } if (bSideTagged [1]) Renderer ().SelectPen (pen + 1, penWeight); } //-------------------------------------------------------------------------- void CMineView::DrawSegmentWireFrame (CSegment *pSegment, bool bSparse, bool bTagged, char bTunnel) { CHECKMINE; if (!Visible (pSegment)) return; if (pSegment->m_info.bTunnel != bTunnel) return; if (!m_nRenderer && (bSparse || Renderer ().Ortho ())) { short xMax = ViewWidth (); short yMax = ViewHeight (); ushort* vertexIds = pSegment->m_info.vertexIds; for (int i = 0; i < 8; i++, vertexIds++) { int v = *vertexIds; if ((v <= MAX_VERTEX) && !vertexManager [v].InRange (xMax, yMax, Renderer ().Type ())) return; } } if (bSparse) DrawSparseSegmentWireFrame (pSegment); else RenderSegmentWireFrame (pSegment, false, bTagged); } //-------------------------------------------------------------------------- // draw_segmentPoints() //-------------------------------------------------------------------------- void CMineView::DrawSegmentPoints (CSegment *pSegment) { CHECKMINE; ushort* vertexIds = pSegment->m_info.vertexIds; int h; Renderer ().SelectPen (penGray + 1); for (int i = 0; i < 8; i++, vertexIds++) if (MAX_VERTEX >= (h = *vertexIds)) Renderer ().Ellipse (vertexManager [h].m_screen.x, vertexManager [h].m_screen.y, 2, 2); } //-------------------------------------------------------------------------- bool CMineView::SelectWireFramePen (CSegment* pSegment) { if (pSegment->IsTagged ()) { Renderer ().SelectPen (penOrange + 1); return true; } if (ViewFlag (eViewMineSpecial) && (m_viewOption != eViewTextured)) { switch (pSegment->m_info.function) { case SEGMENT_FUNC_PRODUCER: case SEGMENT_FUNC_SPEEDBOOST: Renderer ().SelectPen (penYellow + 1); return true; case SEGMENT_FUNC_REACTOR: Renderer ().SelectPen (penOrange + 1); return true; case SEGMENT_FUNC_REPAIRCEN: Renderer ().SelectPen (penLtBlue + 1); return true; case SEGMENT_FUNC_ROBOTMAKER: case SEGMENT_FUNC_EQUIPMAKER: Renderer ().SelectPen (penMagenta + 1); return true; case SEGMENT_FUNC_GOAL_BLUE: case SEGMENT_FUNC_TEAM_BLUE: Renderer ().SelectPen (penBlue + 1); return true; case SEGMENT_FUNC_GOAL_RED: case SEGMENT_FUNC_TEAM_RED: Renderer ().SelectPen (penRed + 1); return true; default: if (pSegment->m_info.props & SEGMENT_PROP_WATER) Renderer ().SelectPen (penMedBlue + 1); else if (pSegment->m_info.props & SEGMENT_PROP_LAVA) Renderer ().SelectPen (penMedRed + 1); else if (pSegment->m_info.props & SEGMENT_PROP_FOG) Renderer ().SelectPen (penDkGray + 1); else if (pSegment->IsTagged (short (-1))) Renderer ().SelectPen (penGray + 1); else return false; return true; } } if (pSegment->IsTagged (short (-1))) { Renderer ().SelectPen (penGray + 1); return true; } return false; } //-------------------------------------------------------------------------- void CMineView::DrawTaggedSegments (void) { CHECKMINE; CSegment* pSegment; short xMax = ViewWidth (); short yMax = ViewHeight (); short i; Renderer ().BeginRender (Renderer ().Type () == 0); if (!Renderer ().Ortho ()) glDepthFunc (GL_LEQUAL); for (i = 0; i < segmentManager.Count (); i++) if (SelectWireFramePen (pSegment = segmentManager.Segment (i))) DrawSegmentWireFrame (pSegment, false, true); Renderer ().EndRender (); Renderer ().BeginRender (true); // draw a square around all marked points Renderer ().SelectObject ((HBRUSH) GetStockObject (NULL_BRUSH)); #if 1 Renderer ().SelectPen (penOrange + 1); #else if (SelectMode (eSelectBlock)) Renderer ().SelectPen (penRed + 1); else Renderer ().SelectPen (penGold + 1); #endif for (i = 0; i < vertexManager.Count (); i++) if ((vertexManager.Status (i) & TAGGED_MASK) && vertexManager [i].InRange (xMax, yMax, Renderer ().Type ())) Renderer ().Rectangle (vertexManager [i], 5, 5); Renderer ().EndRender (); } //-------------------------------------------------------------------------- void CMineView::DrawCurrentSegment (CSegment *pSegment, bool bSparse) { CHECKMINE; short xMax = ViewWidth (); short yMax = ViewHeight (); short nSide = current->SideId (); short nLine = current->Point (); short nPoint = current->Point (); CSide* pSide = pSegment->Side (nSide); short nVertices = pSide->VertexCount (); if (Renderer ().Type ()) { BeginRender (); glDisable (GL_DEPTH_TEST); } else { for (int i = 0; i < nVertices; i++) if (!vertexManager [pSegment->m_info.vertexIds [pSide->VertexIdIndex (i)]].InRange (xMax, yMax, Renderer ().Type ())) return; BeginRender (true); } Renderer ().SelectPen ((m_selectMode == SIDE_MODE) ? penRed + 1 : penGreen + 1); for (int i = 0; i < nVertices; i++) DrawLine (pSegment, pSide->VertexIdIndex (i), pSide->VertexIdIndex (i + 1)); // draw current line Renderer ().SelectPen ((m_selectMode == SIDE_MODE) ? penRed + 1 : penGold + 1); DrawLine (pSegment, pSide->VertexIdIndex (nLine), pSide->VertexIdIndex (nLine + 1)); // draw a circle around the current point Renderer ().SelectObject ((HBRUSH) GetStockObject (NULL_BRUSH)); Renderer ().SelectPen ((m_selectMode == SIDE_MODE) ? penRed + 1 : penGold + 1); Renderer ().Ellipse (vertexManager [pSegment->m_info.vertexIds [pSide->VertexIdIndex (nPoint)]], 4, 4); EndRender (); } //-------------------------------------------------------------------------- void CMineView::DrawLine (CSegment* pSegment, short i1, short i2) { CHECKMINE; if (Renderer ().Ortho ()) { Renderer ().MoveTo (vertexManager [pSegment->m_info.vertexIds [i1]].m_screen.x, vertexManager [pSegment->m_info.vertexIds [i1]].m_screen.y); Renderer ().LineTo (vertexManager [pSegment->m_info.vertexIds [i2]].m_screen.x, vertexManager [pSegment->m_info.vertexIds [i2]].m_screen.y); } else { Renderer ().MoveTo (vertexManager [pSegment->m_info.vertexIds [i1]]); Renderer ().LineTo (vertexManager [pSegment->m_info.vertexIds [i2]]); } } //-------------------------------------------------------------------------- void CMineView::SelectWallPen (CWall* pWall) { switch (pWall->Type ()) { case WALL_NORMAL: Renderer ().SelectPen (penLtGray + 1); break; case WALL_BLASTABLE: Renderer ().SelectPen (penLtGray + 1); break; case WALL_DOOR: switch(pWall->Info ().keys) { case KEY_NONE: Renderer ().SelectPen (penLtGray + 1); break; case KEY_BLUE: Renderer ().SelectPen (penBlue + 1); break; case KEY_RED: Renderer ().SelectPen (penRed + 1); break; case KEY_GOLD: Renderer ().SelectPen (penYellow + 1); break; default: Renderer ().SelectPen (penGray + 1); } break; case WALL_ILLUSION: Renderer ().SelectPen (penLtGray + 1); break; case WALL_OPEN: Renderer ().SelectPen (penLtGray + 1); break; case WALL_CLOSED: Renderer ().SelectPen (penLtGray + 1); break; default: Renderer ().SelectPen (penLtGray + 1); } } //-------------------------------------------------------------------------- void CMineView::DrawWalls (void) { CHECKMINE; CWall* walls = wallManager.Wall (0); CSegment* segments = segmentManager.Segment (0); CSegment* pSegment; CSide* pSide; short i,j; short xMax = ViewWidth () * 2; short yMax = ViewHeight () * 2; for (i = 0; i < wallManager.WallCount (); i++) { if (walls [i].m_nSegment > segmentManager.Count ()) continue; pSegment = segments + (int) walls [i].m_nSegment; if (!Visible (pSegment)) continue; short nSide = walls [i].m_nSide; pSide = pSegment->Side (nSide); for (j = 0; j < 4; j++) { CVertex& v = vertexManager [pSegment->m_info.vertexIds [pSide->VertexIdIndex (j)]]; if (IN_RANGE (v.m_screen.x, xMax) && IN_RANGE (v.m_screen.y, yMax)) break; } if (j < 4) { CVertex center, normal, vector; CVertex arrowStartPoint, arrowEndPoint, arrow1Point, arrow2Point; center = segmentManager.CalcSideCenter (walls [i]); normal = segmentManager.CalcSideNormal (walls [i]); vector = center - normal; Renderer ().BeginRender (); vector.Transform (ViewMatrix ()); vector.Project (ViewMatrix ()); if (walls [i].Info ().nTrigger != NO_TRIGGER) { // calculate arrow points arrowStartPoint = center - (normal * 3); arrowStartPoint.Transform (ViewMatrix ()); arrowStartPoint.Project (ViewMatrix ()); arrowEndPoint = center + (normal * 3); arrowEndPoint.Transform (ViewMatrix ()); arrowEndPoint.Project (ViewMatrix ()); // direction toward center of line 0 from center CVertex vector = Average (*pSegment->Vertex (nSide, 0), *pSegment->Vertex (nSide, 1)); vector -= center; vector.Normalize (); arrow1Point = (normal * 2); arrow1Point += center; arrow1Point += vector; arrow1Point.Transform (ViewMatrix ()); arrow1Point.Project (ViewMatrix ()); vector *= 2; arrow2Point = arrow1Point - vector; arrow2Point.Transform (ViewMatrix ()); arrow2Point.Project (ViewMatrix ()); } Renderer ().EndRender (); if (Renderer ().Type ()) { Renderer ().BeginRender (false); glEnable (GL_DEPTH_TEST); SelectWallPen (&walls [i]); glLineWidth (ViewOption (eViewTexturedWireFrame) ? 4.0f : 3.0f); for (j = 0; j < pSide->VertexCount (); j++) { Renderer ().MoveTo (vector); Renderer ().LineTo (*pSegment->Vertex (nSide, j)); } if (walls [i].Info ().nTrigger != NO_TRIGGER) { // draw arrow Renderer ().MoveTo (arrowStartPoint); Renderer ().LineTo (arrowEndPoint); Renderer ().LineTo (arrow1Point); Renderer ().MoveTo (arrowEndPoint); Renderer ().LineTo (arrow2Point); } } else { Renderer ().BeginRender (true); SelectWallPen (&walls [i]); for (j = 0; j < pSide->VertexCount (); j++) { Renderer ().MoveTo (vector.m_screen.x, vector.m_screen.y); CVertex& v = *pSegment->Vertex (nSide, j); Renderer ().LineTo (v.m_screen.x, v.m_screen.y); } if (walls [i].Info ().nTrigger != NO_TRIGGER) { // draw arrow Renderer ().MoveTo (arrowStartPoint.m_screen.x, arrowStartPoint.m_screen.y); Renderer ().LineTo (arrowEndPoint.m_screen.x, arrowEndPoint.m_screen.y); Renderer ().LineTo (arrow1Point.m_screen.x, arrow1Point.m_screen.y); Renderer ().MoveTo (arrowEndPoint.m_screen.x, arrowEndPoint.m_screen.y); Renderer ().LineTo (arrow2Point.m_screen.x, arrow2Point.m_screen.y); } } Renderer ().EndRender (); } } } //-------------------------------------------------------------------------- void CMineView::DrawLights (void) { CHECKMINE; // now show variable lights CViewMatrix* viewMatrix = Renderer ().ViewMatrix (); CVariableLight* pLight = lightManager.VariableLight (0); // find variable light from Renderer ().BeginRender (); pLight = lightManager.VariableLight (0); for (INT i = 0; i < lightManager.Count (); i++, pLight++) if (Visible (segmentManager.Segment (pLight->m_nSegment))) DrawOctagon (pLight->m_nSide, pLight->m_nSegment); Renderer ().EndRender (); } //-------------------------------------------------------------------------- void CMineView::DrawOctagon (short nSide, short nSegment) { CHECKMINE; short xMax = ViewWidth (); short yMax = ViewHeight (); if (nSegment >= 0 && nSegment <= segmentManager.Count () && nSide >= 0 && nSide <= 5) { CSegment* pSegment = segmentManager.Segment (nSegment); CSide* pSide = pSegment->Side (nSide); short nVertices = pSide->VertexCount (); if (nVertices < 3) return; CVertex vCenter = pSegment->ComputeCenter (nSide); if (!vCenter.InRange (xMax, yMax, m_nRenderer)) return; if (ViewMatrix ()->Distance (vCenter) <= MODEL_DISPLAY_LIMIT) { pSide->ComputeNormals (pSegment->m_info.vertexIds, pSegment->ComputeCenter ()); vCenter += pSide->Normal (); Renderer ().Sprite (&textureManager.Icon (LIGHT_ICON), vCenter, 5.0, 5.0, false); } else { pSide->ComputeNormals (pSegment->m_info.vertexIds, pSegment->ComputeCenter (true), true); CVertex vertices [4]; short nVertices = pSide->VertexCount (); #if 1 CDoubleVector vOffset = pSide->Normal (); for (short i = 0; i < nVertices; i++) vertices [i].m_view = pSegment->Vertex (nSide, i)->m_view + vOffset; #else for (short i = 0; i < nVertices; i++) vertices [i] = *pSegment->Vertex (nSide, i); CDoubleVector vNormal = Normal (vertices [0], vertices [1], vertices [2]); // = pSide->Normal (); vertices [0] -= vCenter; vertices [0].Normalize (); vertices [3] = vCenter + vNormal; vertices [1] = Normal (vCenter, vertices [0], vertices [3]); vertices [0] *= 50.0; vertices [1] *= 50.0; vertices [2] = vCenter - vertices [0]; vertices [3] = vCenter - vertices [1]; vertices [0] += vCenter; vertices [1] += vCenter; CDoubleVector vOffset = vNormal * 10.0; for (short i = 0; i < nVertices; i++) { vertices [i].Transform (Renderer ().ViewMatrix ()); vertices [i].m_view += vOffset; } #endif glDisable (GL_CULL_FACE); Renderer ().TexturedPolygon (&textureManager.Icon (CIRCLE_ICON), null, null, vertices, nVertices, null); glEnable (GL_CULL_FACE); } } } //---------------------------------------------------------------------------- void CMineView::DrawTunnel (void) { CVertex points [4]; CRenderer& renderer = DLE.MineView ()->Renderer (); renderer.SelectPen (penRed + 1); Renderer ().SelectObject ((HBRUSH)GetStockObject (NULL_BRUSH)); tunnelMaker.Create (); renderer.BeginRender (); points [1].Transform (ViewMatrix ()); points [1].Project (ViewMatrix ()); if (IN_RANGE (points [1].m_screen.x, m_viewMax.x) && IN_RANGE (points [1].m_screen.y, m_viewMax.y)) { points [0].Transform (ViewMatrix ()); points [0].Project (ViewMatrix ()); if (IN_RANGE (points [0].m_screen.x, m_viewMax.x) && IN_RANGE (points [0].m_screen.y, m_viewMax.y)){ renderer.BeginRender (true); renderer.MoveTo (points [0].m_screen.x, points [0].m_screen.y); renderer.LineTo (points [1].m_screen.x, points [1].m_screen.y); renderer.Ellipse (points [1], 4, 4); renderer.EndRender (); renderer.BeginRender (); } } points [2].Transform (ViewMatrix ()); points [2].Project (ViewMatrix ()); if (IN_RANGE (points [2].m_screen.x, m_viewMax.x) && IN_RANGE (points [2].m_screen.y, m_viewMax.y)){ points [2].Transform (ViewMatrix ()); points [2].Project (ViewMatrix ()); if (IN_RANGE (points [3].m_screen.x, m_viewMax.x) && IN_RANGE (points [3].m_screen.y, m_viewMax.y)){ renderer.BeginRender (true); renderer.MoveTo (points [3].m_screen.x, points [3].m_screen.y); renderer.LineTo (points [2].m_screen.x, points [2].m_screen.y); renderer.Ellipse (points [2].m_screen.x - 4, points [2].m_screen.y - 4, points [2].m_screen.x+4, points [2].m_screen.y+4); renderer.EndRender (); renderer.BeginRender (); } } #if 1 tunnelMaker.Draw (Renderer (), Pen (penRed), Pen (penBlue), ViewMatrix ()); #else j = MAX_VERTICES; for (h = tunnelMaker.Length () * 4, i = 0; i < h; i++) { vertexManager [--j].Transform (ViewMatrix ()); vertexManager [--j].Project (ViewMatrix ()); } CSegment *pSegment = segmentManager.Segment (SEGMENT_LIMIT - 1); renderer.BeginRender (renderer.Type () == 0); renderer.SelectPen (penBlue + 1); for (i = 0; i < tunnelMaker.Length (); i++, pSegment--) DrawSegmentWireFrame (pSegment, false, false, 1); renderer.EndRender (); #endif } //-------------------------------------------------------------------------- // DrawObject () // // Changed: 0=normal,1=gray,2=black // if (nObject == (objectManager.Count () // then its a secret return point) //-------------------------------------------------------------------------- void CMineView::SelectObjectPen (CGameObject* pObject) { if ((m_selectMode == OBJECT_MODE) && (pObject == current->Object ())) Renderer ().SelectPen (penRed + 1); // RED else { switch(pObject->Type ()) { case OBJ_ROBOT: case OBJ_CAMBOT: case OBJ_EXPLOSION: case OBJ_MONSTERBALL: Renderer ().SelectPen (penMagenta + 1); break; case OBJ_SMOKE: case OBJ_EFFECT: Renderer ().SelectPen (penGreen + 1, 2); break; case OBJ_HOSTAGE: Renderer ().SelectPen (penBlue + 1); break; case OBJ_PLAYER: Renderer ().SelectPen (penGold + 1); break; case OBJ_WEAPON: Renderer ().SelectPen (penDkGreen + 1); break; case OBJ_POWERUP: Renderer ().SelectPen (penOrange + 1); break; case OBJ_REACTOR: Renderer ().SelectPen (penLtGray + 1); break; case OBJ_COOP: Renderer ().SelectPen (penGold + 1); break; default: Renderer ().SelectPen (penGreen + 1); } } } //-------------------------------------------------------------------------- void CMineView::DrawObject (short nObject) { CHECKMINE; CGameObject* pObject; CGameObject tempObj; if (nObject >= 0 && nObject < objectManager.Count ()) { pObject = objectManager.Object (nObject); if (!Visible (segmentManager.Segment (pObject->m_info.nSegment))) return; } else { // secret return pObject = &tempObj; pObject->Type () = -1; pObject->m_info.renderType = RT_NONE; // theMine->secret_orient = Objects () [0]->orient; pObject->m_location.orient.m.rVec = -objectManager.SecretOrient ().m.rVec; pObject->m_location.orient.m.uVec = objectManager.SecretOrient ().m.fVec; pObject->m_location.orient.m.fVec = objectManager.SecretOrient ().m.uVec; // pObject->m_location.orient = theMine->secret_orient; ushort nSegment = (ushort)objectManager.SecretSegment (); if (nSegment >= segmentManager.Count ()) nSegment = 0; if (!Visible (segmentManager.Segment (nSegment))) return; CVertex center; pObject->Position () = segmentManager.CalcCenter (center, nSegment); // define pObject->position } double d = (ViewOption (eViewTexturedWireFrame) || ViewOption (eViewTextured)) ? ViewMatrix ()->Distance (pObject->Position ()) : 1e30; if (textureManager.Available (1) && pObject->HasPolyModel () && modelManager.Setup (pObject, m_renderer, DC ()) && ((nObject == current->ObjectId ()) || (d <= MODEL_DISPLAY_LIMIT))) { SelectObjectPen (pObject); if (pObject->IsInView (Renderer (), true)) { // only render if fully visible Renderer ().SelectObject ((HBRUSH) GetStockObject (BLACK_BRUSH)); modelManager.Draw (); } } else { if ((d > MODEL_DISPLAY_LIMIT) || !pObject->DrawSprite (Renderer ()) || (nObject == current->ObjectId ())) { SelectObjectPen (pObject); pObject->DrawArrow (Renderer (), (nObject == current->ObjectId ())); } } if (((nObject == current->ObjectId ()) || (nObject == other->ObjectId ())) && pObject->IsInView (Renderer (), false)) pObject->DrawHighlight (Renderer (), (nObject == current->ObjectId ())); } //-------------------------------------------------------------------------- void CMineView::DrawObjects (void) { CHECKMINE; if (!ViewObject ()) return; int i, j; Renderer ().BeginRender (); if (DLE.IsD2File ()) { // see if there is a secret exit trigger for(i = 0; i < triggerManager.WallTriggerCount (); i++) if (triggerManager.Trigger (i)->Type () == TT_SECRET_EXIT) { DrawObject ((short)objectManager.Count ()); break; // only draw one secret exit } } HiliteTarget (); CGameObject *pObject = objectManager.Object (0); for (i = objectManager.Count (), j = 0; i; i--, j++, pObject++) if (ViewObject (pObject)) DrawObject (j); Renderer ().EndRender (); } //-------------------------------------------------------------------------- // Determine the side edge the projection of which to the mine view is closest // to the current mouse position. bool CMineView::DrawSelectablePoint (void) { if (!SelectMode (eSelectPoint)) return false; CRect viewport; GetClientRect (viewport); double minDist = 1e30; short nNearestVertex = -1; CDoubleVector mousePos (double (LastMousePos ().x), double (LastMousePos ().y), 0.0); short nVertices = vertexManager.Count (); for (short nVertex = 0; nVertex < nVertices; nVertex++) { CVertex& v = vertexManager [nVertex]; if (!v.InRange (viewport.right, viewport.bottom, m_nRenderer)) continue; double dist = Distance (mousePos, v.m_proj); if (minDist > dist) { minDist = dist; nNearestVertex = nVertex; } } if (nNearestVertex < 0) return false; Renderer ().BeginRender (true); Renderer ().SelectPen (penMedBlue + 1, 1); Renderer ().Ellipse (vertexManager [nNearestVertex], 8.0, 8.0); Renderer ().EndRender (); return true; } //-------------------------------------------------------------------------- // Determine the side edge the projection of which to the mine view is closest // to the current mouse position. bool CMineView::DrawSelectableEdge (void) { if (!SelectMode (eSelectLine)) return false; CSegment* nearestSegment = null; CSide* nearestSide = null; short nNearestEdge = FindNearestLine (&nearestSegment, &nearestSide, false); if (nNearestEdge < 0) return false; nearest->Setup (segmentManager.Index (nearestSegment), nearestSegment->SideIndex (nearestSide), nNearestEdge, nNearestEdge); Renderer ().BeginRender (true); if (m_nRenderer) { glLineStipple (1, 0x00ff); glEnable (GL_LINE_STIPPLE); } Renderer ().SelectPen (penMedBlue + 1, 2); CVertex* v1 = nearest->Segment ()->Vertex (nearest->m_nSide, nNearestEdge); CVertex* v2 = nearest->Segment ()->Vertex (nearest->m_nSide, nNearestEdge + 1); Renderer ().MoveTo (v1->m_screen.x, v1->m_screen.y); Renderer ().LineTo (v2->m_screen.x, v2->m_screen.y); if (m_nRenderer) glDisable (GL_LINE_STIPPLE); Renderer ().SelectPen (penMedBlue + 1); Renderer ().Ellipse (*v1, 8.0, 8.0); Renderer ().Ellipse (*v2, 8.0, 8.0); Renderer ().EndRender (); return true; } //-------------------------------------------------------------------------- // Determine all sides in the projection of which to the mine viewthe current // mouse position lies. Draw a circle in each side's center and a line from // each side vertex to the circle to mark it. Open sides have the circle // moved in by their normal * 2.0. static inline double sqr (long v) { return double (v) * double (v); } bool CMineView::DrawSelectableSides (void) { if (!SelectMode (eSelectSide)) return false; CRect viewport; GetClientRect (viewport); if (!segmentManager.GatherSelectableSides (viewport, LastMousePos ().x, LastMousePos ().y, ViewFlag (eViewMineSkyBox), false)) return false; double minDist = 1e30; CSegment* nearestSegment = null; CSide* nearestSide = null; for (CSide* pSide = segmentManager.SelectedSides (); pSide; pSide = pSide->GetLink ()) { CSegment* pSegment = segmentManager.Segment (pSide->GetParent ()); CVertex& center = pSide->Center (); double dist = sqrt (sqr (LastMousePos ().x - center.m_screen.x) + sqr (LastMousePos ().y - center.m_screen.y)); #if 0 if (dist > 64.0) continue; #endif if (minDist > dist) { minDist = dist; nearestSegment = segmentManager.Segment (pSide->GetParent ()); nearestSide = pSide; } } nearest->Setup (segmentManager.Index (nearestSegment), nearestSegment->SideIndex (nearestSide)); if (nearest->m_nSegment < 0) return false; if (m_nShowSelectionCandidates > 1) { Renderer ().BeginRender (); if (m_nRenderer) { glLineStipple (1, 0x00ff); glEnable (GL_LINE_STIPPLE); glDepthFunc (GL_ALWAYS); } for (CSide* pSide = segmentManager.SelectedSides (); pSide; pSide = pSide->GetLink ()) { CSegment* pSegment = segmentManager.Segment (pSide->GetParent ()); short nSide = pSegment->SideIndex (pSide); short nVertices = pSide->VertexCount (); Renderer ().SelectPen ((pSide == nearestSide) ? penGold + 1 : penMedBlue + 1); CVertex& center = pSide->Center (); #if 0 double dist = sqrt (sqr (m_lastMousePos.x - center.m_screen.x) + sqr (m_lastMousePos.y - center.m_screen.y)); if (dist > 64.0) continue; #endif if (m_nRenderer) glLineStipple (1, 0x00ff); if (Renderer ().Ortho ()) { for (int i = 0; i <= nVertices; i++) { CVertex* vertex = pSegment->Vertex (nSide, i); if (i) Renderer ().LineTo (vertex->m_screen.x, vertex->m_screen.y); else Renderer ().MoveTo (vertex->m_screen.x, vertex->m_screen.y); } } else { for (int i = 0; i <= nVertices; i++) { CVertex* vertex = pSegment->Vertex (nSide, i); if (i) Renderer ().LineTo (*vertex); else Renderer ().MoveTo (*vertex); } } if (!pSide->IsVisible ()) { CVertex normal = pSide->Normal (2); normal.Project (ViewMatrix ()); center += normal; } if (m_nRenderer) glLineStipple (1, 0x3333); for (int i = 0; i < nVertices; i++) { if (Renderer ().Ortho ()) { CVertex* vertex = pSegment->Vertex (nSide, i); CDoubleVector c (double (center.m_screen.x), double (center.m_screen.y), double (center.m_screen.z)); CDoubleVector v (double (vertex->m_screen.x), double (vertex->m_screen.y), double (vertex->m_screen.z)); c -= v; double m = c.Mag (); c *= (m - 8.0) / m; c += v; Renderer ().MoveTo (vertex->m_screen.x, vertex->m_screen.y); Renderer ().LineTo (long (Round (c.v.x)), long (Round (c.v.y))); } else { Renderer ().MoveTo (*pSegment->Vertex (nSide, i)); Renderer ().LineTo (center); } } } Renderer ().EndRender (); } if (m_nShowSelectionCandidates > 0) { Renderer ().BeginRender (); if (m_nRenderer) glDepthFunc (GL_ALWAYS); for (CSide* pSide = segmentManager.SelectedSides (); pSide; pSide = pSide->GetLink ()) { CSegment* pSegment = segmentManager.Segment (pSide->GetParent ()); short nSide = pSegment->SideIndex (pSide); CVertex& center = pSide->Center (); #if 0 double dist = sqrt (sqr (m_lastMousePos.x - center.m_screen.x) + sqr (m_lastMousePos.y - center.m_screen.y)); if (dist > 64.0) continue; #endif Renderer ().SelectPen ((pSide == nearestSide) ? penGold + 1 : penMedBlue + 1, 1.5f); Renderer ().Ellipse (center, 5.0, 5.0); } Renderer ().EndRender (); } return true; } //-------------------------------------------------------------------------- // Determine all segments in the projection of which to the mine view the current // mouse position lies. Draw a circle in each segment's center and a line from // each side vertex to the circle to mark it. Open sides have the circle // moved in by their normal * 2.0. bool CMineView::DrawSelectableSegments (void) { if (!SelectMode (eSelectSegment)) return false; CRect viewport; GetClientRect (viewport); if (!segmentManager.GatherSelectableSides (viewport, LastMousePos ().x, LastMousePos ().y, ViewFlag (eViewMineSkyBox), true)) return false; double minDist = 1e30; CSegment* nearestSegment = null; CSide* nearestSide = null; short nSegment = -1; for (CSide* pSide = segmentManager.SelectedSides (); pSide; pSide = pSide->GetLink ()) { if (nSegment == pSide->GetParent ()) continue; CSegment* pSegment = segmentManager.Segment (nSegment = pSide->GetParent ()); CVertex& center = pSegment->Center (); double dist = sqrt (sqr (LastMousePos ().x - center.m_screen.x) + sqr (LastMousePos ().y - center.m_screen.y)); #if 0 if (dist > 64.0) continue; #endif if (minDist > dist) { minDist = dist; nearestSegment = pSegment; nearestSide = pSide; } } nearest->Setup (segmentManager.Index (nearestSegment), nearestSegment->SideIndex (nearestSide)); if (nearest->m_nSegment < 0) return false; if (m_nShowSelectionCandidates > 1) { Renderer ().BeginRender (); if (m_nRenderer) { glLineStipple (1, 0x00ff); glDepthFunc (GL_ALWAYS); glEnable (GL_LINE_STIPPLE); } nSegment = -1; for (CSide* pSide = segmentManager.SelectedSides (); pSide; pSide = pSide->GetLink ()) { if (nSegment == pSide->GetParent ()) continue; CSegment* pSegment = segmentManager.Segment (nSegment = pSide->GetParent ()); short nSide = pSegment->SideIndex (pSide); CVertex& center = pSegment->Center (); #if 0 double dist = sqrt (sqr (m_lastMousePos.x - center.m_screen.x) + sqr (m_lastMousePos.y - center.m_screen.y)); if (dist > 64.0) continue; #endif Renderer ().SelectPen ((pSide == nearestSide) ? penGold + 1 : penMedBlue + 1); if (m_nRenderer) glLineStipple (1, 0x00ff); DrawSegmentWireFrame (pSegment); Renderer ().SelectPen ((pSide == nearestSide) ? penGold + 1 : penMedBlue + 1); if (m_nRenderer) glLineStipple (1, 0x3333); for (int i = 0; i < 8; i++) { if (pSegment->VertexId (i) > MAX_VERTEX) continue; if (Renderer ().Ortho ()) { CVertex* vertex = pSegment->Vertex (i); CDoubleVector c (double (center.m_screen.x), double (center.m_screen.y), double (center.m_screen.z)); CDoubleVector v (double (vertex->m_screen.x), double (vertex->m_screen.y), double (vertex->m_screen.z)); c -= v; double m = c.Mag (); c *= (m - 8.0) / m; c += v; Renderer ().MoveTo (vertex->m_screen.x, vertex->m_screen.y); Renderer ().LineTo (long (Round (c.v.x)), long (Round (c.v.y))); } else { Renderer ().MoveTo (*pSegment->Vertex (nSide, i)); Renderer ().LineTo (center); } } } Renderer ().EndRender (); } if (m_nShowSelectionCandidates > 0) { Renderer ().BeginRender (); if (m_nRenderer) glDepthFunc (GL_ALWAYS); nSegment = -1; for (CSide* pSide = segmentManager.SelectedSides (); pSide; pSide = pSide->GetLink ()) { if (nSegment == pSide->GetParent ()) continue; CSegment* pSegment = segmentManager.Segment (nSegment = pSide->GetParent ()); short nSide = pSegment->SideIndex (pSide); CVertex& center = pSegment->Center (); #if 0 double dist = sqrt (sqr (m_lastMousePos.x - center.m_screen.x) + sqr (m_lastMousePos.y - center.m_screen.y)); if (dist > 64.0) continue; #endif Renderer ().SelectPen ((pSide == nearestSide) ? penGold + 1 : penMedBlue + 1, 1.5f); Renderer ().Ellipse (center, 5.0, 5.0); } Renderer ().EndRender (); } return true; } //-------------------------------------------------------------------------- void CMineView::DrawHighlight (void) { CHECKMINE; short currSide, currPoint; // short i; // RECT rect; if (segmentManager.Count ()== 0) return; // draw Objects () DrawObjects (); // if (/*!(preferences & PREFS_HIDE_TAGGED_BLOCKS) ||*/ SelectMode (eSelectBlock)) DrawTaggedSegments (); Renderer ().BeginRender (Renderer ().Type () == 0); // draw highlighted Segments () (other first, then current) // use pointer comparison so we don't draw the wrong selection if current/other are on the same segment and side if (current == &selections [0]) { if (selections [0].SegmentId () != selections [1].SegmentId ()) DrawSegmentHighlighted (selections [1].SegmentId (), selections [1].SideId (), selections [1].Edge (), selections [1].Point ()); DrawSegmentHighlighted (selections [0].SegmentId (), selections [0].SideId (), selections [0].Edge (), selections [0].Point ()); } else { if (selections [0].SegmentId () != selections [1].SegmentId ()) DrawSegmentHighlighted (selections [0].SegmentId (), selections [0].SideId (), selections [0].Edge (), selections [0].Point ()); DrawSegmentHighlighted (selections [1].SegmentId (), selections [1].SideId (), selections [1].Edge (), selections [1].Point ()); } Renderer ().EndRender (); if (ViewFlag (eViewMineWalls)) DrawWalls (); if (ViewFlag (eViewMineLights)) DrawLights (); nearest->SetSegmentId (-1); nearest->SetSideId (-1); nearest->SetEdge (-1); if ((m_inputHandler.MouseState () == eMouseStateSelect && m_inputHandler.HasMouseMovedInCurrentState ()) || m_inputHandler.MouseState () == eMouseStateApplySelect) { if (DrawSelectablePoint ()) ; else if (DrawSelectableEdge ()) ; else if (DrawSelectableSides () || DrawSelectableSegments ()) { Renderer ().BeginRender (false); if (m_nRenderer) { glLineStipple (1, 0x00ff); glEnable (GL_LINE_STIPPLE); glDepthFunc (GL_ALWAYS); } DrawSegmentHighlighted (selections [2].m_nSegment, selections [2].m_nSide, DEFAULT_EDGE, DEFAULT_POINT); if (m_nRenderer) glDisable (GL_LINE_STIPPLE); Renderer ().EndRender (); } } tunnelMaker.Draw (Renderer (), Pen (penRed), Pen (penBlue), ViewMatrix ()); textureProjector.DrawProjectGuides (Renderer (), ViewMatrix ()); *message = '\0'; #if 0 if (preferences & PREFS_SHOW_POINT_COORDINATES) { strcat_s (message, sizeof (message), " point (x, y,z): ("); short vertex = segmentManager.Segment (0) [current->SegmentId ()].m_info.vertexIds [sideVertexTable [current->SideId ()][current->Point ()]]; char szCoord [20]; sprintf_s (szCoord, sizeof (szCoord), "%1.4f,%1.4f,%1.4f)", vertexManager.Vertex (vertex)->v.x, vertexManager.Vertex (vertex)->v.y, vertexManager.Vertex (vertex)->v.z); strcat_s (message, sizeof (message), szCoord); } else #endif { // calculate segment size (length between center point of opposing sides) strcat_s (message, sizeof (message), " segment size: "); CDoubleVector center1, center2; double length; center1 = segmentManager.CalcSideCenter (CSideKey (current->SegmentId (), 0)); center2 = segmentManager.CalcSideCenter (CSideKey (current->SegmentId (), 2)); length = Distance (center1, center2); sprintf_s (message + strlen (message), sizeof (message) - strlen (message), "%.1f", (double) length); strcat_s (message, sizeof (message), " x "); center1 = segmentManager.CalcSideCenter (CSideKey (current->SegmentId (), 1)); center2 = segmentManager.CalcSideCenter (CSideKey (current->SegmentId (), 3)); length = Distance (center1, center2); sprintf_s (message + strlen (message), sizeof (message) - strlen (message), "%.1f", (double) length); strcat_s (message, sizeof (message), " x "); center1 = segmentManager.CalcSideCenter (CSideKey (current->SegmentId (), 4)); center2 = segmentManager.CalcSideCenter (CSideKey (current->SegmentId (), 5)); length = Distance (center1, center2); sprintf_s (message + strlen (message), sizeof (message) - strlen (message), "%.1f", (double) length); } strcat_s (message, sizeof (message), ", segment:"); _itoa_s (current->SegmentId (), message + strlen (message), sizeof (message) - strlen (message), 10); strcat_s (message, sizeof (message), " side:"); _itoa_s ((currSide = current->SideId ()) + 1, message + strlen (message), sizeof (message) - strlen (message), 10); strcat_s (message, sizeof (message), " point:"); _itoa_s (currPoint = current->Point (), message + strlen (message), sizeof (message) - strlen (message), 10); strcat_s (message, sizeof (message), " vertex:"); _itoa_s (current->Segment ()->m_info.vertexIds [current->Side ()->VertexIdIndex (currPoint)], message + strlen (message), sizeof (message) - strlen (message), 10); strcat_s (message, sizeof (message), ", textures:"); strcat_s (message, sizeof (message), " 1st:"); _itoa_s (current->Side ()->BaseTex (), message + strlen (message), sizeof (message) - strlen (message), 10); strcat_s (message, sizeof (message), " 2nd:"); _itoa_s (current->Side ()->OvlTex (0), message + strlen (message), sizeof (message) - strlen (message), 10); strcat_s (message, sizeof (message), ", zoom:"); double zoom = log (10 * Scale ().v.x) / log (zoomScales [m_nRenderer]); if (zoom > 0) zoom += 0.5; else zoom -= 0.5; sprintf_s (message + strlen (message), sizeof (message) - strlen (message), "%1.2f", zoom); STATUSMSG (message); } //------------------------------------------------------------------------------ //eof
#ifndef RBX_BUILTIN_IO_HPP #define RBX_BUILTIN_IO_HPP #include "builtin/object.hpp" #include "type_info.hpp" namespace rubinius { class ByteArray; class Channel; class String; class ByteArray; class IO : public Object { public: const static object_type type = IOType; private: Fixnum* descriptor_; // slot Object* ibuffer_; // slot Fixnum* mode_; // slot Object* eof_; // slot Integer* lineno_; // slot Object* sync_; // slot public: /* accessors */ attr_accessor(descriptor, Fixnum); attr_accessor(ibuffer, Object); attr_accessor(mode, Fixnum); attr_accessor(eof, Object); attr_accessor(lineno, Integer); attr_accessor(sync, Object); /* interface */ static void init(STATE); static IO* create(STATE, int fd); native_int to_fd(); void set_mode(STATE); void unsafe_set_descriptor(native_int fd); void force_read_only(STATE); void force_write_only(STATE); static void finalize(STATE, IO* io); /* Class primitives */ // Ruby.primitive :io_allocate static IO* allocate(STATE, Object* self); // Ruby.primitive :io_connect_pipe static Object* connect_pipe(STATE, IO* lhs, IO* rhs); // Ruby.primitive :io_open static Fixnum* open(STATE, String* path, Fixnum* mode, Fixnum* perm); /** * Perform select() on descriptors. * * @todo Replace with an evented version when redoing events. --rue */ // Ruby.primitive :io_select static Object* select(STATE, Object* readables, Object* writables, Object* errorables, Object* timeout, CallFrame* calling_environment); // Ruby.primitive :io_fnmatch static Object* fnmatch(STATE, String* pattern, String* path, Fixnum* flags); /* Instance primitives */ // Ruby.primitive :io_ensure_open Object* ensure_open(STATE); /** * Directly read up to number of bytes from descriptor. * * Returns Qnil at EOF. */ // Ruby.primitive :io_sysread Object* sysread(STATE, Fixnum* number_of_bytes, CallFrame* calling_environment); // Ruby.primitive :io_read_if_available Object* read_if_available(STATE, Fixnum* number_of_bytes); // Ruby.primitive :io_socket_read Object* socket_read(STATE, Fixnum* bytes, Fixnum* flags, Fixnum* type, CallFrame* calling_environment); // Ruby.primitive :io_seek Integer* seek(STATE, Integer* amount, Fixnum* whence); // Ruby.primitive :io_write Object* write(STATE, String* buf, CallFrame* calling_environment); // Ruby.primitive :io_reopen Object* reopen(STATE, IO* other); // Ruby.primitive :io_reopen_path Object* reopen_path(STATE, String* other, Fixnum * mode); // Ruby.primitive :io_close Object* close(STATE); // Ruby.primitive :io_accept Object* accept(STATE, CallFrame* calling_environment); // Ruby.primitive :io_send_io Object* send_io(STATE, IO* io); // Ruby.primitive :io_recv_fd Object* recv_fd(STATE, CallFrame* calling_environment); /** * Shutdown a full-duplex descriptor's read and/or write stream. * * Careful with this, it applies to full-duplex only. * It also shuts the stream *in all processes*, not * just the current one. */ // Ruby.primitive :io_shutdown Object* shutdown(STATE, Fixnum* how); // Ruby.primitive :io_blocking_read Object* blocking_read(STATE, Fixnum* count); // Ruby.primitive :io_query Object* query(STATE, Symbol* op); // Ruby.primitive :io_write_nonblock Object* write_nonblock(STATE, String* buf); void set_nonblock(STATE); class Info : public TypeInfo { public: BASIC_TYPEINFO(TypeInfo) }; }; #define IOBUFFER_SIZE 1024U class IOBuffer : public Object { public: const static size_t fields = 7; const static object_type type = IOBufferType; private: ByteArray* storage_; // slot Channel* channel_; // slot Integer* total_; // slot Integer* used_; // slot Integer* start_; // slot Object* eof_; // slot Object* write_synced_;// slot public: /* accessors */ attr_accessor(storage, ByteArray); attr_accessor(channel, Channel); attr_accessor(total, Integer); attr_accessor(used, Integer); attr_accessor(start, Integer); attr_accessor(eof, Object); attr_accessor(write_synced, Object); /* interface */ static IOBuffer* create(STATE, size_t bytes = IOBUFFER_SIZE); // Ruby.primitive :iobuffer_allocate static IOBuffer* allocate(STATE); // Ruby.primitive :iobuffer_unshift Object* unshift(STATE, String* str, Fixnum* start_pos); // Ruby.primitive :iobuffer_fill Object* fill(STATE, IO* io, CallFrame* calling_environment); void reset(STATE); String* drain(STATE); char* byte_address(); size_t left(); char* at_unused(); void read_bytes(STATE, size_t bytes); class Info : public TypeInfo { public: BASIC_TYPEINFO(TypeInfo) }; }; } #endif
/// @copyright /// Copyright (C) 2020 Assured Information Security, Inc. /// /// @copyright /// 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: /// /// @copyright /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// @copyright /// 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 <bsl/source_location.hpp> #include <bsl/discard.hpp> #include <bsl/ut.hpp> namespace { class fixture_t final { bsl::source_location sloc{bsl::here()}; public: [[nodiscard]] constexpr bool test_member_const() const { bsl::discard(sloc.file_name()); bsl::discard(sloc.function_name()); bsl::discard(sloc.line()); return true; } [[nodiscard]] constexpr bool test_member_nonconst() { bsl::discard(sloc.file_name()); bsl::discard(sloc.function_name()); bsl::discard(sloc.line()); return true; } }; constexpr fixture_t fixture1{}; } /// <!-- description --> /// @brief Main function for this unit test. If a call to ut_check() fails /// the application will fast fail. If all calls to ut_check() pass, this /// function will successfully return with bsl::exit_success. /// /// <!-- inputs/outputs --> /// @return Always returns bsl::exit_success. /// bsl::exit_code main() noexcept { using namespace bsl; bsl::ut_scenario{"verify noexcept"} = []() { bsl::ut_given{} = []() { bsl::ut_then{} = []() { static_assert(noexcept(bsl::source_location::current())); static_assert(noexcept(bsl::here())); static_assert(noexcept(bsl::here().file_name())); static_assert(noexcept(bsl::here().function_name())); static_assert(noexcept(bsl::here().line())); }; }; }; bsl::ut_scenario{"verify constness"} = []() { bsl::ut_given{} = []() { fixture_t fixture2{}; bsl::ut_then{} = [&fixture2]() { static_assert(fixture1.test_member_const()); ut_check(fixture2.test_member_nonconst()); }; }; }; return bsl::ut_success(); }
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Steemann //////////////////////////////////////////////////////////////////////////////// #include "CpuUsageFeature.h" #include "ApplicationFeatures/GreetingsFeaturePhase.h" #include "Basics/MutexLocker.h" #include "Basics/NumberUtils.h" #include "Basics/debugging.h" #if defined(_WIN32) #include <Windows.h> #endif #include <algorithm> #include <cstdio> #include <cstring> namespace arangodb { #if defined(__linux__) struct CpuUsageFeature::SnapshotProvider { SnapshotProvider(); ~SnapshotProvider(); SnapshotProvider(SnapshotProvider const&) = delete; SnapshotProvider& operator=(SnapshotProvider const&) = delete; bool canTakeSnapshot() const noexcept { return _statFile != nullptr; } bool tryTakeSnapshot(CpuUsageSnapshot& result) noexcept; private: size_t readStatFile(char* buffer, size_t bufferSize) noexcept; /// @brief handle for /proc/stat FILE* _statFile; }; CpuUsageFeature::SnapshotProvider::SnapshotProvider() : _statFile(nullptr) { // we are opening the /proc/stat file only once during the lifetime of the // process, in order to avoid frequent open/close calls _statFile = fopen("/proc/stat", "r"); } CpuUsageFeature::SnapshotProvider::~SnapshotProvider() { if (_statFile != nullptr) { fclose(_statFile); } } bool CpuUsageFeature::SnapshotProvider::tryTakeSnapshot( CpuUsageSnapshot& result) noexcept { constexpr size_t bufferSize = 4096; // none of the following methods will throw an exception rewind(_statFile); fflush(_statFile); char buffer[bufferSize]; buffer[0] = '\0'; size_t nread = readStatFile(&buffer[0], bufferSize); // expect a minimum size if (nread < 32 || memcmp(&buffer[0], "cpu ", 4) != 0) { // invalid data read. return false; } // 4 bytes because we skip the initial "cpu " intro result = CpuUsageSnapshot::fromString(&buffer[4], bufferSize - 4); return true; } size_t CpuUsageFeature::SnapshotProvider::readStatFile( char* buffer, size_t bufferSize) noexcept { size_t offset = 0; size_t remain = bufferSize - 1; while (remain > 0) { TRI_ASSERT(offset < bufferSize); size_t nread = fread(buffer + offset, 1, remain, _statFile); if (nread == 0) { break; } remain -= nread; offset += nread; } TRI_ASSERT(offset < bufferSize); buffer[offset] = '\0'; return offset; } #elif defined(_WIN32) struct CpuUsageFeature::SnapshotProvider { bool canTakeSnapshot() const noexcept { return true; } bool tryTakeSnapshot(CpuUsageSnapshot& result) noexcept; }; bool CpuUsageFeature::SnapshotProvider::tryTakeSnapshot( CpuUsageSnapshot& result) noexcept { FILETIME idleTime, kernelTime, userTime; if (GetSystemTimes(&idleTime, &kernelTime, &userTime) == FALSE) { return false; } auto toUInt64 = [](FILETIME const& value) { ULARGE_INTEGER result; result.LowPart = value.dwLowDateTime; result.HighPart = value.dwHighDateTime; return result.QuadPart; }; result.idle = toUInt64(idleTime); result.user = toUInt64(userTime); // the kernel time returned by GetSystemTimes includes the amount of time the // system has been idle result.system = toUInt64(kernelTime) - result.idle; return true; } #else struct CpuUsageFeature::SnapshotProvider { bool canTakeSnapshot() const noexcept { return false; } bool tryTakeSnapshot(CpuUsageSnapshot&) noexcept { TRI_ASSERT(false); // should never be called! return false; } }; #endif CpuUsageFeature::CpuUsageFeature( application_features::ApplicationServer& server) : ApplicationFeature(server, "CpuUsage"), _snapshotProvider(), _updateInProgress(false) { setOptional(true); startsAfter<application_features::GreetingsFeaturePhase>(); } CpuUsageFeature::~CpuUsageFeature() = default; void CpuUsageFeature::prepare() { _snapshotProvider = std::make_unique<SnapshotProvider>(); if (!_snapshotProvider->canTakeSnapshot()) { // we will not be able to provide any stats, so let's disable ourselves disable(); } } CpuUsageSnapshot CpuUsageFeature::snapshot() { CpuUsageSnapshot lastSnapshot, lastDelta; if (!isEnabled()) { return lastDelta; } // whether or not a concurrent thread is currently updating our // snapshot. if this is the case, we will simply return the old // snapshot bool updateInProgress; { // read last snapshot under the mutex MUTEX_LOCKER(guard, _snapshotMutex); lastSnapshot = _snapshot; lastDelta = _snapshotDelta; updateInProgress = _updateInProgress; if (!updateInProgress) { // its our turn! _updateInProgress = true; } } // now we can go on with a copy of the last snapshot without // holding the mutex if (updateInProgress) { // in a multi-threaded environment, we need to serialize our access // to /proc/stat by multiple concurrent threads. this also helps // reducing the load if multiple threads concurrently request the // CPU statistics return lastDelta; } CpuUsageSnapshot next; auto success = _snapshotProvider->tryTakeSnapshot(next); { // snapshot must be updated and returned under mutex MUTEX_LOCKER(guard, _snapshotMutex); if (success) { // if we failed to obtain new snapshot, we simply return whatever we had // before _snapshot = next; if (lastSnapshot.valid()) { next.subtract(lastSnapshot); } _snapshotDelta = next; } _updateInProgress = false; return _snapshotDelta; } } } // namespace arangodb
// Copyright 2019 The Fuchsia 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 <unistd.h> #include <limits> #include <soc/as370/audio-dsp.h> // Cascaded integrator–comb filter. // TODO(andresoportus) generalize and place in signal processing library. uint32_t CicFilter::Filter(uint32_t index, // e.g. 0. void* input, uint32_t input_size, // e.g. 16K. void* output, uint32_t input_total_channels, // e.g. 2. uint32_t input_channel, // e.g. 0 or 1. uint32_t output_total_channels, // e.f. 2. uint32_t output_channel, // e.g. 0 or 1. uint32_t multiplier_shift) { constexpr uint32_t input_bits_per_channel = 32; constexpr uint32_t input_bits_per_sample = 64; uint32_t* in = static_cast<uint32_t*>(input); uint32_t* in_end = reinterpret_cast<uint32_t*>(static_cast<uint8_t*>(input) + input_size); // 16 output bits per sample. uint16_t* out = static_cast<uint16_t*>(output); if (index > kMaxIndex) { return 0; } uint32_t amount_pcm = 0; while (in < in_end) { // Integrate. for (size_t word = 0; word < input_bits_per_sample / input_bits_per_channel; ++word) { uint32_t bits = in[input_channel]; in += input_total_channels; for (uint32_t i = 0; i < input_bits_per_channel; ++i, bits >>= 1) { // Integrator state is allowed to overflow and wrap, this is ok becuase of modulo // arithmetic, the differentiation will undo the wrapping. auto plus_or_minus = (static_cast<int32_t>(bits & 1) << 1) - 1; // +1/-1 from 1/0; integrator_state[index][0] += plus_or_minus; for (uint32_t stage = 1; stage < kOrder; ++stage) { integrator_state[index][stage] += integrator_state[index][stage - 1]; } } } // COMB (differentiator). int32_t acc = integrator_state[index][kOrder - 1]; int32_t old_acc = 0; for (uint32_t stage = 0; stage < kOrder; ++stage) { old_acc = acc; acc -= differentiator_state[index][stage]; differentiator_state[index][stage] = old_acc; } // Output pre-amplified by multiplier_shift. int32_t result = acc; if (result >= ((1 << (31 - multiplier_shift)) - 1)) { result = std::numeric_limits<int32_t>::max(); } else { result <<= multiplier_shift; } out[output_channel] = static_cast<int16_t>(result >> 16); // 16 output bits per sample. out += output_total_channels; amount_pcm += static_cast<uint32_t>(output_total_channels * sizeof(int16_t)); } return amount_pcm; }
#include <gameplay/GameplayModule.hpp> #include <poll.h> #include <QMutexLocker> #include <protobuf/RadioRx.pb.h> #include <protobuf/RadioTx.pb.h> #include <protobuf/messages_robocup_ssl_detection.pb.h> #include <protobuf/messages_robocup_ssl_geometry.pb.h> #include <protobuf/messages_robocup_ssl_wrapper.pb.h> #include <Constants.hpp> #include <Geometry2d/Util.hpp> #include <LogUtils.hpp> #include <Robot.hpp> #include <RobotConfig.hpp> #include <Utils.hpp> #include <joystick/GamepadController.hpp> #include <joystick/GamepadJoystick.hpp> #include <joystick/Joystick.hpp> #include <joystick/SpaceNavJoystick.hpp> #include <motion/MotionControl.hpp> #include <multicast.hpp> #include <planning/IndependentMultiRobotPathPlanner.hpp> #include <rc-fshare/git_version.hpp> #include "DebugDrawer.hpp" #include "Processor.hpp" #include "radio/NetworkRadio.hpp" #include "radio/SimRadio.hpp" #include "vision/VisionFilter.hpp" REGISTER_CONFIGURABLE(Processor) using namespace std; using namespace boost; using namespace Geometry2d; using namespace google::protobuf; static const auto Command_Latency = 0ms; RobotConfig* Processor::robotConfig2008; RobotConfig* Processor::robotConfig2011; RobotConfig* Processor::robotConfig2015; std::vector<RobotStatus*> Processor::robotStatuses; ///< FIXME: verify that this is correct Field_Dimensions* currentDimensions = &Field_Dimensions::Current_Dimensions; void Processor::createConfiguration(Configuration* cfg) { robotConfig2008 = new RobotConfig(cfg, "Rev2008"); robotConfig2011 = new RobotConfig(cfg, "Rev2011"); robotConfig2015 = new RobotConfig(cfg, "Rev2015"); for (size_t s = 0; s < Num_Shells; ++s) { robotStatuses.push_back( new RobotStatus(cfg, QString("Robot Statuses/Robot %1").arg(s))); } } Processor::Processor(bool sim, bool defendPlus, VisionChannel visionChannel, bool blueTeam, std::string readLogFile="") : _loopMutex(), _blueTeam(blueTeam), _readLogFile(readLogFile) { _running = true; _manualID = -1; _framerate = 0; _useOurHalf = true; _useOpponentHalf = true; _initialized = false; _simulation = sim; _radio = nullptr; _multipleManual = false; setupJoysticks(); _dampedTranslation = true; _dampedRotation = true; _kickOnBreakBeam = false; // Initialize team-space transformation defendPlusX(defendPlus); QMetaObject::connectSlotsByName(this); _vision = std::make_shared<VisionFilter>(); _refereeModule = std::make_shared<NewRefereeModule>(&_context, _blueTeam); _refereeModule->start(); _gameplayModule = std::make_shared<Gameplay::GameplayModule>(&_context); _pathPlanner = std::unique_ptr<Planning::MultiRobotPathPlanner>( new Planning::IndependentMultiRobotPathPlanner()); vision.simulation = _simulation; if (sim) { vision.port = SimVisionPort; } vision.start(); _visionChannel = visionChannel; // Create radio socket _radio = _simulation ? static_cast<Radio*>(new SimRadio(&_context, _blueTeam)) : static_cast<Radio*>(new NetworkRadio(NetworkRadioServerPort)); if (!readLogFile.empty()) { _logger.readFrames(readLogFile.c_str()); firstLogTime = _logger.startTime(); } _modules.push_back(std::make_unique<MotionControlNode>(&_context)); } Processor::~Processor() { stop(); for (Joystick* joy : _joysticks) { delete joy; } // DEBUG - This is unnecessary, but lets us determine which one breaks. //_refereeModule.reset(); _gameplayModule.reset(); } void Processor::stop() { if (_running) { _running = false; wait(); } } void Processor::manualID(int value) { QMutexLocker locker(&_loopMutex); _manualID = value; for (Joystick* joy : _joysticks) { joy->reset(); } } void Processor::multipleManual(bool value) { _multipleManual = value; } void Processor::goalieID(int value) { QMutexLocker locker(&_loopMutex); _gameplayModule->goalieID(value); } int Processor::goalieID() { QMutexLocker locker(&_loopMutex); return _gameplayModule->goalieID(); } void Processor::dampedRotation(bool value) { QMutexLocker locker(&_loopMutex); _dampedRotation = value; } void Processor::dampedTranslation(bool value) { QMutexLocker locker(&_loopMutex); _dampedTranslation = value; } void Processor::joystickKickOnBreakBeam(bool value) { QMutexLocker locker(&_loopMutex); _kickOnBreakBeam = value; } void Processor::setupJoysticks() { _joysticks.clear(); GamepadController::controllersInUse.clear(); GamepadController::joystickRemoved = -1; for (int i = 0; i < Robots_Per_Team; i++) { _joysticks.push_back(new GamepadController()); } //_joysticks.push_back(new SpaceNavJoystick()); //Add this back when // isValid() is working properly } /** * sets the team * @param value the value indicates whether or not the current team is blue or * yellow */ void Processor::blueTeam(bool value) { // This is called from the GUI thread QMutexLocker locker(&_loopMutex); if (_blueTeam != value) { _blueTeam = value; if (_radio) _radio->switchTeam(_blueTeam); // Try to set the team in the referee module. // Note: this will not update if we are being referee controlled. _refereeModule->overrideTeam(value); } } bool Processor::joystickValid() const { for (Joystick* joy : _joysticks) { if (joy->valid()) return true; } return false; } void Processor::runModels(const vector<const SSL_DetectionFrame*>& detectionFrames) { std::vector<CameraFrame> frames; for (const SSL_DetectionFrame* frame : detectionFrames) { vector<CameraBall> ballObservations; vector<CameraRobot> yellowObservations; vector<CameraRobot> blueObservations; RJ::Time time = RJ::Time(chrono::duration_cast<chrono::microseconds>( RJ::Seconds(frame->t_capture()))); // Add ball observations ballObservations.reserve(frame->balls().size()); for (const SSL_DetectionBall& ball : frame->balls()) { ballObservations.emplace_back(time, _worldToTeam * Point(ball.x() / 1000, ball.y() / 1000)); } // Collect camera data from all robots yellowObservations.reserve(frame->robots_yellow().size()); for (const SSL_DetectionRobot& robot : frame->robots_yellow()) { yellowObservations.emplace_back(time, _worldToTeam * Point(robot.x() / 1000, robot.y() / 1000), fixAngleRadians(robot.orientation() + _teamAngle), robot.robot_id()); } // Collect camera data from all robots blueObservations.reserve(frame->robots_blue().size()); for (const SSL_DetectionRobot& robot : frame->robots_blue()) { blueObservations.emplace_back(time, _worldToTeam * Point(robot.x() / 1000, robot.y() / 1000), fixAngleRadians(robot.orientation() + _teamAngle), robot.robot_id()); } frames.emplace_back(time, frame->camera_id(), ballObservations, yellowObservations, blueObservations); } _vision->addFrames(frames); // Fill the list of our robots/balls based on whether we are the blue team or not _vision->fillBallState(_context.state); _vision->fillRobotState(_context.state, _blueTeam); } /** * program loop */ void Processor::run() { Status curStatus; bool first = true; // main loop while (_running) { RJ::Time startTime = RJ::now(); auto deltaTime = startTime - curStatus.lastLoopTime; _framerate = RJ::Seconds(1) / deltaTime; curStatus.lastLoopTime = startTime; _context.state.time = startTime; if (!firstLogTime) { firstLogTime = startTime; } //////////////// // Reset // Make a new log frame _context.state.logFrame = std::make_shared<Packet::LogFrame>(); _context.state.logFrame->set_timestamp(RJ::timestamp()); _context.state.logFrame->set_command_time( RJ::timestamp(startTime + Command_Latency)); _context.state.logFrame->set_use_our_half(_useOurHalf); _context.state.logFrame->set_use_opponent_half(_useOpponentHalf); _context.state.logFrame->set_manual_id(_manualID); _context.state.logFrame->set_blue_team(_blueTeam); _context.state.logFrame->set_defend_plus_x(_defendPlusX); _context.debug_drawer.setLogFrame(_context.state.logFrame.get()); if (first) { first = false; Packet::LogConfig* logConfig = _context.state.logFrame->mutable_log_config(); logConfig->set_generator("soccer"); logConfig->set_git_version_hash(git_version_hash); logConfig->set_git_version_dirty(git_version_dirty); logConfig->set_simulation(_simulation); } for (OurRobot* robot : _context.state.self) { // overall robot config switch (robot->hardwareVersion()) { case Packet::RJ2008: robot->config = robotConfig2008; break; case Packet::RJ2011: robot->config = robotConfig2011; break; case Packet::RJ2015: robot->config = robotConfig2015; break; case Packet::Unknown: robot->config = robotConfig2011; // FIXME: defaults to 2011 robots break; } // per-robot configs robot->status = robotStatuses.at(robot->shell()); } //////////////// // Inputs // Read vision packets vector<const SSL_DetectionFrame*> detectionFrames; vector<VisionPacket*> visionPackets; vision.getPackets(visionPackets); for (VisionPacket* packet : visionPackets) { SSL_WrapperPacket* log = _context.state.logFrame->add_raw_vision(); log->CopyFrom(packet->wrapper); curStatus.lastVisionTime = packet->receivedTime; // If packet has geometry data, attempt to read information and // update if changed. if (packet->wrapper.has_geometry()) { updateGeometryPacket(packet->wrapper.geometry().field()); } if (packet->wrapper.has_detection()) { SSL_DetectionFrame* det = packet->wrapper.mutable_detection(); double rt = RJ::numSeconds(packet->receivedTime.time_since_epoch()); det->set_t_capture(rt - det->t_sent() + det->t_capture()); det->set_t_sent(rt); // Remove balls on the excluded half of the field google::protobuf::RepeatedPtrField<SSL_DetectionBall>* balls = det->mutable_balls(); for (int i = 0; i < balls->size(); ++i) { float x = balls->Get(i).x(); // FIXME - OMG too many terms if ((!_context.state.logFrame->use_opponent_half() && ((_defendPlusX && x < 0) || (!_defendPlusX && x > 0))) || (!_context.state.logFrame->use_our_half() && ((_defendPlusX && x > 0) || (!_defendPlusX && x < 0)))) { balls->SwapElements(i, balls->size() - 1); balls->RemoveLast(); --i; } } // Remove robots on the excluded half of the field google::protobuf::RepeatedPtrField<SSL_DetectionRobot>* robots[2] = {det->mutable_robots_yellow(), det->mutable_robots_blue()}; for (int team = 0; team < 2; ++team) { for (int i = 0; i < robots[team]->size(); ++i) { float x = robots[team]->Get(i).x(); if ((!_context.state.logFrame->use_opponent_half() && ((_defendPlusX && x < 0) || (!_defendPlusX && x > 0))) || (!_context.state.logFrame->use_our_half() && ((_defendPlusX && x > 0) || (!_defendPlusX && x < 0)))) { robots[team]->SwapElements( i, robots[team]->size() - 1); robots[team]->RemoveLast(); --i; } } } detectionFrames.push_back(det); } } // Read radio reverse packets _radio->receive(); while (_radio->hasReversePackets()) { Packet::RadioRx rx = _radio->popReversePacket(); _context.state.logFrame->add_radio_rx()->CopyFrom(rx); curStatus.lastRadioRxTime = RJ::Time(chrono::microseconds(rx.timestamp())); // Store this packet in the appropriate robot unsigned int board = rx.robot_id(); if (board < Num_Shells) { // We have to copy because the RX packet will survive past this // frame but LogFrame will not (the RadioRx in LogFrame will be // reused). _context.state.self[board]->setRadioRx(rx); _context.state.self[board]->radioRxUpdated(); } } for (Joystick* joystick : _joysticks) { joystick->update(); } GamepadController::joystickRemoved = -1; runModels(detectionFrames); for (VisionPacket* packet : visionPackets) { delete packet; } // Log referee data vector<NewRefereePacket*> refereePackets; _refereeModule.get()->getPackets(refereePackets); for (NewRefereePacket* packet : refereePackets) { SSL_Referee* log = _context.state.logFrame->add_raw_refbox(); log->CopyFrom(packet->wrapper); curStatus.lastRefereeTime = std::max(curStatus.lastRefereeTime, packet->receivedTime); delete packet; } // Update gamestate w/ referee data _refereeModule->updateGameState(blueTeam()); _refereeModule->spinKickWatcher(); string yellowname, bluename; if (blueTeam()) { bluename = _context.game_state.OurInfo.name; yellowname = _context.game_state.TheirInfo.name; } else { yellowname = _context.game_state.OurInfo.name; bluename = _context.game_state.TheirInfo.name; } _context.state.logFrame->set_team_name_blue(bluename); _context.state.logFrame->set_team_name_yellow(yellowname); // Run high-level soccer logic _gameplayModule->run(); // recalculates Field obstacles on every run through to account for // changing inset if (_gameplayModule->hasFieldEdgeInsetChanged()) { _gameplayModule->calculateFieldObstacles(); } /// Collect global obstacles Geometry2d::ShapeSet globalObstacles = _gameplayModule->globalObstacles(); Geometry2d::ShapeSet globalObstaclesWithGoalZones = globalObstacles; Geometry2d::ShapeSet goalZoneObstacles = _gameplayModule->goalZoneObstacles(); globalObstaclesWithGoalZones.add(goalZoneObstacles); // Build a plan request for each robot. std::map<int, Planning::PlanRequest> requests; for (OurRobot* r : _context.state.self) { if (r && r->visible) { if (_context.game_state.state == GameState::Halt) { r->setPath(nullptr); continue; } // Visualize local obstacles for (auto& shape : r->localObstacles().shapes()) { _context.debug_drawer.drawShape(shape, Qt::black, "LocalObstacles"); } auto& globalObstaclesForBot = (r->shell() == _gameplayModule->goalieID() || r->isPenaltyKicker || r->isBallPlacer) ? globalObstacles : globalObstaclesWithGoalZones; // create and visualize obstacles Geometry2d::ShapeSet staticObstacles = r->collectStaticObstacles( globalObstaclesForBot, !(r->shell() == _gameplayModule->goalieID() || r->isPenaltyKicker || r->isBallPlacer)); std::vector<Planning::DynamicObstacle> dynamicObstacles = r->collectDynamicObstacles(); requests.emplace( r->shell(), Planning::PlanRequest( &_context, Planning::MotionInstant(r->pos, r->vel), r->motionCommand()->clone(), r->robotConstraints(), std::move(r->angleFunctionPath.path), std::move(staticObstacles), std::move(dynamicObstacles), r->shell(), r->getPlanningPriority())); } } // Run path planner and set the path for each robot that was planned for auto pathsById = _pathPlanner->run(std::move(requests)); for (auto& entry : pathsById) { OurRobot* r = _context.state.self[entry.first]; auto& path = entry.second; path->draw(&_context.debug_drawer, Qt::magenta, "Planning"); path->drawDebugText(&_context.debug_drawer); r->setPath(std::move(path)); r->angleFunctionPath.angleFunction = angleFunctionForCommandType(r->rotationCommand()); } // Visualize obstacles for (auto& shape : globalObstacles.shapes()) { _context.debug_drawer.drawShape(shape, Qt::black, "Global Obstacles"); } // TODO(Kyle, Collin): This is a horrible hack to get around the fact // that joystick code only (sort of) supports one joystick at a time. // Figure out which robots are manual controlled. for (OurRobot* robot : _context.state.self) { robot->setJoystickControlled(robot->shell() == _manualID); } // Run all modules in sequence for (auto& module : _modules) { module->run(); } //////////////// // Store logging information // Debug layers const QStringList& layers = _context.debug_drawer.debugLayers(); for (const QString& str : layers) { _context.state.logFrame->add_debug_layers(str.toStdString()); } // Add our robots data to the LogFram for (OurRobot* r : _context.state.self) { if (r->visible) { r->addStatusText(); Packet::LogFrame::Robot* log = _context.state.logFrame->add_self(); *log->mutable_pos() = r->pos; *log->mutable_world_vel() = r->vel; *log->mutable_body_vel() = r->vel.rotated(M_PI_2 - r->angle); //*log->mutable_cmd_body_vel() = r-> // *log->mutable_cmd_vel() = r->cmd_vel; // log->set_cmd_w(r->cmd_w); log->set_shell(r->shell()); log->set_angle(r->angle); auto radioRx = r->radioRx(); if (radioRx.has_kicker_voltage()) { log->set_kicker_voltage(radioRx.kicker_voltage()); } if (radioRx.has_kicker_status()) { log->set_charged(radioRx.kicker_status() & 0x01); log->set_kicker_works(!(radioRx.kicker_status() & 0x90)); } if (radioRx.has_ball_sense_status()) { log->set_ball_sense_status(radioRx.ball_sense_status()); } if (radioRx.has_battery()) { log->set_battery_voltage(radioRx.battery()); } log->mutable_motor_status()->Clear(); log->mutable_motor_status()->MergeFrom(radioRx.motor_status()); if (radioRx.has_quaternion()) { log->mutable_quaternion()->Clear(); log->mutable_quaternion()->MergeFrom(radioRx.quaternion()); } else { log->clear_quaternion(); } for (const Packet::DebugText& t : r->robotText) { log->add_text()->CopyFrom(t); } } } // Opponent robots for (OpponentRobot* r : _context.state.opp) { if (r->visible) { Packet::LogFrame::Robot* log = _context.state.logFrame->add_opp(); *log->mutable_pos() = r->pos; log->set_shell(r->shell()); log->set_angle(r->angle); *log->mutable_world_vel() = r->vel; *log->mutable_body_vel() = r->vel.rotated(2 * M_PI - r->angle); } } // Ball if (_context.state.ball.valid) { Packet::LogFrame::Ball* log = _context.state.logFrame->mutable_ball(); *log->mutable_pos() = _context.state.ball.pos; *log->mutable_vel() = _context.state.ball.vel; } //////////////// // Outputs // Send motion commands to the robots sendRadioData(); // Write to the log unless we are viewing logs or main window is paused if (_readLogFile.empty() && !_paused) { _logger.addFrame(_context.state.logFrame); } // Store processing loop status _statusMutex.lock(); _status = curStatus; _statusMutex.unlock(); // Processor Initialization Completed _initialized = true; //////////////// // Timing auto endTime = RJ::now(); auto timeLapse = endTime - startTime; if (timeLapse < _framePeriod) { // Use system usleep, not QThread::usleep. // // QThread::usleep uses pthread_cond_wait which sometimes fails to // unblock. // This seems to depend on how many threads are blocked. ::usleep(RJ::numMicroseconds(_framePeriod - timeLapse)); } else { // printf("Processor took too long: %d us\n", lastFrameTime); } } vision.stop(); } /* * Updates the geometry packet if different from the existing one, * Based on the geometry vision data. */ void Processor::updateGeometryPacket(const SSL_GeometryFieldSize& fieldSize) { if (fieldSize.field_lines_size() == 0) { return; } const SSL_FieldCicularArc* penalty = nullptr; const SSL_FieldCicularArc* center = nullptr; float penaltyShortDist = 0; // default value float penaltyLongDist = 0; // default value float displacement = Field_Dimensions::Default_Dimensions.GoalFlat(); // default displacment // Loop through field arcs looking for needed fields for (const SSL_FieldCicularArc& arc : fieldSize.field_arcs()) { if (arc.name() == "CenterCircle") { // Assume center circle center = &arc; } } for (const SSL_FieldLineSegment& line : fieldSize.field_lines()) { if (line.name() == "RightPenaltyStretch") { displacement = abs(line.p2().y() - line.p1().y()); penaltyLongDist = displacement; } else if (line.name() == "RightFieldRightPenaltyStretch") { penaltyShortDist = abs(line.p2().x() - line.p1().x()); } } float thickness = fieldSize.field_lines().Get(0).thickness() / 1000.0f; // The values we get are the center of the lines, we want to use the // outside, so we can add this as an offset. float adj = fieldSize.field_lines().Get(0).thickness() / 1000.0f / 2.0f; float fieldBorder = currentDimensions->Border(); if (penaltyLongDist != 0 && penaltyShortDist != 0 && center != nullptr && thickness != 0) { // Force a resize Field_Dimensions newDim = Field_Dimensions( fieldSize.field_length() / 1000.0f, fieldSize.field_width() / 1000.0f, fieldBorder, thickness, fieldSize.goal_width() / 1000.0f, fieldSize.goal_depth() / 1000.0f, Field_Dimensions::Default_Dimensions.GoalHeight(), penaltyShortDist / 1000.0f, // PenaltyShortDist penaltyLongDist / 1000.0f, // PenaltyLongDist center->radius() / 1000.0f + adj, // CenterRadius (center->radius()) * 2 / 1000.0f + adj, // CenterDiameter displacement / 1000.0f, // GoalFlat (fieldSize.field_length() / 1000.0f + (fieldBorder)*2), (fieldSize.field_width() / 1000.0f + (fieldBorder)*2)); if (newDim != *currentDimensions) { setFieldDimensions(newDim); } } else if (center != nullptr && thickness != 0) { Field_Dimensions defaultDim = Field_Dimensions::Default_Dimensions; Field_Dimensions newDim = Field_Dimensions( fieldSize.field_length() / 1000.0f, fieldSize.field_width() / 1000.0f, fieldBorder, thickness, fieldSize.goal_width() / 1000.0f, fieldSize.goal_depth() / 1000.0f, Field_Dimensions::Default_Dimensions.GoalHeight(), defaultDim.PenaltyShortDist(), // PenaltyShortDist defaultDim.PenaltyLongDist(), // PenaltyLongDist center->radius() / 1000.0f + adj, // CenterRadius (center->radius()) * 2 / 1000.0f + adj, // CenterDiameter displacement / 1000.0f, // GoalFlat (fieldSize.field_length() / 1000.0f + (fieldBorder)*2), (fieldSize.field_width() / 1000.0f + (fieldBorder)*2)); if (newDim != *currentDimensions) { setFieldDimensions(newDim); } } else { cerr << "Error: failed to decode SSL geometry packet. Not resizing " "field." << endl; } } void Processor::sendRadioData() { Packet::RadioTx* tx = _context.state.logFrame->mutable_radio_tx(); tx->set_txmode(Packet::RadioTx::UNICAST); // Halt overrides normal motion control, but not joystick if (_context.game_state.halt()) { // Force all motor speeds to zero for (OurRobot* r : _context.state.self) { Packet::Control* control = r->control; control->set_xvelocity(0); control->set_yvelocity(0); control->set_avelocity(0); control->set_dvelocity(0); control->set_kcstrength(0); control->set_shootmode(Packet::Control::KICK); control->set_triggermode(Packet::Control::STAND_DOWN); control->set_song(Packet::Control::STOP); } } // Add RadioTx commands for visible robots and apply joystick input std::vector<int> manualIds = getJoystickRobotIds(); for (OurRobot* r : _context.state.self) { if (r->visible || _manualID == r->shell() || _multipleManual) { Packet::Robot* txRobot = tx->add_robots(); // Copy motor commands. // Even if we are using the joystick, this sets robot_id and the // number of motors. txRobot->CopyFrom(r->robotPacket); // MANUAL STUFF if (_multipleManual) { auto info = find(manualIds.begin(), manualIds.end(), r->shell()); int index = info - manualIds.begin(); // figure out if this shell value has been assigned to a // joystick // do stuff with that information such as assign it to the first // available if (info == manualIds.end()) { for (int i = 0; i < manualIds.size(); i++) { if (manualIds[i] == -1) { index = i; _joysticks[i]->setRobotId(r->shell()); manualIds[i] = r->shell(); break; } } } if (index < manualIds.size()) { applyJoystickControls( getJoystickControlValue(*_joysticks[index]), txRobot->mutable_control(), r); } } else if (_manualID == r->shell()) { auto controlValues = getJoystickControlValues(); if (controlValues.size()) { applyJoystickControls(controlValues[0], txRobot->mutable_control(), r); } } } } if (_radio) { _radio->send(*_context.state.logFrame->mutable_radio_tx()); } } void Processor::applyJoystickControls(const JoystickControlValues& controlVals, Packet::Control* tx, OurRobot* robot) { Geometry2d::Point translation(controlVals.translation); // use world coordinates if we can see the robot // otherwise default to body coordinates if (robot && robot->visible && _useFieldOrientedManualDrive) { translation.rotate(-M_PI / 2 - robot->angle); } // translation tx->set_xvelocity(translation.x()); tx->set_yvelocity(translation.y()); // rotation tx->set_avelocity(controlVals.rotation); // kick/chip bool kick = controlVals.kick || controlVals.chip; tx->set_triggermode(kick ? (_kickOnBreakBeam ? Packet::Control::ON_BREAK_BEAM : Packet::Control::IMMEDIATE) : Packet::Control::STAND_DOWN); tx->set_kcstrength(controlVals.kickPower); tx->set_shootmode(controlVals.kick ? Packet::Control::KICK : Packet::Control::CHIP); // dribbler tx->set_dvelocity(controlVals.dribble ? controlVals.dribblerPower : 0); } JoystickControlValues Processor::getJoystickControlValue(Joystick& joy) { JoystickControlValues vals = joy.getJoystickControlValues(); if (joy.valid()) { // keep it in range vals.translation.clamp(sqrt(2.0)); if (vals.rotation > 1) vals.rotation = 1; if (vals.rotation < -1) vals.rotation = -1; // Gets values from the configured joystick control // values,respecting damped // state if (_dampedTranslation) { vals.translation *= Joystick::JoystickTranslationMaxDampedSpeed->value(); } else { vals.translation *= Joystick::JoystickTranslationMaxSpeed->value(); } if (_dampedRotation) { vals.rotation *= Joystick::JoystickRotationMaxDampedSpeed->value(); } else { vals.rotation *= Joystick::JoystickRotationMaxSpeed->value(); } // scale up kicker and dribbler speeds vals.dribblerPower *= Max_Dribble; vals.kickPower *= Max_Kick; } return vals; } std::vector<JoystickControlValues> Processor::getJoystickControlValues() { std::vector<JoystickControlValues> vals; for (Joystick* joy : _joysticks) { if (joy->valid()) { vals.push_back(getJoystickControlValue(*joy)); } } return vals; } vector<int> Processor::getJoystickRobotIds() { vector<int> robotIds; for (Joystick* joy : _joysticks) { if (joy->valid()) { robotIds.push_back(joy->getRobotId()); } else { robotIds.push_back(-2); } } return robotIds; } void Processor::defendPlusX(bool value) { _defendPlusX = value; if (_defendPlusX) { _teamAngle = -M_PI_2; } else { _teamAngle = M_PI_2; } recalculateWorldToTeamTransform(); } void Processor::changeVisionChannel(int port) { _loopMutex.lock(); vision.stop(); vision.simulation = _simulation; vision.port = port; vision.start(); _loopMutex.unlock(); } void Processor::recalculateWorldToTeamTransform() { _worldToTeam = Geometry2d::TransformMatrix::translate( 0, Field_Dimensions::Current_Dimensions.Length() / 2.0f); _worldToTeam *= Geometry2d::TransformMatrix::rotate(_teamAngle); } void Processor::setFieldDimensions(const Field_Dimensions& dims) { cout << "Updating field geometry based off of vision packet." << endl; Field_Dimensions::Current_Dimensions = dims; recalculateWorldToTeamTransform(); _gameplayModule->calculateFieldObstacles(); _gameplayModule->updateFieldDimensions(); } bool Processor::isRadioOpen() const { return _radio->isOpen(); } bool Processor::isInitialized() const { return _initialized; }
#include "polindrom.h" #include <iostream> #include <string> #include <map> Polindrom::Polindrom(/* args */) { } Polindrom::~Polindrom() { } void Polindrom::testShow(char message[]) { std::cout << message << std::endl; } void Polindrom::SetInput(std::string input) { mInput = input; } void Polindrom::InputLength() { std::cout << "length: " << mInput.length() << std::endl; } void Polindrom::Process() { std::map<char, int> mapping; int maxPolindrom = 0; InputLength(); //Подсчитать кол-во символов в строке for (int i = 0; i < mInput.length(); i++) { mapping[mInput[i]]++; } std::string polindromString; std::string polindromTemp; char anyCharWithNoPair; for (std::map<char, int>::iterator element = mapping.begin(); element != mapping.end(); element++) { int possibleInPolidrom = element->second / 2; //составляем начальную часть полиндрома или запоминаем нечетный символ if (possibleInPolidrom > 0) { for (int index = 0; index < possibleInPolidrom; index++) { polindromTemp.push_back(element->first); } } else { anyCharWithNoPair = element->first; } maxPolindrom += possibleInPolidrom; std::cout << "1 = " << element->first << std::endl; std::cout << "2 = " << element->second << std::endl; } //По сути расчитано кол-во символов в половине -> умножим на 2 maxPolindrom *= 2; polindromString = polindromTemp; if (mInput.length() % 2 != 0) { maxPolindrom += 1; polindromString.push_back(anyCharWithNoPair); } for (int i = polindromTemp.length() - 1; i >= 0; i--) { polindromString.push_back(polindromTemp[i]); } std::cout << "maxPolindrom: " << maxPolindrom << std::endl; std::cout << "Polindrom string " << polindromString << std::endl; }
#include "stdafx.h" #include "HumanCharacterController.h" #include "Pedestrian.h" #include "PhysicsManager.h" #include "PhysicsComponents.h" #include "PhysicsDefs.h" #include "Vehicle.h" ////////////////////////////////////////////////////////////////////////// struct DefaultActionMapping { public: DefaultActionMapping(ePedActionsGroup group, ePedestrianAction action, eKeycode keycode, eGamepadButton gpButton = eGamepadButton_null) : mActionGroup(group) , mAction(action) , mKeycode(keycode) , mGpButton(gpButton) { } public: ePedActionsGroup mActionGroup; ePedestrianAction mAction; eKeycode mKeycode; eGamepadButton mGpButton; }; static const DefaultActionMapping gDefaultActionsMapping[] = { // common {ePedActionsGroup_Common, ePedestrianAction_NextWeapon, eKeycode_X}, {ePedActionsGroup_Common, ePedestrianAction_PrevWeapon, eKeycode_Z}, // in car {ePedActionsGroup_InCar, ePedestrianAction_LeaveCar, eKeycode_ENTER}, {ePedActionsGroup_InCar, ePedestrianAction_HandBrake, eKeycode_SPACE}, {ePedActionsGroup_InCar, ePedestrianAction_Accelerate, eKeycode_UP}, {ePedActionsGroup_InCar, ePedestrianAction_Reverse, eKeycode_DOWN}, {ePedActionsGroup_InCar, ePedestrianAction_SteerLeft, eKeycode_LEFT}, {ePedActionsGroup_InCar, ePedestrianAction_SteerRight, eKeycode_RIGHT}, {ePedActionsGroup_InCar, ePedestrianAction_Horn, eKeycode_TAB}, // on foot {ePedActionsGroup_OnFoot, ePedestrianAction_TurnLeft, eKeycode_LEFT}, {ePedActionsGroup_OnFoot, ePedestrianAction_TurnRight, eKeycode_RIGHT}, {ePedActionsGroup_OnFoot, ePedestrianAction_Jump, eKeycode_SPACE}, {ePedActionsGroup_OnFoot, ePedestrianAction_WalkBackward, eKeycode_DOWN}, {ePedActionsGroup_OnFoot, ePedestrianAction_Run, eKeycode_UP}, {ePedActionsGroup_OnFoot, ePedestrianAction_Shoot, eKeycode_LEFT_CTRL}, {ePedActionsGroup_OnFoot, ePedestrianAction_EnterCar, eKeycode_ENTER}, {ePedActionsGroup_OnFoot, ePedestrianAction_EnterCarAsPassenger, eKeycode_F}, }; InputActionsMapping::InputActionsMapping() { SetNull(); } void InputActionsMapping::SetNull() { mControllerType = eInputControllerType_None; ::memset(mKeycodes, 0, sizeof(mKeycodes)); ::memset(mGpButtons, 0, sizeof(mGpButtons)); } void InputActionsMapping::SetDefaults() { mControllerType = eInputControllerType_Keyboard; for (const DefaultActionMapping& curr: gDefaultActionsMapping) { mKeycodes[curr.mAction] = curr.mKeycode; } } void InputActionsMapping::SetFromConfig(cxx::config_node& configNode) { const char* controller_type_str = configNode.get_child("controller_type").get_value_string(); if (!cxx::parse_enum(controller_type_str, mControllerType)) { gConsole.LogMessage(eLogMessage_Warning, "Unknown controller type '%s'", controller_type_str); } // scan keycodes if (cxx::config_node keysNode = configNode.get_child("keys")) { ePedestrianAction action = ePedestrianAction_null; eKeycode keycode = eKeycode_null; for (cxx::config_node currNode = keysNode.first_child(); currNode; currNode = currNode.next_sibling()) { const char* action_str = currNode.get_element_name(); if (!cxx::parse_enum(action_str, action)) { gConsole.LogMessage(eLogMessage_Warning, "Unknown action %s", action_str); continue; } const char* keycode_str = currNode.get_value_string(); if (!cxx::parse_enum(keycode_str, keycode)) { gConsole.LogMessage(eLogMessage_Warning, "Unknown keycode %s", keycode_str); continue; } mKeycodes[action] = keycode; } } // scan gamepad buttons if (cxx::config_node gpNode = configNode.get_child("gamepad")) { ePedestrianAction action = ePedestrianAction_null; eGamepadButton gpButton = eGamepadButton_null; for (cxx::config_node currNode = gpNode.first_child(); currNode; currNode = currNode.next_sibling()) { const char* action_str = currNode.get_element_name(); if (!cxx::parse_enum(action_str, action)) { gConsole.LogMessage(eLogMessage_Warning, "Unknown action %s", action_str); continue; } const char* gpbutton_str = currNode.get_value_string(); if (!cxx::parse_enum(gpbutton_str, gpButton)) { gConsole.LogMessage(eLogMessage_Warning, "Unknown gamepad button %s", gpbutton_str); continue; } mGpButtons[action] = gpButton; } } int bp = 0; } ePedestrianAction InputActionsMapping::GetAction(ePedActionsGroup group, eKeycode keycode) const { for (const DefaultActionMapping& curr: gDefaultActionsMapping) { if ((curr.mActionGroup == ePedActionsGroup_Common || curr.mActionGroup == group) && mKeycodes[curr.mAction] == keycode) { return curr.mAction; } } return ePedestrianAction_null; } ePedestrianAction InputActionsMapping::GetAction(ePedActionsGroup group, eGamepadButton gpButton) const { for (const DefaultActionMapping& curr: gDefaultActionsMapping) { if ((curr.mActionGroup == ePedActionsGroup_Common || curr.mActionGroup == group) && mGpButtons[curr.mAction] == gpButton) { return curr.mAction; } } return ePedestrianAction_null; } ////////////////////////////////////////////////////////////////////////// void HumanCharacterController::UpdateFrame(Pedestrian* pedestrian, Timespan deltaTime) { debug_assert(pedestrian == mCharacter); } void HumanCharacterController::InputEvent(KeyInputEvent& inputEvent) { debug_assert(mCharacter); if (mInputs.mControllerType != eInputControllerType_Keyboard) return; ePedActionsGroup actionGroup = mCharacter->IsCarPassenger() ? ePedActionsGroup_InCar : ePedActionsGroup_OnFoot; ePedestrianAction action = mInputs.GetAction(actionGroup, inputEvent.mKeycode); if (action == ePedestrianAction_null) return; if (HandleInputAction(action, inputEvent.mPressed)) { inputEvent.SetConsumed(); return; } } void HumanCharacterController::InputEvent(GamepadInputEvent& inputEvent) { debug_assert(mCharacter); static const eInputControllerType gamepadControllers[MAX_GAMEPADS] = { eInputControllerType_Gamepad1, eInputControllerType_Gamepad2, eInputControllerType_Gamepad3, eInputControllerType_Gamepad4 }; if (inputEvent.mGamepad < MAX_GAMEPADS) { eInputControllerType controllerType = gamepadControllers[inputEvent.mGamepad]; if (controllerType != mInputs.mControllerType) return; ePedActionsGroup actionGroup = mCharacter->IsCarPassenger() ? ePedActionsGroup_InCar : ePedActionsGroup_OnFoot; ePedestrianAction action = mInputs.GetAction(actionGroup, inputEvent.mButton); if (action == ePedestrianAction_null) return; if (HandleInputAction(action, inputEvent.mPressed)) { inputEvent.SetConsumed(); return; } } } bool HumanCharacterController::HandleInputAction(ePedestrianAction action, bool isActivated) { switch (action) { case ePedestrianAction_SteerLeft: case ePedestrianAction_TurnLeft: case ePedestrianAction_SteerRight: case ePedestrianAction_TurnRight: case ePedestrianAction_Run: case ePedestrianAction_Accelerate: case ePedestrianAction_Reverse: case ePedestrianAction_WalkBackward: case ePedestrianAction_WalkForward: case ePedestrianAction_Jump: case ePedestrianAction_HandBrake: case ePedestrianAction_Shoot: mCharacter->mCtlActions[action] = isActivated; break; case ePedestrianAction_Horn: if (mCharacter->IsCarPassenger()) { mCharacter->mCtlActions[ePedestrianAction_Horn] = isActivated; if (mCharacter->mCurrentCar->HasEmergencyLightsAnimation()) { mCharacter->mCurrentCar->EnableEmergencyLights(isActivated); } } break; case ePedestrianAction_NextWeapon: if (isActivated) { SwitchNextWeapon(); } break; case ePedestrianAction_PrevWeapon: if (isActivated) { SwitchPrevWeapon(); } break; case ePedestrianAction_EnterCar: case ePedestrianAction_LeaveCar: case ePedestrianAction_EnterCarAsPassenger: if (isActivated) { EnterOrExitCar(action == ePedestrianAction_EnterCarAsPassenger); } break; default: debug_assert(false); return false; } return true; } void HumanCharacterController::SetCharacter(Pedestrian* character) { if (mCharacter) { debug_assert(mCharacter->mController == this); mCharacter->mController = nullptr; } mCharacter = character; if (mCharacter) { mCharacter->mController = this; } } void HumanCharacterController::SwitchNextWeapon() { int nextWeaponIndex = (mCharacter->mCurrentWeapon + 1) % eWeaponType_COUNT; for (; nextWeaponIndex != mCharacter->mCurrentWeapon; ) { if (mCharacter->mWeaponsAmmo[nextWeaponIndex] != 0) { PedestrianStateEvent ev = PedestrianStateEvent::Get_ActionWeaponChange((eWeaponType) nextWeaponIndex); mCharacter->ProcessEvent(ev); return; } nextWeaponIndex = (nextWeaponIndex + 1) % eWeaponType_COUNT; } } void HumanCharacterController::SwitchPrevWeapon() { int nextWeaponIndex = mCharacter->mCurrentWeapon == 0 ? (eWeaponType_COUNT - 1) : (mCharacter->mCurrentWeapon - 1); for (; nextWeaponIndex != mCharacter->mCurrentWeapon; ) { if (mCharacter->mWeaponsAmmo[nextWeaponIndex] != 0) { PedestrianStateEvent ev = PedestrianStateEvent::Get_ActionWeaponChange((eWeaponType) nextWeaponIndex); mCharacter->ProcessEvent(ev); return; } nextWeaponIndex = nextWeaponIndex == 0 ? (eWeaponType_COUNT - 1) : (nextWeaponIndex - 1); } } void HumanCharacterController::EnterOrExitCar(bool alternative) { if (mCharacter->IsCarPassenger()) { PedestrianStateEvent ev = PedestrianStateEvent::Get_ActionLeaveCar(); mCharacter->ProcessEvent(ev); return; } PhysicsQueryResult queryResult; glm::vec3 pos = mCharacter->mPhysicsComponent->GetPosition(); glm::vec2 posA { pos.x, pos.z }; glm::vec2 posB = posA + (mCharacter->mPhysicsComponent->GetSignVector() * gGameParams.mPedestrianSpotTheCarDistance); gPhysics.QueryObjects(posA, posB, queryResult); // process all cars for (int icar = 0; icar < queryResult.mCarsCount; ++icar) { Vehicle* currCar = queryResult.mCarsList[icar]->mReferenceCar; eCarSeat carSeat = alternative ? eCarSeat_Passenger : eCarSeat_Driver; if (currCar->IsSeatPresent(carSeat)) { PedestrianStateEvent ev = PedestrianStateEvent::Get_ActionEnterCar(currCar, carSeat); mCharacter->ProcessEvent(ev); } return; } }
#include "audio_encoder_adapter.h" #define LOG_TAG "AudioEncoderAdapter" AudioEncoderAdapter::AudioEncoderAdapter() { audioCodecName = NULL; audioEncoder = NULL; isEncoding = false; } AudioEncoderAdapter::~AudioEncoderAdapter() { } static int fill_pcm_frame_callback(int16_t *samples, int frame_size, int nb_channels, double* presentationTimeMills, void *context) { AudioEncoderAdapter* audioEncoderAdapter = (AudioEncoderAdapter*) context; return audioEncoderAdapter->getAudioFrame(samples, frame_size, nb_channels, presentationTimeMills); } void AudioEncoderAdapter::init(LivePacketPool* pcmPacketPool, int audioSampleRate, int audioChannels, int audioBitRate, const char* audio_codec_name){ /** iOS是1.0f Android是2.0f **/ this->channelRatio = 1.0f; this->packetBuffer = NULL; this->packetBufferSize = 0; this->packetBufferCursor = 0; this->pcmPacketPool = pcmPacketPool; this->audioSampleRate = audioSampleRate; this->audioChannels = audioChannels; this->audioBitRate = audioBitRate; int audioCodecNameLength = strlen(audio_codec_name); audioCodecName = new char[audioCodecNameLength + 1]; memset(audioCodecName, 0, audioCodecNameLength + 1); memcpy(audioCodecName, audio_codec_name, audioCodecNameLength); this->isEncoding = true; this->aacPacketPool = LiveAudioPacketPool::GetInstance(); pthread_create(&audioEncoderThread, NULL, startEncodeThread, this); } void* AudioEncoderAdapter::startEncodeThread(void* ptr) { AudioEncoderAdapter* audioEncoderAdapter = (AudioEncoderAdapter *) ptr; audioEncoderAdapter->startEncode(); pthread_exit(0); return NULL; } void AudioEncoderAdapter::startEncode(){ audioEncoder = new AudioEncoder(); audioEncoder->init(audioBitRate, audioChannels, audioSampleRate, audioCodecName, fill_pcm_frame_callback, this); while(isEncoding){ //1:调用AudioEncoder进行编码并且打上时间戳 LiveAudioPacket *audioPacket = NULL; int ret = audioEncoder->encode(&audioPacket); //2:将编码之后的数据放入aacPacketPool中 if(ret >= 0 && NULL != audioPacket){ aacPacketPool->pushAudioPacketToQueue(audioPacket); } } } void AudioEncoderAdapter::destroy(){ isEncoding = false; pcmPacketPool->abortAudioPacketQueue(); pthread_join(audioEncoderThread, 0); pcmPacketPool->destoryAudioPacketQueue(); if (NULL != audioEncoder) { audioEncoder->destroy(); delete audioEncoder; audioEncoder = NULL; } if(NULL != audioCodecName){ delete[] audioCodecName; audioCodecName = NULL; } if(NULL != packetBuffer){ delete packetBuffer; packetBuffer = NULL; } } int AudioEncoderAdapter::getAudioFrame(int16_t * samples, int frame_size, int nb_channels, double* presentationTimeMills) { int byteSize = frame_size * nb_channels * 2; int samplesInShortCursor = 0; while (true) { if (packetBufferSize == 0) { int ret = this->getAudioPacket(); if (ret < 0) { return ret; } } int copyToSamplesInShortSize = (byteSize - samplesInShortCursor * 2) / 2; if (packetBufferCursor + copyToSamplesInShortSize <= packetBufferSize) { this->cpyToSamples(samples, samplesInShortCursor, copyToSamplesInShortSize, presentationTimeMills); packetBufferCursor += copyToSamplesInShortSize; samplesInShortCursor = 0; break; } else { int subPacketBufferSize = packetBufferSize - packetBufferCursor; this->cpyToSamples(samples, samplesInShortCursor, subPacketBufferSize, presentationTimeMills); samplesInShortCursor += subPacketBufferSize; packetBufferSize = 0; continue; } } return frame_size * nb_channels; } int AudioEncoderAdapter::cpyToSamples(int16_t * samples, int samplesInShortCursor, int cpyPacketBufferSize, double* presentationTimeMills) { if(0 == samplesInShortCursor){ //第一次为samples拷贝进sample 这里要记录时间给sampleBuffer double packetBufferCursorDuration = (double)packetBufferCursor * 1000.0f / (double)(audioSampleRate * channelRatio); (*presentationTimeMills) = packetBufferPresentationTimeMills + packetBufferCursorDuration; } memcpy(samples + samplesInShortCursor, packetBuffer + packetBufferCursor, cpyPacketBufferSize * sizeof(short)); return 1; } void AudioEncoderAdapter::discardAudioPacket() { while(pcmPacketPool->detectDiscardAudioPacket()){ if(!pcmPacketPool->discardAudioPacket()){ break; } } } int AudioEncoderAdapter::getAudioPacket() { this->discardAudioPacket(); LiveAudioPacket *audioPacket = NULL; if (pcmPacketPool->getAudioPacket(&audioPacket, true) < 0) { return -1; } packetBufferCursor = 0; packetBufferPresentationTimeMills = audioPacket->position; /** * 在Android平台 录制是单声道的 经过音效处理之后是双声道 channelRatio 2 * 在iOS平台 录制的是双声道的 是已经处理音效过后的 channelRatio 1 */ packetBufferSize = audioPacket->size * channelRatio; if (NULL == packetBuffer) { packetBuffer = new short[packetBufferSize]; } memcpy(packetBuffer, audioPacket->buffer, audioPacket->size * sizeof(short)); int actualSize = this->processAudio(); if (actualSize > 0 && actualSize < packetBufferSize) { packetBufferCursor = packetBufferSize - actualSize; memmove(packetBuffer + packetBufferCursor, packetBuffer, actualSize * sizeof(short)); } if (NULL != audioPacket) { delete audioPacket; audioPacket = NULL; } return actualSize > 0 ? 1 : -1; }
// // debug.hpp // // Created by OTAKE Takayoshi on 2017/08/19. // Copyright © 2017 OTAKE Takayoshi. All rights reserved. // #pragma once // [C++14] #include <chrono> #include <cstdio> #include <cstdarg> #include <string> #include <iomanip> namespace bb { inline std::string make_log_message(char const* format, ...) { auto time_point = std::chrono::system_clock::now(); auto time = std::chrono::system_clock::to_time_t(time_point); auto time_usec = std::chrono::duration_cast<std::chrono::microseconds>(time_point - std::chrono::time_point_cast<std::chrono::seconds>(time_point)).count(); char buf[1024]; va_list arg; va_start(arg, format); vsnprintf(buf, sizeof(buf), format, arg); va_end(arg); std::stringstream ss; ss << std::put_time(std::localtime(&time), "%F %T.") << std::setw(6) << std::setfill('0') << time_usec << " " << buf; return ss.str(); } #ifdef DEBUG inline std::string make_trace_message(char const* file, int line, char const* format, ...) { char buf[1024]; va_list arg; va_start(arg, format); int pos = vsnprintf(buf, sizeof(buf), format, arg); snprintf(&buf[pos], sizeof(buf) - pos, "\n at %s:%d", file, line); va_end(arg); return buf; } #else inline std::string make_trace_message(char const* format, ...) { char buf[1024]; va_list arg; va_start(arg, format); vsnprintf(buf, sizeof(buf), format, arg); va_end(arg); return buf; } #endif } #ifdef DEBUG #define bb_trace_message(format, ...) [&](){\ return bb::make_trace_message(__FILE__, __LINE__, format, ##__VA_ARGS__);\ }() #else #define bb_trace_message(format, ...) [&](){\ return bb::make_trace_message(format, ##__VA_ARGS__);\ }() #endif
#include <cl_banque_spectres.h> #include <vector> #include <utility> #include <iostream> #include <fstream> bool salib::banque_spectres::sauvegarder_collection_spectres( const std::string &url_collection) { std::ofstream ecriture_fichier; ecriture_fichier.open(url_collection, std::ios::out); if (!ecriture_fichier.is_open()) return false; ecriture_fichier << "nom_collection = " << url_collection.c_str << std::endl; ecriture_fichier << "nombre_spectres = " << collection_spectres.size() << std::endl; ecriture_fichier << std::endl; // Ecriture des spectres for (std::size_t i_spectre = 0; i_spectre < collection_spectres.size(); i_spectre++) { ecriture_fichier << "indice_spectre = " << i_spectre << std::endl; ecriture_fichier << std::endl; // Ecriture des amplitudes ecriture_fichier << "amplitudes = " << std::endl; for (std::size_t i_partiel = 0; i_partiel < collection_spectres[i_spectre].partiels.size(); i_partiel++) { ecriture_fichier << collection_spectres[i_spectre].partiels[i_partiel].first << std::endl; } ecriture_fichier << std::endl; // Ecriture des fréquences ecriture_fichier << "frequences = " << std::endl; for (std::size_t i_partiel = 0; i_partiel < collection_spectres[i_spectre].partiels.size(); i_partiel++) { ecriture_fichier << collection_spectres[i_spectre].partiels[i_partiel].second << std::endl; } ecriture_fichier << std::endl; // Ecriture des caractéristiques ecriture_fichier << "puissance = " << collection_spectres[i_spectre].puissance << std::endl; ecriture_fichier << "dispersion = " << collection_spectres[i_spectre].dispersion << std::endl; ecriture_fichier << std::endl; } ecriture_fichier.close(); return true; }
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2018 The Circle Foundation // Copyright (c) 2019 Aluisyo // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "CommandLine.h" namespace command_line { const arg_descriptor<bool> arg_help = {"help", "Produce help message"}; const arg_descriptor<bool> arg_version = {"version", "Output version information"}; const arg_descriptor<std::string> arg_data_dir = {"data-dir", "Specify data directory"}; }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/rds/model/UpgradeTarget.h> #include <aws/core/utils/xml/XmlSerializer.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::Utils::Xml; using namespace Aws::Utils; namespace Aws { namespace RDS { namespace Model { UpgradeTarget::UpgradeTarget() : m_engineHasBeenSet(false), m_engineVersionHasBeenSet(false), m_descriptionHasBeenSet(false), m_autoUpgrade(false), m_autoUpgradeHasBeenSet(false), m_isMajorVersionUpgrade(false), m_isMajorVersionUpgradeHasBeenSet(false), m_supportedEngineModesHasBeenSet(false), m_supportsParallelQuery(false), m_supportsParallelQueryHasBeenSet(false), m_supportsGlobalDatabases(false), m_supportsGlobalDatabasesHasBeenSet(false), m_supportsBabelfish(false), m_supportsBabelfishHasBeenSet(false) { } UpgradeTarget::UpgradeTarget(const XmlNode& xmlNode) : m_engineHasBeenSet(false), m_engineVersionHasBeenSet(false), m_descriptionHasBeenSet(false), m_autoUpgrade(false), m_autoUpgradeHasBeenSet(false), m_isMajorVersionUpgrade(false), m_isMajorVersionUpgradeHasBeenSet(false), m_supportedEngineModesHasBeenSet(false), m_supportsParallelQuery(false), m_supportsParallelQueryHasBeenSet(false), m_supportsGlobalDatabases(false), m_supportsGlobalDatabasesHasBeenSet(false), m_supportsBabelfish(false), m_supportsBabelfishHasBeenSet(false) { *this = xmlNode; } UpgradeTarget& UpgradeTarget::operator =(const XmlNode& xmlNode) { XmlNode resultNode = xmlNode; if(!resultNode.IsNull()) { XmlNode engineNode = resultNode.FirstChild("Engine"); if(!engineNode.IsNull()) { m_engine = Aws::Utils::Xml::DecodeEscapedXmlText(engineNode.GetText()); m_engineHasBeenSet = true; } XmlNode engineVersionNode = resultNode.FirstChild("EngineVersion"); if(!engineVersionNode.IsNull()) { m_engineVersion = Aws::Utils::Xml::DecodeEscapedXmlText(engineVersionNode.GetText()); m_engineVersionHasBeenSet = true; } XmlNode descriptionNode = resultNode.FirstChild("Description"); if(!descriptionNode.IsNull()) { m_description = Aws::Utils::Xml::DecodeEscapedXmlText(descriptionNode.GetText()); m_descriptionHasBeenSet = true; } XmlNode autoUpgradeNode = resultNode.FirstChild("AutoUpgrade"); if(!autoUpgradeNode.IsNull()) { m_autoUpgrade = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(autoUpgradeNode.GetText()).c_str()).c_str()); m_autoUpgradeHasBeenSet = true; } XmlNode isMajorVersionUpgradeNode = resultNode.FirstChild("IsMajorVersionUpgrade"); if(!isMajorVersionUpgradeNode.IsNull()) { m_isMajorVersionUpgrade = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(isMajorVersionUpgradeNode.GetText()).c_str()).c_str()); m_isMajorVersionUpgradeHasBeenSet = true; } XmlNode supportedEngineModesNode = resultNode.FirstChild("SupportedEngineModes"); if(!supportedEngineModesNode.IsNull()) { XmlNode supportedEngineModesMember = supportedEngineModesNode.FirstChild("member"); while(!supportedEngineModesMember.IsNull()) { m_supportedEngineModes.push_back(supportedEngineModesMember.GetText()); supportedEngineModesMember = supportedEngineModesMember.NextNode("member"); } m_supportedEngineModesHasBeenSet = true; } XmlNode supportsParallelQueryNode = resultNode.FirstChild("SupportsParallelQuery"); if(!supportsParallelQueryNode.IsNull()) { m_supportsParallelQuery = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(supportsParallelQueryNode.GetText()).c_str()).c_str()); m_supportsParallelQueryHasBeenSet = true; } XmlNode supportsGlobalDatabasesNode = resultNode.FirstChild("SupportsGlobalDatabases"); if(!supportsGlobalDatabasesNode.IsNull()) { m_supportsGlobalDatabases = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(supportsGlobalDatabasesNode.GetText()).c_str()).c_str()); m_supportsGlobalDatabasesHasBeenSet = true; } XmlNode supportsBabelfishNode = resultNode.FirstChild("SupportsBabelfish"); if(!supportsBabelfishNode.IsNull()) { m_supportsBabelfish = StringUtils::ConvertToBool(StringUtils::Trim(Aws::Utils::Xml::DecodeEscapedXmlText(supportsBabelfishNode.GetText()).c_str()).c_str()); m_supportsBabelfishHasBeenSet = true; } } return *this; } void UpgradeTarget::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const { if(m_engineHasBeenSet) { oStream << location << index << locationValue << ".Engine=" << StringUtils::URLEncode(m_engine.c_str()) << "&"; } if(m_engineVersionHasBeenSet) { oStream << location << index << locationValue << ".EngineVersion=" << StringUtils::URLEncode(m_engineVersion.c_str()) << "&"; } if(m_descriptionHasBeenSet) { oStream << location << index << locationValue << ".Description=" << StringUtils::URLEncode(m_description.c_str()) << "&"; } if(m_autoUpgradeHasBeenSet) { oStream << location << index << locationValue << ".AutoUpgrade=" << std::boolalpha << m_autoUpgrade << "&"; } if(m_isMajorVersionUpgradeHasBeenSet) { oStream << location << index << locationValue << ".IsMajorVersionUpgrade=" << std::boolalpha << m_isMajorVersionUpgrade << "&"; } if(m_supportedEngineModesHasBeenSet) { unsigned supportedEngineModesIdx = 1; for(auto& item : m_supportedEngineModes) { oStream << location << index << locationValue << ".SupportedEngineModes.member." << supportedEngineModesIdx++ << "=" << StringUtils::URLEncode(item.c_str()) << "&"; } } if(m_supportsParallelQueryHasBeenSet) { oStream << location << index << locationValue << ".SupportsParallelQuery=" << std::boolalpha << m_supportsParallelQuery << "&"; } if(m_supportsGlobalDatabasesHasBeenSet) { oStream << location << index << locationValue << ".SupportsGlobalDatabases=" << std::boolalpha << m_supportsGlobalDatabases << "&"; } if(m_supportsBabelfishHasBeenSet) { oStream << location << index << locationValue << ".SupportsBabelfish=" << std::boolalpha << m_supportsBabelfish << "&"; } } void UpgradeTarget::OutputToStream(Aws::OStream& oStream, const char* location) const { if(m_engineHasBeenSet) { oStream << location << ".Engine=" << StringUtils::URLEncode(m_engine.c_str()) << "&"; } if(m_engineVersionHasBeenSet) { oStream << location << ".EngineVersion=" << StringUtils::URLEncode(m_engineVersion.c_str()) << "&"; } if(m_descriptionHasBeenSet) { oStream << location << ".Description=" << StringUtils::URLEncode(m_description.c_str()) << "&"; } if(m_autoUpgradeHasBeenSet) { oStream << location << ".AutoUpgrade=" << std::boolalpha << m_autoUpgrade << "&"; } if(m_isMajorVersionUpgradeHasBeenSet) { oStream << location << ".IsMajorVersionUpgrade=" << std::boolalpha << m_isMajorVersionUpgrade << "&"; } if(m_supportedEngineModesHasBeenSet) { unsigned supportedEngineModesIdx = 1; for(auto& item : m_supportedEngineModes) { oStream << location << ".SupportedEngineModes.member." << supportedEngineModesIdx++ << "=" << StringUtils::URLEncode(item.c_str()) << "&"; } } if(m_supportsParallelQueryHasBeenSet) { oStream << location << ".SupportsParallelQuery=" << std::boolalpha << m_supportsParallelQuery << "&"; } if(m_supportsGlobalDatabasesHasBeenSet) { oStream << location << ".SupportsGlobalDatabases=" << std::boolalpha << m_supportsGlobalDatabases << "&"; } if(m_supportsBabelfishHasBeenSet) { oStream << location << ".SupportsBabelfish=" << std::boolalpha << m_supportsBabelfish << "&"; } } } // namespace Model } // namespace RDS } // namespace Aws
/* TextureAtlas.mm * WhirlyGlobeLib * * Created by Steve Gifford on 3/28/11. * Copyright 2011-2021 mousebird consulting * * 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. */ #import "TextureAtlas.h" #import "WhirlyGeometry.h" #import "GlobeMath.h" using namespace Eigen; using namespace WhirlyKit; // Set up the texture mapping matrix from the destination texture coords void SubTexture::setFromTex(const TexCoord &texOrg,const TexCoord &texDest) { trans = decltype(trans)::Identity(); trans.translate(texOrg); trans.scale(texDest - texOrg); } // Calculate a destination texture coordinate TexCoord SubTexture::processTexCoord(const TexCoord &inCoord) const { const Vector3f res = trans * Vector3f(inCoord.x(),inCoord.y(),1.0); return TexCoord(res.x(),res.y()); } // Calculate destination texture coords for a while group void SubTexture::processTexCoords(std::vector<TexCoord> &coords) const { for (auto &coord : coords) { const Vector3f res = trans * Vector3f(coord.x(),coord.y(),1.0f); coord.x() = res.x(); coord.y() = res.y(); } }
#include "EvHideShowSideBarWidget.h" #include "EvButton.h" #include "EvAppSettings.h" #include <QHBoxLayout> #include <QResizeEvent> EvHideShowSideBarWidget::EvHideShowSideBarWidget(QWidget *parent) : QWidget(parent) { m_minimizeButton = new EvButton(this); m_minimizeButton->setIcon(evIconsFactory->applicationIcon(EvIconsFactory::LeftShortArrow,EvIconsFactory::Light)); m_minimizeButton->setPaintMode(EvButton::IconOnly); m_minimizeButton->setRounded(true); m_minimizeButton->setBackgroundColor(QColor(0,0,0,0)); m_maximizeButton = new EvButton(this); m_maximizeButton->setIcon(evIconsFactory->applicationIcon(EvIconsFactory::RightShortArrow,EvIconsFactory::Light)); m_maximizeButton->setPaintMode(EvButton::IconOnly); m_maximizeButton->setRounded(true); m_maximizeButton->setBackgroundColor(QColor(0,0,0,0)); QHBoxLayout * layout =new QHBoxLayout(this); layout->setSpacing(3); layout->setContentsMargins(0,0,0,0); layout->setMargin(0); layout->addWidget(m_minimizeButton); layout->addWidget(m_maximizeButton); connect(m_minimizeButton,SIGNAL(clicked()),this,SIGNAL(minimizeRequest())); connect(m_maximizeButton,SIGNAL(clicked()),this,SIGNAL(maximizeRequest())); } bool EvHideShowSideBarWidget::maximizeAvailable() const { return m_maximizeButton->isVisible(); } bool EvHideShowSideBarWidget::minimizeAvailable() const { return m_minimizeButton->isVisible(); } void EvHideShowSideBarWidget::setMaximizeAvailable(bool arg) { m_maximizeButton->setVisible(arg); } void EvHideShowSideBarWidget::setMinimizeAvailable(bool arg) { m_minimizeButton->setVisible(arg); }
#ifndef TERMOX_TERMINAL_DETAIL_SCREEN_BUFFERS_HPP #define TERMOX_TERMINAL_DETAIL_SCREEN_BUFFERS_HPP #include <termox/terminal/detail/canvas.hpp> #include <termox/widget/area.hpp> namespace ox::detail { /// Holds the current and next screen buffers as Canvas objects. /** Provides merge and diff capabilities for the two buffers to determine what * has changed and what should be written to the screen. */ class Screen_buffers { public: Canvas current; Canvas next; public: /// Construct with both Canvas objects having Area \p a. Screen_buffers(ox::Area a); public: /// Resizes both current and next Canvas objects to \p a. void resize(ox::Area a); /// Return the current size of the screen buffers. [[nodiscard]] auto area() const -> Area; /// Merges the next Canvas into the current Canvas. /** This will copy every Glyph from next that differs with current into * current Canvas. */ void merge(); /// Merges the next Canvas into the current Canvas and returns the changes. /** This will copy every Glyph from next that differs with current into * current, and writes that change to the returned Canvas::Diff object. */ [[nodiscard]] auto merge_and_diff() -> Canvas::Diff const&; /// Generates a Canvas::Diff, with every Glyph from current that has \p c. /** This isn't a true difference, it is meant to be used to generate a list * of Glyphs that need to be re-written to the screen. Used by * Dynamic_color_engine. */ [[nodiscard]] auto generate_color_diff(Color c) -> Canvas::Diff const&; /// Returns the entire current screen as a Diff. Used on Window Resize. [[nodiscard]] auto current_screen_as_diff() -> Canvas::Diff const&; private: Canvas::Diff diff_; }; } // namespace ox::detail #endif // TERMOX_TERMINAL_DETAIL_SCREEN_BUFFERS_HPP
// no-networkit-format /* * KPathCentrality.h * * Created on: 05.10.2014 * Author: nemes */ #ifndef NETWORKIT_CENTRALITY_K_PATH_CENTRALITY_HPP_ #define NETWORKIT_CENTRALITY_K_PATH_CENTRALITY_HPP_ #include <networkit/centrality/Centrality.hpp> namespace NetworKit { /** * @ingroup centrality */ class KPathCentrality: public Centrality { public: /* * the maximum length of paths * default value ln(n+m) */ count k; /* * value in interval [-0.5, 0.5] * tradeoff between runtime and precision * -0.5: maximum precision, maximum runtime * 0.5: lowest precision, lowest runtime * default value 0.2 */ double alpha; /** * Constructs the K-Path Centrality class for the given Graph @a G. * * @param G The graph. * @param alpha tradeoff between precision and runtime. * @param k maximum length of paths. * TODO running times */ KPathCentrality(const Graph& G, double alpha=0.2, count k=0); /** * Computes k-path centrality on the graph passed in constructor. */ void run() override; }; } /* namespace NetworKit */ #endif // NETWORKIT_CENTRALITY_K_PATH_CENTRALITY_HPP_
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/secretsmanager/model/DescribeSecretResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::SecretsManager::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; DescribeSecretResult::DescribeSecretResult() : m_rotationEnabled(false) { } DescribeSecretResult::DescribeSecretResult(const Aws::AmazonWebServiceResult<JsonValue>& result) : m_rotationEnabled(false) { *this = result; } DescribeSecretResult& DescribeSecretResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("ARN")) { m_aRN = jsonValue.GetString("ARN"); } if(jsonValue.ValueExists("Name")) { m_name = jsonValue.GetString("Name"); } if(jsonValue.ValueExists("Description")) { m_description = jsonValue.GetString("Description"); } if(jsonValue.ValueExists("KmsKeyId")) { m_kmsKeyId = jsonValue.GetString("KmsKeyId"); } if(jsonValue.ValueExists("RotationEnabled")) { m_rotationEnabled = jsonValue.GetBool("RotationEnabled"); } if(jsonValue.ValueExists("RotationLambdaARN")) { m_rotationLambdaARN = jsonValue.GetString("RotationLambdaARN"); } if(jsonValue.ValueExists("RotationRules")) { m_rotationRules = jsonValue.GetObject("RotationRules"); } if(jsonValue.ValueExists("LastRotatedDate")) { m_lastRotatedDate = jsonValue.GetDouble("LastRotatedDate"); } if(jsonValue.ValueExists("LastChangedDate")) { m_lastChangedDate = jsonValue.GetDouble("LastChangedDate"); } if(jsonValue.ValueExists("LastAccessedDate")) { m_lastAccessedDate = jsonValue.GetDouble("LastAccessedDate"); } if(jsonValue.ValueExists("DeletedDate")) { m_deletedDate = jsonValue.GetDouble("DeletedDate"); } if(jsonValue.ValueExists("Tags")) { Array<JsonView> tagsJsonList = jsonValue.GetArray("Tags"); for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) { m_tags.push_back(tagsJsonList[tagsIndex].AsObject()); } } if(jsonValue.ValueExists("VersionIdsToStages")) { Aws::Map<Aws::String, JsonView> versionIdsToStagesJsonMap = jsonValue.GetObject("VersionIdsToStages").GetAllObjects(); for(auto& versionIdsToStagesItem : versionIdsToStagesJsonMap) { Array<JsonView> secretVersionStagesTypeJsonList = versionIdsToStagesItem.second.AsArray(); Aws::Vector<Aws::String> secretVersionStagesTypeList; secretVersionStagesTypeList.reserve((size_t)secretVersionStagesTypeJsonList.GetLength()); for(unsigned secretVersionStagesTypeIndex = 0; secretVersionStagesTypeIndex < secretVersionStagesTypeJsonList.GetLength(); ++secretVersionStagesTypeIndex) { secretVersionStagesTypeList.push_back(secretVersionStagesTypeJsonList[secretVersionStagesTypeIndex].AsString()); } m_versionIdsToStages[versionIdsToStagesItem.first] = std::move(secretVersionStagesTypeList); } } if(jsonValue.ValueExists("OwningService")) { m_owningService = jsonValue.GetString("OwningService"); } return *this; }
#pragma once enum class PropertyUnit { CELSIUS, FAHRENHEIT, DEGREE, LITER, GALON, VOLTS, WATT, AMPERE, PERCENT, METER, FEET, PASCAL, PSI, COUNT, NONE }; enum class PropertyDataType { INTEGER, FLOAT, BOOLEAN, STRING, ENUM, COLOR }; class HomieNodeProperty { public: HomieNodeProperty(const char* name, const bool _settable, const bool _retained, const PropertyUnit _unit, const PropertyDataType _dataType, const char* _format); ~HomieNodeProperty(); const char* getName(); const bool isSettable(); const bool isRetained(); const char* getUnit(); const char* getDataType(); const char* getFormat(); private: const char* name; const bool settable; const bool retained; const PropertyUnit unit; const PropertyDataType dataType; const char* format; };
// Copyright (c) 2009-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "uritests.h" #include "guiutil.h" #include "walletmodel.h" #include <QUrl> void URITests::uriTests() { SendCoinsRecipient rv; QUrl uri; uri.setUrl(QString("jinxiangcoin:LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2?req-dontexist=")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("jinxiangcoin:LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2?dontexist=")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 0); uri.setUrl(QString("jinxiangcoin:LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2?label=Wikipedia Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2")); QVERIFY(rv.label == QString("Wikipedia Example Address")); QVERIFY(rv.amount == 0); uri.setUrl(QString("jinxiangcoin:LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2?amount=0.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100000); uri.setUrl(QString("jinxiangcoin:LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2?amount=1.001")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2")); QVERIFY(rv.label == QString()); QVERIFY(rv.amount == 100100000); uri.setUrl(QString("jinxiangcoin:LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2?amount=100&label=Wikipedia Example")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2")); QVERIFY(rv.amount == 10000000000LL); QVERIFY(rv.label == QString("Wikipedia Example")); uri.setUrl(QString("jinxiangcoin:LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2?message=Wikipedia Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); QVERIFY(rv.address == QString("LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2")); QVERIFY(rv.label == QString()); QVERIFY(GUIUtil::parseBitcoinURI("jinxiangcoin://LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2?message=Wikipedia Example Address", &rv)); QVERIFY(rv.address == QString("LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2")); QVERIFY(rv.label == QString()); uri.setUrl(QString("jinxiangcoin:LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2?req-message=Wikipedia Example Address")); QVERIFY(GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("jinxiangcoin:LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2?amount=1,000&label=Wikipedia Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); uri.setUrl(QString("jinxiangcoin:LEr4HnaeFWYhBmGxCfP2po1NPRueIk8kM2?amount=1,000.0&label=Wikipedia Example")); QVERIFY(!GUIUtil::parseBitcoinURI(uri, &rv)); }
/******************************************************************************* * Copyright 2019-2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "cpu/x64/jit_generator.hpp" #include "cpu/x64/gemm/f32/common_f32.hpp" namespace dnnl { namespace impl { namespace cpu { namespace x64 { jit_avx_f32_copy_bn_kern::jit_avx_f32_copy_bn_kern() : jit_generator(nullptr, F32_COPY_KERNEL_CODE_SIZE) {} void jit_avx_f32_copy_bn_kern::generate() { #ifndef _WIN32 #define M rdi #define N rsi #define A rdx #define LDA rcx #define ALPHA r8 #define B r9 #define I rax #define A1 r10 #define A2 r8 #define LDA3 r11 #else #define M rcx #define N rdx #define A r8 #define LDA r9 #define ALPHA rsi #define B rdi #define I rax #define A1 r10 #define A2 rsi #define LDA3 r11 #define ARG_ALPHA 40 + stacksize + rsp #define ARG_B 48 + stacksize + rsp #endif inLocalLabel(); { Xbyak::Label l118; Xbyak::Label l15c; Xbyak::Label l16c; Xbyak::Label l18c; Xbyak::Label l1cc; Xbyak::Label l200; Xbyak::Label l230; Xbyak::Label l234; Xbyak::Label l254; Xbyak::Label l294; Xbyak::Label l2c4; Xbyak::Label l2e8; Xbyak::Label l2ec; Xbyak::Label l2f4; Xbyak::Label l310; Xbyak::Label l328; Xbyak::Label l398; Xbyak::Label l3ec; Xbyak::Label l434; Xbyak::Label l444; Xbyak::Label l464; Xbyak::Label l4ac; Xbyak::Label l4e4; Xbyak::Label l518; Xbyak::Label l51c; Xbyak::Label l53c; Xbyak::Label l54; Xbyak::Label l580; Xbyak::Label l5b4; Xbyak::Label l5dc; Xbyak::Label l5e0; Xbyak::Label l5e8; Xbyak::Label l5f4; Xbyak::Label l60c; Xbyak::Label l67c; Xbyak::Label l6c; Xbyak::Label l6d0; Xbyak::Label l718; Xbyak::Label l728; Xbyak::Label l748; Xbyak::Label l790; Xbyak::Label l7c8; Xbyak::Label l7fc; Xbyak::Label l800; Xbyak::Label l820; Xbyak::Label l864; Xbyak::Label l898; Xbyak::Label l8c0; Xbyak::Label l8c4; Xbyak::Label lcc; preamble(); #ifdef _WIN32 auto stacksize = get_size_of_abi_save_regs(); mov(ALPHA, ptr[ARG_ALPHA]); mov(B, ptr[ARG_B]); #endif mov(M, qword[M]); mov(N, qword[N]); mov(LDA, qword[LDA]); sub(A, 0x0); sub(B, -128); shl(LDA, 0x2); lea(LDA3, ptr[LDA + LDA * 2]); vbroadcastss(ymm6, dword[ALPHA]); vpcmpeqb(xmm3, xmm3, xmm3); vpsrld(xmm3, xmm3, 0x17); vpslld(xmm3, xmm3, 0x19); vpsrld(xmm3, xmm3, 0x2); vpcmpeqb(xmm4, xmm4, xmm4); vpslld(xmm4, xmm4, 0x1f); vperm2f128(ymm4, ymm4, ymm4, 0x20); vucomiss(xmm6, xmm3); jne(l2f4, T_NEAR); cmp(N, 0x4); jl(l16c, T_NEAR); align(4); L(l54); mov(A1, A); mov(I, LDA); imul(I, I, 0x4); add(A, I); mov(I, M); sar(I, 0x2); jle(lcc, T_NEAR); align(4); L(l6c); vmovups(xmm0, xword[A1]); vmovups(xmm1, xword[A1 + LDA * 1]); vmovups(xmm2, xword[A1 + LDA * 2]); vmovups(xmm3, xword[A1 + LDA3 * 1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm5, xmm0, xmm1); vunpcklps(xmm1, xmm2, xmm3); vunpckhps(xmm3, xmm2, xmm3); vunpcklpd(xmm0, xmm4, xmm1); vunpckhpd(xmm1, xmm4, xmm1); vunpcklpd(xmm2, xmm5, xmm3); vunpckhpd(xmm3, xmm5, xmm3); vmovups(xword[B - 0x80], xmm0); vmovups(xword[B - 0x70], xmm1); vmovups(xword[B - 0x60], xmm2); vmovups(xword[B - 0x50], xmm3); lea(A2, ptr[A1 + LDA * 4]); sub(A1, -16); sub(B, -64); dec(I); jg(l6c, T_NEAR); align(4); L(lcc); test(M, 0x2); jle(l118, T_NEAR); vmovsd(xmm0, qword[A1]); vmovsd(xmm1, qword[A1 + LDA * 1]); vmovhps(xmm0, xmm0, qword[A1 + LDA * 2]); vmovhps(xmm1, xmm1, qword[A1 + LDA3 * 1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm1, xmm0, xmm1); vunpcklpd(xmm0, xmm4, xmm1); vunpckhpd(xmm1, xmm4, xmm1); vmovups(xword[B - 0x80], xmm0); vmovups(xword[B - 0x70], xmm1); lea(A2, ptr[A1 + LDA * 4]); sub(A1, -8); sub(B, -32); align(4); L(l118); test(M, 0x1); jle(l15c, T_NEAR); vmovss(xmm0, dword[A1]); vmovss(xmm1, dword[A1 + LDA * 1]); vunpcklps(xmm0, xmm0, xmm1); vmovss(xmm2, dword[A1 + LDA * 2]); vmovss(xmm3, dword[A1 + LDA3 * 1]); vunpcklps(xmm2, xmm2, xmm3); vunpcklpd(xmm0, xmm0, xmm2); vmovups(xword[B - 0x80], xmm0); lea(A2, ptr[A1 + LDA * 4]); sub(A1, -4); sub(B, -16); align(4); L(l15c); sub(N, 0x4); cmp(N, 0x4); jge(l54, T_NEAR); align(4); L(l16c); cmp(N, 0x2); jl(l234, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x2); add(A, I); mov(I, M); sar(I, 0x2); jle(l1cc, T_NEAR); align(4); L(l18c); vmovups(xmm0, xword[A1]); vmovups(xmm1, xword[A1 + LDA * 1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm1, xmm0, xmm1); vmovaps(xmm0, xmm4); vmovlps(qword[B - 0x80], xmm0); vmovhps(qword[B - 0x78], xmm0); vmovlps(qword[B - 0x70], xmm1); vmovhps(qword[B - 0x68], xmm1); lea(A2, ptr[A1 + LDA * 2]); sub(A1, -16); sub(B, -32); dec(I); jg(l18c, T_NEAR); align(4); L(l1cc); test(M, 0x2); jle(l200, T_NEAR); vmovsd(xmm0, qword[A1]); vmovsd(xmm1, qword[A1 + LDA * 1]); vunpcklps(xmm0, xmm0, xmm1); vmovlps(qword[B - 0x80], xmm0); vmovhps(qword[B - 0x78], xmm0); lea(A2, ptr[A1 + LDA * 2]); sub(A1, -8); sub(B, -16); align(4); L(l200); test(M, 0x1); jle(l230, T_NEAR); vmovss(xmm0, dword[A1]); vmovss(xmm1, dword[A1 + LDA * 1]); vunpcklps(xmm0, xmm0, xmm1); vmovlps(qword[B - 0x80], xmm0); lea(A2, ptr[A1 + LDA * 2]); sub(A1, -4); sub(B, -8); align(4); L(l230); sub(N, 0x2); align(4); L(l234); cmp(N, 0x1); jl(l2ec, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x1); add(A, I); mov(I, M); sar(I, 0x2); jle(l294, T_NEAR); align(4); L(l254); vmovups(xmm0, xword[A1]); vpshufd(xmm1, xmm0, 0x55); vpshufd(xmm2, xmm0, 0xaa); vpshufd(xmm3, xmm0, 0xff); vmovss(dword[B - 0x80], xmm0); vmovss(dword[B - 0x7c], xmm1); vmovss(dword[B - 0x78], xmm2); vmovss(dword[B - 0x74], xmm3); lea(A2, ptr[A1 + LDA * 1]); sub(A1, -16); sub(B, -16); dec(I); jg(l254, T_NEAR); align(4); L(l294); test(M, 0x2); jle(l2c4, T_NEAR); vmovsd(xmm0, qword[A1]); vpshufd(xmm1, xmm0, 0x55); vmovss(dword[B - 0x80], xmm0); vmovss(dword[B - 0x7c], xmm1); lea(A2, ptr[A1 + LDA * 1]); sub(A1, -8); sub(B, -8); align(4); L(l2c4); test(M, 0x1); jle(l2e8, T_NEAR); vmovss(xmm0, dword[A1]); vmovss(dword[B - 0x80], xmm0); lea(A2, ptr[A1 + LDA * 1]); sub(A1, -4); sub(B, -4); align(4); L(l2e8); sub(N, 0x1); align(4); L(l2ec); jmp(l8c4, T_NEAR); align(4); L(l2f4); vxorps(xmm3, xmm3, xmm4); vucomiss(xmm6, xmm3); jne(l5e8, T_NEAR); vmovaps(ymm6, ymm4); cmp(N, 0x4); jl(l444, T_NEAR); align(4); L(l310); mov(A1, A); mov(I, LDA); imul(I, I, 0x4); add(A, I); mov(I, M); sar(I, 0x2); jle(l398, T_NEAR); align(4); L(l328); vmovups(xmm0, xword[A1]); vmovups(xmm1, xword[A1 + LDA * 1]); vmovups(xmm2, xword[A1 + LDA * 2]); vmovups(xmm3, xword[A1 + LDA3 * 1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm5, xmm0, xmm1); vunpcklps(xmm1, xmm2, xmm3); vunpckhps(xmm3, xmm2, xmm3); vunpcklpd(xmm0, xmm4, xmm1); vunpckhpd(xmm1, xmm4, xmm1); vunpcklpd(xmm2, xmm5, xmm3); vunpckhpd(xmm3, xmm5, xmm3); vxorps(xmm0, xmm6, xmm0); vxorps(xmm1, xmm6, xmm1); vxorps(xmm2, xmm6, xmm2); vxorps(xmm3, xmm6, xmm3); vmovups(xword[B - 0x80], xmm0); vmovups(xword[B - 0x70], xmm1); vmovups(xword[B - 0x60], xmm2); vmovups(xword[B - 0x50], xmm3); lea(A2, ptr[A1 + LDA * 4]); sub(A1, -16); sub(B, -64); dec(I); jg(l328, T_NEAR); align(4); L(l398); test(M, 0x2); jle(l3ec, T_NEAR); vmovsd(xmm0, qword[A1]); vmovsd(xmm1, qword[A1 + LDA * 1]); vmovhps(xmm0, xmm0, qword[A1 + LDA * 2]); vmovhps(xmm1, xmm1, qword[A1 + LDA3 * 1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm1, xmm0, xmm1); vunpcklpd(xmm0, xmm4, xmm1); vunpckhpd(xmm1, xmm4, xmm1); vxorps(xmm0, xmm6, xmm0); vxorps(xmm1, xmm6, xmm1); vmovups(xword[B - 0x80], xmm0); vmovups(xword[B - 0x70], xmm1); lea(A2, ptr[A1 + LDA * 4]); sub(A1, -8); sub(B, -32); align(4); L(l3ec); test(M, 0x1); jle(l434, T_NEAR); vmovss(xmm0, dword[A1]); vmovss(xmm1, dword[A1 + LDA * 1]); vunpcklps(xmm0, xmm0, xmm1); vmovss(xmm2, dword[A1 + LDA * 2]); vmovss(xmm3, dword[A1 + LDA3 * 1]); vunpcklps(xmm2, xmm2, xmm3); vunpcklpd(xmm0, xmm0, xmm2); vxorps(xmm0, xmm6, xmm0); vmovups(xword[B - 0x80], xmm0); lea(A2, ptr[A1 + LDA * 4]); sub(A1, -4); sub(B, -16); align(4); L(l434); sub(N, 0x4); cmp(N, 0x4); jge(l310, T_NEAR); align(4); L(l444); cmp(N, 0x2); jl(l51c, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x2); add(A, I); mov(I, M); sar(I, 0x2); jle(l4ac, T_NEAR); align(4); L(l464); vmovups(xmm0, xword[A1]); vmovups(xmm1, xword[A1 + LDA * 1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm1, xmm0, xmm1); vmovaps(xmm0, xmm4); vxorps(xmm0, xmm6, xmm0); vxorps(xmm1, xmm6, xmm1); vmovlps(qword[B - 0x80], xmm0); vmovhps(qword[B - 0x78], xmm0); vmovlps(qword[B - 0x70], xmm1); vmovhps(qword[B - 0x68], xmm1); lea(A2, ptr[A1 + LDA * 2]); sub(A1, -16); sub(B, -32); dec(I); jg(l464, T_NEAR); align(4); L(l4ac); test(M, 0x2); jle(l4e4, T_NEAR); vmovsd(xmm0, qword[A1]); vmovsd(xmm1, qword[A1 + LDA * 1]); vunpcklps(xmm0, xmm0, xmm1); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B - 0x80], xmm0); vmovhps(qword[B - 0x78], xmm0); lea(A2, ptr[A1 + LDA * 2]); sub(A1, -8); sub(B, -16); align(4); L(l4e4); test(M, 0x1); jle(l518, T_NEAR); vmovss(xmm0, dword[A1]); vmovss(xmm1, dword[A1 + LDA * 1]); vunpcklps(xmm0, xmm0, xmm1); vxorps(xmm0, xmm6, xmm0); vmovlps(qword[B - 0x80], xmm0); lea(A2, ptr[A1 + LDA * 2]); sub(A1, -4); sub(B, -8); align(4); L(l518); sub(N, 0x2); align(4); L(l51c); cmp(N, 0x1); jl(l5e0, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x1); add(A, I); mov(I, M); sar(I, 0x2); jle(l580, T_NEAR); align(4); L(l53c); vmovups(xmm0, xword[A1]); vxorps(xmm0, xmm6, xmm0); vpshufd(xmm1, xmm0, 0x55); vpshufd(xmm2, xmm0, 0xaa); vpshufd(xmm3, xmm0, 0xff); vmovss(dword[B - 0x80], xmm0); vmovss(dword[B - 0x7c], xmm1); vmovss(dword[B - 0x78], xmm2); vmovss(dword[B - 0x74], xmm3); lea(A2, ptr[A1 + LDA * 1]); sub(A1, -16); sub(B, -16); dec(I); jg(l53c, T_NEAR); align(4); L(l580); test(M, 0x2); jle(l5b4, T_NEAR); vmovsd(xmm0, qword[A1]); vxorps(xmm0, xmm6, xmm0); vpshufd(xmm1, xmm0, 0x55); vmovss(dword[B - 0x80], xmm0); vmovss(dword[B - 0x7c], xmm1); lea(A2, ptr[A1 + LDA * 1]); sub(A1, -8); sub(B, -8); align(4); L(l5b4); test(M, 0x1); jle(l5dc, T_NEAR); vmovss(xmm0, dword[A1]); vxorps(xmm0, xmm6, xmm0); vmovss(dword[B - 0x80], xmm0); lea(A2, ptr[A1 + LDA * 1]); sub(A1, -4); sub(B, -4); align(4); L(l5dc); sub(N, 0x1); align(4); L(l5e0); jmp(l8c4, T_NEAR); align(4); L(l5e8); cmp(N, 0x4); jl(l728, T_NEAR); align(4); L(l5f4); mov(A1, A); mov(I, LDA); imul(I, I, 0x4); add(A, I); mov(I, M); sar(I, 0x2); jle(l67c, T_NEAR); align(4); L(l60c); vmovups(xmm0, xword[A1]); vmovups(xmm1, xword[A1 + LDA * 1]); vmovups(xmm2, xword[A1 + LDA * 2]); vmovups(xmm3, xword[A1 + LDA3 * 1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm5, xmm0, xmm1); vunpcklps(xmm1, xmm2, xmm3); vunpckhps(xmm3, xmm2, xmm3); vunpcklpd(xmm0, xmm4, xmm1); vunpckhpd(xmm1, xmm4, xmm1); vunpcklpd(xmm2, xmm5, xmm3); vunpckhpd(xmm3, xmm5, xmm3); vmulps(xmm0, xmm6, xmm0); vmulps(xmm1, xmm6, xmm1); vmulps(xmm2, xmm6, xmm2); vmulps(xmm3, xmm6, xmm3); vmovups(xword[B - 0x80], xmm0); vmovups(xword[B - 0x70], xmm1); vmovups(xword[B - 0x60], xmm2); vmovups(xword[B - 0x50], xmm3); lea(A2, ptr[A1 + LDA * 4]); sub(A1, -16); sub(B, -64); dec(I); jg(l60c, T_NEAR); align(4); L(l67c); test(M, 0x2); jle(l6d0, T_NEAR); vmovsd(xmm0, qword[A1]); vmovsd(xmm1, qword[A1 + LDA * 1]); vmovhps(xmm0, xmm0, qword[A1 + LDA * 2]); vmovhps(xmm1, xmm1, qword[A1 + LDA3 * 1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm1, xmm0, xmm1); vunpcklpd(xmm0, xmm4, xmm1); vunpckhpd(xmm1, xmm4, xmm1); vmulps(xmm0, xmm6, xmm0); vmulps(xmm1, xmm6, xmm1); vmovups(xword[B - 0x80], xmm0); vmovups(xword[B - 0x70], xmm1); lea(A2, ptr[A1 + LDA * 4]); sub(A1, -8); sub(B, -32); align(4); L(l6d0); test(M, 0x1); jle(l718, T_NEAR); vmovss(xmm0, dword[A1]); vmovss(xmm1, dword[A1 + LDA * 1]); vunpcklps(xmm0, xmm0, xmm1); vmovss(xmm2, dword[A1 + LDA * 2]); vmovss(xmm3, dword[A1 + LDA3 * 1]); vunpcklps(xmm2, xmm2, xmm3); vunpcklpd(xmm0, xmm0, xmm2); vmulps(xmm0, xmm6, xmm0); vmovups(xword[B - 0x80], xmm0); lea(A2, ptr[A1 + LDA * 4]); sub(A1, -4); sub(B, -16); align(4); L(l718); sub(N, 0x4); cmp(N, 0x4); jge(l5f4, T_NEAR); align(4); L(l728); cmp(N, 0x2); jl(l800, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x2); add(A, I); mov(I, M); sar(I, 0x2); jle(l790, T_NEAR); align(4); L(l748); vmovups(xmm0, xword[A1]); vmovups(xmm1, xword[A1 + LDA * 1]); vunpcklps(xmm4, xmm0, xmm1); vunpckhps(xmm1, xmm0, xmm1); vmovaps(xmm0, xmm4); vmulps(xmm0, xmm6, xmm0); vmulps(xmm1, xmm6, xmm1); vmovlps(qword[B - 0x80], xmm0); vmovhps(qword[B - 0x78], xmm0); vmovlps(qword[B - 0x70], xmm1); vmovhps(qword[B - 0x68], xmm1); lea(A2, ptr[A1 + LDA * 2]); sub(A1, -16); sub(B, -32); dec(I); jg(l748, T_NEAR); align(4); L(l790); test(M, 0x2); jle(l7c8, T_NEAR); vmovsd(xmm0, qword[A1]); vmovsd(xmm1, qword[A1 + LDA * 1]); vunpcklps(xmm0, xmm0, xmm1); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B - 0x80], xmm0); vmovhps(qword[B - 0x78], xmm0); lea(A2, ptr[A1 + LDA * 2]); sub(A1, -8); sub(B, -16); align(4); L(l7c8); test(M, 0x1); jle(l7fc, T_NEAR); vmovss(xmm0, dword[A1]); vmovss(xmm1, dword[A1 + LDA * 1]); vunpcklps(xmm0, xmm0, xmm1); vmulps(xmm0, xmm6, xmm0); vmovlps(qword[B - 0x80], xmm0); lea(A2, ptr[A1 + LDA * 2]); sub(A1, -4); sub(B, -8); align(4); L(l7fc); sub(N, 0x2); align(4); L(l800); cmp(N, 0x1); jl(l8c4, T_NEAR); mov(A1, A); mov(I, LDA); imul(I, I, 0x1); add(A, I); mov(I, M); sar(I, 0x2); jle(l864, T_NEAR); align(4); L(l820); vmovups(xmm0, xword[A1]); vmulps(xmm0, xmm6, xmm0); vpshufd(xmm1, xmm0, 0x55); vpshufd(xmm2, xmm0, 0xaa); vpshufd(xmm3, xmm0, 0xff); vmovss(dword[B - 0x80], xmm0); vmovss(dword[B - 0x7c], xmm1); vmovss(dword[B - 0x78], xmm2); vmovss(dword[B - 0x74], xmm3); lea(A2, ptr[A1 + LDA * 1]); sub(A1, -16); sub(B, -16); dec(I); jg(l820, T_NEAR); align(4); L(l864); test(M, 0x2); jle(l898, T_NEAR); vmovsd(xmm0, qword[A1]); vmulps(xmm0, xmm6, xmm0); vpshufd(xmm1, xmm0, 0x55); vmovss(dword[B - 0x80], xmm0); vmovss(dword[B - 0x7c], xmm1); lea(A2, ptr[A1 + LDA * 1]); sub(A1, -8); sub(B, -8); align(4); L(l898); test(M, 0x1); jle(l8c0, T_NEAR); vmovss(xmm0, dword[A1]); vmulps(xmm0, xmm6, xmm0); vmovss(dword[B - 0x80], xmm0); lea(A2, ptr[A1 + LDA * 1]); sub(A1, -4); sub(B, -4); align(4); L(l8c0); sub(N, 0x1); align(4); L(l8c4); postamble(); } outLocalLabel(); #undef M #undef N #undef A #undef LDA #undef ALPHA #undef B #undef I #undef A1 #undef A2 #undef LDA3 #ifdef _WIN32 #undef ARG_ALPHA #undef ARG_B #endif } } // namespace x64 } // namespace cpu } // namespace impl } // namespace dnnl
#include "interface.h" #include "uart.h" #include "config.h" using openxc::config::getConfiguration; static const char interfaceNames[][5] = { "USB", "UART", "NET", }; const char* openxc::interface::descriptorToString(InterfaceDescriptor* descriptor) { if(descriptor->type < sizeof(interfaceNames) / sizeof(interfaceNames[0])) { return interfaceNames[descriptor->type]; } return "Unknown"; } bool openxc::interface::anyConnected() { return openxc::interface::uart::connected(&getConfiguration()->uart) || openxc::interface::usb::connected(&getConfiguration()->usb) || openxc::interface::network::connected(&getConfiguration()->network); }
#include "stone/Driver/Job.h" using namespace stone; using namespace stone::driver; Job::~Job() {} void Job::Print(llvm::raw_ostream &os, const char *terminator, bool quote, CrashCondition *crash) const {} int Job::AsyncExecute(llvm::ArrayRef<llvm::Optional<llvm::StringRef>> redirects, std::string *errMsg, bool *failed) const { return 0; } int Job::SyncExecute(llvm::ArrayRef<llvm::Optional<llvm::StringRef>> redirects, std::string *errMsg, bool *failed) const { return 0; }
#include <iostream> using namespace std; class your; class My { private: int a; protected: int b; public: int c; friend your; }; class your { public: My m; void fun() { m.a = 15; m.b = 20; m.c = 13; } }; int main() { return 0; }
/* Copyright (c) 2007-2009 The Regents of the University of California. All rights reserved. Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following two paragraphs appear in all copies of this software. IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. PT_COPYRIGHT_VERSION_2 COPYRIGHTENDKEY */ #ifndef _NO_SYSTEMC_ #include "systemc.h" #endif #include "core.h" /* This include file is automatically generated when running make regression. This is a hack to get the PRET_ISS path for the following files that are used below. */ #include "regression.h" #ifndef _NO_SYSTEMC_ int sc_main(int argc, char *argv[]) #else int main(int argc, char *argv[]) #endif { #ifdef _NO_SYSTEMC_ cout << "SystemC Simulation" << endl; #else sc_report_handler::set_actions("/IEEE_Std_1666/deprecated", SC_DO_NOTHING); #endif /* Setup the strings for filenames file_name : This is the file that has the location of the tests. */ string file_name = "/tests/tests/pret/sys/binsearch/binsearch.txt"; string otxt_name = "rbinsearch.txt"; string txt_name; string load_file; /* Ensure that the include/regression.h set the PRET_ISS path correctly */ if (pret_iss_path != "") { txt_name = pret_iss_path + file_name; ifstream txt(txt_name.c_str()); ofstream otxt(otxt_name.c_str()); if (txt.is_open()) { string line; getline(txt, line); if (line.size() > 0) { if (line.at(0) == '.') { line.erase(line.begin()); } load_file = pret_iss_path + "/tests/tests/pret/sys/binsearch" + line; otxt << load_file << endl; } otxt.close(); } /* Generate the SREC files*/ string compile_srec = pret_iss_path + "/scripts/compile_threads.py " + load_file.c_str() + " -q"; compile_srec = compile_srec + " 2>/dev/null";//cout << "compile command: " << compile_srec << endl; int failed = system(compile_srec.c_str()); if (failed) { cout << "Error: system() failed." << endl; } core db(otxt_name.c_str()); db.run(3000000); } else { cout << "Error: regression.h has not set the pret_iss_path string correctly" << endl; } return(0); }
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Timer.h" #include "PictureBenchmark.h" #include "SkCanvas.h" #include "SkPicture.h" #include "SkString.h" #include "picture_utils.h" namespace sk_tools { PictureBenchmark::PictureBenchmark() : fRepeats(1) , fRenderer(NULL) , fTimerResult(TimerData::kAvg_Result) , fTimerTypes(0) , fTimeIndividualTiles(false) , fPurgeDecodedTex(false) , fWriter(NULL) { } PictureBenchmark::~PictureBenchmark() { SkSafeUnref(fRenderer); } void PictureBenchmark::setTimersToShow(bool wall, bool truncatedWall, bool cpu, bool truncatedCpu, bool gpu) { fTimerTypes = 0; fTimerTypes |= wall ? TimerData::kWall_Flag : 0; fTimerTypes |= truncatedWall ? TimerData::kTruncatedWall_Flag : 0; fTimerTypes |= cpu ? TimerData::kCpu_Flag : 0; fTimerTypes |= truncatedCpu ? TimerData::kTruncatedCpu_Flag : 0; fTimerTypes |= gpu ? TimerData::kGpu_Flag : 0; } Timer* PictureBenchmark::setupTimer(bool useGLTimer) { #if SK_SUPPORT_GPU if (useGLTimer && fRenderer != NULL && fRenderer->isUsingGpuDevice()) { return SkNEW_ARGS(Timer, (fRenderer->getGLContext())); } #endif return SkNEW_ARGS(Timer, (NULL)); } PictureRenderer* PictureBenchmark::setRenderer(sk_tools::PictureRenderer* renderer) { SkRefCnt_SafeAssign(fRenderer, renderer); return renderer; } void PictureBenchmark::run(SkPicture* pict, bool useMultiPictureDraw) { SkASSERT(pict); if (NULL == pict) { return; } SkASSERT(fRenderer != NULL); if (NULL == fRenderer) { return; } fRenderer->init(pict, NULL, NULL, NULL, false, useMultiPictureDraw); // We throw this away to remove first time effects (such as paging in this program) fRenderer->setup(); fRenderer->render(NULL); fRenderer->resetState(true); // flush, swapBuffers and Finish if (fPurgeDecodedTex) { fRenderer->purgeTextures(); } bool usingGpu = false; #if SK_SUPPORT_GPU usingGpu = fRenderer->isUsingGpuDevice(); #endif uint32_t timerTypes = fTimerTypes; if (!usingGpu) { timerTypes &= ~TimerData::kGpu_Flag; } SkString timeFormat; if (TimerData::kPerIter_Result == fTimerResult) { timeFormat = fRenderer->getPerIterTimeFormat(); } else { timeFormat = fRenderer->getNormalTimeFormat(); } static const int kNumInnerLoops = 10; int numOuterLoops = 1; int numInnerLoops = fRepeats; if (TimerData::kPerIter_Result == fTimerResult && fRepeats > 1) { // interpret this flag combination to mean: generate 'fRepeats' // numbers by averaging each rendering 'kNumInnerLoops' times numOuterLoops = fRepeats; numInnerLoops = kNumInnerLoops; } if (fTimeIndividualTiles) { TiledPictureRenderer* tiledRenderer = fRenderer->getTiledRenderer(); SkASSERT(tiledRenderer && tiledRenderer->supportsTimingIndividualTiles()); if (NULL == tiledRenderer || !tiledRenderer->supportsTimingIndividualTiles()) { return; } int xTiles, yTiles; if (!tiledRenderer->tileDimensions(xTiles, yTiles)) { return; } int x, y; while (tiledRenderer->nextTile(x, y)) { // There are two timers, which will behave slightly differently: // 1) longRunningTimer, along with perTileTimerData, will time how long it takes to draw // one tile fRepeats times, and take the average. As such, it will not respect the // logPerIter or printMin options, since it does not know the time per iteration. It // will also be unable to call flush() for each tile. // The goal of this timer is to make up for a system timer that is not precise enough to // measure the small amount of time it takes to draw one tile once. // // 2) perTileTimer, along with perTileTimerData, will record each run separately, and // then take the average. As such, it supports logPerIter and printMin options. // // Although "legal", having two gpu timers running at the same time // seems to cause problems (i.e., INVALID_OPERATIONs) on several // platforms. To work around this, we disable the gpu timer on the // long running timer. SkAutoTDelete<Timer> longRunningTimer(this->setupTimer()); TimerData longRunningTimerData(numOuterLoops); for (int outer = 0; outer < numOuterLoops; ++outer) { SkAutoTDelete<Timer> perTileTimer(this->setupTimer(false)); TimerData perTileTimerData(numInnerLoops); longRunningTimer->start(); for (int inner = 0; inner < numInnerLoops; ++inner) { perTileTimer->start(); tiledRenderer->drawCurrentTile(); perTileTimer->truncatedEnd(); tiledRenderer->resetState(false); // flush & swapBuffers, but don't Finish perTileTimer->end(); SkAssertResult(perTileTimerData.appendTimes(perTileTimer.get())); if (fPurgeDecodedTex) { fRenderer->purgeTextures(); } } longRunningTimer->truncatedEnd(); tiledRenderer->resetState(true); // flush, swapBuffers and Finish longRunningTimer->end(); SkAssertResult(longRunningTimerData.appendTimes(longRunningTimer.get())); } fWriter->logRenderer(tiledRenderer); fWriter->tileMeta(x, y, xTiles, yTiles); // TODO(borenet): Turn off per-iteration tile time reporting for now. // Avoiding logging the time for every iteration for each tile cuts // down on data file size by a significant amount. Re-enable this once // we're loading the bench data directly into a data store and are no // longer generating SVG graphs. #if 0 fWriter->tileData( &perTileTimerData, timeFormat.c_str(), fTimerResult, timerTypes); #endif if (fPurgeDecodedTex) { fWriter->addTileFlag(PictureResultsWriter::kPurging); } fWriter->addTileFlag(PictureResultsWriter::kAvg); fWriter->tileData( &longRunningTimerData, tiledRenderer->getNormalTimeFormat().c_str(), TimerData::kAvg_Result, timerTypes, numInnerLoops); } } else { SkAutoTDelete<Timer> longRunningTimer(this->setupTimer()); TimerData longRunningTimerData(numOuterLoops); for (int outer = 0; outer < numOuterLoops; ++outer) { SkAutoTDelete<Timer> perRunTimer(this->setupTimer(false)); TimerData perRunTimerData(numInnerLoops); longRunningTimer->start(); for (int inner = 0; inner < numInnerLoops; ++inner) { fRenderer->setup(); perRunTimer->start(); fRenderer->render(NULL); perRunTimer->truncatedEnd(); fRenderer->resetState(false); // flush & swapBuffers, but don't Finish perRunTimer->end(); SkAssertResult(perRunTimerData.appendTimes(perRunTimer.get())); if (fPurgeDecodedTex) { fRenderer->purgeTextures(); } } longRunningTimer->truncatedEnd(); fRenderer->resetState(true); // flush, swapBuffers and Finish longRunningTimer->end(); SkAssertResult(longRunningTimerData.appendTimes(longRunningTimer.get())); } fWriter->logRenderer(fRenderer); if (fPurgeDecodedTex) { fWriter->addTileFlag(PictureResultsWriter::kPurging); } // Beware - since the per-run-timer doesn't ever include a glFinish it can // report a lower time then the long-running-timer #if 0 fWriter->tileData( &perRunTimerData, timeFormat.c_str(), fTimerResult, timerTypes); #else fWriter->tileData( &longRunningTimerData, timeFormat.c_str(), fTimerResult, timerTypes, numInnerLoops); #endif } fRenderer->end(); } }
#pragma once #include <fmt/chrono.h> #include <fmt/color.h> #include <fmt/core.h> #include <fmt/ranges.h> #include <string> #include <string_view> namespace journal { namespace v3 { template <typename... Args> inline auto critical( const std::string_view tag, Args&&... args ) -> void { const auto str = fmt::format( std::forward<Args>( args )... ); const auto t = std::time( nullptr ); const auto style = bg( fmt::terminal_color::red ) | fmt::emphasis::bold; fmt::print( style, "{:%Y-%m-%d %H-%M-%S} CRITICAL [{}] {}\n", fmt::localtime( t ), tag, str ); } template <typename... Args> inline auto error( const std::string_view tag, Args&&... args ) -> void { const auto str = fmt::format( std::forward<Args>( args )... ); const auto t = std::time( nullptr ); const auto style = fg( fmt::terminal_color::bright_red ); fmt::print( style, "{:%Y-%m-%d %H-%M-%S} ERROR [{}] {}\n", fmt::localtime( t ), tag, str ); } template <typename... Args> inline auto warning( const std::string_view tag, Args&&... args ) -> void { const auto str = fmt::format( std::forward<Args>( args )... ); const auto t = std::time( nullptr ); const auto style = fg( fmt::terminal_color::bright_yellow ); fmt::print( style, "{:%Y-%m-%d %H-%M-%S} WARNING [{}] {}\n", fmt::localtime( t ), tag, str ); } template <typename... Args> inline auto info( const std::string_view tag, Args&&... args ) -> void { const auto str = fmt::format( std::forward<Args>( args )... ); const auto t = std::time( nullptr ); const auto style = fg( fmt::terminal_color::white ); fmt::print( style, "{:%Y-%m-%d %H-%M-%S} INFO [{}] {}\n", fmt::localtime( t ), tag, str ); } template <typename... Args> inline auto debug( const std::string_view tag, Args&&... args ) -> void { const auto str = fmt::format( std::forward<Args>( args )... ); const auto t = std::time( nullptr ); const auto style = fg( fmt::terminal_color::cyan ); fmt::print( style, "{:%Y-%m-%d %H-%M-%S} DEBUG [{}] {}\n", fmt::localtime( t ), tag, str ); } template <typename... Args> inline auto verbose( const std::string_view tag, Args&&... args ) -> void { const auto str = fmt::format( std::forward<Args>( args )... ); const auto t = std::time( nullptr ); const auto style = fg( fmt::terminal_color::blue ); fmt::print( style, "{:%Y-%m-%d %H-%M-%S} VERBOSE [{}] {}\n", fmt::localtime( t ), tag, str ); } } // namespace v3 } // namespace journal namespace journal { using namespace v3; } // namespace journal
/*++ Copyright (C) 1996-1999 Microsoft Corporation Module Name: _LOCSTR.INL History: --*/ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Swaps two elements of the translation array. // //----------------------------------------------------------------------------- inline void CLocTranslationArray::SwapElements( UINT iOne, // First index to swap UINT iTwo) // Second index to swap { CLocTranslation Temp; LTASSERT(iOne <= (UINT)GetSize()); LTASSERT(iTwo <= (UINT)GetSize()); Temp = (*this)[iOne]; (*this)[iOne] = (*this)[iTwo]; (*this)[iTwo] = Temp; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Assignment operator for cracked strings. // //----------------------------------------------------------------------------- inline const CLocCrackedString & CLocCrackedString::operator=( const CLocCrackedString &csSource) { m_pstrBaseString = csSource.m_pstrBaseString; m_pstrExtension = csSource.m_pstrExtension; m_pstrControl = csSource.m_pstrControl; m_cControlLeader = csSource.m_cControlLeader; m_cHotKeyChar = csSource.m_cHotKeyChar; m_uiHotKeyPos = csSource.m_uiHotKeyPos; return *this; } //----------------------------------------------------------------------------- // // Implementation for comparing two cracked strings. Language ID and // string type are NOT significant! // //----------------------------------------------------------------------------- inline BOOL CLocCrackedString::Compare( const CLocCrackedString &csOther) const { return ((m_uiHotKeyPos == csOther.m_uiHotKeyPos) && (m_cHotKeyChar == csOther.m_cHotKeyChar) && (m_pstrControl == csOther.m_pstrControl) && (m_cControlLeader == csOther.m_cControlLeader) && (m_pstrExtension == csOther.m_pstrExtension) && (m_pstrBaseString == csOther.m_pstrBaseString)); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Comparision operator. // //----------------------------------------------------------------------------- inline int CLocCrackedString::operator==( const CLocCrackedString &csOther) const { return Compare(csOther); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Comparision operator. // //----------------------------------------------------------------------------- inline int CLocCrackedString::operator!=( const CLocCrackedString &csOther) const { return !Compare(csOther); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Tests to see if the Cracked string has an 'extension'. The extension // is a sequence of characters ("...", ">>", stc) that indicates that this // item leads to another UI element. // //----------------------------------------------------------------------------- inline BOOL // TRUE if the extension is non-null. CLocCrackedString::HasExtension(void) const { return m_pstrExtension.GetStringLength() != 0; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Tests to see if the cracked string has a 'control' sequence. This is // usually text describing a shortcut key that invokes the same action as this // item, for example "Ctrl + F". // //----------------------------------------------------------------------------- inline BOOL // TRUE if the control seq. is non-null CLocCrackedString::HasControl(void) const { return m_pstrControl.GetStringLength() != 0; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Check to see if the cracked string has a hot-key. This come directly out // of the CLocString that was parsed into the Cracked String. // //----------------------------------------------------------------------------- inline BOOL // TRUE if the string has a hot-key. CLocCrackedString::HasHotKey(void) const { return (m_cHotKeyChar != 0); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Returns the 'base string'. This is the original string stripped of // extension and control sequences, and of the hot-key. // //----------------------------------------------------------------------------- inline const CPascalString & // Base string. CLocCrackedString::GetBaseString(void) const { return m_pstrBaseString; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Returns the extension component of the string. // //----------------------------------------------------------------------------- inline const CPascalString & CLocCrackedString::GetExtension(void) const { return m_pstrExtension; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Returns the constol sequence of the string. // //----------------------------------------------------------------------------- inline const CPascalString & CLocCrackedString::GetControl(void) const { return m_pstrControl; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Returns the hot-key character for the string. // //----------------------------------------------------------------------------- inline WCHAR CLocCrackedString::GetHotKeyChar(void) const { LTASSERT(HasHotKey()); return m_cHotKeyChar; } inline UINT CLocCrackedString::GetHotKeyPos(void) const { LTASSERT(HasHotKey()); return m_uiHotKeyPos; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Returns the string type for the string. // //----------------------------------------------------------------------------- inline CST::StringType CLocCrackedString::GetStringType(void) const { return m_stStringType; } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Cleans out all the components of the cracked string. // //----------------------------------------------------------------------------- inline void CLocCrackedString::ClearCrackedString(void) { m_pstrBaseString.ClearString(); m_pstrExtension.ClearString(); m_pstrControl.ClearString(); m_cControlLeader = L'\0'; m_cHotKeyChar = L'\0'; m_uiHotKeyPos = 0; m_stStringType = CST::None; } inline void CLocCrackedString::SetBaseString( const CPascalString &pasBase) { m_pstrBaseString = pasBase; } inline void CLocCrackedString::SetHotKey( WCHAR cHotKeyChar, UINT uiHotKeyPos) { m_cHotKeyChar = cHotKeyChar; m_uiHotKeyPos = uiHotKeyPos; }
/** BSD-3-Clause Copyright 2019 Alliance for Sustainable Energy, LLC Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met : 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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. */ // Trough CSP - physical model #include "core.h" //#include "tckernel.h" // for adjustment factors #include "common.h" //#include "lib_weatherfile.h //#include "csp_solver_util.h" #include "csp_solver_core.h" #include "csp_solver_trough_collector_receiver.h" #include "csp_solver_pc_Rankine_indirect_224.h" #include "csp_solver_two_tank_tes.h" #include "csp_solver_tou_block_schedules.h" #include <ctime> // signed/unsigned mismatch #pragma warning (disable : 4388) static var_info _cm_vtab_trough_physical[] = { /* VARTYPE DATATYPE NAME LABEL UNITS META GROUP REQUIRED_IF CONSTRAINTS UI_HINTS*/ // Weather Reader { SSC_INPUT, SSC_STRING, "file_name", "Local weather file with path", "none", "", "weather", "*", "LOCAL_FILE", "" }, //{ SSC_INPUT, SSC_NUMBER, "track_mode", "Tracking mode", "none", "", "weather", "*", "", "" }, // Solar Field, Trough { SSC_INPUT, SSC_NUMBER, "nSCA", "Number of SCAs in a loop", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "nHCEt", "Number of HCE types", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "nColt", "Number of collector types", "none", "constant=4", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "nHCEVar", "Number of HCE variants per type", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "nLoops", "Number of loops in the field", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "FieldConfig", "Number of subfield headers", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "include_fixed_power_block_runner", "Should model consider piping through power block?", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "L_power_block_piping", "Length of piping (full mass flow) through heat sink (if applicable)", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "eta_pump", "HTF pump efficiency", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "Fluid", "Field HTF fluid ID number", "none", "", "solar_field", "*", "", "" }, //{ SSC_INPUT, SSC_NUMBER, "fthrok", "Flag to allow partial defocusing of the collectors", "W/SCA", "", "solar_field", "*", "INTEGER", "" }, //{ SSC_INPUT, SSC_NUMBER, "fthrctrl", "Defocusing strategy", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "accept_loc", "In acceptance testing mode - temperature sensor location", "1/2", "hx/loop", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "HDR_rough", "Header pipe roughness", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "theta_stow", "Stow angle", "deg", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "theta_dep", "Deploy angle", "deg", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "Row_Distance", "Spacing between rows (centerline to centerline)", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "T_loop_in_des", "Design loop inlet temperature", "C", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "T_loop_out", "Target loop outlet temperature", "C", "", "solar_field", "*", "", "" }, //{ SSC_INPUT, SSC_NUMBER, "T_startup", "Required temperature of the system before the power block can be switched on", "C", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "m_dot_htfmin", "Minimum loop HTF flow rate", "kg/s", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "m_dot_htfmax", "Maximum loop HTF flow rate", "kg/s", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "field_fl_props", "User defined field fluid property data", "-", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "T_fp", "Freeze protection temperature (heat trace activation temperature)", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "I_bn_des", "Solar irradiation at design", "C", "", "solar_field", "*", "", "" }, //{ SSC_INPUT, SSC_NUMBER, "V_hdr_max", "Maximum HTF velocity in the header at design", "W/m2", "", "solar_field", "*", "", "" }, //{ SSC_INPUT, SSC_NUMBER, "V_hdr_min", "Minimum HTF velocity in the header at design", "m/s", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "Pipe_hl_coef", "Loss coefficient from the header, runner pipe, and non-HCE piping", "m/s", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "SCA_drives_elec", "Tracking power, in Watts per SCA drive", "W/m2-K", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "tilt", "Tilt angle of surface/axis", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "azimuth", "Azimuth angle of surface/axis", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "wind_stow_speed", "Trough wind stow speed", "m/s", "", "solar_field", "?=50", "", "" }, { SSC_INPUT, SSC_NUMBER, "accept_mode", "Acceptance testing mode?", "0/1", "no/yes", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "accept_init", "In acceptance testing mode - require steady-state startup", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "solar_mult", "Solar multiple", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "mc_bal_hot", "Heat capacity of the balance of plant on the hot side", "kWht/K-MWt", "none", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "mc_bal_cold", "Heat capacity of the balance of plant on the cold side", "kWht/K-MWt", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "mc_bal_sca", "Non-HTF heat capacity associated with each SCA - per meter basis", "Wht/K-m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "W_aperture", "The collector aperture width (Total structural area used for shadowing)", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "A_aperture", "Reflective aperture area of the collector", "m2", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "TrackingError", "User-defined tracking error derate", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "GeomEffects", "User-defined geometry effects derate", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "Rho_mirror_clean", "User-defined clean mirror reflectivity", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "Dirt_mirror", "User-defined dirt on mirror derate", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "Error", "User-defined general optical error derate ", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "Ave_Focal_Length", "Average focal length of the collector ", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "L_SCA", "Length of the SCA ", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "L_aperture", "Length of a single mirror/HCE unit", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "ColperSCA", "Number of individual collector sections in an SCA ", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "Distance_SCA", "Piping distance between SCA's in the field", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "IAM_matrix", "IAM coefficients, matrix for 4 collectors", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "HCE_FieldFrac", "Fraction of the field occupied by this HCE type ", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "D_2", "Inner absorber tube diameter", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "D_3", "Outer absorber tube diameter", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "D_4", "Inner glass envelope diameter ", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "D_5", "Outer glass envelope diameter ", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "D_p", "Diameter of the absorber flow plug (optional) ", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "Flow_type", "Flow type through the absorber", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "Rough", "Relative roughness of the internal HCE surface ", "-", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "alpha_env", "Envelope absorptance ", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_11", "Absorber emittance for receiver type 1 variation 1", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_12", "Absorber emittance for receiver type 1 variation 2", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_13", "Absorber emittance for receiver type 1 variation 3", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_14", "Absorber emittance for receiver type 1 variation 4", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_21", "Absorber emittance for receiver type 2 variation 1", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_22", "Absorber emittance for receiver type 2 variation 2", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_23", "Absorber emittance for receiver type 2 variation 3", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_24", "Absorber emittance for receiver type 2 variation 4", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_31", "Absorber emittance for receiver type 3 variation 1", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_32", "Absorber emittance for receiver type 3 variation 2", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_33", "Absorber emittance for receiver type 3 variation 3", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_34", "Absorber emittance for receiver type 3 variation 4", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_41", "Absorber emittance for receiver type 4 variation 1", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_42", "Absorber emittance for receiver type 4 variation 2", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_43", "Absorber emittance for receiver type 4 variation 3", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "epsilon_3_44", "Absorber emittance for receiver type 4 variation 4", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "alpha_abs", "Absorber absorptance ", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "Tau_envelope", "Envelope transmittance", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "EPSILON_4", "Inner glass envelope emissivities (Pyrex) ", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "EPSILON_5", "Outer glass envelope emissivities (Pyrex) ", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "GlazingIntactIn", "Glazing intact (broken glass) flag {1=true, else=false}", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "P_a", "Annulus gas pressure", "torr", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "AnnulusGas", "Annulus gas type (1=air, 26=Ar, 27=H2)", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "AbsorberMaterial", "Absorber material type", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "Shadowing", "Receiver bellows shadowing loss factor", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "Dirt_HCE", "Loss due to dirt on the receiver envelope", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "Design_loss", "Receiver heat loss at design", "W/m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "SCAInfoArray", "Receiver (,1) and collector (,2) type for each assembly in loop", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "SCADefocusArray", "Collector defocus order", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "rec_su_delay", "Fixed startup delay time for the receiver", "hr", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "rec_qf_delay", "Energy-based receiver startup delay (fraction of rated thermal power)", "-", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "p_start", "Collector startup energy, per SCA", "kWe-hr", "", "solar_field", "*", "", "" }, // Power Cycle //{ SSC_INPUT, SSC_NUMBER, "q_pb_design", "Design heat input to power block", "MWt", "", "controller", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "pc_config", "0: Steam Rankine (224), 1: user defined", "-", "", "powerblock", "?=0", "INTEGER", "" }, { SSC_INPUT, SSC_NUMBER, "P_ref", "Rated plant capacity", "MWe", "", "powerblock", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "eta_ref", "Power cycle efficiency at design", "none", "", "powerblock", "*", "", "" }, //{ SSC_INPUT, SSC_NUMBER, "T_htf_hot_des", "Hot HTF outlet temperature at design conditions", "C", "", "powerblock", "*", "", "" }, //{ SSC_INPUT, SSC_NUMBER, "T_htf_cold_des", "Cold HTF inlet temperature at design conditions", "C", "", "powerblock", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "cycle_max_frac", "Maximum turbine over design operation fraction", "-", "", "powerblock", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "cycle_cutoff_frac", "Minimum turbine operation fraction before shutdown", "-", "", "powerblock", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "q_sby_frac", "Fraction of thermal power required for standby mode", "none", "", "powerblock", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "startup_time", "Time needed for power block startup", "hr", "", "powerblock", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "startup_frac", "Fraction of design thermal power needed for startup", "none", "", "powerblock", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "pb_pump_coef", "Pumping power to move 1kg of HTF through PB loop", "kW/kg", "", "powerblock", "*", "", "" }, //{ SSC_INPUT, SSC_NUMBER, "rec_htf", "17: Salt (60% NaNO3, 40% KNO3) 10: Salt (46.5% LiF 11.5% NaF 42% KF) 50: Lookup tables", "", "", "powerblock", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "dT_cw_ref", "Reference condenser cooling water inlet/outlet T diff", "C", "", "powerblock", "pc_config=0", "", "" }, { SSC_INPUT, SSC_NUMBER, "T_amb_des", "Reference ambient temperature at design point", "C", "", "powerblock", "pc_config=0", "", "" }, { SSC_INPUT, SSC_NUMBER, "P_boil", "Boiler operating pressure", "bar", "", "powerblock", "pc_config=0", "", "" }, { SSC_INPUT, SSC_NUMBER, "CT", "Flag for using dry cooling or wet cooling system", "none", "", "powerblock", "pc_config=0", "", "" }, { SSC_INPUT, SSC_NUMBER, "tech_type", "Turbine inlet pressure control flag (sliding=user, fixed=trough)", "1/2/3", "tower/trough/user", "powerblock", "pc_config=0", "", "" }, { SSC_INPUT, SSC_NUMBER, "T_approach", "Cooling tower approach temperature", "C", "", "powerblock", "pc_config=0", "", "" }, { SSC_INPUT, SSC_NUMBER, "T_ITD_des", "ITD at design for dry system", "C", "", "powerblock", "pc_config=0", "", "" }, { SSC_INPUT, SSC_NUMBER, "P_cond_ratio", "Condenser pressure ratio", "none", "", "powerblock", "pc_config=0", "", "" }, { SSC_INPUT, SSC_NUMBER, "pb_bd_frac", "Power block blowdown steam fraction ", "none", "", "powerblock", "pc_config=0", "", "" }, { SSC_INPUT, SSC_NUMBER, "P_cond_min", "Minimum condenser pressure", "inHg", "", "powerblock", "pc_config=0", "", "" }, { SSC_INPUT, SSC_NUMBER, "n_pl_inc", "Number of part-load increments for the heat rejection system", "none", "", "powerblock", "pc_config=0", "", "" }, { SSC_INPUT, SSC_ARRAY, "F_wc", "Fraction indicating wet cooling use for hybrid system", "none", "constant=[0,0,0,0,0,0,0,0,0]", "powerblock", "pc_config=0", "", "" }, // UDPC parameters { SSC_INPUT, SSC_NUMBER, "ud_f_W_dot_cool_des", "Percent of user-defined power cycle design gross output consumed by cooling", "%", "", "powerblock", "pc_config=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "ud_m_dot_water_cool_des", "Mass flow rate of water required at user-defined power cycle design point", "kg/s", "", "powerblock", "pc_config=1", "", "" }, { SSC_INPUT, SSC_MATRIX, "ud_ind_od", "Off design user-defined power cycle performance as function of T_htf, m_dot_htf [ND], and T_amb", "", "", "powerblock", "pc_config=1", "", "" }, // TES { SSC_INPUT, SSC_NUMBER, "store_fluid", "Material number for storage fluid", "-", "", "TES", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "store_fl_props", "User defined storage fluid property data", "-", "", "TES", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "is_hx", "Heat exchanger (HX) exists (1=yes, 0=no)" , "-", "", "TES", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "tshours", "Equivalent full-load thermal storage hours", "hr", "", "TES", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "h_tank", "Total height of tank (height of HTF when tank is full", "m", "", "TES", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "u_tank", "Loss coefficient from the tank", "W/m2-K", "", "TES", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "tank_pairs", "Number of equivalent tank pairs", "-", "", "TES", "*", "INTEGER", "" }, { SSC_INPUT, SSC_NUMBER, "hot_tank_Thtr", "Minimum allowable hot tank HTF temp", "C", "", "TES", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "hot_tank_max_heat", "Rated heater capacity for hot tank heating", "MWe", "", "TES", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "cold_tank_Thtr", "Minimum allowable cold tank HTF temp", "C", "", "TES", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "cold_tank_max_heat", "Rated heater capacity for cold tank heating", "MWe", "", "TES", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "dt_hot", "Hot side HX approach temp", "C", "", "TES", "*", "", "" }, //{ SSC_INPUT, SSC_NUMBER, "dt_cold", "Cold side HX approach temp", "C", "", "TES", "*", "", "" }, //{ SSC_INPUT, SSC_NUMBER, "T_tank_hot_ini", "Initial hot tank fluid tmeperature", "C", "", "TES", "*", "", "" }, //{ SSC_INPUT, SSC_NUMBER, "T_tank_cold_ini", "Initial cold tank fluid tmeperature", "C", "", "TES", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "h_tank_min", "Minimum allowable HTF height in storage tank", "m", "", "TES", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "init_hot_htf_percent", "Initial fraction of avail. vol that is hot", "%", "", "TES", "*", "", "" }, // TOU { SSC_INPUT, SSC_MATRIX, "weekday_schedule", "12x24 CSP operation Time-of-Use Weekday schedule", "-", "", "tou", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "weekend_schedule", "12x24 CSP operation Time-of-Use Weekend schedule", "-", "", "tou", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "dispatch_sched_weekday", "12x24 PPA pricing Weekday schedule", "", "", "tou", "?=1", "", "" }, { SSC_INPUT, SSC_MATRIX, "dispatch_sched_weekend", "12x24 PPA pricing Weekend schedule", "", "", "tou", "?=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "is_tod_pc_target_also_pc_max", "Is the TOD target cycle heat input also the max cycle heat input?", "", "", "tou", "?=0", "", "" }, { SSC_INPUT, SSC_NUMBER, "is_dispatch", "Allow dispatch optimization?", /*TRUE=1*/ "-", "", "tou", "?=0", "", "" }, { SSC_INPUT, SSC_NUMBER, "is_write_ampl_dat", "Write AMPL data files for dispatch run", "-", "", "tou", "?=0", "", "" }, { SSC_INPUT, SSC_NUMBER, "is_ampl_engine", "Run dispatch optimization with external AMPL engine", "-", "", "tou", "?=0", "", "" }, { SSC_INPUT, SSC_STRING, "ampl_data_dir", "AMPL data file directory", "-", "", "tou", "?=''", "", "" }, { SSC_INPUT, SSC_STRING, "ampl_exec_call", "System command to run AMPL code", "-", "", "tou", "?='ampl sdk_solution.run'", "", "" }, { SSC_INPUT, SSC_NUMBER, "disp_frequency", "Frequency for dispatch optimization calculations", "hour", "", "tou", "is_dispatch=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "disp_steps_per_hour", "Time steps per hour for dispatch optimization calculations", "-", "", "tou", "?=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "disp_horizon", "Time horizon for dispatch optimization", "hour", "", "tou", "is_dispatch=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "disp_max_iter", "Max. no. dispatch optimization iterations", "-", "", "tou", "is_dispatch=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "disp_timeout", "Max. dispatch optimization solve duration", "s", "", "tou", "is_dispatch=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "disp_mip_gap", "Dispatch optimization solution tolerance", "-", "", "tou", "is_dispatch=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "disp_spec_presolve", "Dispatch optimization presolve heuristic", "-", "", "tou", "?=-1", "", "" }, { SSC_INPUT, SSC_NUMBER, "disp_spec_bb", "Dispatch optimization B&B heuristic", "-", "", "tou", "?=-1", "", "" }, { SSC_INPUT, SSC_NUMBER, "disp_reporting", "Dispatch optimization reporting level", "-", "", "tou", "?=-1", "", "" }, { SSC_INPUT, SSC_NUMBER, "disp_spec_scaling", "Dispatch optimization scaling heuristic", "-", "", "tou", "?=-1", "", "" }, { SSC_INPUT, SSC_NUMBER, "disp_time_weighting", "Dispatch optimization future time discounting factor", "-", "", "tou", "?=0.99", "", "" }, { SSC_INPUT, SSC_NUMBER, "disp_rsu_cost", "Receiver startup cost", "$", "", "tou", "is_dispatch=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "disp_csu_cost", "Cycle startup cost", "$", "", "tou", "is_dispatch=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "disp_pen_delta_w", "Dispatch cycle production change penalty", "$/kWe-change", "", "tou", "is_dispatch=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "q_rec_standby", "Receiver standby energy consumption", "kWt", "", "tou", "?=9e99", "", "" }, { SSC_INPUT, SSC_NUMBER, "q_rec_heattrace", "Receiver heat trace energy consumption during startup", "kWe-hr", "", "tou", "?=0.0", "", "" }, { SSC_INPUT, SSC_NUMBER, "is_wlim_series", "Use time-series net electricity generation limits", "", "", "tou", "?=0", "", "" }, { SSC_INPUT, SSC_ARRAY, "wlim_series", "Time series net electicity generation limits", "kWe", "", "tou", "is_wlim_series=1", "", "" }, { SSC_INPUT, SSC_ARRAY, "f_turb_tou_periods", "Dispatch logic for turbine load fraction", "-", "", "tou", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "ppa_multiplier_model", "PPA multiplier model", "0/1", "0=diurnal,1=timestep","tou", "?=0", "INTEGER,MIN=0", "" }, { SSC_INPUT, SSC_ARRAY, "dispatch_factors_ts", "Dispatch payment factor array", "", "", "tou", "ppa_multiplier_model=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "dispatch_factor1", "Dispatch payment factor 1", "", "", "tou", "?=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "dispatch_factor2", "Dispatch payment factor 2", "", "", "tou", "?=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "dispatch_factor3", "Dispatch payment factor 3", "", "", "tou", "?=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "dispatch_factor4", "Dispatch payment factor 4", "", "", "tou", "?=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "dispatch_factor5", "Dispatch payment factor 5", "", "", "tou", "?=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "dispatch_factor6", "Dispatch payment factor 6", "", "", "tou", "?=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "dispatch_factor7", "Dispatch payment factor 7", "", "", "tou", "?=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "dispatch_factor8", "Dispatch payment factor 8", "", "", "tou", "?=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "dispatch_factor9", "Dispatch payment factor 9", "", "", "tou", "?=1", "", "" }, { SSC_INPUT, SSC_NUMBER, "is_dispatch_series", "Use time-series dispatch factors", "", "", "tou", "?=1", "", "" }, { SSC_INPUT, SSC_ARRAY, "dispatch_series", "Time series dispatch factors", "", "", "tou", "", "", "" }, // System { SSC_INPUT, SSC_NUMBER, "pb_fixed_par", "Fraction of rated gross power constantly consumed", "MWe/MWcap", "", "system", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "bop_array", "Balance of plant parasitic power fraction, mult frac and const, linear and quad coeff", "", "", "system", "*", "", "" }, { SSC_INPUT, SSC_ARRAY, "aux_array", "Auxiliary heater, mult frac and const, linear and quad coeff", "", "", "system", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "gross_net_conversion_factor", "Estimated gross to net conversion factor", "", "", "system", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "water_usage_per_wash", "Water usage per wash", "L/m2_aper", "", "system", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "washing_frequency", "Mirror washing frequency", "-/year", "", "system", "*", "", "" }, //{ SSC_INPUT, SSC_NUMBER, "system_capacity", "Nameplate capacity", "kW", "", "system", "*", "", "" }, // Newly added { SSC_INPUT, SSC_NUMBER, "calc_design_pipe_vals", "Calculate temps and pressures at design conditions for runners and headers", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "V_hdr_cold_max", "Maximum HTF velocity in the cold headers at design", "m/s", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "V_hdr_cold_min", "Minimum HTF velocity in the cold headers at design", "m/s", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "V_hdr_hot_max", "Maximum HTF velocity in the hot headers at design", "m/s", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "V_hdr_hot_min", "Minimum HTF velocity in the hot headers at design", "m/s", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "N_max_hdr_diams", "Maximum number of diameters in each of the hot and cold headers", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "L_rnr_pb", "Length of runner pipe in power block", "m", "", "powerblock", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "L_rnr_per_xpan", "Threshold length of straight runner pipe without an expansion loop", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "L_xpan_hdr", "Compined perpendicular lengths of each header expansion loop", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "L_xpan_rnr", "Compined perpendicular lengths of each runner expansion loop", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "Min_rnr_xpans", "Minimum number of expansion loops per single-diameter runner section", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "northsouth_field_sep", "North/south separation between subfields. 0 = SCAs are touching", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "N_hdr_per_xpan", "Number of collector loops per expansion loop", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "offset_xpan_hdr", "Location of first header expansion loop. 1 = after first collector loop", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "K_cpnt", "Interconnect component minor loss coefficients, row=intc, col=cpnt", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "D_cpnt", "Interconnect component diameters, row=intc, col=cpnt", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "L_cpnt", "Interconnect component lengths, row=intc, col=cpnt", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "Type_cpnt", "Interconnect component type, row=intc, col=cpnt", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "custom_sf_pipe_sizes", "Use custom solar field pipe diams, wallthks, and lengths", "none", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "sf_rnr_diams", "Custom runner diameters", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "sf_rnr_wallthicks", "Custom runner wall thicknesses", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "sf_rnr_lengths", "Custom runner lengths", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "sf_hdr_diams", "Custom header diameters", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "sf_hdr_wallthicks", "Custom header wall thicknesses", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "sf_hdr_lengths", "Custom header lengths", "m", "", "solar_field", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "tanks_in_parallel", "Tanks are in parallel, not in series, with solar field", "-", "", "controller", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "has_hot_tank_bypass", "Bypass valve connects field outlet to cold tank", "-", "", "controller", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "T_tank_hot_inlet_min", "Minimum hot tank htf inlet temperature", "C", "", "controller", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "tes_pump_coef", "Pumping power to move 1kg of HTF through tes loop", "kW/(kg/s)", "", "controller", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "V_tes_des", "Design-point velocity to size the TES pipe diameters", "m/s", "", "controller", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "custom_tes_p_loss", "TES pipe losses are based on custom lengths and coeffs", "-", "", "controller", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "k_tes_loss_coeffs", "Minor loss coeffs for the coll, gen, and bypass loops", "-", "", "controller", "*", "", "" }, { SSC_INPUT, SSC_NUMBER, "custom_tes_pipe_sizes", "Use custom TES pipe diams, wallthks, and lengths", "-", "", "controller", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "tes_diams", "Custom TES diameters", "m", "", "controller", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "tes_wallthicks", "Custom TES wall thicknesses", "m", "", "controller", "*", "", "" }, { SSC_INPUT, SSC_MATRIX, "tes_lengths", "Custom TES lengths", "m", "", "controller", "", "", "" }, { SSC_INPUT, SSC_NUMBER, "DP_SGS", "Pressure drop within the steam generator", "bar", "", "controller", "*", "", "" }, // ************************************************************************************************* // OUTPUTS // ************************************************************************************************* // Simulation Kernel { SSC_OUTPUT, SSC_ARRAY, "time_hr", "Time at end of timestep", "hr", "", "solver", "*", "", "" }, // Weather Reader { SSC_OUTPUT, SSC_ARRAY, "month", "Resource Month", "", "", "weather", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "hour_day", "Resource Hour of Day", "", "", "weather", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "solazi", "Resource Solar Azimuth", "deg", "", "weather", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "solzen", "Resource Solar Zenith", "deg", "", "weather", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "beam", "Resource Beam normal irradiance", "W/m2", "", "weather", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "tdry", "Resource Dry bulb temperature", "C", "", "weather", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "twet", "Resource Wet bulb temperature", "C", "", "weather", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "rh", "Resource Relative Humidity", "%", "", "weather", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "wspd", "Resource Wind Speed", "m/s", "", "weather", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pres", "Resource Pressure", "mbar", "", "weather", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "defocus", "Field optical focus fraction", "", "", "weather", "*", "", "" }, // Solar Field { SSC_OUTPUT, SSC_ARRAY, "Theta_ave", "Field collector solar incidence angle", "deg", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "CosTh_ave", "Field collector cosine efficiency", "", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "IAM_ave", "Field collector incidence angle modifier", "", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "RowShadow_ave", "Field collector row shadowing loss", "", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "EndLoss_ave", "Field collector optical end loss", "", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "dni_costh", "Field collector DNI-cosine product", "W/m2", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "EqOpteff", "Field optical efficiency before defocus", "", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "SCAs_def", "Field fraction of focused SCAs", "", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_inc_sf_tot", "Field thermal power incident", "MWt", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "qinc_costh", "Field thermal power incident after cosine", "MWt", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_rec_inc", "Receiver thermal power incident", "MWt", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_rec_thermal_loss", "Receiver thermal losses", "MWt", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_rec_abs", "Receiver thermal power absorbed", "MWt", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_piping_loss", "Field piping thermal losses", "MWt", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "e_dot_field_int_energy", "Field change in material/htf internal energy", "MWt", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_htf_sf_out", "Field thermal power leaving in HTF", "MWt", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_freeze_prot", "Field freeze protection required", "MWt", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "m_dot_loop", "Receiver mass flow rate", "kg/s", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "m_dot_field_recirc", "Field total mass flow recirculated", "kg/s", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "m_dot_field_delivered", "Field total mass flow delivered", "kg/s", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "T_field_cold_in", "Field timestep-averaged inlet temperature", "C", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "T_rec_cold_in", "Loop timestep-averaged inlet temperature", "C", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "T_rec_hot_out", "Loop timestep-averaged outlet temperature", "C", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "T_field_hot_out", "Field timestep-averaged outlet temperature", "C", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "deltaP_field", "Field pressure drop", "bar", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "W_dot_sca_track", "Field collector tracking power", "MWe", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "W_dot_field_pump", "Field htf pumping power", "MWe", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_header_diams", "Field piping header diameters", "m", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_header_wallthk", "Field piping header wall thicknesses", "m", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_header_lengths", "Field piping header lengths", "m", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_header_expansions", "Number of field piping header expansions", "-", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_header_mdot_dsn", "Field piping header mass flow at design", "kg/s", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_header_vel_dsn", "Field piping header velocity at design", "m/s", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_header_T_dsn", "Field piping header temperature at design", "C", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_header_P_dsn", "Field piping header pressure at design", "bar", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_runner_diams", "Field piping runner diameters", "m", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_runner_wallthk", "Field piping runner wall thicknesses", "m", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_runner_lengths", "Field piping runner lengths", "m", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_runner_expansions", "Number of field piping runner expansions", "-", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_runner_mdot_dsn", "Field piping runner mass flow at design", "kg/s", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_runner_vel_dsn", "Field piping runner velocity at design", "m/s", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_runner_T_dsn", "Field piping runner temperature at design", "C", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_runner_P_dsn", "Field piping runner pressure at design", "bar", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_loop_T_dsn", "Field piping loop temperature at design", "C", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_loop_P_dsn", "Field piping loop pressure at design", "bar", "", "solar_field", "*", "", "" }, // Power Block { SSC_OUTPUT, SSC_ARRAY, "eta", "PC efficiency: gross", "", "", "powerblock", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_pb", "PC input energy", "MWt", "", "powerblock", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "m_dot_pc", "PC HTF mass flow rate", "kg/s", "", "powerblock", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_pc_startup", "PC startup thermal power", "MWt", "", "powerblock", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "P_cycle", "PC electrical power output: gross", "MWe", "", "powerblock", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "T_pc_in", "PC HTF inlet temperature", "C", "", "powerblock", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "T_pc_out", "PC HTF outlet temperature", "C", "", "powerblock", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "m_dot_water_pc", "PC water consumption: makeup + cooling", "kg/s", "", "powerblock", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_pc_startup", "PC startup thermal energy", "MWht", "", "powerblock", "*", "", "" }, // TES { SSC_OUTPUT, SSC_ARRAY, "tank_losses", "TES thermal losses", "MWt", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_tes_heater", "TES freeze protection power", "MWe", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "T_tes_hot", "TES hot temperature", "C", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "T_tes_cold", "TES cold temperature", "C", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "mass_tes_cold", "TES cold tank mass (end)", "kg", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "mass_tes_hot", "TES hot tank mass (end)", "kg", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dc_tes", "TES discharge thermal power", "MWt", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_ch_tes", "TES charge thermal power", "MWt", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "e_ch_tes", "TES charge state", "MWht", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "m_dot_cr_to_tes_hot", "Mass flow: field to hot TES", "kg/s", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "m_dot_tes_hot_out", "Mass flow: TES hot out", "kg/s", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "m_dot_pc_to_tes_cold", "Mass flow: cycle to cold TES", "kg/s", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "m_dot_tes_cold_out", "Mass flow: TES cold out", "kg/s", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "m_dot_field_to_cycle", "Mass flow: field to cycle", "kg/s", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "m_dot_cycle_to_field", "Mass flow: cycle to field", "kg/s", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "m_dot_cold_tank_to_hot_tank", "Mass flow: cold tank to hot tank", "kg/s", "", "TES", "*", "", "" }, //{ SSC_OUTPUT, SSC_ARRAY, "m_dot_tes_dc", "TES discharge mass flow rate", "kg/s", "", "TES", "*", "", "" }, //{ SSC_OUTPUT, SSC_ARRAY, "m_dot_tes_ch", "TES charge mass flow rate", "kg/s", "", "TES", "*", "", "" }, // SYSTEM //{ SSC_OUTPUT, SSC_ARRAY, "W_dot_parasitic_tot", "System total electrical parasitic", "MWe", "", "system", "*", "", "" }, // Controller { SSC_OUTPUT, SSC_ARRAY, "op_mode_1", "1st operating mode", "", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "op_mode_2", "2nd op. mode, if applicable", "", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "op_mode_3", "3rd op. mode, if applicable", "", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "m_dot_balance", "Relative mass flow balance error", "", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_balance", "Relative energy balance error", "", "", "solver", "*", "", "" }, // Monthly Outputs { SSC_OUTPUT, SSC_ARRAY, "monthly_energy", "Monthly Energy", "kWh", "", "Post-process", "*", "LENGTH=12", "" }, // Annual Outputs { SSC_OUTPUT, SSC_NUMBER, "annual_energy", "Annual Net Electrical Energy Production w/ avail derate", "kWe-hr", "", "Post-process", "*", "", "" }, //{ SSC_OUTPUT, SSC_NUMBER, "annual_gross_energy", "Annual Gross Electrical Energy Production w/ avail derate", "kWe-hr", "", "Post-process", "*", "", "" }, { SSC_OUTPUT, SSC_NUMBER, "annual_thermal_consumption", "Annual thermal freeze protection required", "kWt-hr", "", "Post-process", "*", "", "" }, //{ SSC_OUTPUT, SSC_NUMBER, "annual_electricity_consumption", "Annual electricity consumptoin w/ avail derate", "kWe-hr", "", "Post-process", "*", "", "" }, { SSC_OUTPUT, SSC_NUMBER, "annual_total_water_use", "Total Annual Water Usage", "m^3", "", "Post-process", "*", "", "" }, { SSC_OUTPUT, SSC_NUMBER, "annual_field_freeze_protection", "Annual thermal power for field freeze protection", "kWt-hr", "", "Post-process", "*", "", "" }, { SSC_OUTPUT, SSC_NUMBER, "annual_tes_freeze_protection", "Annual thermal power for TES freeze protection", "kWt-hr", "", "Post-process", "*", "", "" }, // Newly added { SSC_OUTPUT, SSC_ARRAY, "n_op_modes", "Operating modes in reporting timestep", "", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "tou_value", "CSP operating Time-of-use value", "", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pricing_mult", "PPA price multiplier", "", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_pc_sb", "Thermal power for PC standby", "MWt", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_pc_min", "Thermal power for PC min operation", "MWt", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_pc_target", "Target thermal power to PC", "MWt", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_pc_max", "Max thermal power to PC", "MWt", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "is_rec_su_allowed", "is receiver startup allowed", "", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "is_pc_su_allowed", "is power cycle startup allowed", "", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "is_pc_sb_allowed", "is power cycle standby allowed", "", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_est_cr_su", "Estimate rec. startup thermal power", "MWt", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_est_cr_on", "Estimate rec. thermal power TO HTF", "MWt", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_est_tes_dc", "Estimate max TES discharge thermal power", "MWt", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "q_dot_est_tes_ch", "Estimate max TES charge thermal power", "MWt", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "operating_modes_a", "First 3 operating modes tried", "", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "operating_modes_b", "Next 3 operating modes tried", "", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "operating_modes_c", "Final 3 operating modes tried", "", "", "solver", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_solve_state", "Dispatch solver state", "", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_solve_iter", "Dispatch iterations count", "", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_objective", "Dispatch objective function value", "", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_obj_relax", "Dispatch objective function - relaxed max", "", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_qsf_expected", "Dispatch expected solar field available energy", "MWt", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_qsfprod_expected", "Dispatch expected solar field generation", "MWt", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_qsfsu_expected", "Dispatch expected solar field startup enegy", "MWt", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_tes_expected", "Dispatch expected TES charge level", "MWht", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_pceff_expected", "Dispatch expected power cycle efficiency adj.", "", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_thermeff_expected", "Dispatch expected SF thermal efficiency adj.", "", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_qpbsu_expected", "Dispatch expected power cycle startup energy", "MWht", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_wpb_expected", "Dispatch expected power generation", "MWe", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_rev_expected", "Dispatch expected revenue factor", "", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_presolve_nconstr", "Dispatch number of constraints in problem", "", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_presolve_nvar", "Dispatch number of variables in problem", "", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "disp_solve_time", "Dispatch solver time", "sec", "", "tou", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "htf_pump_power", "Parasitic power TES and Cycle HTF pump", "MWe", "", "system", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "P_cooling_tower_tot", "Parasitic power condenser operation", "MWe", "", "system", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "P_fixed", "Parasitic power fixed load", "MWe", "", "system", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "P_plant_balance_tot", "Parasitic power generation-dependent load", "MWe", "", "system", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "P_out_net", "Total electric power to grid", "MWe", "", "system", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "gen", "Total electric power to grid w/ avail. derate", "kWe", "", "system", "*", "", "" }, { SSC_OUTPUT, SSC_NUMBER, "annual_W_cycle_gross", "Electrical source - Power cycle gross output", "kWhe", "", "system", "*", "", "" }, { SSC_OUTPUT, SSC_NUMBER, "conversion_factor", "Gross to Net Conversion Factor", "%", "", "system", "*", "", "" }, { SSC_OUTPUT, SSC_NUMBER, "capacity_factor", "Capacity factor", "%", "", "system", "*", "", "" }, { SSC_OUTPUT, SSC_NUMBER, "kwh_per_kw", "First year kWh/kW", "kWh/kW", "", "system", "*", "", "" }, { SSC_OUTPUT, SSC_NUMBER, "sim_duration", "Computational time of timeseries simulation", "s", "", "system", "*", "", "" }, //{ SSC_OUTPUT, SSC_NUMBER, "W_dot_par_tot_haf", "Adjusted parasitic power", "kWe", "", "system", "*", "", "" }, //{ SSC_OUTPUT, SSC_NUMBER, "q_dot_defocus_est", "Thermal energy intentionally lost by defocusing", "MWt", "", "system", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "recirculating", "Field recirculating (bypass valve open)", "-", "", "solar_field", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_tes_diams", "Pipe diameters in TES", "m", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_tes_wallthk", "Pipe wall thickness in TES", "m", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_tes_lengths", "Pipe lengths in TES", "m", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_tes_mdot_dsn", "Mass flow TES pipes at design conditions", "kg/s", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_tes_vel_dsn", "Velocity in TES pipes at design conditions", "m/s", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_tes_T_dsn", "Temperature in TES pipes at design conditions", "C", "", "TES", "*", "", "" }, { SSC_OUTPUT, SSC_ARRAY, "pipe_tes_P_dsn", "Pressure in TES pipes at design conditions", "bar", "", "TES", "*", "", "" }, //{ SSC_OUTPUT, SSC_ARRAY, "defocus", "Field optical focus fraction", "", "", "solver", "*", "", "" }, var_info_invalid }; class cm_trough_physical : public compute_module { public: cm_trough_physical() { add_var_info( _cm_vtab_trough_physical ); add_var_info( vtab_adjustment_factors ); } void exec( ) { // ******************************** // ******************************** // Weather reader // ******************************** // ******************************** C_csp_weatherreader weather_reader; weather_reader.m_weather_data_provider = std::make_shared<weatherfile>(as_string("file_name")); weather_reader.m_filename = as_string("file_name"); weather_reader.m_trackmode = 0; weather_reader.m_tilt = 0.0; weather_reader.m_azimuth = 0.0; // Initialize to get weather file info weather_reader.init(); if (weather_reader.has_error()) throw exec_error("trough_physical", weather_reader.get_error()); // Set up ssc output arrays // Set steps per hour double nhourssim = 8760.0; //[hr] Number of hours to simulate C_csp_solver::S_sim_setup sim_setup; sim_setup.m_sim_time_start = 0.0; //[s] starting first hour of year sim_setup.m_sim_time_end = nhourssim*3600.; //[s] full year simulation int steps_per_hour = 1; //[-] int n_wf_records = (int)weather_reader.m_weather_data_provider->nrecords(); steps_per_hour = n_wf_records / 8760; //[-] int n_steps_fixed = steps_per_hour*8760; //[-] sim_setup.m_report_step = 3600.0 / (double)steps_per_hour; //[s] // ******************************** // ******************************** // Solar field, trough // ******************************** // ******************************** C_csp_trough_collector_receiver c_trough; c_trough.m_nSCA = as_integer("nSCA"); //[-] Number of SCA's in a loop c_trough.m_nHCEt = as_integer("nHCEt"); //[-] Number of HCE types c_trough.m_nColt = as_integer("nColt"); //[-] Number of collector types c_trough.m_nHCEVar = as_integer("nHCEVar"); //[-] Number of HCE variants per t c_trough.m_nLoops = as_integer("nLoops"); //[-] Number of loops in the field c_trough.m_FieldConfig = as_integer("FieldConfig"); //[-] Number of subfield headers c_trough.m_L_power_block_piping = as_double("L_power_block_piping"); //[m] Length of piping (full mass flow) through power block (if applicable) c_trough.m_include_fixed_power_block_runner = as_boolean("include_fixed_power_block_runner"); //[-] Should model consider piping through power block? c_trough.m_eta_pump = as_double("eta_pump"); //[-] HTF pump efficiency c_trough.m_Fluid = as_integer("Fluid"); //[-] Field HTF fluid number //c_trough.m_fthrok = as_integer("fthrok"); //[-] Flag to allow partial defocusing of the collectors c_trough.m_fthrctrl = 2; //[-] Defocusing strategy; hardcode = 2 for now c_trough.m_accept_loc = as_integer("accept_loc"); //[-] In acceptance testing mode - temperature sensor location (1=hx,2=loop) c_trough.m_HDR_rough = as_double("HDR_rough"); //[-] Header pipe relative roughness c_trough.m_theta_stow = as_double("theta_stow"); //[deg] stow angle c_trough.m_theta_dep = as_double("theta_dep"); //[deg] deploy angle c_trough.m_Row_Distance = as_double("Row_Distance"); //[m] Spacing between rows (centerline to centerline) double T_loop_in_des = as_double("T_loop_in_des"); //[C] Design loop inlet temperature, converted to K in init c_trough.m_T_loop_in_des = T_loop_in_des; //[C] Design loop inlet temperature, converted to K in init double T_loop_out_des = as_double("T_loop_out"); //[C] Target loop outlet temperature, converted to K in init c_trough.m_T_loop_out_des = T_loop_out_des; //[C] Target loop outlet temperature, converted to K in init double T_startup_min = T_loop_in_des; if (T_loop_out_des > 600.0) { T_startup_min = T_loop_out_des - 70.0; } double T_startup = std::max(T_startup_min, 0.67*T_loop_in_des + 0.33*T_loop_out_des); //[C] c_trough.m_T_startup = T_startup; //[C] The required temperature (converted to K in init) of the system before the power block can be switched on c_trough.m_m_dot_htfmin = as_double("m_dot_htfmin"); //[kg/s] Minimum loop HTF flow rate c_trough.m_m_dot_htfmax = as_double("m_dot_htfmax"); //[kg/s] Maximum loop HTF flow rate c_trough.m_field_fl_props = as_matrix("field_fl_props"); //[-] User-defined field HTF properties c_trough.m_T_fp = as_double("T_fp"); //[C] Freeze protection temperature (heat trace activation temperature), convert to K in init c_trough.m_I_bn_des = as_double("I_bn_des"); //[W/m^2] Solar irradiation at design c_trough.m_V_hdr_cold_max = as_double("V_hdr_cold_max"); //[m/s] Maximum HTF velocity in the cold header at design c_trough.m_V_hdr_cold_min = as_double("V_hdr_cold_min"); //[m/s] Minimum HTF velocity in the cold header at design c_trough.m_V_hdr_hot_max = as_double("V_hdr_hot_max"); //[m/s] Maximum HTF velocity in the hot header at design c_trough.m_V_hdr_hot_min = as_double("V_hdr_hot_min"); //[m/s] Minimum HTF velocity in the hot header at design c_trough.m_Pipe_hl_coef = as_double("Pipe_hl_coef"); //[W/m2-K] Loss coefficient from the header, runner pipe, and non-HCE piping c_trough.m_SCA_drives_elec = as_double("SCA_drives_elec"); //[W/SCA] Tracking power, in Watts per SCA drive c_trough.m_ColTilt = as_double("tilt"); //[deg] Collector tilt angle (0 is horizontal, 90deg is vertical) c_trough.m_ColAz = as_double("azimuth"); //[deg] Collector azimuth angle c_trough.m_wind_stow_speed = as_double("wind_stow_speed"); //[m/s] Wind speed at and above which the collectors will be stowed c_trough.m_accept_mode = as_integer("accept_mode"); //[-] Acceptance testing mode? (1=yes, 0=no) c_trough.m_accept_init = as_boolean("accept_init"); //[-] In acceptance testing mode - require steady-state startup c_trough.m_solar_mult = as_double("solar_mult"); //[-] Solar Multiple c_trough.m_mc_bal_hot_per_MW = as_double("mc_bal_hot"); //[kWht/K-MWt] The heat capacity of the balance of plant on the hot side c_trough.m_mc_bal_cold_per_MW = as_double("mc_bal_cold"); //[kWht/K-MWt] The heat capacity of the balance of plant on the cold side c_trough.m_mc_bal_sca = as_double("mc_bal_sca"); //[Wht/K-m] Non-HTF heat capacity associated with each SCA - per meter basis //[m] The collector aperture width (Total structural area.. used for shadowing) size_t nval_W_aperture = 0; ssc_number_t *W_aperture = as_array("W_aperture", &nval_W_aperture); c_trough.m_W_aperture.resize(nval_W_aperture); for (size_t i = 0; i < nval_W_aperture; i++) c_trough.m_W_aperture[i] = (double)W_aperture[i]; //[m^2] Reflective aperture area of the collector size_t nval_A_aperture = 0; ssc_number_t *A_aperture = as_array("A_aperture", &nval_A_aperture); c_trough.m_A_aperture.resize(nval_A_aperture); for (size_t i = 0; i < nval_A_aperture; i++) c_trough.m_A_aperture[i] = (double)A_aperture[i]; //[-] Tracking error derate size_t nval_TrackingError = 0; ssc_number_t *TrackingError = as_array("TrackingError", &nval_TrackingError); c_trough.m_TrackingError.resize(nval_TrackingError); for (size_t i = 0; i < nval_TrackingError; i++) c_trough.m_TrackingError[i] = (double)TrackingError[i]; //[-] Geometry effects derate size_t nval_GeomEffects = 0; ssc_number_t *GeomEffects = as_array("GeomEffects", &nval_GeomEffects); c_trough.m_GeomEffects.resize(nval_GeomEffects); for (size_t i = 0; i < nval_GeomEffects; i++) c_trough.m_GeomEffects[i] = (double)GeomEffects[i]; //[-] Clean mirror reflectivity size_t nval_Rho_mirror_clean = 0; ssc_number_t *Rho_mirror_clean = as_array("Rho_mirror_clean", &nval_Rho_mirror_clean); c_trough.m_Rho_mirror_clean.resize(nval_Rho_mirror_clean); for (size_t i = 0; i < nval_Rho_mirror_clean; i++) c_trough.m_Rho_mirror_clean[i] = (double)Rho_mirror_clean[i]; //[-] Dirt on mirror derate size_t nval_Dirt_mirror = 0; ssc_number_t *Dirt_mirror = as_array("Dirt_mirror", &nval_Dirt_mirror); c_trough.m_Dirt_mirror.resize(nval_Dirt_mirror); for (size_t i = 0; i < nval_Dirt_mirror; i++) c_trough.m_Dirt_mirror[i] = (double)Dirt_mirror[i]; //[-] General optical error derate size_t nval_Error = 0; ssc_number_t *Error = as_array("Error", &nval_Error); c_trough.m_Error.resize(nval_Error); for (size_t i = 0; i < nval_Error; i++) c_trough.m_Error[i] = (double)Error[i]; //[m] The average focal length of the collector size_t nval_Ave_Focal_Length = 0; ssc_number_t *Ave_Focal_Length = as_array("Ave_Focal_Length", &nval_Ave_Focal_Length); c_trough.m_Ave_Focal_Length.resize(nval_Ave_Focal_Length); for (size_t i = 0; i < nval_Ave_Focal_Length; i++) c_trough.m_Ave_Focal_Length[i] = (double)Ave_Focal_Length[i]; //[m] The length of the SCA size_t nval_L_SCA = 0; ssc_number_t *L_SCA = as_array("L_SCA", &nval_L_SCA); c_trough.m_L_SCA.resize(nval_L_SCA); for (size_t i = 0; i < nval_L_SCA; i++) c_trough.m_L_SCA[i] = (double)L_SCA[i]; //[m] The length of a single mirror/HCE unit size_t nval_L_aperture = 0; ssc_number_t *L_aperture = as_array("L_aperture", &nval_L_aperture); c_trough.m_L_aperture.resize(nval_L_aperture); for (size_t i = 0; i < nval_L_aperture; i++) c_trough.m_L_aperture[i] = (double)L_aperture[i]; //[-] The number of individual collector sections in an SCA size_t nval_ColperSCA = 0; ssc_number_t *ColperSCA = as_array("ColperSCA", &nval_ColperSCA); c_trough.m_ColperSCA.resize(nval_ColperSCA); for (size_t i = 0; i < nval_ColperSCA; i++) c_trough.m_ColperSCA[i] = (double)ColperSCA[i]; //[m] Piping distance between SCA's in the field size_t nval_Distance_SCA = 0; ssc_number_t *Distance_SCA = as_array("Distance_SCA", &nval_Distance_SCA); c_trough.m_Distance_SCA.resize(nval_Distance_SCA); for (size_t i = 0; i < nval_Distance_SCA; i++) c_trough.m_Distance_SCA[i] = (double)Distance_SCA[i]; c_trough.m_IAM_matrix = as_matrix("IAM_matrix"); //[-] IAM coefficients, matrix for 4 collectors // Why are these matrices - can't they be arrays? c_trough.m_HCE_FieldFrac = as_matrix("HCE_FieldFrac"); //[-] Fraction of the field occupied by this HCE type c_trough.m_D_2 = as_matrix("D_2"); //[m] Inner absorber tube diameter c_trough.m_D_3 = as_matrix("D_3"); //[m] Outer absorber tube diameter c_trough.m_D_4 = as_matrix("D_4"); //[m] Inner glass envelope diameter c_trough.m_D_5 = as_matrix("D_5"); //[m] Outer glass envelope diameter c_trough.m_D_p = as_matrix("D_p"); //[m] Diameter of the absorber flow plug (optional) c_trough.m_Flow_type = as_matrix("Flow_type"); //[-] Flow type through the absorber c_trough.m_Rough = as_matrix("Rough"); //[-] Relative roughness of the internal HCE surface c_trough.m_alpha_env = as_matrix("alpha_env"); //[-] Envelope absorptance // ********************************************************** // Emittance vs. temperature profile for each receiver type and variation c_trough.m_epsilon_3_11 = as_matrix_transpose("epsilon_3_11"); //[-] Absorber emittance for receiver type 1 variation 1 c_trough.m_epsilon_3_12 = as_matrix_transpose("epsilon_3_12"); //[-] Absorber emittance for receiver type 1 variation 2 c_trough.m_epsilon_3_13 = as_matrix_transpose("epsilon_3_13"); //[-] Absorber emittance for receiver type 1 variation 3 c_trough.m_epsilon_3_14 = as_matrix_transpose("epsilon_3_14"); //[-] Absorber emittance for receiver type 1 variation 4 c_trough.m_epsilon_3_21 = as_matrix_transpose("epsilon_3_21"); //[-] Absorber emittance for receiver type 2 variation 1 c_trough.m_epsilon_3_22 = as_matrix_transpose("epsilon_3_22"); //[-] Absorber emittance for receiver type 2 variation 2 c_trough.m_epsilon_3_23 = as_matrix_transpose("epsilon_3_23"); //[-] Absorber emittance for receiver type 2 variation 3 c_trough.m_epsilon_3_24 = as_matrix_transpose("epsilon_3_24"); //[-] Absorber emittance for receiver type 2 variation 4 c_trough.m_epsilon_3_31 = as_matrix_transpose("epsilon_3_31"); //[-] Absorber emittance for receiver type 3 variation 1 c_trough.m_epsilon_3_32 = as_matrix_transpose("epsilon_3_32"); //[-] Absorber emittance for receiver type 3 variation 2 c_trough.m_epsilon_3_33 = as_matrix_transpose("epsilon_3_33"); //[-] Absorber emittance for receiver type 3 variation 3 c_trough.m_epsilon_3_34 = as_matrix_transpose("epsilon_3_34"); //[-] Absorber emittance for receiver type 3 variation 4 c_trough.m_epsilon_3_41 = as_matrix_transpose("epsilon_3_41"); //[-] Absorber emittance for receiver type 4 variation 1 c_trough.m_epsilon_3_42 = as_matrix_transpose("epsilon_3_42"); //[-] Absorber emittance for receiver type 4 variation 2 c_trough.m_epsilon_3_43 = as_matrix_transpose("epsilon_3_43"); //[-] Absorber emittance for receiver type 4 variation 3 c_trough.m_epsilon_3_44 = as_matrix_transpose("epsilon_3_44"); //[-] Absorber emittance for receiver type 4 variation 4 c_trough.m_alpha_abs = as_matrix("alpha_abs"); //[-] Absorber absorptance c_trough.m_Tau_envelope = as_matrix("Tau_envelope"); //[-] Envelope transmittance c_trough.m_EPSILON_4 = as_matrix("EPSILON_4"); //[-] Inner glass envelope emissivities c_trough.m_EPSILON_5 = as_matrix("EPSILON_5"); //[-] Outer glass envelope emissivities //c_trough.m_GlazingIntact = (as_matrix("GlazingIntactIn") > 0); //[-] Glazing intact (broken glass) flag {1=true, else=false} util::matrix_t<double> glazing_intact_double = as_matrix("GlazingIntactIn"); //[-] Is the glazing intact? int n_gl_row = (int)glazing_intact_double.nrows(); int n_gl_col = (int)glazing_intact_double.ncols(); c_trough.m_GlazingIntact.resize(n_gl_row, n_gl_col); for (int i = 0; i < n_gl_row; i++) { for (int j = 0; j < n_gl_col; j++) { c_trough.m_GlazingIntact(i, j) = (glazing_intact_double(i, j) > 0); } } c_trough.m_P_a = as_matrix("P_a"); //[torr] Annulus gas pressure c_trough.m_AnnulusGas = as_matrix("AnnulusGas"); //[-] Annulus gas type (1=air, 26=Ar, 27=H2) c_trough.m_AbsorberMaterial = as_matrix("AbsorberMaterial"); //[-] Absorber material type c_trough.m_Shadowing = as_matrix("Shadowing"); //[-] Receiver bellows shadowing loss factor c_trough.m_Dirt_HCE = as_matrix("Dirt_HCE"); //[-] Loss due to dirt on the receiver envelope c_trough.m_Design_loss = as_matrix("Design_loss"); //[-] Receiver heat loss at design c_trough.m_SCAInfoArray = as_matrix("SCAInfoArray"); //[-] Receiver (,1) and collector (,2) type for each assembly in loop c_trough.m_rec_su_delay = as_double("rec_su_delay"); //[hr] Fixed startup delay time for the receiver c_trough.m_rec_qf_delay = as_double("rec_qf_delay"); //[-] Energy-based receiver startup delay (fraction of rated thermal power) c_trough.m_p_start = as_double("p_start"); //[kWe-hr] Collector startup energy, per SCA c_trough.m_calc_design_pipe_vals = as_boolean("calc_design_pipe_vals"); //[-] Should the HTF state be calculated at design conditions c_trough.m_L_rnr_pb = as_double("L_rnr_pb"); //[m] Length of hot or cold runner pipe around the power block c_trough.m_N_max_hdr_diams = as_double("N_max_hdr_diams"); //[-] Maximum number of allowed diameters in each of the hot and cold headers c_trough.m_L_rnr_per_xpan = as_double("L_rnr_per_xpan"); //[m] Threshold length of straight runner pipe without an expansion loop c_trough.m_L_xpan_hdr = as_double("L_xpan_hdr"); //[m] Combined length in meters of the two perpendicular segments of a header expansion loop c_trough.m_L_xpan_rnr = as_double("L_xpan_rnr"); //[m] Combined length in meters of the two perpendicular segments of a runner expansion loop c_trough.m_Min_rnr_xpans = as_double("Min_rnr_xpans"); //[-] Minimum number of expansion loops per single-diameter runner section c_trough.m_northsouth_field_sep = as_double("northsouth_field_sep"); //[m] Shortest north/south distance between SCAs in different subfields c_trough.m_N_hdr_per_xpan = as_double("N_hdr_per_xpan"); //[-] Number of collector loops per header expansion loops. 1 = expansion loop between every collector loop c_trough.m_offset_xpan_hdr = as_double("offset_xpan_hdr"); //[-] Location of first header expansion loop. 1 = after first collector loop c_trough.m_K_cpnt = as_matrix("K_cpnt"); //[-] Minor loss coefficients of the components in each loop interconnect c_trough.m_D_cpnt = as_matrix("D_cpnt"); //[m] Inner diameters of the components in each loop interconnect c_trough.m_L_cpnt = as_matrix("L_cpnt"); //[m] Lengths of the components in each loop interconnect c_trough.m_Type_cpnt = as_matrix("Type_cpnt"); //[-] Type of component in each loop interconnect [0=fitting | 1=pipe | 2=flex_hose] c_trough.m_custom_sf_pipe_sizes = as_boolean("custom_sf_pipe_sizes"); //[-] Should the field pipe diameters, wall thickness and lengths be imported instead of calculated c_trough.m_sf_rnr_diams = as_matrix("sf_rnr_diams"); //[m] Imported runner diameters, used if custom_sf_pipe_sizes is true c_trough.m_sf_rnr_wallthicks = as_matrix("sf_rnr_wallthicks"); //[m] Imported runner wall thicknesses, used if custom_sf_pipe_sizes is true c_trough.m_sf_rnr_lengths = as_matrix("sf_rnr_lengths"); //[m] Imported runner lengths, used if custom_sf_pipe_sizes is true c_trough.m_sf_hdr_diams = as_matrix("sf_hdr_diams"); //[m] Imported header diameters, used if custom_sf_pipe_sizes is true c_trough.m_sf_hdr_wallthicks = as_matrix("sf_hdr_wallthicks"); //[m] Imported header wall thicknesses, used if custom_sf_pipe_sizes is true c_trough.m_sf_hdr_lengths = as_matrix("sf_hdr_lengths"); //[m] Imported header lengths, used if custom_sf_pipe_sizes is true //[-] Collector defocus order size_t nval_SCADefocusArray = 0; ssc_number_t *SCADefocusArray = as_array("SCADefocusArray", &nval_SCADefocusArray); c_trough.m_SCADefocusArray.resize(nval_SCADefocusArray); for (size_t i = 0; i < nval_SCADefocusArray; i++) c_trough.m_SCADefocusArray[i] = (int)SCADefocusArray[i]; // Allocate trough outputs c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_THETA_AVE, allocate("Theta_ave", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_COSTH_AVE, allocate("CosTh_ave", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_IAM_AVE, allocate("IAM_ave", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_ROWSHADOW_AVE, allocate("RowShadow_ave", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_ENDLOSS_AVE, allocate("EndLoss_ave", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_DNI_COSTH, allocate("dni_costh", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_EQUIV_OPT_ETA_TOT, allocate("EqOpteff", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_DEFOCUS, allocate("SCAs_def", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_Q_DOT_INC_SF_TOT, allocate("q_inc_sf_tot", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_Q_DOT_INC_SF_COSTH, allocate("qinc_costh", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_Q_DOT_REC_INC, allocate("q_dot_rec_inc", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_Q_DOT_REC_THERMAL_LOSS, allocate("q_dot_rec_thermal_loss", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_Q_DOT_REC_ABS, allocate("q_dot_rec_abs", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_Q_DOT_PIPING_LOSS, allocate("q_dot_piping_loss", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_E_DOT_INTERNAL_ENERGY, allocate("e_dot_field_int_energy", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_Q_DOT_HTF_OUT, allocate("q_dot_htf_sf_out", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_Q_DOT_FREEZE_PROT, allocate("q_dot_freeze_prot", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_M_DOT_LOOP, allocate("m_dot_loop", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_IS_RECIRCULATING, allocate("recirculating", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_M_DOT_FIELD_RECIRC, allocate("m_dot_field_recirc", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_M_DOT_FIELD_DELIVERED, allocate("m_dot_field_delivered", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_T_FIELD_COLD_IN, allocate("T_field_cold_in", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_T_REC_COLD_IN, allocate("T_rec_cold_in", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_T_REC_HOT_OUT, allocate("T_rec_hot_out", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_T_FIELD_HOT_OUT, allocate("T_field_hot_out", n_steps_fixed), n_steps_fixed); c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_PRESSURE_DROP, allocate("deltaP_field", n_steps_fixed), n_steps_fixed); //[bar] c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_W_DOT_SCA_TRACK, allocate("W_dot_sca_track", n_steps_fixed), n_steps_fixed); //[MWe] c_trough.mc_reported_outputs.assign(C_csp_trough_collector_receiver::E_W_DOT_PUMP, allocate("W_dot_field_pump", n_steps_fixed), n_steps_fixed); //[MWe] // ******************************** // ******************************** // Power cycle // ******************************** // ******************************** C_csp_power_cycle * p_csp_power_cycle; // Steam Rankine and User Defined power cycle classes C_pc_Rankine_indirect_224 rankine_pc; int pb_tech_type = as_integer("pc_config"); if ( !(pb_tech_type == 0 || pb_tech_type == 1) ) // 0 = Rankine, 1 = UDPC { throw exec_error("trough_physical", "unsupported power cycle"); } else { C_pc_Rankine_indirect_224::S_params *pc = &rankine_pc.ms_params; pc->m_P_ref = as_double("P_ref"); pc->m_eta_ref = as_double("eta_ref"); pc->m_T_htf_hot_ref = as_double("T_loop_out"); pc->m_T_htf_cold_ref = as_double("T_loop_in_des"); pc->m_cycle_max_frac = as_double("cycle_max_frac"); pc->m_cycle_cutoff_frac = as_double("cycle_cutoff_frac"); pc->m_q_sby_frac = as_double("q_sby_frac"); pc->m_startup_time = as_double("startup_time"); pc->m_startup_frac = as_double("startup_frac"); pc->m_htf_pump_coef = as_double("pb_pump_coef"); pc->m_pc_fl = as_integer("Fluid"); // power cycle HTF is same as receiver HTF pc->m_pc_fl_props = as_matrix("field_fl_props"); pc->DP_SGS = as_double("DP_SGS"); if (pb_tech_type == 0) { pc->m_dT_cw_ref = as_double("dT_cw_ref"); pc->m_T_amb_des = as_double("T_amb_des"); pc->m_P_boil = as_double("P_boil"); pc->m_CT = as_integer("CT"); // cooling tech type: 1=evaporative, 2=air, 3=hybrid pc->m_tech_type = as_integer("tech_type"); // turbine inlet pressure: 1: Fixed, 3: Sliding if (pc->m_tech_type == 1) { pc->m_tech_type = 2; }; // changing fixed pressure for the tower to fixed pressure for the trough if (pc->m_tech_type == 3) { pc->m_tech_type = 8; }; // changing sliding pressure for the tower to sliding pressure for the trough if (!(pc->m_tech_type == 2 || pc->m_tech_type == 5 || pc->m_tech_type == 6 || pc->m_tech_type == 8)) { std::string tech_msg = util::format("tech_type must be either 2 (fixed pressure) or 8 (sliding). Input was %d." " Simulation proceeded with fixed pressure", pc->m_tech_type); pc->m_tech_type = 2; } pc->m_T_approach = as_double("T_approach"); pc->m_T_ITD_des = as_double("T_ITD_des"); pc->m_P_cond_ratio = as_double("P_cond_ratio"); pc->m_pb_bd_frac = as_double("pb_bd_frac"); pc->m_P_cond_min = as_double("P_cond_min"); pc->m_n_pl_inc = as_integer("n_pl_inc"); size_t n_F_wc = 0; ssc_number_t *p_F_wc = as_array("F_wc", &n_F_wc); pc->m_F_wc.resize(n_F_wc, 0.0); for (size_t i = 0; i < n_F_wc; i++) pc->m_F_wc[i] = (double)p_F_wc[i]; pc->m_is_user_defined_pc = false; pc->m_W_dot_cooling_des = std::numeric_limits<double>::quiet_NaN(); } else if (pb_tech_type == 1) { pc->m_is_user_defined_pc = true; // User-Defined Cycle Parameters pc->m_W_dot_cooling_des = as_double("ud_f_W_dot_cool_des") / 100.0*as_double("P_ref"); //[MWe] pc->m_m_dot_water_des = as_double("ud_m_dot_water_cool_des"); //[kg/s] // User-Defined Cycle Off-Design Tables pc->mc_combined_ind = as_matrix("ud_ind_od"); } // Set pointer to parent class p_csp_power_cycle = &rankine_pc; // Set power cycle outputs common to all power cycle technologies p_csp_power_cycle->assign(C_pc_Rankine_indirect_224::E_ETA_THERMAL, allocate("eta", n_steps_fixed), n_steps_fixed); p_csp_power_cycle->assign(C_pc_Rankine_indirect_224::E_Q_DOT_HTF, allocate("q_pb", n_steps_fixed), n_steps_fixed); p_csp_power_cycle->assign(C_pc_Rankine_indirect_224::E_M_DOT_HTF, allocate("m_dot_pc", n_steps_fixed), n_steps_fixed); p_csp_power_cycle->assign(C_pc_Rankine_indirect_224::E_Q_DOT_STARTUP, allocate("q_dot_pc_startup", n_steps_fixed), n_steps_fixed); p_csp_power_cycle->assign(C_pc_Rankine_indirect_224::E_W_DOT, allocate("P_cycle", n_steps_fixed), n_steps_fixed); p_csp_power_cycle->assign(C_pc_Rankine_indirect_224::E_T_HTF_IN, allocate("T_pc_in", n_steps_fixed), n_steps_fixed); p_csp_power_cycle->assign(C_pc_Rankine_indirect_224::E_T_HTF_OUT, allocate("T_pc_out", n_steps_fixed), n_steps_fixed); p_csp_power_cycle->assign(C_pc_Rankine_indirect_224::E_M_DOT_WATER, allocate("m_dot_water_pc", n_steps_fixed), n_steps_fixed); } // ******************************** // ******************************** // TES // ******************************** // ******************************** C_csp_two_tank_tes storage; C_csp_two_tank_tes::S_params *tes = &storage.ms_params; tes->m_field_fl = c_trough.m_Fluid; //[-] tes->m_field_fl_props = c_trough.m_field_fl_props; //[-] tes->m_tes_fl = as_integer("store_fluid"); //[-] tes->m_tes_fl_props = as_matrix("store_fl_props"); //[-] tes->m_is_hx = as_boolean("is_hx"); //[-] tes->m_W_dot_pc_design = as_double("P_ref"); //[MWt] tes->m_eta_pc = as_double("eta_ref"); //[-] tes->m_solarm = as_double("solar_mult"); //[-] tes->m_ts_hours = as_double("tshours"); //[hr] tes->m_h_tank = as_double("h_tank"); //[m] tes->m_u_tank = as_double("u_tank"); //[W/m^2-K] tes->m_tank_pairs = as_integer("tank_pairs"); //[-] tes->m_hot_tank_Thtr = as_double("hot_tank_Thtr"); //[C] tes->m_hot_tank_max_heat = as_double("hot_tank_max_heat"); //[MWe] tes->m_cold_tank_Thtr = as_double("cold_tank_Thtr"); //[C] tes->m_cold_tank_max_heat = as_double("cold_tank_max_heat"); //[MWe] tes->m_dt_hot = as_double("dt_hot"); //[C] //tes->m_dt_cold = as_double("dt_cold"); //[C] tes->m_T_field_in_des = T_loop_in_des; //[C] tes->m_T_field_out_des = T_loop_out_des; //[C] tes->m_T_tank_hot_ini = T_loop_out_des; //[C] tes->m_T_tank_cold_ini = T_loop_in_des; //[C] tes->m_h_tank_min = as_double("h_tank_min"); //[m] tes->m_f_V_hot_ini = as_double("init_hot_htf_percent"); //[-] tes->m_htf_pump_coef = as_double("pb_pump_coef"); //[kWe/kg/s] tes->m_tes_pump_coef = as_double("tes_pump_coef"); //[kWe/kg/s] tes->eta_pump = as_double("eta_pump"); //[-] tes->tanks_in_parallel = as_boolean("tanks_in_parallel"); //[-] tes->has_hot_tank_bypass = as_boolean("has_hot_tank_bypass"); //[-] tes->T_tank_hot_inlet_min = as_double("T_tank_hot_inlet_min"); //[C] tes->V_tes_des = as_double("V_tes_des"); //[m/s] tes->custom_tes_p_loss = as_boolean("custom_tes_p_loss"); //[-] tes->k_tes_loss_coeffs = as_matrix("k_tes_loss_coeffs"); //[-] tes->custom_tes_pipe_sizes = as_boolean("custom_tes_pipe_sizes"); //[-] tes->tes_diams = as_matrix("tes_diams"); //[m] tes->tes_wallthicks = as_matrix("tes_wallthicks"); //[m] tes->calc_design_pipe_vals = as_boolean("calc_design_pipe_vals"); //[-] tes->pipe_rough = as_double("HDR_rough"); //[m] tes->DP_SGS = as_double("DP_SGS"); //[bar] if (is_assigned("tes_lengths")) { tes->tes_lengths = as_matrix("tes_lengths"); //[m] } if (!is_assigned("tes_lengths") || tes->tes_lengths.ncells() < 11) { double vals1[11] = { 0., 90., 100., 120., 0., 30., 90., 80., 80., 120., 80. }; tes->tes_lengths.assign(vals1, 11); } // Set storage outputs storage.mc_reported_outputs.assign(C_csp_two_tank_tes::E_Q_DOT_LOSS, allocate("tank_losses", n_steps_fixed), n_steps_fixed); storage.mc_reported_outputs.assign(C_csp_two_tank_tes::E_W_DOT_HEATER, allocate("q_tes_heater", n_steps_fixed), n_steps_fixed); storage.mc_reported_outputs.assign(C_csp_two_tank_tes::E_TES_T_HOT, allocate("T_tes_hot", n_steps_fixed), n_steps_fixed); storage.mc_reported_outputs.assign(C_csp_two_tank_tes::E_TES_T_COLD, allocate("T_tes_cold", n_steps_fixed), n_steps_fixed); storage.mc_reported_outputs.assign(C_csp_two_tank_tes::E_M_DOT_TANK_TO_TANK, allocate("m_dot_cold_tank_to_hot_tank", n_steps_fixed), n_steps_fixed); storage.mc_reported_outputs.assign(C_csp_two_tank_tes::E_MASS_COLD_TANK, allocate("mass_tes_cold", n_steps_fixed), n_steps_fixed); storage.mc_reported_outputs.assign(C_csp_two_tank_tes::E_MASS_HOT_TANK, allocate("mass_tes_hot", n_steps_fixed), n_steps_fixed); // ******************************** // ******************************** // TOU // ******************************** // ******************************** C_csp_tou_block_schedules tou; C_csp_tou_block_schedules::S_params *tou_params = &tou.ms_params; tou_params->mc_csp_ops.mc_weekdays = as_matrix("weekday_schedule"); tou_params->mc_csp_ops.mc_weekends = as_matrix("weekend_schedule"); tou_params->mc_pricing.mc_weekdays = as_matrix("dispatch_sched_weekday"); tou_params->mc_pricing.mc_weekends = as_matrix("dispatch_sched_weekend"); if (tou_params->mc_pricing.mc_weekdays.ncells() == 1) { // Resize default value from var table to proper dimensions tou_params->mc_pricing.mc_weekdays = util::matrix_t<double>(12, 24, 1.0); } if (tou_params->mc_pricing.mc_weekends.ncells() == 1) { // Resize default value from var table to proper dimensions tou_params->mc_pricing.mc_weekends = util::matrix_t<double>(12, 24, 1.0); } tou.mc_dispatch_params.m_dispatch_optimize = as_boolean("is_dispatch"); tou.mc_dispatch_params.m_is_write_ampl_dat = as_boolean("is_write_ampl_dat"); tou.mc_dispatch_params.m_is_ampl_engine = as_boolean("is_ampl_engine"); tou.mc_dispatch_params.m_ampl_data_dir = as_string("ampl_data_dir"); tou.mc_dispatch_params.m_ampl_exec_call = as_string("ampl_exec_call"); if (tou.mc_dispatch_params.m_dispatch_optimize) { tou.mc_dispatch_params.m_optimize_frequency = as_integer("disp_frequency"); tou.mc_dispatch_params.m_disp_steps_per_hour = as_integer("disp_steps_per_hour"); tou.mc_dispatch_params.m_optimize_horizon = as_integer("disp_horizon"); tou.mc_dispatch_params.m_max_iterations = as_integer("disp_max_iter"); tou.mc_dispatch_params.m_solver_timeout = as_double("disp_timeout"); tou.mc_dispatch_params.m_mip_gap = as_double("disp_mip_gap"); tou.mc_dispatch_params.m_presolve_type = as_integer("disp_spec_presolve"); tou.mc_dispatch_params.m_bb_type = as_integer("disp_spec_bb"); tou.mc_dispatch_params.m_disp_reporting = as_integer("disp_reporting"); tou.mc_dispatch_params.m_scaling_type = as_integer("disp_spec_scaling"); tou.mc_dispatch_params.m_disp_time_weighting = as_double("disp_time_weighting"); tou.mc_dispatch_params.m_rsu_cost = as_double("disp_rsu_cost"); tou.mc_dispatch_params.m_csu_cost = as_double("disp_csu_cost"); tou.mc_dispatch_params.m_pen_delta_w = as_double("disp_pen_delta_w"); tou.mc_dispatch_params.m_q_rec_standby = as_double("q_rec_standby"); tou.mc_dispatch_params.m_w_rec_ht = as_double("q_rec_heattrace"); if (as_boolean("is_wlim_series")) { size_t n_wlim_series = 0; ssc_number_t* wlim_series = as_array("wlim_series", &n_wlim_series); if ((int)n_wlim_series != n_wf_records) throw exec_error("trough_physical", "Invalid net electricity generation limit series dimension. Matrix must have " + util::to_string(n_wf_records) + " rows."); for (int i = 0; i < n_wf_records; i++) tou.mc_dispatch_params.m_w_lim_full.at(i) = (double)wlim_series[i]; } } tou.mc_dispatch_params.m_is_tod_pc_target_also_pc_max = as_boolean("is_tod_pc_target_also_pc_max"); tou.mc_dispatch_params.m_is_block_dispatch = !tou.mc_dispatch_params.m_dispatch_optimize; //mw tou.mc_dispatch_params.m_use_rule_1 = true; tou.mc_dispatch_params.m_standby_off_buffer = 2.0; tou.mc_dispatch_params.m_use_rule_2 = false; tou.mc_dispatch_params.m_q_dot_rec_des_mult = -1.23; tou.mc_dispatch_params.m_f_q_dot_pc_overwrite = -1.23; size_t n_f_turbine = 0; ssc_number_t *p_f_turbine = as_array("f_turb_tou_periods", &n_f_turbine); tou_params->mc_csp_ops.mvv_tou_arrays[C_block_schedule_csp_ops::TURB_FRAC].resize(n_f_turbine, 0.0); //tou_params->mv_t_frac.resize(n_f_turbine, 0.0); for (size_t i = 0; i < n_f_turbine; i++) tou_params->mc_csp_ops.mvv_tou_arrays[C_block_schedule_csp_ops::TURB_FRAC][i] = (double)p_f_turbine[i]; bool is_timestep_input = (as_integer("ppa_multiplier_model") == 1); tou_params->mc_pricing.mv_is_diurnal = !(is_timestep_input); if (is_timestep_input) { size_t nmultipliers; ssc_number_t *multipliers = as_array("dispatch_factors_ts", &nmultipliers); tou_params->mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE].resize(nmultipliers, 0.0); for (size_t ii = 0; ii < nmultipliers; ii++) tou_params->mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][ii] = multipliers[ii]; } else // standard diuranal input { tou_params->mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE].resize(9, 0.0); tou_params->mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][0] = as_double("dispatch_factor1"); tou_params->mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][1] = as_double("dispatch_factor2"); tou_params->mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][2] = as_double("dispatch_factor3"); tou_params->mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][3] = as_double("dispatch_factor4"); tou_params->mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][4] = as_double("dispatch_factor5"); tou_params->mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][5] = as_double("dispatch_factor6"); tou_params->mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][6] = as_double("dispatch_factor7"); tou_params->mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][7] = as_double("dispatch_factor8"); tou_params->mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][8] = as_double("dispatch_factor9"); } // System parameters C_csp_solver::S_csp_system_params system; system.m_pb_fixed_par = as_double("pb_fixed_par"); size_t nval_bop_array = 0; ssc_number_t *bop_array = as_array("bop_array", &nval_bop_array); if (nval_bop_array != 5) throw exec_error("trough_physical", "Should be 5 elements in bop_array, has " + util::to_string((int)nval_bop_array) + "."); system.m_bop_par = bop_array[0]; //as_double("bop_par"); system.m_bop_par_f = bop_array[1]; //as_double("bop_par_f"); system.m_bop_par_0 = bop_array[2]; //as_double("bop_par_0"); system.m_bop_par_1 = bop_array[3]; //as_double("bop_par_1"); system.m_bop_par_2 = bop_array[4]; //as_double("bop_par_2"); // Instantiate Solver C_csp_solver csp_solver(weather_reader, c_trough, *p_csp_power_cycle, storage, tou, system, ssc_cmod_update, (void*)(this)); // Set solver reporting outputs // Simulation Kernel csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::TIME_FINAL, allocate("time_hr", n_steps_fixed), n_steps_fixed); // Weather reader csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::MONTH, allocate("month", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::HOUR_DAY, allocate("hour_day", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::SOLAZ, allocate("solazi", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::SOLZEN, allocate("solzen", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::BEAM, allocate("beam", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::TDRY, allocate("tdry", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::TWET, allocate("twet", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::RH, allocate("RH", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::WSPD, allocate("wspd", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::PRES, allocate("pres", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::CR_DEFOCUS, allocate("defocus", n_steps_fixed), n_steps_fixed); // TES csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::TES_Q_DOT_DC, allocate("q_dc_tes", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::TES_Q_DOT_CH, allocate("q_ch_tes", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::TES_E_CH_STATE, allocate("e_ch_tes", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::M_DOT_CR_TO_TES_HOT, allocate("m_dot_cr_to_tes_hot", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::M_DOT_TES_HOT_OUT, allocate("m_dot_tes_hot_out", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::M_DOT_PC_TO_TES_COLD, allocate("m_dot_pc_to_tes_cold", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::M_DOT_TES_COLD_OUT, allocate("m_dot_tes_cold_out", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::M_DOT_FIELD_TO_CYCLE, allocate("m_dot_field_to_cycle", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::M_DOT_CYCLE_TO_FIELD, allocate("m_dot_cycle_to_field", n_steps_fixed), n_steps_fixed); // System csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::COL_W_DOT_TRACK, allocate("pparasi", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::SYS_W_DOT_PUMP, allocate("htf_pump_power", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::PC_W_DOT_COOLING, allocate("P_cooling_tower_tot", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::SYS_W_DOT_FIXED, allocate("P_fixed", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::SYS_W_DOT_BOP, allocate("P_plant_balance_tot", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::W_DOT_NET, allocate("P_out_net", n_steps_fixed), n_steps_fixed); // Controller csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::OP_MODE_1, allocate("op_mode_1", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::OP_MODE_2, allocate("op_mode_2", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::OP_MODE_3, allocate("op_mode_3", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::ERR_M_DOT, allocate("m_dot_balance", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::ERR_Q_DOT, allocate("q_balance", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::N_OP_MODES, allocate("n_op_modes", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::TOU_PERIOD, allocate("tou_value", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::PRICING_MULT, allocate("pricing_mult", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::PC_Q_DOT_SB, allocate("q_dot_pc_sb", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::PC_Q_DOT_MIN, allocate("q_dot_pc_min", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::PC_Q_DOT_TARGET, allocate("q_dot_pc_target", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::PC_Q_DOT_MAX, allocate("q_dot_pc_max", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::CTRL_IS_REC_SU, allocate("is_rec_su_allowed", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::CTRL_IS_PC_SU, allocate("is_pc_su_allowed", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::CTRL_IS_PC_SB, allocate("is_pc_sb_allowed", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::EST_Q_DOT_CR_SU, allocate("q_dot_est_cr_su", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::EST_Q_DOT_CR_ON, allocate("q_dot_est_cr_on", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::EST_Q_DOT_DC, allocate("q_dot_est_tes_dc", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::EST_Q_DOT_CH, allocate("q_dot_est_tes_ch", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::CTRL_OP_MODE_SEQ_A, allocate("operating_modes_a", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::CTRL_OP_MODE_SEQ_B, allocate("operating_modes_b", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::CTRL_OP_MODE_SEQ_C, allocate("operating_modes_c", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_SOLVE_STATE, allocate("disp_solve_state", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_SOLVE_ITER, allocate("disp_solve_iter", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_SOLVE_OBJ, allocate("disp_objective", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_SOLVE_OBJ_RELAX, allocate("disp_obj_relax", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_QSF_EXPECT, allocate("disp_qsf_expected", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_QSFPROD_EXPECT, allocate("disp_qsfprod_expected", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_QSFSU_EXPECT, allocate("disp_qsfsu_expected", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_TES_EXPECT, allocate("disp_tes_expected", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_PCEFF_EXPECT, allocate("disp_pceff_expected", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_SFEFF_EXPECT, allocate("disp_thermeff_expected", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_QPBSU_EXPECT, allocate("disp_qpbsu_expected", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_WPB_EXPECT, allocate("disp_wpb_expected", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_REV_EXPECT, allocate("disp_rev_expected", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_PRES_NCONSTR, allocate("disp_presolve_nconstr", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_PRES_NVAR, allocate("disp_presolve_nvar", n_steps_fixed), n_steps_fixed); csp_solver.mc_reported_outputs.assign(C_csp_solver::C_solver_outputs::DISPATCH_SOLVE_TIME, allocate("disp_solve_time", n_steps_fixed), n_steps_fixed); update("Initialize physical trough model...", 0.0); int out_type = -1; std::string out_msg = ""; try { // Initialize Solver csp_solver.init(); } catch( C_csp_exception &csp_exception ) { // Report warning before exiting with error while( csp_solver.mc_csp_messages.get_message(&out_type, &out_msg) ) { log(out_msg, out_type); } throw exec_error("trough_physical", csp_exception.m_error_message); } // If no exception, then report messages while (csp_solver.mc_csp_messages.get_message(&out_type, &out_msg)) { log(out_msg, out_type); } //if the pricing schedule is provided as hourly, overwrite the tou schedule if (as_boolean("is_dispatch_series")) { size_t n_dispatch_series; ssc_number_t *dispatch_series = as_array("dispatch_series", &n_dispatch_series); //if( n_dispatch_series != n_steps_fixed) // throw exec_error("trough_physical", "Invalid dispatch pricing series dimension. Array length must match number of simulation time steps ("+my_to_string(n_steps_fixed)+")."); //resize the m_hr_tou array if (tou_params->mc_pricing.m_hr_tou != 0) delete[] tou_params->mc_pricing.m_hr_tou; tou_params->mc_pricing.m_hr_tou = new double[n_steps_fixed]; //set the tou period as unique for each time step for (int i = 0; i < n_steps_fixed; i++) tou_params->mc_pricing.m_hr_tou[i] = i + 1; //allocate reported arrays tou_params->mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE].resize(n_steps_fixed); for (int i = 0; i < n_steps_fixed; i++) tou_params->mc_pricing.mvv_tou_arrays[C_block_schedule_pricing::MULT_PRICE][i] = dispatch_series[i]; } update("Begin timeseries simulation...", 0.0); std::clock_t clock_start = std::clock(); try { // Simulate ! csp_solver.Ssimulate(sim_setup); } catch( C_csp_exception &csp_exception ) { // Report warning before exiting with error while( csp_solver.mc_csp_messages.get_message(&out_type, &out_msg) ) { log(out_msg); } throw exec_error("trough_physical", csp_exception.m_error_message); } // If no exception, then report messages while( csp_solver.mc_csp_messages.get_message(&out_type, &out_msg) ) { log(out_msg, out_type); } std::clock_t clock_end = std::clock(); double sim_duration = (clock_end - clock_start) / (double)CLOCKS_PER_SEC; //[s] assign("sim_duration", (ssc_number_t)sim_duration); // Do unit post-processing here double *p_q_pc_startup = allocate("q_pc_startup", n_steps_fixed); size_t count_pc_su = 0; ssc_number_t *p_q_dot_pc_startup = as_array("q_dot_pc_startup", &count_pc_su); if ((int)count_pc_su != n_steps_fixed) { log("q_dot_pc_startup array is a different length than 'n_steps_fixed'.", SSC_WARNING); return; } for (int i = 0; i < n_steps_fixed; i++) { p_q_pc_startup[i] = (float)(p_q_dot_pc_startup[i] * (sim_setup.m_report_step / 3600.0)); //[MWh] } // Convert mass flow rates from [kg/hr] to [kg/s] size_t count_m_dot_pc, count_m_dot_water_pc; //count_m_dot_rec, count_m_dot_tes_dc, count_m_dot_tes_ch; count_m_dot_pc = count_m_dot_water_pc = 0; //count_m_dot_rec = count_m_dot_tes_dc = count_m_dot_tes_ch = 0; ssc_number_t *p_m_dot_pc = as_array("m_dot_pc", &count_m_dot_pc); ssc_number_t *p_m_dot_water_pc = as_array("m_dot_water_pc", &count_m_dot_water_pc); //ssc_number_t *p_m_dot_tes_dc = as_array("m_dot_tes_dc", &count_m_dot_tes_dc); //ssc_number_t *p_m_dot_tes_ch = as_array("m_dot_tes_ch", &count_m_dot_tes_ch); if ((int)count_m_dot_pc != n_steps_fixed || (int)count_m_dot_water_pc != n_steps_fixed) //|| count_m_dot_rec != n_steps_fixed || count_m_dot_tes_dc != n_steps_fixed || count_m_dot_tes_ch != n_steps_fixed) { log("At least one m_dot array is a different length than 'n_steps_fixed'.", SSC_WARNING); return; } for (int i = 0; i < n_steps_fixed; i++) { //p_m_dot_rec[i] = (ssc_number_t)(p_m_dot_rec[i] / 3600.0); //[kg/s] convert from kg/hr p_m_dot_pc[i] = (ssc_number_t)(p_m_dot_pc[i] / 3600.0); //[kg/s] convert from kg/hr p_m_dot_water_pc[i] = (ssc_number_t)(p_m_dot_water_pc[i] / 3600.0); //[kg/s] convert from kg/hr //p_m_dot_tes_dc[i] = (ssc_number_t)(p_m_dot_tes_dc[i] / 3600.0); //[kg/s] convert from kg/hr //p_m_dot_tes_ch[i] = (ssc_number_t)(p_m_dot_tes_ch[i] / 3600.0); //[kg/s] convert from kg/hr } size_t count; ssc_number_t *p_W_dot_net = as_array("P_out_net", &count); ssc_number_t *p_time_final_hr = as_array("time_hr", &count); if((int)count != n_steps_fixed) throw exec_error("trough_physical", "The number of fixed steps does not match the length of output data arrays"); // 'adjustment_factors' class stores factors in hourly array, so need to index as such adjustment_factors haf(this, "adjust"); if( !haf.setup() ) throw exec_error("trough_physical", "failed to setup adjustment factors: " + haf.error()); ssc_number_t *p_gen = allocate("gen", n_steps_fixed); //ssc_number_t *p_W_dot_par_tot_haf = allocate("W_dot_par_tot_haf", n_steps_fixed); ssc_number_t *p_q_dot_defocus_est = allocate("q_dot_defocus_est", n_steps_fixed); //ssc_number_t *p_W_dot_parasitic_tot = as_array("W_dot_parasitic_tot", &count); //if (count != n_steps_fixed) // throw exec_error("trough_physical", "The number of fixed steps does not match the length of output data arrays1"); ssc_number_t *p_SCAs_def = as_array("SCAs_def", &count); if ((int)count != n_steps_fixed) throw exec_error("trough_physical", "The number of fixed steps does not match the length of output data arrays2"); ssc_number_t *p_q_dot_htf_sf_out = as_array("q_dot_htf_sf_out", &count); if ((int)count != n_steps_fixed) throw exec_error("trough_physical", "The number of fixed steps does not match the length of output data arrays3"); //ssc_number_t *p_m_dot_tes_dc = as_array("m_dot_tes_dc", &count); //if ((int)count != n_steps_fixed) // throw exec_error("trough_physical", "The number of fixed steps for 'm_dot_tes_dc' does not match the length of output data arrays"); // //ssc_number_t *p_m_dot_tes_ch = as_array("m_dot_tes_ch", &count); //if ((int)count != n_steps_fixed) // throw exec_error("trough_physical", "The number of fixed steps for 'm_dot_tes_ch' does not match the length of output data arrays"); for(int i = 0; i < n_steps_fixed; i++) { size_t hour = (size_t)ceil(p_time_final_hr[i]); p_gen[i] = (ssc_number_t)(p_W_dot_net[i] * haf(hour) * 1.E3); //[kWe] //p_W_dot_parasitic_tot[i] *= -1.0; //[kWe] Label is total parasitics, so change to a positive value //p_W_dot_par_tot_haf[i] = (ssc_number_t)(p_W_dot_parasitic_tot[i] * haf(hour) * 1.E3); //[kWe] p_q_dot_defocus_est[i] = (ssc_number_t)(1.0 - p_SCAs_def[i])*p_q_dot_htf_sf_out[i]; //[MWt] //p_m_dot_tes_dc[i] = (ssc_number_t)(p_m_dot_tes_dc[i] / 3600.0); //[kg/s] convert from kg/hr //p_m_dot_tes_ch[i] = (ssc_number_t)(p_m_dot_tes_ch[i] / 3600.0); //[kg/s] convert from kg/hr } ssc_number_t* p_annual_energy_dist_time = gen_heatmap(this, steps_per_hour); // Non-timeseries array outputs double P_adj = storage.P_in_des; // slightly adjust all field design pressures to account for pressure drop in TES before hot tank transform(c_trough.m_P_rnr_dsn.begin(), c_trough.m_P_rnr_dsn.end(), c_trough.m_P_rnr_dsn.begin(), [P_adj](double x) {return x + P_adj; }); transform(c_trough.m_P_hdr_dsn.begin(), c_trough.m_P_hdr_dsn.end(), c_trough.m_P_hdr_dsn.begin(), [P_adj](double x) {return x + P_adj; }); transform(c_trough.m_P_loop_dsn.begin(), c_trough.m_P_loop_dsn.end(), c_trough.m_P_loop_dsn.begin(), [P_adj](double x) {return x + P_adj; }); ssc_number_t *p_pipe_runner_diams = allocate("pipe_runner_diams", c_trough.m_D_runner.size()); std::copy(c_trough.m_D_runner.begin(), c_trough.m_D_runner.end(), p_pipe_runner_diams); ssc_number_t *p_pipe_runner_wallthk = allocate("pipe_runner_wallthk", c_trough.m_WallThk_runner.size()); std::copy(c_trough.m_WallThk_runner.begin(), c_trough.m_WallThk_runner.end(), p_pipe_runner_wallthk); ssc_number_t *p_pipe_runner_lengths = allocate("pipe_runner_lengths", c_trough.m_L_runner.size()); std::copy(c_trough.m_L_runner.begin(), c_trough.m_L_runner.end(), p_pipe_runner_lengths); ssc_number_t *p_pipe_runner_expansions = allocate("pipe_runner_expansions", c_trough.m_N_rnr_xpans.size()); std::copy(c_trough.m_N_rnr_xpans.begin(), c_trough.m_N_rnr_xpans.end(), p_pipe_runner_expansions); ssc_number_t *p_pipe_runner_mdot_dsn = allocate("pipe_runner_mdot_dsn", c_trough.m_m_dot_rnr_dsn.size()); std::copy(c_trough.m_m_dot_rnr_dsn.begin(), c_trough.m_m_dot_rnr_dsn.end(), p_pipe_runner_mdot_dsn); ssc_number_t *p_pipe_runner_vel_dsn = allocate("pipe_runner_vel_dsn", c_trough.m_V_rnr_dsn.size()); std::copy(c_trough.m_V_rnr_dsn.begin(), c_trough.m_V_rnr_dsn.end(), p_pipe_runner_vel_dsn); ssc_number_t *p_pipe_runner_T_dsn = allocate("pipe_runner_T_dsn", c_trough.m_T_rnr_dsn.size()); std::copy(c_trough.m_T_rnr_dsn.begin(), c_trough.m_T_rnr_dsn.end(), p_pipe_runner_T_dsn); ssc_number_t *p_pipe_runner_P_dsn = allocate("pipe_runner_P_dsn", c_trough.m_P_rnr_dsn.size()); std::copy(c_trough.m_P_rnr_dsn.begin(), c_trough.m_P_rnr_dsn.end(), p_pipe_runner_P_dsn); ssc_number_t *p_pipe_header_diams = allocate("pipe_header_diams", c_trough.m_D_hdr.size()); std::copy(c_trough.m_D_hdr.begin(), c_trough.m_D_hdr.end(), p_pipe_header_diams); ssc_number_t *p_pipe_header_wallthk = allocate("pipe_header_wallthk", c_trough.m_WallThk_hdr.size()); std::copy(c_trough.m_WallThk_hdr.begin(), c_trough.m_WallThk_hdr.end(), p_pipe_header_wallthk); ssc_number_t *p_pipe_header_lengths = allocate("pipe_header_lengths", c_trough.m_L_hdr.size()); std::copy(c_trough.m_L_hdr.begin(), c_trough.m_L_hdr.end(), p_pipe_header_lengths); ssc_number_t *p_pipe_header_expansions = allocate("pipe_header_expansions", c_trough.m_N_hdr_xpans.size()); std::copy(c_trough.m_N_hdr_xpans.begin(), c_trough.m_N_hdr_xpans.end(), p_pipe_header_expansions); ssc_number_t *p_pipe_header_mdot_dsn = allocate("pipe_header_mdot_dsn", c_trough.m_m_dot_hdr_dsn.size()); std::copy(c_trough.m_m_dot_hdr_dsn.begin(), c_trough.m_m_dot_hdr_dsn.end(), p_pipe_header_mdot_dsn); ssc_number_t *p_pipe_header_vel_dsn = allocate("pipe_header_vel_dsn", c_trough.m_V_hdr_dsn.size()); std::copy(c_trough.m_V_hdr_dsn.begin(), c_trough.m_V_hdr_dsn.end(), p_pipe_header_vel_dsn); ssc_number_t *p_pipe_header_T_dsn = allocate("pipe_header_T_dsn", c_trough.m_T_hdr_dsn.size()); std::copy(c_trough.m_T_hdr_dsn.begin(), c_trough.m_T_hdr_dsn.end(), p_pipe_header_T_dsn); ssc_number_t *p_pipe_header_P_dsn = allocate("pipe_header_P_dsn", c_trough.m_P_hdr_dsn.size()); std::copy(c_trough.m_P_hdr_dsn.begin(), c_trough.m_P_hdr_dsn.end(), p_pipe_header_P_dsn); ssc_number_t *p_pipe_loop_T_dsn = allocate("pipe_loop_T_dsn", c_trough.m_T_loop_dsn.size()); std::copy(c_trough.m_T_loop_dsn.begin(), c_trough.m_T_loop_dsn.end(), p_pipe_loop_T_dsn); ssc_number_t *p_pipe_loop_P_dsn = allocate("pipe_loop_P_dsn", c_trough.m_P_loop_dsn.size()); std::copy(c_trough.m_P_loop_dsn.begin(), c_trough.m_P_loop_dsn.end(), p_pipe_loop_P_dsn); ssc_number_t *p_pipe_tes_diams = allocate("pipe_tes_diams", storage.pipe_diams.ncells()); std::copy(storage.pipe_diams.data(), storage.pipe_diams.data() + storage.pipe_diams.ncells(), p_pipe_tes_diams); ssc_number_t *p_pipe_tes_wallthk = allocate("pipe_tes_wallthk", storage.pipe_wall_thk.ncells()); std::copy(storage.pipe_wall_thk.data(), storage.pipe_wall_thk.data() + storage.pipe_wall_thk.ncells(), p_pipe_tes_wallthk); ssc_number_t* p_pipe_tes_lengths = allocate("pipe_tes_lengths", storage.pipe_lengths.ncells()); std::copy(storage.pipe_lengths.data(), storage.pipe_lengths.data() + storage.pipe_lengths.ncells(), p_pipe_tes_lengths); ssc_number_t *p_pipe_tes_mdot_dsn = allocate("pipe_tes_mdot_dsn", storage.pipe_m_dot_des.ncells()); std::copy(storage.pipe_m_dot_des.data(), storage.pipe_m_dot_des.data() + storage.pipe_m_dot_des.ncells(), p_pipe_tes_mdot_dsn); ssc_number_t *p_pipe_tes_vel_dsn = allocate("pipe_tes_vel_dsn", storage.pipe_vel_des.ncells()); std::copy(storage.pipe_vel_des.data(), storage.pipe_vel_des.data() + storage.pipe_vel_des.ncells(), p_pipe_tes_vel_dsn); ssc_number_t *p_pipe_tes_T_dsn = allocate("pipe_tes_T_dsn", storage.pipe_T_des.ncells()); std::copy(storage.pipe_T_des.data(), storage.pipe_T_des.data() + storage.pipe_T_des.ncells(), p_pipe_tes_T_dsn); ssc_number_t *p_pipe_tes_P_dsn = allocate("pipe_tes_P_dsn", storage.pipe_P_des.ncells()); std::copy(storage.pipe_P_des.data(), storage.pipe_P_des.data() + storage.pipe_P_des.ncells(), p_pipe_tes_P_dsn); // Monthly outputs accumulate_monthly_for_year("gen", "monthly_energy", sim_setup.m_report_step / 3600.0, steps_per_hour, 1); // Annual outputs accumulate_annual_for_year("gen", "annual_energy", sim_setup.m_report_step / 3600.0, steps_per_hour, 1, n_steps_fixed / steps_per_hour); accumulate_annual_for_year("P_cycle", "annual_W_cycle_gross", 1000.0*sim_setup.m_report_step / 3600.0, steps_per_hour, 1, n_steps_fixed / steps_per_hour); //[kWe-hr] //accumulate_annual_for_year("W_dot_par_tot_haf", "annual_electricity_consumption", sim_setup.m_report_step/3600.0, steps_per_hour); //[kWe-hr] accumulate_annual_for_year("disp_objective", "disp_objective_ann", 1000.0*sim_setup.m_report_step / 3600.0, steps_per_hour, 1, n_steps_fixed / steps_per_hour); accumulate_annual_for_year("disp_solve_iter", "disp_iter_ann", 1000.0*sim_setup.m_report_step / 3600.0, steps_per_hour, 1, n_steps_fixed / steps_per_hour); accumulate_annual_for_year("disp_presolve_nconstr", "disp_presolve_nconstr_ann", sim_setup.m_report_step / 3600.0 / as_double("disp_frequency"), steps_per_hour, 1, n_steps_fixed / steps_per_hour); accumulate_annual_for_year("disp_presolve_nvar", "disp_presolve_nvar_ann", sim_setup.m_report_step / 3600.0 / as_double("disp_frequency"), steps_per_hour, 1, n_steps_fixed / steps_per_hour); accumulate_annual_for_year("disp_solve_time", "disp_solve_time_ann", sim_setup.m_report_step / 3600. / as_double("disp_frequency"), steps_per_hour, 1, n_steps_fixed / steps_per_hour); accumulate_annual_for_year("q_dc_tes", "annual_q_dc_tes", sim_setup.m_report_step / 3600.0, steps_per_hour, 1, n_steps_fixed / steps_per_hour); accumulate_annual_for_year("q_ch_tes", "annual_q_ch_tes", sim_setup.m_report_step / 3600.0, steps_per_hour, 1, n_steps_fixed / steps_per_hour); ssc_number_t annual_field_fp = accumulate_annual_for_year("q_dot_freeze_prot", "annual_field_freeze_protection", sim_setup.m_report_step / 3600.0*1.E3, steps_per_hour); //[kWt-hr] ssc_number_t annual_tes_fp = accumulate_annual_for_year("q_tes_heater", "annual_tes_freeze_protection", sim_setup.m_report_step / 3600.0*1.E3, steps_per_hour); //[kWt-hr] ssc_number_t annual_thermal_consumption = annual_field_fp + annual_tes_fp; //[kWt-hr] assign("annual_thermal_consumption", annual_thermal_consumption); // Calculate water use // First, sum power cycle water consumption timeseries outputs accumulate_annual_for_year("m_dot_water_pc", "annual_total_water_use", sim_setup.m_report_step / 1000.0, steps_per_hour, 1, n_steps_fixed / steps_per_hour); //[m^3], convert from kg ssc_number_t V_water_cycle = as_number("annual_total_water_use"); // Then, add water usage from mirror cleaning double A_aper_tot = csp_solver.get_cr_aperture_area(); //[m2] double V_water_mirrors = as_double("water_usage_per_wash")/1000.0*A_aper_tot*as_double("washing_frequency"); assign("annual_total_water_use", (ssc_number_t)(V_water_mirrors + V_water_cycle)); //[m3] ssc_number_t ae = as_number("annual_energy"); ssc_number_t pg = as_number("annual_W_cycle_gross"); ssc_number_t convfactor = (pg != 0) ? 100 * ae / pg : (ssc_number_t)0.0; assign("conversion_factor", convfactor); double kWh_per_kW = 0.0; double system_capacity = as_double("P_ref") * as_double("gross_net_conversion_factor") *1.E3; //[kWe] double nameplate = system_capacity; //[kWe] if (nameplate > 0.0) kWh_per_kW = ae / nameplate; assign("capacity_factor", (ssc_number_t)(kWh_per_kW / ((double)n_steps_fixed / (double)steps_per_hour)*100.)); assign("kwh_per_kw", (ssc_number_t)kWh_per_kW); } }; DEFINE_MODULE_ENTRY(trough_physical, "Physical trough applications", 1)
// Copyright (c) 2011-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. /** * See https://www.boost.org/doc/libs/1_71_0/libs/test/doc/html/boost_test/utf_reference/link_references/link_boost_test_module_macro.html */ #define BOOST_TEST_MODULE Baddcoin Core Test Suite #include <boost/test/unit_test.hpp> #include <test/util/setup_common.h> #include <iostream> /** Redirect debug log to unit_test.log files */ const std::function<void(const std::string&)> G_TEST_LOG_FUN = [](const std::string& s) { static const bool should_log{std::any_of( &boost::unit_test::framework::master_test_suite().argv[1], &boost::unit_test::framework::master_test_suite().argv[boost::unit_test::framework::master_test_suite().argc], [](const char* arg) { return std::string{"DEBUG_LOG_OUT"} == arg; })}; if (!should_log) return; std::cout << s; };
#include "common.hpp" #include "io/bulkio.hpp" #include "module.hpp" #include <unordered_map> TEST(Module, open) { Module m(io::read_all(DATADIR "/mod_files/test0.mod"), "test0.mod"); if (!m.buffer().size()) { std::cout << "skipping Module.open test because unable to open input file" << std::endl; return; } Lexer lexer(m.buffer()); auto t = lexer.parse(); while (t.type != tok::eof) { t = lexer.parse(); EXPECT_NE(t.type, tok::reserved); } } TEST(Module, ion_deps) { Module m(io::read_all(DATADIR "/mod_files/test0.mod"), "test0.mod"); EXPECT_NE(m.buffer().size(), 0); Parser p(m, false); EXPECT_TRUE(p.parse()); EXPECT_TRUE(m.has_ion("k")); auto k_dep = m.find_ion("k"); EXPECT_TRUE(k_dep->writes_current()); EXPECT_TRUE(k_dep->uses_current()); EXPECT_FALSE(k_dep->uses_rev_potential()); EXPECT_TRUE(k_dep->uses_concentration_int()); EXPECT_FALSE(k_dep->uses_concentration_ext()); EXPECT_TRUE(k_dep->writes_current()); EXPECT_FALSE(k_dep->writes_concentration_int()); EXPECT_FALSE(k_dep->writes_concentration_ext()); EXPECT_FALSE(k_dep->writes_rev_potential()); EXPECT_FALSE(k_dep->uses_valence()); EXPECT_FALSE(k_dep->verifies_valence()); EXPECT_TRUE(m.has_ion("ca")); auto ca_dep = m.find_ion("ca"); EXPECT_FALSE(ca_dep->writes_current()); EXPECT_FALSE(ca_dep->uses_current()); EXPECT_FALSE(ca_dep->uses_rev_potential()); EXPECT_TRUE(ca_dep->uses_concentration_int()); EXPECT_FALSE(ca_dep->uses_concentration_ext()); EXPECT_FALSE(ca_dep->writes_current()); EXPECT_FALSE(ca_dep->writes_concentration_int()); EXPECT_FALSE(ca_dep->writes_concentration_ext()); EXPECT_FALSE(ca_dep->writes_rev_potential()); EXPECT_FALSE(ca_dep->uses_valence()); EXPECT_FALSE(ca_dep->verifies_valence()); } TEST(Module, identifiers) { Module m(io::read_all(DATADIR "/mod_files/test0.mod"), "test0.mod"); EXPECT_NE(m.buffer().size(), 0); Parser p(m, false); EXPECT_TRUE(p.parse()); std::unordered_map<std::string, std::pair<std::string, bool>> expected{ {"cai", {"", false}}, {"vhalfh", {"mV", true}}, {"q10", {"", true}}, {"gkbar", {"mho / cm2", false}}}; for (const auto& parm: m.parameter_block().parameters) { auto it = expected.find(parm.name()); if (it != expected.end()) { const auto& [units, rangep] = it->second; EXPECT_EQ(units, parm.unit_string()); EXPECT_EQ(rangep, parm.has_range()); } } } TEST(Module, linear_mechanisms) { for (int i = 1; i < 6; i++) { auto file_name = "test" + std::to_string(i) + ".mod"; Module m(io::read_all(DATADIR "/mod_files/" + file_name), file_name); if (!m.buffer().size()) { std::cout << "skipping Module.open test because unable to open input file" << std::endl; return; } Parser p(m, false); if (!p.parse()) { std::cout << "problem with parsing input file" << std::endl; return; } m.semantic(); if (i < 3) { EXPECT_TRUE(m.is_linear()); } else { EXPECT_FALSE(m.is_linear()); } } } TEST(Module, breakpoint) { // Test function call in BREAKPOINT block Module m(io::read_all(DATADIR "/mod_files/test8.mod"), "test8.mod"); EXPECT_NE(m.buffer().size(), 0); Parser p(m, false); EXPECT_TRUE(p.parse()); EXPECT_TRUE(m.semantic()); }
#include <stdio.h> #include <unistd.h> #include <termios.h> #include <iostream> #include <fstream> #include <sys/select.h> #include <openservo.h> #include <vector> #include <algorithm> #include <yaml-cpp/yaml.h> using namespace std; using namespace openservo; float hardcoded_factors[] = {0.0009380807, 0.0009349769, 0.0009304994, 0.0008597145, 0.0008597145, 0.0008597145}; typedef struct motor_calibration { int min; int max; int center; float factor; int addr; int id; int position; int delta; vector<int> measurements; } motor_calibration; bool compare (const motor_calibration& i, const motor_calibration& j) { return (i.id < j.id); } vector<motor_calibration> motors; int wait_key() { fd_set readSet; FD_ZERO(&readSet); FD_SET(STDIN_FILENO, &readSet); struct timeval tv = {0, 25}; if (select(STDIN_FILENO+1, &readSet, NULL, NULL, &tv) < 0) perror("select"); if (!FD_ISSET(STDIN_FILENO, &readSet)) return -1; unsigned char c; c = getchar(); return c; } void print_motor(const motor_calibration& motor) { cout << "ID: " << motor.id << " Addr: " << motor.addr << " Pos: " << motor.position << " Min:" << motor.min << " Max:" << motor.max << endl; } int update_state(ServoBus& bus, vector<motor_calibration>& motors) { bus.update(); for (int i = 0; i < motors.size(); i++) { if (motors[i].id > -1) continue; ServoHandler sv = bus.find(motors[i].addr); motors[i].measurements.push_back(sv->getPosition()); if (motors[i].measurements.size() > 20) { std::nth_element(motors[i].measurements.begin(), motors[i].measurements.begin() + motors[i].measurements.size()/2, motors[i].measurements.end()); int position = motors[i].measurements[motors[i].measurements.size()/2]; motors[i].min = std::min(motors[i].min, position); motors[i].max = std::max(motors[i].max, position); motors[i].delta += abs(motors[i].position - position); motors[i].position = position; motors[i].center = position; print_motor(motors[i]); motors[i].measurements.clear(); } } } int main(int argc, char** argv) { ServoBus bus; struct termios old_tio, new_tio; if (argc < 2 || !bus.open(argv[1])) { cout << "Unable to connect to i2c bus" << endl; return -1; } cout << "Welcome to OpenServo manipulator calibration utility" << endl; int n = bus.scan(); cout << "Found " << n << " motors\n"; if (argc < 3) { motors.resize(n); for (int i = 0; i < n; i++) { motors[i].min = 1000000; motors[i].max = -1000000; motors[i].center = 0; motors[i].factor = 0; motors[i].addr = bus.get(i)->getAddress(); motors[i].id = -1; } /* get the terminal settings for stdin */ tcgetattr(STDIN_FILENO,&old_tio); /* we want to keep the old setting to restore them a the end */ new_tio = old_tio; /* disable canonical mode (buffered i/o) and local echo */ new_tio.c_lflag &=(~ICANON & ~ECHO); /* set the new settings immediately */ tcsetattr(STDIN_FILENO,TCSANOW,&new_tio); int m = 0; while (m < n) { cout << "Please move motor " << m << " to both extreme positions and then to center position and press any key." << endl; while (wait_key() < 0) { update_state(bus, motors); } int candidate = -1; int max_delta = 0; for (int i = 0; i < n; i++) { int delta = motors[i].delta; motors[i].delta = 0; if (motors[i].id > -1) continue; if (delta > max_delta) { max_delta = delta; candidate = i; } } motors[candidate].id = m; m++; } /* restore the former settings */ tcsetattr(STDIN_FILENO,TCSANOW,&old_tio); } else { YAML::Node doc = YAML::LoadFile(argv[2]); cout << "Loaded " << doc.size() << endl; for (int i = 0; i < doc.size(); i++) { motor_calibration d; d.id = i; d.addr = doc[i]["id"].as<int>(); d.min = doc[i]["min"].as<int>(); d.max = doc[i]["max"].as<int>(); d.center = doc[i]["center"].as<int>(); d.factor = doc[i]["factor"].as<float>(); motors.push_back(d); } } cout << "Writing data to motors" << endl; for (int i = 0; i < motors.size(); i++) { motors[i].max = min(motors[i].max, 4096 - 16); motors[i].min = max(motors[i].min, 16); cout << "Writing data to motor " << i << endl; ServoHandler sv = bus.find(motors[i].addr); sv->unlock(); sv->set("seek.max", motors[i].max); sv->set("seek.min", motors[i].min); bus.update(); sv->registersCommit(); } cout << "Verifying ... " << endl; bus.update(true); for (int i = 0; i < motors.size(); i++) { ServoHandler sv = bus.find(motors[i].addr); cout << "Motor " << motors[i].addr << " min: " << sv->getMinSeek() << " max: " << sv->getMaxSeek() << endl; } std::sort(motors.begin(), motors.end(), compare); YAML::Node sequence; // starts out as null for (int i = 0; i < n; i++) { YAML::Node motor; motor["id"] = motors[i].addr; motor["min"] = motors[i].min; motor["max"] = motors[i].max; motor["center"] = motors[i].center; motor["factor"] = hardcoded_factors[i]; sequence.push_back(motor); } cout << sequence << endl; }
/// https://github.com/Rominitch/MouCaLab /// \author Rominitch /// \license No license #include "Dependencies.h" #include "LibVulkan/include/VKCommand.h" #include "LibVulkan/include/VKCommandBuffer.h" #include "LibVulkan/include/VKCommandPool.h" #include "LibVulkan/include/VKDescriptorSet.h" #include "LibVulkan/include/VKDevice.h" #include "LibVulkan/include/VKFrameBuffer.h" #include "LibVulkan/include/VKMesh.h" #include "LibVulkan/include/VKGraphicsPipeline.h" #include "LibVulkan/include/VKRenderPass.h" #include "LibVulkan/include/VKSurfaceFormat.h" #include "LibVulkan/include/VKSwapChain.h" namespace Vulkan { ICommandBuffer::ICommandBuffer(): _usage(0) {} void ICommandBuffer::executeCommand(const ExecuteCommands& executer, const VkCommandBufferResetFlags reset) const { MOUCA_PRE_CONDITION(!isNull()); //DEV Issue: missing to call initialize; MOUCA_PRE_CONDITION(!_commands.empty()); //DEV Issue: missing to call registerCommands; // Reset if (vkResetCommandBuffer(executer.commandBuffer, reset) != VK_SUCCESS) { MOUCA_THROW_ERROR(u8"Vulkan", u8"CommandBufferResetError"); } const VkCommandBufferBeginInfo cmdBufferBeginInfo { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // VkStructureType sType nullptr, // const void *pNext _usage, // VkCommandBufferUsageFlags flags nullptr // const VkCommandBufferInheritanceInfo *pInheritanceInfo }; // Begin if (vkBeginCommandBuffer(executer.commandBuffer, &cmdBufferBeginInfo) != VK_SUCCESS) { MOUCA_THROW_ERROR(u8"Vulkan", u8"CommandBufferBeginError"); } // Execute all commands for (const auto& command : _commands) { command->execute(executer); } // End if (vkEndCommandBuffer(executer.commandBuffer) != VK_SUCCESS) { MOUCA_THROW_ERROR(u8"Vulkan", u8"CommandBufferEndError"); } } CommandBuffer::CommandBuffer(): _commandBuffer(VK_NULL_HANDLE) { MOUCA_ASSERT(isNull()); } CommandBuffer::~CommandBuffer() { MOUCA_ASSERT(isNull()); } void CommandBuffer::initialize(const Device& device, const CommandPoolSPtr pool, const VkCommandBufferLevel level, const VkCommandBufferUsageFlags usage) { MOUCA_PRE_CONDITION(isNull()); //DEV Issue: Already initialize ? MOUCA_PRE_CONDITION(!device.isNull()); //DEV Issue: Bad device ? MOUCA_PRE_CONDITION(!pool->isNull()); //DEV Issue: Bad pool ? // Copy data _usage = usage; _pool = pool; // Create command Buffer const VkCommandBufferAllocateInfo cmdBufferAllocateInfo { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, // VkStructureType sType nullptr, // const void* pNext pool->getInstance(), // VkCommandPool commandPool level, // VkCommandBufferLevel level 1 // uint32_t bufferCount }; // Allocate if (vkAllocateCommandBuffers(device.getInstance(), &cmdBufferAllocateInfo, &_commandBuffer) != VK_SUCCESS) { MOUCA_THROW_ERROR(u8"Vulkan", u8"CommandBufferCreationError"); } MOUCA_POST_CONDITION(!isNull()); //DEV Issue: Not initialize ? } void CommandBuffer::release(const Device& device) { MOUCA_PRE_CONDITION(!isNull()); //DEV Issue: Not initialize ? MOUCA_PRE_CONDITION(!_pool.expired()); //DEV Issue: Pool was delete before command. // Delete command buffer vkFreeCommandBuffers(device.getInstance(), _pool.lock()->getInstance(), 1, &_commandBuffer); // Remove memory about commands _commands.clear(); _commandBuffer = VK_NULL_HANDLE; _pool.reset(); MOUCA_POST_CONDITION(isNull()); //DEV Issue: Still alive ? } void CommandBuffer::registerCommands(Commands&& commands) { MOUCA_PRE_CONDITION(!commands.empty()); //DEV Issue: insert no command ? _commands = std::move(commands); } void CommandBuffer::addCommands(Commands&& commands) { MOUCA_PRE_CONDITION(!commands.empty()); //DEV Issue: insert no command ? _commands.insert(_commands.end(), std::make_move_iterator(commands.begin()), std::make_move_iterator(commands.end())); } void CommandBuffer::addCommand(CommandUPtr&& command) { MOUCA_PRE_CONDITION(command != nullptr); //DEV Issue: insert no command ? _commands.emplace_back(std::move(command)); } void CommandBuffer::execute(const VkCommandBufferResetFlags reset) const { executeCommand({ _commandBuffer, 0 }, reset); } }
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/vod/model/CreateUploadAttachedMediaRequest.h> using AlibabaCloud::Vod::Model::CreateUploadAttachedMediaRequest; CreateUploadAttachedMediaRequest::CreateUploadAttachedMediaRequest() : RpcServiceRequest("vod", "2017-03-21", "CreateUploadAttachedMedia") { setMethod(HttpRequest::Method::Post); } CreateUploadAttachedMediaRequest::~CreateUploadAttachedMediaRequest() {} std::string CreateUploadAttachedMediaRequest::getIcon()const { return icon_; } void CreateUploadAttachedMediaRequest::setIcon(const std::string& icon) { icon_ = icon; setParameter("Icon", icon); } std::string CreateUploadAttachedMediaRequest::getDescription()const { return description_; } void CreateUploadAttachedMediaRequest::setDescription(const std::string& description) { description_ = description; setParameter("Description", description); } std::string CreateUploadAttachedMediaRequest::getFileSize()const { return fileSize_; } void CreateUploadAttachedMediaRequest::setFileSize(const std::string& fileSize) { fileSize_ = fileSize; setParameter("FileSize", fileSize); } std::string CreateUploadAttachedMediaRequest::getTitle()const { return title_; } void CreateUploadAttachedMediaRequest::setTitle(const std::string& title) { title_ = title; setParameter("Title", title); } std::string CreateUploadAttachedMediaRequest::getAccessKeyId()const { return accessKeyId_; } void CreateUploadAttachedMediaRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); } std::string CreateUploadAttachedMediaRequest::getBusinessType()const { return businessType_; } void CreateUploadAttachedMediaRequest::setBusinessType(const std::string& businessType) { businessType_ = businessType; setParameter("BusinessType", businessType); } std::string CreateUploadAttachedMediaRequest::getStorageLocation()const { return storageLocation_; } void CreateUploadAttachedMediaRequest::setStorageLocation(const std::string& storageLocation) { storageLocation_ = storageLocation; setParameter("StorageLocation", storageLocation); } std::string CreateUploadAttachedMediaRequest::getUserData()const { return userData_; } void CreateUploadAttachedMediaRequest::setUserData(const std::string& userData) { userData_ = userData; setParameter("UserData", userData); } long CreateUploadAttachedMediaRequest::getCateId()const { return cateId_; } void CreateUploadAttachedMediaRequest::setCateId(long cateId) { cateId_ = cateId; setParameter("CateId", std::to_string(cateId)); } std::string CreateUploadAttachedMediaRequest::getCateIds()const { return cateIds_; } void CreateUploadAttachedMediaRequest::setCateIds(const std::string& cateIds) { cateIds_ = cateIds; setParameter("CateIds", cateIds); } std::string CreateUploadAttachedMediaRequest::getTags()const { return tags_; } void CreateUploadAttachedMediaRequest::setTags(const std::string& tags) { tags_ = tags; setParameter("Tags", tags); } std::string CreateUploadAttachedMediaRequest::getMediaExt()const { return mediaExt_; } void CreateUploadAttachedMediaRequest::setMediaExt(const std::string& mediaExt) { mediaExt_ = mediaExt; setParameter("MediaExt", mediaExt); } std::string CreateUploadAttachedMediaRequest::getFileName()const { return fileName_; } void CreateUploadAttachedMediaRequest::setFileName(const std::string& fileName) { fileName_ = fileName; setParameter("FileName", fileName); } std::string CreateUploadAttachedMediaRequest::getAppId()const { return appId_; } void CreateUploadAttachedMediaRequest::setAppId(const std::string& appId) { appId_ = appId; setParameter("AppId", appId); }
//===--- DeclOpenMP.cpp - Declaration OpenMP AST Node Implementation ------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// /// \file /// This file implements OMPThreadPrivateDecl, OMPCapturedExprDecl /// classes. /// //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclBase.h" #include "clang/AST/DeclOpenMP.h" #include "clang/AST/Expr.h" using namespace clang; //===----------------------------------------------------------------------===// // OMPThreadPrivateDecl Implementation. //===----------------------------------------------------------------------===// void OMPThreadPrivateDecl::anchor() { } OMPThreadPrivateDecl *OMPThreadPrivateDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, ArrayRef<Expr *> VL) { OMPThreadPrivateDecl *D = new (C, DC, additionalSizeToAlloc<Expr *>(VL.size())) OMPThreadPrivateDecl(OMPThreadPrivate, DC, L); D->NumVars = VL.size(); D->setVars(VL); return D; } OMPThreadPrivateDecl *OMPThreadPrivateDecl::CreateDeserialized(ASTContext &C, unsigned ID, unsigned N) { OMPThreadPrivateDecl *D = new (C, ID, additionalSizeToAlloc<Expr *>(N)) OMPThreadPrivateDecl(OMPThreadPrivate, nullptr, SourceLocation()); D->NumVars = N; return D; } void OMPThreadPrivateDecl::setVars(ArrayRef<Expr *> VL) { assert(VL.size() == NumVars && "Number of variables is not the same as the preallocated buffer"); std::uninitialized_copy(VL.begin(), VL.end(), getTrailingObjects<Expr *>()); } //===----------------------------------------------------------------------===// // OMPRequiresDecl Implementation. //===----------------------------------------------------------------------===// void OMPRequiresDecl::anchor() {} OMPRequiresDecl *OMPRequiresDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, ArrayRef<OMPClause *> CL) { OMPRequiresDecl *D = new (C, DC, additionalSizeToAlloc<OMPClause *>(CL.size())) OMPRequiresDecl(OMPRequires, DC, L); D->NumClauses = CL.size(); D->setClauses(CL); return D; } OMPRequiresDecl *OMPRequiresDecl::CreateDeserialized(ASTContext &C, unsigned ID, unsigned N) { OMPRequiresDecl *D = new (C, ID, additionalSizeToAlloc<OMPClause *>(N)) OMPRequiresDecl(OMPRequires, nullptr, SourceLocation()); D->NumClauses = N; return D; } void OMPRequiresDecl::setClauses(ArrayRef<OMPClause *> CL) { assert(CL.size() == NumClauses && "Number of clauses is not the same as the preallocated buffer"); std::uninitialized_copy(CL.begin(), CL.end(), getTrailingObjects<OMPClause *>()); } //===----------------------------------------------------------------------===// // OMPDeclareReductionDecl Implementation. //===----------------------------------------------------------------------===// OMPDeclareReductionDecl::OMPDeclareReductionDecl( Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name, QualType Ty, OMPDeclareReductionDecl *PrevDeclInScope) : ValueDecl(DK, DC, L, Name, Ty), DeclContext(DK), Combiner(nullptr), PrevDeclInScope(PrevDeclInScope) { setInitializer(nullptr, CallInit); } void OMPDeclareReductionDecl::anchor() {} OMPDeclareReductionDecl *OMPDeclareReductionDecl::Create( ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, QualType T, OMPDeclareReductionDecl *PrevDeclInScope) { return new (C, DC) OMPDeclareReductionDecl(OMPDeclareReduction, DC, L, Name, T, PrevDeclInScope); } OMPDeclareReductionDecl * OMPDeclareReductionDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) OMPDeclareReductionDecl( OMPDeclareReduction, /*DC=*/nullptr, SourceLocation(), DeclarationName(), QualType(), /*PrevDeclInScope=*/nullptr); } OMPDeclareReductionDecl *OMPDeclareReductionDecl::getPrevDeclInScope() { return cast_or_null<OMPDeclareReductionDecl>( PrevDeclInScope.get(getASTContext().getExternalSource())); } const OMPDeclareReductionDecl * OMPDeclareReductionDecl::getPrevDeclInScope() const { return cast_or_null<OMPDeclareReductionDecl>( PrevDeclInScope.get(getASTContext().getExternalSource())); } //===----------------------------------------------------------------------===// // OMPCapturedExprDecl Implementation. //===----------------------------------------------------------------------===// void OMPCapturedExprDecl::anchor() {} OMPCapturedExprDecl *OMPCapturedExprDecl::Create(ASTContext &C, DeclContext *DC, IdentifierInfo *Id, QualType T, SourceLocation StartLoc) { return new (C, DC) OMPCapturedExprDecl( C, DC, Id, T, C.getTrivialTypeSourceInfo(T), StartLoc); } OMPCapturedExprDecl *OMPCapturedExprDecl::CreateDeserialized(ASTContext &C, unsigned ID) { return new (C, ID) OMPCapturedExprDecl(C, nullptr, nullptr, QualType(), /*TInfo=*/nullptr, SourceLocation()); } SourceRange OMPCapturedExprDecl::getSourceRange() const { assert(hasInit()); return SourceRange(getInit()->getBeginLoc(), getInit()->getEndLoc()); }
/* * File: CAMS.hpp * Author: Koncord <koncord at rwa.su> * * Created on 10 Апрель 2015 г., 19:08 */ #ifndef CAMS_HPP #define CAMS_HPP #include "../Record.hpp" class RecordCAMS: public Record { public: struct DATA { std::string edid; formid imageSpaceModifier; // FormID of an IMAD record. struct _DATA { uint32_t action; uint32_t location; uint32_t target; uint32_t flags; float playerTimeMult; float targetTimeMult; float globalTimeMult; float maxTime; float minTime; float targetPercentBetweenActors; enum Action { Shoot = 0, Fly, Hit, Zoom }; enum class Location { Attacker = 0, Projectile, Target }; using Target = Location; enum Flag { PositionFollowsLocation = 0x00000001, RotationFollowsTarget = 0x00000002, DontFollowBone = 0x00000004, FirstPersonCamera = 0x00000008, NoTracer = 0x00000010, StartAtTimeZero = 0x00000020 }; } data; } data; explicit RecordCAMS(const RecHeader &head) : Record(head) { Parse(); } RecordCAMS() : Record() { Parse(); } virtual bool DoParse(); }; #endif /* CAMS_HPP */
// Copyright (c) 2018-2021 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/json/ #ifndef TAO_JSON_UTF8_HPP #define TAO_JSON_UTF8_HPP #include <tao/pegtl/memory_input.hpp> #include <tao/pegtl/parse_error.hpp> #include <tao/pegtl/utf8.hpp> namespace tao::json { enum class utf8_mode : bool { check, trust }; namespace internal { template< typename Input > bool consume_utf8_impl( Input& in, const std::size_t todo ) { std::size_t i = 0; while( i < todo ) { const auto p = pegtl::internal::peek_utf8::peek( in ).size; if( ( p == 0 ) || ( ( i += p ) > todo ) ) { return false; } in.bump_in_this_line( p ); } return true; } template< utf8_mode M, typename Input > void consume_utf8_throws( Input& in, const std::size_t todo ) { if constexpr( M == utf8_mode::trust ) { in.bump_in_this_line( todo ); } else if( !consume_utf8_impl( in, todo ) ) { throw pegtl::parse_error( "invalid utf8", in ); } } inline bool validate_utf8_nothrow( const std::string_view sv ) noexcept { pegtl::memory_input in( sv, "validate_utf8" ); return consume_utf8_impl( in, sv.size() ); } } // namespace internal } // namespace tao::json #endif
// Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "base58.h" #include "clientversion.h" #include "coins.h" #include "consensus/consensus.h" #include "core_io.h" #include "keystore.h" #include "policy/policy.h" #include "policy/rbf.h" #include "primitives/transaction.h" #include "script/script.h" #include "script/sign.h" #include <univalue.h> #include "util.h" #include "utilmoneystr.h" #include "utilstrencodings.h" #include <stdio.h> #include <boost/algorithm/string.hpp> static bool fCreateBlank; static std::map<std::string,UniValue> registers; static const int CONTINUE_EXECUTION=-1; // // This function returns either one of EXIT_ codes when it's expected to stop the process or // CONTINUE_EXECUTION when it's expected to continue further. // static int AppInitRawTx(int argc, char* argv[]) { // // Parameters // gArgs.ParseParameters(argc, argv); // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(ChainNameFromCommandLine()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return EXIT_FAILURE; } fCreateBlank = gArgs.GetBoolArg("-create", false); if (argc<2 || gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help")) { // First part of help message is specific to this utility std::string strUsage = strprintf(_("%s troin-tx utility version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n\n" + _("Usage:") + "\n" + " troin-tx [options] <hex-tx> [commands] " + _("Update hex-encoded troin transaction") + "\n" + " troin-tx [options] -create [commands] " + _("Create hex-encoded troin transaction") + "\n" + "\n"; fprintf(stdout, "%s", strUsage.c_str()); strUsage = HelpMessageGroup(_("Options:")); strUsage += HelpMessageOpt("-?", _("This help message")); strUsage += HelpMessageOpt("-create", _("Create new, empty TX.")); strUsage += HelpMessageOpt("-json", _("Select JSON output")); strUsage += HelpMessageOpt("-txid", _("Output only the hex-encoded transaction id of the resultant transaction.")); AppendParamsHelpMessages(strUsage); fprintf(stdout, "%s", strUsage.c_str()); strUsage = HelpMessageGroup(_("Commands:")); strUsage += HelpMessageOpt("delin=N", _("Delete input N from TX")); strUsage += HelpMessageOpt("delout=N", _("Delete output N from TX")); strUsage += HelpMessageOpt("in=TXID:VOUT(:SEQUENCE_NUMBER)", _("Add input to TX")); strUsage += HelpMessageOpt("locktime=N", _("Set TX lock time to N")); strUsage += HelpMessageOpt("nversion=N", _("Set TX version to N")); strUsage += HelpMessageOpt("replaceable(=N)", _("Set RBF opt-in sequence number for input N (if not provided, opt-in all available inputs)")); strUsage += HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX")); strUsage += HelpMessageOpt("outpubkey=VALUE:PUBKEY[:FLAGS]", _("Add pay-to-pubkey output to TX") + ". " + _("Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output") + ". " + _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.")); strUsage += HelpMessageOpt("outdata=[VALUE:]DATA", _("Add data-based output to TX")); strUsage += HelpMessageOpt("outscript=VALUE:SCRIPT[:FLAGS]", _("Add raw script output to TX") + ". " + _("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " + _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.")); strUsage += HelpMessageOpt("outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]", _("Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS") + ". " + _("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " + _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash.")); strUsage += HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " + _("This command requires JSON registers:") + _("prevtxs=JSON object") + ", " + _("privatekeys=JSON object") + ". " + _("See signrawtransaction docs for format of sighash flags, JSON objects.")); fprintf(stdout, "%s", strUsage.c_str()); strUsage = HelpMessageGroup(_("Register Commands:")); strUsage += HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME")); strUsage += HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING")); fprintf(stdout, "%s", strUsage.c_str()); if (argc < 2) { fprintf(stderr, "Error: too few parameters\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } return CONTINUE_EXECUTION; } static void RegisterSetJson(const std::string& key, const std::string& rawJson) { UniValue val; if (!val.read(rawJson)) { std::string strErr = "Cannot parse JSON for key " + key; throw std::runtime_error(strErr); } registers[key] = val; } static void RegisterSet(const std::string& strInput) { // separate NAME:VALUE in string size_t pos = strInput.find(':'); if ((pos == std::string::npos) || (pos == 0) || (pos == (strInput.size() - 1))) throw std::runtime_error("Register input requires NAME:VALUE"); std::string key = strInput.substr(0, pos); std::string valStr = strInput.substr(pos + 1, std::string::npos); RegisterSetJson(key, valStr); } static void RegisterLoad(const std::string& strInput) { // separate NAME:FILENAME in string size_t pos = strInput.find(':'); if ((pos == std::string::npos) || (pos == 0) || (pos == (strInput.size() - 1))) throw std::runtime_error("Register load requires NAME:FILENAME"); std::string key = strInput.substr(0, pos); std::string filename = strInput.substr(pos + 1, std::string::npos); FILE *f = fopen(filename.c_str(), "r"); if (!f) { std::string strErr = "Cannot open file " + filename; throw std::runtime_error(strErr); } // load file chunks into one big buffer std::string valStr; while ((!feof(f)) && (!ferror(f))) { char buf[4096]; int bread = fread(buf, 1, sizeof(buf), f); if (bread <= 0) break; valStr.insert(valStr.size(), buf, bread); } int error = ferror(f); fclose(f); if (error) { std::string strErr = "Error reading file " + filename; throw std::runtime_error(strErr); } // evaluate as JSON buffer register RegisterSetJson(key, valStr); } static CAmount ExtractAndValidateValue(const std::string& strValue) { CAmount value; if (!ParseMoney(strValue, value)) throw std::runtime_error("invalid TX output value"); return value; } static void MutateTxVersion(CMutableTransaction& tx, const std::string& cmdVal) { int64_t newVersion = atoi64(cmdVal); if (newVersion < 1 || newVersion > CTransaction::MAX_STANDARD_VERSION) throw std::runtime_error("Invalid TX version requested"); tx.nVersion = (int) newVersion; } static void MutateTxLocktime(CMutableTransaction& tx, const std::string& cmdVal) { int64_t newLocktime = atoi64(cmdVal); if (newLocktime < 0LL || newLocktime > 0xffffffffLL) throw std::runtime_error("Invalid TX locktime requested"); tx.nLockTime = (unsigned int) newLocktime; } static void MutateTxRBFOptIn(CMutableTransaction& tx, const std::string& strInIdx) { // parse requested index int inIdx = atoi(strInIdx); if (inIdx < 0 || inIdx >= (int)tx.vin.size()) { throw std::runtime_error("Invalid TX input index '" + strInIdx + "'"); } // set the nSequence to MAX_INT - 2 (= RBF opt in flag) int cnt = 0; for (CTxIn& txin : tx.vin) { if (strInIdx == "" || cnt == inIdx) { if (txin.nSequence > MAX_BIP125_RBF_SEQUENCE) { txin.nSequence = MAX_BIP125_RBF_SEQUENCE; } } ++cnt; } } static void MutateTxAddInput(CMutableTransaction& tx, const std::string& strInput) { std::vector<std::string> vStrInputParts; boost::split(vStrInputParts, strInput, boost::is_any_of(":")); // separate TXID:VOUT in string if (vStrInputParts.size()<2) throw std::runtime_error("TX input missing separator"); // extract and validate TXID std::string strTxid = vStrInputParts[0]; if ((strTxid.size() != 64) || !IsHex(strTxid)) throw std::runtime_error("invalid TX input txid"); uint256 txid(uint256S(strTxid)); static const unsigned int minTxOutSz = 9; static const unsigned int maxVout = MAX_BLOCK_WEIGHT / (WITNESS_SCALE_FACTOR * minTxOutSz); // extract and validate vout std::string strVout = vStrInputParts[1]; int vout = atoi(strVout); if ((vout < 0) || (vout > (int)maxVout)) throw std::runtime_error("invalid TX input vout"); // extract the optional sequence number uint32_t nSequenceIn=std::numeric_limits<unsigned int>::max(); if (vStrInputParts.size() > 2) nSequenceIn = std::stoul(vStrInputParts[2]); // append to transaction input list CTxIn txin(txid, vout, CScript(), nSequenceIn); tx.vin.push_back(txin); } static void MutateTxAddOutAddr(CMutableTransaction& tx, const std::string& strInput) { // Separate into VALUE:ADDRESS std::vector<std::string> vStrInputParts; boost::split(vStrInputParts, strInput, boost::is_any_of(":")); if (vStrInputParts.size() != 2) throw std::runtime_error("TX output missing or too many separators"); // Extract and validate VALUE CAmount value = ExtractAndValidateValue(vStrInputParts[0]); // extract and validate ADDRESS std::string strAddr = vStrInputParts[1]; CBitcoinAddress addr(strAddr); if (!addr.IsValid()) throw std::runtime_error("invalid TX output address"); // build standard output script via GetScriptForDestination() CScript scriptPubKey = GetScriptForDestination(addr.Get()); // construct TxOut, append to transaction output list CTxOut txout(value, scriptPubKey); tx.vout.push_back(txout); } static void MutateTxAddOutPubKey(CMutableTransaction& tx, const std::string& strInput) { // Separate into VALUE:PUBKEY[:FLAGS] std::vector<std::string> vStrInputParts; boost::split(vStrInputParts, strInput, boost::is_any_of(":")); if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3) throw std::runtime_error("TX output missing or too many separators"); // Extract and validate VALUE CAmount value = ExtractAndValidateValue(vStrInputParts[0]); // Extract and validate PUBKEY CPubKey pubkey(ParseHex(vStrInputParts[1])); if (!pubkey.IsFullyValid()) throw std::runtime_error("invalid TX output pubkey"); CScript scriptPubKey = GetScriptForRawPubKey(pubkey); // Extract and validate FLAGS bool bSegWit = false; bool bScriptHash = false; if (vStrInputParts.size() == 3) { std::string flags = vStrInputParts[2]; bSegWit = (flags.find("W") != std::string::npos); bScriptHash = (flags.find("S") != std::string::npos); } if (bSegWit) { // Call GetScriptForWitness() to build a P2WSH scriptPubKey scriptPubKey = GetScriptForWitness(scriptPubKey); } if (bScriptHash) { // Get the address for the redeem script, then call // GetScriptForDestination() to construct a P2SH scriptPubKey. CBitcoinAddress redeemScriptAddr(scriptPubKey); scriptPubKey = GetScriptForDestination(redeemScriptAddr.Get()); } // construct TxOut, append to transaction output list CTxOut txout(value, scriptPubKey); tx.vout.push_back(txout); } static void MutateTxAddOutMultiSig(CMutableTransaction& tx, const std::string& strInput) { // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS] std::vector<std::string> vStrInputParts; boost::split(vStrInputParts, strInput, boost::is_any_of(":")); // Check that there are enough parameters if (vStrInputParts.size()<3) throw std::runtime_error("Not enough multisig parameters"); // Extract and validate VALUE CAmount value = ExtractAndValidateValue(vStrInputParts[0]); // Extract REQUIRED uint32_t required = stoul(vStrInputParts[1]); // Extract NUMKEYS uint32_t numkeys = stoul(vStrInputParts[2]); // Validate there are the correct number of pubkeys if (vStrInputParts.size() < numkeys + 3) throw std::runtime_error("incorrect number of multisig pubkeys"); if (required < 1 || required > 20 || numkeys < 1 || numkeys > 20 || numkeys < required) throw std::runtime_error("multisig parameter mismatch. Required " \ + std::to_string(required) + " of " + std::to_string(numkeys) + "signatures."); // extract and validate PUBKEYs std::vector<CPubKey> pubkeys; for(int pos = 1; pos <= int(numkeys); pos++) { CPubKey pubkey(ParseHex(vStrInputParts[pos + 2])); if (!pubkey.IsFullyValid()) throw std::runtime_error("invalid TX output pubkey"); pubkeys.push_back(pubkey); } // Extract FLAGS bool bSegWit = false; bool bScriptHash = false; if (vStrInputParts.size() == numkeys + 4) { std::string flags = vStrInputParts.back(); bSegWit = (flags.find("W") != std::string::npos); bScriptHash = (flags.find("S") != std::string::npos); } else if (vStrInputParts.size() > numkeys + 4) { // Validate that there were no more parameters passed throw std::runtime_error("Too many parameters"); } CScript scriptPubKey = GetScriptForMultisig(required, pubkeys); if (bSegWit) { // Call GetScriptForWitness() to build a P2WSH scriptPubKey scriptPubKey = GetScriptForWitness(scriptPubKey); } if (bScriptHash) { // Get the address for the redeem script, then call // GetScriptForDestination() to construct a P2SH scriptPubKey. CBitcoinAddress addr(scriptPubKey); scriptPubKey = GetScriptForDestination(addr.Get()); } // construct TxOut, append to transaction output list CTxOut txout(value, scriptPubKey); tx.vout.push_back(txout); } static void MutateTxAddOutData(CMutableTransaction& tx, const std::string& strInput) { CAmount value = 0; // separate [VALUE:]DATA in string size_t pos = strInput.find(':'); if (pos==0) throw std::runtime_error("TX output value not specified"); if (pos != std::string::npos) { // Extract and validate VALUE value = ExtractAndValidateValue(strInput.substr(0, pos)); } // extract and validate DATA std::string strData = strInput.substr(pos + 1, std::string::npos); if (!IsHex(strData)) throw std::runtime_error("invalid TX output data"); std::vector<unsigned char> data = ParseHex(strData); CTxOut txout(value, CScript() << OP_RETURN << data); tx.vout.push_back(txout); } static void MutateTxAddOutScript(CMutableTransaction& tx, const std::string& strInput) { // separate VALUE:SCRIPT[:FLAGS] std::vector<std::string> vStrInputParts; boost::split(vStrInputParts, strInput, boost::is_any_of(":")); if (vStrInputParts.size() < 2) throw std::runtime_error("TX output missing separator"); // Extract and validate VALUE CAmount value = ExtractAndValidateValue(vStrInputParts[0]); // extract and validate script std::string strScript = vStrInputParts[1]; CScript scriptPubKey = ParseScript(strScript); // Extract FLAGS bool bSegWit = false; bool bScriptHash = false; if (vStrInputParts.size() == 3) { std::string flags = vStrInputParts.back(); bSegWit = (flags.find("W") != std::string::npos); bScriptHash = (flags.find("S") != std::string::npos); } if (bSegWit) { scriptPubKey = GetScriptForWitness(scriptPubKey); } if (bScriptHash) { CBitcoinAddress addr(scriptPubKey); scriptPubKey = GetScriptForDestination(addr.Get()); } // construct TxOut, append to transaction output list CTxOut txout(value, scriptPubKey); tx.vout.push_back(txout); } static void MutateTxDelInput(CMutableTransaction& tx, const std::string& strInIdx) { // parse requested deletion index int inIdx = atoi(strInIdx); if (inIdx < 0 || inIdx >= (int)tx.vin.size()) { std::string strErr = "Invalid TX input index '" + strInIdx + "'"; throw std::runtime_error(strErr.c_str()); } // delete input from transaction tx.vin.erase(tx.vin.begin() + inIdx); } static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOutIdx) { // parse requested deletion index int outIdx = atoi(strOutIdx); if (outIdx < 0 || outIdx >= (int)tx.vout.size()) { std::string strErr = "Invalid TX output index '" + strOutIdx + "'"; throw std::runtime_error(strErr.c_str()); } // delete output from transaction tx.vout.erase(tx.vout.begin() + outIdx); } static const unsigned int N_SIGHASH_OPTS = 6; static const struct { const char *flagStr; int flags; } sighashOptions[N_SIGHASH_OPTS] = { {"ALL", SIGHASH_ALL}, {"NONE", SIGHASH_NONE}, {"SINGLE", SIGHASH_SINGLE}, {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY}, {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY}, {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY}, }; static bool findSighashFlags(int& flags, const std::string& flagStr) { flags = 0; for (unsigned int i = 0; i < N_SIGHASH_OPTS; i++) { if (flagStr == sighashOptions[i].flagStr) { flags = sighashOptions[i].flags; return true; } } return false; } static CAmount AmountFromValue(const UniValue& value) { if (!value.isNum() && !value.isStr()) throw std::runtime_error("Amount is not a number or string"); CAmount amount; if (!ParseFixedPoint(value.getValStr(), 8, &amount)) throw std::runtime_error("Invalid amount"); if (!MoneyRange(amount)) throw std::runtime_error("Amount out of range"); return amount; } static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr) { int nHashType = SIGHASH_ALL; if (flagStr.size() > 0) if (!findSighashFlags(nHashType, flagStr)) throw std::runtime_error("unknown sighash flag/sign option"); std::vector<CTransaction> txVariants; txVariants.push_back(tx); // mergedTx will end up with all the signatures; it // starts as a clone of the raw tx: CMutableTransaction mergedTx(txVariants[0]); bool fComplete = true; CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); if (!registers.count("privatekeys")) throw std::runtime_error("privatekeys register variable must be set."); CBasicKeyStore tempKeystore; UniValue keysObj = registers["privatekeys"]; for (unsigned int kidx = 0; kidx < keysObj.size(); kidx++) { if (!keysObj[kidx].isStr()) throw std::runtime_error("privatekey not a std::string"); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(keysObj[kidx].getValStr()); if (!fGood) throw std::runtime_error("privatekey not valid"); CKey key = vchSecret.GetKey(); tempKeystore.AddKey(key); } // Add previous txouts given in the RPC call: if (!registers.count("prevtxs")) throw std::runtime_error("prevtxs register variable must be set."); UniValue prevtxsObj = registers["prevtxs"]; { for (unsigned int previdx = 0; previdx < prevtxsObj.size(); previdx++) { UniValue prevOut = prevtxsObj[previdx]; if (!prevOut.isObject()) throw std::runtime_error("expected prevtxs internal object"); std::map<std::string, UniValue::VType> types = { {"txid", UniValue::VSTR}, {"vout", UniValue::VNUM}, {"scriptPubKey", UniValue::VSTR}, }; if (!prevOut.checkObject(types)) throw std::runtime_error("prevtxs internal object typecheck fail"); uint256 txid = ParseHashUV(prevOut["txid"], "txid"); int nOut = atoi(prevOut["vout"].getValStr()); if (nOut < 0) throw std::runtime_error("vout must be positive"); COutPoint out(txid, nOut); std::vector<unsigned char> pkData(ParseHexUV(prevOut["scriptPubKey"], "scriptPubKey")); CScript scriptPubKey(pkData.begin(), pkData.end()); { const Coin& coin = view.AccessCoin(out); if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) { std::string err("Previous output scriptPubKey mismatch:\n"); err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+ ScriptToAsmStr(scriptPubKey); throw std::runtime_error(err); } Coin newcoin; newcoin.out.scriptPubKey = scriptPubKey; newcoin.out.nValue = 0; if (prevOut.exists("amount")) { newcoin.out.nValue = AmountFromValue(prevOut["amount"]); } newcoin.nHeight = 1; view.AddCoin(out, std::move(newcoin), true); } // if redeemScript given and private keys given, // add redeemScript to the tempKeystore so it can be signed: if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) && prevOut.exists("redeemScript")) { UniValue v = prevOut["redeemScript"]; std::vector<unsigned char> rsData(ParseHexUV(v, "redeemScript")); CScript redeemScript(rsData.begin(), rsData.end()); tempKeystore.AddCScript(redeemScript); } } } const CKeyStore& keystore = tempKeystore; bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; const Coin& coin = view.AccessCoin(txin.prevout); if (coin.IsSpent()) { fComplete = false; continue; } const CScript& prevPubKey = coin.out.scriptPubKey; const CAmount& amount = coin.out.nValue; SignatureData sigdata; // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mergedTx, i, amount, nHashType), prevPubKey, sigdata); // ... and merge in other signatures: for (const CTransaction& txv : txVariants) sigdata = CombineSignatures(prevPubKey, MutableTransactionSignatureChecker(&mergedTx, i, amount), sigdata, DataFromTransaction(txv, i)); UpdateTransaction(mergedTx, i, sigdata); if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i, amount))) fComplete = false; } if (fComplete) { // do nothing... for now // perhaps store this for later optional JSON output } tx = mergedTx; } class Secp256k1Init { ECCVerifyHandle globalVerifyHandle; public: Secp256k1Init() { ECC_Start(); } ~Secp256k1Init() { ECC_Stop(); } }; static void MutateTx(CMutableTransaction& tx, const std::string& command, const std::string& commandVal) { std::unique_ptr<Secp256k1Init> ecc; if (command == "nversion") MutateTxVersion(tx, commandVal); else if (command == "locktime") MutateTxLocktime(tx, commandVal); else if (command == "replaceable") { MutateTxRBFOptIn(tx, commandVal); } else if (command == "delin") MutateTxDelInput(tx, commandVal); else if (command == "in") MutateTxAddInput(tx, commandVal); else if (command == "delout") MutateTxDelOutput(tx, commandVal); else if (command == "outaddr") MutateTxAddOutAddr(tx, commandVal); else if (command == "outpubkey") { if (!ecc) { ecc.reset(new Secp256k1Init()); } MutateTxAddOutPubKey(tx, commandVal); } else if (command == "outmultisig") { if (!ecc) { ecc.reset(new Secp256k1Init()); } MutateTxAddOutMultiSig(tx, commandVal); } else if (command == "outscript") MutateTxAddOutScript(tx, commandVal); else if (command == "outdata") MutateTxAddOutData(tx, commandVal); else if (command == "sign") { if (!ecc) { ecc.reset(new Secp256k1Init()); } MutateTxSign(tx, commandVal); } else if (command == "load") RegisterLoad(commandVal); else if (command == "set") RegisterSet(commandVal); else throw std::runtime_error("unknown command"); } static void OutputTxJSON(const CTransaction& tx) { UniValue entry(UniValue::VOBJ); TxToUniv(tx, uint256(), entry); std::string jsonOutput = entry.write(4); fprintf(stdout, "%s\n", jsonOutput.c_str()); } static void OutputTxHash(const CTransaction& tx) { std::string strHexHash = tx.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id) fprintf(stdout, "%s\n", strHexHash.c_str()); } static void OutputTxHex(const CTransaction& tx) { std::string strHex = EncodeHexTx(tx); fprintf(stdout, "%s\n", strHex.c_str()); } static void OutputTx(const CTransaction& tx) { if (gArgs.GetBoolArg("-json", false)) OutputTxJSON(tx); else if (gArgs.GetBoolArg("-txid", false)) OutputTxHash(tx); else OutputTxHex(tx); } static std::string readStdin() { char buf[4096]; std::string ret; while (!feof(stdin)) { size_t bread = fread(buf, 1, sizeof(buf), stdin); ret.append(buf, bread); if (bread < sizeof(buf)) break; } if (ferror(stdin)) throw std::runtime_error("error reading stdin"); boost::algorithm::trim_right(ret); return ret; } static int CommandLineRawTx(int argc, char* argv[]) { std::string strPrint; int nRet = 0; try { // Skip switches; Permit common stdin convention "-" while (argc > 1 && IsSwitchChar(argv[1][0]) && (argv[1][1] != 0)) { argc--; argv++; } CMutableTransaction tx; int startArg; if (!fCreateBlank) { // require at least one param if (argc < 2) throw std::runtime_error("too few parameters"); // param: hex-encoded bitcoin transaction std::string strHexTx(argv[1]); if (strHexTx == "-") // "-" implies standard input strHexTx = readStdin(); if (!DecodeHexTx(tx, strHexTx, true)) throw std::runtime_error("invalid transaction encoding"); startArg = 2; } else startArg = 1; for (int i = startArg; i < argc; i++) { std::string arg = argv[i]; std::string key, value; size_t eqpos = arg.find('='); if (eqpos == std::string::npos) key = arg; else { key = arg.substr(0, eqpos); value = arg.substr(eqpos + 1); } MutateTx(tx, key, value); } OutputTx(tx); } catch (const boost::thread_interrupted&) { throw; } catch (const std::exception& e) { strPrint = std::string("error: ") + e.what(); nRet = EXIT_FAILURE; } catch (...) { PrintExceptionContinue(nullptr, "CommandLineRawTx()"); throw; } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } int main(int argc, char* argv[]) { SetupEnvironment(); try { int ret = AppInitRawTx(argc, argv); if (ret != CONTINUE_EXECUTION) return ret; } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInitRawTx()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(nullptr, "AppInitRawTx()"); return EXIT_FAILURE; } int ret = EXIT_FAILURE; try { ret = CommandLineRawTx(argc, argv); } catch (const std::exception& e) { PrintExceptionContinue(&e, "CommandLineRawTx()"); } catch (...) { PrintExceptionContinue(nullptr, "CommandLineRawTx()"); } return ret; }
/* * 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. */ /* * $Id$ */ #if !defined(XERCESC_INCLUDE_GUARD_XSWILDCARD_HPP) #define XERCESC_INCLUDE_GUARD_XSWILDCARD_HPP #include <xercesc/framework/psvi/XSObject.hpp> XERCES_CPP_NAMESPACE_BEGIN /** * This class describes all properties of a Schema Wildcard * component. * This is *always* owned by the validator /parser object from which * it is obtained. */ // forward declarations class XSAnnotation; class SchemaAttDef; class ContentSpecNode; class XMLPARSER_EXPORT XSWildcard : public XSObject { public: // Namespace Constraint enum NAMESPACE_CONSTRAINT { /** * Namespace Constraint: any namespace is allowed. */ NSCONSTRAINT_ANY = 1, /** * Namespace Constraint: namespaces in the list are not allowed. */ NSCONSTRAINT_NOT = 2, /** * Namespace Constraint: namespaces in the list are allowed. */ NSCONSTRAINT_DERIVATION_LIST = 3 }; // Process contents enum PROCESS_CONTENTS { /** * There must be a top-level declaration for the item available, or the * item must have an xsi:type, and the item must be valid as appropriate. */ PC_STRICT = 1, /** * No constraints at all: the item must simply be well-formed XML. */ PC_SKIP = 2, /** * If the item, or any items among its [children] is an element * information item, has a uniquely determined declaration available, it * must be valid with respect to that definition, that is, validate * where you can, don't worry when you can't. */ PC_LAX = 3 }; // Constructors and Destructor // ----------------------------------------------------------------------- /** @name Constructors */ //@{ /** * The default constructor * * @param attWildCard * @param annot * @param xsModel * @param manager The configurable memory manager */ XSWildcard ( SchemaAttDef* const attWildCard , XSAnnotation* const annot , XSModel* const xsModel , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); XSWildcard ( const ContentSpecNode* const elmWildCard , XSAnnotation* const annot , XSModel* const xsModel , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); //@} /** @name Destructor */ //@{ ~XSWildcard(); //@} //--------------------- /** @name XSWildcard methods */ //@{ /** * Namespace constraint: A constraint type: any, not, list. */ NAMESPACE_CONSTRAINT getConstraintType() const; /** * Namespace constraint. For <code>constraintType</code> * <code>NSCONSTRAINT_DERIVATION_LIST</code>, the list contains allowed namespaces. * For <code>constraintType</code> <code>NSCONSTRAINT_NOT</code>, the * list contains disallowed namespaces. */ StringList *getNsConstraintList(); /** * [process contents]: one of skip, lax or strict. Valid constants values * are: <code>PC_SKIP, PC_LAX, PC_STRICT</code>. */ PROCESS_CONTENTS getProcessContents() const; /** * Optional. An [annotation]. */ XSAnnotation *getAnnotation() const; //@} //---------------------------------- /** methods needed by implementation */ //@{ //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- XSWildcard(const XSWildcard&); XSWildcard & operator=(const XSWildcard &); /** * Build namespace list */ void buildNamespaceList(const ContentSpecNode* const rootNode); protected: // ----------------------------------------------------------------------- // data members // ----------------------------------------------------------------------- NAMESPACE_CONSTRAINT fConstraintType; PROCESS_CONTENTS fProcessContents; StringList* fNsConstraintList; XSAnnotation* fAnnotation; }; inline XSAnnotation *XSWildcard::getAnnotation() const { return fAnnotation; } inline XSWildcard::PROCESS_CONTENTS XSWildcard::getProcessContents() const { return fProcessContents; } inline StringList* XSWildcard::getNsConstraintList() { return fNsConstraintList; } inline XSWildcard::NAMESPACE_CONSTRAINT XSWildcard::getConstraintType() const { return fConstraintType; } XERCES_CPP_NAMESPACE_END #endif
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2018 Aquila Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "addresstablemodel.h" #include "askpassphrasedialog.h" #include "bitcoinunits.h" #include "clientmodel.h" #include "coincontroldialog.h" #include "guiutil.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "walletmodel.h" #include "base58.h" #include "coincontrol.h" #include "ui_interface.h" #include "utilmoneystr.h" #include "wallet.h" #include <QMessageBox> #include <QScrollBar> #include <QSettings> #include <QTextDocument> SendCoinsDialog::SendCoinsDialog(QWidget* parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), clientModel(0), model(0), fNewRecipientAllowed(true), fFeeMinimized(true) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this); addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString&)), this, SLOT(coinControlChangeEdited(const QString&))); // UTXO Splitter connect(ui->splitBlockCheckBox, SIGNAL(stateChanged(int)), this, SLOT(splitBlockChecked(int))); connect(ui->splitBlockLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(splitBlockLineEditChanged(const QString&))); // AQA specific QSettings settings; if (!settings.contains("bUseObfuScation")) settings.setValue("bUseObfuScation", false); if (!settings.contains("bUseSwiftTX")) settings.setValue("bUseSwiftTX", false); bool useObfuScation = settings.value("bUseObfuScation").toBool(); bool useSwiftTX = settings.value("bUseSwiftTX").toBool(); if (fLiteMode) { ui->checkUseObfuscation->setChecked(false); ui->checkUseObfuscation->setVisible(false); ui->checkSwiftTX->setVisible(false); CoinControlDialog::coinControl->useObfuScation = false; CoinControlDialog::coinControl->useSwiftTX = false; } else { ui->checkUseObfuscation->setChecked(useObfuScation); ui->checkSwiftTX->setChecked(useSwiftTX); CoinControlDialog::coinControl->useObfuScation = useObfuScation; CoinControlDialog::coinControl->useSwiftTX = useSwiftTX; } connect(ui->checkUseObfuscation, SIGNAL(stateChanged(int)), this, SLOT(updateDisplayUnit())); connect(ui->checkSwiftTX, SIGNAL(stateChanged(int)), this, SLOT(updateSwiftTX())); // Coin Control: clipboard actions QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction* clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction* clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction* clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction* clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction* clipboardLowOutputAction = new QAction(tr("Copy dust"), this); QAction* clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); // init transaction fee section if (!settings.contains("fFeeSectionMinimized")) settings.setValue("fFeeSectionMinimized", true); if (!settings.contains("nFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility settings.setValue("nFeeRadio", 1); // custom if (!settings.contains("nFeeRadio")) settings.setValue("nFeeRadio", 0); // recommended if (!settings.contains("nCustomFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility settings.setValue("nCustomFeeRadio", 1); // total at least if (!settings.contains("nCustomFeeRadio")) settings.setValue("nCustomFeeRadio", 0); // per kilobyte if (!settings.contains("nSmartFeeSliderPosition")) settings.setValue("nSmartFeeSliderPosition", 0); if (!settings.contains("nTransactionFee")) settings.setValue("nTransactionFee", (qint64)DEFAULT_TRANSACTION_FEE); if (!settings.contains("fPayOnlyMinFee")) settings.setValue("fPayOnlyMinFee", false); if (!settings.contains("fSendFreeTransactions")) settings.setValue("fSendFreeTransactions", false); ui->groupFee->setId(ui->radioSmartFee, 0); ui->groupFee->setId(ui->radioCustomFee, 1); ui->groupFee->button((int)std::max(0, std::min(1, settings.value("nFeeRadio").toInt())))->setChecked(true); ui->groupCustomFee->setId(ui->radioCustomPerKilobyte, 0); ui->groupCustomFee->setId(ui->radioCustomAtLeast, 1); ui->groupCustomFee->button((int)std::max(0, std::min(1, settings.value("nCustomFeeRadio").toInt())))->setChecked(true); ui->sliderSmartFee->setValue(settings.value("nSmartFeeSliderPosition").toInt()); ui->customFee->setValue(settings.value("nTransactionFee").toLongLong()); ui->checkBoxMinimumFee->setChecked(settings.value("fPayOnlyMinFee").toBool()); ui->checkBoxFreeTx->setChecked(settings.value("fSendFreeTransactions").toBool()); minimizeFeeSection(settings.value("fFeeSectionMinimized").toBool()); } void SendCoinsDialog::setClientModel(ClientModel* clientModel) { this->clientModel = clientModel; if (clientModel) { connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(updateSmartFeeLabel())); } } void SendCoinsDialog::setModel(WalletModel* model) { this->model = model; if (model && model->getOptionsModel()) { for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if (entry) { entry->setModel(model); } } setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getAnonymizedBalance(), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateDisplayUnit(); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); // fee section connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(updateSmartFeeLabel())); connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(updateFeeSectionControls())); connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->groupCustomFee, SIGNAL(buttonClicked(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->groupCustomFee, SIGNAL(buttonClicked(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->customFee, SIGNAL(valueChanged()), this, SLOT(updateGlobalFeeVariables())); connect(ui->customFee, SIGNAL(valueChanged()), this, SLOT(coinControlUpdateLabels())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(setMinimumFee())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateFeeSectionControls())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->checkBoxFreeTx, SIGNAL(stateChanged(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->checkBoxFreeTx, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels())); ui->customFee->setSingleStep(CWallet::minTxFee.GetFeePerK()); updateFeeSectionControls(); updateMinFeeLabel(); updateSmartFeeLabel(); updateGlobalFeeVariables(); } } SendCoinsDialog::~SendCoinsDialog() { QSettings settings; settings.setValue("fFeeSectionMinimized", fFeeMinimized); settings.setValue("nFeeRadio", ui->groupFee->checkedId()); settings.setValue("nCustomFeeRadio", ui->groupCustomFee->checkedId()); settings.setValue("nSmartFeeSliderPosition", ui->sliderSmartFee->value()); settings.setValue("nTransactionFee", (qint64)ui->customFee->value()); settings.setValue("fPayOnlyMinFee", ui->checkBoxMinimumFee->isChecked()); settings.setValue("fSendFreeTransactions", ui->checkBoxFreeTx->isChecked()); delete ui; } void SendCoinsDialog::on_sendButton_clicked() { if (!model || !model->getOptionsModel()) return; QList<SendCoinsRecipient> recipients; bool valid = true; for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); //UTXO splitter - address should be our own CBitcoinAddress address = entry->getValue().address.toStdString(); if (!model->isMine(address) && ui->splitBlockCheckBox->checkState() == Qt::Checked) { CoinControlDialog::coinControl->fSplitBlock = false; ui->splitBlockCheckBox->setCheckState(Qt::Unchecked); QMessageBox::warning(this, tr("Send Coins"), tr("The split block tool does not work when sending to outside addresses. Try again."), QMessageBox::Ok, QMessageBox::Ok); return; } if (entry) { if (entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if (!valid || recipients.isEmpty()) { return; } //set split block in model CoinControlDialog::coinControl->fSplitBlock = ui->splitBlockCheckBox->checkState() == Qt::Checked; if (ui->entries->count() > 1 && ui->splitBlockCheckBox->checkState() == Qt::Checked) { CoinControlDialog::coinControl->fSplitBlock = false; ui->splitBlockCheckBox->setCheckState(Qt::Unchecked); QMessageBox::warning(this, tr("Send Coins"), tr("The split block tool does not work with multiple addresses. Try again."), QMessageBox::Ok, QMessageBox::Ok); return; } if (CoinControlDialog::coinControl->fSplitBlock) CoinControlDialog::coinControl->nSplitBlock = int(ui->splitBlockLineEdit->text().toInt()); QString strFunds = tr("using") + " <b>" + tr("anonymous funds") + "</b>"; QString strFee = ""; recipients[0].inputType = ONLY_DENOMINATED; if (ui->checkUseObfuscation->isChecked()) { recipients[0].inputType = ONLY_DENOMINATED; strFunds = tr("using") + " <b>" + tr("anonymous funds") + "</b>"; QString strNearestAmount( BitcoinUnits::formatWithUnit( model->getOptionsModel()->getDisplayUnit(), 0.1 * COIN)); strFee = QString(tr( "(obfuscation requires this amount to be rounded up to the nearest %1).") .arg(strNearestAmount)); } else { recipients[0].inputType = ALL_COINS; strFunds = tr("using") + " <b>" + tr("any available funds (not recommended)") + "</b>"; } if (ui->checkSwiftTX->isChecked()) { recipients[0].useSwiftTX = true; strFunds += " "; strFunds += tr("and SwiftTX"); } else { recipients[0].useSwiftTX = false; } // Format confirmation message QStringList formatted; foreach (const SendCoinsRecipient& rcp, recipients) { // generate bold amount string QString amount = "<b>" + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount); amount.append("</b> ").append(strFunds); // generate monospace address string QString address = "<span style='font-family: monospace;'>" + rcp.address; address.append("</span>"); QString recipientElement; if (!rcp.paymentRequest.IsInitialized()) // normal payment { if (rcp.label.length() > 0) // label with address { recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.label)); recipientElement.append(QString(" (%1)").arg(address)); } else // just address { recipientElement = tr("%1 to %2").arg(amount, address); } } else if (!rcp.authenticatedMerchant.isEmpty()) // secure payment request { recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.authenticatedMerchant)); } else // insecure payment request { recipientElement = tr("%1 to %2").arg(amount, address); } if (fSplitBlock) { recipientElement.append(tr(" split into %1 outputs using the UTXO splitter.").arg(CoinControlDialog::coinControl->nSplitBlock)); } formatted.append(recipientElement); } fNewRecipientAllowed = false; // request unlock only if was locked or unlocked for mixing: // this way we let users unlock by walletpassphrase or by menu // and make many transactions while unlocking through this dialog // will call relock WalletModel::EncryptionStatus encStatus = model->getEncryptionStatus(); if (encStatus == model->Locked || encStatus == model->UnlockedForAnonymizationOnly) { WalletModel::UnlockContext ctx(model->requestUnlock(true)); if (!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } send(recipients, strFee, formatted); return; } // already unlocked or not encrypted at all send(recipients, strFee, formatted); } void SendCoinsDialog::send(QList<SendCoinsRecipient> recipients, QString strFee, QStringList formatted) { // prepare transaction for getting txFee earlier WalletModelTransaction currentTransaction(recipients); WalletModel::SendCoinsReturn prepareStatus; if (model->getOptionsModel()->getCoinControlFeatures()) // coin control enabled prepareStatus = model->prepareTransaction(currentTransaction, CoinControlDialog::coinControl); else prepareStatus = model->prepareTransaction(currentTransaction); // process prepareStatus and on error generate message shown to user processSendCoinsReturn(prepareStatus, BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee()), true); if (prepareStatus.status != WalletModel::OK) { fNewRecipientAllowed = true; return; } CAmount txFee = currentTransaction.getTransactionFee(); QString questionString = tr("Are you sure you want to send?"); questionString.append("<br /><br />%1"); if (txFee > 0) { // append fee string if a fee is required questionString.append("<hr /><span style='color:#aa0000;'>"); questionString.append(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), txFee)); questionString.append("</span> "); questionString.append(tr("are added as transaction fee")); questionString.append(" "); questionString.append(strFee); // append transaction size questionString.append(" (" + QString::number((double)currentTransaction.getTransactionSize() / 1000) + " kB)"); } // add total amount in all subdivision units questionString.append("<hr />"); CAmount totalAmount = currentTransaction.getTotalTransactionAmount() + txFee; QStringList alternativeUnits; foreach (BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) { if (u != model->getOptionsModel()->getDisplayUnit()) alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount)); } // Show total amount + all alternative units questionString.append(tr("Total Amount = <b>%1</b><br />= %2") .arg(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), totalAmount)) .arg(alternativeUnits.join("<br />= "))); // Limit number of displayed entries int messageEntries = formatted.size(); int displayedEntries = 0; for (int i = 0; i < formatted.size(); i++) { if (i >= MAX_SEND_POPUP_ENTRIES) { formatted.removeLast(); i--; } else { displayedEntries = i + 1; } } questionString.append("<hr />"); questionString.append(tr("<b>(%1 of %2 entries displayed)</b>").arg(displayedEntries).arg(messageEntries)); // Display message box QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), questionString.arg(formatted.join("<br />")), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } // now send the prepared transaction WalletModel::SendCoinsReturn sendStatus = model->sendCoins(currentTransaction); // process sendStatus and on error generate message shown to user processSendCoinsReturn(sendStatus); if (sendStatus.status == WalletModel::OK) { accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while (ui->entries->count()) { ui->entries->takeAt(0)->widget()->deleteLater(); } addEntry(); updateTabsAndLabels(); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry* SendCoinsDialog::addEntry() { SendCoinsEntry* entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateTabsAndLabels(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); qApp->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if (bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateTabsAndLabels() { setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { entry->hide(); // If the last entry is about to be removed add an empty one if (ui->entries->count() == 1) addEntry(); entry->deleteLater(); updateTabsAndLabels(); } QWidget* SendCoinsDialog::setupTabChain(QWidget* prev) { for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if (entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->sendButton); QWidget::setTabOrder(ui->sendButton, ui->clearButton); QWidget::setTabOrder(ui->clearButton, ui->addButton); return ui->addButton; } void SendCoinsDialog::setAddress(const QString& address) { SendCoinsEntry* entry = 0; // Replace the first entry if it is still unused if (ui->entries->count() == 1) { SendCoinsEntry* first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if (first->isClear()) { entry = first; } } if (!entry) { entry = addEntry(); } entry->setAddress(address); } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient& rv) { if (!fNewRecipientAllowed) return; SendCoinsEntry* entry = 0; // Replace the first entry if it is still unused if (ui->entries->count() == 1) { SendCoinsEntry* first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if (first->isClear()) { entry = first; } } if (!entry) { entry = addEntry(); } entry->setValue(rv); updateTabsAndLabels(); } bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient& rv) { // Just paste the entry, all pre-checks // are done in paymentserver.cpp. pasteEntry(rv); return true; } void SendCoinsDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& anonymizedBalance, const CAmount& watchBalance, const CAmount& watchUnconfirmedBalance, const CAmount& watchImmatureBalance) { Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); Q_UNUSED(anonymizedBalance); Q_UNUSED(watchBalance); Q_UNUSED(watchUnconfirmedBalance); Q_UNUSED(watchImmatureBalance); if (model && model->getOptionsModel()) { uint64_t bal = 0; QSettings settings; settings.setValue("bUseObfuScation", ui->checkUseObfuscation->isChecked()); if (ui->checkUseObfuscation->isChecked()) { bal = anonymizedBalance; } else { bal = balance; } ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), bal)); } } void SendCoinsDialog::updateDisplayUnit() { TRY_LOCK(cs_main, lockMain); if (!lockMain) return; setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getAnonymizedBalance(), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); CoinControlDialog::coinControl->useObfuScation = ui->checkUseObfuscation->isChecked(); coinControlUpdateLabels(); ui->customFee->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); updateMinFeeLabel(); updateSmartFeeLabel(); } void SendCoinsDialog::updateSwiftTX() { QSettings settings; settings.setValue("bUseSwiftTX", ui->checkSwiftTX->isChecked()); CoinControlDialog::coinControl->useSwiftTX = ui->checkSwiftTX->isChecked(); coinControlUpdateLabels(); } void SendCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn& sendCoinsReturn, const QString& msgArg, bool fPrepare) { bool fAskForUnlock = false; QPair<QString, CClientUIInterface::MessageBoxFlags> msgParams; // Default to a warning message, override if error message is needed msgParams.second = CClientUIInterface::MSG_WARNING; // This comment is specific to SendCoinsDialog usage of WalletModel::SendCoinsReturn. // WalletModel::TransactionCommitFailed is used only in WalletModel::sendCoins() // all others are used only in WalletModel::prepareTransaction() switch (sendCoinsReturn.status) { case WalletModel::InvalidAddress: msgParams.first = tr("The recipient address is not valid, please recheck."); break; case WalletModel::InvalidAmount: msgParams.first = tr("The amount to pay must be larger than 0."); break; case WalletModel::AmountExceedsBalance: msgParams.first = tr("The amount exceeds your balance."); break; case WalletModel::AmountWithFeeExceedsBalance: msgParams.first = tr("The total exceeds your balance when the %1 transaction fee is included.").arg(msgArg); break; case WalletModel::DuplicateAddress: msgParams.first = tr("Duplicate address found, can only send to each address once per send operation."); break; case WalletModel::TransactionCreationFailed: msgParams.first = tr("Transaction creation failed!"); msgParams.second = CClientUIInterface::MSG_ERROR; break; case WalletModel::TransactionCommitFailed: msgParams.first = tr("The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); msgParams.second = CClientUIInterface::MSG_ERROR; break; case WalletModel::AnonymizeOnlyUnlocked: // Unlock is only need when the coins are send if(!fPrepare) fAskForUnlock = true; else msgParams.first = tr("Error: The wallet was unlocked only to anonymize coins."); break; case WalletModel::InsaneFee: msgParams.first = tr("A fee %1 times higher than %2 per kB is considered an insanely high fee.").arg(10000).arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ::minRelayTxFee.GetFeePerK())); break; // included to prevent a compiler warning. case WalletModel::OK: default: return; } // Unlock wallet if it wasn't fully unlocked already if(fAskForUnlock) { model->requestUnlock(false); if(model->getEncryptionStatus () != WalletModel::Unlocked) { msgParams.first = tr("Error: The wallet was unlocked only to anonymize coins. Unlock canceled."); } else { // Wallet unlocked return; } } emit message(tr("Send Coins"), msgParams.first, msgParams.second); } void SendCoinsDialog::minimizeFeeSection(bool fMinimize) { ui->labelFeeMinimized->setVisible(fMinimize); ui->buttonChooseFee->setVisible(fMinimize); ui->buttonMinimizeFee->setVisible(!fMinimize); ui->frameFeeSelection->setVisible(!fMinimize); ui->horizontalLayoutSmartFee->setContentsMargins(0, (fMinimize ? 0 : 6), 0, 0); fFeeMinimized = fMinimize; } void SendCoinsDialog::on_buttonChooseFee_clicked() { minimizeFeeSection(false); } void SendCoinsDialog::on_buttonMinimizeFee_clicked() { updateFeeMinimizedLabel(); minimizeFeeSection(true); } void SendCoinsDialog::setMinimumFee() { ui->radioCustomPerKilobyte->setChecked(true); ui->customFee->setValue(CWallet::minTxFee.GetFeePerK()); } void SendCoinsDialog::updateFeeSectionControls() { ui->sliderSmartFee->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFee->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFee2->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFee3->setEnabled(ui->radioSmartFee->isChecked()); ui->labelFeeEstimation->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFeeNormal->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFeeFast->setEnabled(ui->radioSmartFee->isChecked()); ui->checkBoxMinimumFee->setEnabled(ui->radioCustomFee->isChecked()); ui->labelMinFeeWarning->setEnabled(ui->radioCustomFee->isChecked()); ui->radioCustomPerKilobyte->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked()); ui->radioCustomAtLeast->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked()); ui->customFee->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked()); } void SendCoinsDialog::updateGlobalFeeVariables() { if (ui->radioSmartFee->isChecked()) { nTxConfirmTarget = (int)25 - (int)std::max(0, std::min(24, ui->sliderSmartFee->value())); payTxFee = CFeeRate(0); } else { nTxConfirmTarget = 25; payTxFee = CFeeRate(ui->customFee->value()); fPayAtLeastCustomFee = ui->radioCustomAtLeast->isChecked(); } fSendFreeTransactions = ui->checkBoxFreeTx->isChecked(); } void SendCoinsDialog::updateFeeMinimizedLabel() { if (!model || !model->getOptionsModel()) return; if (ui->radioSmartFee->isChecked()) ui->labelFeeMinimized->setText(ui->labelSmartFee->text()); else { ui->labelFeeMinimized->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ui->customFee->value()) + ((ui->radioCustomPerKilobyte->isChecked()) ? "/kB" : "")); } } void SendCoinsDialog::updateMinFeeLabel() { if (model && model->getOptionsModel()) ui->checkBoxMinimumFee->setText(tr("Pay only the minimum fee of %1").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK()) + "/kB")); } void SendCoinsDialog::updateSmartFeeLabel() { if (!model || !model->getOptionsModel()) return; int nBlocksToConfirm = (int)25 - (int)std::max(0, std::min(24, ui->sliderSmartFee->value())); CFeeRate feeRate = mempool.estimateFee(nBlocksToConfirm); if (feeRate <= CFeeRate(0)) // not enough data => minfee { ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK()) + "/kB"); ui->labelSmartFee2->show(); // (Smart fee not initialized yet. This usually takes a few blocks...) ui->labelFeeEstimation->setText(""); } else { ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB"); ui->labelSmartFee2->hide(); ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", nBlocksToConfirm)); } updateFeeMinimizedLabel(); } // UTXO splitter void SendCoinsDialog::splitBlockChecked(int state) { if (model) { CoinControlDialog::coinControl->fSplitBlock = (state == Qt::Checked); fSplitBlock = (state == Qt::Checked); ui->splitBlockLineEdit->setEnabled((state == Qt::Checked)); ui->labelBlockSizeText->setEnabled((state == Qt::Checked)); ui->labelBlockSize->setEnabled((state == Qt::Checked)); coinControlUpdateLabels(); } } //UTXO splitter void SendCoinsDialog::splitBlockLineEditChanged(const QString& text) { //grab the amount in Coin Control AFter Fee field QString qAfterFee = ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", "").simplified().replace(" ", ""); //convert to CAmount CAmount nAfterFee; ParseMoney(qAfterFee.toStdString().c_str(), nAfterFee); //if greater than 0 then divide after fee by the amount of blocks CAmount nSize = nAfterFee; int nBlocks = text.toInt(); if (nAfterFee && nBlocks) nSize = nAfterFee / nBlocks; //assign to split block dummy, which is used to recalculate the fee amount more outputs CoinControlDialog::nSplitBlockDummy = nBlocks; //update labels ui->labelBlockSize->setText(QString::fromStdString(FormatMoney(nSize))); coinControlUpdateLabels(); } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace("~", "")); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", "")); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace("~", "")); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Dust" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace("~", "")); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); if (checked) coinControlUpdateLabels(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (state == Qt::Unchecked) { CoinControlDialog::coinControl->destChange = CNoDestination(); ui->labelCoinControlChangeLabel->clear(); } else // use this to re-validate an already entered address coinControlChangeEdited(ui->lineEditCoinControlChange->text()); ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString& text) { if (model && model->getAddressTableModel()) { // Default to no change address until verified CoinControlDialog::coinControl->destChange = CNoDestination(); ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); CBitcoinAddress addr = CBitcoinAddress(text.toStdString()); if (text.isEmpty()) // Nothing entered { ui->labelCoinControlChangeLabel->setText(""); } else if (!addr.IsValid()) // Invalid address { ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid AQA address")); } else // Valid address { CPubKey pubkey; CKeyID keyid; addr.GetKeyID(keyid); if (!model->getPubKey(keyid, pubkey)) // Unknown change address { ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address")); } else // Known change address { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); // Query label QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else ui->labelCoinControlChangeLabel->setText(tr("(no label)")); CoinControlDialog::coinControl->destChange = addr.Get(); } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if (entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } ui->checkUseObfuscation->setChecked(CoinControlDialog::coinControl->useObfuScation); if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
#include "ConsoleLog/ConsoleLines.h" #include "SteamID.h" #include "WorldState.h" #include <catch2/catch.hpp> #include <mh/error/not_implemented_error.hpp> using namespace std::chrono_literals; using namespace tf2_bot_detector; namespace { class DummyWorldState : public IWorldState { // Inherited via IWorldState virtual IConsoleLineListener& GetConsoleLineListenerBroadcaster() override { throw mh::not_implemented_error(); } virtual void UpdateTimestamp(const ConsoleLogParser& parser) override { throw mh::not_implemented_error(); } virtual void Update() override { throw mh::not_implemented_error(); } virtual time_point_t GetCurrentTime() const override { throw mh::not_implemented_error(); } virtual time_point_t GetLastStatusUpdateTime() const override { throw mh::not_implemented_error(); } virtual void AddWorldEventListener(IWorldEventListener* listener) override { throw mh::not_implemented_error(); } virtual void RemoveWorldEventListener(IWorldEventListener* listener) override { throw mh::not_implemented_error(); } virtual void AddConsoleLineListener(IConsoleLineListener* listener) override { throw mh::not_implemented_error(); } virtual void RemoveConsoleLineListener(IConsoleLineListener* listener) override { throw mh::not_implemented_error(); } virtual void AddConsoleOutputChunk(const std::string_view& chunk) override { throw mh::not_implemented_error(); } virtual mh::task<> AddConsoleOutputLine(std::string line) override { throw mh::not_implemented_error(); } virtual std::optional<SteamID> FindSteamIDForName(const std::string_view& playerName) const override { throw mh::not_implemented_error(); } virtual std::optional<LobbyMemberTeam> FindLobbyMemberTeam(const SteamID& id) const override { throw mh::not_implemented_error(); } virtual std::optional<UserID_t> FindUserID(const SteamID& id) const override { throw mh::not_implemented_error(); } virtual TeamShareResult GetTeamShareResult(const SteamID& id) const override { throw mh::not_implemented_error(); } virtual TeamShareResult GetTeamShareResult(const SteamID& id0, const SteamID& id1) const override { throw mh::not_implemented_error(); } virtual TeamShareResult GetTeamShareResult(const std::optional<LobbyMemberTeam>& team0, const SteamID& id1) const override { throw mh::not_implemented_error(); } virtual const IPlayer* FindPlayer(const SteamID& id) const override { throw mh::not_implemented_error(); } virtual size_t GetApproxLobbyMemberCount() const override { throw mh::not_implemented_error(); } virtual mh::generator<const IPlayer&> GetLobbyMembers() const override { throw mh::not_implemented_error(); } virtual mh::generator<const IPlayer&> GetPlayers() const override { throw mh::not_implemented_error(); } virtual bool IsLocalPlayerInitialized() const override { throw mh::not_implemented_error(); } virtual bool IsVoteInProgress() const override { throw mh::not_implemented_error(); } virtual const IAccountAges& GetAccountAges() const override { throw mh::not_implemented_error(); } } static s_DummyWorldState; } TEST_CASE("tf2bd_cl_status", "[ConsoleLines]") { struct StatusLineTest { std::string_view m_StatusLine; uint32_t m_ExpectedUserID; std::string_view m_ExpectedName; SteamID m_ExpectedSteamID; duration_t m_ExpectedConnectionTime; uint32_t m_ExpectedPing; uint32_t m_ExpectedLoss; PlayerStatusState m_ExpectedState; }; constexpr StatusLineTest s_StatusLineTests[] = { { .m_StatusLine = "# 348 \"2fort\x0A closed due to COVID\x0A\" [U:1:1118537734] 00:51 157 0 active", .m_ExpectedUserID = 348, .m_ExpectedName = "2fort\x0A closed due to COVID\x0A", .m_ExpectedSteamID = SteamID(1118537734, SteamAccountType::Individual, SteamAccountUniverse::Public), .m_ExpectedConnectionTime = 51s, .m_ExpectedPing = 157, .m_ExpectedLoss = 0, .m_ExpectedState = PlayerStatusState::Active, }, { .m_StatusLine = "# 348 \"2fort\x0D closed due to COVID\x0D\" [U:1:1118537734] 00:51 157 0 active", .m_ExpectedUserID = 348, .m_ExpectedName = "2fort\x0D closed due to COVID\x0D", .m_ExpectedSteamID = SteamID(1118537734, SteamAccountType::Individual, SteamAccountUniverse::Public), .m_ExpectedConnectionTime = 51s, .m_ExpectedPing = 157, .m_ExpectedLoss = 0, .m_ExpectedState = PlayerStatusState::Active, } }; for (const auto& test : s_StatusLineTests) { ConsoleLineTryParseArgs args{ test.m_StatusLine, tfbd_clock_t::now(), s_DummyWorldState }; auto parsedLine = ServerStatusPlayerLine::TryParse(args); REQUIRE(parsedLine); auto parsedStatusLine = dynamic_cast<ServerStatusPlayerLine*>(parsedLine.get()); REQUIRE(parsedStatusLine); const PlayerStatus& playerStatus = parsedStatusLine->GetPlayerStatus(); REQUIRE(playerStatus.m_UserID == test.m_ExpectedUserID); REQUIRE(playerStatus.m_Name == test.m_ExpectedName); REQUIRE(playerStatus.m_SteamID == test.m_ExpectedSteamID); //REQUIRE(playerStatus.m_ConnectionTime == test.m_ExpectedConnectionTime); // why did i do this... REQUIRE(playerStatus.m_Ping == test.m_ExpectedPing); REQUIRE(playerStatus.m_Loss == test.m_ExpectedLoss); REQUIRE(playerStatus.m_State == test.m_ExpectedState); } }
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2018 Klaus Spanderen This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #include "utilities.hpp" #include "nthorderderivativeop.hpp" #include <ql/math/comparison.hpp> #include <ql/pricingengines/blackformula.hpp> #include <ql/math/initializers.hpp> #include <ql/math/richardsonextrapolation.hpp> #include <ql/math/matrixutilities/bicgstab.hpp> #include <ql/math/integrals/gausslobattointegral.hpp> #include <ql/math/optimization/levenbergmarquardt.hpp> #include <ql/math/interpolations/cubicinterpolation.hpp> #include <ql/methods/finitedifferences/meshers/uniform1dmesher.hpp> #include <ql/methods/finitedifferences/meshers/concentrating1dmesher.hpp> #include <ql/methods/finitedifferences/meshers/predefined1dmesher.hpp> #include <ql/methods/finitedifferences/meshers/fdmmeshercomposite.hpp> #include <ql/methods/finitedifferences/operators/fdmlinearoplayout.hpp> #include <ql/methods/finitedifferences/operators/fdmlinearopcomposite.hpp> #include <ql/methods/finitedifferences/operators/nthorderderivativeop.hpp> #include <ql/methods/finitedifferences/operators/secondderivativeop.hpp> #include <ql/methods/finitedifferences/solvers/fdmbackwardsolver.hpp> #include <ql/functional.hpp> #include <numeric> using namespace QuantLib; using namespace boost::unit_test_framework; #ifndef QL_NO_UBLAS_SUPPORT void NthOrderDerivativeOpTest::testSparseMatrixApply() { BOOST_TEST_MESSAGE("Testing sparse matrix apply..."); SparseMatrix sm(5,7); BOOST_CHECK(sm.size1() == SparseMatrix::size_type(5)); BOOST_CHECK(sm.size2() == SparseMatrix::size_type(7)); sm(1,3) = 3.0; const Array x(7,0.0,1.0); const Array y = prod(sm, x); BOOST_CHECK(close_enough(y[0], 0.0)); BOOST_CHECK(close_enough(y[1], 3.0*3.0)); BOOST_CHECK(close_enough(y[2], 0.0)); BOOST_CHECK(close_enough(y[3], 0.0)); BOOST_CHECK(close_enough(y[4], 0.0)); } void NthOrderDerivativeOpTest::testFirstOrder2PointsApply() { BOOST_TEST_MESSAGE("Testing two points first order " "derivative operator apply on an uniform grid..."); const Real dx = 1/5.0; const NthOrderDerivativeOp op(0, 1, 3, ext::make_shared<FdmMesherComposite>( ext::make_shared<Uniform1dMesher>(0.0, 1.0, 6))); const Array x(6,0.0, 1.0); const Array y = op.apply(x); for (Size i=0; i < x.size(); ++i) BOOST_CHECK(close_enough(y[i], 1/dx)); } void NthOrderDerivativeOpTest::testFirstOrder3PointsOnUniformGrid() { BOOST_TEST_MESSAGE("Testing three points first order " "derivative operator on an uniform grid..."); const Real ddx = 1.0/0.2; const SparseMatrix m = NthOrderDerivativeOp(0, 1, 3, ext::make_shared<FdmMesherComposite>( ext::make_shared<Uniform1dMesher>(0.0, 1.0, 6))).toMatrix(); // to reproduce the reference results use // http://web.media.mit.edu/~crtaylor/calculator.html BOOST_CHECK(close_enough(m(2,0), 0.0)); BOOST_CHECK(close_enough(m(2,1), -0.5*ddx)); BOOST_CHECK(m(2,2) < 42*QL_EPSILON); BOOST_CHECK(close_enough(m(2,3), 0.5*ddx)); BOOST_CHECK(close_enough(m(2,4), 0.0)); BOOST_CHECK(close_enough(m(2,5), 0.0)); BOOST_CHECK(close_enough(m(0,0), -3.0/2.0*ddx)); BOOST_CHECK(close_enough(m(0,1), 2.0*ddx)); BOOST_CHECK(close_enough(m(0,2), -0.5*ddx)); BOOST_CHECK(close_enough(m(0,3), 0.0)); BOOST_CHECK(close_enough(m(0,4), 0.0)); BOOST_CHECK(close_enough(m(0,5), 0.0)); BOOST_CHECK(close_enough(m(5,0), 0.0)); BOOST_CHECK(close_enough(m(5,1), 0.0)); BOOST_CHECK(close_enough(m(5,2), 0.0)); BOOST_CHECK(close_enough(m(5,3), 0.5*ddx)); BOOST_CHECK(close_enough(m(5,4), -2.0*ddx)); BOOST_CHECK(close_enough(m(5,5), 3.0/2.0*ddx)); } void NthOrderDerivativeOpTest::testFirstOrder5PointsOnUniformGrid() { BOOST_TEST_MESSAGE("Testing five points first order " "derivative operator on an uniform grid..."); const Real ddx = 1.0/0.4; const SparseMatrix m = NthOrderDerivativeOp(0, 1, 5, ext::make_shared<FdmMesherComposite>( ext::make_shared<Uniform1dMesher>(0.0, 2.0, 6))).toMatrix(); BOOST_CHECK(close_enough(m(2,0), 1.0/12.0*ddx)); BOOST_CHECK(close_enough(m(2,1), -2.0/3.0*ddx)); BOOST_CHECK(m(2,2) < 42*QL_EPSILON); BOOST_CHECK(close_enough(m(2,3), 2.0/3.0*ddx)); BOOST_CHECK(close_enough(m(2,4), -1.0/12.0*ddx)); BOOST_CHECK(close_enough(m(2,5), 0.0)); BOOST_CHECK(close_enough(m(0,0), -25.0/12.0*ddx)); BOOST_CHECK(close_enough(m(0,1), 4.0*ddx)); BOOST_CHECK(close_enough(m(0,2), -3.0*ddx)); BOOST_CHECK(close_enough(m(0,3), 4.0/3.0*ddx)); BOOST_CHECK(close_enough(m(0,4), -0.25*ddx)); BOOST_CHECK(close_enough(m(0,5), 0.0)); BOOST_CHECK(close_enough(m(1,0), -0.25*ddx)); BOOST_CHECK(close_enough(m(1,1), -5.0/6.0*ddx)); BOOST_CHECK(close_enough(m(1,2), 3.0/2.0*ddx)); BOOST_CHECK(close_enough(m(1,3), -0.5*ddx)); BOOST_CHECK(close_enough(m(1,4), 1.0/12.0*ddx)); BOOST_CHECK(close_enough(m(1,5), 0.0)); BOOST_CHECK(close_enough(m(4,5), 0.25*ddx)); BOOST_CHECK(close_enough(m(4,4), 5.0/6.0*ddx)); BOOST_CHECK(close_enough(m(4,3), -3.0/2.0*ddx)); BOOST_CHECK(close_enough(m(4,2), 0.5*ddx)); BOOST_CHECK(close_enough(m(4,1), -1.0/12.0*ddx)); BOOST_CHECK(close_enough(m(4,0), 0.0)); BOOST_CHECK(close_enough(m(5,0), 0.0)); BOOST_CHECK(close_enough(m(5,1), 0.25*ddx)); BOOST_CHECK(close_enough(m(5,2), -4.0/3.0*ddx)); BOOST_CHECK(close_enough(m(5,3), 3.0*ddx)); BOOST_CHECK(close_enough(m(5,4), -4.0*ddx)); BOOST_CHECK(close_enough(m(5,5), 25.0/12.0*ddx)); } void NthOrderDerivativeOpTest::testFirstOrder2PointsOnUniformGrid() { BOOST_TEST_MESSAGE("Testing two points first order " "derivative operator on an uniform grid..."); const Real ddx = 1.0/0.2; const SparseMatrix m = NthOrderDerivativeOp(0, 1, 2, ext::make_shared<FdmMesherComposite>( ext::make_shared<Uniform1dMesher>(0.0, 0.6, 4))).toMatrix(); BOOST_CHECK(close_enough(m(0,0), -ddx)); BOOST_CHECK(close_enough(m(0,1), ddx)); BOOST_CHECK(close_enough(m(0,2), 0.0)); BOOST_CHECK(close_enough(m(0,3), 0.0)); BOOST_CHECK(close_enough(m(1,0), -ddx)); BOOST_CHECK(close_enough(m(1,1), ddx)); BOOST_CHECK(close_enough(m(1,2), 0.0)); BOOST_CHECK(close_enough(m(1,3), 0.0)); BOOST_CHECK(close_enough(m(2,0), 0.0)); BOOST_CHECK(close_enough(m(2,1), -ddx)); BOOST_CHECK(close_enough(m(2,2), ddx)); BOOST_CHECK(close_enough(m(2,3), 0.0)); BOOST_CHECK(close_enough(m(3,0), 0.0)); BOOST_CHECK(close_enough(m(3,1), 0.0)); BOOST_CHECK(close_enough(m(3,2), -ddx)); BOOST_CHECK(close_enough(m(3,3), ddx)); } void NthOrderDerivativeOpTest::testFirstOrder4PointsOnUniformGrid() { BOOST_TEST_MESSAGE("Testing four points first order " "derivative operator on an uniform grid..."); const Real ddx = 1.0/0.2; const SparseMatrix m = NthOrderDerivativeOp(0, 1, 4, ext::make_shared<FdmMesherComposite>( ext::make_shared<Uniform1dMesher>(0.0, 0.6, 4))).toMatrix(); BOOST_CHECK(close_enough(m(0,0), -11.0/6.0*ddx)); BOOST_CHECK(close_enough(m(0,1), 3.0*ddx)); BOOST_CHECK(close_enough(m(0,2), -1.5*ddx)); BOOST_CHECK(close_enough(m(2,3), 1.0/3.0*ddx)); BOOST_CHECK(close_enough(m(1,0), -1.0/3.0*ddx)); BOOST_CHECK(close_enough(m(1,1), -0.5*ddx)); BOOST_CHECK(close_enough(m(1,2), ddx)); BOOST_CHECK(close_enough(m(1,3), -1.0/6.0*ddx)); BOOST_CHECK(close_enough(m(2,0), 1.0/6.0*ddx)); BOOST_CHECK(close_enough(m(2,1), -ddx)); BOOST_CHECK(close_enough(m(2,2), 0.5*ddx)); BOOST_CHECK(close_enough(m(2,3), 1.0/3.0*ddx)); BOOST_CHECK(close_enough(m(3,0), -1.0/3.0*ddx)); BOOST_CHECK(close_enough(m(3,1), 1.5*ddx)); BOOST_CHECK(close_enough(m(3,2), -3.0*ddx)); BOOST_CHECK(close_enough(m(3,3), 11.0/6.0*ddx)); } void NthOrderDerivativeOpTest::testFirstOrder2PointsOn2DimUniformGrid() { BOOST_TEST_MESSAGE("Testing two points first order " "derivative operator on a 2 dimensional uniform grid..."); const Real ddx = 1.0/0.2; const Size xGrid=4; const ext::shared_ptr<FdmMesher> mesher = ext::make_shared<FdmMesherComposite>( ext::make_shared<Uniform1dMesher>(0.0, 1, xGrid), ext::make_shared<Uniform1dMesher>(0.0, 0.4, 3)); const SparseMatrix m = NthOrderDerivativeOp(1, 1, 2, mesher).toMatrix(); const ext::shared_ptr<FdmLinearOpLayout> layout = mesher->layout(); const FdmLinearOpIterator endIter = layout->end(); for (FdmLinearOpIterator iter = layout->begin(); iter!=endIter; ++iter) { const Size i = iter.index(); const Size ix = iter.coordinates()[1]; switch (ix) { case 0: BOOST_CHECK(close_enough(m(i, i ),-ddx)); BOOST_CHECK(close_enough(m(i, i+ xGrid), ddx)); BOOST_CHECK(close_enough(m(i, i+2*xGrid), 0.0)); break; case 1: BOOST_CHECK(close_enough(m(i, i- xGrid),-ddx)); BOOST_CHECK(close_enough(m(i, i ), ddx)); BOOST_CHECK(close_enough(m(i, i+2*xGrid), 0.0)); break; case 2: BOOST_CHECK(close_enough(m(i, i-2*xGrid), 0.0)); BOOST_CHECK(close_enough(m(i, i- xGrid),-ddx)); BOOST_CHECK(close_enough(m(i, i ), ddx)); break; default: QL_FAIL("inconsistent coordinate"); } } } void NthOrderDerivativeOpTest::testSecondOrder3PointsNonUniformGrid() { BOOST_TEST_MESSAGE("Testing three points second order " "derivative operator on a non-uniform grid..."); std::vector<Real> xValues(4); xValues[0] = 0.5; xValues[1] = 1.0; xValues[2] = 2.0; xValues[3] = 4.0; const SparseMatrix m = NthOrderDerivativeOp(0, 2, 3, ext::make_shared<FdmMesherComposite>( ext::make_shared<Predefined1dMesher>(xValues))).toMatrix(); BOOST_CHECK(close_enough(m(0,0), 8.0/3.0)); BOOST_CHECK(close_enough(m(0,1), -4.0)); BOOST_CHECK(close_enough(m(0,2), 4.0/3.0)); BOOST_CHECK(close_enough(m(0,3), 0.0)); BOOST_CHECK(close_enough(m(1,0), 8.0/3.0)); BOOST_CHECK(close_enough(m(1,1), -4.0)); BOOST_CHECK(close_enough(m(1,2), 4.0/3.0)); BOOST_CHECK(close_enough(m(1,3), 0.0)); BOOST_CHECK(close_enough(m(2,0), 0.0)); BOOST_CHECK(close_enough(m(2,1), 2.0/3.0)); BOOST_CHECK(close_enough(m(2,2), -1.0)); BOOST_CHECK(close_enough(m(2,3), 1.0/3.0)); BOOST_CHECK(close_enough(m(3,0), 0.0)); BOOST_CHECK(close_enough(m(3,1), 2.0/3.0)); BOOST_CHECK(close_enough(m(3,2), -1.0)); BOOST_CHECK(close_enough(m(3,3), 1.0/3.0)); } void NthOrderDerivativeOpTest::testSecondOrder4PointsNonUniformGrid() { BOOST_TEST_MESSAGE("Testing four points second order " "derivative operator on a non-uniform grid..."); std::vector<Real> xValues(5); xValues[0] = 0.5; xValues[1] = 1.0; xValues[2] = 2.0; xValues[3] = 4.0; xValues[4] = 8.0; const SparseMatrix m = NthOrderDerivativeOp(0, 2, 4, ext::make_shared<FdmMesherComposite>( ext::make_shared<Predefined1dMesher>(xValues))).toMatrix(); BOOST_CHECK(close_enough(m(0,0), 88.0/21.0)); BOOST_CHECK(close_enough(m(0,1), -140.0/21.0)); BOOST_CHECK(close_enough(m(0,2), 56.0/21.0)); BOOST_CHECK(close_enough(m(0,3), -4.0/21.0)); BOOST_CHECK(close_enough(m(0,4), 0.0)); BOOST_CHECK(close_enough(m(1,0), 64.0/21.0)); BOOST_CHECK(close_enough(m(1,1), -98.0/21.0)); BOOST_CHECK(close_enough(m(1,2), 35.0/21.0)); BOOST_CHECK(close_enough(m(1,3), -1.0/21.0)); BOOST_CHECK(close_enough(m(1,4), 0.0)); BOOST_CHECK(close_enough(m(2,0), 16.0/21.0)); BOOST_CHECK(close_enough(m(2,1), -2.0/3.0)); BOOST_CHECK(close_enough(m(2,2), -1.0/3.0)); BOOST_CHECK(close_enough(m(2,3), 5.0/21.0)); BOOST_CHECK(close_enough(m(2,4), 0.0)); BOOST_CHECK(close_enough(m(3,0), 0.0)); BOOST_CHECK(close_enough(m(3,1), 4.0/21.0)); BOOST_CHECK(close_enough(m(3,2), -1.0/6.0)); BOOST_CHECK(close_enough(m(3,3), -1.0/12.0)); BOOST_CHECK(close_enough(m(3,4), 5.0/84.0)); BOOST_CHECK(close_enough(m(4,0), 0.0)); BOOST_CHECK(close_enough(m(4,1), -20.0/21.0)); BOOST_CHECK(close_enough(m(4,2), 11.0/6.0)); BOOST_CHECK(close_enough(m(4,3), -13.0/12.0)); BOOST_CHECK(close_enough(m(4,4), 17.0/84.0)); } void NthOrderDerivativeOpTest::testThirdOrder4PointsUniformGrid() { BOOST_TEST_MESSAGE("Testing four points third order " "derivative operator on a uniform grid..."); const SparseMatrix m = NthOrderDerivativeOp(0, 3, 4, ext::make_shared<FdmMesherComposite>( ext::make_shared<Uniform1dMesher>(0.0, 0.6, 4))).toMatrix(); for (Size i=0; i < 4; ++i) { BOOST_CHECK(close_enough(m(i,0), -125.0)); BOOST_CHECK(close_enough(m(i,1), 375.0)); BOOST_CHECK(close_enough(m(i,2), -375.0)); BOOST_CHECK(close_enough(m(i,3), 125)); } } namespace { struct GridSetup { Real alpha; Real density; bool cellAvg; bool midPoint; Size nPoints; Size tGrid; Size yGrid; FdmSchemeDesc scheme; }; class FdmHeatEquationOp : public FdmLinearOpComposite { public: FdmHeatEquationOp( Size nPoints, Volatility vol, const ext::shared_ptr<FdmMesher>& mesher, Size direction = 0) : vol2_(0.5*vol*vol), direction_(direction), map_(ext::make_shared<NthOrderDerivativeOp>( direction, 2, nPoints, mesher)), preconditioner_(SecondDerivativeOp(direction, mesher) .mult(Array(mesher->layout()->size(), vol2_))) { } Size size() const { return 1; } void setTime(Time t1, Time t2) { } Disposable<Array> apply(const Array& r) const { return vol2_*map_->apply(r); } Disposable<Array> apply_mixed(const Array& r) const { Array retVal(r.size(), 0.0); return retVal; } Disposable<Array> apply_direction( Size direction, const Array& r) const { if (direction == direction_) return apply(r); else return apply_mixed(r); } Disposable<Array> solve_splitting( Size direction, const Array& r, Real dt) const { using namespace ext::placeholders; if (direction == direction_) { BiCGStabResult result = QuantLib::BiCGstab( ext::function<Disposable<Array>(const Array&)>( ext::bind( &FdmHeatEquationOp::solve_apply, this, _1, -dt)), std::max(Size(10), r.size()), 1e-14, ext::function<Disposable<Array>(const Array&)>( ext::bind(&FdmLinearOpComposite::preconditioner, this, _1, dt)) ).solve(r, r); return result.x; } else { Array retVal(r); return retVal; } } Disposable<Array> preconditioner(const Array& r, Real dt) const { return preconditioner_.solve_splitting(r, dt, 1.0); } private: Disposable<Array> solve_apply(const Array& r, Real dt) const { return r - dt*apply(r); } const Volatility vol2_; const Size direction_; const ext::shared_ptr<FdmLinearOp> map_; const TripleBandLinearOp preconditioner_; }; class AvgPayoffFct { public: AvgPayoffFct(const ext::shared_ptr<PlainVanillaPayoff>& payoff, Volatility vol, Time T, Real growthFactor) : payoff_(payoff), vol2_(0.5*vol*vol*T), growthFactor_(growthFactor) { } Real operator()(Real x) const { return (*payoff_)(std::exp(x - vol2_)*growthFactor_); } private: const ext::shared_ptr<PlainVanillaPayoff> payoff_; const Volatility vol2_; const Real growthFactor_; }; Disposable<Array> priceReport( const GridSetup& setup, const Array& strikes) { const Date today(2, May, 2018); const DayCounter dc = Actual365Fixed(); const Date maturity = today + Period(1, Years); const Time T = dc.yearFraction(today, maturity); const ext::shared_ptr<YieldTermStructure> rTS = flatRate(today, 0.05, dc); const ext::shared_ptr<YieldTermStructure> qTS = flatRate(today, 0.025, dc); const Real S = 100.0; const Volatility vol = 0.2; const Real stdDev = vol * std::sqrt(T); const DiscountFactor df = qTS->discount(maturity)/rTS->discount(maturity); const Real y = std::log(S); const Real ymin = y - setup.alpha*stdDev; const Real ymax = y + setup.alpha*stdDev; const Size yGrid = setup.yGrid; Array diffs(strikes.size()), fdmPrices(strikes.size()); for (Size k=0; k < strikes.size(); ++k) { const Real strike = strikes[k]; const Real specialPoint = std::log(strike/df) + 0.5*vol*vol*T; const ext::shared_ptr<Fdm1dMesher> mesher1d = ext::make_shared<Concentrating1dMesher>( ymin, ymax, yGrid, std::pair<Real, Real>(specialPoint, setup.density)); std::vector<Real> loc = mesher1d->locations(); for (Size i = 0; setup.midPoint && i < loc.size()-1; ++i) if (loc[i] < specialPoint && loc[i+1]>= specialPoint) { const Real d = loc[i+1] - loc[i]; const Real offset = (specialPoint - 0.5*d) - loc[i]; for (Size l = 0; l < loc.size(); ++l) loc[l] += offset; break; } const ext::shared_ptr<FdmMesher> mesher = ext::make_shared<FdmMesherComposite>( ext::make_shared<Predefined1dMesher>(loc)); const Array g = mesher->locations(0); const Array sT = Exp(g - 0.5*vol*vol*T)*df; Array rhs(setup.yGrid); const ext::shared_ptr<PlainVanillaPayoff> payoff = ext::make_shared<PlainVanillaPayoff>(Option::Call, strike); rhs[0] = (*payoff)(sT[0]); rhs[yGrid-1] = (*payoff)(sT[yGrid-1]); for (Size j=1; j < yGrid-1; ++j) if (setup.cellAvg && ( (sT[j] < strike && sT[j+1] >= strike) || (sT[j-1] < strike && sT[j] >= strike))) { const Real gMin = 0.5*(g[j-1]+g[j]); const Real gMax = 0.5*(g[j+1]+g[j]); const AvgPayoffFct f(payoff, vol, T, df); rhs[j] = GaussLobattoIntegral(1000, 1e-12)( f, gMin, gMax)/(gMax - gMin); } else rhs[j] = (*payoff)(sT[j]); const ext::shared_ptr<FdmHeatEquationOp> heatEqn = ext::make_shared<FdmHeatEquationOp>( setup.nPoints, vol, mesher); FdmBackwardSolver solver( heatEqn, FdmBoundaryConditionSet(), ext::shared_ptr<FdmStepConditionComposite>(), setup.scheme); solver.rollback(rhs, T, 0.0, setup.tGrid, 0); rhs *= rTS->discount(maturity); const Real fdmPrice = MonotonicCubicNaturalSpline( g.begin(), g.end(), rhs.begin())(y); const Real npv = blackFormula(payoff, S*df, stdDev, rTS->discount(maturity)); diffs[k] = npv-fdmPrice; } return diffs; } class FdmMispricingCostFunction : public CostFunction { public: FdmMispricingCostFunction( const GridSetup& setup, const Array& strikes) : setup_(setup), strikes_(strikes) { } Disposable<Array> values(const Array& x) const { const GridSetup g = { x[0], x[1], setup_.cellAvg, setup_.midPoint, setup_.nPoints, setup_.tGrid, setup_.yGrid, setup_.scheme }; try { return priceReport(g, strikes_); } catch (std::exception const&) { Array q(2, 1000); return q; } } private: const GridSetup setup_; const Array strikes_; }; } void NthOrderDerivativeOpTest::testHigerOrderBSOptionPricing() { BOOST_TEST_MESSAGE("Testing Black-Scholes option pricing convergence with " "higher order finite difference operators..."); SavedSettings backup; Array strikes(8); strikes << 50, 75, 90, 100, 110, 125, 150, 200; const GridSetup initSetup = { 5.2, 0.1, true, false, 5, 31, 51, FdmSchemeDesc::Douglas() }; Array initialValues(2); initialValues << initSetup.alpha, initSetup.density; FdmMispricingCostFunction costFct(initSetup, strikes); NoConstraint noConstraint; Problem p(costFct, noConstraint, initialValues); LevenbergMarquardt().minimize( p, EndCriteria(400, 40, 1.0e-6, 1.0e-6, 1.0e-6)); const GridSetup optimalSetup = { p.currentValue()[0], p.currentValue()[1], initSetup.cellAvg, initSetup.midPoint, initSetup.nPoints, initSetup.tGrid, initSetup.yGrid/2, initSetup.scheme }; const Array q = priceReport(optimalSetup, strikes); const Real ac = std::sqrt(DotProduct(q,q)/q.size()); const Real convergence = std::log(ac/p.functionValue())*M_LOG2E; if (convergence < 3.6) { BOOST_ERROR("convergence order is too low" << "\n expected convergence: 4.0" << "\n measured convergence: " << convergence << "\n tolerance : 0.4"); } } namespace { Real priceQuality(Real h) { Array strikes(1); strikes << 100; const Size yGrid = Size(1/h); const GridSetup setup = { 5.20966, 0.00130581, true, false, 5, 801, yGrid, FdmSchemeDesc::Douglas() }; return std::fabs(priceReport(setup, strikes)[0]); } } void NthOrderDerivativeOpTest::testHigerOrderAndRichardsonExtrapolationg() { BOOST_TEST_MESSAGE( "Testing Black-Scholes option pricing convergence with " "higher order FDM operators and Richardson Extrapolation..."); SavedSettings backup; const Real n1 = priceQuality(1.0/50); const Real n3 = std::fabs(RichardsonExtrapolation(priceQuality, 1.0/50, 4.0)(2.0)); const Real r2 = std::log(n1/n3)*M_LOG2E; if (r2 < 4.9) { BOOST_ERROR("convergence order is too low using Richardson extrapolation" << "\n expected convergence: 5.0" << "\n measured convergence: " << r2 << "\n tolerance : 0.1"); } } #endif test_suite* NthOrderDerivativeOpTest::suite() { test_suite* suite = BOOST_TEST_SUITE("NthOrderDerivativeOp tests"); #ifndef QL_NO_UBLAS_SUPPORT suite->add(QUANTLIB_TEST_CASE( &NthOrderDerivativeOpTest::testSparseMatrixApply)); suite->add(QUANTLIB_TEST_CASE( &NthOrderDerivativeOpTest::testFirstOrder2PointsApply)); suite->add(QUANTLIB_TEST_CASE( &NthOrderDerivativeOpTest::testFirstOrder3PointsOnUniformGrid)); suite->add(QUANTLIB_TEST_CASE( &NthOrderDerivativeOpTest::testFirstOrder5PointsOnUniformGrid)); suite->add(QUANTLIB_TEST_CASE( &NthOrderDerivativeOpTest::testFirstOrder2PointsOnUniformGrid)); suite->add(QUANTLIB_TEST_CASE( &NthOrderDerivativeOpTest::testFirstOrder4PointsOnUniformGrid)); suite->add(QUANTLIB_TEST_CASE( &NthOrderDerivativeOpTest::testFirstOrder2PointsOn2DimUniformGrid)); suite->add(QUANTLIB_TEST_CASE( &NthOrderDerivativeOpTest::testSecondOrder3PointsNonUniformGrid)); suite->add(QUANTLIB_TEST_CASE( &NthOrderDerivativeOpTest::testSecondOrder4PointsNonUniformGrid)); suite->add(QUANTLIB_TEST_CASE( &NthOrderDerivativeOpTest::testThirdOrder4PointsUniformGrid)); suite->add(QUANTLIB_TEST_CASE( &NthOrderDerivativeOpTest::testHigerOrderBSOptionPricing)); suite->add(QUANTLIB_TEST_CASE( &NthOrderDerivativeOpTest::testHigerOrderAndRichardsonExtrapolationg)); #endif return suite; }
// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // 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 co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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 "shell_browser_context.h" #include "base/bind.h" #include "base/command_line.h" #include "base/environment.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/threading/thread.h" #include "base/values.h" #include "content/public/browser/browser_thread.h" #include "nw_package.h" #include "shell_download_manager_delegate.h" #include "shell_resource_context.h" #include "shell_switches.h" #include "shell_url_request_context_getter.h" #if defined(OS_WIN) #include "base/base_paths_win.h" #elif defined(OS_LINUX) #include "base/nix/xdg_util.h" #elif defined(OS_MACOSX) #include "base/base_paths_mac.h" #endif namespace content { ShellBrowserContext::ShellBrowserContext(bool off_the_record) : off_the_record_(off_the_record) { InitWhileIOAllowed(); } ShellBrowserContext::~ShellBrowserContext() { if (resource_context_.get()) { BrowserThread::DeleteSoon( BrowserThread::IO, FROM_HERE, resource_context_.release()); } } void ShellBrowserContext::InitWhileIOAllowed() { CommandLine* cmd_line = CommandLine::ForCurrentProcess(); if (cmd_line->HasSwitch(switches::kDumpRenderTree)) { CHECK(testing_path_.CreateUniqueTempDir()); path_ = testing_path_.path(); return; } if (cmd_line->HasSwitch(switches::kContentShellDataPath)) { path_ = cmd_line->GetSwitchValuePath(switches::kContentShellDataPath); return; } base::DictionaryValue *manifest = nw::GetManifest(); FilePath::StringType name( #if defined(OS_WIN) L"node-webkit" #else "node-webkit" #endif ); manifest->GetString(switches::kmName, &name); #if defined(OS_WIN) CHECK(PathService::Get(base::DIR_LOCAL_APP_DATA, &path_)); path_ = path_.Append(name); #elif defined(OS_LINUX) scoped_ptr<base::Environment> env(base::Environment::Create()); FilePath config_dir( base::nix::GetXDGDirectory(env.get(), base::nix::kXdgConfigHomeEnvVar, base::nix::kDotConfigDir)); path_ = config_dir.Append(name); #elif defined(OS_MACOSX) CHECK(PathService::Get(base::DIR_APP_DATA, &path_)); path_ = path_.Append(name); #elif defined(OS_ANDROID) DCHECK(PathService::Get(base::DIR_ANDROID_APP_DATA, &path_)); path_ = path_.Append(name); #else NOTIMPLEMENTED(); #endif if (!file_util::PathExists(path_)) file_util::CreateDirectory(path_); } FilePath ShellBrowserContext::GetPath() { return path_; } bool ShellBrowserContext::IsOffTheRecord() const { return off_the_record_; } DownloadManagerDelegate* ShellBrowserContext::GetDownloadManagerDelegate() { DownloadManager* manager = BrowserContext::GetDownloadManager(this); if (!download_manager_delegate_.get()) { download_manager_delegate_ = new ShellDownloadManagerDelegate(); download_manager_delegate_->SetDownloadManager(manager); } return download_manager_delegate_.get(); } net::URLRequestContextGetter* ShellBrowserContext::GetRequestContext() { if (!url_request_getter_) { url_request_getter_ = new ShellURLRequestContextGetter( GetPath(), BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::IO), BrowserThread::UnsafeGetMessageLoopForThread(BrowserThread::FILE)); } return url_request_getter_; } net::URLRequestContextGetter* ShellBrowserContext::GetRequestContextForRenderProcess( int renderer_child_id) { return GetRequestContext(); } net::URLRequestContextGetter* ShellBrowserContext::GetMediaRequestContext() { return GetRequestContext(); } net::URLRequestContextGetter* ShellBrowserContext::GetMediaRequestContextForRenderProcess( int renderer_child_id) { return GetRequestContext(); } ResourceContext* ShellBrowserContext::GetResourceContext() { if (!resource_context_.get()) { resource_context_.reset(new ShellResourceContext( static_cast<ShellURLRequestContextGetter*>(GetRequestContext()))); } return resource_context_.get(); } GeolocationPermissionContext* ShellBrowserContext::GetGeolocationPermissionContext() { return NULL; } SpeechRecognitionPreferences* ShellBrowserContext::GetSpeechRecognitionPreferences() { return NULL; } bool ShellBrowserContext::DidLastSessionExitCleanly() { return true; } quota::SpecialStoragePolicy* ShellBrowserContext::GetSpecialStoragePolicy() { return NULL; } } // namespace content
#include "global.h" #include "GameConstantsAndTypes.h" #include "MusicWheel.h" #include "RageTimer.h" #include "RageUtil.h" #include "ThemeManager.h" #include "WheelNotifyIcon.h" #include "WheelNotifyIcon.h" /* todo: replace this entire thing with a set of AutoActors and a Scroller. * In reality, everything except the Beginner/Training icon can be replicated * in Lua (in stock StepMania 4), so I'm not sure if we even need this... -aj */ static ThemeMetric<bool> SHOW_TRAINING("WheelNotifyIcon", "ShowTraining"); static ThemeMetric<bool> BLINK_BEST_ICON("WheelNotifyIcon", "BlinkPlayersBest"); static ThemeMetric<int> NUM_ICONS_TO_SHOW("WheelNotifyIcon", "NumIconsToShow"); WheelNotifyIcon::WheelNotifyIcon() { // Load( THEME->GetPathG("MusicWheelItem","WheelNotifyIcon") ); Load(THEME->GetPathG("WheelNotifyIcon", "icons 4x2")); StopAnimating(); } void WheelNotifyIcon::SetFlags(Flags flags) { m_vIconsToShow.clear(); // push onto vector in highest to lowest priority switch (flags.iPlayersBestNumber) { case 1: m_vIconsToShow.push_back(best1); break; case 2: m_vIconsToShow.push_back(best2); break; case 3: m_vIconsToShow.push_back(best3); break; } if (flags.bEdits) m_vIconsToShow.push_back(edits); switch (flags.iStagesForSong) { case 1: break; case 2: m_vIconsToShow.push_back(long_ver); break; case 3: m_vIconsToShow.push_back(marathon); break; default: FAIL_M(ssprintf("flags.iStagesForSong = %d", flags.iStagesForSong)); } if (flags.bHasBeginnerOr1Meter && (bool)SHOW_TRAINING) m_vIconsToShow.push_back(training); // If BLINK_BEST_ICON, make player's best icon blink if it's the only icon. if (m_vIconsToShow.size() == 1 && BLINK_BEST_ICON) { if (m_vIconsToShow[0] >= best1 && m_vIconsToShow[0] <= best3) m_vIconsToShow.push_back(empty); } m_vIconsToShow.resize( min(m_vIconsToShow.size(), static_cast<unsigned int>(NUM_ICONS_TO_SHOW))); // Broadcast Set message so items can react. (futures) -aj // Message msg("Set"); // this->HandleMessage( msg ); /* Make sure the right icon is selected, since we might be drawn before * we get another update. */ Update(0); } bool WheelNotifyIcon::EarlyAbortDraw() const { if (m_vIconsToShow.empty()) return true; return Sprite::EarlyAbortDraw(); } void WheelNotifyIcon::Update(float fDeltaTime) { if (m_vIconsToShow.size() > 0) { /* We should probably end up parsing the vector and then dynamically * insert flag icons based on "priority". Easy to do, hopefully - Midiman */ const float fSecondFraction = fmodf(RageTimer::GetTimeSinceStartFast(), 1); const int index = (int)(fSecondFraction * m_vIconsToShow.size()); Sprite::SetState(m_vIconsToShow[index]); } Sprite::Update(fDeltaTime); } /* * (c) 2001-2004 Chris Danford * All rights reserved. * * 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, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
// // Input.cpp // EnginePrototype // // Created by Samir Sinha on 1/15/16. // // #include "Input.hpp" #include <SDL2/SDL_events.h> #include <SDL2/SDL_keyboard.h> #include <SDL2/SDL_mouse.h> #include <cinek/debug.h> namespace cinek { namespace input { bool InputState::testKey(uint8_t key) const { CK_ASSERT_RETURN_VALUE(key < keystateArraySize, false); return keystate[key]; } bool InputState::testKeyMod(int mod) const { return (keyModifiers & mod) != 0; } uint32_t processSDLEvent(InputState& state, const SDL_Event& event) { uint32_t flags = 0; switch (event.type) { case SDL_QUIT: flags |= kPollSDLEvent_Quit; break; case SDL_WINDOWEVENT: break; case SDL_MOUSEWHEEL: if (event.wheel.which != SDL_TOUCH_MOUSEID) { state.mxWheel += event.wheel.x; state.myWheel += event.wheel.y; } break; case SDL_KEYDOWN: case SDL_KEYUP: break; case SDL_TEXTINPUT: break; default: break; } return flags; } } /* namespace uicore */ } /* namespace cinek */
/* * Copyright 2021 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <SPL/Runtime/ProcessingElement/PEMetricsImpl.h> #include <NAM/NAM_NameService.h> #include <SAM/augmentedApplicationModel.h> #include <SPL/Runtime/Common/RuntimeMessage.h> #include <SPL/Runtime/Common/SystemMetricInfoFactory.h> #include <SPL/Runtime/ProcessingElement/PEImpl.h> #include <SPL/Runtime/ProcessingElement/PETransportPorts.h> #include <UTILS/HostInfo.h> #include <cassert> #include <sstream> #include <string> #include <sys/resource.h> using namespace SPL; using namespace std; using namespace Distillery; using namespace Streams; PEMetricsImpl::PEMetricsImpl(PEImpl& pe) : pe_(pe) { uint32_t numIps = pe_.getPEModel().inputPorts().inputPort().size(); uint32_t numOps = pe_.getPEModel().outputPorts().outputPort().size(); inputMetricsRaw_ = new InputPortMetricBlock[numIps]; outputMetricsRaw_ = new OutputPortMetricBlock[numOps]; // Check metric count assert(SystemMetricInfoFactory::getSystemMetricInfoCount( SystemMetricInfoFactory::PEInputPort) == nFinalPunctsProcessed + 1); assert(SystemMetricInfoFactory::getSystemMetricInfoCount( SystemMetricInfoFactory::PEOutputPort) == nConnections + 1); // input port metrics for (uint32_t i = 0; i < numIps; ++i) { createInputPortMetric(i, nTuplesProcessed, "nTuplesProcessed"); createInputPortMetric(i, nTupleBytesProcessed, "nTupleBytesProcessed"); createInputPortMetric(i, nWindowPunctsProcessed, "nWindowPunctsProcessed"); createInputPortMetric(i, nFinalPunctsProcessed, "nFinalPunctsProcessed"); } // output port metrics for (uint32_t i = 0; i < numOps; ++i) { createOutputPortMetric(i, nTuplesSubmitted, "nTuplesSubmitted"); createOutputPortMetric(i, nTupleBytesSubmitted, "nTupleBytesSubmitted"); createOutputPortMetric(i, nWindowPunctsSubmitted, "nWindowPunctsSubmitted"); createOutputPortMetric(i, nFinalPunctsSubmitted, "nFinalPunctsSubmitted"); createOutputPortMetric(i, nBrokenConnections, "nBrokenConnections"); createOutputPortMetric(i, nRequiredConnecting, "nRequiredConnecting"); createOutputPortMetric(i, nOptionalConnecting, "nOptionalConnecting"); createOutputPortMetric(i, nTuplesTransmitted, "nTuplesTransmitted"); createOutputPortMetric(i, nTupleBytesTransmitted, "nTupleBytesTransmitted"); createOutputPortMetric(i, nConnections, "nConnections"); } } PEMetricsImpl::~PEMetricsImpl() { APPTRC(L_DEBUG, "Deallocating metrics data structure for PE " << "'" << pe_.getPEId() << "'", SPL_METRIC_DBG); for (size_t i = 0, iu = inputMetrics_.size(); i < iu; ++i) { for (size_t j = 0, ju = inputMetrics_[i].size(); j < ju; ++j) { dumpMetricAtExit(*inputMetrics_[i][j]); delete inputMetrics_[i][j]; } } for (size_t i = 0, iu = outputMetrics_.size(); i < iu; ++i) { for (size_t j = 0, ju = outputMetrics_[i].size(); j < ju; ++j) { dumpMetricAtExit(*outputMetrics_[i][j]); delete outputMetrics_[i][j]; } } delete[] inputMetricsRaw_; delete[] outputMetricsRaw_; } void PEMetricsImpl::dumpMetricAtExit(Metric& metric) { if (!pe_.isStandalone()) { APPTRC((pe_.hasFailedOperators() ? L_ERROR : L_DEBUG), SPL_RUNTIME_PE_METRIC_FINAL_VALUE(metric.getDescription(), metric.getValueNoLock()), SPL_METRIC_DBG); } } void PEMetricsImpl::createInputPortMetric(uint32_t port, InputPortMetricName name, string const& shortName) { SystemMetricInfo const& mi = SystemMetricInfoFactory::getSystemMetricInfo(shortName, SystemMetricInfoFactory::PEInputPort); assert((InputPortMetricName)mi.getIndex() == name); const string& longName = mi.getDescription(); Metric::Kind kind = mi.getKind(); SystemMetricImpl* m = createPortMetric(port, shortName, longName, kind, &(inputMetricsRaw_[port][name])); if (inputMetrics_.size() == port) { inputMetrics_.push_back(vector<SystemMetricImpl*>()); } inputMetrics_[port].push_back(m); inputMetricsRaw_[port][name].store(0, boost::memory_order_relaxed); } void PEMetricsImpl::createOutputPortMetric(uint32_t port, OutputPortMetricName name, string const& shortName) { SystemMetricInfo const& mi = SystemMetricInfoFactory::getSystemMetricInfo( shortName, SystemMetricInfoFactory::PEOutputPort); assert((OutputPortMetricName)mi.getIndex() == name); const string& longName = mi.getDescription(); Metric::Kind kind = mi.getKind(); SystemMetricImpl* m = createPortMetric(port, shortName, longName, kind, &(outputMetricsRaw_[port][name])); if (outputMetrics_.size() == port) { outputMetrics_.push_back(vector<SystemMetricImpl*>()); } outputMetrics_[port].push_back(m); outputMetricsRaw_[port][name].store(0, boost::memory_order_relaxed); } SystemMetricImpl* PEMetricsImpl::createPortMetric(uint32_t port, string const& shortName, string const& longName, Metric::Kind kind, boost::atomic<int64_t>* value) { stringstream strLong; strLong.imbue(locale::classic()); strLong << longName << " (port " << port << ")"; SystemMetricImpl* np = new SystemMetricImpl(shortName, strLong.str(), kind, value); return np; } /// Fill in system PE metrics data (PE ports) void PEMetricsImpl::getMetrics(PEMetricsInfo& peMetrics) const { uint32_t numIps = pe_.getPEModel().inputPorts().inputPort().size(); uint32_t numOps = pe_.getPEModel().outputPorts().outputPort().size(); // input port metrics for (uint32_t i = 0; i < numIps; ++i) { APPTRC(L_TRACE, "Get input port metric" << i, SPL_METRIC_DBG); InputPortMetricBlock& m = inputMetricsRaw_[i]; PortMetricsInfo pmi(i); for (uint32_t j = 0; j < numInputPortMetrics; j++) { pmi.addMetrics(m[j]); } peMetrics.addInputPortMetrics(pmi); } APPTRC(L_TRACE, "Finished input metrics", SPL_METRIC_DBG); // output port metrics for (uint32_t i = 0; i < numOps; ++i) { APPTRC(L_TRACE, "Get output port metric " << i, SPL_METRIC_DBG); OutputPortMetricBlock& m = outputMetricsRaw_[i]; PEOutputPortMetricsInfo pmi(i); for (uint32_t j = 0; j < numOutputPortMetrics; j++) { pmi.addMetrics(m[j]); } // We need to add the congestion factor for the output port // Also put in a 0 for nTuplesFilteredOut at this time vector<DataSender::OutputCongestion> congestionfactors; vector<PETransportOPort::FilterMetric> metrics; APPTRC(L_TRACE, "Get congestion factors", SPL_METRIC_DBG); pe_.getCongestionFactorsAndMetrics(i, congestionfactors, metrics); for (uint32_t j = 0, uj = congestionfactors.size(); j < uj; j++) { APPTRC(L_TRACE, "Process congestion factor " << j, SPL_METRIC_DBG); const DataSender::OutputCongestion& cf = congestionfactors[j]; vector<int64_t> opm; // Congestion factor opm.push_back(cf.congestionFactor); // nTuplesFilteredOut int64_t nTuplesFilteredOut = 0; for (uint32_t k = 0, uk = metrics.size(); k < uk; k++) { PETransportOPort::FilterMetric& fm = metrics[k]; if (fm.match(cf.receiverPEId, cf.receiverPortId)) { nTuplesFilteredOut = fm.nTuplesFilteredOut(); break; } } opm.push_back(nTuplesFilteredOut); pmi.addConnectionMetric(cf.receiverPEId, cf.receiverPortId, opm); } peMetrics.addOutputPortMetrics(pmi); } APPTRC(L_TRACE, "Finished output metrics", SPL_METRIC_DBG); }
// pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys. // The pbrt source code is licensed under the Apache License, Version 2.0. // SPDX: Apache-2.0 #include <pbrt/util/lowdiscrepancy.h> #include <pbrt/util/bits.h> #include <pbrt/util/parallel.h> #include <pbrt/util/primes.h> #include <pbrt/util/print.h> #include <pbrt/util/shuffle.h> #include <pbrt/util/stats.h> namespace pbrt { std::string DigitPermutation::ToString() const { std::string s = StringPrintf( "[ DigitPermitation base: %d nDigits: %d permutations: ", base, nDigits); for (int digitIndex = 0; digitIndex < nDigits; ++digitIndex) { s += StringPrintf("[%d] ( ", digitIndex); for (int digitValue = 0; digitValue < base; ++digitValue) { s += StringPrintf("%d", permutations[digitIndex * base + digitValue]); if (digitValue != base - 1) s += ", "; } s += ") "; } return s + " ]"; } // HaltonIndexer Local Constants constexpr int HaltonPixelIndexer::MaxHaltonResolution; // HaltonIndexer Method Definitions HaltonPixelIndexer::HaltonPixelIndexer(const Point2i &fullResolution) { // Find radical inverse base scales and exponents that cover sampling area for (int i = 0; i < 2; ++i) { int base = (i == 0) ? 2 : 3; int scale = 1, exp = 0; while (scale < std::min(fullResolution[i], MaxHaltonResolution)) { scale *= base; ++exp; } baseScales[i] = scale; baseExponents[i] = exp; } // Compute multiplicative inverses for _baseScales_ multInverse[0] = multiplicativeInverse(baseScales[1], baseScales[0]); multInverse[1] = multiplicativeInverse(baseScales[0], baseScales[1]); } uint64_t HaltonPixelIndexer::multiplicativeInverse(int64_t a, int64_t n) { int64_t x, y; extendedGCD(a, n, &x, &y); return Mod(x, n); } void HaltonPixelIndexer::extendedGCD(uint64_t a, uint64_t b, int64_t *x, int64_t *y) { if (b == 0) { *x = 1; *y = 0; return; } int64_t d = a / b, xp, yp; extendedGCD(b, a % b, &xp, &yp); *x = yp; *y = xp - (d * yp); } std::string ToString(RandomizeStrategy r) { switch (r) { case RandomizeStrategy::None: return "None"; case RandomizeStrategy::CranleyPatterson: return "CranleyPatterson"; case RandomizeStrategy::Xor: return "Xor"; case RandomizeStrategy::Owen: return "Owen"; default: LOG_FATAL("Unhandled RandomizeStrategy"); return ""; } } // Low Discrepancy Static Functions template <int base> PBRT_NOINLINE PBRT_CPU_GPU static Float RadicalInverseSpecialized(uint64_t a) { const Float invBase = (Float)1 / (Float)base; uint64_t reversedDigits = 0; Float invBaseN = 1; while (a) { uint64_t next = a / base; uint64_t digit = a - next * base; reversedDigits = reversedDigits * base + digit; invBaseN *= invBase; a = next; } DCHECK_LT(reversedDigits * invBaseN, 1.00001); return std::min(reversedDigits * invBaseN, OneMinusEpsilon); } template <int base> PBRT_NOINLINE PBRT_CPU_GPU static Float ScrambledRadicalInverseSpecialized( uint64_t a, const DigitPermutation &perm) { CHECK_EQ(perm.base, base); const Float invBase = (Float)1 / (Float)base; uint64_t reversedDigits = 0; Float invBaseN = 1; int digitIndex = 0; while (1 - invBaseN < 1) { uint64_t next = a / base; int digitValue = a - next * base; reversedDigits = reversedDigits * base + perm.Permute(digitIndex, digitValue); invBaseN *= invBase; ++digitIndex; a = next; } return std::min(invBaseN * reversedDigits, OneMinusEpsilon); } // Low Discrepancy Function Definitions pstd::vector<DigitPermutation> *ComputeRadicalInversePermutations(uint32_t seed, Allocator alloc) { pstd::vector<DigitPermutation> *perms = alloc.new_object<pstd::vector<DigitPermutation>>(alloc); perms->resize(PrimeTableSize); ParallelFor(0, PrimeTableSize, [&perms, &alloc, seed](int64_t i) { (*perms)[i] = DigitPermutation(Primes[i], seed, alloc); }); return perms; } } // namespace pbrt
#pragma once #include <limits> #include <seqan3/alignment/matrix/alignment_score_matrix.hpp> #include <seqan3/alignment/matrix/alignment_trace_matrix.hpp> namespace seqan3::literal {} namespace seqan3::fixture { using namespace seqan3::literal; using detail::alignment_coordinate; static constexpr auto INF = std::numeric_limits<int>::max(); static constexpr auto NON = detail::trace_directions::none; static constexpr auto D = detail::trace_directions::diagonal; static constexpr auto U = detail::trace_directions::up; static constexpr auto L = detail::trace_directions::left; static constexpr auto DU = D | U; static constexpr auto UL = U | L; static constexpr auto DL = D | L; static constexpr auto DUL = D | U | L; template <typename sequence1_t, typename sequence2_t, typename config_t, typename score_t, typename score_matrix_t, typename trace_matrix_t> struct alignment_fixture { template <typename trace_t> alignment_fixture( sequence1_t && _sequence1, sequence2_t && _sequence2, config_t _config, score_t _score, std::string _gapped_sequence1, std::string _gapped_sequence2, alignment_coordinate _end_coordinate, std::vector<score_t> _score_vector, std::vector<trace_t> _trace_vector ) : sequence1{_sequence1}, sequence2{_sequence2}, config{_config}, score{_score}, gapped_sequence1{_gapped_sequence1}, gapped_sequence2{_gapped_sequence2}, end_coordinate{_end_coordinate}, score_matrix{std::move(_score_vector), sequence2.size()+1, sequence1.size()+1}, trace_matrix{std::move(_trace_vector), sequence2.size()+1, sequence1.size()+1} { } sequence1_t sequence1; sequence2_t sequence2; config_t config; score_t score; std::string gapped_sequence1; std::string gapped_sequence2; alignment_coordinate end_coordinate; score_matrix_t score_matrix; trace_matrix_t trace_matrix; }; template <typename sequence1_t, typename sequence2_t, typename config_t, typename score_t, typename trace_t> alignment_fixture( sequence1_t && _sequence1, sequence2_t && _sequence2, config_t _config, score_t _score, std::string _gapped_sequence1, std::string _gapped_sequence2, alignment_coordinate _end_coordinate, std::vector<score_t> _score_vector, std::vector<trace_t> _trace_vector ) -> alignment_fixture< sequence1_t, sequence2_t, config_t, score_t, detail::alignment_score_matrix<std::vector<score_t>>, detail::alignment_trace_matrix<std::vector<trace_t>> >; } // namespace seqan3::fixture
#pragma comment(linker, "/stack:640000000") #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <climits> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <iomanip> #include <iterator> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <utility> #include <vector> using namespace std; const double EPS = 1e-9; const int INF = 0x7f7f7f7f; const double PI=acos(-1.0); #define READ(f) freopen(f, "r", stdin) #define WRITE(f) freopen(f, "w", stdout) #define MP(x, y) make_pair(x, y) #define PB(x) push_back(x) #define rep(i,n) for(int i = 1 ; i<=(n) ; i++) #define repI(i,n) for(int i = 0 ; i<(n) ; i++) #define FOR(i,L,R) for (int i = (int)(L); i <= (int)(R); i++) #define ROF(i,L,R) for (int i = (int)(L); i >= (int)(R); i--) #define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++) #define ALL(p) p.begin(),p.end() #define ALLR(p) p.rbegin(),p.rend() #define SET(p) memset(p, -1, sizeof(p)) #define CLR(p) memset(p, 0, sizeof(p)) #define MEM(p, v) memset(p, v, sizeof(p)) #define getI(a) scanf("%d", &a) #define getII(a,b) scanf("%d%d", &a, &b) #define getIII(a,b,c) scanf("%d%d%d", &a, &b, &c) #define getL(a) scanf("%lld",&a) #define getLL(a,b) scanf("%lld%lld",&a,&b) #define getLLL(a,b,c) scanf("%lld%lld%lld",&a,&b,&c) #define getC(n) scanf("%c",&n) #define getF(n) scanf("%lf",&n) #define getS(n) scanf("%s",n) #define bitCheck(N,in) ((bool)(N&(1<<(in)))) #define bitOff(N,in) (N&(~(1<<(in)))) #define bitOn(N,in) (N|(1<<(in))) #define bitCount(a) __builtin_popcount(a) #define iseq(a,b) (fabs(a-b)<EPS) #define UNIQUE(V) (V).erase(unique((V).begin(),(V).end()),(V).end()) #define vi vector < int > #define vii vector < vector < int > > #define pii pair< int, int > #define ff first #define ss second #define ll long long #define ull unsigned long long template< class T > inline T _abs(T n) { return ((n) < 0 ? -(n) : (n)); } template< class T > inline T _max(T a, T b) { return (!((a)<(b))?(a):(b)); } template< class T > inline T _min(T a, T b) { return (((a)<(b))?(a):(b)); } template< class T > inline T _swap(T &a, T &b) { a=a^b;b=a^b;a=a^b;} template< class T > inline T gcd(T a, T b) { return (b) == 0 ? (a) : gcd((b), ((a) % (b))); } template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b)) * (b)); } template <typename T> string NumberToString ( T Number ) { ostringstream ss; ss << Number; return ss.str(); } #ifdef dipta007 #define debug(args...) {cerr<<"Debug: "; dbg,args; cerr<<endl;} #else #define debug(args...) // Just strip off all debug tokens #endif struct debugger{ template<typename T> debugger& operator , (const T& v){ cerr<<v<<" "; return *this; } }dbg; int main() { #ifdef dipta007 //READ("in.txt"); // WRITE("in.txt"); #endif // dipta007 // ios_base::sync_with_stdio(0);cin.tie(0); int n; while(~getI(n)) { int a[n+4]; FOR(i,1,n) { getI(a[i]); } int maxy = 0; int pos = -1; FOR(i,1,n) { if(a[i]==1) { int sz = 1; int now = 1; FOR(j,i+1,n) { if(a[j]==now+1) { now ++ ; sz ++; } } if(sz>maxy) { maxy = sz; pos = i; } } } if(pos==-1) { printf("0\n"); continue; } vi v; int now = 0; FOR(i,pos,n) { if(a[i]==now+1) { v.PB(i+2000); now++; } } printf("%d\n",v.size()); FOR(i,0,(int)v.size()-1) { if(i) printf(" "); printf("%d",v[i]); } printf("\n"); } return 0; }
#include "Halide.h" #include "benchmark.h" #include <cstdio> #include <chrono> using namespace Halide; int main(int argc, char **argv) { ImageParam src(UInt(8), 1); Func dst; Var x; dst(x) = src(x); dst.vectorize(x, 32, TailStrategy::GuardWithIf); dst.compile_to_assembly("halide_memcpy.s", {src}, "halide_memcpy"); dst.compile_jit(); const int32_t buffer_size = 12345678; Buffer<uint8_t> input(buffer_size); Buffer<uint8_t> output(buffer_size); src.set(input); double t1 = benchmark(10, 10, [&]() { dst.realize(output); }); double t2 = benchmark(10, 10, [&]() { memcpy(output.data(), input.data(), input.width()); }); printf("system memcpy: %.3e byte/s\n", buffer_size / t2); printf("halide memcpy: %.3e byte/s\n", buffer_size / t1); // memcpy will win by a little bit for large inputs because it uses streaming stores if (t1 > t2 * 3) { printf("Halide memcpy is slower than it should be.\n"); return -1; } printf("Success!\n"); return 0; }
// ____ ______ __ // / __ \ / ____// / // / /_/ // / / / // / ____// /___ / /___ PixInsight Class Library // /_/ \____//_____/ PCL 2.4.9 // ---------------------------------------------------------------------------- // Standard TIFF File Format Module Version 1.0.8 // ---------------------------------------------------------------------------- // TIFFPreferencesDialog.cpp - Released 2021-04-09T19:41:31Z // ---------------------------------------------------------------------------- // This file is part of the standard TIFF PixInsight module. // // Copyright (c) 2003-2021 Pleiades Astrophoto S.L. All Rights Reserved. // // Redistribution and use in both source and binary forms, with or without // modification, is permitted provided that the following conditions are met: // // 1. All redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. All redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names // of their contributors, may be used to endorse or promote products derived // from this software without specific prior written permission. For written // permission, please contact info@pixinsight.com. // // 4. All products derived from this software, in any form whatsoever, must // reproduce the following acknowledgment in the end-user documentation // and/or other materials provided with the product: // // "This product is based on software from the PixInsight project, developed // by Pleiades Astrophoto and its contributors (https://pixinsight.com/)." // // Alternatively, if that is where third-party acknowledgments normally // appear, this acknowledgment must be reproduced in the product itself. // // THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS 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 PLEIADES ASTROPHOTO OR ITS // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS // INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE, // DATA OR PROFITS) 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 "TIFFPreferencesDialog.h" #include <float.h> namespace pcl { // ---------------------------------------------------------------------------- TIFFPreferencesDialog::TIFFPreferencesDialog( const TIFFFormat::OutOfRangePolicyOptions& r, const TIFFFormat::EmbeddingOverrides& o, const TIFFImageOptions& f ) : outOfRange( r ) , overrides( o ) , tiffOptions( f ) { pcl::Font fnt = Font(); int labelWidth = fnt.Width( String( "64-bit IEEE 754 floating point" ) + 'M' ); int labelWidth1 = fnt.Width( String( "How to proceed:" ) + 'M' ); int editWidth = fnt.Width( String( '0', 30 ) ); // LowerRange_NumericEdit.label.SetText( "Lower Range:" ); LowerRange_NumericEdit.label.SetMinWidth( labelWidth1 ); LowerRange_NumericEdit.SetReal( true ); LowerRange_NumericEdit.SetRange( -DBL_MAX, +DBL_MAX ); LowerRange_NumericEdit.SetPrecision( 15 ); LowerRange_NumericEdit.EnableScientificNotation(); LowerRange_NumericEdit.SetScientificNotationTriggerExponent( 5 ); LowerRange_NumericEdit.edit.SetFixedWidth( editWidth ); LowerRange_NumericEdit.sizer.AddStretch(); LowerRange_NumericEdit.SetToolTip( "<p>Lower range of read TIFF floating point pixel samples</p>" ); LowerRange_NumericEdit.SetValue( outOfRange.lowerRange ); UpperRange_NumericEdit.label.SetText( "Upper Range:" ); UpperRange_NumericEdit.label.SetMinWidth( labelWidth1 ); UpperRange_NumericEdit.SetReal( true ); UpperRange_NumericEdit.SetRange( -DBL_MAX, +DBL_MAX ); UpperRange_NumericEdit.SetPrecision( 15 ); UpperRange_NumericEdit.EnableScientificNotation(); UpperRange_NumericEdit.SetScientificNotationTriggerExponent( 5 ); UpperRange_NumericEdit.edit.SetFixedWidth( editWidth ); UpperRange_NumericEdit.sizer.AddStretch(); UpperRange_NumericEdit.SetToolTip( "<p>Upper range of read TIFF floating point pixel samples</p>" ); UpperRange_NumericEdit.SetValue( outOfRange.upperRange ); ReadRange_Sizer.SetMargin( 6 ); ReadRange_Sizer.SetSpacing( 4 ); ReadRange_Sizer.Add( LowerRange_NumericEdit ); ReadRange_Sizer.Add( UpperRange_NumericEdit ); ReadRange_GroupBox.SetTitle( "Default Floating Point Input Range" ); ReadRange_GroupBox.SetSizer( ReadRange_Sizer ); ReadRange_GroupBox.AdjustToContents(); // const char* readRangeModeToolTip = "<p>This parameter specifies how to proceed when pixel values in a read " "TIFF image exceed the default input range.</p>" "<p><b>** Important **</b> If the 'Ignore' option is selected for 'Action' " "(see below), this option will be ignored (not applied). Please read the tooltip " "information provided for the 'Action' combo box below.</p>"; ReadRangeMode_Label.SetText( "How to proceed:" ); ReadRangeMode_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); ReadRangeMode_Label.SetMinWidth( labelWidth1 ); ReadRangeMode_Label.SetToolTip( readRangeModeToolTip ); ReadRangeMode_ComboBox.AddItem( "Normalize to the default input range" ); ReadRangeMode_ComboBox.AddItem( "Ask on out-of-range read values" ); ReadRangeMode_ComboBox.AddItem( "Always ask" ); ReadRangeMode_ComboBox.SetToolTip( readRangeModeToolTip ); ReadRangeMode_ComboBox.SetCurrentItem( outOfRange.outOfRangePolicy ); ReadRangeMode_Sizer.SetSpacing( 4 ); ReadRangeMode_Sizer.Add( ReadRangeMode_Label ); ReadRangeMode_Sizer.Add( ReadRangeMode_ComboBox, 100 ); const char* readRescaleModeToolTip = "<p>This parameter specifies how to fix input pixel samples that " "exceed the default input range in a read FITS image.</p>" "<p><b>** Warning **</b> If you select the 'Ignore' option, out-of-range pixel " "values will not be fixed. Images with out-of-range pixels will not be " "rendered correctly on the screen and may cause problems with some tools." "If you select this option, platform stability is not guaranteed. Use this " "option <b><u>at your own risk.</u></b></p>"; ReadRescaleMode_Label.SetText( "Action:" ); ReadRescaleMode_Label.SetTextAlignment( TextAlign::Right|TextAlign::VertCenter ); ReadRescaleMode_Label.SetMinWidth( labelWidth1 ); ReadRescaleMode_Label.SetToolTip( readRescaleModeToolTip ); ReadRescaleMode_ComboBox.AddItem( "Rescale image on out-of-range values" ); ReadRescaleMode_ComboBox.AddItem( "Truncate all out-of-range values" ); ReadRescaleMode_ComboBox.AddItem( "Ignore out-of-range values" ); ReadRescaleMode_ComboBox.SetToolTip( readRescaleModeToolTip ); ReadRescaleMode_ComboBox.SetCurrentItem( outOfRange.outOfRangeFixMode ); ReadRescaleMode_Sizer.SetSpacing( 4 ); ReadRescaleMode_Sizer.Add( ReadRescaleMode_Label ); ReadRescaleMode_Sizer.Add( ReadRescaleMode_ComboBox, 100 ); ReadRangeOptions_Sizer.SetMargin( 6 ); ReadRangeOptions_Sizer.SetSpacing( 4 ); ReadRangeOptions_Sizer.Add( ReadRangeMode_Sizer ); ReadRangeOptions_Sizer.Add( ReadRescaleMode_Sizer ); ReadRangeOptions_GroupBox.SetTitle( "Floating Point Out Of Range Policy" ); ReadRangeOptions_GroupBox.SetSizer( ReadRangeOptions_Sizer ); ReadRangeOptions_GroupBox.AdjustToContents(); // NoCompression_RadioButton.SetText( "None" ); NoCompression_RadioButton.SetMinWidth( labelWidth ); NoCompression_RadioButton.SetChecked( tiffOptions.compression == pcl::TIFFCompression::None ); ZIP_RadioButton.SetText( "ZIP" ); ZIP_RadioButton.SetMinWidth( labelWidth ); ZIP_RadioButton.SetChecked( tiffOptions.compression == pcl::TIFFCompression::ZIP ); LZW_RadioButton.SetText( "LZW" ); LZW_RadioButton.SetMinWidth( labelWidth ); LZW_RadioButton.SetChecked( tiffOptions.compression == pcl::TIFFCompression::LZW ); Compression_Sizer.SetMargin( 6 ); Compression_Sizer.SetSpacing( 4 ); Compression_Sizer.Add( NoCompression_RadioButton ); Compression_Sizer.Add( ZIP_RadioButton ); Compression_Sizer.Add( LZW_RadioButton ); Compression_GroupBox.SetTitle( "Compression" ); Compression_GroupBox.SetSizer( Compression_Sizer ); Compression_GroupBox.AdjustToContents(); // ICCProfile_CheckBox.SetText( "ICC Profile" ); ICCProfile_CheckBox.SetMinWidth( labelWidth ); ICCProfile_CheckBox.SetTristateMode(); ICCProfile_CheckBox.SetToolTip( "Override global core application settings for embedded ICC profiles." ); ICCProfile_CheckBox.SetState( overrides.overrideICCProfileEmbedding ? (overrides.embedICCProfiles ? CheckState::Checked : CheckState::Unchecked) : CheckState::ThirdState ); EmbeddedData_Sizer.SetMargin( 6 ); EmbeddedData_Sizer.SetSpacing( 4 ); EmbeddedData_Sizer.Add( ICCProfile_CheckBox ); EmbeddedData_GroupBox.SetTitle( "Override Embedding Settings" ); EmbeddedData_GroupBox.SetSizer( EmbeddedData_Sizer ); EmbeddedData_GroupBox.AdjustToContents(); // Planar_CheckBox.SetText( "Planar organization" ); Planar_CheckBox.AdjustToContents(); Planar_CheckBox.SetMinSize(); Planar_CheckBox.SetToolTip( "Write each color channel in a separate data block, or <i>plane</i>." ); Planar_CheckBox.SetChecked( tiffOptions.planar ); AssociatedAlpha_CheckBox.SetText( "Associated alpha channel" ); AssociatedAlpha_CheckBox.AdjustToContents(); AssociatedAlpha_CheckBox.SetMinSize(); AssociatedAlpha_CheckBox.SetToolTip( "Select the active alpha channel as the associated image transparency." ); AssociatedAlpha_CheckBox.SetChecked( tiffOptions.associatedAlpha ); PremultipliedAlpha_CheckBox.SetText( "Premultiplied alpha channel" ); PremultipliedAlpha_CheckBox.AdjustToContents(); PremultipliedAlpha_CheckBox.SetMinSize(); PremultipliedAlpha_CheckBox.SetToolTip( "Write RGB/K components premultiplied by the active alpha channel." ); PremultipliedAlpha_CheckBox.SetChecked( tiffOptions.premultipliedAlpha ); Miscellaneous_Sizer.SetMargin( 6 ); Miscellaneous_Sizer.SetSpacing( 4 ); Miscellaneous_Sizer.Add( Planar_CheckBox ); Miscellaneous_Sizer.Add( AssociatedAlpha_CheckBox ); Miscellaneous_Sizer.Add( PremultipliedAlpha_CheckBox ); Miscellaneous_GroupBox.SetTitle( "Miscellaneous Options" ); Miscellaneous_GroupBox.SetSizer( Miscellaneous_Sizer ); Miscellaneous_GroupBox.AdjustToContents(); // LeftPanel_Sizer.SetSpacing( 6 ); LeftPanel_Sizer.Add( Compression_GroupBox ); LeftPanel_Sizer.Add( EmbeddedData_GroupBox ); LeftPanel_Sizer.Add( Miscellaneous_GroupBox ); LeftPanel_Sizer.AddStretch(); // ImageCopyright_TextBox.SetText( tiffOptions.copyright ); ImageCopyright_Sizer.SetMargin( 6 ); ImageCopyright_Sizer.Add( ImageCopyright_TextBox ); ImageCopyright_GroupBox.SetTitle( "Image Copyright" ); ImageCopyright_GroupBox.SetSizer( ImageCopyright_Sizer ); SoftwareDescription_TextBox.SetText( tiffOptions.software ); SoftwareDescription_Sizer.SetMargin( 6 ); SoftwareDescription_Sizer.Add( SoftwareDescription_TextBox ); SoftwareDescription_GroupBox.SetTitle( "Software Description" ); SoftwareDescription_GroupBox.SetSizer( SoftwareDescription_Sizer ); // Reset_PushButton.SetText( "Reset" ); Reset_PushButton.SetDefault(); Reset_PushButton.OnClick( (pcl::Button::click_event_handler)&TIFFPreferencesDialog::Button_Click, *this ); OK_PushButton.SetText( "OK" ); OK_PushButton.SetDefault(); OK_PushButton.SetCursor( StdCursor::Checkmark ); OK_PushButton.OnClick( (pcl::Button::click_event_handler)&TIFFPreferencesDialog::Button_Click, *this ); Cancel_PushButton.SetText( "Cancel" ); Cancel_PushButton.SetCursor( StdCursor::Crossmark ); Cancel_PushButton.OnClick( (pcl::Button::click_event_handler)&TIFFPreferencesDialog::Button_Click, *this ); Buttons_Sizer.SetSpacing( 8 ); Buttons_Sizer.Add( Reset_PushButton ); Buttons_Sizer.AddStretch(); Buttons_Sizer.Add( OK_PushButton ); Buttons_Sizer.Add( Cancel_PushButton ); // RightPanel_Sizer.SetSpacing( 6 ); RightPanel_Sizer.Add( ImageCopyright_GroupBox, 75 ); RightPanel_Sizer.Add( SoftwareDescription_GroupBox, 25 ); RightPanel_Sizer.AddSpacing( 8 ); RightPanel_Sizer.Add( Buttons_Sizer ); // BottomSection_Sizer.SetSpacing( 16 ); BottomSection_Sizer.Add( LeftPanel_Sizer ); BottomSection_Sizer.Add( RightPanel_Sizer ); // Global_Sizer.SetMargin( 8 ); Global_Sizer.SetSpacing( 8 ); Global_Sizer.Add( ReadRange_GroupBox ); Global_Sizer.Add( ReadRangeOptions_GroupBox ); Global_Sizer.AddSpacing( 8 ); Global_Sizer.Add( BottomSection_Sizer ); SetSizer( Global_Sizer ); EnsureLayoutUpdated(); AdjustToContents(); SetFixedSize(); SetWindowTitle( "TIFF Format Preferences" ); OnReturn( (pcl::Dialog::return_event_handler)&TIFFPreferencesDialog::Dialog_Return, *this ); } // ---------------------------------------------------------------------------- void TIFFPreferencesDialog::Button_Click( Button& sender, bool /*checked*/ ) { if ( sender == Reset_PushButton ) { LowerRange_NumericEdit.SetValue( 0 ); UpperRange_NumericEdit.SetValue( 1 ); ReadRangeMode_ComboBox.SetCurrentItem( TIFFFormat::OutOfRangePolicy_Default ); ReadRescaleMode_ComboBox.SetCurrentItem( TIFFFormat::OutOfRangeFix_Default ); ICCProfile_CheckBox.SetState( CheckState::ThirdState ); TIFFImageOptions o; NoCompression_RadioButton.SetChecked( o.compression == TIFFCompression::None ); ZIP_RadioButton.SetChecked( o.compression == TIFFCompression::ZIP ); LZW_RadioButton.SetChecked( o.compression == TIFFCompression::LZW ); // ### PCL 1.1: Consider suppressing Planar_CheckBox.SetChecked( o.planar ); AssociatedAlpha_CheckBox.SetChecked( o.associatedAlpha ); PremultipliedAlpha_CheckBox.SetChecked( o.premultipliedAlpha ); ImageCopyright_TextBox.SetText( o.copyright ); SoftwareDescription_TextBox.SetText( o.software ); } else if ( sender == OK_PushButton ) Ok(); else Cancel(); } // ---------------------------------------------------------------------------- void TIFFPreferencesDialog::Dialog_Return( Dialog& sender, int retVal ) { if ( retVal == StdDialogCode::Ok ) { outOfRange.lowerRange = LowerRange_NumericEdit.Value(); outOfRange.upperRange = UpperRange_NumericEdit.Value(); outOfRange.outOfRangePolicy = TIFFFormat::out_of_range_policy( ReadRangeMode_ComboBox.CurrentItem() ); outOfRange.outOfRangeFixMode = TIFFFormat::out_of_range_fix_mode( ReadRescaleMode_ComboBox.CurrentItem() ); overrides.overrideICCProfileEmbedding = ICCProfile_CheckBox.State() != CheckState::ThirdState; overrides.embedICCProfiles = ICCProfile_CheckBox.IsChecked(); if ( NoCompression_RadioButton.IsChecked() ) tiffOptions.compression = TIFFCompression::None; else if ( ZIP_RadioButton.IsChecked() ) tiffOptions.compression = TIFFCompression::ZIP; else if ( LZW_RadioButton.IsChecked() ) // ### PCL 1.1: Consider suppressing tiffOptions.compression = TIFFCompression::LZW; tiffOptions.planar = Planar_CheckBox.IsChecked(); tiffOptions.associatedAlpha = AssociatedAlpha_CheckBox.IsChecked(); tiffOptions.premultipliedAlpha = PremultipliedAlpha_CheckBox.IsChecked(); tiffOptions.copyright = ImageCopyright_TextBox.Text(); tiffOptions.copyright.Trim(); tiffOptions.software = SoftwareDescription_TextBox.Text(); tiffOptions.software.Trim(); } } // ---------------------------------------------------------------------------- } // pcl // ---------------------------------------------------------------------------- // EOF TIFFPreferencesDialog.cpp - Released 2021-04-09T19:41:31Z
/*========================================================================= Program: Visualization Toolkit Module: vtkCurveRepresentation.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 "vtkCurveRepresentation.h" #include "vtkActor.h" #include "vtkAssemblyPath.h" #include "vtkBoundingBox.h" #include "vtkCallbackCommand.h" #include "vtkCamera.h" #include "vtkCellArray.h" #include "vtkCellPicker.h" #include "vtkConeSource.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkInteractorObserver.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkPickingManager.h" #include "vtkPlaneSource.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderer.h" #include "vtkSphereSource.h" #include "vtkTransform.h" #include <algorithm> #include <assert.h> #include <iterator> //---------------------------------------------------------------------------- vtkCurveRepresentation::vtkCurveRepresentation() { this->LastEventPosition[0] = VTK_DOUBLE_MAX; this->LastEventPosition[1] = VTK_DOUBLE_MAX; this->LastEventPosition[2] = VTK_DOUBLE_MAX; this->Bounds[0] = VTK_DOUBLE_MAX; this->Bounds[1] = -VTK_DOUBLE_MAX; this->Bounds[2] = VTK_DOUBLE_MAX; this->Bounds[3] = -VTK_DOUBLE_MAX; this->Bounds[4] = VTK_DOUBLE_MAX; this->Bounds[5] = -VTK_DOUBLE_MAX; this->HandleSize = 5.0; this->InteractionState = vtkCurveRepresentation::Outside; this->ProjectToPlane = 0; //default off this->ProjectionNormal = 0; //default YZ not used this->ProjectionPosition = 0.0; this->PlaneSource = nullptr; this->Closed = 0; // Build the representation of the widget this->DirectionalLine = false; // Create the handles along a straight line within the bounds of a unit cube this->NumberOfHandles = 5; this->Handle = new vtkActor* [this->NumberOfHandles]; this->HandleGeometry = new HandleSource*[this->NumberOfHandles]; for ( int i = 0; i < this->NumberOfHandles; ++i ) { this->HandleGeometry[i] = HandleSource::New(); vtkPolyDataMapper* handleMapper = vtkPolyDataMapper::New(); handleMapper->SetInputConnection( this->HandleGeometry[i]->GetOutputPort()); this->Handle[i] = vtkActor::New(); this->Handle[i]->SetMapper(handleMapper); handleMapper->Delete(); } this->LineActor = vtkActor::New(); // Default bounds to get started double bounds[6] = { -0.5, 0.5, -0.5, 0.5, -0.5, 0.5 }; // Initial creation of the widget, serves to initialize it this->PlaceFactor = 1.0; this->PlaceWidget(bounds); // Manage the picking stuff this->HandlePicker = vtkCellPicker::New(); this->HandlePicker->SetTolerance(0.005); for ( int i = 0; i < this->NumberOfHandles; ++i ) { this->HandlePicker->AddPickList(this->Handle[i]); } this->HandlePicker->PickFromListOn(); this->LinePicker = vtkCellPicker::New(); this->LinePicker->SetTolerance(0.01); this->LinePicker->AddPickList(this->LineActor); this->LinePicker->PickFromListOn(); this->LastPickPosition[0] = VTK_DOUBLE_MAX; this->LastPickPosition[1] = VTK_DOUBLE_MAX; this->LastPickPosition[2] = VTK_DOUBLE_MAX; this->CurrentHandle = nullptr; this->CurrentHandleIndex = -1; this->FirstSelected = true; this->Transform = vtkTransform::New(); // Set up the initial properties this->HandleProperty = nullptr; this->SelectedHandleProperty = nullptr; this->LineProperty = nullptr; this->SelectedLineProperty = nullptr; this->CreateDefaultProperties(); this->Centroid[0] = 0.0; this->Centroid[1] = 0.0; this->Centroid[2] = 0.0; this->TranslationAxis = Axis::NONE; } //---------------------------------------------------------------------------- vtkCurveRepresentation::~vtkCurveRepresentation() { this->LineActor->Delete(); for ( int i = 0; i < this->NumberOfHandles; ++i ) { this->HandleGeometry[i]->Delete(); this->Handle[i]->Delete(); } delete [] this->Handle; delete [] this->HandleGeometry; this->HandlePicker->Delete(); this->LinePicker->Delete(); if ( this->HandleProperty ) { this->HandleProperty->Delete(); } if ( this->SelectedHandleProperty ) { this->SelectedHandleProperty->Delete(); } if ( this->LineProperty ) { this->LineProperty->Delete(); } if ( this->SelectedLineProperty ) { this->SelectedLineProperty->Delete(); } this->Transform->Delete(); } //---------------------------------------------------------------------- void vtkCurveRepresentation::SetDirectionalLine(bool val) { if (this->DirectionalLine == val) { return; } this->DirectionalLine = val; this->Modified(); if (this->NumberOfHandles < 2) { return; } if (this->DirectionalLine) { this->HandleGeometry[this->NumberOfHandles - 1]->SetUseSphere(false); } else { this->HandleGeometry[this->NumberOfHandles - 1]->SetUseSphere(true); } } //---------------------------------------------------------------------------- void vtkCurveRepresentation::SetClosed(vtkTypeBool closed) { if ( this->Closed == closed ) { return; } this->Closed = closed; this->BuildRepresentation(); } //---------------------------------------------------------------------- void vtkCurveRepresentation::RegisterPickers() { vtkPickingManager* pm = this->GetPickingManager(); if (!pm) { return; } pm->AddPicker(this->HandlePicker, this); pm->AddPicker(this->LinePicker, this); } //---------------------------------------------------------------------------- void vtkCurveRepresentation::SetHandlePosition(int handle, double x, double y, double z) { if ( handle < 0 || handle >= this->NumberOfHandles ) { vtkErrorMacro(<<"vtkCurveRepresentation: handle index out of range."); return; } this->HandleGeometry[handle]->SetCenter(x, y, z); this->HandleGeometry[handle]->Update(); if ( this->ProjectToPlane ) { this->ProjectPointsToPlane(); } this->BuildRepresentation(); } //---------------------------------------------------------------------------- void vtkCurveRepresentation::SetHandlePosition(int handle, double xyz[3]) { this->SetHandlePosition(handle,xyz[0],xyz[1],xyz[2]); } //---------------------------------------------------------------------------- void vtkCurveRepresentation::GetHandlePosition(int handle, double xyz[3]) { if ( handle < 0 || handle >= this->NumberOfHandles ) { vtkErrorMacro(<<"vtkCurveRepresentation: handle index out of range."); return; } this->HandleGeometry[handle]->GetCenter(xyz); } //---------------------------------------------------------------------------- double* vtkCurveRepresentation::GetHandlePosition(int handle) { if ( handle < 0 || handle >= this->NumberOfHandles ) { vtkErrorMacro(<<"vtkCurveRepresentation: handle index out of range."); return nullptr; } return this->HandleGeometry[handle]->GetCenter(); } //---------------------------------------------------------------------------- void vtkCurveRepresentation::ProjectPointsToPlane() { if ( this->ProjectionNormal == VTK_PROJECTION_OBLIQUE ) { if ( this->PlaneSource != nullptr ) { this->ProjectPointsToObliquePlane(); } else { vtkGenericWarningMacro(<<"Set the plane source for oblique projections..."); } } else { this->ProjectPointsToOrthoPlane(); } } //---------------------------------------------------------------------------- void vtkCurveRepresentation::ProjectPointsToObliquePlane() { double o[3]; double u[3]; double v[3]; this->PlaneSource->GetPoint1(u); this->PlaneSource->GetPoint2(v); this->PlaneSource->GetOrigin(o); int i; for ( i = 0; i < 3; ++i ) { u[i] = u[i] - o[i]; v[i] = v[i] - o[i]; } vtkMath::Normalize(u); vtkMath::Normalize(v); double o_dot_u = vtkMath::Dot(o,u); double o_dot_v = vtkMath::Dot(o,v); double fac1; double fac2; double ctr[3]; for ( i = 0; i < this->NumberOfHandles; ++i ) { this->HandleGeometry[i]->GetCenter(ctr); fac1 = vtkMath::Dot(ctr,u) - o_dot_u; fac2 = vtkMath::Dot(ctr,v) - o_dot_v; ctr[0] = o[0] + fac1*u[0] + fac2*v[0]; ctr[1] = o[1] + fac1*u[1] + fac2*v[1]; ctr[2] = o[2] + fac1*u[2] + fac2*v[2]; this->HandleGeometry[i]->SetCenter(ctr); this->HandleGeometry[i]->Update(); } } //---------------------------------------------------------------------------- void vtkCurveRepresentation::ProjectPointsToOrthoPlane() { double ctr[3]; for ( int i = 0; i < this->NumberOfHandles; ++i ) { this->HandleGeometry[i]->GetCenter(ctr); ctr[this->ProjectionNormal] = this->ProjectionPosition; this->HandleGeometry[i]->SetCenter(ctr); this->HandleGeometry[i]->Update(); } } //---------------------------------------------------------------------------- int vtkCurveRepresentation::GetHandleIndex(vtkProp* prop) { auto iter = std::find(this->Handle, this->Handle + this->NumberOfHandles, static_cast<vtkActor*>(prop)); return (iter != this->Handle + NumberOfHandles) ? static_cast<int>(std::distance(this->Handle, iter)) : -1; } //---------------------------------------------------------------------------- void vtkCurveRepresentation::SetCurrentHandleIndex(int index) { if (index < -1 || index >= this->NumberOfHandles) { index = -1; } if (index != this->CurrentHandleIndex) { this->CurrentHandleIndex = index; this->HighlightHandle(index == -1 ? nullptr : this->Handle[index]); } } //---------------------------------------------------------------------------- int vtkCurveRepresentation::HighlightHandle(vtkProp *prop) { // First unhighlight anything picked if (this->CurrentHandle) { this->CurrentHandle->SetProperty(this->HandleProperty); } this->CurrentHandle = static_cast<vtkActor *>(prop); if (this->CurrentHandle) { this->CurrentHandle->SetProperty(this->SelectedHandleProperty); return this->GetHandleIndex(prop); } return -1; } //---------------------------------------------------------------------------- void vtkCurveRepresentation::HighlightLine(int highlight) { if ( highlight ) { this->LineActor->SetProperty(this->SelectedLineProperty); } else { this->LineActor->SetProperty(this->LineProperty); } } //---------------------------------------------------------------------------- void vtkCurveRepresentation::MovePoint(double *p1, double *p2) { if ( this->CurrentHandleIndex < 0 || this->CurrentHandleIndex >= this->NumberOfHandles ) { vtkGenericWarningMacro(<<"Poly line handle index out of range."); return; } // Get the motion vector double v[3] = {0,0,0}; // Move the center of the handle along the motion vector if (this->TranslationAxis == Axis::NONE) { v[0] = p2[0] - p1[0]; v[1] = p2[1] - p1[1]; v[2] = p2[2] - p1[2]; } // Translation restriction handling else { v[this->TranslationAxis] = p2[this->TranslationAxis] - p1[this->TranslationAxis]; } double* ctr = this->HandleGeometry[this->CurrentHandleIndex]->GetCenter(); double newCtr[3]; newCtr[0] = ctr[0] + v[0]; newCtr[1] = ctr[1] + v[1]; newCtr[2] = ctr[2] + v[2]; this->HandleGeometry[this->CurrentHandleIndex]->SetCenter(newCtr); this->HandleGeometry[this->CurrentHandleIndex]->Update(); } //---------------------------------------------------------------------------- void vtkCurveRepresentation::Translate(double *p1, double *p2) { // Get the motion vector double v[3] = {0,0,0}; // Move the center of the handle along the motion vector if (this->TranslationAxis == Axis::NONE) { v[0] = p2[0] - p1[0]; v[1] = p2[1] - p1[1]; v[2] = p2[2] - p1[2]; } // Translation restriction handling else { // this->TranslationAxis in [0,2] assert(this->TranslationAxis > -1 && this->TranslationAxis < 3 && "this->TranslationAxis shoud be in [0,2]"); v[this->TranslationAxis] = p2[this->TranslationAxis] - p1[this->TranslationAxis]; } double newCtr[3]; for ( int i = 0; i < this->NumberOfHandles; ++i ) { double* ctr = this->HandleGeometry[i]->GetCenter(); for ( int j = 0; j < 3; ++j ) { newCtr[j] = ctr[j] + v[j]; } this->HandleGeometry[i]->SetCenter(newCtr); this->HandleGeometry[i]->Update(); } } //---------------------------------------------------------------------------- void vtkCurveRepresentation::Scale(double *p1, double *p2, int vtkNotUsed(X), int Y) { // Get the motion vector double v[3]; v[0] = p2[0] - p1[0]; v[1] = p2[1] - p1[1]; v[2] = p2[2] - p1[2]; double center[3] = {0.0,0.0,0.0}; double avgdist = 0.0; double* prevctr = this->HandleGeometry[0]->GetCenter(); double* ctr; center[0] += prevctr[0]; center[1] += prevctr[1]; center[2] += prevctr[2]; int i; for ( i = 1; i < this->NumberOfHandles; ++i ) { ctr = this->HandleGeometry[i]->GetCenter(); center[0] += ctr[0]; center[1] += ctr[1]; center[2] += ctr[2]; avgdist += sqrt(vtkMath::Distance2BetweenPoints(ctr,prevctr)); prevctr = ctr; } avgdist /= this->NumberOfHandles; center[0] /= this->NumberOfHandles; center[1] /= this->NumberOfHandles; center[2] /= this->NumberOfHandles; // Compute the scale factor double sf = vtkMath::Norm(v) / avgdist; if ( Y > this->LastEventPosition[1] ) { sf = 1.0 + sf; } else { sf = 1.0 - sf; } // Move the handle points double newCtr[3]; for ( i = 0; i < this->NumberOfHandles; ++i ) { ctr = this->HandleGeometry[i]->GetCenter(); for ( int j = 0; j < 3; ++j ) { newCtr[j] = sf * (ctr[j] - center[j]) + center[j]; } this->HandleGeometry[i]->SetCenter(newCtr); this->HandleGeometry[i]->Update(); } } //---------------------------------------------------------------------------- void vtkCurveRepresentation::Spin(double *p1, double *p2, double *vpn) { // Mouse motion vector in world space double v[3]; v[0] = p2[0] - p1[0]; v[1] = p2[1] - p1[1]; v[2] = p2[2] - p1[2]; // Axis of rotation double axis[3] = {0.0,0.0,0.0}; if ( this->ProjectToPlane ) { if ( this->ProjectionNormal == VTK_PROJECTION_OBLIQUE) { if (this->PlaneSource != nullptr ) { double* normal = this->PlaneSource->GetNormal(); axis[0] = normal[0]; axis[1] = normal[1]; axis[2] = normal[2]; vtkMath::Normalize( axis ); } else { axis[0] = 1.; } } else { axis[ this->ProjectionNormal ] = 1.; } } else { // Create axis of rotation and angle of rotation vtkMath::Cross(vpn,v,axis); if ( vtkMath::Normalize(axis) == 0.0 ) { return; } } // Radius vector (from mean center to cursor position) double rv[3] = {p2[0] - this->Centroid[0], p2[1] - this->Centroid[1], p2[2] - this->Centroid[2]}; // Distance between center and cursor location double rs = vtkMath::Normalize(rv); // Spin direction double ax_cross_rv[3]; vtkMath::Cross(axis,rv,ax_cross_rv); // Spin angle double theta = 360.0 * vtkMath::Dot(v,ax_cross_rv) / rs; // Manipulate the transform to reflect the rotation this->Transform->Identity(); this->Transform->Translate(this->Centroid[0],this->Centroid[1],this->Centroid[2]); this->Transform->RotateWXYZ(theta,axis); this->Transform->Translate(-this->Centroid[0],-this->Centroid[1],-this->Centroid[2]); // Set the handle points double newCtr[3]; double ctr[3]; for ( int i = 0; i < this->NumberOfHandles; ++i ) { this->HandleGeometry[i]->GetCenter(ctr); this->Transform->TransformPoint(ctr,newCtr); this->HandleGeometry[i]->SetCenter(newCtr); this->HandleGeometry[i]->Update(); } } //---------------------------------------------------------------------------- void vtkCurveRepresentation::CreateDefaultProperties() { this->HandleProperty = vtkProperty::New(); this->HandleProperty->SetColor(1,1,1); this->SelectedHandleProperty = vtkProperty::New(); this->SelectedHandleProperty->SetColor(1,0,0); this->LineProperty = vtkProperty::New(); this->LineProperty->SetRepresentationToWireframe(); this->LineProperty->SetAmbient(1.0); this->LineProperty->SetColor(1.0,1.0,0.0); this->LineProperty->SetLineWidth(2.0); this->SelectedLineProperty = vtkProperty::New(); this->SelectedLineProperty->SetRepresentationToWireframe(); this->SelectedLineProperty->SetAmbient(1.0); this->SelectedLineProperty->SetAmbientColor(0.0,1.0,0.0); this->SelectedLineProperty->SetLineWidth(2.0); } //---------------------------------------------------------------------------- void vtkCurveRepresentation::SetProjectionPosition(double position) { this->ProjectionPosition = position; if ( this->ProjectToPlane ) { this->ProjectPointsToPlane(); } this->BuildRepresentation(); } //---------------------------------------------------------------------------- void vtkCurveRepresentation::SetPlaneSource(vtkPlaneSource* plane) { if (this->PlaneSource == plane) { return; } this->PlaneSource = plane; } //---------------------------------------------------------------------------- void vtkCurveRepresentation::Initialize() { int i; for ( i = 0; i < this->NumberOfHandles; ++i ) { this->HandlePicker->DeletePickList(this->Handle[i]); this->HandleGeometry[i]->Delete(); this->Handle[i]->Delete(); } this->NumberOfHandles = 0; delete [] this->Handle; delete [] this->HandleGeometry; } //---------------------------------------------------------------------------- void vtkCurveRepresentation::SizeHandles() { if (this->NumberOfHandles > 0) { double radius = this->SizeHandlesInPixels(1.5, this->HandleGeometry[0]->GetCenter()); for ( int i = 0; i < this->NumberOfHandles; ++i ) { this->HandleGeometry[i]->SetRadius(radius); } } } //---------------------------------------------------------------------------- void vtkCurveRepresentation::CalculateCentroid() { this->Centroid[0] = 0.0; this->Centroid[1] = 0.0; this->Centroid[2] = 0.0; double ctr[3]; for ( int i = 0; i < this->NumberOfHandles; ++i ) { this->HandleGeometry[i]->GetCenter(ctr); this->Centroid[0] += ctr[0]; this->Centroid[1] += ctr[1]; this->Centroid[2] += ctr[2]; } this->Centroid[0] /= this->NumberOfHandles; this->Centroid[1] /= this->NumberOfHandles; this->Centroid[2] /= this->NumberOfHandles; } //---------------------------------------------------------------------------- void vtkCurveRepresentation::EraseHandle(const int& index) { if ( this->NumberOfHandles < 3 || index < 0 || index >= this->NumberOfHandles ) { return; } vtkPoints* newpoints = vtkPoints::New(VTK_DOUBLE); newpoints->SetNumberOfPoints(this->NumberOfHandles-1); int count = 0; for (int i = 0; i < this->NumberOfHandles; ++i ) { if ( i != index ) { newpoints->SetPoint(count++, this->HandleGeometry[i]->GetCenter()); } } this->InitializeHandles(newpoints); newpoints->Delete(); } //---------------------------------------------------------------------------- vtkTypeBool vtkCurveRepresentation::IsClosed() { if ( this->NumberOfHandles < 3 || !this->Closed ) { return 0; } vtkPolyData* lineData = vtkPolyData::New(); this->GetPolyData(lineData); if ( !lineData || !(lineData->GetPoints()) ) { vtkErrorMacro(<<"No line data to query geometric closure"); return 0; } vtkPoints *points = lineData->GetPoints(); int numPoints = points->GetNumberOfPoints(); if ( numPoints < 3 ) { return 0; } int numEntries = lineData->GetLines()->GetNumberOfConnectivityEntries(); double p0[3]; double p1[3]; points->GetPoint( 0, p0 ); points->GetPoint( numPoints - 1, p1 ); int minusNth = ( p0[0] == p1[0] && p0[1] == p1[1] && p0[2] == p1[2] ) ? 1 : 0; int result; if ( minusNth ) //definitely closed { result = 1; } else // not physically closed, check connectivity { result = ( ( numEntries - numPoints ) == 2 ) ? 1 : 0; } return result; } //---------------------------------------------------------------------------- void vtkCurveRepresentation::ReleaseGraphicsResources(vtkWindow* win) { this->LineActor->ReleaseGraphicsResources(win); for (int cc=0; cc < this->NumberOfHandles; cc++) { this->Handle[cc]->ReleaseGraphicsResources(win); } } //---------------------------------------------------------------------------- int vtkCurveRepresentation::RenderOpaqueGeometry(vtkViewport* win) { this->BuildRepresentation(); int count = 0; count += this->LineActor->RenderOpaqueGeometry(win); for (int cc=0; cc < this->NumberOfHandles; cc++) { count+= this->Handle[cc]->RenderOpaqueGeometry(win); } return count; } //---------------------------------------------------------------------------- int vtkCurveRepresentation::RenderTranslucentPolygonalGeometry( vtkViewport* win) { int count = 0; count += this->LineActor->RenderTranslucentPolygonalGeometry(win); for (int cc=0; cc < this->NumberOfHandles; cc++) { count += this->Handle[cc]->RenderTranslucentPolygonalGeometry(win); } return count; } //---------------------------------------------------------------------------- int vtkCurveRepresentation::RenderOverlay(vtkViewport* win) { int count = 0; count += this->LineActor->RenderOverlay(win); for (int cc=0; cc < this->NumberOfHandles; cc++) { count += this->Handle[cc]->RenderOverlay(win); } return count; } //---------------------------------------------------------------------------- vtkTypeBool vtkCurveRepresentation::HasTranslucentPolygonalGeometry() { this->BuildRepresentation(); int count = 0; count |= this->LineActor->HasTranslucentPolygonalGeometry(); for (int cc=0; cc < this->NumberOfHandles; cc++) { count |= this->Handle[cc]->HasTranslucentPolygonalGeometry(); } return count; } //---------------------------------------------------------------------------- int vtkCurveRepresentation::ComputeInteractionState(int X, int Y, int vtkNotUsed(modify)) { this->InteractionState = vtkCurveRepresentation::Outside; if (!this->Renderer || !this->Renderer->IsInViewport(X, Y)) { return this->InteractionState; } // Try and pick a handle first. This allows the picking of the handle even // if it is "behind" the poly line. int handlePicked = 0; vtkAssemblyPath* path = this->GetAssemblyPath(X, Y, 0., this->HandlePicker); // always get pick position this->HandlePicker->GetPickPosition(this->LastPickPosition); if ( path != nullptr ) { this->ValidPick = 1; this->InteractionState = vtkCurveRepresentation::OnHandle; this->SetCurrentHandleIndex(this->GetHandleIndex(path->GetFirstNode()->GetViewProp())); handlePicked = 1; this->FirstSelected = (this->CurrentHandleIndex == 0); } else { this->SetCurrentHandleIndex(-1); } if (!handlePicked) { path = this->GetAssemblyPath(X, Y, 0., this->LinePicker); if ( path != nullptr ) { this->ValidPick = 1; this->LinePicker->GetPickPosition(this->LastPickPosition); this->HighlightLine(1); this->InteractionState = vtkCurveRepresentation::OnLine; } else { this->HighlightLine(0); } } else { this->HighlightLine(0); } return this->InteractionState; } //---------------------------------------------------------------------------- void vtkCurveRepresentation::StartWidgetInteraction(double e[2]) { // Store the start position this->StartEventPosition[0] = e[0]; this->StartEventPosition[1] = e[1]; this->StartEventPosition[2] = 0.0; // Store the start position this->LastEventPosition[0] = e[0]; this->LastEventPosition[1] = e[1]; this->LastEventPosition[2] = 0.0; this->ComputeInteractionState(static_cast<int>(e[0]),static_cast<int>(e[1]),0); } //---------------------------------------------------------------------------- void vtkCurveRepresentation::WidgetInteraction(double e[2]) { // Convert events to appropriate coordinate systems vtkCamera *camera = this->Renderer->GetActiveCamera(); if ( !camera ) { return; } double focalPoint[4], pickPoint[4], prevPickPoint[4]; double z, vpn[3]; // Compute the two points defining the motion vector vtkInteractorObserver::ComputeWorldToDisplay(this->Renderer, this->LastPickPosition[0], this->LastPickPosition[1], this->LastPickPosition[2], focalPoint); z = focalPoint[2]; vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer,this->LastEventPosition[0], this->LastEventPosition[1], z, prevPickPoint); vtkInteractorObserver::ComputeDisplayToWorld(this->Renderer, e[0], e[1], z, pickPoint); // Process the motion if (this->InteractionState == vtkCurveRepresentation::Moving) { if (this->CurrentHandleIndex != -1) { this->MovePoint(prevPickPoint, pickPoint); } else { this->Translate(prevPickPoint, pickPoint); } } else if (this->InteractionState == vtkCurveRepresentation::Scaling) { this->Scale(prevPickPoint, pickPoint, static_cast<int>(e[0]), static_cast<int>(e[1])); } else if (this->InteractionState == vtkCurveRepresentation::Spinning) { camera->GetViewPlaneNormal(vpn); this->Spin(prevPickPoint, pickPoint, vpn); } if (this->ProjectToPlane) { this->ProjectPointsToPlane(); } this->BuildRepresentation(); // Store the position this->LastEventPosition[0] = e[0]; this->LastEventPosition[1] = e[1]; this->LastEventPosition[2] = 0.0; } //---------------------------------------------------------------------------- void vtkCurveRepresentation::PushHandle(double* pos) { vtkPoints* newpoints = vtkPoints::New(VTK_DOUBLE); newpoints->SetNumberOfPoints(this->NumberOfHandles + 1); if (this->FirstSelected) { // pushing front newpoints->SetPoint(0, pos); for (int i = 0; i < this->NumberOfHandles; ++i) { newpoints->SetPoint(i + 1, this->HandleGeometry[i]->GetCenter()); } } else { // pushing back newpoints->SetPoint(this->NumberOfHandles, pos); for (int i = 0; i < this->NumberOfHandles; ++i) { newpoints->SetPoint(i, this->HandleGeometry[i]->GetCenter()); } } this->InitializeHandles(newpoints); newpoints->Delete(); } //---------------------------------------------------------------------------- void vtkCurveRepresentation::EndWidgetInteraction(double[2]) { switch (this->InteractionState) { case vtkCurveRepresentation::Pushing: this->PushHandle(this->LastPickPosition); break; case vtkCurveRepresentation::Inserting: this->SetCurrentHandleIndex(this->InsertHandleOnLine(this->LastPickPosition)); break; case vtkCurveRepresentation::Erasing: if (this->CurrentHandleIndex) { int index = this->CurrentHandleIndex; this->SetCurrentHandleIndex(-1); this->EraseHandle(index); } } this->HighlightLine(0); this->InteractionState = vtkCurveRepresentation::Outside; } //---------------------------------------------------------------------------- double* vtkCurveRepresentation::GetBounds() { this->BuildRepresentation(); vtkBoundingBox bbox; bbox.AddBounds(this->LineActor->GetBounds()); for (int cc=0; cc < this->NumberOfHandles; cc++) { bbox.AddBounds(this->HandleGeometry[cc]->GetOutput()->GetBounds()); } bbox.GetBounds(this->Bounds); return this->Bounds; } //---------------------------------------------------------------------------- void vtkCurveRepresentation::SetLineColor(double r, double g, double b) { this->GetLineProperty()->SetColor(r, g, b); } //---------------------------------------------------------------------------- void vtkCurveRepresentation::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if ( this->HandleProperty ) { os << indent << "Handle Property: " << this->HandleProperty << "\n"; } else { os << indent << "Handle Property: (none)\n"; } if ( this->SelectedHandleProperty ) { os << indent << "Selected Handle Property: " << this->SelectedHandleProperty << "\n"; } else { os << indent << "Selected Handle Property: (none)\n"; } if ( this->LineProperty ) { os << indent << "Line Property: " << this->LineProperty << "\n"; } else { os << indent << "Line Property: (none)\n"; } if ( this->SelectedLineProperty ) { os << indent << "Selected Line Property: " << this->SelectedLineProperty << "\n"; } else { os << indent << "Selected Line Property: (none)\n"; } os << indent << "Project To Plane: " << (this->ProjectToPlane ? "On" : "Off") << "\n"; os << indent << "Projection Normal: " << this->ProjectionNormal << "\n"; os << indent << "Projection Position: " << this->ProjectionPosition << "\n"; os << indent << "Number Of Handles: " << this->NumberOfHandles << "\n"; os << indent << "Closed: " << (this->Closed ? "On" : "Off") << "\n"; os << indent << "InteractionState: " << this->InteractionState << endl; } vtkStandardNewMacro(vtkCurveRepresentation::HandleSource); //---------------------------------------------------------------------------- vtkCurveRepresentation::HandleSource::HandleSource() : UseSphere(true) , Radius(0.5) { this->Center[0] = 0.0; this->Center[1] = 0.0; this->Center[2] = 0.0; this->Direction[0] = 1.0; this->Direction[1] = 0.0; this->Direction[2] = 0.0; this->SetNumberOfInputPorts(0); } //---------------------------------------------------------------------------- int vtkCurveRepresentation::HandleSource::RequestData( vtkInformation*, vtkInformationVector**, vtkInformationVector* outputVector) { auto output = vtkPolyData::GetData(outputVector); if (this->UseSphere) { vtkNew<vtkSphereSource> sphere; sphere->SetRadius(this->Radius); sphere->SetCenter(this->Center); sphere->SetThetaResolution(16); sphere->SetPhiResolution(8); sphere->Update(); output->ShallowCopy(sphere->GetOutput(0)); } else { vtkNew<vtkConeSource> cone; cone->SetRadius(this->Radius); cone->SetCenter(this->Center); cone->SetHeight(2.8 * this->Radius); cone->SetResolution(16); cone->SetDirection(this->Direction); cone->Update(); output->ShallowCopy(cone->GetOutput(0)); } return 1; }
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2008 - 2010 Greenplum, Inc. // // @filename: // CErrorContext.cpp // // @doc: // Implements context container for error handling //--------------------------------------------------------------------------- #include "gpos/utils.h" #include "gpos/error/CErrorContext.h" #include "gpos/error/CMessageRepository.h" #include "gpos/error/CMiniDumper.h" #include "gpos/error/CSerializable.h" #include "gpos/io/ioutils.h" #include "gpos/task/CAutoSuspendAbort.h" using namespace gpos; // logger buffer must be large enough to store error messages GPOS_CPL_ASSERT ( GPOS_ERROR_MESSAGE_BUFFER_SIZE <= GPOS_LOG_ENTRY_BUFFER_SIZE ) ; //--------------------------------------------------------------------------- // @function: // CErrorContext::CErrorContext // // @doc: // //--------------------------------------------------------------------------- CErrorContext::CErrorContext ( CMiniDumper *mini_dumper_handle ) : m_exception(CException::m_invalid_exception), m_severity(CException::ExsevError), m_pending(false), m_rethrown(false), m_serializing(false), m_static_buffer(m_error_msg, GPOS_ARRAY_SIZE(m_error_msg)), m_mini_dumper_handle(mini_dumper_handle) { m_serializable_objects_list.Init(GPOS_OFFSET(CSerializable, m_err_ctxt_link)); } //--------------------------------------------------------------------------- // @function: // CErrorContext::~CErrorContext // // @doc: // dtor // //--------------------------------------------------------------------------- CErrorContext::~CErrorContext() { GPOS_ASSERT(!m_pending && "unhandled error pending"); } //--------------------------------------------------------------------------- // @function: // CErrorContext::Reset // // @doc: // Clean up error context // //--------------------------------------------------------------------------- void CErrorContext::Reset() { GPOS_ASSERT(m_pending); m_pending = false; m_rethrown = false; m_serializing = false; m_exception = CException::m_invalid_exception; m_static_buffer.Reset(); } //--------------------------------------------------------------------------- // @function: // CErrorContext::Record // // @doc: // Grab error context and save it off and format error message // //--------------------------------------------------------------------------- void CErrorContext::Record ( CException &exc, VA_LIST vl ) { if (m_serializing) return; #ifdef GPOS_DEBUG if (m_pending) { // reset pending flag so we can throw from here m_pending = false; GPOS_ASSERT(!"Pending error unhandled when raising new error"); } #endif // GPOS_DEBUG m_pending = true; m_exception = exc; // store stack, skipping current frame m_stack_descriptor.BackTrace(1); ELocale locale = ITask::Self()->Locale(); CMessage *msg = CMessageRepository::GetMessageRepository()->LookupMessage(exc, locale); msg->Format(&m_static_buffer, vl); m_severity = msg->GetSeverity(); if (GPOS_FTRACE(EtracePrintExceptionOnRaise)) { std::wcerr << GPOS_WSZ_LIT("Exception: ") << m_static_buffer.GetBuffer() << std::endl; } } //--------------------------------------------------------------------------- // @function: // CErrorContext::AppendErrno // // @doc: // Print errno // //--------------------------------------------------------------------------- void CErrorContext::AppendErrnoMsg() { GPOS_ASSERT(m_pending); GPOS_ASSERT ( GPOS_MATCH_EX(m_exception, CException::ExmaSystem, CException::ExmiIOError) ); GPOS_ASSERT(0 < errno && "Errno has not been set"); // get errno description clib::Strerror_r(errno, m_system_error_msg, GPOS_ARRAY_SIZE(m_system_error_msg)); m_static_buffer.AppendFormat(GPOS_WSZ_LIT(" (%s)"), m_system_error_msg); } //--------------------------------------------------------------------------- // @function: // CErrorContext::CopyPropErrCtxt // // @doc: // Copy necessary info for error propagation // //--------------------------------------------------------------------------- void CErrorContext::CopyPropErrCtxt ( const IErrorContext *err_ctxt ) { GPOS_ASSERT(!m_pending); m_pending = true; // copy exception m_exception = err_ctxt->GetException(); // copy error message m_static_buffer.Reset(); m_static_buffer.Append(&(reinterpret_cast<const CErrorContext*>(err_ctxt)->m_static_buffer)); // copy severity m_severity = err_ctxt->GetSeverity(); } //--------------------------------------------------------------------------- // @function: // CErrorContext::Serialize // // @doc: // Serialize registered objects // //--------------------------------------------------------------------------- void CErrorContext::Serialize() { if (m_serializing) return; if (NULL == m_mini_dumper_handle || m_serializable_objects_list.IsEmpty()) { return; } m_serializing = true; // Abort might throw an error, so prevent aborting to // avoid recursion. CAutoSuspendAbort asa; // get mini-dumper's stream to serialize to COstream& oos = m_mini_dumper_handle->GetOStream(); // serialize objects to reserved space m_mini_dumper_handle->SerializeEntryHeader(); for (CSerializable *serializable_obj = m_serializable_objects_list.First(); NULL != serializable_obj; serializable_obj = m_serializable_objects_list.Next(serializable_obj)) { serializable_obj->Serialize(oos); } m_mini_dumper_handle->SerializeEntryFooter(); m_serializing = false; } // EOF
/* * to_ewald_sphere_helpers.cc * * Copyright (C) 2013 Diamond Light Source * * Author: James Parkhurst * * This code is distributed under the BSD license, a copy of which is * included in the root directory of this package. */ #include <boost/python.hpp> #include <boost/python/def.hpp> #include <scitbx/vec3.h> #include <scitbx/array_family/flex_types.h> #include <dxtbx/model/beam.h> #include <dxtbx/model/detector.h> #include <dxtbx/model/goniometer.h> #include <dxtbx/model/sequence.h> namespace dxtbx { namespace boost_python { using namespace boost::python; using dxtbx::model::MonoBeam; using dxtbx::model::Detector; using dxtbx::model::Goniometer; using dxtbx::model::Scan; using scitbx::vec2; using scitbx::vec3; using scitbx::af::flex_grid; typedef scitbx::af::flex<vec3<double> >::type flex_vec3_double; class ImageToEwaldSphere { public: ImageToEwaldSphere(const MonoBeam &beam, const Detector &detector, const Goniometer &gonio, const Scan &scan) : beam_(beam), detector_(detector), gonio_(gonio), scan_(scan) {} flex_vec3_double operator()(int frame, std::size_t panel) { // Check panel DXTBX_ASSERT(panel < detector_.size()); // Get size and create array std::size_t slow_size = detector_[0].get_image_size()[1]; std::size_t fast_size = detector_[0].get_image_size()[0]; flex_vec3_double x(flex_grid<>(slow_size, fast_size)); // Get rotation angle double phi = scan_.get_angle_from_array_index(frame - 0.5); // Get coordinate for each pixel for (std::size_t j = 0; j < slow_size; ++j) { for (std::size_t i = 0; i < fast_size; ++i) { vec3<double> s1 = detector_[panel].get_pixel_lab_coord(vec2<double>(i, j)); x(j, i) = s1.normalize().unit_rotate_around_origin(gonio_.get_rotation_axis(), phi) / beam_.get_wavelength(); } } // Return array return x; } MonoBeam beam_; Detector detector_; Goniometer gonio_; Scan scan_; }; void export_to_ewald_sphere_helpers() { class_<ImageToEwaldSphere>("ImageToEwaldSphere", no_init) .def(init<const MonoBeam &, const Detector &, const Goniometer &, const Scan &>( (arg("beam"), arg("detector"), arg("goniometer"), arg("scan")))) .def("__call__", &ImageToEwaldSphere::operator()); } }} // namespace dxtbx::boost_python
#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<map> #include<set> #include<vector> #include<utility> #include<queue> #include<stack> #define sd(x) scanf("%d",&x) #define sd2(x,y) scanf("%d%d",&x,&y) #define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z) #define fi first #define se second #define pb(x) push_back(x) #define mp(x,y) make_pair(x,y) #define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); #define tr(x) cout<<x<<endl; #define tr2(x,y) cout<<x<<" "<<y<<endl; #define tr3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl; using namespace std; int n, m, grid[1000][1000], dp[1000][1000], color[1000][1000], mx, flag, col = 1, num; string s; bool inrange(int x, int y){ if(x >= 0 and x < n and y >= 0 and y < m) return true; return false; } int dfs(int x, int y, int prev, int col){ if(flag) return 0; // tr3(x,y,col); if(grid[x][y] != (prev)%4+1) return 0; if(color[x][y] == col and grid[x][y] == 1 and dp[x][y] == -1){ flag = 1; return 0; } if(dp[x][y] > 0){ return dp[x][y]; } // tr3(x,y,col); // cin >> num; color[x][y] = col; int ret = 0; if(inrange(x+1,y) and !flag){ ret = max(ret, dfs(x+1,y,grid[x][y],col)); } if(inrange(x-1,y) and !flag){ ret = max(ret, dfs(x-1,y,grid[x][y],col)); } if(inrange(x,y+1) and !flag){ ret = max(ret, dfs(x,y+1,grid[x][y],col)); } if(inrange(x,y-1) and !flag){ ret = max(ret, dfs(x,y-1,grid[x][y],col)); } if(grid[x][y] == 4) ret++; dp[x][y] = ret; mx = max(mx, ret); return dp[x][y]; } int main(){ sd2(n,m); for(int i = 0; i < n; i++){ cin >> s; for(int j = 0; j < m; j++){ dp[i][j] = -1; if(s[j] == 'D') grid[i][j] = 1; else if(s[j] == 'I') grid[i][j] = 2; else if(s[j] == 'M') grid[i][j] = 3; else if(s[j] == 'A') grid[i][j] = 4; } } for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(grid[i][j] == 1 and dp[i][j] == -1){ dfs(i,j,0,col++); } } } if(flag == 1){ puts("Poor Inna!"); } else{ if(mx == 0){ puts("Poor Dima!"); } else{ printf("%d\n", mx); } } return 0; }
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2019 The Innova Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "coincontroldialog.h" #include "ui_coincontroldialog.h" #include "addresstablemodel.h" #include "bitcoinunits.h" #include "guiutil.h" #include "optionsmodel.h" #include "platformstyle.h" #include "txmempool.h" #include "walletmodel.h" #include "coincontrol.h" #include "init.h" #include "main.h" // For minRelayTxFee #include "wallet/wallet.h" #include "darksend.h" #include "instantx.h" #include <boost/assign/list_of.hpp> // for 'map_list_of()' #include <QApplication> #include <QCheckBox> #include <QCursor> #include <QDialogButtonBox> #include <QFlags> #include <QIcon> #include <QSettings> #include <QString> #include <QTreeWidget> #include <QTreeWidgetItem> QList<CAmount> CoinControlDialog::payAmounts; CCoinControl* CoinControlDialog::coinControl = new CCoinControl(); bool CoinControlDialog::fSubtractFeeFromAmount = false; CoinControlDialog::CoinControlDialog(const PlatformStyle *platformStyle, QWidget *parent) : QDialog(parent), ui(new Ui::CoinControlDialog), model(0), platformStyle(platformStyle) { ui->setupUi(this); /* Open CSS when configured */ this->setStyleSheet(GUIUtil::loadStyleSheet()); // context menu actions QAction *copyAddressAction = new QAction(tr("Copy address"), this); QAction *copyLabelAction = new QAction(tr("Copy label"), this); QAction *copyAmountAction = new QAction(tr("Copy amount"), this); copyTransactionHashAction = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this // context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyAmountAction); contextMenu->addAction(copyTransactionHashAction); contextMenu->addSeparator(); contextMenu->addAction(lockAction); contextMenu->addAction(unlockAction); // context menu signals connect(ui->treeWidget, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showMenu(QPoint))); connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(copyTransactionHashAction, SIGNAL(triggered()), this, SLOT(copyTransactionHash())); connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin())); connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin())); // clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy dust"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(clipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(clipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(clipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(clipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(clipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(clipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(clipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); // toggle tree/list mode connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool))); connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool))); // click on checkbox connect(ui->treeWidget, SIGNAL(itemChanged(QTreeWidgetItem*, int)), this, SLOT(viewItemChanged(QTreeWidgetItem*, int))); // click on header #if QT_VERSION < 0x050000 ui->treeWidget->header()->setClickable(true); #else ui->treeWidget->header()->setSectionsClickable(true); #endif connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(headerSectionClicked(int))); // ok button connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*))); // (un)select all connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(buttonSelectAllClicked())); // Toggle lock state connect(ui->pushButtonToggleLock, SIGNAL(clicked()), this, SLOT(buttonToggleLockClicked())); // change coin control first column label due Qt4 bug. // see https://github.com/bitcoin/bitcoin/issues/5716 ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString()); ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84); ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100); ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170); ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 190); ui->treeWidget->setColumnWidth(COLUMN_PRIVATESEND_ROUNDS, 88); ui->treeWidget->setColumnWidth(COLUMN_DATE, 80); ui->treeWidget->setColumnWidth(COLUMN_CONFIRMATIONS, 100); ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100); ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transacton hash in this column, but don't show it ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but don't show it ui->treeWidget->setColumnHidden(COLUMN_AMOUNT_INT64, true); // store amount int64 in this column, but don't show it ui->treeWidget->setColumnHidden(COLUMN_PRIORITY_INT64, true); // store priority int64 in this column, but don't show it ui->treeWidget->setColumnHidden(COLUMN_DATE_INT64, true); // store date int64 in this column, but don't show it // default view is sorted by amount desc sortView(COLUMN_AMOUNT_INT64, Qt::DescendingOrder); // restore list mode and sortorder as a convenience feature QSettings settings; if (settings.contains("nCoinControlMode") && !settings.value("nCoinControlMode").toBool()) ui->radioTreeMode->click(); if (settings.contains("nCoinControlSortColumn") && settings.contains("nCoinControlSortOrder")) sortView(settings.value("nCoinControlSortColumn").toInt(), ((Qt::SortOrder)settings.value("nCoinControlSortOrder").toInt())); } CoinControlDialog::~CoinControlDialog() { QSettings settings; settings.setValue("nCoinControlMode", ui->radioListMode->isChecked()); settings.setValue("nCoinControlSortColumn", sortColumn); settings.setValue("nCoinControlSortOrder", (int)sortOrder); delete ui; } void CoinControlDialog::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel() && model->getAddressTableModel()) { updateView(); updateLabelLocked(); CoinControlDialog::updateLabels(model, this); } } // helper function str_pad QString CoinControlDialog::strPad(QString s, int nPadLength, QString sPadding) { while (s.length() < nPadLength) s = sPadding + s; return s; } // ok button void CoinControlDialog::buttonBoxClicked(QAbstractButton* button) { if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) done(QDialog::Accepted); // closes the dialog } // (un)select all void CoinControlDialog::buttonSelectAllClicked() { Qt::CheckState state = Qt::Checked; for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked) { state = Qt::Unchecked; break; } } ui->treeWidget->setEnabled(false); for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state) ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state); ui->treeWidget->setEnabled(true); if (state == Qt::Unchecked) coinControl->UnSelectAll(); // just to be sure CoinControlDialog::updateLabels(model, this); } // Toggle lock state void CoinControlDialog::buttonToggleLockClicked() { QTreeWidgetItem *item; QString theme = GUIUtil::getThemeName(); // Works in list-mode only if(ui->radioListMode->isChecked()){ ui->treeWidget->setEnabled(false); for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++){ item = ui->treeWidget->topLevelItem(i); COutPoint outpt(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()); if (model->isLockedCoin(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())){ model->unlockCoin(outpt); item->setDisabled(false); item->setIcon(COLUMN_CHECKBOX, QIcon()); } else{ model->lockCoin(outpt); item->setDisabled(true); item->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/" + theme + "/lock_closed")); } updateLabelLocked(); } ui->treeWidget->setEnabled(true); CoinControlDialog::updateLabels(model, this); } else{ QMessageBox msgBox; msgBox.setObjectName("lockMessageBox"); msgBox.setStyleSheet(GUIUtil::loadStyleSheet()); msgBox.setText(tr("Please switch to \"List mode\" to use this function.")); msgBox.exec(); } } // context menu void CoinControlDialog::showMenu(const QPoint &point) { QTreeWidgetItem *item = ui->treeWidget->itemAt(point); if(item) { contextMenuItem = item; // disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode) { copyTransactionHashAction->setEnabled(true); if (model->isLockedCoin(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())) { lockAction->setEnabled(false); unlockAction->setEnabled(true); } else { lockAction->setEnabled(true); unlockAction->setEnabled(false); } } else // this means click on parent node in tree mode -> disable all { copyTransactionHashAction->setEnabled(false); lockAction->setEnabled(false); unlockAction->setEnabled(false); } // show context menu contextMenu->exec(QCursor::pos()); } } // context menu action: copy amount void CoinControlDialog::copyAmount() { GUIUtil::setClipboard(BitcoinUnits::removeSpaces(contextMenuItem->text(COLUMN_AMOUNT))); } // context menu action: copy label void CoinControlDialog::copyLabel() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent()) GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_LABEL)); else GUIUtil::setClipboard(contextMenuItem->text(COLUMN_LABEL)); } // context menu action: copy address void CoinControlDialog::copyAddress() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent()) GUIUtil::setClipboard(contextMenuItem->parent()->text(COLUMN_ADDRESS)); else GUIUtil::setClipboard(contextMenuItem->text(COLUMN_ADDRESS)); } // context menu action: copy transaction id void CoinControlDialog::copyTransactionHash() { GUIUtil::setClipboard(contextMenuItem->text(COLUMN_TXHASH)); } // context menu action: lock coin void CoinControlDialog::lockCoin() { QString theme = GUIUtil::getThemeName(); if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked) contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); model->lockCoin(outpt); contextMenuItem->setDisabled(true); contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/" + theme + "/lock_closed")); updateLabelLocked(); } // context menu action: unlock coin void CoinControlDialog::unlockCoin() { COutPoint outpt(uint256S(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); model->unlockCoin(outpt); contextMenuItem->setDisabled(false); contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon()); updateLabelLocked(); } // copy label "Quantity" to clipboard void CoinControlDialog::clipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // copy label "Amount" to clipboard void CoinControlDialog::clipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // copy label "Fee" to clipboard void CoinControlDialog::clipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace(ASYMP_UTF8, "")); } // copy label "After fee" to clipboard void CoinControlDialog::clipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace(ASYMP_UTF8, "")); } // copy label "Bytes" to clipboard void CoinControlDialog::clipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace(ASYMP_UTF8, "")); } // copy label "Priority" to clipboard void CoinControlDialog::clipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } // copy label "Dust" to clipboard void CoinControlDialog::clipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // copy label "Change" to clipboard void CoinControlDialog::clipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace(ASYMP_UTF8, "")); } // treeview: sort void CoinControlDialog::sortView(int column, Qt::SortOrder order) { sortColumn = column; sortOrder = order; ui->treeWidget->sortItems(column, order); ui->treeWidget->header()->setSortIndicator(getMappedColumn(sortColumn), sortOrder); } // treeview: clicked on header void CoinControlDialog::headerSectionClicked(int logicalIndex) { if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing { ui->treeWidget->header()->setSortIndicator(getMappedColumn(sortColumn), sortOrder); } else { logicalIndex = getMappedColumn(logicalIndex, false); if (sortColumn == logicalIndex) sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder); else { sortColumn = logicalIndex; sortOrder = ((sortColumn == COLUMN_LABEL || sortColumn == COLUMN_ADDRESS) ? Qt::AscendingOrder : Qt::DescendingOrder); // if label or address then default => asc, else default => desc } sortView(sortColumn, sortOrder); } } // toggle tree mode void CoinControlDialog::radioTreeMode(bool checked) { if (checked && model) updateView(); } // toggle list mode void CoinControlDialog::radioListMode(bool checked) { if (checked && model) updateView(); } // checkbox clicked by user void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column) { if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode) { COutPoint outpt(uint256S(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()); if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked) coinControl->UnSelect(outpt); else if (item->isDisabled()) // locked (this happens if "check all" through parent node) item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); else { coinControl->Select(outpt); CTxIn txin = CTxIn(outpt); int nRounds = pwalletMain->GetInputPrivateSendRounds(txin); if (coinControl->fUsePrivateSend && nRounds < nPrivateSendRounds) { QMessageBox::warning(this, windowTitle(), tr("Non-anonymized input selected. <b>PrivateSend will be disabled.</b><br><br>If you still want to use PrivateSend, please deselect all non-nonymized inputs first and then check PrivateSend checkbox again."), QMessageBox::Ok, QMessageBox::Ok); coinControl->fUsePrivateSend = false; } } // selection changed -> update labels if (ui->treeWidget->isEnabled()) // do not update on every click for (un)select all CoinControlDialog::updateLabels(model, this); } // todo: this is a temporary qt5 fix: when clicking a parent node in tree mode, the parent node // including all children are partially selected. But the parent node should be fully selected // as well as the children. Children should never be partially selected in the first place. // Please remove this ugly fix, once the bug is solved upstream. #if QT_VERSION >= 0x050000 else if (column == COLUMN_CHECKBOX && item->childCount() > 0) { if (item->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked && item->child(0)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) item->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } #endif } // return human readable label for priority number QString CoinControlDialog::getPriorityLabel(double dPriority, double mempoolEstimatePriority) { double dPriorityMedium = mempoolEstimatePriority; if (dPriorityMedium <= 0) dPriorityMedium = AllowFreeThreshold(); // not enough data, back to hard-coded if (dPriority / 1000000 > dPriorityMedium) return tr("highest"); else if (dPriority / 100000 > dPriorityMedium) return tr("higher"); else if (dPriority / 10000 > dPriorityMedium) return tr("high"); else if (dPriority / 1000 > dPriorityMedium) return tr("medium-high"); else if (dPriority > dPriorityMedium) return tr("medium"); else if (dPriority * 10 > dPriorityMedium) return tr("low-medium"); else if (dPriority * 100 > dPriorityMedium) return tr("low"); else if (dPriority * 1000 > dPriorityMedium) return tr("lower"); else return tr("lowest"); } // shows count of locked unspent outputs void CoinControlDialog::updateLabelLocked() { std::vector<COutPoint> vOutpts; model->listLockedCoins(vOutpts); if (vOutpts.size() > 0) { ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size())); ui->labelLocked->setVisible(true); } else ui->labelLocked->setVisible(false); } void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog) { if (!model) return; // nPayAmount CAmount nPayAmount = 0; bool fDust = false; CMutableTransaction txDummy; Q_FOREACH(const CAmount &amount, CoinControlDialog::payAmounts) { nPayAmount += amount; if (amount > 0) { CTxOut txout(amount, (CScript)std::vector<unsigned char>(24, 0)); txDummy.vout.push_back(txout); if (txout.IsDust(::minRelayTxFee)) fDust = true; } } QString sPriorityLabel = tr("none"); CAmount nAmount = 0; CAmount nPayFee = 0; CAmount nAfterFee = 0; CAmount nChange = 0; unsigned int nBytes = 0; unsigned int nBytesInputs = 0; double dPriority = 0; double dPriorityInputs = 0; unsigned int nQuantity = 0; int nQuantityUncompressed = 0; bool fAllowFree = false; std::vector<COutPoint> vCoinControl; std::vector<COutput> vOutputs; coinControl->ListSelected(vCoinControl); model->getOutputs(vCoinControl, vOutputs); BOOST_FOREACH(const COutput& out, vOutputs) { // unselect already spent, very unlikely scenario, this could happen // when selected are spent elsewhere, like rpc or another computer uint256 txhash = out.tx->GetHash(); COutPoint outpt(txhash, out.i); if (model->isSpent(outpt)) { coinControl->UnSelect(outpt); continue; } // Quantity nQuantity++; // Amount nAmount += out.tx->vout[out.i].nValue; // Priority dPriorityInputs += (double)out.tx->vout[out.i].nValue * (out.nDepth+1); // Bytes CTxDestination address; if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) { CPubKey pubkey; CKeyID *keyid = boost::get<CKeyID>(&address); if (keyid && model->getPubKey(*keyid, pubkey)) { nBytesInputs += (pubkey.IsCompressed() ? 148 : 180); if (!pubkey.IsCompressed()) nQuantityUncompressed++; } else nBytesInputs += 148; // in all error cases, simply assume 148 here } else nBytesInputs += 148; // Add inputs to calculate InstantSend Fee later if(coinControl->fUseInstantSend) txDummy.vin.push_back(CTxIn()); } // calculation if (nQuantity > 0) { // Bytes nBytes = nBytesInputs + ((CoinControlDialog::payAmounts.size() > 0 ? CoinControlDialog::payAmounts.size() + 1 : 2) * 34) + 10; // always assume +1 output for change here // Priority double mempoolEstimatePriority = mempool.estimateSmartPriority(nTxConfirmTarget); dPriority = dPriorityInputs / (nBytes - nBytesInputs + (nQuantityUncompressed * 29)); // 29 = 180 - 151 (uncompressed public keys are over the limit. max 151 bytes of the input are ignored for priority) sPriorityLabel = CoinControlDialog::getPriorityLabel(dPriority, mempoolEstimatePriority); // in the subtract fee from amount case, we can tell if zero change already and subtract the bytes, so that fee calculation afterwards is accurate if (CoinControlDialog::fSubtractFeeFromAmount) if (nAmount - nPayAmount == 0) nBytes -= 34; // Fee nPayFee = CWallet::GetMinimumFee(nBytes, nTxConfirmTarget, mempool); if (nPayFee > 0 && coinControl->nMinimumTotalFee > nPayFee) nPayFee = coinControl->nMinimumTotalFee; // InstantSend Fee if (coinControl->fUseInstantSend) nPayFee = std::max(nPayFee, CTxLockRequest(txDummy).GetMinFee()); // Allow free? (require at least hard-coded threshold and default to that if no estimate) double dPriorityNeeded = std::max(mempoolEstimatePriority, AllowFreeThreshold()); fAllowFree = (dPriority >= dPriorityNeeded); if (fSendFreeTransactions) if (fAllowFree && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) nPayFee = 0; if (nPayAmount > 0) { nChange = nAmount - nPayAmount; if (!CoinControlDialog::fSubtractFeeFromAmount) nChange -= nPayFee; // PrivateSend Fee = overpay if(coinControl->fUsePrivateSend && nChange > 0) { nPayFee += nChange; nChange = 0; } // Never create dust outputs; if we would, just add the dust to the fee. if (nChange > 0 && nChange < MIN_CHANGE) { CTxOut txout(nChange, (CScript)std::vector<unsigned char>(24, 0)); if (txout.IsDust(::minRelayTxFee)) { if (CoinControlDialog::fSubtractFeeFromAmount) // dust-change will be raised until no dust nChange = txout.GetDustThreshold(::minRelayTxFee); else { nPayFee += nChange; nChange = 0; } } } if (nChange == 0 && !CoinControlDialog::fSubtractFeeFromAmount) nBytes -= 34; } // after fee nAfterFee = nAmount - nPayFee; if (nAfterFee < 0) nAfterFee = 0; } // actually update labels int nDisplayUnit = BitcoinUnits::INNOVA; if (model && model->getOptionsModel()) nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); QLabel *l1 = dialog->findChild<QLabel *>("labelCoinControlQuantity"); QLabel *l2 = dialog->findChild<QLabel *>("labelCoinControlAmount"); QLabel *l3 = dialog->findChild<QLabel *>("labelCoinControlFee"); QLabel *l4 = dialog->findChild<QLabel *>("labelCoinControlAfterFee"); QLabel *l5 = dialog->findChild<QLabel *>("labelCoinControlBytes"); QLabel *l6 = dialog->findChild<QLabel *>("labelCoinControlPriority"); QLabel *l7 = dialog->findChild<QLabel *>("labelCoinControlLowOutput"); QLabel *l8 = dialog->findChild<QLabel *>("labelCoinControlChange"); // enable/disable "dust" and "change" dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlLowOutput") ->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("labelCoinControlChange") ->setEnabled(nPayAmount > 0); // stats l1->setText(QString::number(nQuantity)); // Quantity l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee l5->setText(((nBytes > 0) ? ASYMP_UTF8 : "") + QString::number(nBytes)); // Bytes l6->setText(sPriorityLabel); // Priority l7->setText(fDust ? tr("yes") : tr("no")); // Dust l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change if (nPayFee > 0 && (coinControl->nMinimumTotalFee < nPayFee)) { l3->setText(ASYMP_UTF8 + l3->text()); l4->setText(ASYMP_UTF8 + l4->text()); if (nChange > 0 && !CoinControlDialog::fSubtractFeeFromAmount) l8->setText(ASYMP_UTF8 + l8->text()); } // turn labels "red" l5->setStyleSheet((nBytes >= MAX_FREE_TRANSACTION_CREATE_SIZE) ? "color:red;" : "");// Bytes >= 1000 l6->setStyleSheet((dPriority > 0 && !fAllowFree) ? "color:red;" : ""); // Priority < "medium" l7->setStyleSheet((fDust) ? "color:red;" : ""); // Dust = "yes" // tool tips QString toolTip1 = tr("This label turns red if the transaction size is greater than 1000 bytes.") + "<br /><br />"; toolTip1 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatHtmlWithUnit(nDisplayUnit, CWallet::GetRequiredFee(1000))) + "<br /><br />"; toolTip1 += tr("Can vary +/- 1 byte per input."); QString toolTip2 = tr("Transactions with higher priority are more likely to get included into a block.") + "<br /><br />"; toolTip2 += tr("This label turns red if the priority is smaller than \"medium\".") + "<br /><br />"; toolTip2 += tr("This means a fee of at least %1 per kB is required.").arg(BitcoinUnits::formatHtmlWithUnit(nDisplayUnit, CWallet::GetRequiredFee(1000))); QString toolTip3 = tr("This label turns red if any recipient receives an amount smaller than %1.").arg(BitcoinUnits::formatHtmlWithUnit(nDisplayUnit, ::minRelayTxFee.GetFee(546))); // how many satoshis the estimated fee can vary per byte we guess wrong double dFeeVary; if (payTxFee.GetFeePerK() > 0) dFeeVary = (double)std::max(CWallet::GetRequiredFee(1000), payTxFee.GetFeePerK()) / 1000; else { dFeeVary = (double)std::max(CWallet::GetRequiredFee(1000), mempool.estimateSmartFee(nTxConfirmTarget).GetFeePerK()) / 1000; } QString toolTip4 = tr("Can vary +/- %1 duff(s) per input.").arg(dFeeVary); l3->setToolTip(toolTip4); l4->setToolTip(toolTip4); l5->setToolTip(toolTip1); l6->setToolTip(toolTip2); l7->setToolTip(toolTip3); l8->setToolTip(toolTip4); dialog->findChild<QLabel *>("labelCoinControlFeeText") ->setToolTip(l3->toolTip()); dialog->findChild<QLabel *>("labelCoinControlAfterFeeText") ->setToolTip(l4->toolTip()); dialog->findChild<QLabel *>("labelCoinControlBytesText") ->setToolTip(l5->toolTip()); dialog->findChild<QLabel *>("labelCoinControlPriorityText") ->setToolTip(l6->toolTip()); dialog->findChild<QLabel *>("labelCoinControlLowOutputText")->setToolTip(l7->toolTip()); dialog->findChild<QLabel *>("labelCoinControlChangeText") ->setToolTip(l8->toolTip()); // Insufficient funds QLabel *label = dialog->findChild<QLabel *>("labelCoinControlInsuffFunds"); if (label) label->setVisible(nChange < 0); } void CoinControlDialog::updateView() { if (!model || !model->getOptionsModel() || !model->getAddressTableModel()) return; bool treeMode = ui->radioTreeMode->isChecked(); QString theme = GUIUtil::getThemeName(); ui->treeWidget->clear(); ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox ui->treeWidget->setAlternatingRowColors(!treeMode); QFlags<Qt::ItemFlag> flgCheckbox = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable; QFlags<Qt::ItemFlag> flgTristate = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate; int nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); double mempoolEstimatePriority = mempool.estimateSmartPriority(nTxConfirmTarget); std::map<QString, std::vector<COutput> > mapCoins; model->listCoins(mapCoins); BOOST_FOREACH(const PAIRTYPE(QString, std::vector<COutput>)& coins, mapCoins) { QTreeWidgetItem *itemWalletAddress = new QTreeWidgetItem(); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); QString sWalletAddress = coins.first; QString sWalletLabel = model->getAddressTableModel()->labelForAddress(sWalletAddress); if (sWalletLabel.isEmpty()) sWalletLabel = tr("(no label)"); if (treeMode) { // wallet address ui->treeWidget->addTopLevelItem(itemWalletAddress); itemWalletAddress->setFlags(flgTristate); itemWalletAddress->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); // label itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel); itemWalletAddress->setToolTip(COLUMN_LABEL, sWalletLabel); // address itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress); itemWalletAddress->setToolTip(COLUMN_ADDRESS, sWalletAddress); } CAmount nSum = 0; double dPrioritySum = 0; int nChildren = 0; int nInputSum = 0; BOOST_FOREACH(const COutput& out, coins.second) { int nInputSize = 0; nSum += out.tx->vout[out.i].nValue; nChildren++; QTreeWidgetItem *itemOutput; if (treeMode) itemOutput = new QTreeWidgetItem(itemWalletAddress); else itemOutput = new QTreeWidgetItem(ui->treeWidget); itemOutput->setFlags(flgCheckbox); itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked); // address CTxDestination outputAddress; QString sAddress = ""; if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress)) { sAddress = QString::fromStdString(CBitcoinAddress(outputAddress).ToString()); // if listMode or change => show innova address. In tree mode, address is not shown again for direct wallet address outputs if (!treeMode || (!(sAddress == sWalletAddress))) itemOutput->setText(COLUMN_ADDRESS, sAddress); itemOutput->setToolTip(COLUMN_ADDRESS, sAddress); CPubKey pubkey; CKeyID *keyid = boost::get<CKeyID>(&outputAddress); if (keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed()) nInputSize = 29; // 29 = 180 - 151 (public key is 180 bytes, priority free area is 151 bytes) } // label if (!(sAddress == sWalletAddress)) // change { // tooltip from where the change comes from itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress)); itemOutput->setText(COLUMN_LABEL, tr("(change)")); } else if (!treeMode) { QString sLabel = model->getAddressTableModel()->labelForAddress(sAddress); if (sLabel.isEmpty()) sLabel = tr("(no label)"); itemOutput->setText(COLUMN_LABEL, sLabel); } // amount itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue)); itemOutput->setToolTip(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue)); itemOutput->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(out.tx->vout[out.i].nValue), 15, " ")); // padding so that sorting works correctly // date itemOutput->setText(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime())); itemOutput->setToolTip(COLUMN_DATE, GUIUtil::dateTimeStr(out.tx->GetTxTime())); itemOutput->setText(COLUMN_DATE_INT64, strPad(QString::number(out.tx->GetTxTime()), 20, " ")); // PrivateSend rounds CTxIn txin = CTxIn(out.tx->GetHash(), out.i); int nRounds = pwalletMain->GetInputPrivateSendRounds(txin); if (nRounds >= 0 || fDebug) itemOutput->setText(COLUMN_PRIVATESEND_ROUNDS, strPad(QString::number(nRounds), 11, " ")); else itemOutput->setText(COLUMN_PRIVATESEND_ROUNDS, strPad(QString(tr("n/a")), 11, " ")); // confirmations itemOutput->setText(COLUMN_CONFIRMATIONS, strPad(QString::number(out.nDepth), 8, " ")); // priority double dPriority = ((double)out.tx->vout[out.i].nValue / (nInputSize + 78)) * (out.nDepth+1); // 78 = 2 * 34 + 10 itemOutput->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPriority, mempoolEstimatePriority)); itemOutput->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64_t)dPriority), 20, " ")); dPrioritySum += (double)out.tx->vout[out.i].nValue * (out.nDepth+1); nInputSum += nInputSize; // transaction hash uint256 txhash = out.tx->GetHash(); itemOutput->setText(COLUMN_TXHASH, QString::fromStdString(txhash.GetHex())); // vout index itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i)); // disable locked coins if (model->isLockedCoin(txhash, out.i)) { COutPoint outpt(txhash, out.i); coinControl->UnSelect(outpt); // just to be sure itemOutput->setDisabled(true); itemOutput->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/" + theme + "/lock_closed")); } // set checkbox if (coinControl->IsSelected(txhash, out.i)) itemOutput->setCheckState(COLUMN_CHECKBOX, Qt::Checked); } // amount if (treeMode) { dPrioritySum = dPrioritySum / (nInputSum + 78); itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")"); itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum)); itemWalletAddress->setToolTip(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum)); itemWalletAddress->setText(COLUMN_AMOUNT_INT64, strPad(QString::number(nSum), 15, " ")); itemWalletAddress->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPrioritySum, mempoolEstimatePriority)); itemWalletAddress->setText(COLUMN_PRIORITY_INT64, strPad(QString::number((int64_t)dPrioritySum), 20, " ")); } } // expand all partially selected if (treeMode) { for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) ui->treeWidget->topLevelItem(i)->setExpanded(true); } // sort view sortView(sortColumn, sortOrder); ui->treeWidget->setEnabled(true); }
/* * This file is part of liblcf. Copyright (c) 2021 liblcf authors. * https://github.com/EasyRPG/liblcf - https://easyrpg.org * * liblcf is Free/Libre Open Source Software, released under the MIT License. * For the full copyright and license information, please view the COPYING * file that was distributed with this source code. */ #include "lcf/ldb/reader.h" #include "lcf/ldb/chunks.h" #include "reader_struct.h" namespace lcf { template <> struct RawStruct<rpg::Equipment> { static void ReadLcf(rpg::Equipment& ref, LcfReader& stream, uint32_t length); static void WriteLcf(const rpg::Equipment& ref, LcfWriter& stream); static int LcfSize(const rpg::Equipment& ref, LcfWriter& stream); static void WriteXml(const rpg::Equipment& ref, XmlWriter& stream); static void BeginXml(rpg::Equipment& ref, XmlReader& stream); }; /** * Reads Equipment. */ void RawStruct<rpg::Equipment>::ReadLcf(rpg::Equipment& ref, LcfReader& stream, uint32_t length) { if (length != 10) { fprintf(stderr, "Equipment has incorrect size %" PRIu32 " (expected 10)\n", length); LcfReader::Chunk chunk_info; chunk_info.ID = 0x33; chunk_info.length = length; stream.Skip(chunk_info, "Equipment"); return; } stream.Read(ref.weapon_id); stream.Read(ref.shield_id); stream.Read(ref.armor_id); stream.Read(ref.helmet_id); stream.Read(ref.accessory_id); } void RawStruct<rpg::Equipment>::WriteLcf(const rpg::Equipment& ref, LcfWriter& stream) { stream.Write(ref.weapon_id); stream.Write(ref.shield_id); stream.Write(ref.armor_id); stream.Write(ref.helmet_id); stream.Write(ref.accessory_id); } int RawStruct<rpg::Equipment>::LcfSize(const rpg::Equipment& /* ref */, LcfWriter& /* stream */) { return 2 * 5; } void RawStruct<rpg::Equipment>::WriteXml(const rpg::Equipment& ref, XmlWriter& stream) { stream.BeginElement("Equipment"); stream.WriteNode<int16_t>("weapon_id", ref.weapon_id); stream.WriteNode<int16_t>("shield_id", ref.shield_id); stream.WriteNode<int16_t>("armor_id", ref.armor_id); stream.WriteNode<int16_t>("helmet_id", ref.helmet_id); stream.WriteNode<int16_t>("accessory_id", ref.accessory_id); stream.EndElement("Equipment"); } class EquipmentXmlHandler : public XmlHandler { private: rpg::Equipment& ref; int16_t* field; public: EquipmentXmlHandler(rpg::Equipment& ref) : ref(ref), field(NULL) {} void StartElement(XmlReader& stream, const char* name, const char** /* atts */) { if (strcmp(name, "weapon_id") == 0) field = &ref.weapon_id; else if (strcmp(name, "shield_id") == 0) field = &ref.shield_id; else if (strcmp(name, "armor_id") == 0) field = &ref.armor_id; else if (strcmp(name, "helmet_id") == 0) field = &ref.helmet_id; else if (strcmp(name, "accessory_id") == 0) field = &ref.accessory_id; else { stream.Error("Unrecognized field '%s'", name); field = NULL; } } void EndElement(XmlReader& /* stream */, const char* /* name */) { field = NULL; } void CharacterData(XmlReader& /* stream*/, const std::string& data) { if (field != NULL) XmlReader::Read(*field, data); } }; void RawStruct<rpg::Equipment>::BeginXml(rpg::Equipment& ref, XmlReader& stream) { stream.SetHandler(new WrapperXmlHandler("Equipment", new EquipmentXmlHandler(ref))); } } //namespace lcf
//---------------------------------------------------------------------------// // Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation> // Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation> // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //---------------------------------------------------------------------------// #ifndef CRYPTO3_ZK_SNARK_SET_COMMITMENT_HPP #define CRYPTO3_ZK_SNARK_SET_COMMITMENT_HPP #include <nil/crypto3/zk/snark/merkle_tree.hpp> #include <nil/crypto3/zk/snark/components/hashes/hash_io.hpp> namespace nil { namespace crypto3 { namespace zk { namespace snark { typedef std::vector<bool> set_commitment; struct set_membership_proof { std::size_t address; merkle_authentication_path merkle_path; bool operator==(const set_membership_proof &other) const { return (this->address == other.address && this->merkle_path == other.merkle_path); } std::size_t size_in_bits() const { if (merkle_path.empty()) { return (8 * sizeof(address)); } else { return (8 * sizeof(address) + merkle_path[0].size() * merkle_path.size()); } } }; template<typename Hash> class set_commitment_accumulator { private: std::shared_ptr<merkle_tree<Hash>> tree; std::map<std::vector<bool>, std::size_t> hash_to_pos; public: std::size_t depth; std::size_t digest_size; std::size_t value_size; set_commitment_accumulator(const std::size_t max_entries, const std::size_t value_size = 0) : value_size(value_size) { depth = static_cast<std::size_t>(std::ceil(std::log2(max_entries))); digest_size = Hash::get_digest_len(); tree.reset(new merkle_tree<Hash>(depth, digest_size)); } void add(const std::vector<bool> &value) { assert(value_size == 0 || value.size() == value_size); const std::vector<bool> hash = Hash::get_hash(value); if (hash_to_pos.find(hash) == hash_to_pos.end()) { const std::size_t pos = hash_to_pos.size(); tree->set_value(pos, hash); hash_to_pos[hash] = pos; } } bool is_in_set(const std::vector<bool> &value) const { assert(value_size == 0 || value.size() == value_size); const std::vector<bool> hash = Hash::get_hash(value); return (hash_to_pos.find(hash) != hash_to_pos.end()); } set_commitment get_commitment() const { return tree->get_root(); } set_membership_proof get_membership_proof(const std::vector<bool> &value) const { const std::vector<bool> hash = Hash::get_hash(value); auto it = hash_to_pos.find(hash); assert(it != hash_to_pos.end()); set_membership_proof proof; proof.address = it->second; proof.merkle_path = tree->get_path(it->second); return proof; } }; } // namespace snark } // namespace zk } // namespace crypto3 } // namespace nil #endif // CRYPTO3_ZK_SNARK_SET_COMMITMENT_HPP
// // Created by Hamza El-Kebir on 12/5/21. // #include "Player.hpp"
/*========================================================================= Program: Visualization Toolkit Module: vtkSortDataArray.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /* * Copyright 2003 Sandia Corporation. * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive * license for use of this work by or on behalf of the * U.S. Government. Redistribution and use in source and binary forms, with * or without modification, are permitted provided that this Notice and any * statement of authorship are reproduced on all copies. */ #include "vtkSortDataArray.h" #include "vtkAbstractArray.h" #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkIdList.h" #include "vtkStdString.h" #include "vtkStringArray.h" #include "vtkVariant.h" #include "vtkVariantArray.h" #include "vtkSMPTools.h" #include <functional> //std::greater //------------------------------------------------------------------------- vtkStandardNewMacro(vtkSortDataArray); //------------------------------------------------------------------------- vtkSortDataArray::vtkSortDataArray() { } //--------------------------------------------------------------------------- vtkSortDataArray::~vtkSortDataArray() { } //--------------------------------------------------------------------------- void vtkSortDataArray::Sort(vtkIdList *keys, int dir) { if ( keys == NULL ) { return; } vtkIdType *data = keys->GetPointer(0); vtkIdType numKeys = keys->GetNumberOfIds(); if ( dir == 0 ) { vtkSMPTools::Sort(data, data + numKeys); } else { vtkSMPTools::Sort(data, data + numKeys, std::greater<vtkIdType>()); } } //--------------------------------------------------------------------------- void vtkSortDataArray::Sort(vtkAbstractArray *keys, int dir) { if ( keys == NULL ) { return; } if (keys->GetNumberOfComponents() != 1) { vtkGenericWarningMacro("Can only sort keys that are 1-tuples."); return; } void *data = keys->GetVoidPointer(0); vtkIdType numKeys = keys->GetNumberOfTuples(); if ( dir == 0 ) { switch (keys->GetDataType()) { vtkExtendedTemplateMacro(vtkSMPTools::Sort(static_cast<VTK_TT *>(data), static_cast<VTK_TT *>(data) + numKeys)); } } else { switch (keys->GetDataType()) { vtkExtendedTemplateMacro(vtkSMPTools::Sort(static_cast<VTK_TT *>(data), static_cast<VTK_TT *>(data) + numKeys, std::greater<VTK_TT>())); } } } //--------------------------------------------------------------------------- // Hide some stuff; mostly things plugged into templated functions namespace { //--------------------------------------------------------------------------- // We sort the indices based on a key value in another array. Produces sort // in ascending direction. Note that sort comparison operator is for single // component arrays. template <typename T> struct KeyComp { const T *Array; KeyComp(T *array) : Array(array) {}; bool operator() (vtkIdType idx0, vtkIdType idx1) const { return ( Array[idx0] < Array[idx1] ); } }; //----------------------------------------------------------------------------- // Special comparison functor using tuple component as a key. Note that this // comparison function is for general arrays of n components. template <typename T> struct TupleComp { const T *Array; int NumComp; int K; TupleComp(T *array, int n, int k) : Array(array), NumComp(n), K(k) {}; bool operator() (vtkIdType idx0, vtkIdType idx1) const {return Array[idx0*NumComp+K] < Array[idx1*NumComp+K];} }; //--------------------------------------------------------------------------- // Given a set of indices (after sorting), copy the data from a pre-sorted // array to a final, post-sorted array, Implementation note: the direction of // sort (dir) is treated here rather than in the std::sort() function to // reduce object file .obj size; e.g., running std::sort with a different // comporator function causes inline expansion to produce very large object // files. template <typename T> void Shuffle1Tuples(vtkIdType *idx, vtkIdType sze, vtkAbstractArray *arrayIn, T *preSort, int dir) { T *postSort = new T [sze]; if ( dir == 0 ) //ascending { for (vtkIdType i=0; i<sze; ++i) { postSort[i] = preSort[idx[i]]; } } else { vtkIdType end=sze-1; for (vtkIdType i=0; i<sze; ++i) { postSort[i] = preSort[idx[end-i]]; } } arrayIn->SetVoidArray(postSort, sze, 0, vtkAbstractArray::VTK_DATA_ARRAY_DELETE); } //--------------------------------------------------------------------------- // Given a set of indices (after sorting), copy the data from a pre-sorted // data array to a final, post-sorted array. Note that the data array is // assumed to have arbitrary sized components. template <typename T> void ShuffleTuples(vtkIdType *idx, vtkIdType sze, int numComp, vtkAbstractArray *arrayIn, T *preSort, int dir) { T *postSort = new T [sze*numComp]; int k; vtkIdType i; if ( dir == 0 ) //ascending { for (i=0; i<sze; ++i) { for (k=0; k<numComp; ++k) { postSort[i*numComp+k] = preSort[idx[i]*numComp+k]; } } } else { vtkIdType end=sze-1; for (i=0; i<sze; ++i) { for (k=0; k<numComp; ++k) { postSort[i*numComp+k] = preSort[idx[end-i]*numComp+k]; } } } arrayIn->SetVoidArray(postSort, sze*numComp, 0, vtkAbstractArray::VTK_DATA_ARRAY_DELETE); } }//anonymous namespace //--------------------------------------------------------------------------- // Allocate and initialize sort indices vtkIdType* vtkSortDataArray::InitializeSortIndices(vtkIdType num) { vtkIdType *idx = new vtkIdType[num]; for (vtkIdType i=0; i < num; ++i) { idx[i] = i; } return idx; } //--------------------------------------------------------------------------- // Efficent function for generating sort ordering specialized to single // component arrays. void vtkSortDataArray:: GenerateSort1Indices(int dataType, void *dataIn, vtkIdType numKeys, vtkIdType *idx) { if ( dataType == VTK_VARIANT) { vtkSMPTools::Sort(idx, idx+numKeys, KeyComp<vtkVariant>(static_cast<vtkVariant*>(dataIn))); } else { switch ( dataType ) { vtkExtendedTemplateMacro(vtkSMPTools::Sort(idx, idx+numKeys, KeyComp<VTK_TT>(static_cast<VTK_TT *>(dataIn)))); } } } //--------------------------------------------------------------------------- // Function for generating sort ordering for general arrays. void vtkSortDataArray:: GenerateSortIndices(int dataType, void *dataIn, vtkIdType numKeys, int numComp, int k, vtkIdType *idx) { // Specialized and faster for single component arrays if ( numComp == 1) { return vtkSortDataArray::GenerateSort1Indices(dataType, dataIn, numKeys, idx); } if ( dataType == VTK_VARIANT) { vtkSMPTools::Sort(idx, idx+numKeys, TupleComp<vtkVariant>(static_cast<vtkVariant*>(dataIn),numComp,k)); } else { switch (dataType) { vtkExtendedTemplateMacro(vtkSMPTools::Sort(idx, idx+numKeys, TupleComp<VTK_TT>(static_cast<VTK_TT *>(dataIn),numComp,k))); } } } //------------------------------------------------------------------------- // Set up the actual templated shuffling operation. This method is for // VTK arrays that are precsisely one component. void vtkSortDataArray:: Shuffle1Array(vtkIdType *idx, int dataType, vtkIdType numKeys, vtkAbstractArray *arr, void *dataIn, int dir) { if ( dataType == VTK_VARIANT) { Shuffle1Tuples(idx, numKeys, arr, static_cast<vtkVariant*>(dataIn), dir); } else { switch (arr->GetDataType()) { vtkExtendedTemplateMacro(Shuffle1Tuples(idx, numKeys, arr, static_cast<VTK_TT *>(dataIn), dir)); } } } //------------------------------------------------------------------------- // Set up the actual templated shuffling operation void vtkSortDataArray:: ShuffleArray(vtkIdType *idx, int dataType, vtkIdType numKeys, int numComp, vtkAbstractArray *arr, void *dataIn, int dir) { // Specialized for single component arrays if ( numComp == 1) { return vtkSortDataArray::Shuffle1Array(idx, dataType, numKeys, arr, dataIn, dir); } if ( dataType == VTK_VARIANT) { ShuffleTuples(idx, numKeys, numComp, arr, static_cast<vtkVariant*>(dataIn), dir); } else { switch (arr->GetDataType()) { vtkExtendedTemplateMacro(ShuffleTuples(idx, numKeys, numComp, arr, static_cast<VTK_TT *>(dataIn), dir)); } } } //--------------------------------------------------------------------------- // Given a set of indices (after sorting), copy the ids from a pre-sorted // id array to a final, post-sorted array. void vtkSortDataArray:: ShuffleIdList(vtkIdType *idx, vtkIdType sze, vtkIdList *arrayIn, vtkIdType *preSort, int dir) { vtkIdType *postSort = new vtkIdType [sze]; if ( dir == 0 ) //ascending { for (vtkIdType i=0; i<sze; ++i) { postSort[i] = preSort[idx[i]]; } } else { vtkIdType end=sze-1; for (vtkIdType i=0; i<sze; ++i) { postSort[i] = preSort[idx[end-i]]; } } arrayIn->SetArray(postSort, sze); } //--------------------------------------------------------------------------- // Sort a position index based on the values in the abstract array. Once // sorted, then shuffle the keys and values around into new arrays. void vtkSortDataArray:: Sort(vtkAbstractArray *keys, vtkAbstractArray *values, int dir) { // Check input if ( keys == NULL || values == NULL ) { return; } if (keys->GetNumberOfComponents() != 1) { vtkGenericWarningMacro("Can only sort keys that are 1-tuples."); return; } vtkIdType numKeys = keys->GetNumberOfTuples(); vtkIdType numValues = values->GetNumberOfTuples(); if ( numKeys != numValues ) { vtkGenericWarningMacro("Could not sort arrays. Key and value arrays have different sizes."); return; } // Sort the index array vtkIdType *idx = vtkSortDataArray::InitializeSortIndices(numKeys); // Generate the sorting index array void *dataIn = keys->GetVoidPointer(0); int numComp = 1; int dataType = keys->GetDataType(); vtkSortDataArray::GenerateSortIndices(dataType, dataIn, numKeys, numComp, 0, idx); // Now shuffle data around based on sorted indices vtkSortDataArray::ShuffleArray(idx, dataType, numKeys, numComp, keys, dataIn, dir); dataIn = values->GetVoidPointer(0); numComp = values->GetNumberOfComponents(); dataType = values->GetDataType(); vtkSortDataArray::ShuffleArray(idx, dataType, numKeys, numComp, values, dataIn, dir); // Clean up delete [] idx; } //--------------------------------------------------------------------------- void vtkSortDataArray:: Sort(vtkAbstractArray *keys, vtkIdList *values, int dir) { // Check input if ( keys == NULL || values == NULL ) { return; } if (keys->GetNumberOfComponents() != 1) { vtkGenericWarningMacro("Can only sort keys that are 1-tuples."); return; } vtkIdType numKeys = keys->GetNumberOfTuples(); vtkIdType numIds = values->GetNumberOfIds(); if ( numKeys != numIds ) { vtkGenericWarningMacro("Could not sort arrays. Key and id arrays have different sizes."); return; } // Sort the index array vtkIdType *idx = vtkSortDataArray::InitializeSortIndices(numKeys); // Generate the sorting index array void *dataIn = keys->GetVoidPointer(0); int numComp = 1; int dataType = keys->GetDataType(); vtkSortDataArray::GenerateSortIndices(dataType, dataIn, numKeys, numComp, 0, idx); // Shuffle the keys vtkSortDataArray::ShuffleArray(idx, dataType, numKeys, numComp, keys, dataIn, dir); // Now shuffle the ids to match the sort vtkIdType *ids = values->GetPointer(0); ShuffleIdList(idx, numKeys, values, ids, dir); // Clean up delete [] idx; } //--------------------------------------------------------------------------- void vtkSortDataArray:: SortArrayByComponent( vtkAbstractArray* arr, int k, int dir) { // Check input if ( arr == NULL ) { return; } vtkIdType numKeys = arr->GetNumberOfTuples(); int nc = arr->GetNumberOfComponents(); if ( k < 0 || k >= nc ) { vtkGenericWarningMacro( "Cannot sort by column " << k << " since the array only has columns 0 through " << (nc-1) ); return; } // Perform the sort vtkIdType *idx = vtkSortDataArray::InitializeSortIndices(numKeys); void *dataIn = arr->GetVoidPointer(0); int dataType = arr->GetDataType(); vtkSortDataArray::GenerateSortIndices(dataType, dataIn, numKeys, nc, k, idx); vtkSortDataArray::ShuffleArray(idx, dataType, numKeys, nc, arr, dataIn, dir); // Clean up delete [] idx; } //------------------------------------------------------------------------- void vtkSortDataArray::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } // vtkSortDataArray methods -------------------------------------------------------
#include "pch.h" #include <dplyr/main.h> #include <dplyr/visitor_set/VisitorSetIndexSet.h> #include <dplyr/visitors/vector/MultipleVectorVisitors.h> #include <dplyr/hybrid/scalar_result/n_distinct.h> #include <dplyr/visitors/subset/DataFrameSelect.h> #include <dplyr/visitors/subset/DataFrameSubsetVisitors.h> using namespace Rcpp; using namespace dplyr; SEXP select_not_grouped(const DataFrame& df, const SymbolVector& keep, const SymbolVector& new_names); // [[Rcpp::export]] SEXP distinct_impl(DataFrame df, const IntegerVector& vars, const IntegerVector& keep) { if (df.size() == 0) { DataFrame res = DataFrame::create(); copy_most_attributes(res, df); res.attr("row.names") = IntegerVector::create(NA_INTEGER, df.nrows() == 0 ? 0 : -1); return res ; } // No vars means ungrouped data with keep_all = TRUE. if (vars.size() == 0) return df; check_valid_colnames(df, true); DataFrameVisitors visitors(df, vars); int n = df.nrows(); // allocate a big enough vector IntegerVector indices(n); VisitorSetIndexSet<DataFrameVisitors> set(visitors); int k = 0; for (int i = 0; i < n; i++) { if (set.insert(i).second) { indices[k++] = i + 1; } } // but then pretend it is smaller in case it is used in R subscripting SETLENGTH(indices, k); SEXP res = DataFrameSubsetVisitors(DataFrameSelect(df, keep)).subset_all(indices); // restore original length for GC bookkeeping SETLENGTH(indices, n); return res; } // [[Rcpp::export]] int n_distinct_multi(List variables, bool na_rm = false) { if (variables.length() == 0) { stop("Need at least one column for `n_distinct()`"); } int n = variables.size(); // get the number of rows of an hypothetical data frame // that would contain variables, taking into account potential // recycling of length 1 variables int length = get_size(variables[0]); for (int i = 1; i < n; i++) { int l = get_size(variables[i]); if (length == l) continue; if (length == 1 && l > 1) { length = l; } } MultipleVectorVisitors visitors(variables, length, 1, 0); typedef VisitorHash<MultipleVectorVisitors> Hash; typedef VisitorEqualPredicate<MultipleVectorVisitors> Pred; typedef dplyr_hash_set<int, Hash, Pred > Set; Set set(n, Hash(visitors), Pred(visitors)); for (int i = 0; i < length; i++) { if (!na_rm || !visitors.is_na(i)) set.insert(i); } return set.size(); }
#ifndef MINIMIZATION_HELPER_HPP #define MINIMIZATION_HELPER_HPP #include "bucket_minimization.hpp" #include <string> #include <vector> namespace abo::minimization { enum class OperatorConstructionMode { //! the operator is applied to a single BDD at a time SINGLE_BDD, //! the operator is applied to the whole BDD forest at the same time MULTI_BDD, //! the operator is applied to a random (single) BDD at a random level RANDOM }; //! A simplified version of the struct MetricDimension with an enum for the metric instead of a //! lambda struct SimpleMetricDimension { //! The number of buckets to create for this metric in the given dimension std::size_t grid_size; //! The error metric used for this dimension ErrorMetric metric; //! The maximum value of the error metric that is represented by a bucket double bound; }; //! Stores a configuration for easily running simple tests with the bucket based minimization //! algorithm struct MinimizationInputInfo { //! can be either an adder (adder8, adder16 or adder32) or an iscas 85 file std::string input; //! whether to sift the input while reading (or generating) it bool sift = true; //! the metrics to target during the minimzation std::vector<SimpleMetricDimension> metrics; //! the operators used for the approximation std::vector<Operator> operators = {Operator::NEGATIVE_COFACTOR, Operator::POSITIVE_COFACTOR}; //! the mode used for constructing the operator application functions OperatorConstructionMode operator_mode = OperatorConstructionMode::SINGLE_BDD; //! only used when operator_mode == RANDOM: the number of operator functions to construct std::size_t num_operator_functions; //! whether or not the algorithm should populate all buckets with a higher node count (if the //! error metrics match) or only the exactly matching one the algorithm generally performs //! slightly better when only the exact bucket is populated bool populate_all_buckets = false; }; //! Stores the result of a BDD minimization by the bucket based algorithm struct MinimizationResult { //! in here to keep all the BDDs valid Cudd mgr; //! the node count of the non-approximated original function std::size_t original_size; //! the time the algorithm took, in milliseconds double minimization_time; //! the result with the smallest BDD found by the algorithm (also present in all_buckets) Bucket smallest_function; //! all buckets created by the algorithm std::vector<Bucket> all_buckets; }; MinimizationResult bucket_minimize_helper(const MinimizationInputInfo& info); std::string format_time(double milliseconds); } // namespace abo::minimization #endif // MINIMIZATION_HELPER_HPP
#include "/home/epasholl/opencv/opencv-master/modules/imgproc/src/precomp.hpp" #include "/home/epasholl/opencv/opencv-master/modules/imgproc/src/morph.simd.hpp"
#include <iostream> #include "assignment/code.hpp" using namespace std; using namespace assignment; int squared_diff(int left, int right) { int total; total = left - right; total = total * total; return total; } int main() { cout << "Write your code here...\n"; return 0; }
//////////////////////////////////////////////////////////////////////////////// // Copyright 2017 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. //////////////////////////////////////////////////////////////////////////////// #include "CPUTMesh.h" //----------------------------------------------------------------------------- // Note: The indices of these strings must match the corresponding value in enum CPUT_VERTEX_ELEMENT_SEMANTIC const char *CPUT_VERTEX_ELEMENT_SEMANTIC_AS_STRING[] = { "UNDEFINED", "UNDEFINED", // Note 1 is missing (back compatibility) "POSITON", "NORMAL", "TEXTURECOORD", "COLOR", "TANGENT", "BINORMAL" }; //----------------------------------------------------------------------------- void CPUTVertexElementDesc::Read(std::ifstream &meshFile) { meshFile.read((char*)this, sizeof(*this)); } //----------------------------------------------------------------------------- void CPUTRawMeshData::Allocate(__int32 numElements) { mVertexCount = numElements; mStride += mPaddingSize; // TODO: move this to stride computation mTotalVerticesSizeInBytes = mVertexCount * mStride; mpVertices = (void*)new char[(UINT)mTotalVerticesSizeInBytes]; ::memset( mpVertices, 0, (size_t)mTotalVerticesSizeInBytes ); } //----------------------------------------------------------------------------- bool CPUTRawMeshData::Read(std::ifstream &modelFile) { unsigned __int32 magicCookie; modelFile.read((char*)&magicCookie,sizeof(magicCookie)); if( !modelFile.good() ) return false; // TODO: Yuck! Why do we need to get here to figure out we're done? ASSERT( magicCookie == 1234, _L("Invalid model file.") ); modelFile.read((char*)&mStride, sizeof(mStride)); modelFile.read((char*)&mPaddingSize, sizeof(mPaddingSize)); // DWM TODO: What is this? modelFile.read((char*)&mTotalVerticesSizeInBytes, sizeof(mTotalVerticesSizeInBytes)); modelFile.read((char*)&mVertexCount, sizeof(mVertexCount)); modelFile.read((char*)&mTopology, sizeof(mTopology)); modelFile.read((char*)&mBboxCenter, sizeof(mBboxCenter)); modelFile.read((char*)&mBboxHalf, sizeof(mBboxHalf)); // read format descriptors modelFile.read((char*)&mFormatDescriptorCount, sizeof(mFormatDescriptorCount)); ASSERT( modelFile.good(), _L("Model file bad" ) ); mpElements = new CPUTVertexElementDesc[mFormatDescriptorCount]; for( UINT ii=0; ii<mFormatDescriptorCount; ++ii ) { mpElements[ii].Read(modelFile); } modelFile.read((char*)&mIndexCount, sizeof(mIndexCount)); modelFile.read((char*)&mIndexType, sizeof(mIndexType)); ASSERT( modelFile.good(), _L("Bad model file(1)." ) ); mpIndices = new UINT[mIndexCount]; if( mIndexCount != 0 ) { modelFile.read((char*)mpIndices, mIndexCount * sizeof(UINT)); } modelFile.read((char*)&magicCookie, sizeof(magicCookie)); ASSERT( magicCookie == 1234, _L("Model file missing magic cookie.") ); ASSERT( modelFile.good(), _L("Bad model file(2).") ); if ( 0 != mTotalVerticesSizeInBytes ) { Allocate(mVertexCount); // recalculates some things modelFile.read((char*)(mpVertices), mTotalVerticesSizeInBytes); } modelFile.read((char*)&magicCookie, sizeof(magicCookie)); ASSERT( modelFile.good() && magicCookie == 1234, _L("Bad model file(3).") ); return modelFile.good(); }
/* * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> * 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 <AK/StringBuilder.h> #include <LibWeb/DOM/HTMLFormElement.h> #include <LibWeb/DOM/HTMLInputElement.h> #include <LibWeb/Frame.h> #include <LibWeb/HtmlView.h> namespace Web { HTMLFormElement::HTMLFormElement(Document& document, const String& tag_name) : HTMLElement(document, tag_name) { } HTMLFormElement::~HTMLFormElement() { } void HTMLFormElement::submit() { if (action().is_null()) { dbg() << "Unsupported form action ''"; return; } if (method().to_lowercase() != "get") { dbg() << "Unsupported form method '" << method() << "'"; return; } URL url(document().complete_url(action())); struct NameAndValue { String name; String value; }; Vector<NameAndValue> parameters; for_each_in_subtree_of_type<HTMLInputElement>([&](auto& node) { auto& input = to<HTMLInputElement>(node); if (!input.name().is_null()) parameters.append({ input.name(), input.value() }); return IterationDecision::Continue; }); StringBuilder builder; for (size_t i = 0; i < parameters.size(); ++i) { builder.append(parameters[i].name); builder.append('='); builder.append(parameters[i].value); if (i != parameters.size() - 1) builder.append('&'); } url.set_query(builder.to_string()); // FIXME: We shouldn't let the form just do this willy-nilly. document().frame()->html_view()->load(url); } }
#include "ParquetBlockOutputFormat.h" #if USE_PARQUET // TODO: clean includes #include <Columns/ColumnDecimal.h> #include <Columns/ColumnFixedString.h> #include <Columns/ColumnNullable.h> #include <Columns/ColumnString.h> #include <Columns/ColumnVector.h> #include <Columns/ColumnsNumber.h> #include <Common/assert_cast.h> #include <Core/ColumnWithTypeAndName.h> #include <Core/callOnTypeIndex.h> #include <DataTypes/DataTypeDateTime.h> #include <DataTypes/DataTypeNullable.h> #include <DataTypes/DataTypesDecimal.h> #include <DataStreams/SquashingBlockOutputStream.h> #include <Formats/FormatFactory.h> #include <IO/WriteHelpers.h> #include <arrow/api.h> #include <arrow/io/api.h> #include <arrow/util/decimal.h> #include <parquet/arrow/writer.h> #include <parquet/exception.h> #include <parquet/util/memory.h> namespace DB { namespace ErrorCodes { extern const int UNKNOWN_EXCEPTION; extern const int UNKNOWN_TYPE; } ParquetBlockOutputFormat::ParquetBlockOutputFormat(WriteBuffer & out_, const Block & header_, const FormatSettings & format_settings_) : IOutputFormat(header_, out_), format_settings{format_settings_} { } static void checkStatus(arrow::Status & status, const std::string & column_name) { if (!status.ok()) throw Exception{"Error with a parquet column \"" + column_name + "\": " + status.ToString(), ErrorCodes::UNKNOWN_EXCEPTION}; } template <typename NumericType, typename ArrowBuilderType> static void fillArrowArrayWithNumericColumnData( ColumnPtr write_column, std::shared_ptr<arrow::Array> & arrow_array, const PaddedPODArray<UInt8> * null_bytemap) { const PaddedPODArray<NumericType> & internal_data = assert_cast<const ColumnVector<NumericType> &>(*write_column).getData(); ArrowBuilderType builder; arrow::Status status; const UInt8 * arrow_null_bytemap_raw_ptr = nullptr; PaddedPODArray<UInt8> arrow_null_bytemap; if (null_bytemap) { /// Invert values since Arrow interprets 1 as a non-null value, while CH as a null arrow_null_bytemap.reserve(null_bytemap->size()); for (size_t i = 0, size = null_bytemap->size(); i < size; ++i) arrow_null_bytemap.emplace_back(1 ^ (*null_bytemap)[i]); arrow_null_bytemap_raw_ptr = arrow_null_bytemap.data(); } status = builder.AppendValues(internal_data.data(), internal_data.size(), arrow_null_bytemap_raw_ptr); checkStatus(status, write_column->getName()); status = builder.Finish(&arrow_array); checkStatus(status, write_column->getName()); } template <typename ColumnType> static void fillArrowArrayWithStringColumnData( ColumnPtr write_column, std::shared_ptr<arrow::Array> & arrow_array, const PaddedPODArray<UInt8> * null_bytemap) { const auto & internal_column = assert_cast<const ColumnType &>(*write_column); arrow::StringBuilder builder; arrow::Status status; for (size_t string_i = 0, size = internal_column.size(); string_i < size; ++string_i) { if (null_bytemap && (*null_bytemap)[string_i]) { status = builder.AppendNull(); } else { StringRef string_ref = internal_column.getDataAt(string_i); status = builder.Append(string_ref.data, string_ref.size); } checkStatus(status, write_column->getName()); } status = builder.Finish(&arrow_array); checkStatus(status, write_column->getName()); } static void fillArrowArrayWithDateColumnData( ColumnPtr write_column, std::shared_ptr<arrow::Array> & arrow_array, const PaddedPODArray<UInt8> * null_bytemap) { const PaddedPODArray<UInt16> & internal_data = assert_cast<const ColumnVector<UInt16> &>(*write_column).getData(); //arrow::Date32Builder date_builder; arrow::UInt16Builder builder; arrow::Status status; for (size_t value_i = 0, size = internal_data.size(); value_i < size; ++value_i) { if (null_bytemap && (*null_bytemap)[value_i]) status = builder.AppendNull(); else /// Implicitly converts UInt16 to Int32 status = builder.Append(internal_data[value_i]); checkStatus(status, write_column->getName()); } status = builder.Finish(&arrow_array); checkStatus(status, write_column->getName()); } static void fillArrowArrayWithDateTimeColumnData( ColumnPtr write_column, std::shared_ptr<arrow::Array> & arrow_array, const PaddedPODArray<UInt8> * null_bytemap) { auto & internal_data = assert_cast<const ColumnVector<UInt32> &>(*write_column).getData(); //arrow::Date64Builder builder; arrow::UInt32Builder builder; arrow::Status status; for (size_t value_i = 0, size = internal_data.size(); value_i < size; ++value_i) { if (null_bytemap && (*null_bytemap)[value_i]) status = builder.AppendNull(); else /// Implicitly converts UInt16 to Int32 //status = date_builder.Append(static_cast<int64_t>(internal_data[value_i]) * 1000); // now ms. TODO check other units status = builder.Append(internal_data[value_i]); checkStatus(status, write_column->getName()); } status = builder.Finish(&arrow_array); checkStatus(status, write_column->getName()); } template <typename DataType> static void fillArrowArrayWithDecimalColumnData( ColumnPtr write_column, std::shared_ptr<arrow::Array> & arrow_array, const PaddedPODArray<UInt8> * null_bytemap, const DataType * decimal_type) { const auto & column = static_cast<const typename DataType::ColumnType &>(*write_column); arrow::DecimalBuilder builder(arrow::decimal(decimal_type->getPrecision(), decimal_type->getScale())); arrow::Status status; for (size_t value_i = 0, size = column.size(); value_i < size; ++value_i) { if (null_bytemap && (*null_bytemap)[value_i]) status = builder.AppendNull(); else status = builder.Append( arrow::Decimal128(reinterpret_cast<const uint8_t *>(&column.getElement(value_i).value))); // TODO: try copy column checkStatus(status, write_column->getName()); } status = builder.Finish(&arrow_array); checkStatus(status, write_column->getName()); /* TODO column copy const auto & internal_data = static_cast<const typename DataType::ColumnType &>(*write_column).getData(); //ArrowBuilderType numeric_builder; arrow::DecimalBuilder builder(arrow::decimal(decimal_type->getPrecision(), decimal_type->getScale())); arrow::Status status; const uint8_t * arrow_null_bytemap_raw_ptr = nullptr; PaddedPODArray<UInt8> arrow_null_bytemap; if (null_bytemap) { /// Invert values since Arrow interprets 1 as a non-null value, while CH as a null arrow_null_bytemap.reserve(null_bytemap->size()); for (size_t i = 0, size = null_bytemap->size(); i < size; ++i) arrow_null_bytemap.emplace_back(1 ^ (*null_bytemap)[i]); arrow_null_bytemap_raw_ptr = arrow_null_bytemap.data(); } status = builder.AppendValues(reinterpret_cast<const uint8_t*>(internal_data.data()), internal_data.size(), arrow_null_bytemap_raw_ptr); checkStatus(status, write_column->getName()); status = builder.Finish(&arrow_array); checkStatus(status, write_column->getName()); */ } #define FOR_INTERNAL_NUMERIC_TYPES(M) \ M(UInt8, arrow::UInt8Builder) \ M(Int8, arrow::Int8Builder) \ M(UInt16, arrow::UInt16Builder) \ M(Int16, arrow::Int16Builder) \ M(UInt32, arrow::UInt32Builder) \ M(Int32, arrow::Int32Builder) \ M(UInt64, arrow::UInt64Builder) \ M(Int64, arrow::Int64Builder) \ M(Float32, arrow::FloatBuilder) \ M(Float64, arrow::DoubleBuilder) const std::unordered_map<String, std::shared_ptr<arrow::DataType>> internal_type_to_arrow_type = { {"UInt8", arrow::uint8()}, {"Int8", arrow::int8()}, {"UInt16", arrow::uint16()}, {"Int16", arrow::int16()}, {"UInt32", arrow::uint32()}, {"Int32", arrow::int32()}, {"UInt64", arrow::uint64()}, {"Int64", arrow::int64()}, {"Float32", arrow::float32()}, {"Float64", arrow::float64()}, //{"Date", arrow::date64()}, //{"Date", arrow::date32()}, {"Date", arrow::uint16()}, // CHECK //{"DateTime", arrow::date64()}, // BUG! saves as date32 {"DateTime", arrow::uint32()}, // TODO: ClickHouse can actually store non-utf8 strings! {"String", arrow::utf8()}, {"FixedString", arrow::utf8()}, }; static const PaddedPODArray<UInt8> * extractNullBytemapPtr(ColumnPtr column) { ColumnPtr null_column = assert_cast<const ColumnNullable &>(*column).getNullMapColumnPtr(); const PaddedPODArray<UInt8> & null_bytemap = assert_cast<const ColumnVector<UInt8> &>(*null_column).getData(); return &null_bytemap; } class OstreamOutputStream : public parquet::OutputStream { public: explicit OstreamOutputStream(WriteBuffer & ostr_) : ostr(ostr_) {} virtual ~OstreamOutputStream() {} virtual void Close() {} virtual int64_t Tell() { return total_length; } virtual void Write(const uint8_t * data, int64_t length) { ostr.write(reinterpret_cast<const char *>(data), length); total_length += length; } private: WriteBuffer & ostr; int64_t total_length = 0; PARQUET_DISALLOW_COPY_AND_ASSIGN(OstreamOutputStream); }; void ParquetBlockOutputFormat::consume(Chunk chunk) { auto & header = getPort(PortKind::Main).getHeader(); const size_t columns_num = chunk.getNumColumns(); /// For arrow::Schema and arrow::Table creation std::vector<std::shared_ptr<arrow::Field>> arrow_fields; std::vector<std::shared_ptr<arrow::Array>> arrow_arrays; arrow_fields.reserve(columns_num); arrow_arrays.reserve(columns_num); for (size_t column_i = 0; column_i < columns_num; ++column_i) { // TODO: constructed every iteration ColumnWithTypeAndName column = header.safeGetByPosition(column_i); column.column = chunk.getColumns()[column_i]; const bool is_column_nullable = column.type->isNullable(); const auto & column_nested_type = is_column_nullable ? static_cast<const DataTypeNullable *>(column.type.get())->getNestedType() : column.type; const std::string column_nested_type_name = column_nested_type->getFamilyName(); if (isDecimal(column_nested_type)) { const auto add_decimal_field = [&](const auto & types) -> bool { using Types = std::decay_t<decltype(types)>; using ToDataType = typename Types::LeftType; if constexpr ( std::is_same_v< ToDataType, DataTypeDecimal< Decimal32>> || std::is_same_v<ToDataType, DataTypeDecimal<Decimal64>> || std::is_same_v<ToDataType, DataTypeDecimal<Decimal128>>) { const auto & decimal_type = static_cast<const ToDataType *>(column_nested_type.get()); arrow_fields.emplace_back(std::make_shared<arrow::Field>( column.name, arrow::decimal(decimal_type->getPrecision(), decimal_type->getScale()), is_column_nullable)); } return false; }; callOnIndexAndDataType<void>(column_nested_type->getTypeId(), add_decimal_field); } else { if (internal_type_to_arrow_type.find(column_nested_type_name) == internal_type_to_arrow_type.end()) { throw Exception{"The type \"" + column_nested_type_name + "\" of a column \"" + column.name + "\"" " is not supported for conversion into a Parquet data format", ErrorCodes::UNKNOWN_TYPE}; } arrow_fields.emplace_back(std::make_shared<arrow::Field>(column.name, internal_type_to_arrow_type.at(column_nested_type_name), is_column_nullable)); } std::shared_ptr<arrow::Array> arrow_array; ColumnPtr nested_column = is_column_nullable ? assert_cast<const ColumnNullable &>(*column.column).getNestedColumnPtr() : column.column; const PaddedPODArray<UInt8> * null_bytemap = is_column_nullable ? extractNullBytemapPtr(column.column) : nullptr; if ("String" == column_nested_type_name) { fillArrowArrayWithStringColumnData<ColumnString>(nested_column, arrow_array, null_bytemap); } else if ("FixedString" == column_nested_type_name) { fillArrowArrayWithStringColumnData<ColumnFixedString>(nested_column, arrow_array, null_bytemap); } else if ("Date" == column_nested_type_name) { fillArrowArrayWithDateColumnData(nested_column, arrow_array, null_bytemap); } else if ("DateTime" == column_nested_type_name) { fillArrowArrayWithDateTimeColumnData(nested_column, arrow_array, null_bytemap); } else if (isDecimal(column_nested_type)) { auto fill_decimal = [&](const auto & types) -> bool { using Types = std::decay_t<decltype(types)>; using ToDataType = typename Types::LeftType; if constexpr ( std::is_same_v< ToDataType, DataTypeDecimal< Decimal32>> || std::is_same_v<ToDataType, DataTypeDecimal<Decimal64>> || std::is_same_v<ToDataType, DataTypeDecimal<Decimal128>>) { const auto & decimal_type = static_cast<const ToDataType *>(column_nested_type.get()); fillArrowArrayWithDecimalColumnData(nested_column, arrow_array, null_bytemap, decimal_type); } return false; }; callOnIndexAndDataType<void>(column_nested_type->getTypeId(), fill_decimal); } #define DISPATCH(CPP_NUMERIC_TYPE, ARROW_BUILDER_TYPE) \ else if (#CPP_NUMERIC_TYPE == column_nested_type_name) \ { \ fillArrowArrayWithNumericColumnData<CPP_NUMERIC_TYPE, ARROW_BUILDER_TYPE>(nested_column, arrow_array, null_bytemap); \ } FOR_INTERNAL_NUMERIC_TYPES(DISPATCH) #undef DISPATCH else { throw Exception{"Internal type \"" + column_nested_type_name + "\" of a column \"" + column.name + "\"" " is not supported for conversion into a Parquet data format", ErrorCodes::UNKNOWN_TYPE}; } arrow_arrays.emplace_back(std::move(arrow_array)); } std::shared_ptr<arrow::Schema> arrow_schema = std::make_shared<arrow::Schema>(std::move(arrow_fields)); std::shared_ptr<arrow::Table> arrow_table = arrow::Table::Make(arrow_schema, arrow_arrays); auto sink = std::make_shared<OstreamOutputStream>(out); if (!file_writer) { parquet::WriterProperties::Builder builder; #if USE_SNAPPY builder.compression(parquet::Compression::SNAPPY); #endif auto props = builder.build(); auto status = parquet::arrow::FileWriter::Open( *arrow_table->schema(), arrow::default_memory_pool(), sink, props, /*parquet::default_writer_properties(),*/ parquet::arrow::default_arrow_writer_properties(), &file_writer); if (!status.ok()) throw Exception{"Error while opening a table: " + status.ToString(), ErrorCodes::UNKNOWN_EXCEPTION}; } // TODO: calculate row_group_size depending on a number of rows and table size auto status = file_writer->WriteTable(*arrow_table, format_settings.parquet.row_group_size); if (!status.ok()) throw Exception{"Error while writing a table: " + status.ToString(), ErrorCodes::UNKNOWN_EXCEPTION}; } void ParquetBlockOutputFormat::finalize() { if (file_writer) { auto status = file_writer->Close(); if (!status.ok()) throw Exception{"Error while closing a table: " + status.ToString(), ErrorCodes::UNKNOWN_EXCEPTION}; } } void registerOutputFormatProcessorParquet(FormatFactory & factory) { factory.registerOutputFormatProcessor( "Parquet", [](WriteBuffer & buf, const Block & sample, const Context & /*context*/, FormatFactory::WriteCallback, const FormatSettings & format_settings) { auto impl = std::make_shared<ParquetBlockOutputFormat>(buf, sample, format_settings); /// TODO // auto res = std::make_shared<SquashingBlockOutputStream>(impl, impl->getHeader(), format_settings.parquet.row_group_size, 0); // res->disableFlush(); return impl; }); } } #else namespace DB { class FormatFactory; void registerOutputFormatProcessorParquet(FormatFactory &) { } } #endif
/* * ===================================================================================== * * Filename: xBasisTests.cpp * * Description: * * Version: 1.0 * Created: 04/30/2015 09:47:07 * Revision: none * Compiler: gcc * * Author: Pablo Colapinto (), gmail->wolftype * Organization: wolftype * * ===================================================================================== */ #include "vsr.h" using namespace vsr; using c = GAE< algebra< metric<3>, float >>::e<2>;//types::e_basis<2>; int main(){ c(1).print(); return 0; }