hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
c8a61f9d0cef4893eff1c4ac135dc8447eb5c73f
10,744
cpp
C++
third_party/boost/libs/pool/test/test_simple_seg_storage.cpp
Jackarain/tinyrpc
07060e3466776aa992df8574ded6c1616a1a31af
[ "BSL-1.0" ]
32
2019-02-27T06:57:07.000Z
2021-08-29T10:56:19.000Z
third_party/boost/libs/pool/test/test_simple_seg_storage.cpp
avplayer/cxxrpc
7049b4079fac78b3828e68f787d04d699ce52f6d
[ "BSL-1.0" ]
1
2019-04-04T18:00:00.000Z
2019-04-04T18:00:00.000Z
third_party/boost/libs/pool/test/test_simple_seg_storage.cpp
avplayer/cxxrpc
7049b4079fac78b3828e68f787d04d699ce52f6d
[ "BSL-1.0" ]
5
2019-08-20T13:45:04.000Z
2022-03-01T18:23:49.000Z
/* Copyright (C) 2011 Kwan Ting Chan * * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) */ #include "test_simple_seg_storage.hpp" #include "track_allocator.hpp" #include "random_shuffle.hpp" #include <boost/pool/simple_segregated_storage.hpp> #include <boost/assert.hpp> #include <boost/integer/common_factor_ct.hpp> #if defined(BOOST_MSVC) && (BOOST_MSVC <= 1600) #pragma warning(push) #pragma warning(disable: 4244) // ..\..\boost/random/uniform_int_distribution.hpp(171) : // warning C4127: conditional expression is constant #pragma warning(disable: 4127) #endif #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int.hpp> #include <boost/random/variate_generator.hpp> #if defined(BOOST_MSVC) && (BOOST_MSVC <= 1600) #pragma warning(pop) #endif #include <boost/core/lightweight_test.hpp> #include <algorithm> #include <functional> #include <set> #include <vector> #include <cstddef> #include <cstdlib> #include <ctime> #ifdef BOOST_MSVC #pragma warning(disable:4267) #endif // "A free list is ordered if repeated calls to malloc() will result in a // constantly-increasing sequence of values, as determined by std::less<void*>" // Return: true if in constantly-increasing order, false otherwise bool check_is_order(const std::vector<void*>& vs) { if(vs.size() < 2) { return true; } void *lower, *higher; std::vector<void*>::const_iterator ci = vs.begin(); lower = *(ci++); while(ci != vs.end()) { higher = *(ci++); if(!std::less<void*>()(lower, higher)) { return false; } } return true; } // Return: number of chunks malloc'd from store std::size_t test_is_order(test_simp_seg_store& store) { std::vector<void*> vpv; std::size_t nchunk = 0; // Pre: !empty() while(!store.empty()) { void* const first = store.get_first(); void* const pv = store.malloc(); // "Takes the first available chunk from the free list // and returns it" BOOST_TEST(first == pv); vpv.push_back(pv); ++nchunk; } BOOST_TEST(check_is_order(vpv)); return nchunk; } boost::mt19937 gen; int main() { std::srand(static_cast<unsigned>(std::time(0))); gen.seed(static_cast<boost::uint32_t>(std::time(0))); /* Store::segregate(block, sz, partition_sz, end) */ std::size_t partition_sz = boost::integer::static_lcm<sizeof(void*), sizeof(int)>::value; boost::uniform_int<> dist(partition_sz, 10000); boost::variate_generator<boost::mt19937&, boost::uniform_int<> > die(gen, dist); std::size_t block_size = die(); // Pre: npartition_sz >= sizeof(void*) // npartition_sz = sizeof(void*) * i, for some integer i // nsz >= npartition_sz // block is properly aligned for an array of object of // size npartition_sz and array of void * BOOST_ASSERT(partition_sz >= sizeof(void*)); BOOST_ASSERT(partition_sz % sizeof(void*) == 0); BOOST_ASSERT(block_size >= partition_sz); { char* const pc = track_allocator::malloc(block_size); // (Test) Pre: block of memory is valid BOOST_ASSERT(pc); int endadd = 0; void* const pvret = test_simp_seg_store::segregate(pc, block_size, partition_sz, &endadd); // The first chunk "is always equal to block" BOOST_TEST(pvret == pc); void* cur = test_simp_seg_store::get_nextof(static_cast<int*>(pvret)); void* last = pvret; std::size_t nchunk = 1; while(cur != &endadd) { ++nchunk; // Memory of each chunk does not overlap // The free list constructed is actually from the given block // The "interleaved free list is ordered" BOOST_TEST(std::less_equal<void*>()(static_cast<char*>(last) + partition_sz, cur)); BOOST_TEST(std::less_equal<void*>()(static_cast<char*>(cur) + partition_sz, pc + block_size)); last = cur; cur = test_simp_seg_store::get_nextof(static_cast<int*>(cur)); } // "The last chunk is set to point to end" // "Partitioning into as many partition_sz-sized chunks as possible" BOOST_TEST(nchunk == block_size/partition_sz); } /* t.add_block(block, sz, partition_sz), t.malloc() */ { // Default constructor of simple_segregated_storage do nothing test_simp_seg_store tstore; // Post: empty() BOOST_TEST(tstore.empty()); char* const pc = track_allocator::malloc(block_size); tstore.add_block(pc, block_size, partition_sz); // The first chunk "is always equal to block" BOOST_TEST(tstore.get_first() == pc); // Empty before add_block() => "is ordered after" std::size_t nchunk = test_is_order(tstore); // "Partitioning into as many partition_sz-sized chunks as possible" BOOST_TEST(nchunk == block_size/partition_sz); BOOST_ASSERT(partition_sz <= 23); test_simp_seg_store tstore2; char* const pc2 = track_allocator::malloc(88); tstore2.add_block(pc2, 24, partition_sz); tstore2.add_block(pc2 + 64, 24, partition_sz); tstore2.add_block(pc2 + 32, 24, partition_sz); tstore2.add_block(track_allocator::malloc(23), 23, partition_sz); std::size_t nchunk_ref = (3*(24/partition_sz)) + (23/partition_sz); for(nchunk = 0; !tstore2.empty(); tstore2.malloc(), ++nchunk) {} // add_block() merges new free list to existing BOOST_TEST(nchunk == nchunk_ref); } /* t.free(chunk) */ { test_simp_seg_store tstore; char* const pc = track_allocator::malloc(partition_sz); tstore.add_block(pc, partition_sz, partition_sz); void* pv = tstore.malloc(); BOOST_TEST(tstore.empty()); tstore.free(pv); } /* t.add_ordered_block(block, sz, partition_sz) */ { { char* const pc = track_allocator::malloc(6 * partition_sz); std::vector<void*> vpv; vpv.push_back(pc); vpv.push_back(pc + (2 * partition_sz)); vpv.push_back(pc + (4 * partition_sz)); do { test_simp_seg_store tstore; tstore.add_ordered_block(vpv[0], 2*partition_sz, partition_sz); tstore.add_ordered_block(vpv[1], 2*partition_sz, partition_sz); tstore.add_ordered_block(vpv[2], 2*partition_sz, partition_sz); // "Order-preserving" test_is_order(tstore); } while(std::next_permutation(vpv.begin(), vpv.end())); } { test_simp_seg_store tstore; char* const pc = track_allocator::malloc(6 * partition_sz); tstore.add_ordered_block(pc, 2 * partition_sz, partition_sz); tstore.add_ordered_block(pc + (4 * partition_sz), (2 * partition_sz), partition_sz); // "Order-preserving" test_is_order(tstore); } { test_simp_seg_store tstore; char* const pc = track_allocator::malloc(6 * partition_sz); tstore.add_ordered_block(pc + (4 * partition_sz), (2 * partition_sz), partition_sz); tstore.add_ordered_block(pc, 2 * partition_sz, partition_sz); // "Order-preserving" test_is_order(tstore); } } /* t.ordered_free(chunk) */ { char* const pc = track_allocator::malloc(6 * partition_sz); test_simp_seg_store tstore; tstore.add_block(pc, 6 * partition_sz, partition_sz); std::vector<void*> vpv; for(std::size_t i=0; i < 6; ++i) { vpv.push_back(tstore.malloc()); } BOOST_ASSERT(tstore.empty()); pool_test_random_shuffle(vpv.begin(), vpv.end()); for(std::size_t i=0; i < 6; ++i) { tstore.ordered_free(vpv[i]); } // "Order-preserving" test_is_order(tstore); } /* t.malloc_n(n, partition_sz) */ { { char* const pc = track_allocator::malloc(12 * partition_sz); test_simp_seg_store tstore; tstore.add_ordered_block(pc, 2 * partition_sz, partition_sz); tstore.add_ordered_block(pc + (3 * partition_sz), 3 * partition_sz, partition_sz); tstore.add_ordered_block(pc + (7 * partition_sz), 5 * partition_sz, partition_sz); void* pvret = tstore.malloc_n(6, partition_sz); BOOST_TEST(pvret == 0); pvret = tstore.malloc_n(0, partition_sz); // There's no prohibition against asking for zero elements BOOST_TEST(pvret == 0); pvret = tstore.malloc_n(3, partition_sz); // Implicit assumption that contiguous sequence found is the first // available while traversing from the start of the free list BOOST_TEST(pvret == pc + (3 * partition_sz)); pvret = tstore.malloc_n(4, partition_sz); BOOST_TEST(pvret == pc + (7 * partition_sz)); // There should still be two contiguous // and one non-contiguous chunk left std::size_t nchunks = 0; while(!tstore.empty()) { tstore.malloc(); ++nchunks; } BOOST_TEST(nchunks == 3); } { char* const pc = track_allocator::malloc(12 * partition_sz); test_simp_seg_store tstore; tstore.add_ordered_block(pc, 2 * partition_sz, partition_sz); tstore.add_ordered_block(pc + (3 * partition_sz), 3 * partition_sz, partition_sz); tstore.add_ordered_block(pc + (7 * partition_sz), 5 * partition_sz, partition_sz); tstore.malloc_n(3, partition_sz); // "Order-preserving" test_is_order(tstore); } } for(std::set<char*>::iterator itr = track_allocator::allocated_blocks.begin(); itr != track_allocator::allocated_blocks.end(); ++itr) { delete [] *itr; } track_allocator::allocated_blocks.clear(); return boost::report_errors(); }
35.22623
81
0.585164
[ "object", "vector" ]
c8a8e46d8a9edc7d45ac662800f5b966d9741263
7,079
cpp
C++
src/Net/Socket.cpp
corymonroe/GrinPlusPlus
bfdcbbcd65872f08270fc3084992eefea234b05e
[ "MIT" ]
null
null
null
src/Net/Socket.cpp
corymonroe/GrinPlusPlus
bfdcbbcd65872f08270fc3084992eefea234b05e
[ "MIT" ]
null
null
null
src/Net/Socket.cpp
corymonroe/GrinPlusPlus
bfdcbbcd65872f08270fc3084992eefea234b05e
[ "MIT" ]
null
null
null
#include <Net/Socket.h> #include <Net/SocketException.h> #include <Common/Util/ThreadUtil.h> #include <Infrastructure/Logger.h> static unsigned long DEFAULT_TIMEOUT = 5 * 1000; // 5s #ifndef _WIN32 #define SOCKET_ERROR -1 #endif Socket::Socket(const SocketAddress& address) : m_address(address), m_socketOpen(false), m_blocking(true), m_receiveBufferSize(0), m_receiveTimeout(DEFAULT_TIMEOUT), m_sendTimeout(DEFAULT_TIMEOUT) { } Socket::~Socket() { m_pSocket.reset(); m_pContext.reset(); } bool Socket::Connect(std::shared_ptr<asio::io_context> pContext) { m_pContext = pContext; asio::ip::tcp::endpoint endpoint(asio::ip::address(asio::ip::address_v4::from_string(m_address.GetIPAddress().Format())), m_address.GetPortNumber()); m_pSocket = std::make_shared<asio::ip::tcp::socket>(*pContext); m_pSocket->async_connect(endpoint, [this](const asio::error_code & ec) { m_errorCode = ec; if (!ec) { asio::socket_base::receive_buffer_size option(32768); m_pSocket->set_option(option); #ifdef _WIN32 if (setsockopt(m_pSocket->native_handle(), SOL_SOCKET, SO_RCVTIMEO, (char*)& DEFAULT_TIMEOUT, sizeof(DEFAULT_TIMEOUT)) == SOCKET_ERROR) { return false; } if (setsockopt(m_pSocket->native_handle(), SOL_SOCKET, SO_SNDTIMEO, (char*)& DEFAULT_TIMEOUT, sizeof(DEFAULT_TIMEOUT)) == SOCKET_ERROR) { return false; } #endif m_address = SocketAddress(m_address.GetIPAddress(), m_pSocket->remote_endpoint().port()); m_socketOpen = true; return true; } else { asio::error_code ignoreError; m_pSocket->close(ignoreError); return false; } } ); pContext->run(); auto timeout = std::chrono::system_clock::now() + std::chrono::seconds(1); while (!m_errorCode && !m_socketOpen && std::chrono::system_clock::now() < timeout) { ThreadUtil::SleepFor(std::chrono::milliseconds(10), false); } return m_socketOpen; } bool Socket::Accept(std::shared_ptr<asio::io_context> pContext, asio::ip::tcp::acceptor& acceptor, const std::atomic_bool& terminate) { m_pContext = pContext; m_pSocket = std::make_shared<asio::ip::tcp::socket>(*pContext); acceptor.async_accept(*m_pSocket, [this, pContext](const asio::error_code & ec) { m_errorCode = ec; if (!ec) { if (setsockopt(m_pSocket->native_handle(), SOL_SOCKET, SO_RCVTIMEO, (char*)& DEFAULT_TIMEOUT, sizeof(DEFAULT_TIMEOUT)) == SOCKET_ERROR) { return false; } if (setsockopt(m_pSocket->native_handle(), SOL_SOCKET, SO_SNDTIMEO, (char*)& DEFAULT_TIMEOUT, sizeof(DEFAULT_TIMEOUT)) == SOCKET_ERROR) { return false; } const std::string address = m_pSocket->remote_endpoint().address().to_string(); m_address = SocketAddress(address, m_pSocket->remote_endpoint().port()); m_socketOpen = true; return true; } else { asio::error_code ignoreError; m_pSocket->close(ignoreError); return false; } } ); while (!m_errorCode && !m_socketOpen) { if (terminate) { break; } pContext->run_one_for(std::chrono::milliseconds(100)); } pContext->reset(); return m_socketOpen; } bool Socket::CloseSocket() { m_socketOpen = false; asio::error_code error; m_pSocket->shutdown(asio::socket_base::shutdown_both, error); if (!error) { m_pSocket->close(error); } return !error; } bool Socket::IsSocketOpen() const { return m_socketOpen; } bool Socket::IsActive() const { if (m_socketOpen && !m_errorCode) { return true; } if (m_errorCode.value() == EAGAIN) { return true; } if (m_errorCode) { LOG_INFO_F("Connection with ({}) not active. Error: {}", m_address, m_errorCode.message()); } return false; } bool Socket::SetReceiveTimeout(const unsigned long milliseconds) { #ifdef _WIN32 const int result = setsockopt(m_pSocket->native_handle(), SOL_SOCKET, SO_RCVTIMEO, (char*)&milliseconds, sizeof(milliseconds)); #else struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = milliseconds * 1000; const int result = setsockopt(m_pSocket->native_handle(), SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)); #endif if (result == 0) { m_receiveTimeout = milliseconds; } else { return false; } return true; } bool Socket::SetReceiveBufferSize(const int bufferSize) { const int socketRcvBuff = bufferSize; const int result = setsockopt(m_pSocket->native_handle(), SOL_SOCKET, SO_RCVBUF, (const char*)&socketRcvBuff, sizeof(int)); if (result == 0) { m_receiveBufferSize = bufferSize; } else { return false; } return true; } bool Socket::SetSendTimeout(const unsigned long milliseconds) { #ifdef _WIN32 const int result = setsockopt(m_pSocket->native_handle(), SOL_SOCKET, SO_SNDTIMEO, (char*)&milliseconds, sizeof(milliseconds)); #else struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = milliseconds * 1000; const int result = setsockopt(m_pSocket->native_handle(), SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout, sizeof(timeout)); #endif if (result == 0) { m_sendTimeout = milliseconds; return true; } else { return false; } } bool Socket::SetBlocking(const bool blocking) { if (m_blocking != blocking) { #ifdef _WIN32 unsigned long blockingValue = (blocking ? 0 : 1); const int result = ioctlsocket(m_pSocket->native_handle(), FIONBIO, &blockingValue); if (result == 0) { m_blocking = blocking; } else { int error = 0; int size = sizeof(error); getsockopt(m_pSocket->native_handle(), SOL_SOCKET, SO_ERROR, (char*)&error, &size); WSASetLastError(error); throw SocketException(); } #else m_blocking = blocking; #endif } return m_blocking == blocking; } bool Socket::Send(const std::vector<unsigned char>& message, const bool incrementCount) { if (incrementCount) { m_rateCounter.AddMessageSent(); } const size_t bytesWritten = asio::write(*m_pSocket, asio::buffer(message.data(), message.size()), m_errorCode); if (m_errorCode && m_errorCode.value() != EAGAIN) { throw SocketException(); } return bytesWritten == message.size(); } bool Socket::Receive(const size_t numBytes, const bool incrementCount, std::vector<unsigned char>& data) { if (data.size() < numBytes) { data.resize(numBytes); } size_t numTries = 0; size_t bytesRead = 0; while (numTries++ < 3) { bytesRead += asio::read(*m_pSocket, asio::buffer(data.data() + bytesRead, numBytes - bytesRead), m_errorCode); if (m_errorCode && m_errorCode.value() != EAGAIN) { throw SocketException(); } if (bytesRead == numBytes) { if (incrementCount) { m_rateCounter.AddMessageReceived(); } return true; } else if (m_errorCode.value() == EAGAIN) { LOG_DEBUG("EAGAIN error returned. Pausing briefly, and then trying again."); std::this_thread::sleep_for(std::chrono::milliseconds(2)); } } return false; } bool Socket::HasReceivedData() { const size_t available = m_pSocket->available(m_errorCode); if (m_errorCode && m_errorCode.value() != EAGAIN) { throw SocketException(); } return available >= 11; }
22.544586
150
0.689645
[ "vector" ]
c8a914db9588e3c4900159f11715137c968c639d
3,138
cpp
C++
GodotModule/test/boost_example.cpp
vkf63516/GodotGymAI
a6d4ce5e95f0d3a5e03d8c94cf59fcf27703c391
[ "MIT" ]
77
2020-11-25T17:57:43.000Z
2022-03-18T12:50:22.000Z
GodotModule/test/boost_example.cpp
vkf63516/GodotGymAI
a6d4ce5e95f0d3a5e03d8c94cf59fcf27703c391
[ "MIT" ]
10
2020-12-05T14:49:21.000Z
2022-01-20T20:28:39.000Z
GodotModule/test/boost_example.cpp
vkf63516/GodotGymAI
a6d4ce5e95f0d3a5e03d8c94cf59fcf27703c391
[ "MIT" ]
12
2020-12-05T11:14:05.000Z
2022-01-29T02:08:46.000Z
#include <boost/interprocess/managed_shared_memory.hpp> #include <cstdlib> //std::system #include <cstddef> #include <cassert> #include <utility> #include <iostream> #include <string> int main(int argc, char *argv[]) { using namespace boost::interprocess; typedef std::pair<double, int> MyType; if(argc == 1){ //Parent process //Remove shared memory on construction and destruction struct shm_remove { shm_remove() { shared_memory_object::remove("MySharedMemory"); } ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); } } remover; //Construct managed shared memory managed_shared_memory segment(create_only, "MySharedMemory", 65536); //Create an object of MyType initialized to {0.0, 0} std::string *instance = segment.construct<std::string> ("MyType instance") //name of the object ("string"); //ctor first argument //Create an array of 10 elements of MyType initialized to {0.0, 0} MyType *array = segment.construct<MyType> ("MyType array") //name of the object [10] //number of elements (0.0, 0); //Same two ctor arguments for all objects //Create an array of 3 elements of MyType initializing each one //to a different value {0.0, 0}, {1.0, 1}, {2.0, 2}... float float_initializer[3] = { 0.0, 1.0, 2.0 }; int int_initializer[3] = { 0, 1, 2 }; MyType *array_it = segment.construct_it<MyType> ("MyType array from it") //name of the object [3] //number of elements ( &float_initializer[0] //Iterator for the 1st ctor argument , &int_initializer[0]); //Iterator for the 2nd ctor argument //Launch child process std::string s(argv[0]); s += " child "; if(0 != std::system(s.c_str())) return 1; //Check child has destroyed all objects if(segment.find<MyType>("MyType array").first || segment.find<std::string>("MyType instance").first || segment.find<MyType>("MyType array from it").first) return 1; } else{ //Open managed shared memory managed_shared_memory segment(open_only, "MySharedMemory"); std::pair<MyType*, managed_shared_memory::size_type> res; std::pair<std::string*, managed_shared_memory::size_type> res1; //Find the array res = segment.find<MyType> ("MyType array"); //Length should be 10 if(res.second != 10) return 1; //Find the object res1 = segment.find<std::string> ("MyType instance"); std::cout<<*(res1.first)<<std::endl; //Length should be 1 if(res1.second != 1) return 1; //Find the array constructed from iterators res = segment.find<MyType> ("MyType array from it"); //Length should be 3 if(res.second != 3) return 1; //We're done, delete all the objects segment.destroy<MyType>("MyType array"); segment.destroy<std::string>("MyType instance"); segment.destroy<MyType>("MyType array from it"); } return 0; }
35.659091
74
0.613129
[ "object" ]
c8aa98d8742a626f5a707d8838a140e1396f74cd
12,008
cpp
C++
platform/default/mbgl/storage/offline_download.cpp
kravtsun/mapbox-gl-native
ea8ec38df156c6683c886253dbb1f6bc828686ff
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
platform/default/mbgl/storage/offline_download.cpp
kravtsun/mapbox-gl-native
ea8ec38df156c6683c886253dbb1f6bc828686ff
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
platform/default/mbgl/storage/offline_download.cpp
kravtsun/mapbox-gl-native
ea8ec38df156c6683c886253dbb1f6bc828686ff
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
#include <mbgl/storage/file_source.hpp> #include <mbgl/storage/offline_database.hpp> #include <mbgl/storage/offline_download.hpp> #include <mbgl/storage/resource.hpp> #include <mbgl/storage/response.hpp> #include <mbgl/storage/http_file_source.hpp> #include <mbgl/style/parser.hpp> #include <mbgl/style/sources/geojson_source_impl.hpp> #include <mbgl/style/tile_source_impl.hpp> #include <mbgl/text/glyph.hpp> #include <mbgl/util/mapbox.hpp> #include <mbgl/util/run_loop.hpp> #include <mbgl/util/tile_cover.hpp> #include <mbgl/util/tileset.hpp> #include <set> namespace mbgl { OfflineDownload::OfflineDownload(int64_t id_, OfflineRegionDefinition&& definition_, OfflineDatabase& offlineDatabase_, FileSource& onlineFileSource_) : id(id_), definition(definition_), offlineDatabase(offlineDatabase_), onlineFileSource(onlineFileSource_) { setObserver(nullptr); } OfflineDownload::~OfflineDownload() = default; void OfflineDownload::setObserver(std::unique_ptr<OfflineRegionObserver> observer_) { observer = observer_ ? std::move(observer_) : std::make_unique<OfflineRegionObserver>(); } void OfflineDownload::setState(OfflineRegionDownloadState state) { if (status.downloadState == state) { return; } status.downloadState = state; if (status.downloadState == OfflineRegionDownloadState::Active) { activateDownload(); } else { deactivateDownload(); } observer->statusChanged(status); } OfflineRegionStatus OfflineDownload::getStatus() const { if (status.downloadState == OfflineRegionDownloadState::Active) { return status; } OfflineRegionStatus result = offlineDatabase.getRegionCompletedStatus(id); result.requiredResourceCount++; optional<Response> styleResponse = offlineDatabase.get(Resource::style(definition.styleURL)); if (!styleResponse) { return result; } style::Parser parser; parser.parse(*styleResponse->data); result.requiredResourceCountIsPrecise = true; for (const auto& source : parser.sources) { SourceType type = source->baseImpl->type; switch (type) { case SourceType::Vector: case SourceType::Raster: { style::TileSourceImpl* tileSource = static_cast<style::TileSourceImpl*>(source->baseImpl.get()); const variant<std::string, Tileset>& urlOrTileset = tileSource->getURLOrTileset(); const uint16_t tileSize = tileSource->getTileSize(); if (urlOrTileset.is<Tileset>()) { result.requiredResourceCount += definition.tileCover(type, tileSize, urlOrTileset.get<Tileset>().zoomRange).size(); } else { result.requiredResourceCount += 1; const std::string& url = urlOrTileset.get<std::string>(); optional<Response> sourceResponse = offlineDatabase.get(Resource::source(url)); if (sourceResponse) { result.requiredResourceCount += definition.tileCover(type, tileSize, style::TileSourceImpl::parseTileJSON( *sourceResponse->data, url, type, tileSize).zoomRange).size(); } else { result.requiredResourceCountIsPrecise = false; } } break; } case SourceType::GeoJSON: { style::GeoJSONSource::Impl* geojsonSource = static_cast<style::GeoJSONSource::Impl*>(source->baseImpl.get()); if (geojsonSource->getURL()) { result.requiredResourceCount += 1; } break; } case SourceType::Video: case SourceType::Annotations: break; } } if (!parser.glyphURL.empty()) { result.requiredResourceCount += parser.fontStacks().size() * GLYPH_RANGES_PER_FONT_STACK; } if (!parser.spriteURL.empty()) { result.requiredResourceCount += 2; } return result; } void OfflineDownload::activateDownload() { status = OfflineRegionStatus(); status.downloadState = OfflineRegionDownloadState::Active; status.requiredResourceCount++; ensureResource(Resource::style(definition.styleURL), [&](Response styleResponse) { status.requiredResourceCountIsPrecise = true; style::Parser parser; parser.parse(*styleResponse.data); for (const auto& source : parser.sources) { SourceType type = source->baseImpl->type; switch (type) { case SourceType::Vector: case SourceType::Raster: { const style::TileSourceImpl* tileSource = static_cast<style::TileSourceImpl*>(source->baseImpl.get()); const variant<std::string, Tileset>& urlOrTileset = tileSource->getURLOrTileset(); const uint16_t tileSize = tileSource->getTileSize(); if (urlOrTileset.is<Tileset>()) { queueTiles(type, tileSize, urlOrTileset.get<Tileset>()); } else { const std::string& url = urlOrTileset.get<std::string>(); status.requiredResourceCountIsPrecise = false; status.requiredResourceCount++; requiredSourceURLs.insert(url); ensureResource(Resource::source(url), [=](Response sourceResponse) { queueTiles(type, tileSize, style::TileSourceImpl::parseTileJSON( *sourceResponse.data, url, type, tileSize)); requiredSourceURLs.erase(url); if (requiredSourceURLs.empty()) { status.requiredResourceCountIsPrecise = true; } }); } break; } case SourceType::GeoJSON: { style::GeoJSONSource::Impl* geojsonSource = static_cast<style::GeoJSONSource::Impl*>(source->baseImpl.get()); if (geojsonSource->getURL()) { queueResource(Resource::source(*geojsonSource->getURL())); } break; } case SourceType::Video: case SourceType::Annotations: break; } } if (!parser.glyphURL.empty()) { for (const auto& fontStack : parser.fontStacks()) { for (char16_t i = 0; i < GLYPH_RANGES_PER_FONT_STACK; i++) { queueResource(Resource::glyphs(parser.glyphURL, fontStack, getGlyphRange(i * GLYPHS_PER_GLYPH_RANGE))); } } } if (!parser.spriteURL.empty()) { queueResource(Resource::spriteImage(parser.spriteURL, definition.pixelRatio)); queueResource(Resource::spriteJSON(parser.spriteURL, definition.pixelRatio)); } continueDownload(); }); } /* Fill up our own request queue by requesting the next few resources. This is called when activating the download, or when a request completes successfully. Note "successfully"; it's not called when a requests receives an error. A request that errors will be retried after some delay. So in that sense it's still "active" and consuming resources, notably the request object, its timer, and network resources when the timer fires. We could try to squeeze in subsequent requests while we wait for the errored request to retry. But that risks overloading the upstream request queue -- defeating our own metering -- if there are a lot of errored requests that all come up for retry at the same time. And many times, the cause of a request error will apply to many requests of the same type. For instance if a server is unreachable, all the requests to that host are going to error. In that case, continuing to try subsequent resources after the first few errors is fruitless anyway. */ void OfflineDownload::continueDownload() { if (resourcesRemaining.empty() && status.complete()) { setState(OfflineRegionDownloadState::Inactive); return; } while (!resourcesRemaining.empty() && requests.size() < HTTPFileSource::maximumConcurrentRequests()) { ensureResource(resourcesRemaining.front()); resourcesRemaining.pop_front(); } } void OfflineDownload::deactivateDownload() { requiredSourceURLs.clear(); resourcesRemaining.clear(); requests.clear(); } void OfflineDownload::queueResource(Resource resource) { status.requiredResourceCount++; resourcesRemaining.push_front(std::move(resource)); } void OfflineDownload::queueTiles(SourceType type, uint16_t tileSize, const Tileset& tileset) { for (const auto& tile : definition.tileCover(type, tileSize, tileset.zoomRange)) { status.requiredResourceCount++; resourcesRemaining.push_back( Resource::tile(tileset.tiles[0], definition.pixelRatio, tile.x, tile.y, tile.z, tileset.scheme)); } } void OfflineDownload::ensureResource(const Resource& resource, std::function<void(Response)> callback) { auto workRequestsIt = requests.insert(requests.begin(), nullptr); *workRequestsIt = util::RunLoop::Get()->invokeCancellable([=]() { requests.erase(workRequestsIt); auto getResourceSizeInDatabase = [&] () -> optional<int64_t> { if (!callback) { return offlineDatabase.hasRegionResource(id, resource); } optional<std::pair<Response, uint64_t>> response = offlineDatabase.getRegionResource(id, resource); if (!response) { return {}; } callback(response->first); return response->second; }; optional<int64_t> offlineResponse = getResourceSizeInDatabase(); if (offlineResponse) { status.completedResourceCount++; status.completedResourceSize += *offlineResponse; if (resource.kind == Resource::Kind::Tile) { status.completedTileCount += 1; status.completedTileSize += *offlineResponse; } observer->statusChanged(status); continueDownload(); return; } if (checkTileCountLimit(resource)) { return; } auto fileRequestsIt = requests.insert(requests.begin(), nullptr); *fileRequestsIt = onlineFileSource.request(resource, [=](Response onlineResponse) { if (onlineResponse.error) { observer->responseError(*onlineResponse.error); return; } requests.erase(fileRequestsIt); if (callback) { callback(onlineResponse); } status.completedResourceCount++; uint64_t resourceSize = offlineDatabase.putRegionResource(id, resource, onlineResponse); status.completedResourceSize += resourceSize; if (resource.kind == Resource::Kind::Tile) { status.completedTileCount += 1; status.completedTileSize += resourceSize; } observer->statusChanged(status); if (checkTileCountLimit(resource)) { return; } continueDownload(); }); }); } bool OfflineDownload::checkTileCountLimit(const Resource& resource) { if (resource.kind == Resource::Kind::Tile && util::mapbox::isMapboxURL(resource.url) && offlineDatabase.offlineMapboxTileCountLimitExceeded()) { observer->mapboxTileCountLimitExceeded(offlineDatabase.getOfflineMapboxTileCountLimit()); setState(OfflineRegionDownloadState::Inactive); return true; } return false; } } // namespace mbgl
36.387879
123
0.617505
[ "object", "vector" ]
c8aab647b0e96b9c76cd61f880288c42ecba7f85
6,624
cpp
C++
inc/log/log.cpp
Kerisa/EzvizLocalProcess
77c72413bbdb862c221af042967d99d44e82fe9f
[ "MIT" ]
null
null
null
inc/log/log.cpp
Kerisa/EzvizLocalProcess
77c72413bbdb862c221af042967d99d44e82fe9f
[ "MIT" ]
null
null
null
inc/log/log.cpp
Kerisa/EzvizLocalProcess
77c72413bbdb862c221af042967d99d44e82fe9f
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <chrono> #include <iomanip> #include <map> #include <sstream> using namespace std; #include "Log.h" #include <windows.h> namespace { int gLevel = LOG::debug; } class Log { public: static Log *instance() { static Log inst; return &inst; } void init(const char *file_name, int max_file_num, int max_file_size) { if (file_name) m_file_name = file_name; m_max_file_num = max_file_num; m_max_file_size = max_file_size; } int get_file_size(const string &file_path) { ifstream file(file_path.data()); if (!file.is_open()) { return 0; } file.seekg(0, ios::end); int size = (int)file.tellg(); file.close(); return size; } string make_file_path(int index) { char path_str[256] = { 0 }; snprintf(path_str, 256, "%s%s.%d.log", m_file_dir.data(), m_file_name.data(), index); return path_str; } string next_file_path() { string path = make_file_path(m_file_index); m_file_index++; if (m_file_index == m_max_file_num) { m_file_index = 0; } return path; } void write_log2(int level, const char *log_str) { string file_path; std::ios_base::openmode open_mode = ios::app; if (m_file_paths.empty()) { file_path = next_file_path(); m_file_paths.push_back(file_path); } else { file_path = m_file_paths.back(); int size = get_file_size(file_path); if (size > m_max_file_size) { if (m_file_paths.size() >= (size_t)m_max_file_num) { auto first = m_file_paths.begin(); if (DeleteFileA(first->c_str())) { m_file_paths.erase(first); } } file_path = next_file_path(); open_mode = ios::trunc; m_file_paths.push_back(file_path); } } ofstream file(file_path.data(), open_mode); if (!file.is_open()) { return; } file << log_str << endl; file.close(); } private: Log() { m_max_file_num = 16; m_max_file_size = 10 * 1024 * 1024; m_file_index = 0; char pszModuleName[512]; memset(pszModuleName, 0, 512); HMODULE hModule = NULL; GetModuleHandleExA( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR)&Log::instance, &hModule); if (hModule) GetModuleFileNameA(hModule, pszModuleName, sizeof(pszModuleName)); std::string strFolder = pszModuleName; int nPos = strFolder.find_last_of('\\'); m_file_name = strFolder.substr(nPos + 1); strFolder.erase(strFolder.begin() + nPos, strFolder.end()); m_file_dir = strFolder + "\\log\\"; CreateDirectoryA(m_file_dir.data(), NULL); for (int index = 0; index<m_max_file_num; index++) { string file_path = make_file_path(index); int size = get_file_size(file_path); if (size<m_max_file_size) { m_file_index = index; break; } } } virtual ~Log() { } int m_max_file_num; int m_max_file_size; string m_file_name; string m_file_dir; int m_file_index; vector<string> m_file_paths; }; void LOG::init(const char *file_name/*=nullptr*/, int max_file_num/*=16*/, int max_file_size/*=10240*/) { Log::instance()->init(file_name, max_file_num, max_file_size); } void LOG::WriteLogToFile(int level, const char *prefix, const char *fmt, ...) { va_list valst; va_start(valst, fmt); WriteLogToFile(level, prefix, fmt, valst); va_end(valst); } void LOG::WriteLogToFile(int level, const char *prefix, const char *fmt, va_list valst) { if (level < gLevel) return; char buf[4096] = { 0 }; vsnprintf(buf, 4096, fmt, valst); std::string msg(prefix); msg += buf; Log::instance()->write_log2(level, msg.c_str()); } void LOG::WriteLogToDebug(int level, const char *prefix, const char *fmt, ...) { va_list valst; va_start(valst, fmt); WriteLogToDebug(level, prefix, fmt, valst); va_end(valst); } void LOG::WriteLogToDebug(int level, const char *prefix, const char *fmt, va_list valst) { char buf[2048] = { 0 }; vsnprintf(buf, 2048, fmt, valst); std::string msg(prefix); msg += buf; strcat_s(buf, sizeof(buf), "\n"); OutputDebugStringA(buf); } #define LOG_TYPE_FILE //#define LOG_TYPE_MEMORY void LOG::WriteLog(int level, const char *prefix, const char *fmt, ...) { #if !defined LOG_TYPE_FILE #if !defined LOG_TYPE_MEMORY return; #endif #endif va_list valst; va_start(valst, fmt); #ifdef LOG_TYPE_FILE WriteLogToFile(level, prefix, fmt, valst); #elif defined LOG_TYPE_MEMORY WriteLogToDebug(level, prefix, fmt, valst); #endif va_end(valst); } std::string LOG::GetTimeOfDay() { std::ostringstream oss; auto now = std::chrono::system_clock::now(); auto t = std::chrono::system_clock::to_time_t(now); auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000; tm fmt; localtime_s(&fmt, &t); oss << std::put_time(&fmt, "%Y/%m/%d %H:%M:%S"); oss << '.' << std::setfill('0') << std::setw(3) << ms.count(); return oss.str(); } const char * LOG::GetLevelMark(int level) { switch (level) { case 0: return "D"; // debug case 2: return "W"; // warning case 3: return "E"; // error case 1: default: return "I"; // info } } uint32_t LOG::GetPid() { return GetCurrentProcessId(); } uint32_t LOG::GetTid() { return GetCurrentThreadId(); } std::string LOG::SpliteFileName(const char * p) { std::string s(p); return s.substr(s.rfind('\\') + 1); } void LOG::SetLogLevel(int L) { gLevel = (L < LOG::debug ? LOG::debug : (L > LOG::error ? LOG::error : L)); }
23.160839
104
0.547554
[ "vector" ]
c8ac1e482dec04a9e70bb584c6b375e5e285658b
43,293
hpp
C++
library/src/blas2/rocblas_trsv.hpp
mohanmithur/rocBLAS
2704b9a9899d5e2291b1e632627b3a8bc1ac4894
[ "MIT" ]
null
null
null
library/src/blas2/rocblas_trsv.hpp
mohanmithur/rocBLAS
2704b9a9899d5e2291b1e632627b3a8bc1ac4894
[ "MIT" ]
null
null
null
library/src/blas2/rocblas_trsv.hpp
mohanmithur/rocBLAS
2704b9a9899d5e2291b1e632627b3a8bc1ac4894
[ "MIT" ]
null
null
null
/* ************************************************************************ * Copyright 2016-2020 Advanced Micro Devices, Inc. * ************************************************************************ */ #include "../blas3/trtri_trsm.hpp" #include "handle.h" #include "logging.h" #include "rocblas.h" #include "rocblas_gemv.hpp" #include "utility.h" #include <algorithm> #include <cstdio> #include <tuple> namespace { using std::max; using std::min; template <typename T> const T negative_one = T(-1); template <typename T> const T zero = T(0); template <typename T> const T one = T(1); template <typename T, typename U> __global__ void flip_vector_kernel(U* __restrict__ data, rocblas_int m, rocblas_int size, rocblas_int abs_incx, rocblas_int offset, rocblas_stride stride) { rocblas_int tx = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(tx < size) { T* pdata = load_ptr_batch(data, hipBlockIdx_y, offset, stride); rocblas_int end = (m - 1 - tx) * abs_incx; rocblas_int start = tx * abs_incx; T temp = pdata[end]; pdata[end] = pdata[start]; pdata[start] = temp; } } template <rocblas_int NB_X, typename T, typename U> void flip_vector(rocblas_handle handle, U* data, rocblas_int m, rocblas_int abs_incx, rocblas_stride stride, rocblas_int batch_count, rocblas_int offset = 0) { rocblas_int size = (m + 1) / 2; rocblas_int blocksX = (size - 1) / NB_X + 1; dim3 grid(blocksX, batch_count, 1); dim3 threads(NB_X, 1, 1); hipLaunchKernelGGL(flip_vector_kernel<T>, grid, threads, 0, handle->rocblas_stream, data, m, size, abs_incx, offset, stride); } template <typename T, typename U, typename V> __global__ void strided_vector_copy_kernel(U __restrict__ dst, rocblas_int dst_incx, rocblas_stride dst_stride, V __restrict__ src, rocblas_int src_incx, rocblas_stride src_stride, rocblas_int size, rocblas_int offset_dst = 0, rocblas_int offset_src = 0) { ptrdiff_t tx = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x; if(tx < size) { const T* __restrict__ xsrc = load_ptr_batch(src, hipBlockIdx_y, offset_src, src_stride); T* __restrict__ xdst = load_ptr_batch(dst, hipBlockIdx_y, offset_dst, dst_stride); xdst[tx * dst_incx] = xsrc[tx * src_incx]; } } template <rocblas_int NB_X, typename T, typename U, typename V> void strided_vector_copy(rocblas_handle handle, U dst, rocblas_int dst_incx, rocblas_stride dst_stride, V src, rocblas_int src_incx, rocblas_stride src_stride, rocblas_int size, rocblas_int batch_count, rocblas_int offset_dst = 0, rocblas_int offset_src = 0) { rocblas_int blocksX = (size - 1) / NB_X + 1; dim3 grid(blocksX, batch_count, 1); dim3 threads(NB_X, 1, 1); hipLaunchKernelGGL(strided_vector_copy_kernel<T>, grid, threads, 0, handle->rocblas_stream, dst, dst_incx, dst_stride, src, src_incx, src_stride, size, offset_dst, offset_src); } template <rocblas_int BLOCK, typename T, typename U, typename V> rocblas_status rocblas_trsv_left(rocblas_handle handle, rocblas_fill uplo, rocblas_operation transA, rocblas_int m, U A, rocblas_int offset_Ain, rocblas_int lda, rocblas_stride stride_A, V B, rocblas_int offset_Bin, rocblas_int incx, rocblas_int stride_B, U invA, rocblas_int offset_invAin, rocblas_stride stride_invA, V X, rocblas_stride stride_X, rocblas_int batch_count) { rocblas_int i, jb; if(transA == rocblas_operation_none) { if(uplo == rocblas_fill_lower) { // left, lower no-transpose jb = min(BLOCK, m); rocblas_gemv_template<T>(handle, transA, jb, jb, &one<T>, 0, invA, offset_invAin, BLOCK, stride_invA, (U)B, offset_Bin, incx, stride_B, &zero<T>, 0, X, 0, 1, stride_X, batch_count); if(BLOCK < m) { rocblas_gemv_template<T>(handle, transA, m - BLOCK, BLOCK, &negative_one<T>, 0, A, offset_Ain + BLOCK, lda, stride_A, (U)X, 0, 1, stride_X, &one<T>, 0, B, offset_Bin + BLOCK * incx, incx, stride_B, batch_count); // remaining blocks for(i = BLOCK; i < m; i += BLOCK) { jb = min(m - i, BLOCK); rocblas_gemv_template<T>(handle, transA, jb, jb, &one<T>, 0, invA, offset_invAin + i * BLOCK, BLOCK, stride_invA, (U)B, offset_Bin + i * incx, incx, stride_B, &zero<T>, 0, X, i, 1, stride_X, batch_count); if(i + BLOCK < m) rocblas_gemv_template<T>(handle, transA, m - i - BLOCK, BLOCK, &negative_one<T>, 0, A, offset_Ain + i + BLOCK + i * lda, lda, stride_A, (U)X, i, 1, stride_X, &one<T>, 0, B, offset_Bin + (i + BLOCK) * incx, incx, stride_B, batch_count); } } } else { // left, upper no-transpose jb = m % BLOCK == 0 ? BLOCK : m % BLOCK; i = m - jb; // if m=n=35=lda=ldb, BLOCK =32, then jb = 3, i = 32; {3, 35, 3, 32, 35, 35} rocblas_gemv_template<T>(handle, transA, jb, jb, &one<T>, 0, invA, offset_invAin + i * BLOCK, BLOCK, stride_invA, (U)B, offset_Bin + i * incx, incx, stride_B, &zero<T>, 0, X, i, 1, stride_X, batch_count); if(i >= BLOCK) { rocblas_gemv_template<T>(handle, transA, i, jb, &negative_one<T>, 0, A, offset_Ain + i * lda, lda, stride_A, (U)X, i, 1, stride_X, &one<T>, 0, B, offset_Bin, incx, stride_B, batch_count); // remaining blocks for(i = m - jb - BLOCK; i >= 0; i -= BLOCK) { //{32, 35, 32, 32, 35, 35} rocblas_gemv_template<T>(handle, transA, BLOCK, BLOCK, &one<T>, 0, invA, offset_invAin + i * BLOCK, BLOCK, stride_invA, (U)B, offset_Bin + i * incx, incx, stride_B, &zero<T>, 0, X, i, 1, stride_X, batch_count); if(i >= BLOCK) rocblas_gemv_template<T>(handle, transA, i, BLOCK, &negative_one<T>, 0, A, offset_Ain + i * lda, lda, stride_A, (U)X, i, 1, stride_X, &one<T>, 0, B, offset_Bin, incx, stride_B, batch_count); } } } } else { // transA == rocblas_operation_transpose || transA == rocblas_operation_conjugate_transpose if(uplo == rocblas_fill_lower) { // left, lower transpose jb = m % BLOCK == 0 ? BLOCK : m % BLOCK; i = m - jb; rocblas_gemv_template<T>(handle, transA, jb, jb, &one<T>, 0, invA, offset_invAin + i * BLOCK, BLOCK, stride_invA, (U)B, offset_Bin + i * incx, incx, stride_B, &zero<T>, 0, X, i, 1, stride_X, batch_count); if(i - BLOCK >= 0) { rocblas_gemv_template<T>(handle, transA, jb, i, &negative_one<T>, 0, A, offset_Ain + i, lda, stride_A, (U)X, i, 1, stride_X, &one<T>, 0, B, offset_Bin, incx, stride_B, batch_count); // remaining blocks for(i = m - jb - BLOCK; i >= 0; i -= BLOCK) { rocblas_gemv_template<T>(handle, transA, BLOCK, BLOCK, &one<T>, 0, invA, offset_invAin + i * BLOCK, BLOCK, stride_invA, (U)B, offset_Bin + i * incx, incx, stride_B, &zero<T>, 0, X, i, 1, stride_X, batch_count); if(i >= BLOCK) rocblas_gemv_template<T>(handle, transA, BLOCK, i, &negative_one<T>, 0, A, offset_Ain + i, lda, stride_A, (U)X, i, 1, stride_X, &one<T>, 0, B, offset_Bin, incx, stride_B, batch_count); } } } else { // left, upper transpose jb = min(BLOCK, m); rocblas_gemv_template<T>(handle, transA, jb, jb, &one<T>, 0, invA, offset_invAin, BLOCK, stride_invA, (U)B, offset_Bin, incx, stride_B, &zero<T>, 0, X, 0, 1, stride_X, batch_count); if(BLOCK < m) { rocblas_gemv_template<T>(handle, transA, BLOCK, m - BLOCK, &negative_one<T>, 0, A, offset_Ain + BLOCK * lda, lda, stride_A, (U)X, 0, 1, stride_X, &one<T>, 0, B, offset_Bin + BLOCK * incx, incx, stride_B, batch_count); // remaining blocks for(i = BLOCK; i < m; i += BLOCK) { jb = min(m - i, BLOCK); rocblas_gemv_template<T>(handle, transA, jb, jb, &one<T>, 0, invA, offset_invAin + i * BLOCK, BLOCK, stride_invA, (U)B, offset_Bin + i * incx, incx, stride_B, &zero<T>, 0, X, i, 1, stride_X, batch_count); if(i + BLOCK < m) rocblas_gemv_template<T>(handle, transA, BLOCK, m - i - BLOCK, &negative_one<T>, 0, A, offset_Ain + i + (i + BLOCK) * lda, lda, stride_A, (U)X, i, 1, stride_X, &one<T>, 0, B, offset_Bin + (i + BLOCK) * incx, incx, stride_B, batch_count); } } } } // transpose return rocblas_status_success; } template <rocblas_int BLOCK, typename T, typename U, typename V> rocblas_status special_trsv_template(rocblas_handle handle, rocblas_fill uplo, rocblas_operation transA, rocblas_diagonal diag, rocblas_int m, U A, rocblas_int offset_Ain, rocblas_int lda, rocblas_stride stride_A, V B, rocblas_int offset_Bin, rocblas_int incx, rocblas_stride stride_B, U invA, rocblas_int offset_invAin, rocblas_stride stride_invA, V x_temp, rocblas_stride stride_X, rocblas_int batch_count) { bool parity = (transA == rocblas_operation_none) ^ (uplo == rocblas_fill_lower); size_t R = m / BLOCK; for(size_t r = 0; r < R; r++) { size_t q = R - r; size_t j = parity ? q - 1 : r; // copy a BLOCK*n piece we are solving at a time strided_vector_copy<BLOCK, T>(handle, x_temp, 1, stride_X, B, incx, stride_B, BLOCK, batch_count, 0, offset_Bin + incx * j * BLOCK); if(r) { rocblas_int M = BLOCK; rocblas_int N = BLOCK; rocblas_int offsetA = 0; rocblas_int offsetB = parity ? q * BLOCK * incx : 0; if(transA == rocblas_operation_none) { N *= r; offsetA = parity ? BLOCK * ((lda + 1) * q - 1) : N; } else { M *= r; offsetA = parity ? BLOCK * ((lda + 1) * q - lda) : M * lda; } rocblas_gemv_template<T>(handle, transA, M, N, &negative_one<T>, 0, A, offset_Ain + offsetA, lda, stride_A, (U)B, offset_Bin + offsetB, incx, stride_B, &one<T>, 0, x_temp, 0, 1, stride_X, batch_count); } rocblas_gemv_template<T>(handle, transA, BLOCK, BLOCK, &one<T>, 0, invA, j * BLOCK * BLOCK, BLOCK, stride_invA, (U)x_temp, 0, 1, stride_X, &zero<T>, 0, B, j * BLOCK * incx, incx, stride_B, batch_count); } return rocblas_status_success; } template <rocblas_int BLOCK, bool BATCHED, typename T, typename U> rocblas_status rocblas_trsv_template_mem(rocblas_handle handle, rocblas_int m, rocblas_int batch_count, void** mem_x_temp, void** mem_x_temp_arr, void** mem_invA, void** mem_invA_arr, U supplied_invA = nullptr, rocblas_int supplied_invA_size = 0) { // Whether size is an exact multiple of blocksize const bool exact_blocks = (m % BLOCK) == 0; // perf_status indicates whether optimal performance is obtainable with available memory rocblas_status perf_status = rocblas_status_success; size_t invA_bytes = 0; size_t c_temp_bytes = 0; // For user-supplied invA, check to make sure size is large enough // If not large enough, indicate degraded performance and ignore supplied invA if(supplied_invA && supplied_invA_size / BLOCK < m) { static int msg = fputs("WARNING: TRSV invA_size argument is too small; invA argument " "is being ignored; TRSV performance is degraded\n", stderr); perf_status = rocblas_status_perf_degraded; supplied_invA = nullptr; } if(!supplied_invA) { // Only allocate bytes for invA if supplied_invA == nullptr or supplied_invA_size is too small invA_bytes = sizeof(T) * BLOCK * m * batch_count; // When m < BLOCK, C is unnecessary for trtri c_temp_bytes = (m / BLOCK) * (sizeof(T) * (BLOCK / 2) * (BLOCK / 2)) * batch_count; // For the TRTRI last diagonal block we need remainder space if m % BLOCK != 0 if(!exact_blocks) { // TODO: Make this more accurate -- right now it's much larger than necessary size_t remainder_bytes = sizeof(T) * ROCBLAS_TRTRI_NB * BLOCK * 2 * batch_count; // C is the maximum of the temporary space needed for TRTRI c_temp_bytes = max(c_temp_bytes, remainder_bytes); } } // Temporary solution vector // If the special solver can be used, then only BLOCK words are needed instead of m words size_t x_temp_bytes = exact_blocks ? sizeof(T) * BLOCK * batch_count : sizeof(T) * m * batch_count; // X and C temporaries can share space, so the maximum size is allocated size_t x_c_temp_bytes = max(x_temp_bytes, c_temp_bytes); size_t arrBytes = BATCHED ? sizeof(T*) * batch_count : 0; size_t xarrBytes = BATCHED ? sizeof(T*) * batch_count : 0; // If this is a device memory size query, set optimal size and return changed status if(handle->is_device_memory_size_query()) return handle->set_optimal_device_memory_size(x_c_temp_bytes, invA_bytes); // Attempt to allocate optimal memory size, returning error if failure auto mem = handle->device_malloc(x_c_temp_bytes, xarrBytes, invA_bytes, arrBytes); if(!mem) return rocblas_status_memory_error; // Get pointers to allocated device memory // Note: Order of pointers in std::tie(...) must match order of sizes in handle->device_malloc(...) std::tie(*mem_x_temp, *mem_x_temp_arr, *mem_invA, *mem_invA_arr) = mem; return perf_status; } template <rocblas_int BLOCK, bool BATCHED, typename T, typename U, typename V> rocblas_status rocblas_trsv_template(rocblas_handle handle, rocblas_fill uplo, rocblas_operation transA, rocblas_diagonal diag, rocblas_int m, U A, rocblas_int offset_A, rocblas_int lda, rocblas_stride stride_A, V B, rocblas_int offset_B, rocblas_int incx, rocblas_stride stride_B, rocblas_int batch_count, void* x_temp, void* x_temparr, void* invA = nullptr, void* invAarr = nullptr, U supplied_invA = nullptr, rocblas_int supplied_invA_size = 0, rocblas_int offset_invA = 0, rocblas_stride stride_invA = 0) { if(batch_count == 0) return rocblas_status_success; rocblas_status status = rocblas_status_success; const bool exact_blocks = (m % BLOCK) == 0; size_t x_temp_els = exact_blocks ? BLOCK : m; // Temporarily switch to host pointer mode, restoring on return auto saved_pointer_mode = handle->push_pointer_mode(rocblas_pointer_mode_host); if(supplied_invA) invA = (U*)(supplied_invA); else { // batched trtri invert diagonal part (BLOCK*BLOCK) of A into invA auto c_temp = x_temp; // Uses same memory as x_temp stride_invA = BLOCK * m; if(BATCHED) { setup_batched_array<BLOCK>( handle->rocblas_stream, (T*)c_temp, 0, (T**)x_temparr, batch_count); setup_batched_array<BLOCK>( handle->rocblas_stream, (T*)invA, stride_invA, (T**)invAarr, batch_count); } status = rocblas_trtri_trsm_template<BLOCK, BATCHED, T>(handle, (V)(BATCHED ? x_temparr : c_temp), uplo, diag, m, A, offset_A, lda, stride_A, (V)(BATCHED ? invAarr : invA), offset_invA, stride_invA, batch_count); if(status != rocblas_status_success) return status; } // TODO: workaround to fix negative incx issue rocblas_int abs_incx = incx < 0 ? -incx : incx; if(incx < 0) flip_vector<BLOCK, T>(handle, B, m, abs_incx, stride_B, batch_count, offset_B); if(BATCHED) { setup_batched_array<BLOCK>( handle->rocblas_stream, (T*)x_temp, x_temp_els, (T**)x_temparr, batch_count); } if(exact_blocks) { status = special_trsv_template<BLOCK, T>(handle, uplo, transA, diag, m, A, offset_A, lda, stride_A, B, offset_B, abs_incx, stride_B, (U)(BATCHED ? invAarr : invA), offset_invA, stride_invA, (V)(BATCHED ? x_temparr : x_temp), x_temp_els, batch_count); if(status != rocblas_status_success) return status; // TODO: workaround to fix negative incx issue if(incx < 0) flip_vector<BLOCK, T>(handle, B, m, abs_incx, stride_B, batch_count, offset_B); } else { status = rocblas_trsv_left<BLOCK, T>(handle, uplo, transA, m, A, offset_A, lda, stride_A, B, offset_B, abs_incx, stride_B, (U)(BATCHED ? invAarr : invA), offset_invA, stride_invA, (V)(BATCHED ? x_temparr : x_temp), x_temp_els, batch_count); if(status != rocblas_status_success) return status; // copy solution X into B // TODO: workaround to fix negative incx issue strided_vector_copy<BLOCK, T>(handle, B, abs_incx, stride_B, (V)(BATCHED ? x_temparr : x_temp), incx < 0 ? -1 : 1, x_temp_els, m, batch_count, offset_B, incx < 0 ? m - 1 : 0); } return status; } } // namespace
47.837569
107
0.247846
[ "vector" ]
c8b0fb1678ef425d8bcaa0772f50d6752776ac36
3,729
hpp
C++
src/cxa_exception.hpp
zhmu/ananas-libcxxabi
b32ae4aa681a73f77527257cb185f501a0049a66
[ "MIT" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
src/cxa_exception.hpp
zhmu/ananas-libcxxabi
b32ae4aa681a73f77527257cb185f501a0049a66
[ "MIT" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
src/cxa_exception.hpp
zhmu/ananas-libcxxabi
b32ae4aa681a73f77527257cb185f501a0049a66
[ "MIT" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
//===------------------------- cxa_exception.hpp --------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // // // This file implements the "Exception Handling APIs" // http://mentorembedded.github.io/cxx-abi/abi-eh.html // //===----------------------------------------------------------------------===// #ifndef _CXA_EXCEPTION_H #define _CXA_EXCEPTION_H #include <exception> // for std::unexpected_handler and std::terminate_handler #include "cxxabi.h" #include "unwind.h" namespace __cxxabiv1 { static const uint64_t kOurExceptionClass = 0x434C4E47432B2B00; // CLNGC++\0 static const uint64_t kOurDependentExceptionClass = 0x434C4E47432B2B01; // CLNGC++\1 static const uint64_t get_vendor_and_language = 0xFFFFFFFFFFFFFF00; // mask for CLNGC++ struct _LIBCXXABI_HIDDEN __cxa_exception { #if defined(__LP64__) || defined(_LIBCXXABI_ARM_EHABI) // This is a new field to support C++ 0x exception_ptr. // For binary compatibility it is at the start of this // struct which is prepended to the object thrown in // __cxa_allocate_exception. size_t referenceCount; #endif // Manage the exception object itself. std::type_info *exceptionType; void (*exceptionDestructor)(void *); std::unexpected_handler unexpectedHandler; std::terminate_handler terminateHandler; __cxa_exception *nextException; int handlerCount; #if defined(_LIBCXXABI_ARM_EHABI) __cxa_exception* nextPropagatingException; int propagationCount; #else int handlerSwitchValue; const unsigned char *actionRecord; const unsigned char *languageSpecificData; void *catchTemp; void *adjustedPtr; #endif #if !defined(__LP64__) && !defined(_LIBCXXABI_ARM_EHABI) // This is a new field to support C++ 0x exception_ptr. // For binary compatibility it is placed where the compiler // previously adding padded to 64-bit align unwindHeader. size_t referenceCount; #endif _Unwind_Exception unwindHeader; }; // http://sourcery.mentor.com/archives/cxx-abi-dev/msg01924.html // The layout of this structure MUST match the layout of __cxa_exception, with // primaryException instead of referenceCount. struct _LIBCXXABI_HIDDEN __cxa_dependent_exception { #if defined(__LP64__) || defined(_LIBCXXABI_ARM_EHABI) void* primaryException; #endif std::type_info *exceptionType; void (*exceptionDestructor)(void *); std::unexpected_handler unexpectedHandler; std::terminate_handler terminateHandler; __cxa_exception *nextException; int handlerCount; #if defined(_LIBCXXABI_ARM_EHABI) __cxa_exception* nextPropagatingException; int propagationCount; #else int handlerSwitchValue; const unsigned char *actionRecord; const unsigned char *languageSpecificData; void * catchTemp; void *adjustedPtr; #endif #if !defined(__LP64__) && !defined(_LIBCXXABI_ARM_EHABI) void* primaryException; #endif _Unwind_Exception unwindHeader; }; struct _LIBCXXABI_HIDDEN __cxa_eh_globals { __cxa_exception * caughtExceptions; unsigned int uncaughtExceptions; #if defined(_LIBCXXABI_ARM_EHABI) __cxa_exception* propagatingExceptions; #endif }; extern "C" _LIBCXXABI_FUNC_VIS __cxa_eh_globals * __cxa_get_globals (); extern "C" _LIBCXXABI_FUNC_VIS __cxa_eh_globals * __cxa_get_globals_fast (); extern "C" _LIBCXXABI_FUNC_VIS void * __cxa_allocate_dependent_exception (); extern "C" _LIBCXXABI_FUNC_VIS void __cxa_free_dependent_exception (void * dependent_exception); } // namespace __cxxabiv1 #endif // _CXA_EXCEPTION_H
31.871795
96
0.725932
[ "object" ]
c8b17bf1806f1b5e60426b3e31ef85900d8ad635
40,234
cpp
C++
src/hsp3dish/geometry.cpp
cielavenir/OpenHSP
eddc647733e82657757055b66fd8c2dbf17898b8
[ "BSD-3-Clause" ]
127
2018-02-24T20:41:15.000Z
2022-03-22T05:57:56.000Z
src/hsp3dish/geometry.cpp
cielavenir/OpenHSP
eddc647733e82657757055b66fd8c2dbf17898b8
[ "BSD-3-Clause" ]
21
2018-09-11T15:04:22.000Z
2022-02-03T09:30:16.000Z
src/hsp3dish/geometry.cpp
cielavenir/OpenHSP
eddc647733e82657757055b66fd8c2dbf17898b8
[ "BSD-3-Clause" ]
21
2019-03-28T07:49:44.000Z
2021-12-25T02:49:07.000Z
//--------------------------------------------------------------------------- #include <stdio.h> #include <math.h> #include "geometry.h" #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif static MATRIX matrixBuf[128]; static MATRIX *currentMatrix; static int rightHand; //--------------------------------------------------------------------------- // コンストラクタ //--------------------------------------------------------------------------- void GeometryInit(void) { InitMatrix(); //RightHand(); LeftHand(); } //--------------------------------------------------------------------------- // デストラクタ //--------------------------------------------------------------------------- void GeometryTerm(void) { } /*----------------------------------------------- ベクトルのコピー -----------------------------------------------*/ void ICopyVector( VECTOR *dst, VECTOR *src ) { *dst = *src; } /*----------------------------------------------- ベクトルの代入 -----------------------------------------------*/ void ISetVector( VECTOR *dst, float x, float y, float z, float w ) { dst->x = x; dst->y = y; dst->z = z; dst->w = w; } /*----------------------------------------------- ベクトルの加算 -----------------------------------------------*/ void AddVector( VECTOR *dst, VECTOR *v0, VECTOR *v1 ) { dst->x = v0->x + v1->x; dst->y = v0->y + v1->y; dst->z = v0->z + v1->z; dst->w = v0->w + v1->w; } /*----------------------------------------------- ベクトルの減算 -----------------------------------------------*/ void SubVector( VECTOR *dst, VECTOR *v0, VECTOR *v1 ) { dst->x = v0->x - v1->x; dst->y = v0->y - v1->y; dst->z = v0->z - v1->z; dst->w = v0->w - v1->w; } /*----------------------------------------------- ベクトルの乗算 -----------------------------------------------*/ void MulVector( VECTOR *dst, VECTOR *v0, VECTOR *v1 ) { dst->x = v0->x * v1->x; dst->y = v0->y * v1->y; dst->z = v0->z * v1->z; dst->w = v0->w * v1->w; } /*----------------------------------------------- ベクトルの乗算 -----------------------------------------------*/ void ScaleVector( VECTOR *dst, VECTOR *v0, float r ) { dst->x = v0->x * r; dst->y = v0->y * r; dst->z = v0->z * r; dst->w = v0->w * r; } /*----------------------------------------------- ベクトルの除算 -----------------------------------------------*/ void DivVector( VECTOR *dst, VECTOR *v0, float r ) { float a; a = 1.0f / r; dst->x = v0->x * a; dst->y = v0->y * a; dst->z = v0->z * a; dst->w = v0->w * a; } /*----------------------------------------------- マトリックス初期化 -----------------------------------------------*/ void InitMatrix(void) { currentMatrix = &matrixBuf[0]; UnitMatrix(); } /*----------------------------------------------- 左手系にする -----------------------------------------------*/ void LeftHand(void) { rightHand = 0; } /*----------------------------------------------- 右手系にする -----------------------------------------------*/ void RightHand(void) { rightHand = 1; } /*----------------------------------------------- マトリックスのコピー -----------------------------------------------*/ void CopyMatrix( MATRIX *dst, MATRIX *src ) { dst->m00 = src->m00; dst->m01 = src->m01; dst->m02 = src->m02; dst->m03 = src->m03; dst->m10 = src->m10; dst->m11 = src->m11; dst->m12 = src->m12; dst->m13 = src->m13; dst->m20 = src->m20; dst->m21 = src->m21; dst->m22 = src->m22; dst->m23 = src->m23; dst->m30 = src->m30; dst->m31 = src->m31; dst->m32 = src->m32; dst->m33 = src->m33; } static inline void CopyMatrixInt( MATRIX *src, MATRIX *dst ) { // Matrix copy ( for internal ) // dst->m00 = src->m00; dst->m01 = src->m01; dst->m02 = src->m02; dst->m03 = src->m03; dst->m10 = src->m10; dst->m11 = src->m11; dst->m12 = src->m12; dst->m13 = src->m13; dst->m20 = src->m20; dst->m21 = src->m21; dst->m22 = src->m22; dst->m23 = src->m23; dst->m30 = src->m30; dst->m31 = src->m31; dst->m32 = src->m32; dst->m33 = src->m33; } /*----------------------------------------------- マトリックス退避 -----------------------------------------------*/ void PushMatrix(void) { /* MATRIX STACK */ CopyMatrixInt(currentMatrix, currentMatrix + 1); currentMatrix++; } /*----------------------------------------------- マトリックス復帰 -----------------------------------------------*/ void PopMatrix(void) { /* MATRIX STACK */ currentMatrix--; } /*----------------------------------------------- カレントマトリックス取得 -----------------------------------------------*/ void GetCurrentMatrix(MATRIX *dst) { CopyMatrixInt(currentMatrix, dst); } /*----------------------------------------------- カレントマトリックス取得 -----------------------------------------------*/ MATRIX *GetCurrentMatrixPtr( void ) { return currentMatrix; } /*----------------------------------------------- カレントマトリックス設定 -----------------------------------------------*/ void SetCurrentMatrix(MATRIX *src) { CopyMatrixInt(src, currentMatrix); } /*----------------------------------------------- 単位マトリックス -----------------------------------------------*/ void UnitMatrix(void) { MATRIX *mat = currentMatrix; mat->m00 = 1.0f; mat->m01 = 0.0f; mat->m02 = 0.0f; mat->m03 = 0.0f; mat->m10 = 0.0f; mat->m11 = 1.0f; mat->m12 = 0.0f; mat->m13 = 0.0f; mat->m20 = 0.0f; mat->m21 = 0.0f; mat->m22 = 1.0f; mat->m23 = 0.0f; mat->m30 = 0.0f; mat->m31 = 0.0f; mat->m32 = 0.0f; mat->m33 = 1.0f; } /*----------------------------------------------- X軸回転(左手系) -----------------------------------------------*/ // //X axis rotation // //|M00 M01 M02 M03| |1 0 0 0||m00 m01 m02 m03| //|M10 M11 M12 M13| = |0 cosx -sinx 0||m10 m11 m12 m13| //|M20 M21 M22 M23| |0 sinx cosx 0||m20 m21 m22 m23| //|M30 M31 M32 M33| |0 0 0 1||m30 m31 m32 m33| static void RotXLeft(float x) { MATRIX *mat, mt; float s, c; mat = currentMatrix; CopyMatrixInt(mat, &mt); s = (float)sin(x); c = (float)cos(x); #if 0 mat->m00 = mt.m00; mat->m01 = mt.m01; mat->m02 = mt.m02; mat->m03 = mt.m03; #endif mat->m10 = c*mt.m10 + -s*mt.m20; mat->m11 = c*mt.m11 + -s*mt.m21; mat->m12 = c*mt.m12 + -s*mt.m22; mat->m13 = c*mt.m13 + -s*mt.m23; mat->m20 = s*mt.m10 + c*mt.m20; mat->m21 = s*mt.m11 + c*mt.m21; mat->m22 = s*mt.m12 + c*mt.m22; mat->m23 = s*mt.m13 + c*mt.m23; } /*----------------------------------------------- Y軸回転(左手系) -----------------------------------------------*/ // //Y axis rotation // //|M00 M01 M02 M03| | cosy 0 siny 0||m00 m01 m02 m03| //|M10 M11 M12 M13| = | 0 1 0 0||m10 m11 m12 m13| //|M20 M21 M22 M23| |-siny 0 cosy 0||m20 m21 m22 m23| //|M30 M31 M32 M33| | 0 0 0 1||m30 m31 m32 m33| static void RotYLeft(float y) { MATRIX *mat, mt; float s, c; mat = currentMatrix; CopyMatrixInt(mat, &mt); s = (float)sin(y); c = (float)cos(y); mat->m00 = c*mt.m00 + s*mt.m20; mat->m01 = c*mt.m01 + s*mt.m21; mat->m02 = c*mt.m02 + s*mt.m22; mat->m03 = c*mt.m03 + s*mt.m23; #if 0 mat->m10 = mt.m10; mat->m11 = mt.m11; mat->m12 = mt.m12; mat->m13 = mt.m13; #endif mat->m20 = -s*mt.m00 + c*mt.m20; mat->m21 = -s*mt.m01 + c*mt.m21; mat->m22 = -s*mt.m02 + c*mt.m22; mat->m23 = -s*mt.m03 + c*mt.m23; } /*----------------------------------------------- Z軸回転(左手系) -----------------------------------------------*/ // //Z axis rotation // //|M00 M01 M02 M03| | cosz -sinz 0 0||m00 m01 m02 m03| //|M10 M11 M12 M13| = | sinz cosz 0 0||m10 m11 m12 m13| //|M20 M21 M22 M23| | 0 0 1 0||m20 m21 m22 m23| //|M30 M31 M32 M33| | 0 0 0 1||m30 m31 m32 m33| static void RotZLeft(float z) { MATRIX *mat, mt; float s, c; mat = currentMatrix; CopyMatrixInt(mat, &mt); s = (float)sin(z); c = (float)cos(z); mat->m00 = c*mt.m00 + -s*mt.m10; mat->m01 = c*mt.m01 + -s*mt.m11; mat->m02 = c*mt.m02 + -s*mt.m12; mat->m03 = c*mt.m03 + -s*mt.m13; mat->m10 = s*mt.m00 + c*mt.m10; mat->m11 = s*mt.m01 + c*mt.m11; mat->m12 = s*mt.m02 + c*mt.m12; mat->m13 = s*mt.m03 + c*mt.m13; #if 0 mat->m20 = mt.m20; mat->m21 = mt.m21; mat->m22 = mt.m22; mat->m23 = mt.m23; #endif } /*----------------------------------------------- X軸回転(右手系) -----------------------------------------------*/ // //X axis rotation // //|M00 M01 M02 M03| |1 0 0 0||m00 m01 m02 m03| //|M10 M11 M12 M13| = |0 cosx sinx 0||m10 m11 m12 m13| //|M20 M21 M22 M23| |0 -sinx cosx 0||m20 m21 m22 m23| //|M30 M31 M32 M33| |0 0 0 1||m30 m31 m32 m33| static void RotXRight(float x) { MATRIX *mat, mt; float s, c; mat = currentMatrix; CopyMatrixInt(mat, &mt); s = (float)sin(x); c = (float)cos(x); #if 0 mat->m00 = mt.m00; mat->m01 = mt.m01; mat->m02 = mt.m02; mat->m03 = mt.m03; #endif mat->m10 = c*mt.m10 + s*mt.m20; mat->m11 = c*mt.m11 + s*mt.m21; mat->m12 = c*mt.m12 + s*mt.m22; mat->m13 = c*mt.m13 + s*mt.m23; mat->m20 = -s*mt.m10 + c*mt.m20; mat->m21 = -s*mt.m11 + c*mt.m21; mat->m22 = -s*mt.m12 + c*mt.m22; mat->m23 = -s*mt.m13 + c*mt.m23; } /*----------------------------------------------- Y軸回転(右手系) -----------------------------------------------*/ // //Y axis rotation // //|M00 M01 M02 M03| | cosy 0 -siny 0||m00 m01 m02 m03| //|M10 M11 M12 M13| = | 0 1 0 0||m10 m11 m12 m13| //|M20 M21 M22 M23| | siny 0 cosy 0||m20 m21 m22 m23| //|M30 M31 M32 M33| | 0 0 0 1||m30 m31 m32 m33| static void RotYRight(float y) { MATRIX *mat, mt; float s, c; mat = currentMatrix; CopyMatrixInt(mat, &mt); s = (float)sin(y); c = (float)cos(y); mat->m00 = c*mt.m00 + -s*mt.m20; mat->m01 = c*mt.m01 + -s*mt.m21; mat->m02 = c*mt.m02 + -s*mt.m22; mat->m03 = c*mt.m03 + -s*mt.m23; #if 0 mat->m10 = mt.m10; mat->m11 = mt.m11; mat->m12 = mt.m12; mat->m13 = mt.m13; #endif mat->m20 = s*mt.m00 + c*mt.m20; mat->m21 = s*mt.m01 + c*mt.m21; mat->m22 = s*mt.m02 + c*mt.m22; mat->m23 = s*mt.m03 + c*mt.m23; } /*----------------------------------------------- Z軸回転(右手系) -----------------------------------------------*/ // //Z axis rotation // //|M00 M01 M02 M03| | cosz sinz 0 0||m00 m01 m02 m03| //|M10 M11 M12 M13| = | -sinz cosz 0 0||m10 m11 m12 m13| //|M20 M21 M22 M23| | 0 0 1 0||m20 m21 m22 m23| //|M30 M31 M32 M33| | 0 0 0 1||m30 m31 m32 m33| static void RotZRight(float z) { MATRIX *mat, mt; float s, c; mat = currentMatrix; CopyMatrixInt(mat, &mt); s = (float)sin(z); c = (float)cos(z); mat->m00 = c*mt.m00 + s*mt.m10; mat->m01 = c*mt.m01 + s*mt.m11; mat->m02 = c*mt.m02 + s*mt.m12; mat->m03 = c*mt.m03 + s*mt.m13; mat->m10 = -s*mt.m00 + c*mt.m10; mat->m11 = -s*mt.m01 + c*mt.m11; mat->m12 = -s*mt.m02 + c*mt.m12; mat->m13 = -s*mt.m03 + c*mt.m13; #if 0 mat->m20 = mt.m20; mat->m21 = mt.m21; mat->m22 = mt.m22; mat->m23 = mt.m23; #endif } /*----------------------------------------------- X軸回転 -----------------------------------------------*/ void RotX(float x) { if (rightHand) RotXRight(x); else RotXLeft(x); } /*----------------------------------------------- Y軸回転 -----------------------------------------------*/ void RotY(float y) { if (rightHand) RotYRight(y); else RotYLeft(y); } /*----------------------------------------------- Z軸回転 -----------------------------------------------*/ void RotZ(float z) { if (rightHand) RotZRight(z); else RotZLeft(z); } /*----------------------------------------------- 平行移動 -----------------------------------------------*/ // //translation // //|M00 M01 M02 M03| | 1 0 0 0||m00 m01 m02 m03| //|M10 M11 M12 M13| = | 0 1 0 0||m10 m11 m12 m13| //|M20 M21 M22 M23| | 0 0 1 0||m20 m21 m22 m23| //|M30 M31 M32 M33| | x y z 1||m30 m31 m32 m33| void Trans(float x, float y, float z) { MATRIX *mat; mat = currentMatrix; mat->m30 += x * mat->m00 + y * mat->m10 + z * mat->m20; mat->m31 += x * mat->m01 + y * mat->m11 + z * mat->m21; mat->m32 += x * mat->m02 + y * mat->m12 + z * mat->m22; mat->m33 += x * mat->m03 + y * mat->m13 + z * mat->m23; } /*----------------------------------------------- スケール -----------------------------------------------*/ // //scaling // //|M00 M01 M02 M03| | x 0 0 0||m00 m01 m02 m03| //|M10 M11 M12 M13| = | 0 y 0 0||m10 m11 m12 m13| //|M20 M21 M22 M23| | 0 0 z 0||m20 m21 m22 m23| //|M30 M31 M32 M33| | 0 0 0 1||m30 m31 m32 m33| void Scale(float x, float y, float z) /* scale vector */ { MATRIX *mat; mat = currentMatrix; mat->m00 *= x; mat->m01 *= x; mat->m02 *= x; mat->m03 *= x; mat->m10 *= y; mat->m11 *= y; mat->m12 *= y; mat->m13 *= y; mat->m20 *= z; mat->m21 *= z; mat->m22 *= z; mat->m23 *= z; } /*----------------------------------------------- 透視投影 -----------------------------------------------*/ // //perspective // //|M00 M01 M02 M03| | 1 0 0 0||m00 m01 m02 m03| //|M10 M11 M12 M13| = | 0 1 0 0||m10 m11 m12 m13| //|M20 M21 M22 M23| | 0 0 1 r||m20 m21 m22 m23| //|M30 M31 M32 M33| | 0 0 0 1||m30 m31 m32 m33| void Perspective(float r) { MATRIX *mat; mat = currentMatrix; mat->m20 += r * mat->m30; mat->m21 += r * mat->m31; mat->m22 += r * mat->m32; mat->m23 += r * mat->m33; } /*----------------------------------------------- ZをZバッファ値にする -----------------------------------------------*/ //(注意) //透視変換マトリックスを掛けた後にこのマトリックスを掛ける。 // //----------解説------------- // //前方クリップ面のZ座標 N,その時のZバッファ値Zn //後方クリップ面のZ座標 F,その時のZバッファ値Zf とする。 // //透視変換したベクトルは(x,y,z,rz+1) //スクリーン上での座標は( x/(rz+1), y/(rz+1), z/(rz+1), 1 ) // //z/(rz+1) = N の時 Zbuffer=Zn //z/(rz+1) = F の時 Zbuffer=Zf //となるようにしたい。 // //z/(rz+1) = N を zについて解くと //z = N/(1-rN) となる。 //つまり // //z = N/(1-rN) の時にZbuffer=Zn ... (1) //z = F/(1-rF) の時にZbuffer=Zf ... (2) // //となるような変換マトリックスを用意する。 // // |1 0 0 0| //|X Y Z W| = |x y z rz+1||0 1 0 0| // |0 0 m22 0| // |0 0 m32 1| // //Z がZBufferの値。 //Z について計算すると // //Z = m22z + m32(rz+1) // //(1)(2)より //m22{N/(1-rN)} + m32{(rN)/(1-rN) + 1} = Zn //m32{F/(1-rF)} + m32{(rF)/(1-rF) + 1} = Zf // //A = N/(1-rN) //B = F/(1-rF) //C = (rN)/(1-rN) + 1 //D = (rF)/(1-rF) + 1 // //とすると、 // //m22A + m32C = Zn //m22B + m32D = Zf // //これを解くと、 // //m22 = (DZn - CZf) / (AD - BC) //m32 = (AZf - BZn) / (AD - BC) // //となる。 // //----------解説終了------------ // //|M00 M01 M02 M03| | 1 0 0 0||m00 m01 m02 m03| //|M10 M11 M12 M13| = | 0 1 0 0||m10 m11 m12 m13| //|M20 M21 M22 M23| | 0 0 m22 0||m20 m21 m22 m23| //|M30 M31 M32 M33| | 0 0 m32 1||m30 m31 m32 m33| // //※※※※※※※※※※※※※※※※※※※※※※※※※ //Zn>Zfでないとうまく動かない(バグか?) //※※※※※※※※※※※※※※※※※※※※※※※※※ void ZBufferMatrix(float N, float F, float Zn, float Zf, float r) { MATRIX m; float A,B,C,D; float coef; A = N / (1.0f - r * N); B = F / (1.0f - r * F); C = r * N / (1.0f - r * N) + 1.0f; D = r * F / (1.0f - r * F) + 1.0f; coef = 1.0f / (A * D - B * C); m.m00 = 1.0f; m.m01 = 0.0f; m.m02 = 0.0f; m.m03 = 0.0f; m.m10 = 0.0f; m.m11 = 1.0f; m.m12 = 0.0f; m.m13 = 0.0f; m.m20 = 0.0f; m.m21 = 0.0f; m.m22 = (D * Zn - C * Zf) * coef; m.m23 = 0.0f; m.m30 = 0.0f; m.m31 = 0.0f; m.m32 = (A * Zf - B * Zn) * coef; m.m33 = 1.0f; MulMatrix(&m); } /*----------------------------------------------- 透視投影かつZをZバッファ値に -----------------------------------------------*/ void PerspectiveWithZBuffer(float r, float N, float F, float Zn, float Zf) { ZBufferMatrix(N, F, Zn, Zf, r); Perspective(r); // currentMatrix->m00 *= 0.001f; // currentMatrix->m11 *= 0.001f; float right = 480.0f; float left = 0.0f; float top = 0.0f; float bottom = 800.0f; MATRIX *mat = currentMatrix; mat->m00 *= 2.0f / (right - left); mat->m11 *= 2.0f / (top - bottom); mat->m30 = -(right + left) / (right - left); mat->m31 = -(top + bottom) / (top - bottom); mat->m32 = 0.5f; } void PerspectiveFOV(float fov, float Zn, float Zf, float left, float top, float right, float bottom) { float f_n = 1.0f / (Zf - Zn); float theta = DEG2RAD(fov) * 0.5f; float divisor = tan(theta); float factor = 1.0f / divisor; MATRIX* mat = currentMatrix; mat->m00 = factor * (2.0f / (right - left)); mat->m01 = 0.0f; mat->m02 = 0.0f; mat->m03 = 0.0f; mat->m10 = 0.0f; mat->m11 = factor * (2.0f / (top - bottom)); mat->m12 = 0.0f; mat->m13 = 0.0f; mat->m20 = 0.0f; mat->m21 = 0.0f; mat->m22 = (-(Zf + Zn)) * f_n; mat->m23 = -2.0f * Zf * Zn * f_n; mat->m30 = 0.0f; mat->m31 = 0.0f; mat->m32 = -1.0f; mat->m33 = 1.0f; mat->m30 = -(right + left) / (right - left); mat->m31 = -(top + bottom) / (top - bottom); } /*----------------------------------------------- マトリックス同士の積(カレントマトリックスに左から掛ける) -----------------------------------------------*/ void MulMatrix(MATRIX *l) { MATRIX *dst, *r, mt; dst = currentMatrix; CopyMatrixInt(dst, &mt); r = &mt; dst->m00 = l->m00 * r->m00 + l->m01 * r->m10 + l->m02 * r->m20 + l->m03 * r->m30; dst->m01 = l->m00 * r->m01 + l->m01 * r->m11 + l->m02 * r->m21 + l->m03 * r->m31; dst->m02 = l->m00 * r->m02 + l->m01 * r->m12 + l->m02 * r->m22 + l->m03 * r->m32; dst->m03 = l->m00 * r->m03 + l->m01 * r->m13 + l->m02 * r->m23 + l->m03 * r->m33; dst->m10 = l->m10 * r->m00 + l->m11 * r->m10 + l->m12 * r->m20 + l->m13 * r->m30; dst->m11 = l->m10 * r->m01 + l->m11 * r->m11 + l->m12 * r->m21 + l->m13 * r->m31; dst->m12 = l->m10 * r->m02 + l->m11 * r->m12 + l->m12 * r->m22 + l->m13 * r->m32; dst->m13 = l->m10 * r->m03 + l->m11 * r->m13 + l->m12 * r->m23 + l->m13 * r->m33; dst->m20 = l->m20 * r->m00 + l->m21 * r->m10 + l->m22 * r->m20 + l->m23 * r->m30; dst->m21 = l->m20 * r->m01 + l->m21 * r->m11 + l->m22 * r->m21 + l->m23 * r->m31; dst->m22 = l->m20 * r->m02 + l->m21 * r->m12 + l->m22 * r->m22 + l->m23 * r->m32; dst->m23 = l->m20 * r->m03 + l->m21 * r->m13 + l->m22 * r->m23 + l->m23 * r->m33; dst->m30 = l->m30 * r->m00 + l->m31 * r->m10 + l->m32 * r->m20 + l->m33 * r->m30; dst->m31 = l->m30 * r->m01 + l->m31 * r->m11 + l->m32 * r->m21 + l->m33 * r->m31; dst->m32 = l->m30 * r->m02 + l->m31 * r->m12 + l->m32 * r->m22 + l->m33 * r->m32; dst->m33 = l->m30 * r->m03 + l->m31 * r->m13 + l->m32 * r->m23 + l->m33 * r->m33; } /*----------------------------------------------- マトリックス同士の積(カレントマトリックスに右から掛ける) -----------------------------------------------*/ void MulMatrixR(MATRIX *r) { MATRIX *dst, *l, mt; dst = currentMatrix; CopyMatrixInt(dst, &mt); l = &mt; dst->m00 = l->m00 * r->m00 + l->m01 * r->m10 + l->m02 * r->m20 + l->m03 * r->m30; dst->m01 = l->m00 * r->m01 + l->m01 * r->m11 + l->m02 * r->m21 + l->m03 * r->m31; dst->m02 = l->m00 * r->m02 + l->m01 * r->m12 + l->m02 * r->m22 + l->m03 * r->m32; dst->m03 = l->m00 * r->m03 + l->m01 * r->m13 + l->m02 * r->m23 + l->m03 * r->m33; dst->m10 = l->m10 * r->m00 + l->m11 * r->m10 + l->m12 * r->m20 + l->m13 * r->m30; dst->m11 = l->m10 * r->m01 + l->m11 * r->m11 + l->m12 * r->m21 + l->m13 * r->m31; dst->m12 = l->m10 * r->m02 + l->m11 * r->m12 + l->m12 * r->m22 + l->m13 * r->m32; dst->m13 = l->m10 * r->m03 + l->m11 * r->m13 + l->m12 * r->m23 + l->m13 * r->m33; dst->m20 = l->m20 * r->m00 + l->m21 * r->m10 + l->m22 * r->m20 + l->m23 * r->m30; dst->m21 = l->m20 * r->m01 + l->m21 * r->m11 + l->m22 * r->m21 + l->m23 * r->m31; dst->m22 = l->m20 * r->m02 + l->m21 * r->m12 + l->m22 * r->m22 + l->m23 * r->m32; dst->m23 = l->m20 * r->m03 + l->m21 * r->m13 + l->m22 * r->m23 + l->m23 * r->m33; dst->m30 = l->m30 * r->m00 + l->m31 * r->m10 + l->m32 * r->m20 + l->m33 * r->m30; dst->m31 = l->m30 * r->m01 + l->m31 * r->m11 + l->m32 * r->m21 + l->m33 * r->m31; dst->m32 = l->m30 * r->m02 + l->m31 * r->m12 + l->m32 * r->m22 + l->m33 * r->m32; dst->m33 = l->m30 * r->m03 + l->m31 * r->m13 + l->m32 * r->m23 + l->m33 * r->m33; } /*----------------------------------------------- 転置行列 -----------------------------------------------*/ void Transpose(MATRIX *dst) { MATRIX *src; MATRIX mt; src = &mt; if (dst == NULL){ dst = currentMatrix; } CopyMatrixInt(dst, src); /* dst->m00 = src->m00; */ dst->m01 = src->m10; dst->m02 = src->m20; dst->m03 = src->m30; dst->m10 = src->m01; /* dst->m11 = src->m11; */ dst->m12 = src->m21; dst->m13 = src->m31; dst->m20 = src->m02; dst->m21 = src->m12; /* dst->m22 = src->m22; */ dst->m23 = src->m32; dst->m30 = src->m03; dst->m31 = src->m13; dst->m32 = src->m23; /* dst->m33 = src->m33; */ } /*----------------------------------------------- マトリックスの行列式 -----------------------------------------------*/ float Determinant(MATRIX *src) { float val0, val1, val2, val3, val4, val5; float val00, val01, val02, val03; float value; if (src == NULL){ src = currentMatrix; } val0 = (src->m22 * src->m33 - src->m23 * src->m32); val1 = (src->m21 * src->m33 - src->m23 * src->m31); val2 = (src->m21 * src->m32 - src->m22 * src->m31); val3 = (src->m20 * src->m33 - src->m23 * src->m30); val4 = (src->m20 * src->m32 - src->m22 * src->m30); val5 = (src->m20 * src->m31 - src->m21 * src->m30); val00 = (src->m11 * val0 - src->m12 * val1 + src->m13 * val2); val01 = (src->m10 * val0 - src->m12 * val3 + src->m13 * val4); val02 = (src->m10 * val1 - src->m11 * val3 + src->m13 * val5); val03 = (src->m10 * val2 - src->m11 * val4 + src->m12 * val5); value = src->m00 * val00 - src->m01 * val01 + src->m02 * val02 - src->m03 * val03; #if 0 value = src->m00 * (src->m11 * val0 - src->m12 * val1 + src->m13 * val2); value += -src->m01 * (src->m10 * val0 - src->m12 * val3 + src->m13 * val4); value += src->m02 * (src->m10 * val1 - src->m11 * val3 + src->m13 * val5); value += -src->m03 * (src->m10 * val2 - src->m11 * val4 + src->m12 * val5); value = src->m00 * ( src->m11 * (src->m22 * src->m33 - src->m23 * src->m32) + -src->m12 * (src->m21 * src->m33 - src->m23 * src->m31) + src->m13 * (src->m21 * src->m32 - src->m22 * src->m31) ); value += -src->m01 * ( src->m10 * (src->m22 * src->m33 - src0>m23 * src->m32) + -src->m12 * (src->m20 * src->m33 - src->m23 * src->m30) + src->m13 * (src->m20 * src->m32 - src->m22 * src->m30) ); value += src->m02 * ( src->m10 * (src->m21 * src->m33 - src->m23 * src->m31) + -src->m11 * (src->m20 * src->m33 - src->m23 * src->m30) + src->m13 * (src->m20 * src->m31 - src->m21 * src->m30) ); value += -src->m03 * ( src->m10 * (src->m21 * src->m32 - src->m22 * src->m31) + -src->m11 * (src->m20 * src->m32 - src->m22 * src->m30) + src->m12 * (src->m20 * src->m31 - src->m21 * src->m30) ); #endif return value; } /* * * 3x3行列式の値(逆行列用) * */ float Determinant3(MATRIX *src) { float val0, val1, val2; float value; val0 = (src->m11 * src->m22 - src->m12 * src->m21); val1 = (src->m10 * src->m22 - src->m12 * src->m20); val2 = (src->m10 * src->m21 - src->m11 * src->m20); value = src->m00 * val0 - src->m01 * val1 + src->m02 * val2; return value; } /*----------------------------------------------- 逆行列 * 0 4 8 12 * 1 5 9 13 * 2 6 10 14 * 3 7 11 15 -----------------------------------------------*/ int InverseMatrix(MATRIX *p_dst) { float m[16]; MATRIX *dst = p_dst; if (dst == NULL) { dst = currentMatrix; } m[0] = currentMatrix->m00; m[4] = currentMatrix->m01; m[8] = currentMatrix->m02; m[12] = currentMatrix->m03; m[1] = currentMatrix->m10; m[5] = currentMatrix->m11; m[9] = currentMatrix->m12; m[13] = currentMatrix->m13; m[2] = currentMatrix->m20; m[6] = currentMatrix->m21; m[10] = currentMatrix->m22; m[14] = currentMatrix->m23; m[3] = currentMatrix->m30; m[7] = currentMatrix->m31; m[11] = currentMatrix->m32; m[15] = currentMatrix->m33; float a0 = m[0] * m[5] - m[1] * m[4]; float a1 = m[0] * m[6] - m[2] * m[4]; float a2 = m[0] * m[7] - m[3] * m[4]; float a3 = m[1] * m[6] - m[2] * m[5]; float a4 = m[1] * m[7] - m[3] * m[5]; float a5 = m[2] * m[7] - m[3] * m[6]; float b0 = m[8] * m[13] - m[9] * m[12]; float b1 = m[8] * m[14] - m[10] * m[12]; float b2 = m[8] * m[15] - m[11] * m[12]; float b3 = m[9] * m[14] - m[10] * m[13]; float b4 = m[9] * m[15] - m[11] * m[13]; float b5 = m[10] * m[15] - m[11] * m[14]; // Calculate the determinant. float det = a0 * b5 - a1 * b4 + a2 * b3 + a3 * b2 - a4 * b1 + a5 * b0; // Close to zero, can't invert. if (fabs(det) == 0.0f) return FALSE; // Support the case where m == dst. dst->m00 = m[5] * b5 - m[6] * b4 + m[7] * b3; dst->m10 = -m[1] * b5 + m[2] * b4 - m[3] * b3; dst->m20 = m[13] * a5 - m[14] * a4 + m[15] * a3; dst->m30 = -m[9] * a5 + m[10] * a4 - m[11] * a3; dst->m01 = -m[4] * b5 + m[6] * b2 - m[7] * b1; dst->m11 = m[0] * b5 - m[2] * b2 + m[3] * b1; dst->m21 = -m[12] * a5 + m[14] * a2 - m[15] * a1; dst->m31 = m[8] * a5 - m[10] * a2 + m[11] * a1; dst->m02 = m[4] * b4 - m[5] * b2 + m[7] * b0; dst->m12 = -m[0] * b4 + m[1] * b2 - m[3] * b0; dst->m22 = m[12] * a4 - m[13] * a2 + m[15] * a0; dst->m32 = -m[8] * a4 + m[9] * a2 - m[11] * a0; dst->m03 = -m[4] * b3 + m[5] * b1 - m[6] * b0; dst->m13 = m[0] * b3 - m[1] * b1 + m[2] * b0; dst->m23 = -m[12] * a3 + m[13] * a1 - m[14] * a0; dst->m33 = m[8] * a3 - m[9] * a1 + m[10] * a0; float w = 1.0f / det; dst->m00 *= w; dst->m01 *= w; dst->m02 *= w; dst->m03 *= w; dst->m10 *= w; dst->m11 *= w; dst->m12 *= w; dst->m13 *= w; dst->m20 *= w; dst->m21 *= w; dst->m22 *= w; dst->m23 *= w; dst->m30 *= w; dst->m31 *= w; dst->m32 *= w; dst->m33 *= w; #if 0 MATRIX *src; MATRIX mt, mat3; float invA; src = &mt; if (dst == NULL){ dst = currentMatrix; } invA = Determinant(NULL); if (invA == 0.0f){ return FALSE; } invA = 1.0f / invA; CopyMatrixInt(dst, src); mat3.m00 = src->m11; mat3.m01 = src->m12; mat3.m02 = src->m13; mat3.m10 = src->m21; mat3.m11 = src->m22; mat3.m12 = src->m23; mat3.m20 = src->m31; mat3.m21 = src->m32; mat3.m22 = src->m33; dst->m00 = Determinant3(&mat3) * invA; mat3.m00 = src->m10; /* mat3.m01 = src->m12; mat3.m02 = src->m13; */ mat3.m10 = src->m20; /* mat3.m11 = src->m22; mat3.m12 = src->m23; */ mat3.m20 = src->m30; /* mat3.m21 = src->m32; mat3.m22 = src->m33; */ dst->m01 = -Determinant3(&mat3) * invA; /* mat3.m00 = src->m10; */ mat3.m01 = src->m11; /* mat3.m02 = src->m13; */ /* mat3.m10 = src->m20; */ mat3.m11 = src->m21; /* mat3.m12 = src->m23; */ /* mat3.m20 = src->m30; */ mat3.m21 = src->m31; /* mat3.m22 = src->m33; */ dst->m02 = Determinant3(&mat3) * invA; /* mat3.m00 = src->m10; mat3.m01 = src->m11; */ mat3.m02 = src->m12; /* mat3.m10 = src->m20; mat3.m11 = src->m21; */ mat3.m12 = src->m22; /* mat3.m20 = src->m30; mat3.m21 = src->m31; */ mat3.m22 = src->m32; dst->m03 = -Determinant3(&mat3) * invA; mat3.m00 = src->m01; mat3.m01 = src->m02; mat3.m02 = src->m03; mat3.m10 = src->m21; mat3.m11 = src->m22; mat3.m12 = src->m23; mat3.m20 = src->m31; mat3.m21 = src->m32; mat3.m22 = src->m33; dst->m10 = -Determinant3(&mat3) * invA; mat3.m00 = src->m00; /* mat3.m01 = src->m02; mat3.m02 = src->m03; */ mat3.m10 = src->m20; /* mat3.m11 = src->m22; mat3.m12 = src->m23; */ mat3.m20 = src->m30; /* mat3.m21 = src->m32; mat3.m22 = src->m33; */ dst->m11 = Determinant3(&mat3) * invA; /* mat3.m00 = src->m00; */ mat3.m01 = src->m01; /* mat3.m02 = src->m03; */ /* mat3.m10 = src->m20; */ mat3.m11 = src->m21; /* mat3.m12 = src->m23; */ /* mat3.m20 = src->m30; */ mat3.m21 = src->m31; /* mat3.m22 = src->m33; */ dst->m12 = -Determinant3(&mat3) * invA; /* mat3.m00 = src->m00; mat3.m01 = src->m01; */ mat3.m02 = src->m02; /* mat3.m10 = src->m20; mat3.m11 = src->m21; */ mat3.m12 = src->m22; /* mat3.m20 = src->m30; mat3.m21 = src->m31; */ mat3.m22 = src->m32; dst->m13 = Determinant3(&mat3) * invA; mat3.m00 = src->m01; mat3.m01 = src->m02; mat3.m02 = src->m03; mat3.m10 = src->m11; mat3.m11 = src->m12; mat3.m12 = src->m13; mat3.m20 = src->m31; mat3.m21 = src->m32; mat3.m22 = src->m33; dst->m20 = Determinant3(&mat3) * invA; mat3.m00 = src->m00; /* mat3.m01 = src->m02; mat3.m02 = src->m03; */ mat3.m10 = src->m10; /* mat3.m11 = src->m12; mat3.m12 = src->m13; */ mat3.m20 = src->m30; /* mat3.m21 = src->m32; mat3.m22 = src->m33; */ dst->m21 = -Determinant3(&mat3) * invA; /* mat3.m00 = src->m00; */ mat3.m01 = src->m01; /* mat3.m02 = src->m03; */ /* mat3.m10 = src->m10; */ mat3.m11 = src->m11; /* mat3.m12 = src->m13; */ /* mat3.m20 = src->m30; */ mat3.m21 = src->m31; /* mat3.m22 = src->m33; */ dst->m22 = Determinant3(&mat3) * invA; /* mat3.m00 = src->m00; mat3.m01 = src->m01; */ mat3.m02 = src->m02; /* mat3.m10 = src->m10; mat3.m11 = src->m11; */ mat3.m12 = src->m12; /* mat3.m20 = src->m30; mat3.m21 = src->m31; */ mat3.m22 = src->m32; dst->m23 = -Determinant3(&mat3) * invA; mat3.m00 = src->m01; mat3.m01 = src->m02; mat3.m02 = src->m03; mat3.m10 = src->m11; mat3.m11 = src->m12; mat3.m12 = src->m13; mat3.m20 = src->m21; mat3.m21 = src->m22; mat3.m22 = src->m23; dst->m30 = -Determinant3(&mat3) * invA; mat3.m00 = src->m00; /* mat3.m01 = src->m02; mat3.m02 = src->m03; */ mat3.m10 = src->m10; /* mat3.m11 = src->m12; mat3.m12 = src->m13; */ mat3.m20 = src->m20; /* mat3.m21 = src->m22; mat3.m22 = src->m23; */ dst->m31 = Determinant3(&mat3) * invA; /* mat3.m00 = src->m00; */ mat3.m01 = src->m01; /* mat3.m02 = src->m03; */ /* mat3.m10 = src->m10; */ mat3.m11 = src->m11; /* mat3.m12 = src->m13; */ /* mat3.m20 = src->m20; */ mat3.m21 = src->m21; /* mat3.m22 = src->m23; */ dst->m32 = -Determinant3(&mat3) * invA; /* mat3.m00 = src->m00; mat3.m01 = src->m01; */ mat3.m02 = src->m02; /* mat3.m10 = src->m10; mat3.m11 = src->m11; */ mat3.m12 = src->m12; /* mat3.m20 = src->m20; mat3.m21 = src->m21; */ mat3.m22 = src->m22; dst->m33 = Determinant3(&mat3) * invA; Transpose(NULL); #endif return TRUE; } /*----------------------------------------------- カレントマトリックスのトランスを得る -----------------------------------------------*/ void GetCurrentTrans(VECTOR *v) { MATRIX *mat = currentMatrix; v->x = mat->m30; v->y = mat->m31; v->z = mat->m32; } /*----------------------------------------------- ベクトル*マトリックス -> ベクトル -----------------------------------------------*/ // // |m00 m01 m02 m03| //|X Y Z W| = |x y z 1||m10 m11 m12 m13| // |m20 m21 m22 m23| // |m30 m31 m32 m33| void ApplyMatrix(VECTOR *v1, VECTOR *v0) { MATRIX *mat; // float w, oow; mat = currentMatrix; v1->x = (v0->x * mat->m00 + v0->y * mat->m10 + v0->z * mat->m20) + mat->m30; v1->y = (v0->x * mat->m01 + v0->y * mat->m11 + v0->z * mat->m21) + mat->m31; v1->z = (v0->x * mat->m02 + v0->y * mat->m12 + v0->z * mat->m22) + mat->m32; v1->w = (v0->x * mat->m03 + v0->y * mat->m13 + v0->z * mat->m23) + mat->m33; /* if (w != 0.0f){ oow = 1.0f / w; } else { oow = 1.0f; } v1->x *= oow; v1->y *= oow; v1->z *= oow; v1->w = w; */ } void ApplyMatrix(MATRIX* mat, VECTOR *v1, VECTOR *v0) { v1->x = (v0->x * mat->m00 + v0->y * mat->m10 + v0->z * mat->m20) + mat->m30; v1->y = (v0->x * mat->m01 + v0->y * mat->m11 + v0->z * mat->m21) + mat->m31; v1->z = (v0->x * mat->m02 + v0->y * mat->m12 + v0->z * mat->m22) + mat->m32; v1->w = (v0->x * mat->m03 + v0->y * mat->m13 + v0->z * mat->m23) + mat->m33; } /*----------------------------------------------- ベクトル*マトリックス -> ベクトル(回転のみ) -----------------------------------------------*/ // // |m00 m01 m02 0| //|X Y Z 1| = |x y z 1||m10 m11 m12 0| // |m20 m21 m22 0| // | 0 0 0 1| void ApplyMatrixRot(VECTOR *v1, VECTOR *v0) { MATRIX *mat; mat = currentMatrix; v1->x = (v0->x * mat->m00 + v0->y * mat->m10 + v0->z * mat->m20); v1->y = (v0->x * mat->m01 + v0->y * mat->m11 + v0->z * mat->m21); v1->z = (v0->x * mat->m02 + v0->y * mat->m12 + v0->z * mat->m22); } /*----------------------------------------------- ベクトル*マトリックス -> ベクトル(平行移動のみ) -----------------------------------------------*/ // // | 1 0 0 0| //|X Y Z 1| = |x y z 1|| 0 1 0 0| // | 0 0 1 0| // |m30 m31 m32 1| void ApplyMatrixTrans(VECTOR *v1, VECTOR *v0) { MATRIX *mat; mat = currentMatrix; v1->x = v0->x + mat->m30; v1->y = v0->y + mat->m31; v1->z = v0->z + mat->m32; } /*----------------------------------------------- 2ベクトルの外積 -----------------------------------------------*/ void OuterProduct( VECTOR *dst, VECTOR *v1, VECTOR *v2 ) { dst->x = v1->y * v2->z - v1->z * v2->y; dst->y = v1->z * v2->x - v1->x * v2->z; dst->z = v1->x * v2->y - v1->y * v2->x; } /*----------------------------------------------- 2ベクトルの内積 -----------------------------------------------*/ float InnerProduct(VECTOR *v1, VECTOR *v2) { return v1->x * v2->x + v1->y * v2->y + v1->z * v2->z; } /*----------------------------------------------- 単位ベクトル -----------------------------------------------*/ void UnitVector(VECTOR *v) { float d; d = (float)sqrt(v->x * v->x + v->y * v->y + v->z * v->z); if (d < 0.00001f){ v->x = 1.0f; v->y = 0.0f; v->z = 0.0f; return; } d = 1.0f / d; v->x *= d; v->y *= d; v->z *= d; } /*----------------------------------------------- カメラマトリックス生成 -----------------------------------------------*/ void LookAt(VECTOR *cam_pos, VECTOR *cam_int) { VECTOR vec; float x, y; /* 注視点->ポジションのベクトル */ vec.x = cam_pos->x - cam_int->x; vec.y = cam_pos->y - cam_int->y; vec.z = cam_pos->z - cam_int->z; /* 回転角 */ y = (float)atan2(vec.x, vec.z); x = (float)-atan2(vec.y, sqrt(vec.x*vec.x + vec.z*vec.z)); RotX(-x); RotY(-y); Trans(-cam_pos->x, -cam_pos->y, -cam_pos->z); } void LookAtWithRoll(VECTOR *cam_pos, VECTOR *cam_int, float roll) { VECTOR vec; float x, y; /* 注視点->ポジションのベクトル */ vec.x = cam_pos->x - cam_int->x; vec.y = cam_pos->y - cam_int->y; vec.z = cam_pos->z - cam_int->z; /* 回転角 */ y = (float)atan2(vec.x, vec.z); x = (float)-atan2(vec.y, sqrt(vec.x*vec.x + vec.z*vec.z)); RotX(-x); RotY(-y); Trans(-cam_pos->x, -cam_pos->y, -cam_pos->z); RotZ(-roll); } /*---------------------------------------------------------------------* * 透視投影 *---------------------------------------------------------------------*/ void PerspectiveViewScreen(ViewScreen* vs, float scrz, float ax, float ay, float xcenter, float ycenter, float zbufsmall, float zbufbig, float zD, float zF, float fognearz, float fogfarz, float W, float H) { // D = nearz, F = farz, W = width/2, H = Height/2 // // Perspective // // | scrz*ax/W 0 0 0 | // m = | 0 scrz*ay/H 0 0 | // | 0 0 (F+D)/(F-D) -2FD/(F-D) | // | 0 0 1 0 | // z = D, zh = -D, z = F, zh = F Zクリップの範囲 zh :(-D, F) float p, q, fscale, foffset, zscale, zoffset, qa, qb, za, zb; p = (zF+zD)/(zF-zD); q = -2*zF*zD/(zF-zD); SetVector( &vs->a, scrz * ax / W, scrz * ay / H, p, 1.0f ); SetVector( &vs->b, 0.0f, 0.0f, q, 0.0f); SetVector( &vs->ra, 1/(scrz * ax / W), 1/(scrz * ay / H), 1/(p), 0.0f ); SetVector( &vs->rb, 0.0f, 0.0f, -q/(p), 0.0f); za = zD * zF * (zbufbig - zbufsmall) / (zF - zD); zb = (zbufsmall * zF - zbufbig * zD) / (zF - zD); zscale = za / q; zoffset = zb - za * p / q; if ( fognearz < fogfarz ) { qa = fogfarz * fognearz / (fogfarz - fognearz) * 255.0f; qb = -fognearz / (fogfarz - fognearz) * 255.0f; } else { qa = 0.0f; qb = 255.0f; }; fscale = qa / q; foffset = qb - qa * p / q; SetVector( &vs->v, xcenter, ycenter, zoffset, fscale ); SetVector( &vs->t, W, H, zscale, foffset); SetVector( &vs->cmin, -W + xcenter, -H + ycenter, -zD, 1.0f ); SetVector( &vs->cmax, W + xcenter, H + ycenter, zF, -zb ); } /*---------------------------------------------------------------------* * 平行投影(垂直投影) *---------------------------------------------------------------------*/ void OrthoMatrix(float basex, float basey, float width, float height, float Znear, float Zfar ) { MATRIX* mat = currentMatrix; float right = basex+width; float left = basex; float top = basey; float bottom = basey+height; mat->m00 = 2.0f / (right - left); mat->m01 = 0.0f; mat->m02 = 0.0f; mat->m03 = 0.0f; mat->m10 = 0.0f; mat->m11 = 2.0f / (top - bottom); mat->m12 = 0.0f; mat->m13 = 0.0f; mat->m20 = 0.0f; mat->m21 = 0.0f; mat->m22 = 1.0f / (Znear - Zfar ); mat->m23 = 0.0f; mat->m30 = -(right + left) / (right - left); mat->m31 = -(top + bottom) / (top - bottom); mat->m32 = -Znear / (Znear - Zfar ); mat->m33 = 1.0f; /* mat->m00 = 0.1f; mat->m01 = 0.0f; mat->m02 = 0.0f; mat->m03 = 0.0f; mat->m10 = 0.0f; mat->m11 = 0.1f; mat->m12 = 0.0f; mat->m13 = 0.0f; mat->m20 = 0.0f; mat->m21 = 0.0f; mat->m22 = 1.0f; mat->m23 = 0.0f; mat->m30 = 0.0f; mat->m31 = 0.0f; mat->m32 = 0.0f; mat->m33 = 1.0f; */ } /*----------------------------------------------- 2点間の距離を求める(3D) -----------------------------------------------*/ float GetVectorDistance( VECTOR *v1, VECTOR *v2 ) { float x,y,z; x = (float)fabs( v1->x - v2->x ); y = (float)fabs( v1->y - v2->y ); z = (float)fabs( v1->z - v2->z ); return (float)sqrt( x * x + y * y + z * z ); } /*----------------------------------------------- 任意の点がポリゴン(四角形)内にあるか?(2D) -----------------------------------------------*/ int HasPoint2D( float x, float y, VECTOR *v ) { int i,j,r,npol; r=0;npol=4; for( i=0,j=npol-1; i<npol; j=i++ ) { if (((( v[i].y <=y ) && ( y<v[j].y )) || (( v[j].y <= y ) && ( y<v[i].y ))) && ( x<(v[j].x-v[i].x)*(y-v[i].y)/(v[j].y-v[i].y)+v[i].x)) r=!r; } return r; } /*----------------------------------------------- 直線と平面の交点を求める(3D) -----------------------------------------------*/ int IntersectLinePlane( VECTOR *lpoint, VECTOR *lvector, VECTOR *ppoint, VECTOR *pnormal, VECTOR *result ) { float top,bottom,mul; top = ( ppoint->x - lpoint->x ) * pnormal->x + ( ppoint->y - lpoint->y ) * pnormal->y + ( ppoint->z - lpoint->z ) * pnormal->z; bottom = lvector->x * pnormal->x + lvector->y * pnormal->y + lvector->z * pnormal->z; if ( bottom == 0.0f ) return -1; // 平行 mul = top / bottom; result->x = lpoint->x + mul * lvector->x; result->y = lpoint->y + mul * lvector->y; result->z = lpoint->z + mul * lvector->z; return 0; } /*----------------------------------------------- 任意の点がポリゴン(四角形)内にあるか?(3D) -----------------------------------------------*/ static int HasPoint3DSub( float x, float y, VECTOR *v, int p1, int p2 ) { int i,j,r,npol; float *ti; float *tj; r=0;npol=4; for( i=0,j=npol-1; i<npol; j=i++ ) { ti = (float *)&v[i]; tj = (float *)&v[j]; if (((( ti[p2] <=y ) && ( y<tj[p2] )) || (( tj[p2] <= y ) && ( y<ti[p2] ))) && ( x<(tj[p1]-ti[p1])*(y-ti[p2])/(tj[p2]-ti[p2])+ti[p1])) r=!r; } return r; } int HasPoint3D( VECTOR *p, VECTOR *v ) { if ( HasPoint3DSub( p->x, p->y, v, 0, 1 ) ) // if ( HasPoint3DSub( p->x, p->z, v, 0, 2 ) ) return -1; if ( HasPoint3DSub( p->y, p->z, v, 1, 2 ) ) return -1; return 0; } void GetTargetAngle( VECTOR *ang, VECTOR *src, VECTOR *target ) { //-------------------------------------------------- // カメラのポジション->注視点の回転角を求める //-------------------------------------------------- VECTOR vec; /* 注視点->ポジションのベクトル */ vec.x = src->x - target->x; vec.y = src->y - target->y; vec.z = src->z - target->z; /* 回転角 */ ang->y = (float)-atan2( vec.x, vec.z ); ang->x = (float)-atan2( vec.y, sqrt(vec.x*vec.x + vec.z*vec.z) ); ang->z = 0.0f; ang->w = 0.0f; }
26.894385
131
0.440374
[ "geometry", "vector", "3d" ]
c8b24153321d258a6e0650679d0d6dcdb569f469
48,209
cc
C++
v8_6_7/src/s390/code-stubs-s390.cc
wenfeifei/miniblink49
2ed562ff70130485148d94b0e5f4c343da0c2ba4
[ "Apache-2.0" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
v8_6_7/src/s390/code-stubs-s390.cc
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
459
2016-09-29T00:51:38.000Z
2022-03-07T14:37:46.000Z
v8_6_7/src/s390/code-stubs-s390.cc
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.000Z
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #if V8_TARGET_ARCH_S390 #include "src/api-arguments.h" #include "src/assembler-inl.h" #include "src/base/bits.h" #include "src/bootstrapper.h" #include "src/code-stubs.h" #include "src/frame-constants.h" #include "src/frames.h" #include "src/ic/ic.h" #include "src/ic/stub-cache.h" #include "src/isolate.h" #include "src/regexp/jsregexp.h" #include "src/regexp/regexp-macro-assembler.h" #include "src/runtime/runtime.h" #include "src/s390/code-stubs-s390.h" // Cannot be the first include. namespace v8 { namespace internal { #define __ ACCESS_MASM(masm) void ArrayNArgumentsConstructorStub::Generate(MacroAssembler* masm) { __ ShiftLeftP(r1, r2, Operand(kPointerSizeLog2)); __ StoreP(r3, MemOperand(sp, r1)); __ push(r3); __ push(r4); __ AddP(r2, r2, Operand(3)); __ TailCallRuntime(Runtime::kNewArray); } void DoubleToIStub::Generate(MacroAssembler* masm) { Label out_of_range, only_low, negate, done, fastpath_done; Register result_reg = destination(); // Immediate values for this stub fit in instructions, so it's safe to use ip. Register scratch = GetRegisterThatIsNotOneOf(result_reg); Register scratch_low = GetRegisterThatIsNotOneOf(result_reg, scratch); Register scratch_high = GetRegisterThatIsNotOneOf(result_reg, scratch, scratch_low); DoubleRegister double_scratch = kScratchDoubleReg; __ push(scratch); // Account for saved regs. int argument_offset = 1 * kPointerSize; // Load double input. __ LoadDouble(double_scratch, MemOperand(sp, argument_offset)); // Do fast-path convert from double to int. __ ConvertDoubleToInt64(result_reg, double_scratch); // Test for overflow __ TestIfInt32(result_reg); __ beq(&fastpath_done, Label::kNear); __ Push(scratch_high, scratch_low); // Account for saved regs. argument_offset += 2 * kPointerSize; __ LoadlW(scratch_high, MemOperand(sp, argument_offset + Register::kExponentOffset)); __ LoadlW(scratch_low, MemOperand(sp, argument_offset + Register::kMantissaOffset)); __ ExtractBitMask(scratch, scratch_high, HeapNumber::kExponentMask); // Load scratch with exponent - 1. This is faster than loading // with exponent because Bias + 1 = 1024 which is a *S390* immediate value. STATIC_ASSERT(HeapNumber::kExponentBias + 1 == 1024); __ SubP(scratch, Operand(HeapNumber::kExponentBias + 1)); // If exponent is greater than or equal to 84, the 32 less significant // bits are 0s (2^84 = 1, 52 significant bits, 32 uncoded bits), // the result is 0. // Compare exponent with 84 (compare exponent - 1 with 83). __ CmpP(scratch, Operand(83)); __ bge(&out_of_range, Label::kNear); // If we reach this code, 31 <= exponent <= 83. // So, we don't have to handle cases where 0 <= exponent <= 20 for // which we would need to shift right the high part of the mantissa. // Scratch contains exponent - 1. // Load scratch with 52 - exponent (load with 51 - (exponent - 1)). __ Load(r0, Operand(51)); __ SubP(scratch, r0, scratch); __ CmpP(scratch, Operand::Zero()); __ ble(&only_low, Label::kNear); // 21 <= exponent <= 51, shift scratch_low and scratch_high // to generate the result. __ ShiftRight(scratch_low, scratch_low, scratch); // Scratch contains: 52 - exponent. // We needs: exponent - 20. // So we use: 32 - scratch = 32 - 52 + exponent = exponent - 20. __ Load(r0, Operand(32)); __ SubP(scratch, r0, scratch); __ ExtractBitMask(result_reg, scratch_high, HeapNumber::kMantissaMask); // Set the implicit 1 before the mantissa part in scratch_high. STATIC_ASSERT(HeapNumber::kMantissaBitsInTopWord >= 16); __ Load(r0, Operand(1 << ((HeapNumber::kMantissaBitsInTopWord)-16))); __ ShiftLeftP(r0, r0, Operand(16)); __ OrP(result_reg, result_reg, r0); __ ShiftLeft(r0, result_reg, scratch); __ OrP(result_reg, scratch_low, r0); __ b(&negate, Label::kNear); __ bind(&out_of_range); __ mov(result_reg, Operand::Zero()); __ b(&done, Label::kNear); __ bind(&only_low); // 52 <= exponent <= 83, shift only scratch_low. // On entry, scratch contains: 52 - exponent. __ LoadComplementRR(scratch, scratch); __ ShiftLeft(result_reg, scratch_low, scratch); __ bind(&negate); // If input was positive, scratch_high ASR 31 equals 0 and // scratch_high LSR 31 equals zero. // New result = (result eor 0) + 0 = result. // If the input was negative, we have to negate the result. // Input_high ASR 31 equals 0xFFFFFFFF and scratch_high LSR 31 equals 1. // New result = (result eor 0xFFFFFFFF) + 1 = 0 - result. __ ShiftRightArith(r0, scratch_high, Operand(31)); #if V8_TARGET_ARCH_S390X __ lgfr(r0, r0); __ ShiftRightP(r0, r0, Operand(32)); #endif __ XorP(result_reg, r0); __ ShiftRight(r0, scratch_high, Operand(31)); __ AddP(result_reg, r0); __ bind(&done); __ Pop(scratch_high, scratch_low); __ bind(&fastpath_done); __ pop(scratch); __ Ret(); } void MathPowStub::Generate(MacroAssembler* masm) { const Register exponent = MathPowTaggedDescriptor::exponent(); DCHECK(exponent == r4); const DoubleRegister double_base = d1; const DoubleRegister double_exponent = d2; const DoubleRegister double_result = d3; const DoubleRegister double_scratch = d0; const Register scratch = r1; const Register scratch2 = r9; Label call_runtime, done, int_exponent; // Detect integer exponents stored as double. __ TryDoubleToInt32Exact(scratch, double_exponent, scratch2, double_scratch); __ beq(&int_exponent, Label::kNear); __ push(r14); { AllowExternalCallThatCantCauseGC scope(masm); __ PrepareCallCFunction(0, 2, scratch); __ MovToFloatParameters(double_base, double_exponent); __ CallCFunction(ExternalReference::power_double_double_function(isolate()), 0, 2); } __ pop(r14); __ MovFromFloatResult(double_result); __ b(&done); // Calculate power with integer exponent. __ bind(&int_exponent); // Get two copies of exponent in the registers scratch and exponent. // Exponent has previously been stored into scratch as untagged integer. __ LoadRR(exponent, scratch); __ ldr(double_scratch, double_base); // Back up base. __ LoadImmP(scratch2, Operand(1)); __ ConvertIntToDouble(double_result, scratch2); // Get absolute value of exponent. Label positive_exponent; __ CmpP(scratch, Operand::Zero()); __ bge(&positive_exponent, Label::kNear); __ LoadComplementRR(scratch, scratch); __ bind(&positive_exponent); Label while_true, no_carry, loop_end; __ bind(&while_true); __ mov(scratch2, Operand(1)); __ AndP(scratch2, scratch); __ beq(&no_carry, Label::kNear); __ mdbr(double_result, double_scratch); __ bind(&no_carry); __ ShiftRightP(scratch, scratch, Operand(1)); __ LoadAndTestP(scratch, scratch); __ beq(&loop_end, Label::kNear); __ mdbr(double_scratch, double_scratch); __ b(&while_true); __ bind(&loop_end); __ CmpP(exponent, Operand::Zero()); __ bge(&done); // get 1/double_result: __ ldr(double_scratch, double_result); __ LoadImmP(scratch2, Operand(1)); __ ConvertIntToDouble(double_result, scratch2); __ ddbr(double_result, double_scratch); // Test whether result is zero. Bail out to check for subnormal result. // Due to subnormals, x^-y == (1/x)^y does not hold in all cases. __ lzdr(kDoubleRegZero); __ cdbr(double_result, kDoubleRegZero); __ bne(&done, Label::kNear); // double_exponent may not containe the exponent value if the input was a // smi. We set it with exponent value before bailing out. __ ConvertIntToDouble(double_exponent, exponent); // Returning or bailing out. __ push(r14); { AllowExternalCallThatCantCauseGC scope(masm); __ PrepareCallCFunction(0, 2, scratch); __ MovToFloatParameters(double_base, double_exponent); __ CallCFunction( ExternalReference::power_double_double_function(isolate()), 0, 2); } __ pop(r14); __ MovFromFloatResult(double_result); __ bind(&done); __ Ret(); } Movability CEntryStub::NeedsImmovableCode() { return kImmovable; } void CodeStub::GenerateStubsAheadOfTime(Isolate* isolate) { CEntryStub::GenerateAheadOfTime(isolate); CommonArrayConstructorStub::GenerateStubsAheadOfTime(isolate); StoreFastElementStub::GenerateAheadOfTime(isolate); } void CodeStub::GenerateFPStubs(Isolate* isolate) { SaveFPRegsMode mode = kSaveFPRegs; CEntryStub(isolate, 1, mode).GetCode(); } void CEntryStub::GenerateAheadOfTime(Isolate* isolate) { CEntryStub stub(isolate, 1, kDontSaveFPRegs); stub.GetCode(); CEntryStub save_doubles(isolate, 1, kSaveFPRegs); save_doubles.GetCode(); } void CEntryStub::Generate(MacroAssembler* masm) { // Called from JavaScript; parameters are on stack as if calling JS function. // r2: number of arguments including receiver // r3: pointer to builtin function // fp: frame pointer (restored after C call) // sp: stack pointer (restored as callee's sp after C call) // cp: current context (C callee-saved) // // If argv_in_register(): // r4: pointer to the first argument ProfileEntryHookStub::MaybeCallEntryHook(masm); __ LoadRR(r7, r3); if (argv_in_register()) { // Move argv into the correct register. __ LoadRR(r3, r4); } else { // Compute the argv pointer. __ ShiftLeftP(r3, r2, Operand(kPointerSizeLog2)); __ lay(r3, MemOperand(r3, sp, -kPointerSize)); } // Enter the exit frame that transitions from JavaScript to C++. FrameScope scope(masm, StackFrame::MANUAL); // Need at least one extra slot for return address location. int arg_stack_space = 1; // Pass buffer for return value on stack if necessary bool needs_return_buffer = result_size() == 2 && !ABI_RETURNS_OBJECTPAIR_IN_REGS; if (needs_return_buffer) { arg_stack_space += result_size(); } #if V8_TARGET_ARCH_S390X // 64-bit linux pass Argument object by reference not value arg_stack_space += 2; #endif __ EnterExitFrame(save_doubles(), arg_stack_space, is_builtin_exit() ? StackFrame::BUILTIN_EXIT : StackFrame::EXIT); // Store a copy of argc, argv in callee-saved registers for later. __ LoadRR(r6, r2); __ LoadRR(r8, r3); // r2, r6: number of arguments including receiver (C callee-saved) // r3, r8: pointer to the first argument // r7: pointer to builtin function (C callee-saved) // Result returned in registers or stack, depending on result size and ABI. Register isolate_reg = r4; if (needs_return_buffer) { // The return value is 16-byte non-scalar value. // Use frame storage reserved by calling function to pass return // buffer as implicit first argument in R2. Shfit original parameters // by one register each. __ LoadRR(r4, r3); __ LoadRR(r3, r2); __ la(r2, MemOperand(sp, (kStackFrameExtraParamSlot + 1) * kPointerSize)); isolate_reg = r5; } // Call C built-in. __ mov(isolate_reg, Operand(ExternalReference::isolate_address(isolate()))); Register target = r7; // To let the GC traverse the return address of the exit frames, we need to // know where the return address is. The CEntryStub is unmovable, so // we can store the address on the stack to be able to find it again and // we never have to restore it, because it will not change. { Label return_label; __ larl(r14, &return_label); // Generate the return addr of call later. __ StoreP(r14, MemOperand(sp, kStackFrameRASlot * kPointerSize)); // zLinux ABI requires caller's frame to have sufficient space for callee // preserved regsiter save area. // __ lay(sp, MemOperand(sp, -kCalleeRegisterSaveAreaSize)); __ b(target); __ bind(&return_label); // __ la(sp, MemOperand(sp, +kCalleeRegisterSaveAreaSize)); } // If return value is on the stack, pop it to registers. if (needs_return_buffer) { __ LoadP(r3, MemOperand(r2, kPointerSize)); __ LoadP(r2, MemOperand(r2)); } // Check result for exception sentinel. Label exception_returned; __ CompareRoot(r2, Heap::kExceptionRootIndex); __ beq(&exception_returned, Label::kNear); // Check that there is no pending exception, otherwise we // should have returned the exception sentinel. if (FLAG_debug_code) { Label okay; ExternalReference pending_exception_address( IsolateAddressId::kPendingExceptionAddress, isolate()); __ mov(r1, Operand(pending_exception_address)); __ LoadP(r1, MemOperand(r1)); __ CompareRoot(r1, Heap::kTheHoleValueRootIndex); // Cannot use check here as it attempts to generate call into runtime. __ beq(&okay, Label::kNear); __ stop("Unexpected pending exception"); __ bind(&okay); } // Exit C frame and return. // r2:r3: result // sp: stack pointer // fp: frame pointer Register argc = argv_in_register() // We don't want to pop arguments so set argc to no_reg. ? no_reg // r6: still holds argc (callee-saved). : r6; __ LeaveExitFrame(save_doubles(), argc); __ b(r14); // Handling of exception. __ bind(&exception_returned); ExternalReference pending_handler_context_address( IsolateAddressId::kPendingHandlerContextAddress, isolate()); ExternalReference pending_handler_entrypoint_address( IsolateAddressId::kPendingHandlerEntrypointAddress, isolate()); ExternalReference pending_handler_fp_address( IsolateAddressId::kPendingHandlerFPAddress, isolate()); ExternalReference pending_handler_sp_address( IsolateAddressId::kPendingHandlerSPAddress, isolate()); // Ask the runtime for help to determine the handler. This will set r3 to // contain the current pending exception, don't clobber it. ExternalReference find_handler(Runtime::kUnwindAndFindExceptionHandler, isolate()); { FrameScope scope(masm, StackFrame::MANUAL); __ PrepareCallCFunction(3, 0, r2); __ LoadImmP(r2, Operand::Zero()); __ LoadImmP(r3, Operand::Zero()); __ mov(r4, Operand(ExternalReference::isolate_address(isolate()))); __ CallCFunction(find_handler, 3); } // Retrieve the handler context, SP and FP. __ mov(cp, Operand(pending_handler_context_address)); __ LoadP(cp, MemOperand(cp)); __ mov(sp, Operand(pending_handler_sp_address)); __ LoadP(sp, MemOperand(sp)); __ mov(fp, Operand(pending_handler_fp_address)); __ LoadP(fp, MemOperand(fp)); // If the handler is a JS frame, restore the context to the frame. Note that // the context will be set to (cp == 0) for non-JS frames. Label skip; __ CmpP(cp, Operand::Zero()); __ beq(&skip, Label::kNear); __ StoreP(cp, MemOperand(fp, StandardFrameConstants::kContextOffset)); __ bind(&skip); // Reset the masking register. if (FLAG_branch_load_poisoning) { __ ResetSpeculationPoisonRegister(); } // Compute the handler entry address and jump to it. __ mov(r3, Operand(pending_handler_entrypoint_address)); __ LoadP(r3, MemOperand(r3)); __ Jump(r3); } void JSEntryStub::Generate(MacroAssembler* masm) { // r2: code entry // r3: function // r4: receiver // r5: argc // r6: argv Label invoke, handler_entry, exit; ProfileEntryHookStub::MaybeCallEntryHook(masm); // saving floating point registers #if V8_TARGET_ARCH_S390X // 64bit ABI requires f8 to f15 be saved __ lay(sp, MemOperand(sp, -8 * kDoubleSize)); __ std(d8, MemOperand(sp)); __ std(d9, MemOperand(sp, 1 * kDoubleSize)); __ std(d10, MemOperand(sp, 2 * kDoubleSize)); __ std(d11, MemOperand(sp, 3 * kDoubleSize)); __ std(d12, MemOperand(sp, 4 * kDoubleSize)); __ std(d13, MemOperand(sp, 5 * kDoubleSize)); __ std(d14, MemOperand(sp, 6 * kDoubleSize)); __ std(d15, MemOperand(sp, 7 * kDoubleSize)); #else // 31bit ABI requires you to store f4 and f6: // http://refspecs.linuxbase.org/ELF/zSeries/lzsabi0_s390.html#AEN417 __ lay(sp, MemOperand(sp, -2 * kDoubleSize)); __ std(d4, MemOperand(sp)); __ std(d6, MemOperand(sp, kDoubleSize)); #endif // zLinux ABI // Incoming parameters: // r2: code entry // r3: function // r4: receiver // r5: argc // r6: argv // Requires us to save the callee-preserved registers r6-r13 // General convention is to also save r14 (return addr) and // sp/r15 as well in a single STM/STMG __ lay(sp, MemOperand(sp, -10 * kPointerSize)); __ StoreMultipleP(r6, sp, MemOperand(sp, 0)); // Set up the reserved register for 0.0. // __ LoadDoubleLiteral(kDoubleRegZero, 0.0, r0); // Push a frame with special values setup to mark it as an entry frame. // Bad FP (-1) // SMI Marker // SMI Marker // kCEntryFPAddress // Frame type __ lay(sp, MemOperand(sp, -5 * kPointerSize)); // Push a bad frame pointer to fail if it is used. __ LoadImmP(r10, Operand(-1)); StackFrame::Type marker = type(); __ Load(r9, Operand(StackFrame::TypeToMarker(marker))); __ Load(r8, Operand(StackFrame::TypeToMarker(marker))); // Save copies of the top frame descriptor on the stack. __ mov(r7, Operand(ExternalReference(IsolateAddressId::kCEntryFPAddress, isolate()))); __ LoadP(r7, MemOperand(r7)); __ StoreMultipleP(r7, r10, MemOperand(sp, kPointerSize)); // Set up frame pointer for the frame to be pushed. // Need to add kPointerSize, because sp has one extra // frame already for the frame type being pushed later. __ lay(fp, MemOperand(sp, -EntryFrameConstants::kCallerFPOffset + kPointerSize)); __ InitializeRootRegister(); // If this is the outermost JS call, set js_entry_sp value. Label non_outermost_js; ExternalReference js_entry_sp(IsolateAddressId::kJSEntrySPAddress, isolate()); __ mov(r7, Operand(ExternalReference(js_entry_sp))); __ LoadAndTestP(r8, MemOperand(r7)); __ bne(&non_outermost_js, Label::kNear); __ StoreP(fp, MemOperand(r7)); __ Load(ip, Operand(StackFrame::OUTERMOST_JSENTRY_FRAME)); Label cont; __ b(&cont, Label::kNear); __ bind(&non_outermost_js); __ Load(ip, Operand(StackFrame::INNER_JSENTRY_FRAME)); __ bind(&cont); __ StoreP(ip, MemOperand(sp)); // frame-type // Jump to a faked try block that does the invoke, with a faked catch // block that sets the pending exception. __ b(&invoke, Label::kNear); __ bind(&handler_entry); handler_offset_ = handler_entry.pos(); // Caught exception: Store result (exception) in the pending exception // field in the JSEnv and return a failure sentinel. Coming in here the // fp will be invalid because the PushStackHandler below sets it to 0 to // signal the existence of the JSEntry frame. __ mov(ip, Operand(ExternalReference( IsolateAddressId::kPendingExceptionAddress, isolate()))); __ StoreP(r2, MemOperand(ip)); __ LoadRoot(r2, Heap::kExceptionRootIndex); __ b(&exit, Label::kNear); // Invoke: Link this frame into the handler chain. __ bind(&invoke); // Must preserve r2-r6. __ PushStackHandler(); // If an exception not caught by another handler occurs, this handler // returns control to the code after the b(&invoke) above, which // restores all kCalleeSaved registers (including cp and fp) to their // saved values before returning a failure to C. // Invoke the function by calling through JS entry trampoline builtin. // Notice that we cannot store a reference to the trampoline code directly in // this stub, because runtime stubs are not traversed when doing GC. // Expected registers by Builtins::JSEntryTrampoline // r2: code entry // r3: function // r4: receiver // r5: argc // r6: argv __ Call(EntryTrampoline(), RelocInfo::CODE_TARGET); // Unlink this frame from the handler chain. __ PopStackHandler(); __ bind(&exit); // r2 holds result // Check if the current stack frame is marked as the outermost JS frame. Label non_outermost_js_2; __ pop(r7); __ CmpP(r7, Operand(StackFrame::OUTERMOST_JSENTRY_FRAME)); __ bne(&non_outermost_js_2, Label::kNear); __ mov(r8, Operand::Zero()); __ mov(r7, Operand(ExternalReference(js_entry_sp))); __ StoreP(r8, MemOperand(r7)); __ bind(&non_outermost_js_2); // Restore the top frame descriptors from the stack. __ pop(r5); __ mov(ip, Operand(ExternalReference(IsolateAddressId::kCEntryFPAddress, isolate()))); __ StoreP(r5, MemOperand(ip)); // Reset the stack to the callee saved registers. __ lay(sp, MemOperand(sp, -EntryFrameConstants::kCallerFPOffset)); // Reload callee-saved preserved regs, return address reg (r14) and sp __ LoadMultipleP(r6, sp, MemOperand(sp, 0)); __ la(sp, MemOperand(sp, 10 * kPointerSize)); // saving floating point registers #if V8_TARGET_ARCH_S390X // 64bit ABI requires f8 to f15 be saved __ ld(d8, MemOperand(sp)); __ ld(d9, MemOperand(sp, 1 * kDoubleSize)); __ ld(d10, MemOperand(sp, 2 * kDoubleSize)); __ ld(d11, MemOperand(sp, 3 * kDoubleSize)); __ ld(d12, MemOperand(sp, 4 * kDoubleSize)); __ ld(d13, MemOperand(sp, 5 * kDoubleSize)); __ ld(d14, MemOperand(sp, 6 * kDoubleSize)); __ ld(d15, MemOperand(sp, 7 * kDoubleSize)); __ la(sp, MemOperand(sp, 8 * kDoubleSize)); #else // 31bit ABI requires you to store f4 and f6: // http://refspecs.linuxbase.org/ELF/zSeries/lzsabi0_s390.html#AEN417 __ ld(d4, MemOperand(sp)); __ ld(d6, MemOperand(sp, kDoubleSize)); __ la(sp, MemOperand(sp, 2 * kDoubleSize)); #endif __ b(r14); } // This stub is paired with DirectCEntryStub::GenerateCall void DirectCEntryStub::Generate(MacroAssembler* masm) { __ CleanseP(r14); __ b(ip); // Callee will return to R14 directly } void DirectCEntryStub::GenerateCall(MacroAssembler* masm, Register target) { #if ABI_USES_FUNCTION_DESCRIPTORS && !defined(USE_SIMULATOR) // Native AIX/S390X Linux use a function descriptor. __ LoadP(ToRegister(ABI_TOC_REGISTER), MemOperand(target, kPointerSize)); __ LoadP(target, MemOperand(target, 0)); // Instruction address #else // ip needs to be set for DirectCEentryStub::Generate, and also // for ABI_CALL_VIA_IP. __ Move(ip, target); #endif __ call(GetCode(), RelocInfo::CODE_TARGET); // Call the stub. } void ProfileEntryHookStub::MaybeCallEntryHookDelayed(TurboAssembler* tasm, Zone* zone) { if (tasm->isolate()->function_entry_hook() != nullptr) { PredictableCodeSizeScope predictable(tasm, #if V8_TARGET_ARCH_S390X 40); #elif V8_HOST_ARCH_S390 36); #else 32); #endif tasm->CleanseP(r14); tasm->Push(r14, ip); tasm->CallStubDelayed(new (zone) ProfileEntryHookStub(nullptr)); tasm->Pop(r14, ip); } } void ProfileEntryHookStub::MaybeCallEntryHook(MacroAssembler* masm) { if (masm->isolate()->function_entry_hook() != nullptr) { PredictableCodeSizeScope predictable(masm, #if V8_TARGET_ARCH_S390X 40); #elif V8_HOST_ARCH_S390 36); #else 32); #endif ProfileEntryHookStub stub(masm->isolate()); __ CleanseP(r14); __ Push(r14, ip); __ CallStub(&stub); // BRASL __ Pop(r14, ip); } } void ProfileEntryHookStub::Generate(MacroAssembler* masm) { // The entry hook is a "push lr" instruction (LAY+ST/STG), followed by a call. #if V8_TARGET_ARCH_S390X const int32_t kReturnAddressDistanceFromFunctionStart = Assembler::kCallTargetAddressOffset + 18; // LAY + STG * 2 #elif V8_HOST_ARCH_S390 const int32_t kReturnAddressDistanceFromFunctionStart = Assembler::kCallTargetAddressOffset + 18; // NILH + LAY + ST * 2 #else const int32_t kReturnAddressDistanceFromFunctionStart = Assembler::kCallTargetAddressOffset + 14; // LAY + ST * 2 #endif // This should contain all kJSCallerSaved registers. const RegList kSavedRegs = kJSCallerSaved | // Caller saved registers. r7.bit(); // Saved stack pointer. // We also save r14+ip, so count here is one higher than the mask indicates. const int32_t kNumSavedRegs = kNumJSCallerSaved + 3; // Save all caller-save registers as this may be called from anywhere. __ CleanseP(r14); __ LoadRR(ip, r14); __ MultiPush(kSavedRegs | ip.bit()); // Compute the function's address for the first argument. __ SubP(r2, ip, Operand(kReturnAddressDistanceFromFunctionStart)); // The caller's return address is two slots above the saved temporaries. // Grab that for the second argument to the hook. __ lay(r3, MemOperand(sp, kNumSavedRegs * kPointerSize)); // Align the stack if necessary. int frame_alignment = masm->ActivationFrameAlignment(); if (frame_alignment > kPointerSize) { __ LoadRR(r7, sp); DCHECK(base::bits::IsPowerOfTwo(frame_alignment)); __ ClearRightImm(sp, sp, Operand(WhichPowerOf2(frame_alignment))); } #if !defined(USE_SIMULATOR) uintptr_t entry_hook = reinterpret_cast<uintptr_t>(isolate()->function_entry_hook()); __ mov(ip, Operand(entry_hook)); #if ABI_USES_FUNCTION_DESCRIPTORS // Function descriptor __ LoadP(ToRegister(ABI_TOC_REGISTER), MemOperand(ip, kPointerSize)); __ LoadP(ip, MemOperand(ip, 0)); // ip already set. #endif #endif // zLinux ABI requires caller's frame to have sufficient space for callee // preserved regsiter save area. __ LoadImmP(r0, Operand::Zero()); __ lay(sp, MemOperand(sp, -kCalleeRegisterSaveAreaSize - kNumRequiredStackFrameSlots * kPointerSize)); __ StoreP(r0, MemOperand(sp)); #if defined(USE_SIMULATOR) // Under the simulator we need to indirect the entry hook through a // trampoline function at a known address. // It additionally takes an isolate as a third parameter __ mov(r4, Operand(ExternalReference::isolate_address(isolate()))); ApiFunction dispatcher(FUNCTION_ADDR(EntryHookTrampoline)); __ mov(ip, Operand(ExternalReference( &dispatcher, ExternalReference::BUILTIN_CALL, isolate()))); #endif __ Call(ip); // zLinux ABI requires caller's frame to have sufficient space for callee // preserved regsiter save area. __ la(sp, MemOperand(sp, kCalleeRegisterSaveAreaSize + kNumRequiredStackFrameSlots * kPointerSize)); // Restore the stack pointer if needed. if (frame_alignment > kPointerSize) { __ LoadRR(sp, r7); } // Also pop lr to get Ret(0). __ MultiPop(kSavedRegs | ip.bit()); __ LoadRR(r14, ip); __ Ret(); } template <class T> static void CreateArrayDispatch(MacroAssembler* masm, AllocationSiteOverrideMode mode) { if (mode == DISABLE_ALLOCATION_SITES) { T stub(masm->isolate(), GetInitialFastElementsKind(), mode); __ TailCallStub(&stub); } else if (mode == DONT_OVERRIDE) { int last_index = GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND); for (int i = 0; i <= last_index; ++i) { ElementsKind kind = GetFastElementsKindFromSequenceIndex(i); __ CmpP(r5, Operand(kind)); T stub(masm->isolate(), kind); __ TailCallStub(&stub, eq); } // If we reached this point there is a problem. __ Abort(AbortReason::kUnexpectedElementsKindInArrayConstructor); } else { UNREACHABLE(); } } static void CreateArrayDispatchOneArgument(MacroAssembler* masm, AllocationSiteOverrideMode mode) { // r4 - allocation site (if mode != DISABLE_ALLOCATION_SITES) // r5 - kind (if mode != DISABLE_ALLOCATION_SITES) // r2 - number of arguments // r3 - constructor? // sp[0] - last argument STATIC_ASSERT(PACKED_SMI_ELEMENTS == 0); STATIC_ASSERT(HOLEY_SMI_ELEMENTS == 1); STATIC_ASSERT(PACKED_ELEMENTS == 2); STATIC_ASSERT(HOLEY_ELEMENTS == 3); STATIC_ASSERT(PACKED_DOUBLE_ELEMENTS == 4); STATIC_ASSERT(HOLEY_DOUBLE_ELEMENTS == 5); if (mode == DISABLE_ALLOCATION_SITES) { ElementsKind initial = GetInitialFastElementsKind(); ElementsKind holey_initial = GetHoleyElementsKind(initial); ArraySingleArgumentConstructorStub stub_holey( masm->isolate(), holey_initial, DISABLE_ALLOCATION_SITES); __ TailCallStub(&stub_holey); } else if (mode == DONT_OVERRIDE) { Label normal_sequence; // is the low bit set? If so, we are holey and that is good. __ AndP(r0, r5, Operand(1)); __ bne(&normal_sequence); // We are going to create a holey array, but our kind is non-holey. // Fix kind and retry (only if we have an allocation site in the slot). __ AddP(r5, r5, Operand(1)); if (FLAG_debug_code) { __ LoadP(r7, FieldMemOperand(r4, 0)); __ CompareRoot(r7, Heap::kAllocationSiteMapRootIndex); __ Assert(eq, AbortReason::kExpectedAllocationSite); } // Save the resulting elements kind in type info. We can't just store r5 // in the AllocationSite::transition_info field because elements kind is // restricted to a portion of the field...upper bits need to be left alone. STATIC_ASSERT(AllocationSite::ElementsKindBits::kShift == 0); __ LoadP(r6, FieldMemOperand( r4, AllocationSite::kTransitionInfoOrBoilerplateOffset)); __ AddSmiLiteral(r6, r6, Smi::FromInt(kFastElementsKindPackedToHoley), r0); __ StoreP(r6, FieldMemOperand( r4, AllocationSite::kTransitionInfoOrBoilerplateOffset)); __ bind(&normal_sequence); int last_index = GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND); for (int i = 0; i <= last_index; ++i) { ElementsKind kind = GetFastElementsKindFromSequenceIndex(i); __ CmpP(r5, Operand(kind)); ArraySingleArgumentConstructorStub stub(masm->isolate(), kind); __ TailCallStub(&stub, eq); } // If we reached this point there is a problem. __ Abort(AbortReason::kUnexpectedElementsKindInArrayConstructor); } else { UNREACHABLE(); } } template <class T> static void ArrayConstructorStubAheadOfTimeHelper(Isolate* isolate) { int to_index = GetSequenceIndexFromFastElementsKind(TERMINAL_FAST_ELEMENTS_KIND); for (int i = 0; i <= to_index; ++i) { ElementsKind kind = GetFastElementsKindFromSequenceIndex(i); T stub(isolate, kind); stub.GetCode(); if (AllocationSite::ShouldTrack(kind)) { T stub1(isolate, kind, DISABLE_ALLOCATION_SITES); stub1.GetCode(); } } } void CommonArrayConstructorStub::GenerateStubsAheadOfTime(Isolate* isolate) { ArrayConstructorStubAheadOfTimeHelper<ArrayNoArgumentConstructorStub>( isolate); ArrayNArgumentsConstructorStub stub(isolate); stub.GetCode(); ElementsKind kinds[2] = {PACKED_ELEMENTS, HOLEY_ELEMENTS}; for (int i = 0; i < 2; i++) { // For internal arrays we only need a few things InternalArrayNoArgumentConstructorStub stubh1(isolate, kinds[i]); stubh1.GetCode(); InternalArraySingleArgumentConstructorStub stubh2(isolate, kinds[i]); stubh2.GetCode(); } } void ArrayConstructorStub::GenerateDispatchToArrayStub( MacroAssembler* masm, AllocationSiteOverrideMode mode) { Label not_zero_case, not_one_case; __ CmpP(r2, Operand::Zero()); __ bne(&not_zero_case); CreateArrayDispatch<ArrayNoArgumentConstructorStub>(masm, mode); __ bind(&not_zero_case); __ CmpP(r2, Operand(1)); __ bgt(&not_one_case); CreateArrayDispatchOneArgument(masm, mode); __ bind(&not_one_case); ArrayNArgumentsConstructorStub stub(masm->isolate()); __ TailCallStub(&stub); } void ArrayConstructorStub::Generate(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- r2 : argc (only if argument_count() == ANY) // -- r3 : constructor // -- r4 : AllocationSite or undefined // -- r5 : new target // -- sp[0] : return address // -- sp[4] : last argument // ----------------------------------- if (FLAG_debug_code) { // The array construct code is only set for the global and natives // builtin Array functions which always have maps. // Initial map for the builtin Array function should be a map. __ LoadP(r6, FieldMemOperand(r3, JSFunction::kPrototypeOrInitialMapOffset)); // Will both indicate a nullptr and a Smi. __ TestIfSmi(r6); __ Assert(ne, AbortReason::kUnexpectedInitialMapForArrayFunction, cr0); __ CompareObjectType(r6, r6, r7, MAP_TYPE); __ Assert(eq, AbortReason::kUnexpectedInitialMapForArrayFunction); // We should either have undefined in r4 or a valid AllocationSite __ AssertUndefinedOrAllocationSite(r4, r6); } // Enter the context of the Array function. __ LoadP(cp, FieldMemOperand(r3, JSFunction::kContextOffset)); Label subclassing; __ CmpP(r5, r3); __ bne(&subclassing, Label::kNear); Label no_info; // Get the elements kind and case on that. __ CompareRoot(r4, Heap::kUndefinedValueRootIndex); __ beq(&no_info); __ LoadP(r5, FieldMemOperand( r4, AllocationSite::kTransitionInfoOrBoilerplateOffset)); __ SmiUntag(r5); STATIC_ASSERT(AllocationSite::ElementsKindBits::kShift == 0); __ AndP(r5, Operand(AllocationSite::ElementsKindBits::kMask)); GenerateDispatchToArrayStub(masm, DONT_OVERRIDE); __ bind(&no_info); GenerateDispatchToArrayStub(masm, DISABLE_ALLOCATION_SITES); __ bind(&subclassing); __ ShiftLeftP(r1, r2, Operand(kPointerSizeLog2)); __ StoreP(r3, MemOperand(sp, r1)); __ AddP(r2, r2, Operand(3)); __ Push(r5, r4); __ JumpToExternalReference(ExternalReference(Runtime::kNewArray, isolate())); } void InternalArrayConstructorStub::GenerateCase(MacroAssembler* masm, ElementsKind kind) { __ CmpLogicalP(r2, Operand(1)); InternalArrayNoArgumentConstructorStub stub0(isolate(), kind); __ TailCallStub(&stub0, lt); ArrayNArgumentsConstructorStub stubN(isolate()); __ TailCallStub(&stubN, gt); if (IsFastPackedElementsKind(kind)) { // We might need to create a holey array // look at the first argument __ LoadP(r5, MemOperand(sp, 0)); __ CmpP(r5, Operand::Zero()); InternalArraySingleArgumentConstructorStub stub1_holey( isolate(), GetHoleyElementsKind(kind)); __ TailCallStub(&stub1_holey, ne); } InternalArraySingleArgumentConstructorStub stub1(isolate(), kind); __ TailCallStub(&stub1); } void InternalArrayConstructorStub::Generate(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- r2 : argc // -- r3 : constructor // -- sp[0] : return address // -- sp[4] : last argument // ----------------------------------- if (FLAG_debug_code) { // The array construct code is only set for the global and natives // builtin Array functions which always have maps. // Initial map for the builtin Array function should be a map. __ LoadP(r5, FieldMemOperand(r3, JSFunction::kPrototypeOrInitialMapOffset)); // Will both indicate a nullptr and a Smi. __ TestIfSmi(r5); __ Assert(ne, AbortReason::kUnexpectedInitialMapForArrayFunction, cr0); __ CompareObjectType(r5, r5, r6, MAP_TYPE); __ Assert(eq, AbortReason::kUnexpectedInitialMapForArrayFunction); } // Figure out the right elements kind __ LoadP(r5, FieldMemOperand(r3, JSFunction::kPrototypeOrInitialMapOffset)); // Load the map's "bit field 2" into |result|. __ LoadlB(r5, FieldMemOperand(r5, Map::kBitField2Offset)); // Retrieve elements_kind from bit field 2. __ DecodeField<Map::ElementsKindBits>(r5); if (FLAG_debug_code) { Label done; __ CmpP(r5, Operand(PACKED_ELEMENTS)); __ beq(&done); __ CmpP(r5, Operand(HOLEY_ELEMENTS)); __ Assert( eq, AbortReason::kInvalidElementsKindForInternalArrayOrInternalPackedArray); __ bind(&done); } Label fast_elements_case; __ CmpP(r5, Operand(PACKED_ELEMENTS)); __ beq(&fast_elements_case); GenerateCase(masm, HOLEY_ELEMENTS); __ bind(&fast_elements_case); GenerateCase(masm, PACKED_ELEMENTS); } static int AddressOffset(ExternalReference ref0, ExternalReference ref1) { return ref0.address() - ref1.address(); } // Calls an API function. Allocates HandleScope, extracts returned value // from handle and propagates exceptions. Restores context. stack_space // - space to be unwound on exit (includes the call JS arguments space and // the additional space allocated for the fast call). static void CallApiFunctionAndReturn(MacroAssembler* masm, Register function_address, ExternalReference thunk_ref, int stack_space, MemOperand* stack_space_operand, MemOperand return_value_operand) { Isolate* isolate = masm->isolate(); ExternalReference next_address = ExternalReference::handle_scope_next_address(isolate); const int kNextOffset = 0; const int kLimitOffset = AddressOffset( ExternalReference::handle_scope_limit_address(isolate), next_address); const int kLevelOffset = AddressOffset( ExternalReference::handle_scope_level_address(isolate), next_address); // Additional parameter is the address of the actual callback. DCHECK(function_address == r3 || function_address == r4); Register scratch = r5; __ mov(scratch, Operand(ExternalReference::is_profiling_address(isolate))); __ LoadlB(scratch, MemOperand(scratch, 0)); __ CmpP(scratch, Operand::Zero()); Label profiler_disabled; Label end_profiler_check; __ beq(&profiler_disabled, Label::kNear); __ mov(scratch, Operand(thunk_ref)); __ b(&end_profiler_check, Label::kNear); __ bind(&profiler_disabled); __ LoadRR(scratch, function_address); __ bind(&end_profiler_check); // Allocate HandleScope in callee-save registers. // r9 - next_address // r6 - next_address->kNextOffset // r7 - next_address->kLimitOffset // r8 - next_address->kLevelOffset __ mov(r9, Operand(next_address)); __ LoadP(r6, MemOperand(r9, kNextOffset)); __ LoadP(r7, MemOperand(r9, kLimitOffset)); __ LoadlW(r8, MemOperand(r9, kLevelOffset)); __ AddP(r8, Operand(1)); __ StoreW(r8, MemOperand(r9, kLevelOffset)); if (FLAG_log_timer_events) { FrameScope frame(masm, StackFrame::MANUAL); __ PushSafepointRegisters(); __ PrepareCallCFunction(1, r2); __ mov(r2, Operand(ExternalReference::isolate_address(isolate))); __ CallCFunction(ExternalReference::log_enter_external_function(isolate), 1); __ PopSafepointRegisters(); } // Native call returns to the DirectCEntry stub which redirects to the // return address pushed on stack (could have moved after GC). // DirectCEntry stub itself is generated early and never moves. DirectCEntryStub stub(isolate); stub.GenerateCall(masm, scratch); if (FLAG_log_timer_events) { FrameScope frame(masm, StackFrame::MANUAL); __ PushSafepointRegisters(); __ PrepareCallCFunction(1, r2); __ mov(r2, Operand(ExternalReference::isolate_address(isolate))); __ CallCFunction(ExternalReference::log_leave_external_function(isolate), 1); __ PopSafepointRegisters(); } Label promote_scheduled_exception; Label delete_allocated_handles; Label leave_exit_frame; Label return_value_loaded; // load value from ReturnValue __ LoadP(r2, return_value_operand); __ bind(&return_value_loaded); // No more valid handles (the result handle was the last one). Restore // previous handle scope. __ StoreP(r6, MemOperand(r9, kNextOffset)); if (__ emit_debug_code()) { __ LoadlW(r3, MemOperand(r9, kLevelOffset)); __ CmpP(r3, r8); __ Check(eq, AbortReason::kUnexpectedLevelAfterReturnFromApiCall); } __ SubP(r8, Operand(1)); __ StoreW(r8, MemOperand(r9, kLevelOffset)); __ CmpP(r7, MemOperand(r9, kLimitOffset)); __ bne(&delete_allocated_handles, Label::kNear); // Leave the API exit frame. __ bind(&leave_exit_frame); // LeaveExitFrame expects unwind space to be in a register. if (stack_space_operand != nullptr) { __ l(r6, *stack_space_operand); } else { __ mov(r6, Operand(stack_space)); } __ LeaveExitFrame(false, r6, stack_space_operand != nullptr); // Check if the function scheduled an exception. __ mov(r7, Operand(ExternalReference::scheduled_exception_address(isolate))); __ LoadP(r7, MemOperand(r7)); __ CompareRoot(r7, Heap::kTheHoleValueRootIndex); __ bne(&promote_scheduled_exception, Label::kNear); __ b(r14); // Re-throw by promoting a scheduled exception. __ bind(&promote_scheduled_exception); __ TailCallRuntime(Runtime::kPromoteScheduledException); // HandleScope limit has changed. Delete allocated extensions. __ bind(&delete_allocated_handles); __ StoreP(r7, MemOperand(r9, kLimitOffset)); __ LoadRR(r6, r2); __ PrepareCallCFunction(1, r7); __ mov(r2, Operand(ExternalReference::isolate_address(isolate))); __ CallCFunction(ExternalReference::delete_handle_scope_extensions(isolate), 1); __ LoadRR(r2, r6); __ b(&leave_exit_frame, Label::kNear); } void CallApiCallbackStub::Generate(MacroAssembler* masm) { // ----------- S t a t e ------------- // -- r6 : call_data // -- r4 : holder // -- r3 : api_function_address // -- cp : context // -- // -- sp[0] : last argument // -- ... // -- sp[(argc - 1) * 4] : first argument // -- sp[argc * 4] : receiver // ----------------------------------- Register call_data = r6; Register holder = r4; Register api_function_address = r3; typedef FunctionCallbackArguments FCA; STATIC_ASSERT(FCA::kArgsLength == 6); STATIC_ASSERT(FCA::kNewTargetIndex == 5); STATIC_ASSERT(FCA::kDataIndex == 4); STATIC_ASSERT(FCA::kReturnValueOffset == 3); STATIC_ASSERT(FCA::kReturnValueDefaultValueIndex == 2); STATIC_ASSERT(FCA::kIsolateIndex == 1); STATIC_ASSERT(FCA::kHolderIndex == 0); // new target __ PushRoot(Heap::kUndefinedValueRootIndex); // call data __ push(call_data); Register scratch = call_data; __ LoadRoot(scratch, Heap::kUndefinedValueRootIndex); // return value __ push(scratch); // return value default __ push(scratch); // isolate __ mov(scratch, Operand(ExternalReference::isolate_address(masm->isolate()))); __ push(scratch); // holder __ push(holder); // Prepare arguments. __ LoadRR(scratch, sp); // Allocate the v8::Arguments structure in the arguments' space since // it's not controlled by GC. // S390 LINUX ABI: // // Create 4 extra slots on stack: // [0] space for DirectCEntryStub's LR save // [1-3] FunctionCallbackInfo const int kApiStackSpace = 4; const int kFunctionCallbackInfoOffset = (kStackFrameExtraParamSlot + 1) * kPointerSize; FrameScope frame_scope(masm, StackFrame::MANUAL); __ EnterExitFrame(false, kApiStackSpace); DCHECK(api_function_address != r2 && scratch != r2); // r2 = FunctionCallbackInfo& // Arguments is after the return address. __ AddP(r2, sp, Operand(kFunctionCallbackInfoOffset)); // FunctionCallbackInfo::implicit_args_ __ StoreP(scratch, MemOperand(r2, 0 * kPointerSize)); // FunctionCallbackInfo::values_ __ AddP(ip, scratch, Operand((FCA::kArgsLength - 1 + argc()) * kPointerSize)); __ StoreP(ip, MemOperand(r2, 1 * kPointerSize)); // FunctionCallbackInfo::length_ = argc __ LoadImmP(ip, Operand(argc())); __ StoreW(ip, MemOperand(r2, 2 * kPointerSize)); ExternalReference thunk_ref = ExternalReference::invoke_function_callback(masm->isolate()); AllowExternalCallThatCantCauseGC scope(masm); // Stores return the first js argument int return_value_offset = 2 + FCA::kReturnValueOffset; MemOperand return_value_operand(fp, return_value_offset * kPointerSize); const int stack_space = argc() + FCA::kArgsLength + 1; MemOperand* stack_space_operand = nullptr; CallApiFunctionAndReturn(masm, api_function_address, thunk_ref, stack_space, stack_space_operand, return_value_operand); } void CallApiGetterStub::Generate(MacroAssembler* masm) { int arg0Slot = 0; int accessorInfoSlot = 0; int apiStackSpace = 0; // Build v8::PropertyCallbackInfo::args_ array on the stack and push property // name below the exit frame to make GC aware of them. STATIC_ASSERT(PropertyCallbackArguments::kShouldThrowOnErrorIndex == 0); STATIC_ASSERT(PropertyCallbackArguments::kHolderIndex == 1); STATIC_ASSERT(PropertyCallbackArguments::kIsolateIndex == 2); STATIC_ASSERT(PropertyCallbackArguments::kReturnValueDefaultValueIndex == 3); STATIC_ASSERT(PropertyCallbackArguments::kReturnValueOffset == 4); STATIC_ASSERT(PropertyCallbackArguments::kDataIndex == 5); STATIC_ASSERT(PropertyCallbackArguments::kThisIndex == 6); STATIC_ASSERT(PropertyCallbackArguments::kArgsLength == 7); Register receiver = ApiGetterDescriptor::ReceiverRegister(); Register holder = ApiGetterDescriptor::HolderRegister(); Register callback = ApiGetterDescriptor::CallbackRegister(); Register scratch = r6; DCHECK(!AreAliased(receiver, holder, callback, scratch)); Register api_function_address = r4; __ push(receiver); // Push data from AccessorInfo. __ LoadP(scratch, FieldMemOperand(callback, AccessorInfo::kDataOffset)); __ push(scratch); __ LoadRoot(scratch, Heap::kUndefinedValueRootIndex); __ Push(scratch, scratch); __ mov(scratch, Operand(ExternalReference::isolate_address(isolate()))); __ Push(scratch, holder); __ Push(Smi::kZero); // should_throw_on_error -> false __ LoadP(scratch, FieldMemOperand(callback, AccessorInfo::kNameOffset)); __ push(scratch); // v8::PropertyCallbackInfo::args_ array and name handle. const int kStackUnwindSpace = PropertyCallbackArguments::kArgsLength + 1; // Load address of v8::PropertyAccessorInfo::args_ array and name handle. __ LoadRR(r2, sp); // r2 = Handle<Name> __ AddP(r3, r2, Operand(1 * kPointerSize)); // r3 = v8::PCI::args_ // If ABI passes Handles (pointer-sized struct) in a register: // // Create 2 extra slots on stack: // [0] space for DirectCEntryStub's LR save // [1] AccessorInfo& // // Otherwise: // // Create 3 extra slots on stack: // [0] space for DirectCEntryStub's LR save // [1] copy of Handle (first arg) // [2] AccessorInfo& if (ABI_PASSES_HANDLES_IN_REGS) { accessorInfoSlot = kStackFrameExtraParamSlot + 1; apiStackSpace = 2; } else { arg0Slot = kStackFrameExtraParamSlot + 1; accessorInfoSlot = arg0Slot + 1; apiStackSpace = 3; } FrameScope frame_scope(masm, StackFrame::MANUAL); __ EnterExitFrame(false, apiStackSpace); if (!ABI_PASSES_HANDLES_IN_REGS) { // pass 1st arg by reference __ StoreP(r2, MemOperand(sp, arg0Slot * kPointerSize)); __ AddP(r2, sp, Operand(arg0Slot * kPointerSize)); } // Create v8::PropertyCallbackInfo object on the stack and initialize // it's args_ field. __ StoreP(r3, MemOperand(sp, accessorInfoSlot * kPointerSize)); __ AddP(r3, sp, Operand(accessorInfoSlot * kPointerSize)); // r3 = v8::PropertyCallbackInfo& ExternalReference thunk_ref = ExternalReference::invoke_accessor_getter_callback(isolate()); __ LoadP(scratch, FieldMemOperand(callback, AccessorInfo::kJsGetterOffset)); __ LoadP(api_function_address, FieldMemOperand(scratch, Foreign::kForeignAddressOffset)); // +3 is to skip prolog, return address and name handle. MemOperand return_value_operand( fp, (PropertyCallbackArguments::kReturnValueOffset + 3) * kPointerSize); CallApiFunctionAndReturn(masm, api_function_address, thunk_ref, kStackUnwindSpace, nullptr, return_value_operand); } #undef __ } // namespace internal } // namespace v8 #endif // V8_TARGET_ARCH_S390
35.976866
80
0.698314
[ "object" ]
c8b6e35adc06ab92ee8632e77bacaf80eeaf0a7e
5,444
hpp
C++
third-party/Empirical/include/emp/web/FileInput.hpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
third-party/Empirical/include/emp/web/FileInput.hpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
third-party/Empirical/include/emp/web/FileInput.hpp
koellingh/empirical-p53-simulator
aa6232f661e8fc65852ab6d3e809339557af521b
[ "MIT" ]
null
null
null
/** * @note This file is part of Empirical, https://github.com/devosoft/Empirical * @copyright Copyright (C) Michigan State University, MIT Software license; see doc/LICENSE.md * @date 2015-2018 * * @file FileInput.hpp * @brief Specs for the FileInput widget (click on to upload a file) * * @todo Setup FileInput to work outside of web mode as well. */ #ifndef EMP_WEB_FILE_INPUT_H #define EMP_WEB_FILE_INPUT_H #include <functional> #include <string> #include "../io/File.hpp" #include "Widget.hpp" namespace emp { namespace web { /// FileInput will convert the file to a std::string and pass the result to a /// designated function. /// /// To create a new file input, you must pass it a void function that takes a /// const std::string & as its only argument. When a file is loaded, the /// specified function is called and the body of the file is passed in as the /// string. class FileInput : public internal::WidgetFacet<FileInput> { friend class FileInputInfo; protected: // FileInputs associated with the same DOM element share a single FileInputInfo object. class FileInputInfo : public internal::WidgetInfo { friend FileInput; protected: bool autofocus; bool disabled; std::function<void(const std::string &)> callback; uint32_t callback_id; FileInputInfo(const std::string & in_id="") : internal::WidgetInfo(in_id) { ; } FileInputInfo(const FileInputInfo &) = delete; // No copies of INFO allowed FileInputInfo & operator=(const FileInputInfo &) = delete; // No copies of INFO allowed virtual ~FileInputInfo() { if (callback_id) emp::JSDelete(callback_id); // Delete callback wrapper. } std::string GetTypeName() const override { return "FileInputInfo"; } void DoCallback(const std::string & file_body) { callback(file_body); UpdateDependants(); } virtual void GetHTML(std::stringstream & HTML) override { HTML.str(""); // Clear the current text. HTML <<"<input type=\"file\""; if (disabled) { HTML << " disabled=true"; } // Check if should be disabled HTML << " id=\"" << id << "\""; // Indicate ID. HTML << " name=\"" << id << "\""; // Use same name as ID HTML << " onchange=\"emp.LoadFileEvent(this.files, " << callback_id << ")\""; HTML << ">"; } void UpdateCallback(const std::function<void(const std::string &)> & in_cb) { callback = in_cb; } void UpdateAutofocus(bool in_af) { autofocus = in_af; if (state == Widget::ACTIVE) ReplaceHTML(); // If node is active, immediately redraw! } void UpdateDisabled(bool in_dis) { disabled = in_dis; if (state == Widget::ACTIVE) ReplaceHTML(); // If node is active, immediately redraw! } public: virtual std::string GetType() override { return "web::FileInputInfo"; } }; // End of FileInputInfo definition // Get a properly cast version of indo. FileInputInfo * Info() { return (FileInputInfo *) info; } const FileInputInfo * Info() const { return (FileInputInfo *) info; } FileInput(FileInputInfo * in_info) : WidgetFacet(in_info) { ; } public: /// Create a new Fileinput; supply the function to call with the file contents as a string /// (and optionally the HTML identifier to be used). FileInput(const std::function<void(const std::string &)> & in_cb, const std::string & in_id="") : WidgetFacet(in_id) { info = new FileInputInfo(in_id); Info()->autofocus = false; Info()->disabled = false; Info()->callback = in_cb; FileInputInfo * w_info = Info(); using callback_t = std::function<void(const std::string & file_body)>; Info()->callback_id = JSWrap( callback_t( [w_info](const std::string & file_body){w_info->DoCallback(file_body);} ) ); } /// Create a new FileInput; supply the function to call with the file contents as a File object /// (and optionally the HTML identifier to be used). FileInput(const std::function<void(const emp::File &)> & cb, const std::string & in_id="") : FileInput( [cb](const std::string & in){ std::stringstream ss(in); File file(ss); cb(file); } ) { ; } /// Load a pre-existing FileInput object. FileInput(const FileInput & in) : WidgetFacet(in) { ; } FileInput(const Widget & in) : WidgetFacet(in) { ; } virtual ~FileInput() { ; } using INFO_TYPE = FileInputInfo; /// Change the callback function to use when a new file is loaded. FileInput & Callback(const std::function<void(const std::string &)> & in_cb) { Info()->UpdateCallback(in_cb); return *this; } /// Set this FileInput object to have autofocus (or not) FileInput & Autofocus(bool in_af) { Info()->UpdateAutofocus(in_af); return *this; } /// Set this FileInput object to be disabled (or renable it.) FileInput & Disabled(bool in_dis) { Info()->UpdateDisabled(in_dis); return *this; } /// Determine if this object currently has autofocus. bool HasAutofocus() const { return Info()->autofocus; } /// Determine if this object is currently disabled. bool IsDisabled() const { return Info()->disabled; } }; } } #endif
37.034014
125
0.627296
[ "object" ]
c8b7f69d92d3447cbfd658cbb24c001a2cec2082
10,233
cpp
C++
source/script/python/RenderModule.cpp
freneticmonkey/epsilonc
0fb7c6c4c6342a770e2882bfd67ed34719e79066
[ "MIT" ]
null
null
null
source/script/python/RenderModule.cpp
freneticmonkey/epsilonc
0fb7c6c4c6342a770e2882bfd67ed34719e79066
[ "MIT" ]
null
null
null
source/script/python/RenderModule.cpp
freneticmonkey/epsilonc
0fb7c6c4c6342a770e2882bfd67ed34719e79066
[ "MIT" ]
null
null
null
#include "script/python/RenderModule.h" #include "script/ScriptCommon.h" #include "scene/Object.h" #include "math/Vector.h" #include "scene/NodeComponent.h" #include "render/RenderManager.h" #include "render/Camera.h" #include "render/Colour.h" #include "render/Light.h" #include "render/Renderer.h" #include "render/material/Material.h" #include "render/material/Shader.h" #include "render/material/ShaderUniform.h" #include "render/texture/Texture.h" #include "render/mesh/Mesh.h" #include "render/mesh/MeshFactory.h" #include "render/mesh/VertexData.h" #include "render/gizmos/GizmoCube.h" #include "resource/Resource.h" // Colour Python Helper Functions void colour_setitem(Colour& v, int index, float value) { int MAX = 4; if ( index < 0 ) index += MAX; if (index >= 0 && index < MAX) { v[index] = value; } else { PyErr_SetString(PyExc_IndexError, "index out of range"); throw_error_already_set(); } } float colour_getitem(Colour&v, int index) { int MAX = 4; float returnVal = 0.f; if ( index < 0 ) index += MAX; if (index >= 0 && index < MAX) { returnVal = v[index]; } else { PyErr_SetString(PyExc_IndexError, "index out of range"); throw_error_already_set(); } return returnVal; } BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS( MeshCreate, Mesh::Create, 0, 1 ) BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS( VertexDataCreate, VertexData::Create, 0, 1 ) enum OpenGLDrawTypes { TRIANGLES = GL_TRIANGLES, LINES = GL_LINES, POINTS_ = GL_POINTS, LINE_STRIP = GL_LINE_STRIP, LINE_LOOP = GL_LINE_LOOP, TRIANGLE_STRIP = GL_TRIANGLE_STRIP, TRIANGLE_FAN = GL_TRIANGLE_FAN }; void initRender() { // make Render package object renderModule( handle<>( borrowed( PyImport_AddModule("epsilon.render") ) ) ); scope().attr("render") = renderModule; scope renderScope = renderModule; enum_<OpenGLDrawTypes>("DrawTypes") .value("TRIANGLES", OpenGLDrawTypes::TRIANGLES) .value("LINES", OpenGLDrawTypes::LINES) .value("POINTS", OpenGLDrawTypes::POINTS_) .value("LINE_STRIP", OpenGLDrawTypes::LINE_STRIP) .value("LINE_LOOP", OpenGLDrawTypes::LINE_LOOP) .value("TRIANGLE_STRIP", OpenGLDrawTypes::TRIANGLE_STRIP) .value("TRIANGLE_FAN", OpenGLDrawTypes::TRIANGLE_FAN) ; class_<Mesh, bases<Object, Resource>, Mesh::Ptr, boost::noncopyable>("Mesh", no_init) .def("create", &Mesh::Create, (python::arg("type") = (GLenum)(GL_TRIANGLES) )) .staticmethod("create") .def("get_vertexdata", &Mesh::VertexData) .add_property("type", &Mesh::GetMeshType) .add_property("parameters", &Mesh::GetMeshParameters) ; //implicitly_convertible<Mesh::Ptr, Resource::Ptr>(); Renderer::Ptr (*RendererCreateStandard)() = &Renderer::Create; Renderer::Ptr (*RendererCreateMesh)(Mesh::Ptr) = &Renderer::Create; Renderer::Ptr (*RendererCreateMeshMaterial)(Mesh::Ptr, Material::Ptr) = &Renderer::Create; class_<Renderer, bases<NodeComponent>, Renderer::Ptr, boost::noncopyable>("Renderer", no_init) .def("create",RendererCreateStandard) .def("create",RendererCreateMesh) .def("create",RendererCreateMeshMaterial) .staticmethod("create") //.def("draw", &Renderer::Draw) .add_property("mesh", &Renderer::GetMesh, &Renderer::SetMesh) .add_property("material", &Renderer::GetMaterial, &Renderer::SetMaterial) .def("set_mesh", &Renderer::SetMesh) .def("set_mesh", &Renderer::SetMeshByName) .def("get_mesh", &Renderer::GetMesh) ; implicitly_convertible<Renderer::Ptr, NodeComponent::Ptr>(); class_<VertexData, VertexData::Ptr, boost::noncopyable>("VertexData", no_init) //.def("create", &VertexData::Create) //.staticmethod("create") .def("set_vertices", &VertexData::SetVertices) .def("set_normals", &VertexData::SetNormals) .def("set_colours", &VertexData::SetColours) .def("set_tex_coords", &VertexData::SetTexCoords) .def("set_indices", &VertexData::SetIndices) .def("get_vertex_index", &VertexData::GetVertexIndex) .def("get_normal_index", &VertexData::GetNormalIndex) .def("get_colour_index", &VertexData::GetColourIndex) .def("get_tex_coord_index", &VertexData::GetTexCoordIndex) .def("build_buffers", &VertexData::BuildBuffers) ; class_<MeshFactory>("MeshFactory", no_init) .def("generate_grid", &MeshFactory::GenerateGrid) .staticmethod("generate_grid") .def("generate_cube", &MeshFactory::GenerateCube) .staticmethod("generate_cube") .def("generate_wire_cube", &MeshFactory::GenerateWireCube) .staticmethod("generate_wire_cube") .def("generate_sphere", &MeshFactory::GenerateSphere) .staticmethod("generate_sphere") .def("generate_wire_sphere", &MeshFactory::GenerateWireSphere) .staticmethod("generate_wire_sphere") .def("generate_plane", &MeshFactory::GeneratePlane) .staticmethod("generate_plane") .def("generate_triangle", &MeshFactory::GenerateTriangle) .staticmethod("generate_triangle") .def("generate_icohedron", &MeshFactory::GenerateIcoHedron) .staticmethod("generate_icohedron") .def("generate_octohedron", &MeshFactory::GenerateOctohedron) .staticmethod("generate_octohedron") ; class_<Colour>("Colour") .def(init<float>()) .def(init<float, float, float, float>()) .def("from_vector4", &Colour::FromVector4) .staticmethod("from_vector4") .def_readwrite("r", &Colour::r) .def_readwrite("g", &Colour::g) .def_readwrite("b", &Colour::b) .def_readwrite("a", &Colour::a) .def("__str__", &Colour::ToString) .def("__getitem__", &colour_getitem) .def("__setitem__", &colour_setitem) .def(self == self) .def(self != self) .def(self == Vector4()) .def(self != Vector4()) .def("from_hex", &Colour::FromHex) .staticmethod("from_hex") .def("to_8bit", &Colour::To8bit) .def("invert", &Colour::Invert) .def("inverted", &Colour::Inverted) .def("tint", &Colour::Tint) .def("tinted", &Colour::Tinted) .def_readonly("RED", &Colour::RED) .def_readonly("GREEN", &Colour::GREEN) .def_readonly("BLUE", &Colour::BLUE) .def_readonly("YELLOW", &Colour::YELLOW) .def_readonly("ORANGE", &Colour::ORANGE) .def_readonly("CYAN", &Colour::CYAN) .def_readonly("PURPLE", &Colour::PURPLE) .def_readonly("BLACK", &Colour::BLACK) .def_readonly("GREY", &Colour::GREY) ; class_<Material, Material::Ptr, boost::noncopyable>("Material", no_init) .add_property("name", &Material::GetName) // Colour Information .def_readwrite("ambient", &Material::ambient) .def_readwrite("diffuse", &Material::diffuse) .def_readwrite("specular", &Material::specular) .def_readwrite("reflectance", &Material::reflectance) // Texture Access .def("add_texture", &Material::AddTexture) .def("add_texture_by_name", &Material::AddTextureByName) .def("add_texture_by_path", &Material::AddTextureByPath) .def("get_textures", &Material::GetTextures) // Shader Access .add_property("shader", &Material::GetShader, &Material::SetShader) ; // Shader and Shader Uniform access enum_<ShaderUniform::OpenGLTypes>("ShaderUniformType") .value("INT", ShaderUniform::OpenGLTypes::INT) .value("FLOAT", ShaderUniform::OpenGLTypes::FLOAT) .value("VECTOR2", ShaderUniform::OpenGLTypes::VECTOR2) .value("VECTOR3", ShaderUniform::OpenGLTypes::VECTOR3) .value("VECTOR4", ShaderUniform::OpenGLTypes::VECTOR4) .value("MATRIX", ShaderUniform::OpenGLTypes::MATRIX) ; class_<ShaderUniform, ShaderUniform::Ptr, boost::noncopyable>("ShaderUniform", no_init) .add_property("changed", &ShaderUniform::HasChanged) .add_property("type", &ShaderUniform::GetType) .add_property("float", &ShaderUniform::GetFloat, &ShaderUniform::SetFloat) .add_property("vector2", &ShaderUniform::GetVector2, &ShaderUniform::SetVector2) .add_property("vector3", &ShaderUniform::GetVector3, &ShaderUniform::SetVector3) .add_property("vector4", &ShaderUniform::GetVector4, &ShaderUniform::SetVector4) .add_property("matrix4", &ShaderUniform::GetMatrix4, &ShaderUniform::SetMatrix4) ; class_<Shader, Shader::Ptr, boost::noncopyable>("Shader", no_init) .add_property("name", &Shader::GetName) .def("get_uniform", &Shader::GetUniform) ; class_<Camera, bases<NodeComponent>, Camera::Ptr, boost::noncopyable>("Camera", no_init) .def("get_projection_matrix", &Camera::GetProjectionMatrix) .def("get_view_matrix", &Camera::GetViewMatrix) .def("screen_to_world", &Camera::ScreenToWorldCoordinate) .def("world_to_screen", &Camera::WorldToScreenCoordinate) ; implicitly_convertible<Camera::Ptr, NodeComponent::Ptr>(); // Lighting enum_<Light::Type>("LightType") .value("POINT", Light::Type::POINT) .value("SPOT", Light::Type::SPOT) .value("DIRECTIONAL", Light::Type::DIRECTIONAL) .value("SUN", Light::Type::SUN) ; enum_<Light::ShadowType>("LightShadowType") .value("NONE", Light::ShadowType::NONE) .value("HARD", Light::ShadowType::HARD) .value("SOFT", Light::ShadowType::SOFT) ; class_<Light, bases<NodeComponent>, Light::Ptr, boost::noncopyable>("Light", no_init) .def("position", &Light::GetPosition) .def("direction", &Light::GetDirection) .def_readwrite("ambient", &Light::ambient) .def_readwrite("diffuse", &Light::diffuse) .def_readwrite("specular", &Light::specular) .def_readwrite("attenuation", &Light::attenuation) .def_readwrite("stength", &Light::strength) .def_readwrite("spot_cutoff", &Light::spotCutoff) .def_readwrite("spot_exponent", &Light::spotExponent) .def_readwrite("type", &Light::type) .def_readwrite("shadow_type", &Light::shadowType) ; class_<Texture, bases<Resource>, Texture::Ptr, boost::noncopyable>("Texture", no_init) .add_property("name", &Texture::GetName) .add_property("width", &Texture::GetWidth) .add_property("height", &Texture::GetHeight) .add_property("size", &Texture::GetSize) .add_property("on_gpu", &Texture::OnGPU) ; class_<Textures>("Textures") .def("__iter__", python::iterator<Textures>()) .def("__len__", &Textures::size) ; object renderConstModule(handle<>(borrowed(PyImport_AddModule("epsilon.render.const")))); renderScope.attr("const") = renderConstModule; scope constScope = renderConstModule; // Add Render Constants constScope.attr("WIDTH") = RenderManager::GetInstance().GetResolution().x; constScope.attr("HEIGHT") = RenderManager::GetInstance().GetResolution().y; }
31.878505
95
0.719926
[ "mesh", "render", "object", "vector" ]
c8b944c024d34dfafd0537d2eb2e1b035dfefd76
12,661
cpp
C++
NFComm/NFNetPlugin/NFNetModule.cpp
flyarong/NoahGameFrame
9847c6dc627cdc58b5407bf2d362f4c708926762
[ "Apache-2.0" ]
2
2019-01-13T13:10:07.000Z
2019-07-28T01:50:02.000Z
NFComm/NFNetPlugin/NFNetModule.cpp
a8037902/NoahGameFrame
0c5b81538f0ee74e03bd3430b106f28ef45db17c
[ "Apache-2.0" ]
null
null
null
NFComm/NFNetPlugin/NFNetModule.cpp
a8037902/NoahGameFrame
0c5b81538f0ee74e03bd3430b106f28ef45db17c
[ "Apache-2.0" ]
1
2019-04-17T06:48:56.000Z
2019-04-17T06:48:56.000Z
/* This file is part of: NoahFrame https://github.com/ketoo/NoahGameFrame Copyright 2009 - 2018 NoahFrame(NoahGameFrame) File creator: lvsheng.huang NoahFrame is open-source software and you can redistribute it and/or modify it under the terms of the License; besides, anyone who use this file/software must include this copyright announcement. 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 "NFNetModule.h" NFNetModule::NFNetModule(NFIPluginManager* p) { pPluginManager = p; mnBufferSize = 0; nLastTime = GetPluginManager()->GetNowTime(); m_pNet = NULL; } NFNetModule::~NFNetModule() { if (m_pNet) { m_pNet->Final(); } delete m_pNet; m_pNet = NULL; } bool NFNetModule::Init() { m_pLogModule = pPluginManager->FindModule<NFILogModule>(); return true; } bool NFNetModule::AfterInit() { return true; } void NFNetModule::Initialization(const char* strIP, const unsigned short nPort) { m_pNet = NF_NEW NFNet(this, &NFNetModule::OnReceiveNetPack, &NFNetModule::OnSocketNetEvent); m_pNet->ExpandBufferSize(mnBufferSize); m_pNet->Initialization(strIP, nPort); } int NFNetModule::Initialization(const unsigned int nMaxClient, const unsigned short nPort, const int nCpuCount) { m_pNet = NF_NEW NFNet(this, &NFNetModule::OnReceiveNetPack, &NFNetModule::OnSocketNetEvent); m_pNet->ExpandBufferSize(mnBufferSize); return m_pNet->Initialization(nMaxClient, nPort, nCpuCount); } int NFNetModule::ExpandBufferSize(const unsigned int size) { if (size > 0) { mnBufferSize = size; if (m_pNet) { m_pNet->ExpandBufferSize(mnBufferSize); } } return mnBufferSize; } void NFNetModule::RemoveReceiveCallBack(const int nMsgID) { std::map<int, std::list<NET_RECEIVE_FUNCTOR_PTR>>::iterator it = mxReceiveCallBack.find(nMsgID); if (mxReceiveCallBack.end() != it) { mxReceiveCallBack.erase(it); } } bool NFNetModule::AddReceiveCallBack(const int nMsgID, const NET_RECEIVE_FUNCTOR_PTR& cb) { if (mxReceiveCallBack.find(nMsgID) == mxReceiveCallBack.end()) { std::list<NET_RECEIVE_FUNCTOR_PTR> xList; xList.push_back(cb); mxReceiveCallBack.insert(std::map<int, std::list<NET_RECEIVE_FUNCTOR_PTR>>::value_type(nMsgID, xList)); return true; } std::map<int, std::list<NET_RECEIVE_FUNCTOR_PTR>>::iterator it = mxReceiveCallBack.find(nMsgID); it->second.push_back(cb); return true; } bool NFNetModule::AddReceiveCallBack(const NET_RECEIVE_FUNCTOR_PTR& cb) { mxCallBackList.push_back(cb); return true; } bool NFNetModule::AddEventCallBack(const NET_EVENT_FUNCTOR_PTR& cb) { mxEventCallBackList.push_back(cb); return true; } bool NFNetModule::Execute() { if (!m_pNet) { return false; } KeepAlive(); return m_pNet->Execute(); } bool NFNetModule::SendMsgWithOutHead(const int nMsgID, const std::string& msg, const NFSOCK nSockIndex) { bool bRet = m_pNet->SendMsgWithOutHead(nMsgID, msg.c_str(), (uint32_t) msg.length(), nSockIndex); if (!bRet) { std::ostringstream stream; stream << " SendMsgWithOutHead failed fd " << nSockIndex; stream << " msg id " << nMsgID; m_pLogModule->LogError(stream, __FUNCTION__, __LINE__); } return bRet; } bool NFNetModule::SendMsgToAllClientWithOutHead(const int nMsgID, const std::string& msg) { bool bRet = m_pNet->SendMsgToAllClientWithOutHead(nMsgID, msg.c_str(), (uint32_t) msg.length()); if (!bRet) { std::ostringstream stream; stream << " SendMsgToAllClientWithOutHead failed"; stream << " msg id " << nMsgID; m_pLogModule->LogError(stream, __FUNCTION__, __LINE__); } return bRet; } bool NFNetModule::SendMsgPB(const uint16_t nMsgID, const google::protobuf::Message& xData, const NFSOCK nSockIndex, const NFGUID id) { NFMsg::MsgBase xMsg; if (!xData.SerializeToString(xMsg.mutable_msg_data())) { std::ostringstream stream; stream << " SendMsgPB Message to " << nSockIndex; stream << " Failed For Serialize of MsgData, MessageID " << nMsgID; m_pLogModule->LogError(stream, __FUNCTION__, __LINE__); return false; } NFMsg::Ident* pPlayerID = xMsg.mutable_player_id(); *pPlayerID = NFToPB(id); std::string strMsg; if (!xMsg.SerializeToString(&strMsg)) { std::ostringstream stream; stream << " SendMsgPB Message to " << nSockIndex; stream << " Failed For Serialize of MsgBase, MessageID " << nMsgID; m_pLogModule->LogError(stream, __FUNCTION__, __LINE__); return false; } return SendMsgWithOutHead(nMsgID, strMsg, nSockIndex); } bool NFNetModule::SendMsg(const uint16_t nMsgID, const std::string & xData, const NFSOCK nSockIndex) { return SendMsgWithOutHead(nMsgID, xData, nSockIndex); } bool NFNetModule::SendMsg(const uint16_t nMsgID, const std::string & xData, const NFSOCK nSockIndex, const NFGUID id) { NFMsg::MsgBase xMsg; xMsg.set_msg_data(xData.data(), xData.length()); NFMsg::Ident* pPlayerID = xMsg.mutable_player_id(); *pPlayerID = NFToPB(id); std::string strMsg; if (!xMsg.SerializeToString(&strMsg)) { std::ostringstream stream; stream << " SendMsgPB Message to " << nSockIndex; stream << " Failed For Serialize of MsgBase, MessageID " << nMsgID; m_pLogModule->LogError(stream, __FUNCTION__, __LINE__); return false; } return SendMsgWithOutHead(nMsgID, strMsg, nSockIndex); } bool NFNetModule::SendMsgPB(const uint16_t nMsgID, const google::protobuf::Message& xData, const NFSOCK nSockIndex) { NFMsg::MsgBase xMsg; if (!xData.SerializeToString(xMsg.mutable_msg_data())) { std::ostringstream stream; stream << " SendMsgPB Message to " << nSockIndex; stream << " Failed For Serialize of MsgData, MessageID " << nMsgID; m_pLogModule->LogError(stream, __FUNCTION__, __LINE__); return false; } NFMsg::Ident* pPlayerID = xMsg.mutable_player_id(); *pPlayerID = NFToPB(NFGUID()); std::string strMsg; if (!xMsg.SerializeToString(&strMsg)) { std::ostringstream stream; stream << " SendMsgPB Message to " << nSockIndex; stream << " Failed For Serialize of MsgBase, MessageID " << nMsgID; m_pLogModule->LogError(stream, __FUNCTION__, __LINE__); return false; } SendMsgWithOutHead(nMsgID, strMsg, nSockIndex); return true; } bool NFNetModule::SendMsgPBToAllClient(const uint16_t nMsgID, const google::protobuf::Message& xData) { NFMsg::MsgBase xMsg; if (!xData.SerializeToString(xMsg.mutable_msg_data())) { std::ostringstream stream; stream << " SendMsgPBToAllClient"; stream << " Failed For Serialize of MsgData, MessageID " << nMsgID; m_pLogModule->LogError(stream, __FUNCTION__, __LINE__); return false; } std::string strMsg; if (!xMsg.SerializeToString(&strMsg)) { std::ostringstream stream; stream << " SendMsgPBToAllClient"; stream << " Failed For Serialize of MsgBase, MessageID " << nMsgID; m_pLogModule->LogError(stream, __FUNCTION__, __LINE__); return false; } return SendMsgToAllClientWithOutHead(nMsgID, strMsg); } bool NFNetModule::SendMsgPB(const uint16_t nMsgID, const google::protobuf::Message& xData, const NFSOCK nSockIndex, const std::vector<NFGUID>* pClientIDList) { if (!m_pNet) { std::ostringstream stream; stream << " m_pNet SendMsgPB faailed fd " << nSockIndex; stream << " Failed For Serialize of MsgBase, MessageID " << nMsgID; m_pLogModule->LogError(stream, __FUNCTION__, __LINE__); return false; } NFMsg::MsgBase xMsg; if (!xData.SerializeToString(xMsg.mutable_msg_data())) { std::ostringstream stream; stream << " SendMsgPB faailed fd " << nSockIndex; stream << " Failed For Serialize of MsgBase, MessageID " << nMsgID; m_pLogModule->LogError(stream, __FUNCTION__, __LINE__); return false; } NFMsg::Ident* pPlayerID = xMsg.mutable_player_id(); *pPlayerID = NFToPB(NFGUID()); if (pClientIDList) { for (int i = 0; i < pClientIDList->size(); ++i) { const NFGUID& ClientID = (*pClientIDList)[i]; NFMsg::Ident* pData = xMsg.add_player_client_list(); if (pData) { *pData = NFToPB(ClientID); } } } std::string strMsg; if (!xMsg.SerializeToString(&strMsg)) { std::ostringstream stream; stream << " SendMsgPB faailed fd " << nSockIndex; stream << " Failed For Serialize of MsgBase, MessageID " << nMsgID; m_pLogModule->LogError(stream, __FUNCTION__, __LINE__); return false; } return SendMsgWithOutHead(nMsgID, strMsg, nSockIndex); } bool NFNetModule::SendMsgPB(const uint16_t nMsgID, const std::string& strData, const NFSOCK nSockIndex, const std::vector<NFGUID>* pClientIDList) { if (!m_pNet) { std::ostringstream stream; stream << " SendMsgPB NULL Of Net faailed fd " << nSockIndex; stream << " Failed For Serialize of MsgBase, MessageID " << nMsgID; m_pLogModule->LogError(stream, __FUNCTION__, __LINE__); return false; } NFMsg::MsgBase xMsg; xMsg.set_msg_data(strData.data(), strData.length()); NFMsg::Ident* pPlayerID = xMsg.mutable_player_id(); *pPlayerID = NFToPB(NFGUID()); if (pClientIDList) { for (int i = 0; i < pClientIDList->size(); ++i) { const NFGUID& ClientID = (*pClientIDList)[i]; NFMsg::Ident* pData = xMsg.add_player_client_list(); if (pData) { *pData = NFToPB(ClientID); } } } std::string strMsg; if (!xMsg.SerializeToString(&strMsg)) { std::ostringstream stream; stream << " SendMsgPB failed fd " << nSockIndex; stream << " Failed For Serialize of MsgBase, MessageID " << nMsgID; m_pLogModule->LogError(stream, __FUNCTION__, __LINE__); return false; } return SendMsgWithOutHead(nMsgID, strMsg, nSockIndex); } NFINet* NFNetModule::GetNet() { return m_pNet; } void NFNetModule::OnReceiveNetPack(const NFSOCK nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen) { m_pLogModule->LogInfo("OnReceiveNetPack " + std::to_string(nMsgID), __FUNCTION__, __LINE__); NFPerformance performance; std::map<int, std::list<NET_RECEIVE_FUNCTOR_PTR>>::iterator it = mxReceiveCallBack.find(nMsgID); if (mxReceiveCallBack.end() != it) { std::list<NET_RECEIVE_FUNCTOR_PTR>& xFunList = it->second; for (std::list<NET_RECEIVE_FUNCTOR_PTR>::iterator itList = xFunList.begin(); itList != xFunList.end(); ++itList) { NET_RECEIVE_FUNCTOR_PTR& pFunPtr = *itList; NET_RECEIVE_FUNCTOR* pFunc = pFunPtr.get(); pFunc->operator()(nSockIndex, nMsgID, msg, nLen); } } else { for (std::list<NET_RECEIVE_FUNCTOR_PTR>::iterator itList = mxCallBackList.begin(); itList != mxCallBackList.end(); ++itList) { NET_RECEIVE_FUNCTOR_PTR& pFunPtr = *itList; NET_RECEIVE_FUNCTOR* pFunc = pFunPtr.get(); pFunc->operator()(nSockIndex, nMsgID, msg, nLen); } } if (performance.CheckTimePoint(1)) { std::ostringstream os; os << "---------------net module performance problem------------------- "; os << performance.TimeScope(); os << "---------- "; m_pLogModule->LogWarning(NFGUID(0, nMsgID), os, __FUNCTION__, __LINE__); } } void NFNetModule::OnSocketNetEvent(const NFSOCK nSockIndex, const NF_NET_EVENT eEvent, NFINet* pNet) { for (std::list<NET_EVENT_FUNCTOR_PTR>::iterator it = mxEventCallBackList.begin(); it != mxEventCallBackList.end(); ++it) { NET_EVENT_FUNCTOR_PTR& pFunPtr = *it; NET_EVENT_FUNCTOR* pFunc = pFunPtr.get(); pFunc->operator()(nSockIndex, eEvent, pNet); } } void NFNetModule::KeepAlive() { if (!m_pNet) { return; } if (m_pNet->IsServer()) { return; } if (nLastTime + 10 > GetPluginManager()->GetNowTime()) { return; } nLastTime = GetPluginManager()->GetNowTime(); NFMsg::ServerHeartBeat xMsg; xMsg.set_count(0); SendMsgPB(NFMsg::EGameMsgID::EGMI_STS_HEART_BEAT, xMsg, 0); }
27.464208
157
0.678698
[ "vector" ]
c8b96e046963ac0b4fcb49806946ad3dadc85d6e
10,946
cc
C++
cpp/src/arrow/csv/column_decoder_test.cc
timkpaine/arrow
a96297e65e17e728e4321cdecc7ace146e1363fb
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
9,734
2016-02-17T13:22:12.000Z
2022-03-31T09:35:00.000Z
cpp/src/arrow/csv/column_decoder_test.cc
timkpaine/arrow
a96297e65e17e728e4321cdecc7ace146e1363fb
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
11,470
2016-02-19T15:30:28.000Z
2022-03-31T23:27:21.000Z
cpp/src/arrow/csv/column_decoder_test.cc
XpressAI/arrow
eafd885e06f6bbc1eb169ed64016f804c1810bec
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
2,637
2016-02-17T10:56:29.000Z
2022-03-31T08:20:13.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include <memory> #include <string> #include <thread> #include <vector> #include <gtest/gtest.h> #include "arrow/csv/column_decoder.h" #include "arrow/csv/options.h" #include "arrow/csv/test_common.h" #include "arrow/memory_pool.h" #include "arrow/table.h" #include "arrow/testing/future_util.h" #include "arrow/testing/gtest_util.h" #include "arrow/testing/util.h" #include "arrow/type.h" #include "arrow/util/checked_cast.h" #include "arrow/util/thread_pool.h" namespace arrow { namespace csv { class BlockParser; using internal::checked_cast; using internal::GetCpuThreadPool; using ChunkData = std::vector<std::vector<std::string>>; class ThreadJoiner { public: explicit ThreadJoiner(std::shared_ptr<std::thread> thread) : thread_(std::move(thread)) {} ~ThreadJoiner() { if (thread_->joinable()) { thread_->join(); } } protected: std::shared_ptr<std::thread> thread_; }; template <typename Func> ThreadJoiner RunThread(Func&& func) { return ThreadJoiner(std::make_shared<std::thread>(std::forward<Func>(func))); } template <typename Func> void RunThreadsAndJoin(Func&& func, int iters) { std::vector<ThreadJoiner> threads; for (int i = 0; i < iters; i++) { threads.emplace_back(std::make_shared<std::thread>([i, func] { func(i); })); } } class ColumnDecoderTest : public ::testing::Test { public: ColumnDecoderTest() : num_chunks_(0), read_ptr_(0) {} void SetDecoder(std::shared_ptr<ColumnDecoder> decoder) { decoder_ = std::move(decoder); decoded_chunks_.clear(); num_chunks_ = 0; read_ptr_ = 0; } void InsertChunk(std::vector<std::string> chunk) { std::shared_ptr<BlockParser> parser; MakeColumnParser(chunk, &parser); auto decoded = decoder_->Decode(parser); decoded_chunks_.push_back(decoded); ++num_chunks_; } void AppendChunks(const ChunkData& chunks) { for (const auto& chunk : chunks) { InsertChunk(chunk); } } Result<std::shared_ptr<Array>> NextChunk() { EXPECT_LT(read_ptr_, static_cast<int64_t>(decoded_chunks_.size())); return decoded_chunks_[read_ptr_++].result(); } void AssertChunk(std::vector<std::string> chunk, std::shared_ptr<Array> expected) { std::shared_ptr<BlockParser> parser; MakeColumnParser(chunk, &parser); ASSERT_FINISHES_OK_AND_ASSIGN(auto decoded, decoder_->Decode(parser)); AssertArraysEqual(*expected, *decoded); } void AssertChunkInvalid(std::vector<std::string> chunk) { std::shared_ptr<BlockParser> parser; MakeColumnParser(chunk, &parser); ASSERT_FINISHES_AND_RAISES(Invalid, decoder_->Decode(parser)); } void AssertFetch(std::shared_ptr<Array> expected_chunk) { ASSERT_OK_AND_ASSIGN(auto chunk, NextChunk()); ASSERT_NE(chunk, nullptr); AssertArraysEqual(*expected_chunk, *chunk); } void AssertFetchInvalid() { ASSERT_RAISES(Invalid, NextChunk()); } protected: std::shared_ptr<ColumnDecoder> decoder_; std::vector<Future<std::shared_ptr<Array>>> decoded_chunks_; int64_t num_chunks_ = 0; int64_t read_ptr_ = 0; ConvertOptions default_options = ConvertOptions::Defaults(); }; ////////////////////////////////////////////////////////////////////////// // Tests for null column decoder class NullColumnDecoderTest : public ColumnDecoderTest { public: NullColumnDecoderTest() {} void MakeDecoder(std::shared_ptr<DataType> type) { ASSERT_OK_AND_ASSIGN(auto decoder, ColumnDecoder::MakeNull(default_memory_pool(), type)); SetDecoder(decoder); } void TestNullType() { auto type = null(); MakeDecoder(type); AppendChunks({{"1", "2", "3"}, {"4", "5"}}); AssertFetch(ArrayFromJSON(type, "[null, null, null]")); AssertFetch(ArrayFromJSON(type, "[null, null]")); MakeDecoder(type); AppendChunks({{}, {"6"}}); AssertFetch(ArrayFromJSON(type, "[]")); AppendChunks({{"7", "8"}}); AssertFetch(ArrayFromJSON(type, "[null]")); AssertFetch(ArrayFromJSON(type, "[null, null]")); } void TestOtherType() { auto type = int32(); MakeDecoder(type); AppendChunks({{"1", "2", "3"}, {"4", "5"}}); AssertFetch(ArrayFromJSON(type, "[null, null, null]")); AssertFetch(ArrayFromJSON(type, "[null, null]")); } void TestThreaded() { constexpr int NITERS = 10; auto type = int32(); MakeDecoder(type); RunThreadsAndJoin( [&](int thread_id) { AssertChunk({"4", "5", std::to_string(thread_id)}, ArrayFromJSON(type, "[null, null, null]")); }, NITERS); } }; TEST_F(NullColumnDecoderTest, NullType) { this->TestNullType(); } TEST_F(NullColumnDecoderTest, OtherType) { this->TestOtherType(); } TEST_F(NullColumnDecoderTest, Threaded) { this->TestThreaded(); } ////////////////////////////////////////////////////////////////////////// // Tests for fixed-type column decoder class TypedColumnDecoderTest : public ColumnDecoderTest { public: TypedColumnDecoderTest() {} void MakeDecoder(const std::shared_ptr<DataType>& type, const ConvertOptions& options) { ASSERT_OK_AND_ASSIGN(auto decoder, ColumnDecoder::Make(default_memory_pool(), type, 0, options)); SetDecoder(decoder); } void TestIntegers() { auto type = int16(); MakeDecoder(type, default_options); AppendChunks({{"123", "456", "-78"}, {"901", "N/A"}}); AssertFetch(ArrayFromJSON(type, "[123, 456, -78]")); AssertFetch(ArrayFromJSON(type, "[901, null]")); MakeDecoder(type, default_options); AppendChunks({{}, {"-987"}}); AssertFetch(ArrayFromJSON(type, "[]")); AppendChunks({{"N/A", "N/A"}}); AssertFetch(ArrayFromJSON(type, "[-987]")); AssertFetch(ArrayFromJSON(type, "[null, null]")); } void TestOptions() { auto type = boolean(); MakeDecoder(type, default_options); AppendChunks({{"true", "false", "N/A"}}); AssertFetch(ArrayFromJSON(type, "[true, false, null]")); // With non-default options auto options = default_options; options.null_values = {"true"}; options.true_values = {"false"}; options.false_values = {"N/A"}; MakeDecoder(type, options); AppendChunks({{"true", "false", "N/A"}}); AssertFetch(ArrayFromJSON(type, "[null, true, false]")); } void TestErrors() { auto type = uint64(); MakeDecoder(type, default_options); AppendChunks({{"123", "456", "N/A"}, {"-901"}}); AppendChunks({{"N/A", "1000"}}); AssertFetch(ArrayFromJSON(type, "[123, 456, null]")); AssertFetchInvalid(); AssertFetch(ArrayFromJSON(type, "[null, 1000]")); } void TestThreaded() { constexpr int NITERS = 10; auto type = uint32(); MakeDecoder(type, default_options); RunThreadsAndJoin( [&](int thread_id) { if (thread_id % 2 == 0) { AssertChunkInvalid({"4", "-5"}); } else { AssertChunk({"1", "2", "3"}, ArrayFromJSON(type, "[1, 2, 3]")); } }, NITERS); } }; TEST_F(TypedColumnDecoderTest, Integers) { this->TestIntegers(); } TEST_F(TypedColumnDecoderTest, Options) { this->TestOptions(); } TEST_F(TypedColumnDecoderTest, Errors) { this->TestErrors(); } TEST_F(TypedColumnDecoderTest, Threaded) { this->TestThreaded(); } ////////////////////////////////////////////////////////////////////////// // Tests for type-inferring column decoder class InferringColumnDecoderTest : public ColumnDecoderTest { public: InferringColumnDecoderTest() {} void MakeDecoder(const ConvertOptions& options) { ASSERT_OK_AND_ASSIGN(auto decoder, ColumnDecoder::Make(default_memory_pool(), 0, options)); SetDecoder(decoder); } void TestIntegers() { auto type = int64(); MakeDecoder(default_options); AppendChunks({{"123", "456", "-78"}, {"901", "N/A"}}); AssertFetch(ArrayFromJSON(type, "[123, 456, -78]")); AssertFetch(ArrayFromJSON(type, "[901, null]")); } void TestThreaded() { constexpr int NITERS = 10; auto type = float64(); MakeDecoder(default_options); // One of these will do the inference so we need to make sure they all have floating // point RunThreadsAndJoin( [&](int thread_id) { if (thread_id % 2 == 0) { AssertChunk({"6.3", "7.2"}, ArrayFromJSON(type, "[6.3, 7.2]")); } else { AssertChunk({"1.1", "2", "3"}, ArrayFromJSON(type, "[1.1, 2, 3]")); } }, NITERS); // These will run after the inference RunThreadsAndJoin( [&](int thread_id) { if (thread_id % 2 == 0) { AssertChunk({"1", "2"}, ArrayFromJSON(type, "[1, 2]")); } else { AssertChunkInvalid({"xyz"}); } }, NITERS); } void TestOptions() { auto type = boolean(); auto options = default_options; options.null_values = {"true"}; options.true_values = {"false"}; options.false_values = {"N/A"}; MakeDecoder(options); AppendChunks({{"true", "false", "N/A"}, {"true"}}); AssertFetch(ArrayFromJSON(type, "[null, true, false]")); AssertFetch(ArrayFromJSON(type, "[null]")); } void TestErrors() { auto type = int64(); MakeDecoder(default_options); AppendChunks({{"123", "456", "-78"}, {"9.5", "N/A"}}); AppendChunks({{"1000", "N/A"}}); AssertFetch(ArrayFromJSON(type, "[123, 456, -78]")); AssertFetchInvalid(); AssertFetch(ArrayFromJSON(type, "[1000, null]")); } void TestEmpty() { auto type = null(); MakeDecoder(default_options); AppendChunks({{}, {}}); AssertFetch(ArrayFromJSON(type, "[]")); AssertFetch(ArrayFromJSON(type, "[]")); } }; TEST_F(InferringColumnDecoderTest, Integers) { this->TestIntegers(); } TEST_F(InferringColumnDecoderTest, Threaded) { this->TestThreaded(); } TEST_F(InferringColumnDecoderTest, Options) { this->TestOptions(); } TEST_F(InferringColumnDecoderTest, Errors) { this->TestErrors(); } TEST_F(InferringColumnDecoderTest, Empty) { this->TestEmpty(); } // More inference tests are in InferringColumnBuilderTest } // namespace csv } // namespace arrow
28.357513
90
0.636854
[ "vector" ]
c8bad9e5bc469a9d63437db94d84659784e372e6
1,689
cpp
C++
stacks_and_queues/stack.cpp
agurusa/interview_prep
b777e0803ee8d3316c0f3fb60efd8463d1437424
[ "MIT" ]
null
null
null
stacks_and_queues/stack.cpp
agurusa/interview_prep
b777e0803ee8d3316c0f3fb60efd8463d1437424
[ "MIT" ]
null
null
null
stacks_and_queues/stack.cpp
agurusa/interview_prep
b777e0803ee8d3316c0f3fb60efd8463d1437424
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> class StackNode{ public: StackNode(int d){ data = d; } int data; StackNode *next = NULL; // included for comparisons in tests.cpp friend bool operator == (const StackNode lhs, const StackNode rhs){ return(lhs.data == rhs.data); } friend std::ostream& operator <<(std::ostream& os, const StackNode *sn){ os << sn->data; return os; } friend std::ostream& operator <<(std::ostream& os, const StackNode& sn){ os << sn.data; return os; } friend bool operator <(const StackNode lhs, const StackNode rhs){ return(lhs.data < rhs.data); } }; class Stack{ public: Stack(){ } void pop(){ //TODO: throw empty stack exception if top == NULL if(top!= NULL){ top = top->next; } }; void push(StackNode *sn){ StackNode *s = top; top = sn; if(s!= NULL){ top->next = s; } }; StackNode *peek(){return top;}; bool isEmpty(){ return (top == NULL); } StackNode *top = NULL; // included for stack_of_plates int capacity = 10; bool at_capacity(){ return(capacity <= 0); } //included for comparisons in tests.cpp friend bool operator == (const Stack lhs, const Stack rhs){ StackNode *topLHS = lhs.top; StackNode *topRHS = rhs.top; while(topLHS != NULL && topRHS != NULL){ if(topLHS != topRHS){ return false; } else{ topLHS = topLHS->next; topRHS = topRHS->next; } } if((topLHS == NULL && topRHS != NULL) || (topLHS!= NULL && topRHS == NULL)){ return false; } return true; } friend std::ostream& operator << (std::ostream& os, Stack const& stack){ StackNode *sn = stack.top; while(sn!= NULL){ os << sn->data << " "; sn = sn->next; } return os; } };
20.107143
78
0.616341
[ "vector" ]
c8be0c4bf51b1063487160389d1a4eed107e48e5
2,966
cpp
C++
cnvex.cpp
knight-ni/informix-cpp
32866db15926fd74a2118f41fdcc9df755f67a28
[ "IBM-pibs" ]
null
null
null
cnvex.cpp
knight-ni/informix-cpp
32866db15926fd74a2118f41fdcc9df755f67a28
[ "IBM-pibs" ]
null
null
null
cnvex.cpp
knight-ni/informix-cpp
32866db15926fd74a2118f41fdcc9df755f67a28
[ "IBM-pibs" ]
null
null
null
/**************************************************************************** * * IBM INC. * * PROPRIETARY DATA * * Licensed Material - Property Of IBM * * "Restricted Materials of IBM" * * IBM Informix Client SDK * * (c) Copyright IBM Corporation 1997, 2004. All rights reserved. * **************************************************************************** */ #include <iostream> #include <it.h> int main(int, char **) { // Make a connection using defaults ITConnection conn; conn.Open(); // Create a query object ITQuery q(conn); // Retrieve a row from the database ITRow *row; row = q.ExecOneRow("select unique count(*) from informix.systables where tabname in ('systables', 'syscolumns', 'sysviews');"); // Check to see if any rows were returned if (row == NULL) { cout << "cnvex: no rows returned by ITQuery::ExecOneRow" << endl; cout << "cnvex: exiting" << endl; return 1; } ITValue *v = row->Column(0); ITConversions *c; // 1 // Extract an interface. The return code IT_QUERYINTERFACE_SUCCESS // should be used for compatibility reasons. if (v->QueryInterface(ITConversionsIID, (void **) &c) == IT_QUERYINTERFACE_SUCCESS) { short short_tabcnt; int int_tabcnt; long long_tabcnt; float float_tabcnt; double double_tabcnt; const char *cstring_tabcnt; ITString itstring_tabcnt; if (c->ConvertTo(short_tabcnt)) { cout << "SQL Integer as short: " << short_tabcnt << endl; } if (c->ConvertTo(int_tabcnt)) { cout << "SQL Integer as int: " << int_tabcnt << endl; } if (c->ConvertTo(long_tabcnt)) { cout << "SQL Integer as long: " << long_tabcnt << endl; } if (c->ConvertTo(float_tabcnt)) { cout << "SQL Integer as float: " << float_tabcnt << endl; } if (c->ConvertTo(double_tabcnt)) { cout << "SQL Integer as double: " << double_tabcnt << endl; } if (c->ConvertTo(cstring_tabcnt)) { cout << "SQL Integer as C string: " << cstring_tabcnt << endl; } if (c->ConvertTo(itstring_tabcnt)) { cout << "SQL Integer as ITString: " << itstring_tabcnt << endl; } // Release the conversions interface c->Release(); } // Release the value interfaces v->Release(); row->Release(); return 0; }
24.512397
131
0.452798
[ "object" ]
c8c3e15ff61a31dc1a198bd8b42ebf306aae808b
683
cc
C++
Code/0027-remove-element.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
2
2019-12-06T14:08:57.000Z
2020-01-15T15:25:32.000Z
Code/0027-remove-element.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
1
2020-01-15T16:29:16.000Z
2020-01-26T12:40:13.000Z
Code/0027-remove-element.cc
SMartQi/Leetcode
9e35c65a48ba1ecd5436bbe07dd65f993588766b
[ "MIT" ]
null
null
null
class Solution { public: int removeElement(vector<int>& nums, int val) { if (nums.size() == 0) { return 0; } int p1 = 0; int p2 = nums.size() - 1; while (true) { while (nums[p1] != val) { p1++; if (p1 == nums.size()) { return p1; } } while (nums[p2] == val) { p2--; if (p2 == -1) { return 0; } } if (p1 > p2) { return p1; } nums[p1] = nums[p2]; nums[p2] = val; } } };
23.551724
51
0.292826
[ "vector" ]
c8c6e87d6bcaed28f8d9eb9f8db501f3e8ab969f
424
hpp
C++
graphics-library/include/scene/scene.hpp
thetorine/opengl3-library
3904d857fd1085ba2c57c4289eb0e0d123f11a14
[ "MIT" ]
null
null
null
graphics-library/include/scene/scene.hpp
thetorine/opengl3-library
3904d857fd1085ba2c57c4289eb0e0d123f11a14
[ "MIT" ]
null
null
null
graphics-library/include/scene/scene.hpp
thetorine/opengl3-library
3904d857fd1085ba2c57c4289eb0e0d123f11a14
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "scene/scene_object.hpp" namespace gl::scene { class Scene { public: Scene(); ~Scene(); void addChild(const std::shared_ptr<SceneObject> &child); void drawScene() const; void updateScene(float dt); size_t getTreeSize() const; private: std::vector<std::shared_ptr<SceneObject>> m_root; }; }
21.2
66
0.580189
[ "vector" ]
c8c7673f761ffa432ae55b0b0ccd54ef0b4c945a
13,206
cpp
C++
iRODS/lib/core/src/irods_environment_properties.cpp
cyverse/irods
4ea33f5f0e220b6e5d257a49b45e10d07ec02d75
[ "BSD-3-Clause" ]
null
null
null
iRODS/lib/core/src/irods_environment_properties.cpp
cyverse/irods
4ea33f5f0e220b6e5d257a49b45e10d07ec02d75
[ "BSD-3-Clause" ]
7
2019-12-02T17:55:49.000Z
2019-12-02T17:55:59.000Z
iRODS/lib/core/src/irods_environment_properties.cpp
benlazarine/irods
83f3c4a6f8f7fc6422a1e73a297b97796a961322
[ "BSD-3-Clause" ]
1
2019-12-02T05:44:10.000Z
2019-12-02T05:44:10.000Z
/* * irods_environment_properties.cpp * */ #include "irods_environment_properties.hpp" #include "irods_get_full_path_for_config_file.hpp" #include "rods.h" #include "irods_log.hpp" #include "irods_lookup_table.hpp" #include "irods_home_directory.hpp" #include "readServerConfig.hpp" #include <string> #include <algorithm> #include <fstream> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; #define BUF_LEN 500 namespace irods { const std::string environment_properties::LEGACY_ENV_FILE = "/.irods/.irodsEnv"; const std::string environment_properties::JSON_ENV_FILE = "/.irods/irods_environment.json"; // Access method for singleton environment_properties& environment_properties::getInstance() { static environment_properties instance; return instance; } error environment_properties::capture_if_needed() { error result = SUCCESS(); if ( !captured_ ) { result = capture(); } return result; } environment_properties::environment_properties() : captured_( false ) { legacy_key_map_[ "irodsUserName" ] = CFG_IRODS_USER_NAME_KW; legacy_key_map_[ "irodsHost" ] = CFG_IRODS_HOST_KW; legacy_key_map_[ "irodsPort" ] = CFG_IRODS_PORT_KW; legacy_key_map_[ "xmsgHost" ] = CFG_IRODS_XMSG_HOST_KW; legacy_key_map_[ "xmsgPort" ] = CFG_IRODS_XMSG_PORT_KW; legacy_key_map_[ "irodsHome" ] = CFG_IRODS_HOME_KW; legacy_key_map_[ "irodsCwd" ] = CFG_IRODS_CWD_KW; legacy_key_map_[ "irodsAuthScheme" ] = CFG_IRODS_AUTHENTICATION_SCHEME_KW; legacy_key_map_[ "irodsDefResource" ] = CFG_IRODS_DEFAULT_RESOURCE_KW; legacy_key_map_[ "irodsZone" ] = CFG_IRODS_ZONE_KW; legacy_key_map_[ "irodsServerDn" ] = CFG_IRODS_GSI_SERVER_DN_KW; legacy_key_map_[ "irodsLogLevel" ] = CFG_IRODS_LOG_LEVEL_KW; legacy_key_map_[ "irodsAuthFileName" ] = CFG_IRODS_AUTHENTICATION_FILE_KW; legacy_key_map_[ "irodsDebug" ] = CFG_IRODS_DEBUG_KW; legacy_key_map_[ "irodsClientServerPolicy" ] = CFG_IRODS_CLIENT_SERVER_POLICY_KW; legacy_key_map_[ "irodsClientServerNegotiation" ] = CFG_IRODS_CLIENT_SERVER_NEGOTIATION_KW; legacy_key_map_[ "irodsEncryptionKeySize" ] = CFG_IRODS_ENCRYPTION_KEY_SIZE_KW; legacy_key_map_[ "irodsEncryptionSaltSize" ] = CFG_IRODS_ENCRYPTION_SALT_SIZE_KW; legacy_key_map_[ "irodsEncryptionNumHashRounds" ] = CFG_IRODS_ENCRYPTION_NUM_HASH_ROUNDS_KW; legacy_key_map_[ "irodsEncryptionAlgorithm" ] = CFG_IRODS_ENCRYPTION_ALGORITHM_KW; legacy_key_map_[ "irodsDefaultHashScheme" ] = CFG_IRODS_DEFAULT_HASH_SCHEME_KW; legacy_key_map_[ "irodsMatchHashPolicy" ] = CFG_IRODS_MATCH_HASH_POLICY_KW; } // ctor error environment_properties::get_json_environment_file( std::string& _env_file, std::string& _session_file ) { // capture parent process id for use in creation of 'session' // file which contains the cwd for a given session. this cwd // is only updated by the icd command which writes a new irods // CFG_IRODS_CWD_KW to the session dir which repaves the existing // one in the original irodsEnv file. std::stringstream ppid_str; ppid_str << getppid(); // if a json version exists, then attempt to capture // that std::string json_file( IRODS_HOME_DIRECTORY ); std::string json_session_file( IRODS_HOME_DIRECTORY ); std::string env_var = to_env( CFG_IRODS_ENVIRONMENT_FILE_KW ); char* irods_env = getenv(env_var.c_str()); if ( irods_env && strlen( irods_env ) > 0 ) { json_file = irods_env; // "cwd" is used in this case instead of the ppid given the // assumption that scripts will set the env file var to allow // for more complex interactions possibly yielding complex pid // hierarchies. this routes all references to the same session // for this given use case json_session_file = json_file + ".cwd"; } else { char* home_dir = getenv( "HOME" ); // if home env exists, prefer that for run in place // or use of existing irods service accound if ( home_dir ) { json_file = home_dir; } json_file += JSON_ENV_FILE; json_session_file = json_file + "." + ppid_str.str(); } _env_file = json_file; _session_file = json_session_file; return SUCCESS(); } // get_json_environment_file error environment_properties::get_legacy_environment_file( std::string& _env_file, std::string& _session_file ) { // capture parent process id for use in creation of 'session' // file which contains the cwd for a given session. this cwd // is only updated by the icd command which writes a new irods // CFG_IRODS_CWD_KW to the session dir which repaves the existing // one in the original irodsEnv file. std::stringstream ppid_str; ppid_str << getppid(); std::string legacy_file( IRODS_HOME_DIRECTORY ); std::string legacy_session_file( IRODS_HOME_DIRECTORY ); char* irods_env = getenv( to_env( CFG_IRODS_ENVIRONMENT_FILE_KW ).c_str() ); if ( irods_env && strlen( irods_env ) != 0 ) { legacy_file = irods_env; // "cwd" is used in this case instead of the ppid given the // assumption that scripts will set the env file var to allow // for more complex interactions possibly yielding complex pid // hierarchies. this routes all references to the same session // for this given use case legacy_session_file = legacy_file + ".cwd"; } else { char* home_dir = getenv( "HOME" ); // if home env exists, prefer that for run in place // or use of existing irods service accound if ( home_dir ) { legacy_file = home_dir; } legacy_file += LEGACY_ENV_FILE; legacy_session_file = legacy_file + "." + ppid_str.str(); } _env_file = legacy_file; _session_file = legacy_session_file; if ( fs::exists( legacy_file ) ) { std::cout << "Warning: use of legacy configuration [" << legacy_file << "] is deprecated." << std::endl; } return SUCCESS(); } // get_legacy_environment_file error environment_properties::capture() { std::string json_file, json_session_file; error ret = get_json_environment_file( json_file, json_session_file ); bool do_parse_legacy = false; if ( ret.ok() ) { if ( fs::exists( json_file ) ) { ret = capture_json( json_file ); if ( !ret.ok() ) { irods::log( ret ); do_parse_legacy = true; } else { config_props_.set< std::string >( CFG_IRODS_ENVIRONMENT_FILE_KW, json_file ); ret = capture_json( json_session_file ); if ( !ret.ok() ) { // debug - irods::log( PASS( ret ) ); } config_props_.set< std::string >( CFG_IRODS_SESSION_ENVIRONMENT_FILE_KW, json_session_file ); } } else { do_parse_legacy = true; } } else { do_parse_legacy = true; } if ( do_parse_legacy ) { std::string legacy_file, legacy_session_file; ret = get_legacy_environment_file( legacy_file, legacy_session_file ); if ( ret.ok() ) { ret = capture_legacy( legacy_file ); if ( !ret.ok() ) { // debug - irods::log( PASS( ret ) ); } else { config_props_.set< std::string >( CFG_IRODS_ENVIRONMENT_FILE_KW, legacy_file ); } // session file ( written by icd ) already moved // to json ret = capture_json( legacy_session_file ); if ( !ret.ok() ) { // debug - irods::log( PASS( ret ) ); } config_props_.set< std::string >( CFG_IRODS_SESSION_ENVIRONMENT_FILE_KW, legacy_session_file ); } else { // debug - irods::log( PASS( ret ) ); } } // do parse legacy // set the captured flag so we no its already // been captured captured_ = true; return SUCCESS(); } // capture error environment_properties::capture_json( const std::string& _fn ) { error ret = config_props_.load( _fn ); return ret; } // capture_json error environment_properties::capture_legacy( const std::string& _fn ) { std::ifstream in_file( _fn.c_str(), std::ios::in ); if ( !in_file.is_open() ) { std::string msg( "failed to open legacy file [" ); msg += _fn; msg += "]"; return ERROR( SYS_INVALID_FILE_PATH, msg ); } std::string line; while ( getline( in_file, line ) ) { // left trim whitespace line.erase( line.begin(), std::find_if( line.begin(), line.end(), std::not1( std::ptr_fun<int, int>( std::isspace ) ) ) ); // skip comments if ( '#' == line[0] ) { continue; } std::vector< std::string > toks; try { boost::split( toks, line, boost::is_any_of( "\t " ), boost::token_compress_on ); } catch ( boost::exception& ) { rodsLog( LOG_ERROR, "boost::split failed on line [%s]", line.c_str() ); continue; } if ( toks.size() != 2 || toks[0].empty() || toks[1].empty() ) { rodsLog( LOG_NOTICE, "environment_properties :: invalid line [%s]", line.c_str() ); continue; } std::string& key = toks[0]; if ( legacy_key_map_.has_entry( key ) ) { key = legacy_key_map_[ key ]; } //if has entry std::string& val = toks[1]; char front = *( val.begin() ); if ( '"' == front || '\'' == front ) { val.erase( 0, 1 ); } char back = *( val.rbegin() ); if ( '"' == back || '\'' == back ) { val.erase( val.size() - 1 ); } error ret; if ( CFG_IRODS_PORT_KW == key || CFG_IRODS_XMSG_PORT_KW == key || CFG_IRODS_LOG_LEVEL_KW == key || CFG_IRODS_ENCRYPTION_KEY_SIZE_KW == key || CFG_IRODS_ENCRYPTION_SALT_SIZE_KW == key || CFG_IRODS_ENCRYPTION_NUM_HASH_ROUNDS_KW == key ) { try { int i_val = boost::lexical_cast< int >( val ); ret = config_props_.set< int >( key, i_val ); } catch ( ... ) { rodsLog( LOG_ERROR, "environment_properties :: lexical_cast failed for [%s]-[%s]", key.c_str(), val.c_str() ); } } else { ret = config_props_.set < std::string > ( key, val ); } if ( !ret.ok() ) { irods::log( PASS( ret ) ); } } // while in_file.close(); return SUCCESS(); } // environment_properties::capture_legacy } // namespace irods
35.691892
100
0.513252
[ "vector" ]
c8cbfb399615a6b7c2e24b60ed0be929f2f1fb06
42,171
cpp
C++
template_mp/src/game/server/doors.cpp
moeabm/VS2013
dd29099567b286acac7bb542a06f085df78ea480
[ "Unlicense" ]
null
null
null
template_mp/src/game/server/doors.cpp
moeabm/VS2013
dd29099567b286acac7bb542a06f085df78ea480
[ "Unlicense" ]
null
null
null
template_mp/src/game/server/doors.cpp
moeabm/VS2013
dd29099567b286acac7bb542a06f085df78ea480
[ "Unlicense" ]
null
null
null
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Implements two types of doors: linear and rotating. // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "doors.h" #include "entitylist.h" #include "physics.h" #include "ndebugoverlay.h" #include "engine/IEngineSound.h" #include "physics_npc_solver.h" #ifdef HL1_DLL #include "filters.h" #endif #ifdef CSTRIKE_DLL #include "KeyValues.h" #endif #ifdef TF_DLL #include "tf_gamerules.h" #endif // TF_DLL // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define CLOSE_AREAPORTAL_THINK_CONTEXT "CloseAreaportalThink" BEGIN_DATADESC( CBaseDoor ) DEFINE_KEYFIELD( m_vecMoveDir, FIELD_VECTOR, "movedir" ), DEFINE_FIELD( m_bLockedSentence, FIELD_CHARACTER ), DEFINE_FIELD( m_bUnlockedSentence, FIELD_CHARACTER ), DEFINE_KEYFIELD( m_NoiseMoving, FIELD_SOUNDNAME, "noise1" ), DEFINE_KEYFIELD( m_NoiseArrived, FIELD_SOUNDNAME, "noise2" ), DEFINE_KEYFIELD( m_NoiseMovingClosed, FIELD_SOUNDNAME, "startclosesound" ), DEFINE_KEYFIELD( m_NoiseArrivedClosed, FIELD_SOUNDNAME, "closesound" ), DEFINE_KEYFIELD( m_ChainTarget, FIELD_STRING, "chainstodoor" ), // DEFINE_FIELD( m_isChaining, FIELD_BOOLEAN ), // DEFINE_FIELD( m_ls, locksound_t ), // DEFINE_FIELD( m_isChaining, FIELD_BOOLEAN ), DEFINE_KEYFIELD( m_ls.sLockedSound, FIELD_SOUNDNAME, "locked_sound" ), DEFINE_KEYFIELD( m_ls.sUnlockedSound, FIELD_SOUNDNAME, "unlocked_sound" ), DEFINE_FIELD( m_bLocked, FIELD_BOOLEAN ), DEFINE_KEYFIELD( m_flWaveHeight, FIELD_FLOAT, "WaveHeight" ), DEFINE_KEYFIELD( m_flBlockDamage, FIELD_FLOAT, "dmg" ), DEFINE_KEYFIELD( m_eSpawnPosition, FIELD_INTEGER, "spawnpos" ), DEFINE_KEYFIELD( m_bForceClosed, FIELD_BOOLEAN, "forceclosed" ), DEFINE_FIELD( m_bDoorGroup, FIELD_BOOLEAN ), #ifdef HL1_DLL DEFINE_KEYFIELD( m_iBlockFilterName, FIELD_STRING, "filtername" ), DEFINE_FIELD( m_hBlockFilter, FIELD_EHANDLE ), #endif DEFINE_KEYFIELD( m_bLoopMoveSound, FIELD_BOOLEAN, "loopmovesound" ), DEFINE_KEYFIELD( m_bIgnoreDebris, FIELD_BOOLEAN, "ignoredebris" ), DEFINE_INPUTFUNC( FIELD_VOID, "Open", InputOpen ), DEFINE_INPUTFUNC( FIELD_VOID, "Close", InputClose ), DEFINE_INPUTFUNC( FIELD_VOID, "Toggle", InputToggle ), DEFINE_INPUTFUNC( FIELD_VOID, "Lock", InputLock ), DEFINE_INPUTFUNC( FIELD_VOID, "Unlock", InputUnlock ), DEFINE_INPUTFUNC( FIELD_FLOAT, "SetSpeed", InputSetSpeed ), DEFINE_INPUTFUNC( FIELD_FLOAT, "SetToggleState", InputSetToggleState ), DEFINE_OUTPUT( m_OnBlockedOpening, "OnBlockedOpening" ), DEFINE_OUTPUT( m_OnBlockedClosing, "OnBlockedClosing" ), DEFINE_OUTPUT( m_OnUnblockedOpening, "OnUnblockedOpening" ), DEFINE_OUTPUT( m_OnUnblockedClosing, "OnUnblockedClosing" ), DEFINE_OUTPUT( m_OnFullyClosed, "OnFullyClosed" ), DEFINE_OUTPUT( m_OnFullyOpen, "OnFullyOpen" ), DEFINE_OUTPUT( m_OnClose, "OnClose" ), DEFINE_OUTPUT( m_OnOpen, "OnOpen" ), DEFINE_OUTPUT( m_OnLockedUse, "OnLockedUse" ), // Function Pointers DEFINE_FUNCTION( DoorTouch ), DEFINE_FUNCTION( DoorGoUp ), DEFINE_FUNCTION( DoorGoDown ), DEFINE_FUNCTION( DoorHitTop ), DEFINE_FUNCTION( DoorHitBottom ), DEFINE_THINKFUNC( MovingSoundThink ), DEFINE_THINKFUNC( CloseAreaPortalsThink ), END_DATADESC() LINK_ENTITY_TO_CLASS( func_door, CBaseDoor ); // // func_water is implemented as a linear door so we can raise/lower the water level. // LINK_ENTITY_TO_CLASS( func_water, CBaseDoor ); // SendTable stuff. IMPLEMENT_SERVERCLASS_ST(CBaseDoor, DT_BaseDoor) SendPropFloat (SENDINFO(m_flWaveHeight), 8, SPROP_ROUNDUP, 0.0f, 8.0f), END_SEND_TABLE() #define DOOR_SENTENCEWAIT 6 #define DOOR_SOUNDWAIT 1 #define BUTTON_SOUNDWAIT 0.5 //----------------------------------------------------------------------------- // Purpose: play door or button locked or unlocked sounds. // NOTE: this routine is shared by doors and buttons // Input : pEdict - // pls - // flocked - if true, play 'door is locked' sound, otherwise play 'door // is unlocked' sound. // fbutton - //----------------------------------------------------------------------------- void PlayLockSounds(CBaseEntity *pEdict, locksound_t *pls, int flocked, int fbutton) { if ( pEdict->HasSpawnFlags( SF_DOOR_SILENT ) ) { return; } float flsoundwait = ( fbutton ) ? BUTTON_SOUNDWAIT : DOOR_SOUNDWAIT; if ( flocked ) { int fplaysound = (pls->sLockedSound != NULL_STRING && gpGlobals->curtime > pls->flwaitSound); int fplaysentence = (pls->sLockedSentence != NULL_STRING && !pls->bEOFLocked && gpGlobals->curtime > pls->flwaitSentence); float fvol = ( fplaysound && fplaysentence ) ? 0.25f : 1.0f; // if there is a locked sound, and we've debounced, play sound if (fplaysound) { // play 'door locked' sound CPASAttenuationFilter filter( pEdict ); EmitSound_t ep; ep.m_nChannel = CHAN_ITEM; ep.m_pSoundName = (char*)STRING(pls->sLockedSound); ep.m_flVolume = fvol; ep.m_SoundLevel = SNDLVL_NORM; CBaseEntity::EmitSound( filter, pEdict->entindex(), ep ); pls->flwaitSound = gpGlobals->curtime + flsoundwait; } // if there is a sentence, we've not played all in list, and we've debounced, play sound if (fplaysentence) { // play next 'door locked' sentence in group int iprev = pls->iLockedSentence; pls->iLockedSentence = SENTENCEG_PlaySequentialSz( pEdict->edict(), STRING(pls->sLockedSentence), 0.85f, SNDLVL_NORM, 0, 100, pls->iLockedSentence, FALSE); pls->iUnlockedSentence = 0; // make sure we don't keep calling last sentence in list pls->bEOFLocked = (iprev == pls->iLockedSentence); pls->flwaitSentence = gpGlobals->curtime + DOOR_SENTENCEWAIT; } } else { // UNLOCKED SOUND int fplaysound = (pls->sUnlockedSound != NULL_STRING && gpGlobals->curtime > pls->flwaitSound); int fplaysentence = (pls->sUnlockedSentence != NULL_STRING && !pls->bEOFUnlocked && gpGlobals->curtime > pls->flwaitSentence); float fvol; // if playing both sentence and sound, lower sound volume so we hear sentence fvol = ( fplaysound && fplaysentence ) ? 0.25f : 1.0f; // play 'door unlocked' sound if set if (fplaysound) { CPASAttenuationFilter filter( pEdict ); EmitSound_t ep; ep.m_nChannel = CHAN_ITEM; ep.m_pSoundName = (char*)STRING(pls->sUnlockedSound); ep.m_flVolume = fvol; ep.m_SoundLevel = SNDLVL_NORM; CBaseEntity::EmitSound( filter, pEdict->entindex(), ep ); pls->flwaitSound = gpGlobals->curtime + flsoundwait; } // play next 'door unlocked' sentence in group if (fplaysentence) { int iprev = pls->iUnlockedSentence; pls->iUnlockedSentence = SENTENCEG_PlaySequentialSz(pEdict->edict(), STRING(pls->sUnlockedSentence), 0.85, SNDLVL_NORM, 0, 100, pls->iUnlockedSentence, FALSE); pls->iLockedSentence = 0; // make sure we don't keep calling last sentence in list pls->bEOFUnlocked = (iprev == pls->iUnlockedSentence); pls->flwaitSentence = gpGlobals->curtime + DOOR_SENTENCEWAIT; } } } //----------------------------------------------------------------------------- // Purpose: Cache user-entity-field values until spawn is called. // Input : szKeyName - // szValue - // Output : Returns true. //----------------------------------------------------------------------------- bool CBaseDoor::KeyValue( const char *szKeyName, const char *szValue ) { if (FStrEq(szKeyName, "locked_sentence")) { m_bLockedSentence = atof(szValue); } else if (FStrEq(szKeyName, "unlocked_sentence")) { m_bUnlockedSentence = atof(szValue); } else return BaseClass::KeyValue( szKeyName, szValue ); return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseDoor::Spawn() { Precache(); #ifdef HL1_DLL SetSolid( SOLID_BSP ); #else if ( GetMoveParent() && GetRootMoveParent()->GetSolid() == SOLID_BSP ) { SetSolid( SOLID_BSP ); } else { SetSolid( SOLID_VPHYSICS ); } #endif // Convert movedir from angles to a vector QAngle angMoveDir = QAngle( m_vecMoveDir.x, m_vecMoveDir.y, m_vecMoveDir.z ); AngleVectors( angMoveDir, &m_vecMoveDir ); SetModel( STRING( GetModelName() ) ); m_vecPosition1 = GetLocalOrigin(); // Subtract 2 from size because the engine expands bboxes by 1 in all directions making the size too big Vector vecOBB = CollisionProp()->OBBSize(); vecOBB -= Vector( 2, 2, 2 ); m_vecPosition2 = m_vecPosition1 + (m_vecMoveDir * (DotProductAbs( m_vecMoveDir, vecOBB ) - m_flLip)); if ( !IsRotatingDoor() ) { if ( ( m_eSpawnPosition == FUNC_DOOR_SPAWN_OPEN ) || HasSpawnFlags( SF_DOOR_START_OPEN_OBSOLETE ) ) { // swap pos1 and pos2, put door at pos2 UTIL_SetOrigin( this, m_vecPosition2); m_toggle_state = TS_AT_TOP; } else { m_toggle_state = TS_AT_BOTTOM; } } if (HasSpawnFlags(SF_DOOR_LOCKED)) { m_bLocked = true; } SetMoveType( MOVETYPE_PUSH ); if (m_flSpeed == 0) { m_flSpeed = 100; } SetTouch( &CBaseDoor::DoorTouch ); if ( !FClassnameIs( this, "func_water" ) ) { if ( HasSpawnFlags(SF_DOOR_PASSABLE) ) { //normal door AddEFlags( EFL_USE_PARTITION_WHEN_NOT_SOLID ); AddSolidFlags( FSOLID_NOT_SOLID ); } if ( HasSpawnFlags( SF_DOOR_NONSOLID_TO_PLAYER ) ) { SetCollisionGroup( COLLISION_GROUP_PASSABLE_DOOR ); // HACKHACK: Set this hoping that any children of the door that get blocked by the player // will get fixed up by vphysics // NOTE: We could decouple this as a separate behavior, but managing player collisions is already complex enough. // NOTE: This is necessary to prevent the player from blocking the wrecked train car in ep2_outland_01 AddFlag( FL_UNBLOCKABLE_BY_PLAYER ); } if ( m_bIgnoreDebris ) { // both of these flags want to set the collision group and // there isn't a combo group Assert( !HasSpawnFlags( SF_DOOR_NONSOLID_TO_PLAYER ) ); if ( HasSpawnFlags( SF_DOOR_NONSOLID_TO_PLAYER ) ) { Warning("Door %s with conflicting collision settings, removing ignoredebris\n", GetDebugName() ); } else { SetCollisionGroup( COLLISION_GROUP_INTERACTIVE ); } } } if ( ( m_eSpawnPosition == FUNC_DOOR_SPAWN_OPEN ) && HasSpawnFlags( SF_DOOR_START_OPEN_OBSOLETE ) ) { Warning("Door %s using obsolete 'Start Open' spawnflag with 'Spawn Position' set to 'Open'. Reverting to old behavior.\n", GetDebugName() ); } CreateVPhysics(); #ifdef TF_DLL if ( TFGameRules() && TFGameRules()->IsMultiplayer() ) { if ( !m_flBlockDamage ) { // Never block doors in TF2 - to prevent various exploits. m_flBlockDamage = 10.f; } } #endif // TF_DLL } void CBaseDoor::MovingSoundThink( void ) { CPASAttenuationFilter filter( this ); filter.MakeReliable(); EmitSound_t ep; ep.m_nChannel = CHAN_STATIC; if ( m_NoiseMovingClosed == NULL_STRING || m_toggle_state == TS_GOING_DOWN || m_toggle_state == TS_AT_BOTTOM ) { ep.m_pSoundName = (char*)STRING(m_NoiseMoving); } else { ep.m_pSoundName = (char*)STRING(m_NoiseMovingClosed); } ep.m_flVolume = 1; ep.m_SoundLevel = SNDLVL_NORM; EmitSound( filter, entindex(), ep ); //Only loop sounds in HL1 to maintain HL2 behavior if( ShouldLoopMoveSound() ) { float duration = enginesound->GetSoundDuration( ep.m_pSoundName ); SetContextThink( &CBaseDoor::MovingSoundThink, gpGlobals->curtime + duration, "MovingSound" ); } } void CBaseDoor::StartMovingSound( void ) { MovingSoundThink(); #ifdef CSTRIKE_DLL // this event is only used by CS:S bots CBasePlayer *player = ToBasePlayer(m_hActivator); IGameEvent * event = gameeventmanager->CreateEvent( "door_moving" ); if( event ) { event->SetInt( "entindex", entindex() ); event->SetInt( "userid", (player)?player->GetUserID():0 ); gameeventmanager->FireEvent( event ); } #endif } void CBaseDoor::StopMovingSound(void) { SetContextThink( NULL, gpGlobals->curtime, "MovingSound" ); char *pSoundName; if ( m_NoiseMovingClosed == NULL_STRING || m_toggle_state == TS_GOING_UP || m_toggle_state == TS_AT_TOP ) { pSoundName = (char*)STRING(m_NoiseMoving); } else { pSoundName = (char*)STRING(m_NoiseMovingClosed); } StopSound( entindex(), CHAN_STATIC, pSoundName ); } bool CBaseDoor::ShouldSavePhysics() { // don't save physics if you're func_water return !FClassnameIs( this, "func_water" ); } //----------------------------------------------------------------------------- bool CBaseDoor::CreateVPhysics( ) { if ( !FClassnameIs( this, "func_water" ) ) { //normal door // NOTE: Create this even when the door is not solid to support constraints. VPhysicsInitShadow( false, false ); } else { // special contents AddSolidFlags( FSOLID_VOLUME_CONTENTS ); SETBITS( m_spawnflags, SF_DOOR_SILENT ); // water is silent for now IPhysicsObject *pPhysics = VPhysicsInitShadow( false, false ); fluidparams_t fluid; Assert( CollisionProp()->GetCollisionAngles() == vec3_angle ); fluid.damping = 0.01f; fluid.surfacePlane[0] = 0; fluid.surfacePlane[1] = 0; fluid.surfacePlane[2] = 1; fluid.surfacePlane[3] = CollisionProp()->GetCollisionOrigin().z + CollisionProp()->OBBMaxs().z - 1; fluid.currentVelocity.Init(0,0,0); fluid.torqueFactor = 0.1f; fluid.viscosityFactor = 0.01f; fluid.pGameData = static_cast<void *>(this); //FIXME: Currently there's no way to specify that you want slime fluid.contents = CONTENTS_WATER; physenv->CreateFluidController( pPhysics, &fluid ); } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseDoor::Activate( void ) { BaseClass::Activate(); CBaseDoor *pDoorList[64]; m_bDoorGroup = true; // force movement groups to sync!!! int doorCount = GetDoorMovementGroup( pDoorList, ARRAYSIZE(pDoorList) ); for ( int i = 0; i < doorCount; i++ ) { if ( pDoorList[i]->m_vecMoveDir == m_vecMoveDir ) { bool error = false; if ( pDoorList[i]->IsRotatingDoor() ) { error = ( pDoorList[i]->GetLocalAngles() != GetLocalAngles() ) ? true : false; } else { error = ( pDoorList[i]->GetLocalOrigin() != GetLocalOrigin() ) ? true : false; } if ( error ) { // don't do group blocking m_bDoorGroup = false; #ifdef HL1_DLL // UNDONE: This should probably fixup m_vecPosition1 & m_vecPosition2 Warning("Door group %s has misaligned origin!\n", STRING(GetEntityName()) ); #endif } } } switch ( m_toggle_state ) { case TS_AT_TOP: UpdateAreaPortals( true ); break; case TS_AT_BOTTOM: UpdateAreaPortals( false ); break; } #ifdef HL1_DLL // Get a handle to my filter entity if there is one if (m_iBlockFilterName != NULL_STRING) { m_hBlockFilter = dynamic_cast<CBaseFilter *>(gEntList.FindEntityByName( NULL, m_iBlockFilterName, NULL )); } #endif } //----------------------------------------------------------------------------- // Purpose: // Input : state - //----------------------------------------------------------------------------- // This is ONLY used by the node graph to test movement through a door void CBaseDoor::InputSetToggleState( inputdata_t &inputdata ) { SetToggleState( inputdata.value.Int() ); } void CBaseDoor::SetToggleState( int state ) { if ( state == TS_AT_TOP ) UTIL_SetOrigin( this, m_vecPosition2 ); else UTIL_SetOrigin( this, m_vecPosition1 ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseDoor::Precache( void ) { //Fill in a default value if necessary if ( IsRotatingDoor() ) { UTIL_ValidateSoundName( m_NoiseMoving, "RotDoorSound.DefaultMove" ); UTIL_ValidateSoundName( m_NoiseArrived, "RotDoorSound.DefaultArrive" ); UTIL_ValidateSoundName( m_ls.sLockedSound, "RotDoorSound.DefaultLocked" ); UTIL_ValidateSoundName( m_ls.sUnlockedSound,"DoorSound.Null" ); } else { UTIL_ValidateSoundName( m_NoiseMoving, "DoorSound.DefaultMove" ); UTIL_ValidateSoundName( m_NoiseArrived, "DoorSound.DefaultArrive" ); #ifndef HL1_DLL UTIL_ValidateSoundName( m_ls.sLockedSound, "DoorSound.DefaultLocked" ); #endif UTIL_ValidateSoundName( m_ls.sUnlockedSound,"DoorSound.Null" ); } #ifdef HL1_DLL if( m_ls.sLockedSound != NULL_STRING && strlen((char*)STRING(m_ls.sLockedSound)) < 4 ) { // Too short to be ANYTHING ".wav", so it must be an old index into a long-lost // array of sound choices. slam it to a known "deny" sound. We lose the designer's // original selection, but we don't get unresponsive doors. m_ls.sLockedSound = AllocPooledString("buttons/button2.wav"); } #endif//HL1_DLL //Precache them all PrecacheScriptSound( (char *) STRING(m_NoiseMoving) ); PrecacheScriptSound( (char *) STRING(m_NoiseArrived) ); PrecacheScriptSound( (char *) STRING(m_NoiseMovingClosed) ); PrecacheScriptSound( (char *) STRING(m_NoiseArrivedClosed) ); PrecacheScriptSound( (char *) STRING(m_ls.sLockedSound) ); PrecacheScriptSound( (char *) STRING(m_ls.sUnlockedSound) ); //Get sentence group names, for doors which are directly 'touched' to open switch (m_bLockedSentence) { case 1: m_ls.sLockedSentence = AllocPooledString("NA"); break; // access denied case 2: m_ls.sLockedSentence = AllocPooledString("ND"); break; // security lockout case 3: m_ls.sLockedSentence = AllocPooledString("NF"); break; // blast door case 4: m_ls.sLockedSentence = AllocPooledString("NFIRE"); break; // fire door case 5: m_ls.sLockedSentence = AllocPooledString("NCHEM"); break; // chemical door case 6: m_ls.sLockedSentence = AllocPooledString("NRAD"); break; // radiation door case 7: m_ls.sLockedSentence = AllocPooledString("NCON"); break; // gen containment case 8: m_ls.sLockedSentence = AllocPooledString("NH"); break; // maintenance door case 9: m_ls.sLockedSentence = AllocPooledString("NG"); break; // broken door default: m_ls.sLockedSentence = NULL_STRING; break; } switch (m_bUnlockedSentence) { case 1: m_ls.sUnlockedSentence = AllocPooledString("EA"); break; // access granted case 2: m_ls.sUnlockedSentence = AllocPooledString("ED"); break; // security door case 3: m_ls.sUnlockedSentence = AllocPooledString("EF"); break; // blast door case 4: m_ls.sUnlockedSentence = AllocPooledString("EFIRE"); break; // fire door case 5: m_ls.sUnlockedSentence = AllocPooledString("ECHEM"); break; // chemical door case 6: m_ls.sUnlockedSentence = AllocPooledString("ERAD"); break; // radiation door case 7: m_ls.sUnlockedSentence = AllocPooledString("ECON"); break; // gen containment case 8: m_ls.sUnlockedSentence = AllocPooledString("EH"); break; // maintenance door default: m_ls.sUnlockedSentence = NULL_STRING; break; } } //----------------------------------------------------------------------------- // Purpose: Doors not tied to anything (e.g. button, another door) can be touched, // to make them activate. // Input : *pOther - //----------------------------------------------------------------------------- void CBaseDoor::DoorTouch( CBaseEntity *pOther ) { if( m_ChainTarget != NULL_STRING ) ChainTouch( pOther ); // Ignore touches by anything but players. if ( !pOther->IsPlayer() ) { #ifdef HL1_DLL if( PassesBlockTouchFilter( pOther ) && m_toggle_state == TS_GOING_DOWN ) { DoorGoUp(); } #endif return; } // If door is not opened by touch, do nothing. if ( !HasSpawnFlags(SF_DOOR_PTOUCH) ) { #ifdef HL1_DLL if( m_toggle_state == TS_AT_BOTTOM ) { PlayLockSounds(this, &m_ls, TRUE, FALSE); } #endif//HL1_DLL return; } // If door has master, and it's not ready to trigger, // play 'locked' sound. if (m_sMaster != NULL_STRING && !UTIL_IsMasterTriggered(m_sMaster, pOther)) { PlayLockSounds(this, &m_ls, TRUE, FALSE); } if (m_bLocked) { m_OnLockedUse.FireOutput( pOther, pOther ); PlayLockSounds(this, &m_ls, TRUE, FALSE); return; } // Remember who activated the door. m_hActivator = pOther; if (DoorActivate( )) { // Temporarily disable the touch function, until movement is finished. SetTouch( NULL ); } } #ifdef HL1_DLL bool CBaseDoor::PassesBlockTouchFilter(CBaseEntity *pOther) { CBaseFilter* pFilter = (CBaseFilter*)(m_hBlockFilter.Get()); return ( pFilter && pFilter->PassesFilter( this, pOther ) ); } #endif //----------------------------------------------------------------------------- // Purpose: Delays turning off area portals when closing doors to prevent visual artifacts //----------------------------------------------------------------------------- void CBaseDoor::CloseAreaPortalsThink( void ) { UpdateAreaPortals( false ); SetContextThink( NULL, gpGlobals->curtime, CLOSE_AREAPORTAL_THINK_CONTEXT ); } //----------------------------------------------------------------------------- // Purpose: // Input : isOpen - //----------------------------------------------------------------------------- void CBaseDoor::UpdateAreaPortals( bool isOpen ) { // cancel pending close SetContextThink( NULL, gpGlobals->curtime, CLOSE_AREAPORTAL_THINK_CONTEXT ); if ( IsRotatingDoor() && HasSpawnFlags(SF_DOOR_START_OPEN_OBSOLETE) ) // logic inverted when using rot doors that start open isOpen = !isOpen; string_t name = GetEntityName(); if ( !name ) return; CBaseEntity *pPortal = NULL; while ( ( pPortal = gEntList.FindEntityByClassname( pPortal, "func_areaportal" ) ) != NULL ) { if ( pPortal->HasTarget( name ) ) { // USE_ON means open the portal, off means close it pPortal->Use( this, this, isOpen?USE_ON:USE_OFF, 0 ); } } } //----------------------------------------------------------------------------- // Purpose: Called when the player uses the door. // Input : pActivator - // pCaller - // useType - // value - //----------------------------------------------------------------------------- void CBaseDoor::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { m_hActivator = pActivator; if( m_ChainTarget != NULL_STRING ) ChainUse(); // We can't +use this if it can't be +used if ( m_hActivator != NULL && m_hActivator->IsPlayer() && HasSpawnFlags( SF_DOOR_PUSE ) == false ) { PlayLockSounds( this, &m_ls, TRUE, FALSE ); return; } bool bAllowUse = false; // if not ready to be used, ignore "use" command. if( HasSpawnFlags(SF_DOOR_NEW_USE_RULES) ) { //New behavior: // If not ready to be used, ignore "use" command. // Allow use in these cases: // - when the door is closed/closing // - when the door is open/opening and can be manually closed if ( ( m_toggle_state == TS_AT_BOTTOM || m_toggle_state == TS_GOING_DOWN ) || ( HasSpawnFlags(SF_DOOR_NO_AUTO_RETURN) && ( m_toggle_state == TS_AT_TOP || m_toggle_state == TS_GOING_UP ) ) ) bAllowUse = true; } else { // Legacy behavior: if (m_toggle_state == TS_AT_BOTTOM || (HasSpawnFlags(SF_DOOR_NO_AUTO_RETURN) && m_toggle_state == TS_AT_TOP) ) bAllowUse = true; } if( bAllowUse ) { if (m_bLocked) { m_OnLockedUse.FireOutput( pActivator, pCaller ); PlayLockSounds(this, &m_ls, TRUE, FALSE); } else { DoorActivate(); } } } //----------------------------------------------------------------------------- // Purpose: Passes Use along to certain named doors. //----------------------------------------------------------------------------- void CBaseDoor::ChainUse( void ) { if ( m_isChaining ) return; CBaseEntity *ent = NULL; while ( ( ent = gEntList.FindEntityByName( ent, m_ChainTarget, NULL ) ) != NULL ) { if ( ent == this ) continue; CBaseDoor *door = dynamic_cast< CBaseDoor * >( ent ); if ( door ) { door->SetChaining( true ); door->Use( m_hActivator, NULL, USE_TOGGLE, 0.0f ); // only the first param is used door->SetChaining( false ); } } } //----------------------------------------------------------------------------- // Purpose: Passes Touch along to certain named doors. //----------------------------------------------------------------------------- void CBaseDoor::ChainTouch( CBaseEntity *pOther ) { if ( m_isChaining ) return; CBaseEntity *ent = NULL; while ( ( ent = gEntList.FindEntityByName( ent, m_ChainTarget, NULL ) ) != NULL ) { if ( ent == this ) continue; CBaseDoor *door = dynamic_cast< CBaseDoor * >( ent ); if ( door ) { door->SetChaining( true ); door->Touch( pOther ); door->SetChaining( false ); } } } //----------------------------------------------------------------------------- // Purpose: Closes the door if it is not already closed. //----------------------------------------------------------------------------- void CBaseDoor::InputClose( inputdata_t &inputdata ) { if ( m_toggle_state != TS_AT_BOTTOM ) { DoorGoDown(); } } //----------------------------------------------------------------------------- // Purpose: Input handler that locks the door. //----------------------------------------------------------------------------- void CBaseDoor::InputLock( inputdata_t &inputdata ) { Lock(); } //----------------------------------------------------------------------------- // Purpose: Opens the door if it is not already open. //----------------------------------------------------------------------------- void CBaseDoor::InputOpen( inputdata_t &inputdata ) { if (m_toggle_state != TS_AT_TOP && m_toggle_state != TS_GOING_UP ) { // I'm locked, can't open if (m_bLocked) return; // Play door unlock sounds. PlayLockSounds(this, &m_ls, false, false); DoorGoUp(); } } //----------------------------------------------------------------------------- // Purpose: Opens the door if it is not already open. //----------------------------------------------------------------------------- void CBaseDoor::InputToggle( inputdata_t &inputdata ) { // I'm locked, can't open if (m_bLocked) return; if (m_toggle_state == TS_AT_BOTTOM) { DoorGoUp(); } else if (m_toggle_state == TS_AT_TOP) { DoorGoDown(); } } //----------------------------------------------------------------------------- // Purpose: Input handler that unlocks the door. //----------------------------------------------------------------------------- void CBaseDoor::InputUnlock( inputdata_t &inputdata ) { Unlock(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CBaseDoor::InputSetSpeed( inputdata_t &inputdata ) { m_flSpeed = inputdata.value.Float(); } //----------------------------------------------------------------------------- // Purpose: Locks the door so that it cannot be opened. //----------------------------------------------------------------------------- void CBaseDoor::Lock( void ) { m_bLocked = true; } //----------------------------------------------------------------------------- // Purpose: Unlocks the door so that it can be opened. //----------------------------------------------------------------------------- void CBaseDoor::Unlock( void ) { m_bLocked = false; } //----------------------------------------------------------------------------- // Purpose: Causes the door to "do its thing", i.e. start moving, and cascade activation. // Output : int //----------------------------------------------------------------------------- int CBaseDoor::DoorActivate( ) { if (!UTIL_IsMasterTriggered(m_sMaster, m_hActivator)) return 0; if (HasSpawnFlags(SF_DOOR_NO_AUTO_RETURN) && m_toggle_state == TS_AT_TOP) { // door should close DoorGoDown(); } else { // door should open // play door unlock sounds PlayLockSounds(this, &m_ls, FALSE, FALSE); if ( m_toggle_state != TS_AT_TOP && m_toggle_state != TS_GOING_UP ) { DoorGoUp(); } } return 1; } //----------------------------------------------------------------------------- // Purpose: Starts the door going to its "up" position (simply ToggleData->vecPosition2). //----------------------------------------------------------------------------- void CBaseDoor::DoorGoUp( void ) { edict_t *pevActivator; UpdateAreaPortals( true ); // It could be going-down, if blocked. ASSERT(m_toggle_state == TS_AT_BOTTOM || m_toggle_state == TS_GOING_DOWN); // emit door moving and stop sounds on CHAN_STATIC so that the multicast doesn't // filter them out and leave a client stuck with looping door sounds! if ( !HasSpawnFlags(SF_DOOR_SILENT ) ) { // If we're not moving already, start the moving noise if ( m_toggle_state != TS_GOING_UP && m_toggle_state != TS_GOING_DOWN ) { StartMovingSound(); } } m_toggle_state = TS_GOING_UP; SetMoveDone( &CBaseDoor::DoorHitTop ); if ( IsRotatingDoor() ) // !!! BUGBUG Triggered doors don't work with this yet { float sign = 1.0; if ( m_hActivator != NULL ) { pevActivator = m_hActivator->edict(); if ( !HasSpawnFlags( SF_DOOR_ONEWAY ) && m_vecMoveAng.y ) // Y axis rotation, move away from the player { // Positive is CCW, negative is CW, so make 'sign' 1 or -1 based on which way we want to open. // Important note: All doors face East at all times, and twist their local angle to open. // So you can't look at the door's facing to determine which way to open. Vector nearestPoint; CollisionProp()->CalcNearestPoint( m_hActivator->GetAbsOrigin(), &nearestPoint ); Vector activatorToNearestPoint = nearestPoint - m_hActivator->GetAbsOrigin(); activatorToNearestPoint.z = 0; Vector activatorToOrigin = GetAbsOrigin() - m_hActivator->GetAbsOrigin(); activatorToOrigin.z = 0; // Point right hand at door hinge, curl hand towards closest spot on door, if thumb // is up, open door CW. -- Department of Basic Cross Product Understanding for Noobs Vector cross = activatorToOrigin.Cross( activatorToNearestPoint ); if( cross.z > 0.0f ) { sign = -1.0f; } } } AngularMove(m_vecAngle2*sign, m_flSpeed); } else { LinearMove(m_vecPosition2, m_flSpeed); } //Fire our open ouput m_OnOpen.FireOutput( this, this ); } //----------------------------------------------------------------------------- // Purpose: The door has reached the "up" position. Either go back down, or // wait for another activation. //----------------------------------------------------------------------------- void CBaseDoor::DoorHitTop( void ) { if ( !HasSpawnFlags( SF_DOOR_SILENT ) ) { CPASAttenuationFilter filter( this ); filter.MakeReliable(); StopMovingSound(); EmitSound_t ep; ep.m_nChannel = CHAN_STATIC; ep.m_pSoundName = (char*)STRING(m_NoiseArrived); ep.m_flVolume = 1; ep.m_SoundLevel = SNDLVL_NORM; EmitSound( filter, entindex(), ep ); } ASSERT(m_toggle_state == TS_GOING_UP); m_toggle_state = TS_AT_TOP; // toggle-doors don't come down automatically, they wait for refire. if (HasSpawnFlags( SF_DOOR_NO_AUTO_RETURN)) { // Re-instate touch method, movement is complete SetTouch( &CBaseDoor::DoorTouch ); } else { // In flWait seconds, DoorGoDown will fire, unless wait is -1, then door stays open SetMoveDoneTime( m_flWait ); SetMoveDone( &CBaseDoor::DoorGoDown ); if ( m_flWait == -1 ) { SetNextThink( TICK_NEVER_THINK ); } } if (HasSpawnFlags(SF_DOOR_START_OPEN_OBSOLETE) ) { m_OnFullyClosed.FireOutput(this, this); } else { m_OnFullyOpen.FireOutput(this, this); } } //----------------------------------------------------------------------------- // Purpose: Starts the door going to its "down" position (simply ToggleData->vecPosition1). //----------------------------------------------------------------------------- void CBaseDoor::DoorGoDown( void ) { if ( !HasSpawnFlags( SF_DOOR_SILENT ) ) { // If we're not moving already, start the moving noise if ( m_toggle_state != TS_GOING_UP && m_toggle_state != TS_GOING_DOWN ) { StartMovingSound(); } } #ifdef DOOR_ASSERT ASSERT(m_toggle_state == TS_AT_TOP); #endif // DOOR_ASSERT m_toggle_state = TS_GOING_DOWN; SetMoveDone( &CBaseDoor::DoorHitBottom ); if ( IsRotatingDoor() )//rotating door AngularMove( m_vecAngle1, m_flSpeed); else LinearMove( m_vecPosition1, m_flSpeed); //Fire our closed output m_OnClose.FireOutput( this, this ); } //----------------------------------------------------------------------------- // Purpose: The door has reached the "down" position. Back to quiescence. //----------------------------------------------------------------------------- void CBaseDoor::DoorHitBottom( void ) { if ( !HasSpawnFlags( SF_DOOR_SILENT ) ) { CPASAttenuationFilter filter( this ); filter.MakeReliable(); StopMovingSound(); EmitSound_t ep; ep.m_nChannel = CHAN_STATIC; if ( m_NoiseArrivedClosed == NULL_STRING ) ep.m_pSoundName = (char*)STRING(m_NoiseArrived); else ep.m_pSoundName = (char*)STRING(m_NoiseArrivedClosed); ep.m_flVolume = 1; ep.m_SoundLevel = SNDLVL_NORM; EmitSound( filter, entindex(), ep ); } ASSERT(m_toggle_state == TS_GOING_DOWN); m_toggle_state = TS_AT_BOTTOM; // Re-instate touch method, cycle is complete SetTouch( &CBaseDoor::DoorTouch ); if (HasSpawnFlags(SF_DOOR_START_OPEN_OBSOLETE)) { m_OnFullyOpen.FireOutput(m_hActivator, this); } else { m_OnFullyClosed.FireOutput(m_hActivator, this); } // Close the area portals just after the door closes, to prevent visual artifacts in multiplayer games SetContextThink( &CBaseDoor::CloseAreaPortalsThink, gpGlobals->curtime + 0.5f, CLOSE_AREAPORTAL_THINK_CONTEXT ); } // Lists all doors in the same movement group as this one int CBaseDoor::GetDoorMovementGroup( CBaseDoor *pDoorList[], int listMax ) { int count = 0; CBaseEntity *pTarget = NULL; // Block all door pieces with the same targetname here. if ( GetEntityName() != NULL_STRING ) { for (;;) { pTarget = gEntList.FindEntityByName( pTarget, GetEntityName(), NULL ); if ( pTarget != this ) { if ( !pTarget ) break; CBaseDoor *pDoor = dynamic_cast<CBaseDoor *>(pTarget); if ( pDoor && count < listMax ) { pDoorList[count] = pDoor; count++; } } } } return count; } //----------------------------------------------------------------------------- // Purpose: Called the first frame that the door is blocked while opening or closing. // Input : pOther - The blocking entity. //----------------------------------------------------------------------------- void CBaseDoor::StartBlocked( CBaseEntity *pOther ) { // // Fire whatever events we need to due to our blocked state. // if (m_toggle_state == TS_GOING_DOWN) { m_OnBlockedClosing.FireOutput(pOther, this); } else { m_OnBlockedOpening.FireOutput(pOther, this); } } //----------------------------------------------------------------------------- // Purpose: Called every frame when the door is blocked while opening or closing. // Input : pOther - The blocking entity. //----------------------------------------------------------------------------- void CBaseDoor::Blocked( CBaseEntity *pOther ) { // Hurt the blocker a little. if ( m_flBlockDamage ) { // if the door is marked "force closed" or it has a negative wait, then there's nothing to do but // push/damage the object. // If block damage is set, but this object is a physics prop that can't be damaged, just // give up and disable collisions if ( (m_bForceClosed || m_flWait < 0) && pOther->GetMoveType() == MOVETYPE_VPHYSICS && (pOther->m_takedamage == DAMAGE_NO || pOther->m_takedamage == DAMAGE_EVENTS_ONLY) ) { EntityPhysics_CreateSolver( this, pOther, true, 4.0f ); } else { pOther->TakeDamage( CTakeDamageInfo( this, this, m_flBlockDamage, DMG_CRUSH ) ); } } // If we're set to force ourselves closed, keep going if ( m_bForceClosed ) return; // if a door has a negative wait, it would never come back if blocked, // so let it just squash the object to death real fast if (m_flWait >= 0) { if (m_toggle_state == TS_GOING_DOWN) { DoorGoUp(); } else { DoorGoDown(); } } // Block all door pieces with the same targetname here. if ( GetEntityName() != NULL_STRING ) { CBaseDoor *pDoorList[64]; int doorCount = GetDoorMovementGroup( pDoorList, ARRAYSIZE(pDoorList) ); for ( int i = 0; i < doorCount; i++ ) { CBaseDoor *pDoor = pDoorList[i]; if ( pDoor->m_flWait >= 0) { if (m_bDoorGroup && pDoor->m_vecMoveDir == m_vecMoveDir && pDoor->GetAbsVelocity() == GetAbsVelocity() && pDoor->GetLocalAngularVelocity() == GetLocalAngularVelocity()) { pDoor->m_nSimulationTick = m_nSimulationTick; // don't run simulation this frame if you haven't run yet // this is the most hacked, evil, bastardized thing I've ever seen. kjb if ( !pDoor->IsRotatingDoor() ) {// set origin to realign normal doors pDoor->SetLocalOrigin( GetLocalOrigin() ); pDoor->SetAbsVelocity( vec3_origin );// stop! } else {// set angles to realign rotating doors pDoor->SetLocalAngles( GetLocalAngles() ); pDoor->SetLocalAngularVelocity( vec3_angle ); } } if ( pDoor->m_toggle_state == TS_GOING_DOWN) pDoor->DoorGoUp(); else pDoor->DoorGoDown(); } } } } //----------------------------------------------------------------------------- // Purpose: Called the first frame that the door is unblocked while opening or closing. //----------------------------------------------------------------------------- void CBaseDoor::EndBlocked( void ) { // // Fire whatever events we need to due to our unblocked state. // if (m_toggle_state == TS_GOING_DOWN) { m_OnUnblockedClosing.FireOutput(this, this); } else { m_OnUnblockedOpening.FireOutput(this, this); } } /*func_door_rotating TOGGLE causes the door to wait in both the start and end states for a trigger event. START_OPEN causes the door to move to its destination when spawned, and operate in reverse. It is used to temporarily or permanently close off an area when triggered (not usefull for touch or takedamage doors). You need to have an origin brush as part of this entity. The center of that brush will be the point around which it is rotated. It will rotate around the Z axis by default. You can check either the X_AXIS or Y_AXIS box to change that. "distance" is how many degrees the door will be rotated. "speed" determines how fast the door moves; default value is 100. REVERSE will cause the door to rotate in the opposite direction. "angle" determines the opening direction "targetname" if set, no touch field will be spawned and a remote button or trigger field activates the door. "health" if set, door must be shot open "speed" movement speed (100 default) "wait" wait before returning (3 default, -1 = never return) "dmg" damage to inflict when blocked (2 default) */ //================================================== // CRotDoor //================================================== class CRotDoor : public CBaseDoor { public: DECLARE_CLASS( CRotDoor, CBaseDoor ); void Spawn( void ); bool CreateVPhysics(); // This is ONLY used by the node graph to test movement through a door virtual void SetToggleState( int state ); virtual bool IsRotatingDoor() { return true; } bool m_bSolidBsp; DECLARE_DATADESC(); }; LINK_ENTITY_TO_CLASS( func_door_rotating, CRotDoor ); BEGIN_DATADESC( CRotDoor ) DEFINE_KEYFIELD( m_bSolidBsp, FIELD_BOOLEAN, "solidbsp" ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CRotDoor::Spawn( void ) { BaseClass::Spawn(); // set the axis of rotation CBaseToggle::AxisDir(); // check for clockwise rotation if ( HasSpawnFlags(SF_DOOR_ROTATE_BACKWARDS) ) m_vecMoveAng = m_vecMoveAng * -1; //m_flWait = 2; who the hell did this? (sjb) m_vecAngle1 = GetLocalAngles(); m_vecAngle2 = GetLocalAngles() + m_vecMoveAng * m_flMoveDistance; ASSERTSZ(m_vecAngle1 != m_vecAngle2, "rotating door start/end positions are equal\n"); // Starting open allows a func_door to be lighted in the closed position but // spawn in the open position // // SF_DOOR_START_OPEN_OBSOLETE is an old broken way of spawning open that has // been deprecated. if ( HasSpawnFlags(SF_DOOR_START_OPEN_OBSOLETE) ) { // swap pos1 and pos2, put door at pos2, invert movement direction QAngle vecNewAngles = m_vecAngle2; m_vecAngle2 = m_vecAngle1; m_vecAngle1 = vecNewAngles; m_vecMoveAng = -m_vecMoveAng; // We've already had our physics setup in BaseClass::Spawn, so teleport to our // current position. If we don't do this, our vphysics shadow will not update. Teleport( NULL, &m_vecAngle1, NULL ); m_toggle_state = TS_AT_BOTTOM; } else if ( m_eSpawnPosition == FUNC_DOOR_SPAWN_OPEN ) { // We've already had our physics setup in BaseClass::Spawn, so teleport to our // current position. If we don't do this, our vphysics shadow will not update. Teleport( NULL, &m_vecAngle2, NULL ); m_toggle_state = TS_AT_TOP; } else { m_toggle_state = TS_AT_BOTTOM; } #ifdef HL1_DLL SetSolid( SOLID_VPHYSICS ); #endif // Slam the object back to solid - if we really want it to be solid. if ( m_bSolidBsp ) { SetSolid( SOLID_BSP ); } } //----------------------------------------------------------------------------- bool CRotDoor::CreateVPhysics() { if ( !IsSolidFlagSet( FSOLID_NOT_SOLID ) ) { VPhysicsInitShadow( false, false ); } return true; } //----------------------------------------------------------------------------- // Purpose: // Input : state - //----------------------------------------------------------------------------- // This is ONLY used by the node graph to test movement through a door void CRotDoor::SetToggleState( int state ) { if ( state == TS_AT_TOP ) SetLocalAngles( m_vecAngle2 ); else SetLocalAngles( m_vecAngle1 ); }
29.49021
191
0.620237
[ "object", "vector", "solid" ]
c8cc6db6e631c0650b4baa6cec865a065926f7c1
10,744
cpp
C++
src/utils/xrAI/game_spawn_constructor.cpp
Samsuper12/ixray-1.6
95b8ad458d4550118c7fbf34c5de872f3d1ca75e
[ "Linux-OpenIB" ]
2
2020-05-17T10:02:18.000Z
2020-08-08T21:10:36.000Z
src/utils/xrAI/game_spawn_constructor.cpp
ixray-team/ixray-1.6-stworld
a8d211b1c4961fad5c9a6835c6b08f7b05d9c5ac
[ "Linux-OpenIB" ]
null
null
null
src/utils/xrAI/game_spawn_constructor.cpp
ixray-team/ixray-1.6-stworld
a8d211b1c4961fad5c9a6835c6b08f7b05d9c5ac
[ "Linux-OpenIB" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// // Module : game_spawn_constructor.cpp // Created : 16.10.2004 // Modified : 16.10.2004 // Author : Dmitriy Iassenev // Description : Game spawn constructor //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "game_spawn_constructor.h" #include "object_broker.h" #include "level_spawn_constructor.h" #include "xrServer_Objects_ALife_All.h" #include "xrai.h" #include "server_entity_wrapper.h" #include "graph_engine.h" #include "patrol_path_storage.h" extern LPCSTR GAME_CONFIG; extern LPCSTR generate_temp_file_name (LPCSTR header0, LPCSTR header1, string_path& buffer); #define NO_MULTITHREADING CGameSpawnConstructor::CGameSpawnConstructor (LPCSTR name, LPCSTR output, LPCSTR start, bool no_separator_check) #ifdef PROFILE_CRITICAL_SECTIONS :m_critical_section(MUTEX_PROFILE_ID(CGameSpawnConstructor)) #endif // PROFILE_CRITICAL_SECTIONS { load_spawns (name,no_separator_check); process_spawns (); process_actor (start); save_spawn (name,output); } CGameSpawnConstructor::~CGameSpawnConstructor () { delete_data (m_level_spawns); delete_data (m_spawn_graph); xr_delete (m_game_graph); xr_delete (m_game_info); xr_delete (m_patrol_path_storage); } IC shared_str CGameSpawnConstructor::actor_level_name() { string256 temp; return ( strconcat( sizeof(temp), temp, *game_graph().header().level( game_graph().vertex( m_actor->m_tGraphID )->level_id()).name(), ".spawn" ) ); } extern void read_levels (CInifile *ini, xr_set<CLevelInfo> &m_levels, bool rebuild_graph, xr_vector<LPCSTR> *); void fill_needed_levels (LPSTR levels, xr_vector<LPCSTR> &result); void CGameSpawnConstructor::load_spawns (LPCSTR name, bool no_separator_check) { m_spawn_id = 0; // init spawn graph m_spawn_graph = xr_new<SPAWN_GRAPH>(); // init ini file m_game_info = xr_new<CInifile>(INI_FILE); R_ASSERT (m_game_info->section_exist("levels")); // init patrol path storage m_patrol_path_storage = xr_new<CPatrolPathStorage>(); xr_vector<LPCSTR> needed_levels; string4096 levels_string; xr_strcpy (levels_string,name); strlwr (levels_string); fill_needed_levels (levels_string,needed_levels); // fill level info read_levels ( &game_info(), m_levels, false, &needed_levels ); // init game graph generate_temp_file_name ("game_graph","",m_game_graph_id); xrMergeGraphs (m_game_graph_id,name,false); m_game_graph = xr_new<CGameGraph>(m_game_graph_id); // load levels GameGraph::SLevel level; LEVEL_INFO_STORAGE::const_iterator I = m_levels.begin(); LEVEL_INFO_STORAGE::const_iterator E = m_levels.end(); for ( ; I != E; ++I) { level.m_offset = (*I).m_offset; level.m_name = (*I).m_name; level.m_id = (*I).m_id; Msg ("%9s %2d %s","level",level.id(),*(*I).m_name); m_level_spawns.push_back (xr_new<CLevelSpawnConstructor>(level,this,no_separator_check)); } string256 temp; xr_sprintf (temp,"There are no valid levels (with AI-map and graph) in the section 'levels' in the '%s' to build spawn file from!",GAME_CONFIG); R_ASSERT2 (!m_level_spawns.empty(),temp); } void CGameSpawnConstructor::process_spawns () { LEVEL_SPAWN_STORAGE::iterator I = m_level_spawns.begin(); LEVEL_SPAWN_STORAGE::iterator E = m_level_spawns.end(); for ( ; I != E; ++I) #ifdef NO_MULTITHREADING (*I)->Execute (); #else m_thread_manager.start (*I); m_thread_manager.wait (); #endif I = m_level_spawns.begin(); for ( ; I != E; ++I) (*I)->update (); verify_level_changers (); verify_spawns (); } void CGameSpawnConstructor::verify_spawns (ALife::_SPAWN_ID spawn_id) { xr_vector<ALife::_SPAWN_ID>::iterator J = std::find(m_temp0.begin(),m_temp0.end(),spawn_id); R_ASSERT3 (J == m_temp0.end(),"RECURSIVE Spawn group chain found in spawn",m_spawn_graph->vertex(spawn_id)->data()->object().name_replace()); m_temp0.push_back (spawn_id); SPAWN_GRAPH::CVertex *vertex = m_spawn_graph->vertex(spawn_id); SPAWN_GRAPH::const_iterator I = vertex->edges().begin(); SPAWN_GRAPH::const_iterator E = vertex->edges().end(); for ( ; I != E; ++I) verify_spawns ((*I).vertex_id()); } void CGameSpawnConstructor::verify_spawns () { SPAWN_GRAPH::const_vertex_iterator I = m_spawn_graph->vertices().begin(); SPAWN_GRAPH::const_vertex_iterator E = m_spawn_graph->vertices().end(); for ( ; I != E; ++I) { m_temp0.clear (); verify_spawns ((*I).second->vertex_id()); } } void CGameSpawnConstructor::verify_level_changers () { if (m_level_changers.empty()) return; Msg ("List of the level changers which are invalid for some reasons"); LEVEL_CHANGER_STORAGE::const_iterator I = m_level_changers.begin(); LEVEL_CHANGER_STORAGE::const_iterator E = m_level_changers.end(); for ( ; I != E; ++I) Msg ("%s",(*I)->name_replace()); VERIFY2 (m_level_changers.empty(),"Some of the level changers setup incorrectly"); } void CGameSpawnConstructor::save_spawn (LPCSTR name, LPCSTR output) { CMemoryWriter stream; m_spawn_header.m_version = XRAI_CURRENT_VERSION; m_spawn_header.m_guid = generate_guid(); m_spawn_header.m_graph_guid = game_graph().header().guid(); m_spawn_header.m_spawn_count = spawn_graph().vertex_count(); m_spawn_header.m_level_count = (u32)m_level_spawns.size(); stream.open_chunk (0); stream.w_u32 (m_spawn_header.m_version); save_data (m_spawn_header.m_guid,stream); save_data (m_spawn_header.m_graph_guid,stream); stream.w_u32 (m_spawn_header.m_spawn_count); stream.w_u32 (m_spawn_header.m_level_count); stream.close_chunk (); stream.open_chunk (1); save_data (spawn_graph(),stream); stream.close_chunk (); stream.open_chunk (2); save_data (m_level_points,stream); stream.close_chunk (); stream.open_chunk (3); save_data (m_patrol_path_storage,stream); stream.close_chunk (); stream.open_chunk (4); m_game_graph->save (stream); stream.close_chunk (); stream.save_to (*spawn_name(output)); } shared_str CGameSpawnConstructor::spawn_name (LPCSTR output) { string_path file_name; if (!output) FS.update_path (file_name,"$game_spawn$",*actor_level_name()); else { actor_level_name (); string_path out; strconcat (sizeof(out),out,output,".spawn"); FS.update_path (file_name,"$game_spawn$",out); } return (file_name); } void CGameSpawnConstructor::add_story_object (ALife::_STORY_ID id, CSE_ALifeDynamicObject *object, LPCSTR level_name) { if (id == INVALID_STORY_ID) return; ALife::STORY_P_PAIR_IT I = m_story_objects.find(id); if (I != m_story_objects.end()) { Msg ("Object %s, story id %d",object->name_replace(),object->m_story_id); Msg ("Object %s, story id %d",(*I).second->name_replace(),(*I).second->m_story_id); VERIFY3 (I == m_story_objects.end(),"There are several objects which has the same unique story ID, level ",level_name); } m_story_objects.insert (std::make_pair(id,object)); } void CGameSpawnConstructor::add_object (CSE_Abstract *object) { m_critical_section.Enter (); object->m_tSpawnID = spawn_id(); spawn_graph().add_vertex (xr_new<CServerEntityWrapper>(object),object->m_tSpawnID); m_critical_section.Leave (); } void CGameSpawnConstructor::remove_object (CSE_Abstract *object) { spawn_graph().remove_vertex (object->m_tSpawnID); } void CGameSpawnConstructor::process_actor (LPCSTR start_level_name) { m_actor = 0; LEVEL_SPAWN_STORAGE::iterator I = m_level_spawns.begin(); LEVEL_SPAWN_STORAGE::iterator E = m_level_spawns.end(); for ( ; I != E; ++I) { if (!(*I)->actor()) continue; Msg ("Actor is on the level %s",*game_graph().header().level(game_graph().vertex((*I)->actor()->m_tGraphID)->level_id()).name()); VERIFY2 (!m_actor,"There must be the SINGLE level with ACTOR!"); m_actor = (*I)->actor(); } R_ASSERT2 (m_actor,"There is no ACTOR spawn point!"); if (!start_level_name) return; if (!xr_strcmp(*actor_level_name(),start_level_name)) return; const CGameGraph::SLevel &level = game_graph().header().level(start_level_name); GameGraph::_GRAPH_ID dest = GameGraph::_GRAPH_ID(-1); GraphEngineSpace::CGameLevelParams evaluator(level.id()); CGraphEngine *graph_engine = xr_new<CGraphEngine>(game_graph().header().vertex_count()); bool failed = !graph_engine->search(game_graph(),m_actor->m_tGraphID,GameGraph::_GRAPH_ID(-1),0,evaluator); if (failed) { Msg ("! Cannot build path via game graph from the current level to the level %s!",start_level_name); float min_dist = flt_max; Fvector current = game_graph().vertex(m_actor->m_tGraphID)->game_point(); GameGraph::_GRAPH_ID n = game_graph().header().vertex_count(); for (GameGraph::_GRAPH_ID i=0; i<n; ++i) { if (game_graph().vertex(i)->level_id() == level.id()) { float distance = game_graph().vertex(i)->game_point().distance_to_sqr(current); if (distance < min_dist) { min_dist = distance; dest = i; } } } if (!game_graph().vertex(dest)) { Msg ("! There is no game vertices on the level %s, cannot jump to the specified level",start_level_name); return; } } else dest = (GameGraph::_GRAPH_ID)evaluator.selected_vertex_id(); m_actor->m_tGraphID = dest; m_actor->m_tNodeID = game_graph().vertex(dest)->level_vertex_id(); m_actor->o_Position = game_graph().vertex(dest)->level_point(); xr_delete (graph_engine); } void clear_temp_folder () { string_path query; FS.update_path (query,"$app_data_root$","temp\\*.*"); _finddata_t file; intptr_t handle = _findfirst(query, &file); if (handle == intptr_t(-1)) return; typedef xr_vector<shared_str> FILES; FILES files; do { if (file.attrib & _A_SUBDIR) continue; files.push_back (file.name); } while (!_findnext(handle, &file)); _findclose (handle); FILES::const_iterator I = files.begin(); FILES::const_iterator E = files.end(); for ( ; I != E; ++I) { if (DeleteFile(**I)) Msg ("file %s is successfully deleted",**I); else Msg ("cannot delete file %s",**I); } }
32.071642
153
0.659531
[ "object" ]
c8cc7c9ed7ccaaaf548e518167cf4a45ff85e47e
16,620
cpp
C++
Engine/source/afx/util/afxParticlePool_T3D.cpp
Parcons/Torque3D
516163fd5debea9c91b558046d858f5f56fc198d
[ "MIT" ]
417
2020-06-01T15:55:15.000Z
2022-03-31T12:50:51.000Z
Engine/source/afx/util/afxParticlePool_T3D.cpp
Ashry00/Torque3D
33e3e41c8b7eb41c743a589558bc21302207ef97
[ "MIT" ]
186
2020-06-02T19:12:39.000Z
2022-02-15T02:22:27.000Z
Engine/source/afx/util/afxParticlePool_T3D.cpp
Ashry00/Torque3D
33e3e41c8b7eb41c743a589558bc21302207ef97
[ "MIT" ]
84
2020-06-01T15:54:44.000Z
2022-03-24T13:52:59.000Z
//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// // Arcane-FX for MIT Licensed Open Source version of Torque 3D from GarageGames // Copyright (C) 2015 Faust Logic, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~// #include "afx/arcaneFX.h" #include "scene/sceneRenderState.h" #include "T3D/fx/particleEmitter.h" #include "renderInstance/renderPassManager.h" #include "lighting/lightInfo.h" #include "lighting/lightManager.h" #include "afx/util/afxParticlePool.h" void afxParticlePool::prepRenderImage(SceneRenderState* state) { const LightInfo *sunlight = LIGHTMGR->getSpecialLight( LightManager::slSunLightType ); pool_prepBatchRender(state->getRenderPass(), state->getCameraPosition(), sunlight->getAmbient()); }; void afxParticlePool::pool_prepBatchRender(RenderPassManager *renderManager, const Point3F &camPos, const LinearColorF &ambientColor) { if (emitters.empty()) return; switch (mDataBlock->pool_type) { case afxParticlePoolData::POOL_TWOPASS : pool_renderObject_TwoPass(renderManager, camPos, ambientColor); break; case afxParticlePoolData::POOL_NORMAL : default: pool_renderObject_Normal(renderManager, camPos, ambientColor); } } void afxParticlePool::pool_renderObject_Normal(RenderPassManager *renderManager, const Point3F &camPos, const LinearColorF &ambientColor) { S32 n_parts = 0; for (S32 i = 0; i < emitters.size(); i++) n_parts += emitters[i]->n_parts; if (n_parts == 0) return; ParticleEmitterData* main_emitter_data = emitters[0]->mDataBlock; main_emitter_data->allocPrimBuffer(n_parts); orderedVector.clear(); MatrixF modelview = GFX->getWorldMatrix(); Point3F viewvec; modelview.getRow(1, &viewvec); for (U32 i=0; i < emitters.size(); i++) { // add each particle and a distance based sort key to orderedVector for (Particle* pp = emitters[i]->part_list_head.next; pp != NULL; pp = pp->next) { orderedVector.increment(); orderedVector.last().p = pp; orderedVector.last().k = mDot(pp->pos, viewvec); orderedVector.last().emitter = emitters[i]; } } // qsort the list into far to near ordering dQsort(orderedVector.address(), orderedVector.size(), sizeof(SortParticlePool), cmpSortParticlePool); static Vector<GFXVertexPCT> tempBuff(2048); tempBuff.reserve(n_parts*4 + 64); // make sure tempBuff is big enough GFXVertexPCT *buffPtr = tempBuff.address(); // use direct pointer (faster) Point3F basePoints[4]; basePoints[0] = Point3F(-1.0, 0.0, -1.0); basePoints[1] = Point3F( 1.0, 0.0, -1.0); basePoints[2] = Point3F( 1.0, 0.0, 1.0); basePoints[3] = Point3F(-1.0, 0.0, 1.0); MatrixF camView = GFX->getWorldMatrix(); camView.transpose(); // inverse - this gets the particles facing camera for (U32 i = 0; i < orderedVector.size(); i++) { Particle* particle = orderedVector[i].p; ParticleEmitter* emitter = orderedVector[i].emitter; if (emitter->mDataBlock->orientParticles) emitter->setupOriented(particle, camPos, ambientColor, buffPtr); else emitter->setupBillboard(particle, basePoints, camView, ambientColor, buffPtr); buffPtr+=4; } // create new VB if emitter size grows if( !mVertBuff || n_parts > mCurBuffSize ) { mCurBuffSize = n_parts; mVertBuff.set(GFX, n_parts*4, GFXBufferTypeDynamic); } // lock and copy tempBuff to video RAM GFXVertexPCT *verts = mVertBuff.lock(); dMemcpy( verts, tempBuff.address(), n_parts * 4 * sizeof(GFXVertexPCT) ); mVertBuff.unlock(); //MeshRenderInst *ri = gRenderInstManager->allocInst<MeshRenderInst>(); ParticleRenderInst *ri = renderManager->allocInst<ParticleRenderInst>(); ri->vertBuff = &mVertBuff; ri->primBuff = &main_emitter_data->primBuff; ri->translucentSort = true; ri->type = RenderPassManager::RIT_Particle; ri->sortDistSq = getWorldBox().getSqDistanceToPoint( camPos ); ri->defaultKey = (-sort_priority*100); ri->modelViewProj = renderManager->allocUniqueXform( GFX->getProjectionMatrix() * GFX->getViewMatrix() * GFX->getWorldMatrix() ); ri->count = n_parts; ri->blendStyle = main_emitter_data->blendStyle; // use first particle's texture unless there is an emitter texture to override it if (main_emitter_data->textureHandle) ri->diffuseTex = &*(main_emitter_data->textureHandle); else ri->diffuseTex = &*(main_emitter_data->particleDataBlocks[0]->getTextureResource()); ri->softnessDistance = main_emitter_data->softnessDistance; // Sort by texture too. //ri->defaultKey = ri->diffuseTex ? (U32)ri->diffuseTex : (U32)ri->vertBuff; renderManager->addInst( ri ); } void afxParticlePool::pool_renderObject_TwoPass(RenderPassManager *renderManager, const Point3F &camPos, const LinearColorF &ambientColor) { S32 n_parts = 0; for (S32 i = 0; i < emitters.size(); i++) n_parts += emitters[i]->n_parts; if (n_parts == 0) return; ParticleEmitterData* main_emitter_data = emitters[0]->mDataBlock; main_emitter_data->allocPrimBuffer(n_parts); orderedVector.clear(); F32 min_d=0.0f, max_d=0.0f; for (U32 i=0; i < emitters.size(); i++) { if (!emitters[i]->mDataBlock->pool_depth_fade || !emitters[i]->mDataBlock->pool_radial_fade) continue; // add particles to orderedVector and calc distance and min/max distance for (Particle* pp = emitters[i]->part_list_head.next; pp != NULL; pp = pp->next) { F32 dist = (pp->pos-camPos).len(); if (dist > max_d) max_d = dist; else if (dist < min_d) min_d = dist; orderedVector.increment(); orderedVector.last().p = pp; orderedVector.last().k = dist; orderedVector.last().emitter = emitters[i]; } } // Add remaining emitters particles to the orderedVector that do not participate in the // above depth computations: for (U32 i=0; i < emitters.size(); i++) { if (emitters[i]->mDataBlock->pool_depth_fade || emitters[i]->mDataBlock->pool_radial_fade) continue; for (Particle* pp = emitters[i]->part_list_head.next; pp != NULL; pp = pp->next) { orderedVector.increment(); orderedVector.last().p = pp; orderedVector.last().k = 0; // no need to compute depth here orderedVector.last().emitter = emitters[i]; } } static Vector<GFXVertexPCT> tempBuff(2048); tempBuff.reserve(n_parts*4 + 64); // make sure tempBuff is big enough GFXVertexPCT *buffPtr = tempBuff.address(); // use direct pointer (faster) Point3F basePoints[4]; basePoints[0] = Point3F(-1.0, 0.0, -1.0); basePoints[1] = Point3F( 1.0, 0.0, -1.0); basePoints[2] = Point3F( 1.0, 0.0, 1.0); basePoints[3] = Point3F(-1.0, 0.0, 1.0); MatrixF camView = GFX->getWorldMatrix(); camView.transpose(); // inverse - this gets the particles facing camera //~~~~~~~~~~~~~~~~~~~~// Point3F bbox_center; mObjBox.getCenter(&bbox_center); F32 d_range = max_d - min_d; bool d_safe = (d_range>0.0001); F32 d_half = min_d + (d_range*0.5f); //~~~~~~~~~~~~~~~~~~~~// for (U32 i = 0; i < orderedVector.size(); i++) { Particle* particle = orderedVector[i].p; ParticleEmitter* emitter = orderedVector[i].emitter; LinearColorF color_save = particle->color; particle->color.set(mDataBlock->base_color.red, mDataBlock->base_color.green, mDataBlock->base_color.blue, mDataBlock->base_color.alpha*particle->color.alpha); emitter->setupBillboard(particle, basePoints, camView, ambientColor, buffPtr); particle->color = color_save; buffPtr+=4; } // create new VB if emitter size grows if( !mVertBuff || n_parts > mCurBuffSize ) { mCurBuffSize = n_parts; mVertBuff.set(GFX, n_parts*4, GFXBufferTypeDynamic); } // lock and copy tempBuff to video RAM GFXVertexPCT *verts = mVertBuff.lock(); dMemcpy( verts, tempBuff.address(), n_parts * 4 * sizeof(GFXVertexPCT) ); mVertBuff.unlock(); ParticleRenderInst *ri = renderManager->allocInst<ParticleRenderInst>(); ri->vertBuff = &mVertBuff; ri->primBuff = &main_emitter_data->primBuff; ri->translucentSort = true; ri->type = RenderPassManager::RIT_Particle; ri->sortDistSq = getWorldBox().getSqDistanceToPoint( camPos ); ri->defaultKey = (-sort_priority*100); ri->modelViewProj = renderManager->allocUniqueXform( GFX->getProjectionMatrix() * GFX->getViewMatrix() * GFX->getWorldMatrix() ); ri->count = n_parts; ri->blendStyle = ParticleRenderInst::BlendNormal; // use first particle's texture unless there is an emitter texture to override it //if (main_emitter_data->textureHandle) // ri->diffuseTex = &*(main_emitter_data->textureHandle); //else ri->diffuseTex = &*(main_emitter_data->particleDataBlocks[0]->getTextureExtResource()); F32 save_sort_dist = ri->sortDistSq; ri->softnessDistance = main_emitter_data->softnessDistance; renderManager->addInst( ri ); //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~// //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~// // 2nd-pass buffPtr = tempBuff.address(); bbox_center.z = mObjBox.minExtents.z; F32 max_radius = (max_d-min_d)*0.5f; // gather fade settings bool do_mixed_fades = false; bool do_radial_fades = (emitters[0]->mDataBlock->pool_radial_fade && (max_radius>0.0001f)); bool do_depth_fades = (emitters[0]->mDataBlock->pool_depth_fade && d_safe); for (U32 i = 1; i < emitters.size(); i++) { if ( (do_radial_fades != (emitters[i]->mDataBlock->pool_radial_fade && (max_radius>0.0001f))) || (do_depth_fades != (emitters[i]->mDataBlock->pool_depth_fade && d_safe))) { do_mixed_fades = true; break; } } if (do_mixed_fades) { for (U32 i = 0; i < orderedVector.size(); i++) { Particle* particle = orderedVector[i].p; ParticleEmitter* emitter = orderedVector[i].emitter; F32 bf = 1.0; // blend factor // blend factor due to radius if (emitter->mDataBlock->pool_radial_fade && (max_radius>0.0001f)) { F32 p_radius = (particle->pos-bbox_center).len(); F32 bf_radius = p_radius/max_radius; if (bf_radius>1.0f) bf_radius = 1.0f; bf *= bf_radius*bf_radius; // quadratic for faster falloff } // blend factor, depth based if (emitter->mDataBlock->pool_depth_fade && d_safe && (orderedVector[i].k > d_half)) { F32 bf_depth = ((max_d-orderedVector[i].k) / (d_range*0.5f)); bf *= bf_depth; } // overall blend factor weight bf *= mDataBlock->blend_weight; LinearColorF color_save = particle->color; particle->color = particle->color*bf; emitter->setupBillboard(particle, basePoints, camView, ambientColor, buffPtr); particle->color = color_save; buffPtr+=4; } } else if (do_radial_fades && do_depth_fades) { for (U32 i = 0; i < orderedVector.size(); i++) { Particle* particle = orderedVector[i].p; ParticleEmitter* emitter = orderedVector[i].emitter; F32 bf = 1.0; // blend factor // blend factor due to radius F32 p_radius = (particle->pos-bbox_center).len(); F32 bf_radius = p_radius/max_radius; if (bf_radius>1.0f) bf_radius = 1.0f; bf *= bf_radius*bf_radius; // quadratic for faster falloff // blend factor, depth based if (orderedVector[i].k > d_half) { F32 bf_depth = ((max_d-orderedVector[i].k) / (d_range*0.5f)); bf *= bf_depth; } // overall blend factor weight bf *= mDataBlock->blend_weight; LinearColorF color_save = particle->color; particle->color = particle->color*bf; emitter->setupBillboard(particle, basePoints, camView, ambientColor, buffPtr); particle->color = color_save; buffPtr+=4; } } else if (do_radial_fades) // && !do_depth_fades { for (U32 i = 0; i < orderedVector.size(); i++) { Particle* particle = orderedVector[i].p; ParticleEmitter* emitter = orderedVector[i].emitter; F32 bf = 1.0; // blend factor // blend factor due to radius F32 p_radius = (particle->pos-bbox_center).len(); F32 bf_radius = p_radius/max_radius; if (bf_radius>1.0f) bf_radius = 1.0f; bf *= bf_radius*bf_radius; // quadratic for faster falloff // overall blend factor weight bf *= mDataBlock->blend_weight; LinearColorF color_save = particle->color; particle->color = particle->color*bf; emitter->setupBillboard(particle, basePoints, camView, ambientColor, buffPtr); particle->color = color_save; buffPtr+=4; } } else if (do_depth_fades) // && !do_radial_fades { for (U32 i = 0; i < orderedVector.size(); i++) { Particle* particle = orderedVector[i].p; ParticleEmitter* emitter = orderedVector[i].emitter; F32 bf = 1.0; // blend factor // blend factor, depth based if (orderedVector[i].k > d_half) { F32 bf_depth = ((max_d-orderedVector[i].k) / (d_range*0.5f)); bf *= bf_depth; } // overall blend factor weight bf *= mDataBlock->blend_weight; LinearColorF color_save = particle->color; particle->color = particle->color*bf; emitter->setupBillboard(particle, basePoints, camView, ambientColor, buffPtr); particle->color = color_save; buffPtr+=4; } } else // (no fades) { for (U32 i = 0; i < orderedVector.size(); i++) { Particle* particle = orderedVector[i].p; ParticleEmitter* emitter = orderedVector[i].emitter; F32 bf = mDataBlock->blend_weight; // blend factor LinearColorF color_save = particle->color; particle->color = particle->color*bf; emitter->setupBillboard(particle, basePoints, camView, ambientColor, buffPtr); particle->color = color_save; buffPtr+=4; } } // create new VB if emitter size grows if( !mVertBuff2 || n_parts > mCurBuffSize2 ) { mCurBuffSize2 = n_parts; mVertBuff2.set(GFX, n_parts*4, GFXBufferTypeDynamic); } // lock and copy tempBuff to video RAM verts = mVertBuff2.lock(); dMemcpy( verts, tempBuff.address(), n_parts * 4 * sizeof(GFXVertexPCT) ); mVertBuff2.unlock(); ri = renderManager->allocInst<ParticleRenderInst>(); ri->vertBuff = &mVertBuff2; ri->primBuff = &main_emitter_data->primBuff; ri->translucentSort = true; ri->type = RenderPassManager::RIT_Particle; ri->sortDistSq = save_sort_dist; ri->defaultKey = (-sort_priority*100) + 1; ri->modelViewProj = renderManager->allocUniqueXform( GFX->getProjectionMatrix() * GFX->getViewMatrix() * GFX->getWorldMatrix() ); ri->count = n_parts; ri->blendStyle = ParticleRenderInst::BlendAdditive; // use first particle's texture unless there is an emitter texture to override it if (main_emitter_data->textureHandle) ri->diffuseTex = &*(main_emitter_data->textureHandle); else ri->diffuseTex = &*(main_emitter_data->particleDataBlocks[0]->getTextureResource()); ri->softnessDistance = main_emitter_data->softnessDistance; renderManager->addInst( ri ); } //~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~//~~~~~~~~~~~~~~~~~~~~~//
33.780488
163
0.650301
[ "vector", "3d" ]
c8cfdc56ae3a77bf52ad947aceb78373377cec2d
10,190
cc
C++
test/common/filesystem/filesystem_impl_test.cc
jaricftw/envoy
766f3fb8dbdafce402631c43c16fda46ed003462
[ "Apache-2.0" ]
2
2020-03-09T19:20:47.000Z
2021-05-05T21:02:07.000Z
test/common/filesystem/filesystem_impl_test.cc
jaricftw/envoy
766f3fb8dbdafce402631c43c16fda46ed003462
[ "Apache-2.0" ]
30
2022-02-17T02:28:37.000Z
2022-03-31T02:31:02.000Z
test/common/filesystem/filesystem_impl_test.cc
jerry2102/envoy
c91d59f66f016ce18f6968e2630677ee28038971
[ "Apache-2.0" ]
2
2019-11-29T12:40:19.000Z
2019-12-13T14:09:55.000Z
#include <chrono> #include <string> #include "common/common/assert.h" #include "common/filesystem/filesystem_impl.h" #include "test/test_common/environment.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace Envoy { namespace Filesystem { static constexpr FlagSet DefaultFlags{ 1 << Filesystem::File::Operation::Read | 1 << Filesystem::File::Operation::Write | 1 << Filesystem::File::Operation::Create | 1 << Filesystem::File::Operation::Append}; class FileSystemImplTest : public testing::Test { protected: int getFd(File* file) { #ifdef WIN32 auto file_impl = dynamic_cast<FileImplWin32*>(file); #else auto file_impl = dynamic_cast<FileImplPosix*>(file); #endif RELEASE_ASSERT(file_impl != nullptr, "failed to cast File* to FileImpl*"); return file_impl->fd_; } #ifdef WIN32 InstanceImplWin32 file_system_; #else Api::SysCallStringResult canonicalPath(const std::string& path) { return file_system_.canonicalPath(path); } InstanceImplPosix file_system_; #endif }; TEST_F(FileSystemImplTest, fileExists) { EXPECT_FALSE(file_system_.fileExists("/dev/blahblahblah")); #ifdef WIN32 const std::string file_path = TestEnvironment::writeStringToFileForTest("test_envoy", "x"); EXPECT_TRUE(file_system_.fileExists(file_path)); EXPECT_TRUE(file_system_.fileExists("c:/windows")); #else EXPECT_TRUE(file_system_.fileExists("/dev/null")); EXPECT_TRUE(file_system_.fileExists("/dev")); #endif } TEST_F(FileSystemImplTest, directoryExists) { EXPECT_FALSE(file_system_.directoryExists("/dev/blahblah")); #ifdef WIN32 const std::string file_path = TestEnvironment::writeStringToFileForTest("test_envoy", "x"); EXPECT_FALSE(file_system_.directoryExists(file_path)); EXPECT_TRUE(file_system_.directoryExists("c:/windows")); #else EXPECT_FALSE(file_system_.directoryExists("/dev/null")); EXPECT_TRUE(file_system_.directoryExists("/dev")); #endif } TEST_F(FileSystemImplTest, fileSize) { #ifdef WIN32 EXPECT_EQ(0, file_system_.fileSize("NUL")); #else EXPECT_EQ(0, file_system_.fileSize("/dev/null")); #endif EXPECT_EQ(-1, file_system_.fileSize("/dev/blahblahblah")); const std::string data = "test string\ntest"; const std::string file_path = TestEnvironment::writeStringToFileForTest("test_envoy", data); EXPECT_EQ(data.length(), file_system_.fileSize(file_path)); } TEST_F(FileSystemImplTest, fileReadToEndSuccess) { const std::string data = "test string\ntest"; const std::string file_path = TestEnvironment::writeStringToFileForTest("test_envoy", data); EXPECT_EQ(data, file_system_.fileReadToEnd(file_path)); } // Files are read into std::string; verify that all bytes (eg non-ascii characters) come back // unmodified TEST_F(FileSystemImplTest, fileReadToEndSuccessBinary) { std::string data; for (unsigned i = 0; i < 256; i++) { data.push_back(i); } const std::string file_path = TestEnvironment::writeStringToFileForTest("test_envoy", data); const std::string read = file_system_.fileReadToEnd(file_path); const std::vector<uint8_t> binary_read(read.begin(), read.end()); EXPECT_EQ(binary_read.size(), 256); for (unsigned i = 0; i < 256; i++) { EXPECT_EQ(binary_read.at(i), i); } } TEST_F(FileSystemImplTest, fileReadToEndDoesNotExist) { unlink(TestEnvironment::temporaryPath("envoy_this_not_exist").c_str()); EXPECT_THROW(file_system_.fileReadToEnd(TestEnvironment::temporaryPath("envoy_this_not_exist")), EnvoyException); } TEST_F(FileSystemImplTest, fileReadToEndBlacklisted) { EXPECT_THROW(file_system_.fileReadToEnd("/dev/urandom"), EnvoyException); EXPECT_THROW(file_system_.fileReadToEnd("/proc/cpuinfo"), EnvoyException); EXPECT_THROW(file_system_.fileReadToEnd("/sys/block/sda/dev"), EnvoyException); } #ifndef WIN32 TEST_F(FileSystemImplTest, CanonicalPathSuccess) { EXPECT_EQ("/", canonicalPath("//").rc_); } #endif #ifndef WIN32 TEST_F(FileSystemImplTest, CanonicalPathFail) { const Api::SysCallStringResult result = canonicalPath("/_some_non_existent_file"); EXPECT_TRUE(result.rc_.empty()); EXPECT_STREQ("No such file or directory", ::strerror(result.errno_)); } #endif TEST_F(FileSystemImplTest, IllegalPath) { EXPECT_FALSE(file_system_.illegalPath("/")); EXPECT_FALSE(file_system_.illegalPath("//")); #ifdef WIN32 EXPECT_FALSE(file_system_.illegalPath("/dev")); EXPECT_FALSE(file_system_.illegalPath("/dev/")); EXPECT_FALSE(file_system_.illegalPath("/proc")); EXPECT_FALSE(file_system_.illegalPath("/proc/")); EXPECT_FALSE(file_system_.illegalPath("/sys")); EXPECT_FALSE(file_system_.illegalPath("/sys/")); EXPECT_FALSE(file_system_.illegalPath("/_some_non_existent_file")); #else EXPECT_TRUE(file_system_.illegalPath("/dev")); EXPECT_TRUE(file_system_.illegalPath("/dev/")); // Exception to allow opening from file descriptors. See #7258. EXPECT_FALSE(file_system_.illegalPath("/dev/fd/0")); EXPECT_TRUE(file_system_.illegalPath("/proc")); EXPECT_TRUE(file_system_.illegalPath("/proc/")); EXPECT_TRUE(file_system_.illegalPath("/sys")); EXPECT_TRUE(file_system_.illegalPath("/sys/")); EXPECT_TRUE(file_system_.illegalPath("/_some_non_existent_file")); #endif } TEST_F(FileSystemImplTest, ConstructedFileNotOpen) { const std::string new_file_path = TestEnvironment::temporaryPath("envoy_this_not_exist"); ::unlink(new_file_path.c_str()); FilePtr file = file_system_.createFile(new_file_path); EXPECT_FALSE(file->isOpen()); } TEST_F(FileSystemImplTest, Open) { const std::string new_file_path = TestEnvironment::temporaryPath("envoy_this_not_exist"); ::unlink(new_file_path.c_str()); FilePtr file = file_system_.createFile(new_file_path); const Api::IoCallBoolResult result = file->open(DefaultFlags); EXPECT_TRUE(result.rc_); EXPECT_TRUE(file->isOpen()); } TEST_F(FileSystemImplTest, OpenTwice) { const std::string new_file_path = TestEnvironment::temporaryPath("envoy_this_not_exist"); ::unlink(new_file_path.c_str()); FilePtr file = file_system_.createFile(new_file_path); EXPECT_EQ(getFd(file.get()), -1); const Api::IoCallBoolResult result1 = file->open(DefaultFlags); const int initial_fd = getFd(file.get()); EXPECT_TRUE(result1.rc_); EXPECT_TRUE(file->isOpen()); // check that we don't leak a file descriptor const Api::IoCallBoolResult result2 = file->open(DefaultFlags); EXPECT_EQ(initial_fd, getFd(file.get())); EXPECT_TRUE(result2.rc_); EXPECT_TRUE(file->isOpen()); } TEST_F(FileSystemImplTest, OpenBadFilePath) { FilePtr file = file_system_.createFile(""); const Api::IoCallBoolResult result = file->open(DefaultFlags); EXPECT_FALSE(result.rc_); } TEST_F(FileSystemImplTest, ExistingFile) { const std::string file_path = TestEnvironment::writeStringToFileForTest("test_envoy", "existing file"); { FilePtr file = file_system_.createFile(file_path); const Api::IoCallBoolResult open_result = file->open(DefaultFlags); EXPECT_TRUE(open_result.rc_); std::string data(" new data"); const Api::IoCallSizeResult result = file->write(data); EXPECT_EQ(data.length(), result.rc_); } auto contents = TestEnvironment::readFileToStringForTest(file_path); EXPECT_EQ("existing file new data", contents); } TEST_F(FileSystemImplTest, NonExistingFile) { const std::string new_file_path = TestEnvironment::temporaryPath("envoy_this_not_exist"); ::unlink(new_file_path.c_str()); { FilePtr file = file_system_.createFile(new_file_path); const Api::IoCallBoolResult open_result = file->open(DefaultFlags); EXPECT_TRUE(open_result.rc_); std::string data(" new data"); const Api::IoCallSizeResult result = file->write(data); EXPECT_EQ(data.length(), result.rc_); } auto contents = TestEnvironment::readFileToStringForTest(new_file_path); EXPECT_EQ(" new data", contents); } TEST_F(FileSystemImplTest, Close) { const std::string new_file_path = TestEnvironment::temporaryPath("envoy_this_not_exist"); ::unlink(new_file_path.c_str()); FilePtr file = file_system_.createFile(new_file_path); const Api::IoCallBoolResult result1 = file->open(DefaultFlags); EXPECT_TRUE(result1.rc_); EXPECT_TRUE(file->isOpen()); const Api::IoCallBoolResult result2 = file->close(); EXPECT_TRUE(result2.rc_); EXPECT_FALSE(file->isOpen()); } TEST_F(FileSystemImplTest, WriteAfterClose) { const std::string new_file_path = TestEnvironment::temporaryPath("envoy_this_not_exist"); ::unlink(new_file_path.c_str()); FilePtr file = file_system_.createFile(new_file_path); const Api::IoCallBoolResult bool_result1 = file->open(DefaultFlags); EXPECT_TRUE(bool_result1.rc_); const Api::IoCallBoolResult bool_result2 = file->close(); EXPECT_TRUE(bool_result2.rc_); const Api::IoCallSizeResult size_result = file->write(" new data"); EXPECT_EQ(-1, size_result.rc_); EXPECT_EQ(IoFileError::IoErrorCode::UnknownError, size_result.err_->getErrorCode()); EXPECT_EQ("Bad file descriptor", size_result.err_->getErrorDetails()); } TEST_F(FileSystemImplTest, NonExistingFileAndReadOnly) { const std::string new_file_path = TestEnvironment::temporaryPath("envoy_this_not_exist"); ::unlink(new_file_path.c_str()); static constexpr FlagSet flag(static_cast<size_t>(Filesystem::File::Operation::Read)); FilePtr file = file_system_.createFile(new_file_path); const Api::IoCallBoolResult open_result = file->open(flag); EXPECT_FALSE(open_result.rc_); } TEST_F(FileSystemImplTest, ExistingReadOnlyFileAndWrite) { const std::string file_path = TestEnvironment::writeStringToFileForTest("test_envoy", "existing file"); { static constexpr FlagSet flag(static_cast<size_t>(Filesystem::File::Operation::Read)); FilePtr file = file_system_.createFile(file_path); const Api::IoCallBoolResult open_result = file->open(flag); EXPECT_TRUE(open_result.rc_); std::string data(" new data"); const Api::IoCallSizeResult result = file->write(data); EXPECT_TRUE(result.rc_ < 0); EXPECT_EQ(result.err_->getErrorDetails(), "Bad file descriptor"); } auto contents = TestEnvironment::readFileToStringForTest(file_path); EXPECT_EQ("existing file", contents); } } // namespace Filesystem } // namespace Envoy
35.754386
98
0.75368
[ "vector" ]
c8d0ced3a627b7c24bca19fe81d8c0a859b5e66a
17,917
cpp
C++
OrionUO/Gumps/GumpCombatBook.cpp
alerdenisov/OrionUO
d0bb54ce62af68a0152edd02d94fdf92eef90d4d
[ "MIT" ]
25
2018-10-30T01:19:10.000Z
2021-06-02T15:35:49.000Z
OrionUO/Gumps/GumpCombatBook.cpp
alerdenisov/OrionUO
d0bb54ce62af68a0152edd02d94fdf92eef90d4d
[ "MIT" ]
74
2018-10-13T00:41:32.000Z
2021-09-04T20:00:12.000Z
OrionUO/Gumps/GumpCombatBook.cpp
alerdenisov/OrionUO
d0bb54ce62af68a0152edd02d94fdf92eef90d4d
[ "MIT" ]
20
2018-10-09T17:42:32.000Z
2022-03-26T05:57:47.000Z
// MIT License // Copyright (C) December 2016 Hotride #include "GumpCombatBook.h" #include "GumpAbility.h" #include "../Config.h" #include "../OrionUO.h" #include "../ToolTip.h" #include "../PressedObject.h" #include "../SelectedObject.h" #include "../ClickObject.h" #include "../OrionWindow.h" #include "../Managers/MouseManager.h" #include "../Managers/GumpManager.h" #include "../Managers/ClilocManager.h" CGumpCombatBook::CGumpCombatBook(int x, int y) : CGump(GT_COMBAT_BOOK, 0, x, y) { DEBUG_TRACE_FUNCTION; Draw2Page = 1; if (g_Config.ClientVersion < CV_7000) { if (g_Config.ClientVersion >= CV_500A) { AbilityCount = 29; } else { AbilityCount = 13; DictionaryPagesCount = 2; } } PagesCount = DictionaryPagesCount + (AbilityCount * 2); } CGumpCombatBook::~CGumpCombatBook() { } vector<uint16_t> CGumpCombatBook::GetItemsList(uint8_t index) { DEBUG_TRACE_FUNCTION; vector<uint16_t> list; switch (index) { case 0: { list.push_back(3908); list.push_back(5048); list.push_back(3935); list.push_back(5119); list.push_back(9927); list.push_back(5181); list.push_back(5040); list.push_back(5121); list.push_back(3939); list.push_back(9932); list.push_back(11554); list.push_back(16497); list.push_back(16502); list.push_back(16494); list.push_back(16491); break; } case 1: { list.push_back(3779); list.push_back(5115); list.push_back(3912); list.push_back(3910); list.push_back(5185); list.push_back(9924); list.push_back(5127); list.push_back(5040); list.push_back(3720); list.push_back(5125); list.push_back(11552); list.push_back(16499); list.push_back(16498); break; } case 2: { list.push_back(5048); list.push_back(3912); list.push_back(5183); list.push_back(5179); list.push_back(3933); list.push_back(5113); list.push_back(3722); list.push_back(9930); list.push_back(3920); list.push_back(11556); list.push_back(16487); list.push_back(16500); break; } case 3: { list.push_back(5050); list.push_back(3914); list.push_back(3935); list.push_back(3714); list.push_back(5092); list.push_back(5179); list.push_back(5127); list.push_back(5177); list.push_back(9926); list.push_back(4021); list.push_back(10146); list.push_back(11556); list.push_back(11560); list.push_back(5109); list.push_back(16500); list.push_back(16495); break; } case 4: { list.push_back(5111); list.push_back(3718); list.push_back(3781); list.push_back(3908); list.push_back(3573); list.push_back(3714); list.push_back(3933); list.push_back(5125); list.push_back(11558); list.push_back(11560); list.push_back(5109); list.push_back(9934); list.push_back(16493); list.push_back(16494); break; } case 5: { list.push_back(3918); list.push_back(3914); list.push_back(9927); list.push_back(3573); list.push_back(5044); list.push_back(3720); list.push_back(9930); list.push_back(5117); list.push_back(16501); list.push_back(16495); break; } case 6: { list.push_back(3718); list.push_back(5187); list.push_back(3916); list.push_back(5046); list.push_back(5119); list.push_back(9931); list.push_back(3722); list.push_back(9929); list.push_back(9933); list.push_back(10148); list.push_back(10153); list.push_back(16488); list.push_back(16493); list.push_back(16496); break; } case 7: { list.push_back(5111); list.push_back(3779); list.push_back(3922); list.push_back(9928); list.push_back(5121); list.push_back(9929); list.push_back(11553); list.push_back(16490); list.push_back(16488); break; } case 8: { list.push_back(3910); list.push_back(9925); list.push_back(9931); list.push_back(5181); list.push_back(9926); list.push_back(5123); list.push_back(3920); list.push_back(5042); list.push_back(16499); list.push_back(16502); list.push_back(16496); list.push_back(16491); break; } case 9: { list.push_back(5117); list.push_back(9932); list.push_back(9933); list.push_back(16492); break; } case 10: { list.push_back(5050); list.push_back(3918); list.push_back(5046); list.push_back(9924); list.push_back(9925); list.push_back(5113); list.push_back(3569); list.push_back(9928); list.push_back(3939); list.push_back(5042); list.push_back(16497); list.push_back(16498); break; } case 11: { list.push_back(3781); list.push_back(5187); list.push_back(5185); list.push_back(5092); list.push_back(5044); list.push_back(3922); list.push_back(5123); list.push_back(4021); list.push_back(11553); list.push_back(16490); break; } case 12: { list.push_back(5115); list.push_back(5183); list.push_back(3916); list.push_back(5177); list.push_back(3569); list.push_back(10157); list.push_back(11559); list.push_back(9934); list.push_back(16501); break; } case 13: { list.push_back(10146); break; } case 14: { list.push_back(10148); list.push_back(10150); list.push_back(10151); break; } case 15: { list.push_back(10147); list.push_back(10158); list.push_back(10159); list.push_back(11557); break; } case 16: { list.push_back(10151); list.push_back(10157); list.push_back(11561); break; } case 17: { list.push_back(10152); break; } case 18: case 20: { list.push_back(10155); break; } case 19: { list.push_back(10152); list.push_back(10153); list.push_back(10158); list.push_back(11554); break; } case 21: { list.push_back(10149); break; } case 22: { list.push_back(10149); list.push_back(10159); break; } case 23: { list.push_back(11555); list.push_back(11558); list.push_back(11559); list.push_back(11561); break; } case 24: case 27: { list.push_back(11550); break; } case 25: { list.push_back(11551); break; } case 26: { list.push_back(11551); list.push_back(11552); break; } case 28: { list.push_back(11557); break; } case 29: { list.push_back(16492); break; } case 30: { list.push_back(16487); break; } default: break; } return list; } void CGumpCombatBook::InitToolTip() { DEBUG_TRACE_FUNCTION; if (Minimized) { g_ToolTip.Set(L"Double click to maximize book gump"); return; } uint32_t serial = g_SelectedObject.Serial; if (Page >= DictionaryPagesCount) { if (serial >= (uint32_t)ID_GCB_ICON) { g_ToolTip.Set( g_ClilocManager.Cliloc(g_Language)->GetW(1061693 + (serial - ID_GCB_ICON), true), 150); } } else { if (serial == ID_GCB_ICON_FIRST) { g_ToolTip.Set( g_ClilocManager.Cliloc(g_Language)->GetW(1028838 + (g_Ability[0] & 0x7F) - 1, true), 80); } else if (serial == ID_GCB_ICON_SECOND) { g_ToolTip.Set( g_ClilocManager.Cliloc(g_Language)->GetW(1028838 + (g_Ability[1] & 0x7F) - 1, true), 80); } } } void CGumpCombatBook::PrepareContent() { DEBUG_TRACE_FUNCTION; if (g_PressedObject.LeftGump == this && Page < DictionaryPagesCount && (g_PressedObject.LeftSerial == ID_GCB_ICON_FIRST || g_PressedObject.LeftSerial == ID_GCB_ICON_SECOND)) { CPoint2Di offset = g_MouseManager.LeftDroppedOffset(); if ((abs(offset.X) >= DRAG_PIXEL_RANGE || abs(offset.Y) >= DRAG_PIXEL_RANGE) || (g_MouseManager.LastLeftButtonClickTimer + g_MouseManager.DoubleClickDelay < g_Ticks)) { g_GumpManager.AddGump(new CGumpAbility( static_cast<int>(g_PressedObject.LeftSerial == ID_GCB_ICON_SECOND), g_MouseManager.Position.X - 20, g_MouseManager.Position.Y - 20)); g_OrionWindow.EmulateOnLeftMouseButtonDown(); } } } void CGumpCombatBook::UpdateContent() { DEBUG_TRACE_FUNCTION; m_PrevPage = nullptr; m_NextPage = nullptr; Clear(); Add(new CGUIPage(-1)); if (Minimized) { Add(new CGUIGumppic(0x2B05, 0, 0)); return; } Add(new CGUIGumppic(0x2B02, 0, 0)); Add(new CGUIHitBox(ID_GCB_BUTTON_MINIMIZE, 6, 100, 16, 16, true)); int offs = 0; for (int page = 0; page < DictionaryPagesCount; page++) { Add(new CGUIPage((int)page)); int indexX = 96; int dataX = 52; int y = 0; int spellsOnPage = 9; if ((page % 2) != 0) { indexX = 259; dataX = 215; spellsOnPage = 4; } CGUIText *text = (CGUIText *)Add(new CGUIText(0x0288, indexX, 6)); text->CreateTextureA(6, "INDEX"); for (int i = 0; i < spellsOnPage; i++) { if (offs >= AbilityCount) { break; } CGUIHitBox *box = (CGUIHitBox *)Add(new CGUIHitBox(ID_GCB_ICON + offs, dataX, 42 + y, 100, 16, true)); box->MoveOnDrag = true; CGUITextEntry *entry = (CGUITextEntry *)Add( new CGUITextEntry(ID_GCB_ICON + offs, 0x0288, 0, 0, dataX, 42 + y, 0, false, 9)); entry->m_Entry.SetTextA(m_AbilityName[offs]); entry->CheckOnSerial = true; entry->ReadOnly = true; y += 15; offs++; } if (spellsOnPage == 4) { CGUIGumppic *icon = (CGUIGumppic *)Add(new CGUIGumppic(0x5200 + (g_Ability[0] & 0x7F) - 1, 215, 105)); icon->Serial = ID_GCB_ICON_FIRST; text = (CGUIText *)Add(new CGUIText(0x0288, 265, 105)); text->CreateTextureA(6, "Primary Ability Icon", 80); icon = (CGUIGumppic *)Add(new CGUIGumppic(0x5200 + (g_Ability[1] & 0x7F) - 1, 215, 150)); icon->Serial = ID_GCB_ICON_SECOND; text = (CGUIText *)Add(new CGUIText(0x0288, 265, 150)); text->CreateTextureA(6, "Secondary Ability Icon", 80); } } int page = DictionaryPagesCount; for (int i = 0; i < AbilityCount; i++) { Add(new CGUIPage(page)); page += 2; CGUIGumppic *icon = (CGUIGumppic *)Add(new CGUIGumppic(0x5200 + (int)i, 62, 40)); icon->Serial = ID_GCB_ICON + (int)i; icon->MoveOnDrag = true; Add(new CGUIGumppicTiled(0x0835, 62, 88, 128, 0)); vector<uint16_t> list = GetItemsList((uint8_t)i); int size = (int)list.size(); size_t maxStaticCount = g_Orion.m_StaticData.size(); int textX = 62; int textY = 98; for (int j = 0; j < size; j++) { if (j == 6) { textX = 215; textY = 34; } uint16_t &id = list[j]; if (id >= maxStaticCount) { continue; } CGUIText *text = (CGUIText *)Add(new CGUIText(0x0288, textX, textY)); text->CreateTextureA(9, ToCamelCase(g_Orion.m_StaticData[id].Name)); textY += 16; } } Add(new CGUIPage(-1)); m_PrevPage = (CGUIButton *)Add(new CGUIButton(ID_GCB_BUTTON_PREV, 0x08BB, 0x08BB, 0x08BB, 50, 8)); m_PrevPage->Visible = (Page != 0); m_NextPage = (CGUIButton *)Add(new CGUIButton(ID_GCB_BUTTON_NEXT, 0x08BC, 0x08BC, 0x08BC, 321, 8)); m_NextPage->Visible = (Page + 2 < PagesCount); } void CGumpCombatBook::GUMP_BUTTON_EVENT_C { DEBUG_TRACE_FUNCTION; int newPage = -1; if (serial == ID_GCB_BUTTON_PREV) { if (Page > 0) { newPage = Page - 2; if (newPage < 0) { newPage = 0; } } } else if (serial == ID_GCB_BUTTON_NEXT) { if (Page < PagesCount) { newPage = Page + 2; if (newPage >= PagesCount) { newPage = PagesCount - 1; } } } else if (serial == ID_GCB_BUTTON_MINIMIZE) { Minimized = true; WantUpdateContent = true; } else if (serial == ID_GCB_LOCK_MOVING) { LockMoving = !LockMoving; } else if (serial >= ID_GCB_ICON) { if (Page < DictionaryPagesCount) { //List of spells newPage = DictionaryPagesCount + ((serial - ID_GCB_ICON) * 2); } } if (newPage > -1 && !g_ClickObject.Enabled) { if ((newPage % 2) != 0) { newPage--; } g_ClickObject.Init(g_PressedObject.LeftObject, this); g_ClickObject.Timer = g_Ticks + g_MouseManager.DoubleClickDelay; g_ClickObject.Page = newPage; } } bool CGumpCombatBook::OnLeftMouseButtonDoubleClick() { DEBUG_TRACE_FUNCTION; bool result = false; if (Minimized) { Minimized = false; WantUpdateContent = true; result = true; } else { if (g_PressedObject.LeftSerial == ID_GCB_BUTTON_PREV) { ChangePage(0); WantRedraw = true; result = true; } else if (g_PressedObject.LeftSerial == ID_GCB_BUTTON_NEXT) { int newPage = PagesCount - 1; if ((newPage % 2) != 0) { newPage--; } ChangePage(newPage); WantRedraw = true; result = true; } else if (g_PressedObject.LeftSerial == ID_GCB_ICON_FIRST) { CGumpAbility::OnAbilityUse(0); WantUpdateContent = true; result = true; } else if (g_PressedObject.LeftSerial == ID_GCB_ICON_SECOND) { CGumpAbility::OnAbilityUse(1); WantUpdateContent = true; result = true; } } return result; } void CGumpCombatBook::DelayedClick(CRenderObject *obj) { DEBUG_TRACE_FUNCTION; if (obj != nullptr) { ChangePage(g_ClickObject.Page); WantRedraw = true; } } void CGumpCombatBook::ChangePage(int newPage) { DEBUG_TRACE_FUNCTION; Page = newPage; m_PrevPage->Visible = (Page != 0); m_NextPage->Visible = (Page + 2 < PagesCount); g_Orion.PlaySoundEffect(0x0055); } const string CGumpCombatBook::m_AbilityName[MAX_ABILITIES_COUNT]{ "Armor Ignore", "Bleed Attack", "Concussion Blow", "Crushing Blow", "Disarm", "Dismount", "Double Strike", "Infecting", "Mortal Strike", "Moving Shot", "Paralyzing Blow", "Shadow Strike", "Whirlwind Attack", "Riding Swipe", //CV_500a "Frenzied Whirlwind", "Block", "Defense Mastery", "Nerve Strike", "Talon Strike", "Feint", "Dual Wield", "Double Shot", "Armor Pierce", "Bladeweave", "Force Arrow", "Lightning Arrow", "Psychic Attack", "Serpent Arrow", "Force of Nature", "Infused Throw", //CV_7000 "Mystic Arc", "Disrobe" };
25.486486
100
0.49774
[ "vector" ]
c8d0d3db861ca25d6ae670f65a37e9235fd0b862
16,110
cpp
C++
src/utils/TICCalculator.cpp
vmusch/OpenMS
3c4a078ad4687677393c138d4acb91bb444a7c7b
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
348
2015-01-17T16:50:12.000Z
2022-03-30T22:55:39.000Z
src/utils/TICCalculator.cpp
vmusch/OpenMS
3c4a078ad4687677393c138d4acb91bb444a7c7b
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
4,259
2015-01-01T14:07:54.000Z
2022-03-31T16:49:14.000Z
src/utils/TICCalculator.cpp
vmusch/OpenMS
3c4a078ad4687677393c138d4acb91bb444a7c7b
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
266
2015-01-24T14:56:14.000Z
2022-03-30T12:32:35.000Z
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2021. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #include <OpenMS/config.h> #include <OpenMS/APPLICATIONS/TOPPBase.h> #include <OpenMS/CONCEPT/LogStream.h> #include <OpenMS/FORMAT/DATAACCESS/MSDataWritingConsumer.h> #include <OpenMS/FORMAT/HANDLERS/CachedMzMLHandler.h> #include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h> #include <OpenMS/FORMAT/CachedMzML.h> #include <OpenMS/FORMAT/FileTypes.h> #include <OpenMS/FORMAT/IndexedMzMLFileLoader.h> #include <OpenMS/FORMAT/IndexedMzMLFileLoader.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/INTERFACES/IMSDataConsumer.h> #include <OpenMS/KERNEL/OnDiscMSExperiment.h> #include <OpenMS/SYSTEM/SysInfo.h> #include <numeric> using namespace OpenMS; using namespace std; using namespace OpenSwath; //------------------------------------------------------------- //Doxygen docu //------------------------------------------------------------- /** @page UTILS_TICCalculator TICCalculator @brief Calculates the TIC of a raw mass spectrometric file. This class was developed to benchmark multiple methods inside OpenMS for reading raw mass spectrometric data. It can be used for benchmarking these different methods as well as benchmarking external tools. Of course you can also calculate the TIC with this tool. <B>The command line parameters of this tool are:</B> @verbinclude UTILS_TICCalculator.cli <B>INI file documentation of this tool:</B> @htmlinclude UTILS_TICCalculator.html */ // We do not want this class to show up in the docu: /// @cond TOPPCLASSES class TICConsumer : public Interfaces::IMSDataConsumer { typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; public: double TIC; int nr_spectra; long int nr_peaks; // Create new consumer, set TIC to zero TICConsumer() : TIC(0.0), nr_spectra(0.0), nr_peaks(0) {} void consumeSpectrum(SpectrumType & s) override { for (Size i = 0; i < s.size(); i++) { TIC += s[i].getIntensity(); } nr_peaks += s.size(); nr_spectra++; } void consumeChromatogram(ChromatogramType& /* c */) override {} void setExpectedSize(Size /* expectedSpectra */, Size /* expectedChromatograms */) override {} void setExperimentalSettings(const ExperimentalSettings& /* exp */) override {} }; /** @brief Abstraction of a std::ifstream Useful for parallel access to the file when each thread is given its own instance of this class. Each thread will then have its own file stream and access the file independently. */ class FileAbstraction { public: // constructor explicit FileAbstraction(std::string filename) : filename_(filename) { ifs_.open(filename.c_str(), std::ios::binary); } // copy constructor FileAbstraction(const FileAbstraction& source) : filename_(source.filename_), ifs_(source.filename_.c_str()) {} // access to underlying stream std::ifstream & getStream() { return ifs_; } private: std::string filename_; std::ifstream ifs_; }; class TOPPTICCalculator : public TOPPBase { public: TOPPTICCalculator() : TOPPBase("TICCalculator", "Calculates the TIC from a mass spectrometric raw file (useful for benchmarking).", false) { } protected: void registerOptionsAndFlags_() override { registerInputFile_("in", "<file>", "", "Input file to convert."); registerStringOption_("in_type", "<type>", "", "Input file type -- default: determined from file extension or content\n", false); String formats("mzData,mzXML,mzML,cachedMzML,dta,dta2d,mgf,featureXML,consensusXML,ms2,fid,tsv,peplist,kroenik,edta"); setValidFormats_("in", ListUtils::create<String>(formats)); setValidStrings_("in_type", ListUtils::create<String>(formats)); registerStringOption_("read_method", "<method>", "regular", "Method to read the file", false); String method("regular,indexed,indexed_parallel,streaming,cached,cached_parallel"); setValidStrings_("read_method", ListUtils::create<String>(method)); registerStringOption_("loadData", "<method>", "true", "Whether to actually load and decode the binary data (or whether to skip decoding the binary data)", false); String loadData("true,false"); setValidStrings_("loadData", ListUtils::create<String>(loadData)); } ExitCodes main_(int, const char**) override { //------------------------------------------------------------- // parameter handling //------------------------------------------------------------- //input file names String in = getStringOption_("in"); String read_method = getStringOption_("read_method"); bool load_data = getStringOption_("loadData") == "true"; if (read_method == "streaming") { std::cout << "Read method: streaming" << std::endl; // Create the consumer, set output file name, transform TICConsumer consumer; MzMLFile mzml; mzml.setLogType(log_type_); PeakFileOptions opt = mzml.getOptions(); opt.setFillData(load_data); // whether to actually load any data opt.setSkipXMLChecks(true); // save time by not checking base64 strings for whitespaces opt.setMaxDataPoolSize(100); opt.setAlwaysAppendData(false); mzml.setOptions(opt); mzml.transform(in, &consumer, true, true); std::cout << "There are " << consumer.nr_spectra << " spectra and " << consumer.nr_peaks << " peaks in the input file." << std::endl; std::cout << "The total ion current is " << consumer.TIC << std::endl; size_t after; SysInfo::getProcessMemoryConsumption(after); std::cout << " Memory consumption after " << after << std::endl; } else if (read_method == "regular") { std::cout << "Read method: regular" << std::endl; MzMLFile mzml; mzml.setLogType(log_type_); PeakFileOptions opt = mzml.getOptions(); opt.setFillData(load_data); // whether to actually load any data opt.setSkipXMLChecks(true); // save time by not checking base64 strings for whitespaces mzml.setOptions(opt); PeakMap map; mzml.load(in, map); double TIC = 0.0; long int nr_peaks = 0; for (Size i =0; i < map.size(); i++) { nr_peaks += map[i].size(); for (Size j = 0; j < map[i].size(); j++) { TIC += map[i][j].getIntensity(); } } std::cout << "There are " << map.size() << " spectra and " << nr_peaks << " peaks in the input file." << std::endl; std::cout << "The total ion current is " << TIC << std::endl; size_t after; SysInfo::getProcessMemoryConsumption(after); std::cout << " Memory consumption after " << after << std::endl; } else if (read_method == "indexed") { std::cout << "Read method: indexed" << std::endl; IndexedMzMLFileLoader imzml; // load data from an indexed MzML file OnDiscPeakMap map; imzml.load(in, map); double TIC = 0.0; long int nr_peaks = 0; if (load_data) { for (Size i =0; i < map.getNrSpectra(); i++) { OpenMS::Interfaces::SpectrumPtr sptr = map.getSpectrumById(i); nr_peaks += sptr->getIntensityArray()->data.size(); TIC += std::accumulate(sptr->getIntensityArray()->data.begin(), sptr->getIntensityArray()->data.end(), 0.0); } } std::cout << "There are " << map.getNrSpectra() << " spectra and " << nr_peaks << " peaks in the input file." << std::endl; std::cout << "The total ion current is " << TIC << std::endl; size_t after; SysInfo::getProcessMemoryConsumption(after); std::cout << " Memory consumption after " << after << std::endl; } else if (read_method == "indexed_parallel") { std::cout << "Read method: indexed (parallel)" << std::endl; IndexedMzMLFileLoader imzml; PeakFileOptions opt = imzml.getOptions(); opt.setFillData(load_data); // whether to actually load any data imzml.setOptions(opt); // load data from an indexed MzML file OnDiscPeakMap map; map.openFile(in, true); map.setSkipXMLChecks(true); double TIC = 0.0; long nr_peaks = 0; if (load_data) { // firstprivate means that each thread has its own instance of the // variable, each copy initialized with the initial value #pragma omp parallel for firstprivate(map) reduction(+: TIC, nr_peaks) for (SignedSize i =0; i < (SignedSize)map.getNrSpectra(); i++) { OpenMS::Interfaces::SpectrumPtr sptr = map.getSpectrumById(i); nr_peaks += sptr->getIntensityArray()->data.size(); TIC += std::accumulate(sptr->getIntensityArray()->data.begin(), sptr->getIntensityArray()->data.end(), 0.0); } } std::cout << "There are " << map.getNrSpectra() << " spectra and " << nr_peaks << " peaks in the input file." << std::endl; std::cout << "The total ion current is " << TIC << std::endl; size_t after; SysInfo::getProcessMemoryConsumption(after); std::cout << " Memory consumption after " << after << std::endl; } else if (read_method == "cached") { std::cout << "Read method: cached" << std::endl; // Special handling of cached mzML as input types: // we expect two paired input files which we should read into exp std::vector<String> split_out; in.split(".cachedMzML", split_out); if (split_out.size() != 2) { OPENMS_LOG_ERROR << "Cannot deduce base path from input '" << in << "' (note that '.cachedMzML' should only occur once as the final ending)" << std::endl; return ILLEGAL_PARAMETERS; } String in_meta = split_out[0] + ".mzML"; MzMLFile f; f.setLogType(log_type_); Internal::CachedMzMLHandler cache; cache.createMemdumpIndex(in); const std::vector<std::streampos> spectra_index = cache.getSpectraIndex(); std::ifstream ifs_; ifs_.open(in.c_str(), std::ios::binary); double TIC = 0.0; long int nr_peaks = 0; for (Size i=0; i < spectra_index.size(); ++i) { BinaryDataArrayPtr mz_array(new BinaryDataArray); BinaryDataArrayPtr intensity_array(new BinaryDataArray); int ms_level = -1; double rt = -1.0; ifs_.seekg(spectra_index[i]); Internal::CachedMzMLHandler::readSpectrumFast(mz_array, intensity_array, ifs_, ms_level, rt); nr_peaks += intensity_array->data.size(); for (Size j = 0; j < intensity_array->data.size(); j++) { TIC += intensity_array->data[j]; } } std::cout << "There are " << spectra_index.size() << " spectra and " << nr_peaks << " peaks in the input file." << std::endl; std::cout << "The total ion current is " << TIC << std::endl; size_t after; SysInfo::getProcessMemoryConsumption(after); std::cout << " Memory consumption after " << after << std::endl; } else if (read_method == "cached_parallel") { std::cout << "Read method: cached parallel" << std::endl; // Special handling of cached mzML as input types: // we expect two paired input files which we should read into exp std::vector<String> split_out; in.split(".cachedMzML", split_out); if (split_out.size() != 2) { OPENMS_LOG_ERROR << "Cannot deduce base path from input '" << in << "' (note that '.cachedMzML' should only occur once as the final ending)" << std::endl; return ILLEGAL_PARAMETERS; } String in_meta = split_out[0] + ".mzML"; MzMLFile f; f.setLogType(log_type_); Internal::CachedMzMLHandler cache; cache.createMemdumpIndex(in); const std::vector<std::streampos> spectra_index = cache.getSpectraIndex(); FileAbstraction filestream(in); double TIC = 0.0; long nr_peaks = 0; #pragma omp parallel for firstprivate(filestream) reduction(+: TIC, nr_peaks) for (SignedSize i=0; i < (SignedSize)spectra_index.size(); ++i) { BinaryDataArrayPtr mz_array(new BinaryDataArray); BinaryDataArrayPtr intensity_array(new BinaryDataArray); int ms_level = -1; double rt = -1.0; // we only change the position of the thread-local filestream filestream.getStream().seekg(spectra_index[i]); Internal::CachedMzMLHandler::readSpectrumFast(mz_array, intensity_array, filestream.getStream(), ms_level, rt); nr_peaks += intensity_array->data.size(); TIC += std::accumulate(intensity_array->data.begin(), intensity_array->data.end(), 0.0); } std::cout << "There are " << spectra_index.size() << " spectra and " << nr_peaks << " peaks in the input file." << std::endl; std::cout << "The total ion current is " << TIC << std::endl; size_t after; SysInfo::getProcessMemoryConsumption(after); std::cout << " Memory consumption after " << after << std::endl; } return EXECUTION_OK; } }; int main(int argc, const char** argv) { // Print usage if used without arguments if (argc == 1) { TOPPTICCalculator tool; tool.main(argc, argv); return 0; } // Add -test at the end of the arguments in order to avoid calling the OpenMS // server for usage statistics (and thus making the benchmark slower) char testflag[] = "-test"; std::vector<const char *> newArgs(argc+1); // vector containing one element more than required for (int arg = 0; arg < argc; ++arg) { newArgs[arg] = argv[arg]; } newArgs[argc] = testflag; TOPPTICCalculator tool; size_t after, before; SysInfo::getProcessMemoryConsumption(before); std::cout << " Memory consumption before " << before << std::endl; tool.main(argc+1, (const char **)&newArgs[0]); SysInfo::getProcessMemoryConsumption(after); std::cout << " Memory consumption final " << after << std::endl; return 0; } /// @endcond
36.202247
166
0.633209
[ "vector", "transform" ]
c8db1cc8ebb5598822918360ac11c2531e611080
1,700
cpp
C++
PAT-Advanced/PAT1057-Stack.cpp
Ad147/LeetCode-Solutions
2ddbaef7387887f030825616cafde87db7d2022e
[ "MIT" ]
null
null
null
PAT-Advanced/PAT1057-Stack.cpp
Ad147/LeetCode-Solutions
2ddbaef7387887f030825616cafde87db7d2022e
[ "MIT" ]
null
null
null
PAT-Advanced/PAT1057-Stack.cpp
Ad147/LeetCode-Solutions
2ddbaef7387887f030825616cafde87db7d2022e
[ "MIT" ]
null
null
null
// PAT1057-Stack.cpp // Ad // Init: 19Aug26 // Score: 17/30 // Time: 60' // Runtime: 4 ms #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; void push(vector<int> &stack); void pop(vector<int> &stack, vector<string> &output); void peek(vector<int> stack, vector<string> &output); // Main ------------------------------------------------------------------------ int main() { int numCommands = 0; cin >> numCommands; vector<int> stack; vector<string> output; for (int i = 0; i < numCommands; ++i) { string command; cin >> command; if (command == "Push") push(stack); else if (command == "Pop") pop(stack, output); else if (command == "PeekMedian") peek(stack, output); else throw exception(); } for (auto o : output) cout << o << endl; system("pause"); return 0; } // Functions --------------------------------------------------------------- void push(vector<int> &stack) { int key = 0; cin >> key; stack.push_back(key); } void pop(vector<int> &stack, vector<string> &output) { if (stack.empty()) { output.push_back("Invalid"); return; } output.push_back(to_string(stack.back())); stack.pop_back(); } void peek(vector<int> stack, vector<string> &output) { if (stack.empty()) { output.push_back("Invalid"); return; } int mid = (stack.size() % 2 == 0) ? stack.size() / 2 : (stack.size() + 1) / 2; nth_element(stack.begin(), stack.begin() + mid - 1, stack.end()); output.push_back(to_string(stack[mid - 1])); }
20.481928
82
0.513529
[ "vector" ]
c8dc0a2fe186a18a31ff8c0fcba019ab00b176ad
3,084
cpp
C++
plugins/ellis_tiler/ellis_tiler.cpp
eayus/wayfire
e71beff56eb8d82b16d02a48efc66fa127886d35
[ "MIT" ]
null
null
null
plugins/ellis_tiler/ellis_tiler.cpp
eayus/wayfire
e71beff56eb8d82b16d02a48efc66fa127886d35
[ "MIT" ]
null
null
null
plugins/ellis_tiler/ellis_tiler.cpp
eayus/wayfire
e71beff56eb8d82b16d02a48efc66fa127886d35
[ "MIT" ]
null
null
null
#include "ellis_tiler.hpp" #include <iostream> #include <algorithm> constexpr int OUTER_GAP = 20; constexpr int INNER_GAP = 20; namespace elos { WindowTree::WindowTree() : root(nullptr), next_split_type(SplitType::Horizontal) { } WindowTree WindowTree::empty() { WindowTree wt; return wt; } void WindowTree::next_split(SplitType type) { this->next_split_type = type; } void WindowTree::insert(wayfire_view view) { std::cout << "Inserting window into tree" << std::endl; if (this->root != nullptr) { this->root = new Node((Container){ .split_type = this->next_split_type, .left = this->root, .right = new Node((Window){ .view = view }), }); } else { this->root = new Node((Window){ .view = view }); } // TODO: Better geometry system this->update_all_geometry(); } void WindowTree::remove(wayfire_view view) { if (this->root == nullptr) return; auto node_type = this->root->which(); if (node_type == 0) { WindowTree::remove_from_container(&this->root, view); } else { Window& win = boost::get<Window>(*this->root); if (win.view == view) { delete this->root; this->root = nullptr; } } // TODO: Better geometry system this->update_all_geometry(); } void WindowTree::remove_from_container(Node** n, wayfire_view view) { Container& con = boost::get<Container>(**n); if (con.left->which() == 1 && boost::get<Window>(*con.left).view == view) { *n = con.right; delete con.left; return; } if (con.right->which() == 1 && boost::get<Window>(*con.right).view == view) { *n = con.left; delete con.right; return; } if (con.left->which() == 0) { WindowTree::remove_from_container(&con.left, view); } if (con.right->which() == 0) { WindowTree::remove_from_container(&con.right, view); } } void WindowTree::update_all_geometry() { // TODO: don't hardcode std::cout << "Updating all geomtry" << std::endl; wf_geometry new_dims = (wf_geometry){ .x = 0 + OUTER_GAP, .y = 0 + OUTER_GAP, .width = 1920 - (2 * OUTER_GAP), .height = 1080 - (2 * OUTER_GAP), }; if (this->root == nullptr) return; WindowTree::update_geometry(this->root, new_dims); } void WindowTree::update_geometry(Node* n, wf_geometry new_dims) { auto i = n->which(); std::cout << i << std::endl; if (i == 0) { Container& con = boost::get<Container>(*n); wf_geometry left_dims = new_dims; wf_geometry right_dims = new_dims; auto half_w = new_dims.width / 2; auto half_h = new_dims.height / 2; auto half_g = INNER_GAP / 2; if (con.split_type == SplitType::Horizontal) { left_dims.width = half_w - half_g; right_dims.width = half_w - half_g; right_dims.x += half_w + half_g; } else { left_dims.height = half_h - half_g; right_dims.height = half_h - half_g; right_dims.y += half_h + half_g; } WindowTree::update_geometry(con.left, left_dims); WindowTree::update_geometry(con.right, right_dims); } else { Window& win = boost::get<Window>(*n); win.view->set_geometry(new_dims); } } }
22.676471
79
0.635538
[ "geometry" ]
c8e0e43cb6b3b8f5569279d560c6b4596d06bcd5
17,941
cpp
C++
media_driver/agnostic/gen9_kbl/media_interfaces/media_interfaces_g9_kbl.cpp
Kexiaox/media-driver
ff820574f8e6999c5fcd97fd4e45653aa8092462
[ "Intel", "BSD-3-Clause", "MIT" ]
1
2018-07-10T07:45:23.000Z
2018-07-10T07:45:23.000Z
media_driver/agnostic/gen9_kbl/media_interfaces/media_interfaces_g9_kbl.cpp
Kexiaox/media-driver
ff820574f8e6999c5fcd97fd4e45653aa8092462
[ "Intel", "BSD-3-Clause", "MIT" ]
null
null
null
media_driver/agnostic/gen9_kbl/media_interfaces/media_interfaces_g9_kbl.cpp
Kexiaox/media-driver
ff820574f8e6999c5fcd97fd4e45653aa8092462
[ "Intel", "BSD-3-Clause", "MIT" ]
null
null
null
/* * Copyright (c) 2017-2018, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ //! //! \file media_interfaces_g9_kbl.cpp //! \brief Helps with KBL factory creation. //! #include "media_interfaces_g9_kbl.h" #include "codechal_cenc_decode.h" #include "igcodeckrn_g9.h" extern template class MediaInterfacesFactory<MhwInterfaces>; extern template class MediaInterfacesFactory<MmdDevice>; extern template class MediaInterfacesFactory<CodechalDevice>; extern template class MediaInterfacesFactory<CMHalDevice>; extern template class MediaInterfacesFactory<MosUtilDevice>; extern template class MediaInterfacesFactory<VphalDevice>; extern template class MediaInterfacesFactory<RenderHalDevice>; extern template class MediaInterfacesFactory<Nv12ToP010Device>; extern template class MediaInterfacesFactory<DecodeHistogramDevice>; static bool kblRegisteredVphal = MediaInterfacesFactory<VphalDevice>:: RegisterHal<VphalInterfacesG9Kbl>((uint32_t)IGFX_KABYLAKE); MOS_STATUS VphalInterfacesG9Kbl::Initialize( PMOS_INTERFACE osInterface, PMOS_CONTEXT osDriverContext, MOS_STATUS *eStatus) { m_vphalState = MOS_New( VphalState, osInterface, osDriverContext, eStatus); return *eStatus; } static bool kblRegisteredMhw = MediaInterfacesFactory<MhwInterfaces>:: RegisterHal<MhwInterfacesG9Kbl>((uint32_t)IGFX_KABYLAKE); #define PLATFORM_INTEL_KBL 11 #define GENX_SKL 5 MOS_STATUS MhwInterfacesG9Kbl::Initialize( CreateParams params, PMOS_INTERFACE osInterface) { if (osInterface == nullptr) { MHW_ASSERTMESSAGE("The OS interface is not valid!"); return MOS_STATUS_INVALID_PARAMETER; } auto gtSystemInfo = osInterface->pfnGetGtSystemInfo(osInterface); if (gtSystemInfo == nullptr) { MHW_ASSERTMESSAGE("The OS interface is not valid!"); return MOS_STATUS_INVALID_PARAMETER; } if ((params.m_isCp == false) && (params.Flags.m_value == 0)) { MHW_ASSERTMESSAGE("No MHW interfaces were requested for creation."); return MOS_STATUS_INVALID_PARAMETER; } // MHW_CP and MHW_MI must always be created MOS_STATUS status; Mhw_Cp_InitInterface(&m_cpInterface, osInterface); m_miInterface = MOS_New(Mi, m_cpInterface, osInterface); if (params.Flags.m_render) { m_renderInterface = MOS_New(Render, m_miInterface, osInterface, gtSystemInfo, params.m_heapMode); } if (params.Flags.m_stateHeap) { m_stateHeapInterface = MOS_New(StateHeap, osInterface, params.m_heapMode); } if (params.Flags.m_sfc) { m_sfcInterface = MOS_New(Sfc, osInterface); } if (params.Flags.m_vebox) { m_veboxInterface = MOS_New(Vebox, osInterface); } if (params.Flags.m_vdboxAll || params.Flags.m_mfx) { m_mfxInterface = MOS_New(Mfx, osInterface, m_miInterface, m_cpInterface, params.m_isDecode); } if (params.Flags.m_vdboxAll || params.Flags.m_hcp) { m_hcpInterface = MOS_New(Hcp, osInterface, m_miInterface, m_cpInterface, params.m_isDecode); } if (params.Flags.m_vdboxAll || params.Flags.m_huc) { m_hucInterface = MOS_New(Huc, osInterface, m_miInterface, m_cpInterface); } if (params.Flags.m_vdboxAll || params.Flags.m_vdenc) { m_vdencInterface = MOS_New(Vdenc, osInterface); } return MOS_STATUS_SUCCESS; } #ifdef _MMC_SUPPORTED static bool kblRegisteredMmd = MediaInterfacesFactory<MmdDevice>:: RegisterHal<MmdDeviceG9Kbl>((uint32_t)IGFX_KABYLAKE); MOS_STATUS MmdDeviceG9Kbl::Initialize( PMOS_INTERFACE osInterface, MhwInterfaces *mhwInterfaces) { #define MMD_FAILURE() \ { \ if (device != nullptr) \ { \ MOS_Delete(device); \ } \ return MOS_STATUS_NO_SPACE; \ } MHW_FUNCTION_ENTER; MhwMiInterface *miInterface = nullptr; MhwRenderInterface *renderInterface = nullptr; Mmd *device = nullptr; if (mhwInterfaces->m_miInterface == nullptr) { MMD_FAILURE(); } miInterface = mhwInterfaces->m_miInterface; if (mhwInterfaces->m_renderInterface == nullptr) { MMD_FAILURE(); } renderInterface = mhwInterfaces->m_renderInterface; device = MOS_New(Mmd); if (device == nullptr) { MMD_FAILURE(); } if (device->Initialize( osInterface, mhwInterfaces->m_cpInterface, miInterface, renderInterface) != MOS_STATUS_SUCCESS) { MMD_FAILURE(); } m_mmdDevice = device; return MOS_STATUS_SUCCESS; } #endif static bool kblRegisteredNv12ToP010 = MediaInterfacesFactory<Nv12ToP010Device>:: RegisterHal<Nv12ToP010DeviceG9Kbl>((uint32_t)IGFX_KABYLAKE); MOS_STATUS Nv12ToP010DeviceG9Kbl::Initialize( PMOS_INTERFACE osInterface) { m_nv12ToP010device = MOS_New(Nv12ToP010, osInterface); if (m_nv12ToP010device == nullptr) { MHW_ASSERTMESSAGE("Create Nv12 to P010 interfaces failed.") return MOS_STATUS_NO_SPACE; } return MOS_STATUS_SUCCESS; } static bool kblRegisteredCodecHal = MediaInterfacesFactory<CodechalDevice>:: RegisterHal<CodechalInterfacesG9Kbl>((uint32_t)IGFX_KABYLAKE); MOS_STATUS CodechalInterfacesG9Kbl::Initialize( void *standardInfo, void *settings, MhwInterfaces *mhwInterfaces, PMOS_INTERFACE osInterface) { if (standardInfo == nullptr || mhwInterfaces == nullptr || osInterface == nullptr) { CODECHAL_PUBLIC_ASSERTMESSAGE("CodecHal device is not valid!"); return MOS_STATUS_INVALID_PARAMETER; } PCODECHAL_STANDARD_INFO info = ((PCODECHAL_STANDARD_INFO)standardInfo); CODECHAL_FUNCTION CodecFunction = info->CodecFunction; CodechalHwInterface *hwInterface = MOS_New(Hw, osInterface, CodecFunction, mhwInterfaces); #if USE_CODECHAL_DEBUG_TOOL CodechalDebugInterface *debugInterface = MOS_New(CodechalDebugInterface); if (debugInterface->Initialize(hwInterface, CodecFunction) != MOS_STATUS_SUCCESS) { CODECHAL_PUBLIC_ASSERTMESSAGE("Debug interface creation failed!"); return MOS_STATUS_INVALID_PARAMETER; } #else CodechalDebugInterface *debugInterface = nullptr; #endif // USE_CODECHAL_DEBUG_TOOL if (CodecHalIsDecode(CodecFunction)) { #ifdef _MPEG2_DECODE_SUPPORTED if (info->Mode == CODECHAL_DECODE_MODE_MPEG2IDCT || info->Mode == CODECHAL_DECODE_MODE_MPEG2VLD) { m_codechalDevice = MOS_New(Decode::Mpeg2, hwInterface, debugInterface, info); } else #endif #ifdef _VC1_DECODE_SUPPORTED if (info->Mode == CODECHAL_DECODE_MODE_VC1IT || info->Mode == CODECHAL_DECODE_MODE_VC1VLD) { m_codechalDevice = MOS_New(Decode::Vc1, hwInterface, debugInterface, info); } else #endif #ifdef _AVC_DECODE_SUPPORTED if (info->Mode == CODECHAL_DECODE_MODE_AVCVLD) { m_codechalDevice = MOS_New(Decode::Avc, hwInterface, debugInterface, info); if (m_codechalDevice == nullptr) { CODECHAL_PUBLIC_ASSERTMESSAGE("Failed to create decode device!"); return MOS_STATUS_NO_SPACE; } #ifdef _DECODE_PROCESSING_SUPPORTED if (settings != nullptr && ((CodechalSetting *)settings)->downsamplingHinted) { CodechalDecode *decoder = dynamic_cast<CodechalDecode *>(m_codechalDevice); if (decoder == nullptr) { CODECHAL_PUBLIC_ASSERTMESSAGE("Failed to create decode device!"); return MOS_STATUS_NO_SPACE; } FieldScalingInterface *fieldScalingInterface = MOS_New(Decode::FieldScaling, hwInterface); if (fieldScalingInterface == nullptr) { CODECHAL_PUBLIC_ASSERTMESSAGE("Failed to create field scaling interface!"); return MOS_STATUS_NO_SPACE; } decoder->m_fieldScalingInterface = fieldScalingInterface; } #endif } else #endif #ifdef _JPEG_DECODE_SUPPORTED if (info->Mode == CODECHAL_DECODE_MODE_JPEG) { m_codechalDevice = MOS_New(Decode::Jpeg, hwInterface, debugInterface, info); } else #endif #ifdef _VP8_DECODE_SUPPORTED if (info->Mode == CODECHAL_DECODE_MODE_VP8VLD) { m_codechalDevice = MOS_New(Decode::Vp8, hwInterface, debugInterface, info); } else #endif #ifdef _HEVC_DECODE_SUPPORTED if (info->Mode == CODECHAL_DECODE_MODE_HEVCVLD) { m_codechalDevice = MOS_New(Decode::Hevc, hwInterface, debugInterface, info); } else #endif #ifdef _VP9_DECODE_SUPPORTED if (info->Mode == CODECHAL_DECODE_MODE_VP9VLD) { m_codechalDevice = MOS_New(Decode::Vp9, hwInterface, debugInterface, info); } else #endif { CODECHAL_PUBLIC_ASSERTMESSAGE("Decode mode requested invalid!"); return MOS_STATUS_INVALID_PARAMETER; } CodechalDecode *decoder = dynamic_cast<CodechalDecode *>(m_codechalDevice); if (decoder == nullptr) { CODECHAL_PUBLIC_ASSERTMESSAGE("Decoder device creation failed!"); return MOS_STATUS_NO_SPACE; } decoder->SetHuCProductFamily(HUC_KABYLAKE); } else if (CodecHalIsEncode(CodecFunction)) { CodechalEncoderState* encoder = nullptr; #ifdef _MPEG2_ENCODE_SUPPORTED if (info->Mode == CODECHAL_ENCODE_MODE_MPEG2) { // Setup encode interface functions encoder = MOS_New(Encode::Mpeg2, hwInterface, debugInterface, info); if (encoder == nullptr) { CODECHAL_PUBLIC_ASSERTMESSAGE("Encode allocation failed!"); return MOS_STATUS_INVALID_PARAMETER; } else { m_codechalDevice = encoder; } encoder->m_kernelBase = (uint8_t*)IGCODECKRN_G9; } else #endif #ifdef _JPEG_ENCODE_SUPPORTED if (info->Mode == CODECHAL_ENCODE_MODE_JPEG) { encoder = MOS_New(Encode::Jpeg, hwInterface, debugInterface, info); if (encoder == nullptr) { CODECHAL_PUBLIC_ASSERTMESSAGE("Encode state creation failed!"); return MOS_STATUS_INVALID_PARAMETER; } else { m_codechalDevice = encoder; } encoder->m_needCheckCpEnabled = true; } else #endif #ifdef _HEVC_ENCODE_SUPPORTED if (info->Mode == CODECHAL_ENCODE_MODE_HEVC) { encoder = MOS_New(Encode::HevcEnc, hwInterface, debugInterface, info); if (encoder == nullptr) { CODECHAL_PUBLIC_ASSERTMESSAGE("Encode state creation failed!"); return MOS_STATUS_INVALID_PARAMETER; } else { m_codechalDevice = encoder; } encoder->m_kernelBase = (uint8_t*)IGCODECKRN_G9; } else #endif #ifdef _AVC_ENCODE_SUPPORTED if (info->Mode == CODECHAL_ENCODE_MODE_AVC) { if (CodecHalUsesVdencEngine(info->CodecFunction)) { encoder = MOS_New(Encode::AvcVdenc, hwInterface, debugInterface, info); } else { encoder = MOS_New(Encode::AvcEnc, hwInterface, debugInterface, info); } if (encoder == nullptr) { CODECHAL_PUBLIC_ASSERTMESSAGE("Encode state creation failed!"); return MOS_STATUS_INVALID_PARAMETER; } else { m_codechalDevice = encoder; } } else #endif { CODECHAL_PUBLIC_ASSERTMESSAGE("Unsupported encode function requested."); return MOS_STATUS_INVALID_PARAMETER; } if (info->Mode != CODECHAL_ENCODE_MODE_JPEG) { // Create CSC and Downscaling interface if ((encoder->m_cscDsState = MOS_New(Encode::CscDs, encoder)) == nullptr) { return MOS_STATUS_INVALID_PARAMETER; } } } else { CODECHAL_PUBLIC_ASSERTMESSAGE("Unsupported codec function requested."); return MOS_STATUS_INVALID_PARAMETER; } return MOS_STATUS_SUCCESS; } CodechalHwInterface *CodechalInterfacesG9Kbl::CreateCodechalHwInterface( CODECHAL_FUNCTION CodecFunction, MhwInterfaces *mhwInterfaces, PMOS_INTERFACE osInterface) { if (mhwInterfaces == nullptr) { CODECHAL_PUBLIC_ASSERTMESSAGE("Create Codechal hardware interfaces failed."); return nullptr; } CodechalHwInterface *codechalHwInterface = MOS_New(Hw, osInterface, CodecFunction, mhwInterfaces); return codechalHwInterface; } static bool kblRegisteredCMHal = MediaInterfacesFactory<CMHalDevice>:: RegisterHal<CMHalInterfacesG9Kbl>((uint32_t)IGFX_KABYLAKE); MOS_STATUS CMHalInterfacesG9Kbl::Initialize(CM_HAL_STATE *pCmState) { m_cmhalDevice = MOS_New(CMHal, pCmState); if (m_cmhalDevice == nullptr) { MHW_ASSERTMESSAGE("Create CM Hal interfaces failed.") return MOS_STATUS_NO_SPACE; } int gengt = PLATFORM_INTEL_GT2; if (MEDIA_IS_SKU(pCmState->skuTable, FtrGT1)) { gengt = PLATFORM_INTEL_GT1; } else if (MEDIA_IS_SKU(pCmState->skuTable, FtrGT1_5)) { gengt = PLATFORM_INTEL_GT1_5; } else if (MEDIA_IS_SKU(pCmState->skuTable, FtrGT2)) { gengt = PLATFORM_INTEL_GT2; } else if (MEDIA_IS_SKU(pCmState->skuTable, FtrGT3)) { gengt = PLATFORM_INTEL_GT3; } else if (MEDIA_IS_SKU(pCmState->skuTable, FtrGT4)) { gengt = PLATFORM_INTEL_GT4; } m_cmhalDevice->SetGenPlatformInfo(PLATFORM_INTEL_KBL, gengt, "SKL"); uint32_t cisaID = GENX_SKL; m_cmhalDevice->AddSupportedCisaIDs(&cisaID); CM_HAL_G9_X *pGen9Device = static_cast<CM_HAL_G9_X *>(m_cmhalDevice); const char *CmSteppingInfo_KBL[] = { "A0", "B0", "C0", "D0", "E0" }; pGen9Device->OverwriteSteppingTable(CmSteppingInfo_KBL, sizeof(CmSteppingInfo_KBL)/sizeof(const char *)); return MOS_STATUS_SUCCESS; } static bool kblRegisteredMosUtil = MediaInterfacesFactory<MosUtilDevice>:: RegisterHal<MosUtilDeviceG9Kbl>((uint32_t)IGFX_KABYLAKE); MOS_STATUS MosUtilDeviceG9Kbl::Initialize() { #define MOSUTIL_FAILURE() \ { \ if (device != nullptr) \ { \ delete device; \ } \ return MOS_STATUS_NO_SPACE; \ } MosUtil *device = nullptr; device = MOS_New(MosUtil); if (device == nullptr) { MOSUTIL_FAILURE(); } if (device->Initialize() != MOS_STATUS_SUCCESS) { MOSUTIL_FAILURE(); } m_mosUtilDevice = device; return MOS_STATUS_SUCCESS; } static bool kblRegisteredRenderHal = MediaInterfacesFactory<RenderHalDevice>:: RegisterHal<RenderHalInterfacesG9Kbl>((uint32_t)IGFX_KABYLAKE); MOS_STATUS RenderHalInterfacesG9Kbl::Initialize() { m_renderhalDevice = MOS_New(XRenderHal); if (m_renderhalDevice == nullptr) { MHW_ASSERTMESSAGE("Create Render Hal interfaces failed.") return MOS_STATUS_NO_SPACE; } return MOS_STATUS_SUCCESS; } static bool kblRegisteredDecodeHistogram = MediaInterfacesFactory<DecodeHistogramDevice>:: RegisterHal<DecodeHistogramDeviceG9Kbl>((uint32_t)IGFX_KABYLAKE); MOS_STATUS DecodeHistogramDeviceG9Kbl::Initialize( CodechalHwInterface *hwInterface, PMOS_INTERFACE osInterface) { m_decodeHistogramDevice = MOS_New(DecodeHistogramVebox, hwInterface, osInterface); if (m_decodeHistogramDevice == nullptr) { MHW_ASSERTMESSAGE("Create vebox decode histogram interfaces failed.") return MOS_STATUS_NO_SPACE; } return MOS_STATUS_SUCCESS; }
31.641975
109
0.637478
[ "render" ]
c8e52b798208037fd9f2a8688e0a1fbd97118097
14,563
cc
C++
src/stirling/source_connectors/dynamic_bpftrace/dynamic_bpftrace_connector_test.cc
robertprast/pixie
d9e8fd70a51aaf4db3c859215e65efa28ccb4582
[ "Apache-2.0" ]
null
null
null
src/stirling/source_connectors/dynamic_bpftrace/dynamic_bpftrace_connector_test.cc
robertprast/pixie
d9e8fd70a51aaf4db3c859215e65efa28ccb4582
[ "Apache-2.0" ]
null
null
null
src/stirling/source_connectors/dynamic_bpftrace/dynamic_bpftrace_connector_test.cc
robertprast/pixie
d9e8fd70a51aaf4db3c859215e65efa28ccb4582
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018- The Pixie Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ #include <unistd.h> #include <regex> #include <gmock/gmock.h> #include "src/common/testing/testing.h" #include "src/stirling/source_connectors/dynamic_bpftrace/dynamic_bpftrace_connector.h" namespace px { namespace stirling { using ::px::stirling::dynamic_tracing::ir::logical::TracepointDeployment_Tracepoint; using ::px::testing::status::StatusIs; using ::testing::HasSubstr; using ::testing::MatchesRegex; // A regex for a string of printable characters. See ASCII table. constexpr char kPrintableRegex[] = "[ -~]*"; TEST(DynamicBPFTraceConnectorTest, Basic) { // Create a BPFTrace program spec TracepointDeployment_Tracepoint tracepoint; tracepoint.set_table_name("pid_sample_table"); constexpr char kScript[] = R"(interval:ms:100 { printf(" aaa time_:%llu pid:%u value:%llu aaa command:%s address:%s aaa\n", nsecs, pid, 0, comm, ntop(0)); })"; tracepoint.mutable_bpftrace()->set_program(kScript); ASSERT_OK_AND_ASSIGN(std::unique_ptr<SourceConnector> connector, DynamicBPFTraceConnector::Create("test", tracepoint)); const int kTableNum = 0; const DataTableSchema& table_schema = connector->table_schemas()[kTableNum]; // Check the inferred table schema. { const ArrayView<DataElement>& elements = table_schema.elements(); ASSERT_EQ(elements.size(), 5); EXPECT_EQ(elements[0].name(), "time_"); EXPECT_EQ(elements[0].type(), types::DataType::TIME64NS); EXPECT_EQ(elements[1].name(), "pid"); EXPECT_EQ(elements[1].type(), types::DataType::INT64); EXPECT_EQ(elements[2].name(), "value"); EXPECT_EQ(elements[2].type(), types::DataType::INT64); EXPECT_EQ(elements[3].name(), "command"); EXPECT_EQ(elements[3].type(), types::DataType::STRING); EXPECT_EQ(elements[4].name(), "address"); EXPECT_EQ(elements[4].type(), types::DataType::STRING); } // Now deploy the spec and check for some data. ASSERT_OK(connector->Init()); // Give some time to collect data. sleep(1); // Read the data. StandaloneContext ctx; DataTable data_table(/*id*/ 0, table_schema); connector->TransferData(&ctx, {&data_table}); std::vector<TaggedRecordBatch> tablets = data_table.ConsumeRecords(); // Should've gotten something in the records. ASSERT_FALSE(tablets.empty()); // Check that we can gracefully wrap-up. ASSERT_OK(connector->Stop()); } TEST(DynamicBPFTraceConnectorTest, BPFTraceBuiltins) { // Create a BPFTrace program spec TracepointDeployment_Tracepoint tracepoint; tracepoint.set_table_name("pid_sample_table"); constexpr char kScript[] = R"(interval:ms:100 { printf("pid:%llu tid:%llu uid:%llu gid:%llu nsecs:%llu elapsed:%llu cpu:%llu comm:%s kstack:%s", pid, tid, uid, gid, nsecs, elapsed, cpu, comm, kstack); })"; tracepoint.mutable_bpftrace()->set_program(kScript); ASSERT_OK_AND_ASSIGN(std::unique_ptr<SourceConnector> connector, DynamicBPFTraceConnector::Create("test", tracepoint)); const int kTableNum = 0; const DataTableSchema& table_schema = connector->table_schemas()[kTableNum]; const int kPIDIdx = 0; const int kTIDIdx = 1; const int kUIDIdx = 2; const int kGIDIdx = 3; const int kNsecsIdx = 4; const int kElapsedIdx = 5; const int kCPUIdx = 6; const int kCommIdx = 7; const int kStackIdx = 8; // Check the inferred table schema. { const ArrayView<DataElement>& elements = table_schema.elements(); ASSERT_EQ(elements.size(), 9); EXPECT_EQ(elements[kPIDIdx].name(), "pid"); EXPECT_EQ(elements[kPIDIdx].type(), types::DataType::INT64); EXPECT_EQ(elements[kTIDIdx].name(), "tid"); EXPECT_EQ(elements[kTIDIdx].type(), types::DataType::INT64); EXPECT_EQ(elements[kUIDIdx].name(), "uid"); EXPECT_EQ(elements[kUIDIdx].type(), types::DataType::INT64); EXPECT_EQ(elements[kGIDIdx].name(), "gid"); EXPECT_EQ(elements[kGIDIdx].type(), types::DataType::INT64); EXPECT_EQ(elements[kNsecsIdx].name(), "nsecs"); EXPECT_EQ(elements[kNsecsIdx].type(), types::DataType::INT64); EXPECT_EQ(elements[kElapsedIdx].name(), "elapsed"); EXPECT_EQ(elements[kElapsedIdx].type(), types::DataType::INT64); EXPECT_EQ(elements[kCPUIdx].name(), "cpu"); EXPECT_EQ(elements[kCPUIdx].type(), types::DataType::INT64); EXPECT_EQ(elements[kCommIdx].name(), "comm"); EXPECT_EQ(elements[kCommIdx].type(), types::DataType::STRING); EXPECT_EQ(elements[kStackIdx].name(), "kstack"); EXPECT_EQ(elements[kStackIdx].type(), types::DataType::STRING); } // Now deploy the spec and check for some data. ASSERT_OK(connector->Init()); // Give some time to collect data. sleep(1); // Read the data. StandaloneContext ctx; DataTable data_table(/*id*/ 0, table_schema); connector->TransferData(&ctx, {&data_table}); std::vector<TaggedRecordBatch> tablets = data_table.ConsumeRecords(); // Should've gotten something in the records. ASSERT_FALSE(tablets.empty()); // TODO(oazizi): Use /proc/sys/kernel/pid_max to make more robust. const uint64_t kMaxPIDValue = 1ULL << 22; const uint64_t kMaxUIDValue = 1ULL << 32; types::ColumnWrapperRecordBatch& records = tablets[0].records; // Check the first record for reasonable values. { int64_t pid = records[kPIDIdx]->Get<types::Int64Value>(0).val; LOG(INFO) << absl::Substitute("PID: $0", pid); EXPECT_GE(pid, 0); EXPECT_LE(pid, kMaxPIDValue); int64_t tid = records[kTIDIdx]->Get<types::Int64Value>(0).val; LOG(INFO) << absl::Substitute("TID: $0", tid); EXPECT_GE(tid, 0); EXPECT_LE(tid, kMaxPIDValue); int64_t uid = records[kUIDIdx]->Get<types::Int64Value>(0).val; LOG(INFO) << absl::Substitute("UID: $0", uid); EXPECT_GE(uid, 0); EXPECT_LE(uid, kMaxUIDValue); int64_t gid = records[kGIDIdx]->Get<types::Int64Value>(0).val; LOG(INFO) << absl::Substitute("GID: $0", gid); EXPECT_GE(gid, 0); EXPECT_LE(gid, kMaxUIDValue); int64_t nsecs = records[kNsecsIdx]->Get<types::Int64Value>(0).val; LOG(INFO) << absl::Substitute("nsecs: $0", nsecs); // Event should have been in the last 10 seconds (being generous). auto now = std::chrono::steady_clock::now().time_since_epoch(); auto now_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(now).count(); constexpr int64_t kNanosPerSecond = 1000 * 1000 * 1000; EXPECT_GE(nsecs, now_ns - 10 * kNanosPerSecond); EXPECT_LE(nsecs, now_ns); int64_t elapsed = records[kElapsedIdx]->Get<types::Int64Value>(0).val; LOG(INFO) << absl::Substitute("elpased: $0", elapsed); // TODO(oazizi): Investigate why this produces negative numbers. // EXPECT_GE(elapsed, 0*kNanosPerSecond); // EXPECT_LE(elapsed, 100*kNanosPerSecond); int64_t cpu = records[kCPUIdx]->Get<types::Int64Value>(0).val; LOG(INFO) << absl::Substitute("CPU: $0", cpu); EXPECT_GE(cpu, 0); EXPECT_LE(cpu, 100); // comm std::string comm = records[kCommIdx]->Get<types::StringValue>(0); LOG(INFO) << absl::Substitute("comm: $0", comm); EXPECT_THAT(comm, MatchesRegex(kPrintableRegex)); } // Check that we can gracefully wrap-up. ASSERT_OK(connector->Stop()); } TEST(DynamicBPFTraceConnectorTest, BPFTraceBuiltins2) { // Create a BPFTrace program spec TracepointDeployment_Tracepoint tracepoint; tracepoint.set_table_name("pid_sample_table"); constexpr char kScript[] = R"(interval:ms:100 { printf("username:%s ftime:%s inet:%s", username, strftime("%H:%M:%S", nsecs), ntop(0)); })"; tracepoint.mutable_bpftrace()->set_program(kScript); ASSERT_OK_AND_ASSIGN(std::unique_ptr<SourceConnector> connector, DynamicBPFTraceConnector::Create("test", tracepoint)); const int kTableNum = 0; const DataTableSchema& table_schema = connector->table_schemas()[kTableNum]; const int kUsernameIdx = 0; const int kFTimeIdx = 1; const int kInetIdx = 2; // Check the inferred table schema. { const ArrayView<DataElement>& elements = table_schema.elements(); ASSERT_EQ(elements.size(), 3); EXPECT_EQ(elements[kUsernameIdx].name(), "username"); EXPECT_EQ(elements[kUsernameIdx].type(), types::DataType::STRING); EXPECT_EQ(elements[kFTimeIdx].name(), "ftime"); EXPECT_EQ(elements[kFTimeIdx].type(), types::DataType::STRING); EXPECT_EQ(elements[kInetIdx].name(), "inet"); EXPECT_EQ(elements[kInetIdx].type(), types::DataType::STRING); } // Now deploy the spec and check for some data. ASSERT_OK(connector->Init()); // Give some time to collect data. sleep(1); // Read the data. StandaloneContext ctx; DataTable data_table(/*id*/ 0, table_schema); connector->TransferData(&ctx, {&data_table}); std::vector<TaggedRecordBatch> tablets = data_table.ConsumeRecords(); // Should've gotten something in the records. ASSERT_FALSE(tablets.empty()); types::ColumnWrapperRecordBatch& records = tablets[0].records; std::string username = records[kUsernameIdx]->Get<types::StringValue>(0); LOG(INFO) << absl::Substitute("username: $0", username); EXPECT_THAT(username, MatchesRegex(kPrintableRegex)); std::string ftime = records[kFTimeIdx]->Get<types::StringValue>(0); LOG(INFO) << absl::Substitute("ftime: $0", ftime); EXPECT_THAT(ftime, MatchesRegex("[0-2][0-9]:[0-5][0-9]:[0-5][0-9]")); std::string inet = records[kInetIdx]->Get<types::StringValue>(0); LOG(INFO) << absl::Substitute("inet: $0", inet); EXPECT_EQ(inet, "0.0.0.0"); // Check that we can gracefully wrap-up. ASSERT_OK(connector->Stop()); } TEST(DynamicBPFTraceConnectorTest, BPFTraceUnlabeledColumn) { // Create a BPFTrace program spec TracepointDeployment_Tracepoint tracepoint; tracepoint.set_table_name("pid_sample_table"); constexpr char kScript[] = R"(interval:ms:100 { printf("username:%s foo %s inet:%s", username, strftime("%H:%M:%S", nsecs), ntop(0)); })"; tracepoint.mutable_bpftrace()->set_program(kScript); ASSERT_OK_AND_ASSIGN(std::unique_ptr<SourceConnector> connector, DynamicBPFTraceConnector::Create("test", tracepoint)); const int kTableNum = 0; const DataTableSchema& table_schema = connector->table_schemas()[kTableNum]; const int kUsernameIdx = 0; const int kFTimeIdx = 1; const int kInetIdx = 2; // Check the inferred table schema. { const ArrayView<DataElement>& elements = table_schema.elements(); ASSERT_EQ(elements.size(), 3); EXPECT_EQ(elements[kUsernameIdx].name(), "username"); EXPECT_EQ(elements[kUsernameIdx].type(), types::DataType::STRING); EXPECT_EQ(elements[kFTimeIdx].name(), "Column_1"); EXPECT_EQ(elements[kFTimeIdx].type(), types::DataType::STRING); EXPECT_EQ(elements[kInetIdx].name(), "inet"); EXPECT_EQ(elements[kInetIdx].type(), types::DataType::STRING); } // Now deploy the spec and check for some data. ASSERT_OK(connector->Init()); // Give some time to collect data. sleep(1); // Read the data. StandaloneContext ctx; DataTable data_table(/*id*/ 0, table_schema); connector->TransferData(&ctx, {&data_table}); std::vector<TaggedRecordBatch> tablets = data_table.ConsumeRecords(); // Should've gotten something in the records. ASSERT_FALSE(tablets.empty()); types::ColumnWrapperRecordBatch& records = tablets[0].records; std::string username = records[kUsernameIdx]->Get<types::StringValue>(0); LOG(INFO) << absl::Substitute("username: $0", username); EXPECT_THAT(username, MatchesRegex(kPrintableRegex)); std::string ftime = records[kFTimeIdx]->Get<types::StringValue>(0); LOG(INFO) << absl::Substitute("ftime: $0", ftime); EXPECT_THAT(ftime, MatchesRegex("[0-2][0-9]:[0-5][0-9]:[0-5][0-9]")); std::string inet = records[kInetIdx]->Get<types::StringValue>(0); LOG(INFO) << absl::Substitute("inet: $0", inet); EXPECT_EQ(inet, "0.0.0.0"); // Check that we can gracefully wrap-up. ASSERT_OK(connector->Stop()); } TEST(DynamicBPFTraceConnectorTest, BPFTraceSyntacticError) { // Create a BPFTrace program spec TracepointDeployment_Tracepoint tracepoint; tracepoint.set_table_name("pid_sample_table"); constexpr char kScript[] = R"(interval:ms:100 { bogus printf("username:%s time:%s", username, nsecs); })"; tracepoint.mutable_bpftrace()->set_program(kScript); // TODO(oazizi): Find a way to get the clang error passed up. ASSERT_THAT(DynamicBPFTraceConnector::Create("test", tracepoint).status(), StatusIs(statuspb::INTERNAL, HasSubstr("Could not load bpftrace script"))); } TEST(DynamicBPFTraceConnectorTest, BPFTraceSemanticError) { // Create a BPFTrace program spec TracepointDeployment_Tracepoint tracepoint; tracepoint.set_table_name("pid_sample_table"); constexpr char kScript[] = R"(interval:ms:100 { printf("username:%s foo %s inet:%s", username, strftime("%H:%M:%S", nsecs), ntop(0), 0); })"; tracepoint.mutable_bpftrace()->set_program(kScript); ASSERT_THAT(DynamicBPFTraceConnector::Create("test", tracepoint).status(), StatusIs(statuspb::INTERNAL, HasSubstr("ERROR: printf: Too many arguments for format string"))); } TEST(DynamicBPFTraceConnectorTest, BPFTraceCheckPrintfsError) { // Create a BPFTrace program spec TracepointDeployment_Tracepoint tracepoint; tracepoint.set_table_name("pid_sample_table"); constexpr char kScript[] = R"(interval:ms:100 { printf("time:%llu val:%d inet:%s", nsecs, 1, "true"); printf("time:%llu name:%s", nsecs, "hello"); })"; tracepoint.mutable_bpftrace()->set_program(kScript); ASSERT_THAT( DynamicBPFTraceConnector::Create("test", tracepoint).status(), StatusIs(statuspb::INTERNAL, HasSubstr("All printf statements must have exactly the same format string"))); } } // namespace stirling } // namespace px
34.025701
110
0.691341
[ "vector" ]
c8e5ece4499c2822cc2f7d2ad1d49258420142f3
58,780
cpp
C++
src/tests/reservation_endpoints_tests.cpp
zagrev/mesos
eefec152dffc4977183089b46fbfe37dbd19e9d7
[ "Apache-2.0" ]
4,537
2015-01-01T03:26:40.000Z
2022-03-31T03:07:00.000Z
src/tests/reservation_endpoints_tests.cpp
zagrev/mesos
eefec152dffc4977183089b46fbfe37dbd19e9d7
[ "Apache-2.0" ]
227
2015-01-29T02:21:39.000Z
2022-03-29T13:35:50.000Z
src/tests/reservation_endpoints_tests.cpp
zagrev/mesos
eefec152dffc4977183089b46fbfe37dbd19e9d7
[ "Apache-2.0" ]
1,992
2015-01-05T12:29:19.000Z
2022-03-31T03:07:07.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include <vector> #include <gmock/gmock.h> #include <mesos/executor.hpp> #include <mesos/scheduler.hpp> #include <process/clock.hpp> #include <process/future.hpp> #include <process/gmock.hpp> #include <process/http.hpp> #include <process/owned.hpp> #include <process/pid.hpp> #include <stout/option.hpp> #include "master/flags.hpp" #include "master/master.hpp" #include "tests/mesos.hpp" #include "tests/resources_utils.hpp" #include "tests/utils.hpp" using std::string; using std::vector; using google::protobuf::RepeatedPtrField; using mesos::internal::master::Master; using mesos::internal::protobuf::createLabel; using mesos::internal::slave::Slave; using mesos::master::detector::MasterDetector; using process::Clock; using process::Future; using process::Owned; using process::PID; using process::http::Accepted; using process::http::BadRequest; using process::http::Conflict; using process::http::Forbidden; using process::http::OK; using process::http::Response; using process::http::Unauthorized; using testing::_; namespace mesos { namespace internal { namespace tests { class ReservationEndpointsTest : public MesosTest { public: // Set up the master flags such that it allows registration of the framework // created with 'createFrameworkInfo'. master::Flags CreateMasterFlags() override { // Turn off periodic allocations to avoid the race between // `HierarchicalAllocator::updateAvailable()` and periodic allocations. master::Flags flags = MesosTest::CreateMasterFlags(); flags.allocation_interval = Seconds(1000); flags.roles = createFrameworkInfo().roles(0); return flags; } // Returns a FrameworkInfo with role, "role". FrameworkInfo createFrameworkInfo() { FrameworkInfo info = DEFAULT_FRAMEWORK_INFO; info.set_roles(0, "role"); return info; } string createRequestBody( const SlaveID& slaveId, const RepeatedPtrField<Resource>& resources) const { return strings::format( "slaveId=%s&resources=%s", slaveId.value(), JSON::protobuf(resources)).get(); } }; // This tests that an operator can reserve/unreserve available resources. TEST_F(ReservationEndpointsTest, AvailableResources) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get()); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); FrameworkInfo frameworkInfo = createFrameworkInfo(); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources dynamicallyReserved = unreserved.pushReservation(createDynamicReservationInfo( frameworkInfo.roles(0), DEFAULT_CREDENTIAL.principal())); Future<Response> response = process::http::post( master.get()->pid, "reserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, dynamicallyReserved)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); MockScheduler sched; MesosSchedulerDriver driver( &sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL); Future<vector<Offer>> offers; EXPECT_CALL(sched, registered(&driver, _, _)); EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)); driver.start(); AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); Offer offer = offers.get()[0]; EXPECT_TRUE(Resources(offer.resources()).contains( allocatedResources(dynamicallyReserved, frameworkInfo.roles(0)))); // The filter to decline the offer "forever". Filters filtersForever; filtersForever.set_refuse_seconds(1000); // Decline the offer "forever" in order to deallocate resources. driver.declineOffer(offer.id(), filtersForever); response = process::http::post( master.get()->pid, "unreserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, dynamicallyReserved)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); // Summon an offer. EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)); driver.reviveOffers(); AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); offer = offers.get()[0]; EXPECT_TRUE(Resources(offer.resources()).contains( allocatedResources(unreserved, frameworkInfo.roles(0)))); driver.stop(); driver.join(); } // This tests that an operator can reserve offered resources by rescinding the // outstanding offers. TEST_F(ReservationEndpointsTest, ReserveOfferedResources) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get()); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); FrameworkInfo frameworkInfo = createFrameworkInfo(); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources dynamicallyReserved = unreserved.pushReservation(createDynamicReservationInfo( frameworkInfo.roles(0), DEFAULT_CREDENTIAL.principal())); MockScheduler sched; MesosSchedulerDriver driver( &sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL); Future<vector<Offer>> offers; EXPECT_CALL(sched, registered(&driver, _, _)); EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)); driver.start(); AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); Offer offer = offers.get()[0]; EXPECT_TRUE(Resources(offer.resources()).contains( allocatedResources(unreserved, frameworkInfo.roles(0)))); // Expect an offer to be rescinded! EXPECT_CALL(sched, offerRescinded(_, _)); Future<Response> response = process::http::post( master.get()->pid, "reserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, dynamicallyReserved)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); // Summon an offer. EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)); driver.reviveOffers(); AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); offer = offers.get()[0]; EXPECT_TRUE(Resources(offer.resources()).contains( allocatedResources(dynamicallyReserved, frameworkInfo.roles(0)))); driver.stop(); driver.join(); } // This tests that an operator can unreserve offered resources by rescinding the // outstanding offers. TEST_F(ReservationEndpointsTest, UnreserveOfferedResources) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get()); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); FrameworkInfo frameworkInfo = createFrameworkInfo(); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources dynamicallyReserved = unreserved.pushReservation(createDynamicReservationInfo( frameworkInfo.roles(0), DEFAULT_CREDENTIAL.principal())); Future<Response> response = process::http::post( master.get()->pid, "reserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, dynamicallyReserved)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); MockScheduler sched; MesosSchedulerDriver driver( &sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL); Future<vector<Offer>> offers; EXPECT_CALL(sched, registered(&driver, _, _)); EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)); driver.start(); AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); Offer offer = offers.get()[0]; EXPECT_TRUE(Resources(offer.resources()).contains( allocatedResources(dynamicallyReserved, frameworkInfo.roles(0)))); // Expect an offer to be rescinded. EXPECT_CALL(sched, offerRescinded(_, _)); response = process::http::post( master.get()->pid, "unreserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, dynamicallyReserved)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); // Summon an offer. EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)); driver.reviveOffers(); AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); offer = offers.get()[0]; EXPECT_TRUE(Resources(offer.resources()).contains( allocatedResources(unreserved, frameworkInfo.roles(0)))); driver.stop(); driver.join(); } // This tests that an operator can reserve a mix of available and offered // resources by rescinding the outstanding offers. TEST_F(ReservationEndpointsTest, ReserveAvailableAndOfferedResources) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get()); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); FrameworkInfo frameworkInfo = createFrameworkInfo(); Resources available = Resources::parse("cpus:1;mem:128").get(); Resources offered = Resources::parse("mem:384").get(); Resources total = available + offered; Resources dynamicallyReserved = total.pushReservation(createDynamicReservationInfo( frameworkInfo.roles(0), DEFAULT_CREDENTIAL.principal())); MockScheduler sched; MesosSchedulerDriver driver( &sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL); // Expect one TASK_STARTING and one TASK_RUNNING update EXPECT_CALL(sched, registered(&driver, _, _)); Future<vector<Offer>> offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)); driver.start(); // We want to get the cluster in a state where 'available' resources are left // in the allocator, and 'offered' resources are offered to the framework. // To achieve this state, we perform the following steps: // (1) Receive an offer containing 'total' = 'available' + 'offered'. // (2) Launch a "forever-running" task with 'available' resources. // (3) Summon an offer containing 'offered'. // (4) Kill the task, which recovers 'available' resources. // Expect to receive 'available + offered' resources. AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); Offer offer = offers.get()[0]; EXPECT_TRUE(Resources(offer.resources()).contains( allocatedResources(available + offered, frameworkInfo.roles(0)))); // Launch a task on the 'available' resources portion of the offer, which // recovers 'offered' resources portion. TaskInfo taskInfo = createTask(offer.slave_id(), available, "sleep 1000"); // Expect a TASK_STARTING and a TASK_RUNNING status. EXPECT_CALL(sched, statusUpdate(_, _)) .WillRepeatedly(Return()); Future<Nothing> _statusUpdateAcknowledgement1 = FUTURE_DISPATCH(_, &Slave::_statusUpdateAcknowledgement); Future<Nothing> _statusUpdateAcknowledgement2 = FUTURE_DISPATCH(_, &Slave::_statusUpdateAcknowledgement); driver.acceptOffers({offer.id()}, {LAUNCH({taskInfo})}); // Wait for update acks. AWAIT_READY(_statusUpdateAcknowledgement1); AWAIT_READY(_statusUpdateAcknowledgement2); // Summon an offer to receive the 'offered' resources. EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.reviveOffers(); AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); offer = offers.get()[0]; EXPECT_TRUE(Resources(offer.resources()).contains( allocatedResources(offered, frameworkInfo.roles(0)))); // Kill the task running on 'available' resources to make it available. Future<TaskStatus> statusUpdate; EXPECT_CALL(sched, statusUpdate(_, _)) .WillOnce(FutureArg<1>(&statusUpdate)); // Send a KillTask message to the master. driver.killTask(taskInfo.task_id()); AWAIT_READY(statusUpdate); ASSERT_EQ(TaskState::TASK_KILLED, statusUpdate->state()); // At this point, we have 'available' resources in the allocator, and // 'offered' resources offered to the framework. // Expect offers to be rescinded and recovered! EXPECT_CALL(sched, offerRescinded(_, _)) .WillRepeatedly(Return()); Future<Response> response = process::http::post( master.get()->pid, "reserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, dynamicallyReserved)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); // Summon an offer. EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)); driver.reviveOffers(); AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); offer = offers.get()[0]; EXPECT_TRUE(Resources(offer.resources()).contains( allocatedResources(dynamicallyReserved, frameworkInfo.roles(0)))); driver.stop(); driver.join(); } // This tests that an operator can unreserve a mix of available and offered // resources by rescinding the outstanding offers. TEST_F(ReservationEndpointsTest, UnreserveAvailableAndOfferedResources) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get()); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); FrameworkInfo frameworkInfo = createFrameworkInfo(); Resources available = Resources::parse("cpus:1;mem:128").get(); available = available.pushReservation(createDynamicReservationInfo( frameworkInfo.roles(0), DEFAULT_CREDENTIAL.principal())); Resources offered = Resources::parse("mem:384").get(); offered = offered.pushReservation(createDynamicReservationInfo( frameworkInfo.roles(0), DEFAULT_CREDENTIAL.principal())); Resources total = available + offered; Resources unreserved = total.toUnreserved(); Future<Response> response = process::http::post( master.get()->pid, "reserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, total)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); MockScheduler sched; MesosSchedulerDriver driver( &sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL); EXPECT_CALL(sched, registered(&driver, _, _)); Future<vector<Offer>> offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); // We want to get the cluster in a state where 'available' resources are left // in the allocator, and 'offered' resources are offered to the framework. // To achieve this state, we perform the following steps: // (1) Receive an offer containing 'total' = 'available' + 'offered'. // (2) Launch a "forever-running" task with 'available' resources. // (3) Summon an offer containing 'offered'. // (4) Kill the task, which recovers 'available' resources. // Expect to receive 'available + offered' resources. AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); Offer offer = offers.get()[0]; EXPECT_TRUE(Resources(offer.resources()).contains( allocatedResources(available + offered, frameworkInfo.roles(0)))); // Launch a task on the 'available' resources portion of the offer, which // recovers 'offered' resources portion. TaskInfo taskInfo = createTask(offer.slave_id(), available, "sleep 1000"); // Expect a TASK_STARTING and a TASK_RUNNING status. EXPECT_CALL(sched, statusUpdate(_, _)) .WillRepeatedly(Return()); Future<Nothing> _statusUpdateAcknowledgement1 = FUTURE_DISPATCH(_, &Slave::_statusUpdateAcknowledgement); Future<Nothing> _statusUpdateAcknowledgement2 = FUTURE_DISPATCH(_, &Slave::_statusUpdateAcknowledgement); driver.acceptOffers({offer.id()}, {LAUNCH({taskInfo})}); // Wait for update acks from TASK_STARTING and TASK_RUNNING. AWAIT_READY(_statusUpdateAcknowledgement1); AWAIT_READY(_statusUpdateAcknowledgement2); // Summon an offer to receive the 'offered' resources. EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)); driver.reviveOffers(); AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); offer = offers.get()[0]; EXPECT_TRUE(Resources(offer.resources()).contains( allocatedResources(offered, frameworkInfo.roles(0)))); // Kill the task running on 'available' resources to make it available. Future<TaskStatus> statusUpdate; EXPECT_CALL(sched, statusUpdate(_, _)) .WillOnce(FutureArg<1>(&statusUpdate)); // Send a KillTask message to the master. driver.killTask(taskInfo.task_id()); AWAIT_READY(statusUpdate); ASSERT_EQ(TaskState::TASK_KILLED, statusUpdate->state()); // At this point, we have 'available' resources in the allocator, and // 'offered' resources offered to the framework. // Expect offers to be rescinded and recovered! EXPECT_CALL(sched, offerRescinded(_, _)) .WillRepeatedly(Return()); response = process::http::post( master.get()->pid, "unreserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, total)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); // Summon an offer. EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)); driver.reviveOffers(); AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); offer = offers.get()[0]; EXPECT_TRUE(Resources(offer.resources()).contains( allocatedResources(unreserved, frameworkInfo.roles(0)))); driver.stop(); driver.join(); } // This tests that attempts to reserve/unreserve labeled resources // behave as expected. TEST_F(ReservationEndpointsTest, LabeledResources) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); slave::Flags slaveFlags = CreateSlaveFlags(); slaveFlags.resources = "cpus:2;mem:1024"; Resources totalSlaveResources = Resources::parse(slaveFlags.resources.get()).get(); Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), slaveFlags); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); FrameworkInfo frameworkInfo = createFrameworkInfo(); Labels labels1; labels1.add_labels()->CopyFrom(createLabel("foo", "bar")); Labels labels2; labels2.add_labels()->CopyFrom(createLabel("foo", "baz")); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources labeledResources1 = unreserved.pushReservation(createDynamicReservationInfo( frameworkInfo.roles(0), DEFAULT_CREDENTIAL.principal(), labels1)); Resources labeledResources2 = unreserved.pushReservation(createDynamicReservationInfo( frameworkInfo.roles(0), DEFAULT_CREDENTIAL.principal(), labels2)); // Make two resource reservations with different labels. Future<Response> response = process::http::post( master.get()->pid, "reserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, labeledResources1)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); response = process::http::post( master.get()->pid, "reserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, labeledResources2)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); MockScheduler sched; MesosSchedulerDriver driver( &sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL); Future<vector<Offer>> offers; EXPECT_CALL(sched, registered(&driver, _, _)); EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)); driver.start(); AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); Offer offer = offers.get()[0]; Resources offeredResources = Resources(offer.resources()); EXPECT_TRUE(offeredResources.contains( allocatedResources(labeledResources1, frameworkInfo.roles(0)))); EXPECT_TRUE(offeredResources.contains( allocatedResources(labeledResources2, frameworkInfo.roles(0)))); // Expect an offer to be rescinded. EXPECT_CALL(sched, offerRescinded(_, _)); // Unreserve one of the labeled reservations. response = process::http::post( master.get()->pid, "unreserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, labeledResources1)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); // Summon an offer. EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)); driver.reviveOffers(); AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); offer = offers.get()[0]; offeredResources = Resources(offer.resources()); EXPECT_FALSE(offeredResources.contains( allocatedResources(totalSlaveResources, frameworkInfo.roles(0)))); EXPECT_TRUE(offeredResources.contains( allocatedResources(unreserved, frameworkInfo.roles(0)))); EXPECT_FALSE(offeredResources.contains( allocatedResources(labeledResources1, frameworkInfo.roles(0)))); EXPECT_TRUE(offeredResources.contains( allocatedResources(labeledResources2, frameworkInfo.roles(0)))); // Now that the first labeled reservation has been unreserved, // attempting to unreserve it again should fail. response = process::http::post( master.get()->pid, "unreserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, labeledResources1)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Conflict().status, response); // Expect an offer to be rescinded. EXPECT_CALL(sched, offerRescinded(_, _)); // Unreserve the other labeled reservation. response = process::http::post( master.get()->pid, "unreserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, labeledResources2)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); // Summon an offer. EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)); driver.reviveOffers(); AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); offer = offers.get()[0]; offeredResources = Resources(offer.resources()); EXPECT_TRUE(offeredResources.contains( allocatedResources(totalSlaveResources, frameworkInfo.roles(0)))); EXPECT_FALSE(offeredResources.contains( allocatedResources(labeledResources1, frameworkInfo.roles(0)))); EXPECT_FALSE(offeredResources.contains( allocatedResources(labeledResources2, frameworkInfo.roles(0)))); driver.stop(); driver.join(); } // This tests that an attempt to reserve or unreserve an invalid resource will // return a Bad Request response. TEST_F(ReservationEndpointsTest, InvalidResource) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get()); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); FrameworkInfo frameworkInfo = createFrameworkInfo(); // This resource is marked for the default "*" role and it also has a // `ReservationInfo`, which is not allowed. Try<Resource> resource = Resources::parse("cpus", "4", "*"); ASSERT_SOME(resource); resource->add_reservations()->CopyFrom( createDynamicReservationInfo("*", DEFAULT_CREDENTIAL.principal())); process::http::Headers headers = createBasicAuthHeaders(DEFAULT_CREDENTIAL); // We construct the body manually here because it's difficult to construct a // `Resources` object that contains an invalid `Resource`, and our helper // function `createRequestBody` accepts `Resources`. string body = strings::format( "slaveId=%s&resources=[%s]", slaveId.value(), JSON::protobuf(resource.get())).get(); { Future<Response> response = process::http::post(master.get()->pid, "reserve", headers, body); AWAIT_EXPECT_RESPONSE_STATUS_EQ(BadRequest().status, response); ASSERT_TRUE(strings::contains( response->body, "Invalid reservation: role \"*\" cannot be reserved")); } { Future<Response> response = process::http::post(master.get()->pid, "unreserve", headers, body); AWAIT_EXPECT_RESPONSE_STATUS_EQ(BadRequest().status, response); ASSERT_TRUE(strings::contains( response->body, "Invalid reservation: role \"*\" cannot be reserved")); } } // This tests that an attempt to reserve/unreserve more resources than available // results in a 'Conflict' HTTP error. TEST_F(ReservationEndpointsTest, InsufficientResources) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get()); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); FrameworkInfo frameworkInfo = createFrameworkInfo(); Resources unreserved = Resources::parse("cpus:4;mem:4096").get(); Resources dynamicallyReserved = unreserved.pushReservation(createDynamicReservationInfo( frameworkInfo.roles(0), DEFAULT_CREDENTIAL.principal())); process::http::Headers headers = createBasicAuthHeaders(DEFAULT_CREDENTIAL); string body = createRequestBody(slaveId, dynamicallyReserved); Future<Response> response = process::http::post(master.get()->pid, "reserve", headers, body); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Conflict().status, response); response = process::http::post(master.get()->pid, "unreserve", headers, body); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Conflict().status, response); } // This tests that an attempt to reserve with no authorization header results in // an 'Unauthorized' HTTP error. TEST_F(ReservationEndpointsTest, NoHeader) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get()); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); FrameworkInfo frameworkInfo = createFrameworkInfo(); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources dynamicallyReserved = unreserved.pushReservation(createDynamicReservationInfo( frameworkInfo.roles(0), DEFAULT_CREDENTIAL.principal())); Future<Response> response = process::http::post( master.get()->pid, "reserve", None(), createRequestBody(slaveId, dynamicallyReserved)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Unauthorized({}).status, response); response = process::http::post( master.get()->pid, "unreserve", None(), createRequestBody(slaveId, dynamicallyReserved)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Unauthorized({}).status, response); } // This tests that an attempt to reserve with bad credentials results in an // 'Unauthorized' HTTP error. TEST_F(ReservationEndpointsTest, BadCredentials) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get()); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); Credential credential; credential.set_principal("bad-principal"); credential.set_secret("bad-secret"); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources dynamicallyReserved = unreserved.pushReservation( createDynamicReservationInfo("role", DEFAULT_CREDENTIAL.principal())); process::http::Headers headers = createBasicAuthHeaders(credential); string body = createRequestBody(slaveId, dynamicallyReserved); Future<Response> response = process::http::post(master.get()->pid, "reserve", headers, body); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Unauthorized({}).status, response); response = process::http::post(master.get()->pid, "unreserve", headers, body); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Unauthorized({}).status, response); } // This tests that correct setup of Reserve/Unreserve ACLs allows // the operator to perform reserve/unreserve operations successfully. TEST_F(ReservationEndpointsTest, GoodReserveAndUnreserveACL) { ACLs acls; // This ACL asserts that the principal of `DEFAULT_CREDENTIAL` // can reserve resources for any role. mesos::ACL::ReserveResources* reserve = acls.add_reserve_resources(); reserve->mutable_principals()->add_values(DEFAULT_CREDENTIAL.principal()); reserve->mutable_roles()->set_type(mesos::ACL::Entity::ANY); // This ACL asserts that the principal of `DEFAULT_CREDENTIAL` // can unreserve its own resources. mesos::ACL::UnreserveResources* unreserve = acls.add_unreserve_resources(); unreserve->mutable_principals()->add_values(DEFAULT_CREDENTIAL.principal()); unreserve->mutable_reserver_principals()->add_values( DEFAULT_CREDENTIAL.principal()); // Create a master. master::Flags masterFlags = CreateMasterFlags(); masterFlags.acls = acls; Try<Owned<cluster::Master>> master = StartMaster(masterFlags); ASSERT_SOME(master); // Create a slave. slave::Flags slaveFlags = CreateSlaveFlags(); slaveFlags.resources = "cpus:1;mem:512"; Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), slaveFlags); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); process::http::Headers headers = createBasicAuthHeaders(DEFAULT_CREDENTIAL); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources dynamicallyReserved = unreserved.pushReservation(createDynamicReservationInfo( createFrameworkInfo().roles(0), DEFAULT_CREDENTIAL.principal())); // Reserve the resources. Future<Response> response = process::http::post( master.get()->pid, "reserve", headers, createRequestBody(slaveId, dynamicallyReserved)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); // Unreserve the resources. response = process::http::post( master.get()->pid, "unreserve", headers, createRequestBody(slaveId, dynamicallyReserved)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); } // This tests that correct setup of `ReserveResources` ACLs allows the operator // to perform reserve operations for multiple roles successfully. TEST_F(ReservationEndpointsTest, GoodReserveACLMultipleRoles) { ACLs acls; // This ACL asserts that the principal of `DEFAULT_CREDENTIAL` // can reserve resources for any role. mesos::ACL::ReserveResources* reserve = acls.add_reserve_resources(); reserve->mutable_principals()->add_values(DEFAULT_CREDENTIAL.principal()); reserve->mutable_roles()->set_type(mesos::ACL::Entity::ANY); // Create a master. master::Flags masterFlags = CreateMasterFlags(); masterFlags.acls = acls; Try<Owned<cluster::Master>> master = StartMaster(masterFlags); ASSERT_SOME(master); // Create a slave. slave::Flags slaveFlags = CreateSlaveFlags(); slaveFlags.resources = "cpus:2;mem:1024"; Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), slaveFlags); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources dynamicallyReserved1 = unreserved.pushReservation(createDynamicReservationInfo( "jedi_master", DEFAULT_CREDENTIAL.principal())); Resources dynamicallyReserved2 = unreserved.pushReservation(createDynamicReservationInfo( "sith_lord", DEFAULT_CREDENTIAL.principal())); Resources dynamicallyReservedMultipleRoles = dynamicallyReserved1 + dynamicallyReserved2; // Reserve the resources. Future<Response> response = process::http::post( master.get()->pid, "reserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, dynamicallyReservedMultipleRoles)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); } // This tests that an incorrect set-up of Reserve ACL disallows the // operator from performing reserve operations. TEST_F(ReservationEndpointsTest, BadReserveACL) { ACLs acls; // This ACL asserts that ANY principal can reserve NONE, // i.e. no principal can reserve resources. mesos::ACL::ReserveResources* reserve = acls.add_reserve_resources(); reserve->mutable_principals()->set_type(mesos::ACL::Entity::ANY); reserve->mutable_roles()->set_type(mesos::ACL::Entity::NONE); // Create a master. master::Flags masterFlags = CreateMasterFlags(); masterFlags.acls = acls; Try<Owned<cluster::Master>> master = StartMaster(masterFlags); ASSERT_SOME(master); // Create a slave. slave::Flags slaveFlags = CreateSlaveFlags(); slaveFlags.resources = "cpus:1;mem:512"; Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), slaveFlags); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); process::http::Headers headers = createBasicAuthHeaders(DEFAULT_CREDENTIAL); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources dynamicallyReserved = unreserved.pushReservation(createDynamicReservationInfo( createFrameworkInfo().roles(0), DEFAULT_CREDENTIAL.principal())); // Attempt to reserve the resources. Future<Response> response = process::http::post( master.get()->pid, "reserve", headers, createRequestBody(slaveId, dynamicallyReserved)); // Expect a failed authorization. AWAIT_EXPECT_RESPONSE_STATUS_EQ(Forbidden().status, response); } // This tests that correct set-up of Unreserve ACLs disallows the // operator from performing unreserve operations. TEST_F(ReservationEndpointsTest, BadUnreserveACL) { ACLs acls; // This ACL asserts that ANY principal can unreserve NONE, // i.e. no principals can unreserve anything. mesos::ACL::UnreserveResources* unreserve = acls.add_unreserve_resources(); unreserve->mutable_principals()->set_type(mesos::ACL::Entity::ANY); unreserve->mutable_reserver_principals()->set_type(mesos::ACL::Entity::NONE); // Create a master. master::Flags masterFlags = CreateMasterFlags(); masterFlags.acls = acls; Try<Owned<cluster::Master>> master = StartMaster(masterFlags); ASSERT_SOME(master); // Create a slave. slave::Flags slaveFlags = CreateSlaveFlags(); slaveFlags.resources = "cpus:1;mem:512"; Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), slaveFlags); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); process::http::Headers headers = createBasicAuthHeaders(DEFAULT_CREDENTIAL); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources dynamicallyReserved = unreserved.pushReservation(createDynamicReservationInfo( createFrameworkInfo().roles(0), DEFAULT_CREDENTIAL.principal())); // Reserve the resources. Future<Response> response = process::http::post( master.get()->pid, "reserve", headers, createRequestBody(slaveId, dynamicallyReserved)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); // Attempt to unreserve the resources. response = process::http::post( master.get()->pid, "unreserve", headers, createRequestBody(slaveId, dynamicallyReserved)); // Expect a failed authorization. AWAIT_EXPECT_RESPONSE_STATUS_EQ(Forbidden().status, response); } // Tests that reserve operations will fail if multiple roles are included in a // request, while the principal attempting the reservation is not authorized to // reserve for one of them. TEST_F(ReservationEndpointsTest, BadReserveACLMultipleRoles) { const string AUTHORIZED_ROLE = "panda"; const string UNAUTHORIZED_ROLE = "giraffe"; ACLs acls; // This ACL asserts that the principal of `DEFAULT_CREDENTIAL` // can reserve resources for `AUTHORIZED_ROLE`. mesos::ACL::ReserveResources* reserve1 = acls.add_reserve_resources(); reserve1->mutable_principals()->add_values(DEFAULT_CREDENTIAL.principal()); reserve1->mutable_roles()->add_values(AUTHORIZED_ROLE); // This ACL asserts that the principal of `DEFAULT_CREDENTIAL` // cannot reserve resources for any other role. mesos::ACL::ReserveResources* reserve2 = acls.add_reserve_resources(); reserve2->mutable_principals()->add_values(DEFAULT_CREDENTIAL.principal()); reserve2->mutable_roles()->set_type(mesos::ACL::Entity::NONE); // Create a master. master::Flags masterFlags = CreateMasterFlags(); masterFlags.acls = acls; Try<Owned<cluster::Master>> master = StartMaster(masterFlags); ASSERT_SOME(master); // Create a slave. slave::Flags slaveFlags = CreateSlaveFlags(); slaveFlags.resources = "cpus:2;mem:1024"; Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), slaveFlags); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources dynamicallyReserved1 = unreserved.pushReservation(createDynamicReservationInfo( AUTHORIZED_ROLE, DEFAULT_CREDENTIAL.principal())); Resources dynamicallyReserved2 = unreserved.pushReservation(createDynamicReservationInfo( UNAUTHORIZED_ROLE, DEFAULT_CREDENTIAL.principal())); Resources dynamicallyReservedMultipleRoles = dynamicallyReserved1 + dynamicallyReserved2; // Reserve the resources. Future<Response> response = process::http::post( master.get()->pid, "reserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, dynamicallyReservedMultipleRoles)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Forbidden().status, response); } // This tests that an attempt to reserve with no 'slaveId' results in a // 'BadRequest' HTTP error. TEST_F(ReservationEndpointsTest, NoSlaveId) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get()); ASSERT_SOME(slave); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources dynamicallyReserved = unreserved.pushReservation( createDynamicReservationInfo("role", DEFAULT_CREDENTIAL.principal())); process::http::Headers headers = createBasicAuthHeaders(DEFAULT_CREDENTIAL); string body = "resources=" + stringify(JSON::protobuf( static_cast<const RepeatedPtrField<Resource>&>(dynamicallyReserved))); Future<Response> response = process::http::post(master.get()->pid, "reserve", headers, body); AWAIT_EXPECT_RESPONSE_STATUS_EQ(BadRequest().status, response); response = process::http::post(master.get()->pid, "unreserve", headers, body); AWAIT_EXPECT_RESPONSE_STATUS_EQ(BadRequest().status, response); } // This tests that an attempt to reserve with no 'resources' results in a // 'BadRequest' HTTP error. TEST_F(ReservationEndpointsTest, NoResources) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get()); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); process::http::Headers headers = createBasicAuthHeaders(DEFAULT_CREDENTIAL); string body = "slaveId=" + slaveId.value(); Future<Response> response = process::http::post(master.get()->pid, "reserve", headers, body); AWAIT_EXPECT_RESPONSE_STATUS_EQ(BadRequest().status, response); response = process::http::post(master.get()->pid, "unreserve", headers, body); AWAIT_EXPECT_RESPONSE_STATUS_EQ(BadRequest().status, response); } // This tests that an attempt to reserve with a non-matching principal results // in a 'BadRequest' HTTP error. TEST_F(ReservationEndpointsTest, NonMatchingPrincipal) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get()); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources dynamicallyReserved = unreserved.pushReservation( createDynamicReservationInfo("role", "badPrincipal")); Future<Response> response = process::http::post( master.get()->pid, "reserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, dynamicallyReserved)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(BadRequest().status, response); } // Tests the situation where framework and HTTP authentication are disabled // and no ACLs are set in the master. TEST_F(ReservationEndpointsTest, ReserveAndUnreserveNoAuthentication) { FrameworkInfo frameworkInfo = createFrameworkInfo(); // Create a master. master::Flags masterFlags = CreateMasterFlags(); masterFlags.authenticate_frameworks = false; masterFlags.authenticate_http_readwrite = false; Try<Owned<cluster::Master>> master = StartMaster(masterFlags); ASSERT_SOME(master); // Create an agent. slave::Flags slaveFlags = CreateSlaveFlags(); slaveFlags.resources = "cpus:1;mem:512"; Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), slaveFlags); ASSERT_SOME(slave); // Advance the clock to trigger agent registration. Clock::advance(slaveFlags.registration_backoff_factor); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources dynamicallyReservedWithNoPrincipal = unreserved.pushReservation( createDynamicReservationInfo(frameworkInfo.roles(0))); // Try a reservation with no principal in `ReservationInfo` and no // authentication headers. Future<Response> response = process::http::post( master.get()->pid, "reserve", None(), createRequestBody(slaveId, dynamicallyReservedWithNoPrincipal)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); // Try to unreserve with no principal in `ReservationInfo` and no // authentication headers. response = process::http::post( master.get()->pid, "unreserve", None(), createRequestBody(slaveId, dynamicallyReservedWithNoPrincipal)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); Resources dynamicallyReservedWithPrincipal = unreserved.pushReservation(createDynamicReservationInfo( frameworkInfo.roles(0), DEFAULT_CREDENTIAL.principal())); // Try a reservation with a principal in `ReservationInfo` and no // authentication headers. response = process::http::post( master.get()->pid, "reserve", None(), createRequestBody(slaveId, dynamicallyReservedWithPrincipal)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); // Try to unreserve with a principal in `ReservationInfo` and no // authentication headers. response = process::http::post( master.get()->pid, "unreserve", None(), createRequestBody(slaveId, dynamicallyReservedWithPrincipal)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); } // This test checks that two resource reservations for the same role // at the same agent that use different principals are not "merged" // into a single reserved resource. TEST_F(ReservationEndpointsTest, DifferentPrincipalsSameRole) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); slave::Flags slaveFlags = CreateSlaveFlags(); slaveFlags.resources = "cpus:2;mem:1024"; Future<SlaveRegisteredMessage> slaveRegisteredMessage = FUTURE_PROTOBUF(SlaveRegisteredMessage(), master.get()->pid, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> slave = StartSlave(detector.get(), slaveFlags); ASSERT_SOME(slave); AWAIT_READY(slaveRegisteredMessage); const SlaveID& slaveId = slaveRegisteredMessage->slave_id(); FrameworkInfo frameworkInfo = createFrameworkInfo(); Resources unreserved = Resources::parse("cpus:1;mem:512").get(); Resources dynamicallyReserved1 = unreserved.pushReservation(createDynamicReservationInfo( frameworkInfo.roles(0), DEFAULT_CREDENTIAL.principal())); Resources dynamicallyReserved2 = unreserved.pushReservation(createDynamicReservationInfo( frameworkInfo.roles(0), DEFAULT_CREDENTIAL_2.principal())); Future<Response> response = process::http::post( master.get()->pid, "reserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, dynamicallyReserved1)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); response = process::http::post( master.get()->pid, "reserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL_2), createRequestBody(slaveId, dynamicallyReserved2)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); MockScheduler sched; MesosSchedulerDriver driver( &sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL); Future<vector<Offer>> offers; EXPECT_CALL(sched, registered(&driver, _, _)); EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)); driver.start(); AWAIT_READY(offers); ASSERT_EQ(1u, offers->size()); Offer offer = offers.get()[0]; Resources resources = Resources(offer.resources()); EXPECT_TRUE(resources.contains( allocatedResources(dynamicallyReserved1, frameworkInfo.roles(0)))); EXPECT_TRUE(resources.contains( allocatedResources(dynamicallyReserved2, frameworkInfo.roles(0)))); driver.stop(); driver.join(); } // This test verifies that unreserved resources, dynamic reservations, allocated // resources per each role are reflected in the agent's "/state" endpoint. TEST_F(ReservationEndpointsTest, AgentStateEndpointResources) { Try<Owned<cluster::Master>> master = StartMaster(); ASSERT_SOME(master); slave::Flags slaveFlags = CreateSlaveFlags(); slaveFlags.resources = "cpus:4;mem:2048;disk:4096;cpus(role):2;mem(role):512"; Future<UpdateSlaveMessage> updateSlaveMessage = FUTURE_PROTOBUF(UpdateSlaveMessage(), _, _); Owned<MasterDetector> detector = master.get()->createDetector(); Try<Owned<cluster::Slave>> agent = StartSlave(detector.get(), slaveFlags); ASSERT_SOME(agent); AWAIT_READY(updateSlaveMessage); const SlaveID& slaveId = updateSlaveMessage->slave_id(); Resources unreserved = Resources::parse("cpus:1;mem:512;disk:1024").get(); Resources dynamicallyReserved = unreserved.pushReservation( createDynamicReservationInfo("role1", DEFAULT_CREDENTIAL.principal())); Future<UpdateOperationStatusMessage> updateOperationStatusMessage = FUTURE_PROTOBUF(UpdateOperationStatusMessage(), _, _); { Future<Response> response = process::http::post( master.get()->pid, "reserve", createBasicAuthHeaders(DEFAULT_CREDENTIAL), createRequestBody(slaveId, dynamicallyReserved)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(Accepted().status, response); } // Now verify the reservations from the agent's /state endpoint. We wait for // the agent to receive and process the `ApplyOperationMessage` and respond // with an initial operation status update. AWAIT_READY(updateOperationStatusMessage); EXPECT_TRUE(metricEquals("master/operations/finished", 1)); // Make sure CheckpointResourcesMessage handling is completed // before proceeding. Clock::pause(); Clock::settle(); Clock::resume(); FrameworkInfo frameworkInfo = createFrameworkInfo(); MockScheduler sched; MesosSchedulerDriver driver( &sched, frameworkInfo, master.get()->pid, DEFAULT_CREDENTIAL); EXPECT_CALL(sched, registered(&driver, _, _)); Future<vector<Offer>> offers; EXPECT_CALL(sched, resourceOffers(&driver, _)) .WillOnce(FutureArg<1>(&offers)) .WillRepeatedly(Return()); // Ignore subsequent offers. driver.start(); AWAIT_READY(offers); ASSERT_FALSE(offers->empty()); Offer offer = offers.get()[0]; Future<TaskStatus> statusStarting; Future<TaskStatus> statusRunning; EXPECT_CALL(sched, statusUpdate(_, _)) .WillOnce(FutureArg<1>(&statusStarting)) .WillOnce(FutureArg<1>(&statusRunning)); Resources taskResources = Resources::parse( "cpus(role):2;mem(role):512;cpus:2;mem:1024").get(); TaskInfo task = createTask(offer.slave_id(), taskResources, "sleep 1000"); driver.acceptOffers({offer.id()}, {LAUNCH({task})}); AWAIT_READY(statusStarting); ASSERT_EQ(TASK_STARTING, statusStarting->state()); AWAIT_READY(statusRunning); ASSERT_EQ(TASK_RUNNING, statusRunning->state()); Future<Response> response = process::http::get( agent.get()->pid, "state", None(), createBasicAuthHeaders(DEFAULT_CREDENTIAL)); AWAIT_EXPECT_RESPONSE_STATUS_EQ(OK().status, response); Try<JSON::Object> parse = JSON::parse<JSON::Object>(response->body); ASSERT_SOME(parse); JSON::Object state = parse.get(); { JSON::Value expected = JSON::parse( R"~( { "role": { "cpus": 2.0, "disk": 0.0, "gpus": 0.0, "mem": 512.0 }, "role1": { "cpus": 1.0, "disk": 1024.0, "gpus": 0.0, "mem": 512.0 } })~").get(); EXPECT_EQ(expected, state.values["reserved_resources"]); } { JSON::Value expected = JSON::parse( R"~( { "role": { "cpus": 2.0, "disk": 0.0, "gpus": 0.0, "mem": 512.0 } })~").get(); EXPECT_EQ(expected, state.values["reserved_resources_allocated"]); } { JSON::Value expected = JSON::parse( R"~( { "cpus": 3.0, "disk": 3072.0, "gpus": 0.0, "mem": 1536.0, "ports": "[31000-32000]" })~").get(); EXPECT_EQ(expected, state.values["unreserved_resources"]); } { // NOTE: executor consumes extra 0.1 cpus and 32.0 mem JSON::Value expected = JSON::parse( R"~( { "cpus": 2.1, "disk": 0.0, "gpus": 0.0, "mem": 1056.0 })~").get(); EXPECT_EQ(expected, state.values["unreserved_resources_allocated"]); } { JSON::Value expected = JSON::parse(strings::format( R"~( { "role": [ { "name": "cpus", "type": "SCALAR", "scalar": { "value": 2.0 }, "role": "role", "reservations": [ { "role": "role", "type": "STATIC" } ] }, { "name": "mem", "type": "SCALAR", "scalar": { "value": 512.0 }, "role": "role", "reservations": [ { "role": "role", "type": "STATIC" } ] } ], "role1": [ { "name": "cpus", "type": "SCALAR", "scalar": { "value": 1.0 }, "role": "role1", "reservation": { "principal": "%s" }, "reservations": [ { "principal": "%s", "role": "role1", "type": "DYNAMIC" } ] }, { "name": "mem", "type": "SCALAR", "scalar": { "value": 512.0 }, "role": "role1", "reservation": { "principal": "%s" }, "reservations": [ { "principal": "%s", "role": "role1", "type": "DYNAMIC" } ] }, { "name": "disk", "type": "SCALAR", "scalar": { "value": 1024.0 }, "role": "role1", "reservation": { "principal": "%s" }, "reservations": [ { "principal": "%s", "role": "role1", "type": "DYNAMIC" } ] } ] })~", DEFAULT_CREDENTIAL.principal(), // Three occurrences of '%s' above. DEFAULT_CREDENTIAL.principal(), DEFAULT_CREDENTIAL.principal(), DEFAULT_CREDENTIAL.principal(), DEFAULT_CREDENTIAL.principal(), DEFAULT_CREDENTIAL.principal()).get()).get(); EXPECT_EQ(expected, state.values["reserved_resources_full"]); } { JSON::Value expected = JSON::parse( R"~( [ { "name": "cpus", "role": "*", "scalar": { "value": 3.0 }, "type": "SCALAR" }, { "name": "mem", "role": "*", "scalar": { "value": 1536.0 }, "type": "SCALAR" }, { "name": "disk", "role": "*", "scalar": { "value": 3072.0 }, "type": "SCALAR" }, { "name": "ports", "role": "*", "ranges": { "range": [ { "begin": 31000, "end": 32000 } ] }, "type": "RANGES" } ])~").get(); EXPECT_EQ(expected, state.values["unreserved_resources_full"]); } driver.stop(); driver.join(); } } // namespace tests { } // namespace internal { } // namespace mesos {
31.945652
80
0.702093
[ "object", "vector" ]
c8e7c284ffd7fd1be94e663068fbeed5d683d7f2
18,325
cpp
C++
glib-adv/yahoodm.cpp
ksemer/snap
0084126c30ad49a4437bc8ea30be78484f8c58d7
[ "BSD-3-Clause" ]
1,805
2015-01-06T20:01:35.000Z
2022-03-29T16:12:51.000Z
glib-adv/yahoodm.cpp
lizhaoqing/snap
907c34aac6bcddc7c2f8efb64be76e87dd7e4ea5
[ "BSD-3-Clause" ]
168
2015-01-07T22:57:29.000Z
2022-03-15T01:20:24.000Z
glib-adv/yahoodm.cpp
lizhaoqing/snap
907c34aac6bcddc7c2f8efb64be76e87dd7e4ea5
[ "BSD-3-Clause" ]
768
2015-01-09T02:28:45.000Z
2022-03-30T00:53:46.000Z
///////////////////////////////////////////////// // Includes #include "yahoodm.h" ///////////////////////////////////////////////// // Yahoo-Table TYTb::TYTb(const PYBs& _YBs, const PYDsBs& _YDsBs): YBs(_YBs), YDsBs(_YDsBs), VarNToWordIdV(YBs->GetWords()), WordIdToVarNV(YBs->GetMxWordIds()), TupNToDocIdV(YBs->GetDocs()), DocIdToTupNV(YBs->GetMxDocIds()){ int WordId=YBs->FFirstWordId(); int VarN=0-1; while (YBs->FNextWordId(WordId)){VarN++; VarNToWordIdV[VarN]=WordId; WordIdToVarNV[WordId]=VarN;} int DocId=YBs->FFirstDocId(); int TupN=0-1; while (YBs->FNextDocId(DocId)){TupN++; TupNToDocIdV[TupN]=DocId; DocIdToTupNV[DocId]=TupN;} } TTbVal TYTb::GetVal(const int& TupN, const int& VarN){ int DocId=TupNToDocIdV[TupN]; int WordId=VarNToWordIdV[VarN]; double WordFq; if (YDsBs->GetWordDs(DocId)->IsWordId(WordId, WordFq)){return WordFq;} else {return double(0);} } ///////////////////////////////////////////////// // Yahoo-Domain-Distribution TYDmDs::TYDmDs( const bool& _DoPriorDmDs, const int& ClassN, const int& _YNegDsType, const int& _YPriorType, const PYBs& _YBs, const PYDsBs& _YDsBs, const PDmHd& _DmHd): DoPriorDmDs(_DoPriorDmDs), YNegDsType(_YNegDsType), YPriorType(_YPriorType), YBs(_YBs), YDsBs(_YDsBs), DmHd(_DmHd), NegWordDs(), PosWordDs(), CValDs(), NegCValPrb(), PosCValPrb(){ NegWordDs=GetNegWordDs(YNegDsType, YBs, YDsBs); PosWordDs=YDsBs->GetWordDs(ClassN); CValDs=GetPriorValDs(YPriorType, NegWordDs, PosWordDs); NegCValPrb=CValDs->GetPrb_RelFq(TTbVal::NegVal); PosCValPrb=CValDs->GetPrb_RelFq(TTbVal::PosVal); } double TYDmDs::GetSumW(){ return CValDs->GetSumW(); } PTbValDs TYDmDs::GetCDs(){ return CValDs; } PTbValDs TYDmDs::GetAVDs(const int& AttrN){ if (DoPriorDmDs){ return TTbValDs::GetBoolValDs(-1, NegWordDs->GetWordPrb(AttrN)); } else { return TTbValDs::GetBoolValDs(-1, NegCValPrb*NegWordDs->GetWordPrb(AttrN)+ PosCValPrb*PosWordDs->GetWordPrb(AttrN)); } } PTbValDs TYDmDs::GetCAVDs(const TTbVal& CVal, const int& AttrN){ if (DoPriorDmDs){ return TTbValDs::GetBoolValDs(-1, NegWordDs->GetWordPrb(AttrN)); } else { if (CVal==TTbVal::NegVal){ return TTbValDs::GetBoolValDs(-1, NegWordDs->GetWordPrb(AttrN)); } else if (CVal==TTbVal::PosVal){ return TTbValDs::GetBoolValDs(-1, PosWordDs->GetWordPrb(AttrN)); } else { Fail; return NULL; } } } PYWordDs TYDmDs::GetNegWordDs( const int& YNegDsType, const PYBs& YBs, const PYDsBs& YDsBs){ PYWordDs NegWordDs; switch (TYNegDsType(YNegDsType)){ case yndtEmpty: NegWordDs=PYWordDs(new TYWordDs(0, 0, 0)); break; case yndtRoot: NegWordDs=YDsBs->GetWordDs(YBs->GetRootDocId()); break; case yndtAll: NegWordDs=YDsBs->GetAllWordDs(); break; default: Fail; } return NegWordDs; } PTbValDs TYDmDs::GetPriorValDs(const int& YPriorType, const PYWordDs& NegWordDs, const PYWordDs& PosWordDs){ double PosW; double AllW; switch (TYPriorType(YPriorType)){ case yptWords: PosW=PosWordDs->GetSumWordFq(); AllW=NegWordDs->GetSumWordFq(); break; case yptSects: PosW=PosWordDs->GetSects(); AllW=NegWordDs->GetSects(); break; case yptDocs: PosW=PosWordDs->GetDocs(); AllW=NegWordDs->GetDocs(); break; default: Fail; } return TTbValDs::GetBoolValDs(AllW, PosW); } TStr TYDmDs::GetYNegDsTypeStr(const TYNegDsType& YNegDsType){ switch (YNegDsType){ case yndtEmpty: return "Empty"; case yndtRoot: return "Root"; case yndtAll: return "All"; default: Fail; return TStr(); } } TStr TYDmDs::GetYPriorTypeStr(const TYPriorType& YPriorType){ switch (YPriorType){ case yptWords: return "Words"; case yptSects: return "Sects"; case yptDocs: return "Docs"; default: Fail; return TStr(); } } ///////////////////////////////////////////////// // Yahoo-Feature-Selection TYFSelBs::TYFSelBs( const TYFSelType& FSelType, const double& FSels, const bool& FSelPosWords, const PAttrEst& AttrEst, const TYNegDsType& _YNegDsType, const TYPriorType& YPriorType, const PYBs& YBs, const PYDsBs& YDsBs, const PNotify& Notify): YNegDsType(_YNegDsType), DocIdToWordIdEstVV(YBs->GetDocs()){ TNotify::OnNotify(Notify, ntInfo, "Start Feature Selection"); PDmHd DmHd=new TYDmHd(YBs, YDsBs); PYWordDs NegWordDs=TYDmDs::GetNegWordDs(YNegDsType, YBs, YDsBs); PTbValSplit BoolValSplit=TTbValSplit::GetBoolValSplit(); int DocId=YBs->FFirstDocId(); int DocIds=0; while (YBs->FNextDocId(DocId)){ PYWordDs PosWordDs=YDsBs->GetWordDs(DocId); DocIds++; int SelWordIds; switch (FSelType){ case yfstFix: SelWordIds=int(FSels); break; case yfstPosPrc: SelWordIds=int(FSels*double(PosWordDs->GetWordIds())); break; case yfstUnionPrc:{ PYWordDs UnionWordDs=TYWordDs::GetMerged(PosWordDs, NegWordDs, 1, 1); SelWordIds=int(FSels*double(UnionWordDs->GetWordIds())); break;} default: Fail; SelWordIds=0; } if (SelWordIds<=0){SelWordIds=1;} PDmDs DmDs=PDmDs(new TYDmDs( false, DocId, YNegDsType, YPriorType, YBs, YDsBs, DmHd)); PDmDs PriorDmDs=PDmDs(new TYDmDs( true, DocId, yndtAll, yptDocs, YBs, YDsBs, DmHd)); PYWordDs WordDs; PYWordDs TrvWordDs; TIntH SelWordIdH(SelWordIds); TFltIntKdV WordEstIdKdV(SelWordIds, 0); for (int CDsc=0; CDsc<TTbVal::BoolVals; CDsc++){ switch (CDsc){ case 0: WordDs=NegWordDs; break; case 1: WordDs=PosWordDs; break; default: Fail; } if (FSelPosWords){TrvWordDs=PosWordDs;} else {TrvWordDs=WordDs;} int WordIdN=TrvWordDs->FFirstWordId(); int WordId; while (TrvWordDs->FNextWordId(WordIdN, WordId)){ if (SelWordIdH.IsKey(WordId)){continue;} double WordEst; if (AttrEst.Empty()){ // Shortcut: Odds-Ratio double PriorSumW=YBs->GetDocs(); // double PriorSumW=PosWordDs->GetDocs()+NegWordDs->GetDocs(); IAssert(PriorSumW>0); double S1C0Prb=NegWordDs->GetWordPrb(WordId); double S1C1Prb=PosWordDs->GetWordPrb(WordId); if (S1C0Prb==0){S1C0Prb=1/sqr(PriorSumW);} if (S1C0Prb==1){S1C0Prb=1-(1/sqr(PriorSumW));} double OddsS1C0=S1C0Prb/(1-S1C0Prb); if (S1C1Prb==0){S1C1Prb=1/sqr(PriorSumW);} if (S1C1Prb==1){S1C1Prb=1-(1/sqr(PriorSumW));} double OddsS1C1=S1C1Prb/(1-S1C1Prb); WordEst=log(OddsS1C1/OddsS1C0); } else { WordEst=AttrEst->GetAttrQ(WordId, BoolValSplit, DmDs, PriorDmDs); } WordEstIdKdV.AddSorted(TFltIntKd(WordEst, WordId), false, SelWordIds); SelWordIdH.AddKey(WordId); } } TIntFltKdV& WordIdEstKdV=DocIdToWordIdEstVV[DocId]; WordIdEstKdV.Gen(WordEstIdKdV.Len(), 0); for (int WordIdN=0; WordIdN<WordEstIdKdV.Len(); WordIdN++){ double WordEst=WordEstIdKdV[WordIdN].Key; int WordId=WordEstIdKdV[WordIdN].Dat; WordIdEstKdV.Add(TIntFltKd(WordId, WordEst)); } WordIdEstKdV.Sort(); if (DocIds%100==0){ TNotify::OnNotify(Notify, ntInfo, TStr("...")+TInt::GetStr(DocIds)+" Selections.");} } TNotify::OnNotify(Notify, ntInfo, TStr("Feature Selection Finished (")+ TInt::GetStr(DocIds)+")."); } void TYFSelBs::GetBestWordIdV( const int& DocId, const double& EstExp, const double& SumEstPrb, const PYWordDs& IntrsWordDs, TIntV& BestWordIdV){ TIntFltKdV& WordIdEstKdV=DocIdToWordIdEstVV[DocId]; TFltIntKdV WordEstIdKdV(WordIdEstKdV.Len(), 0); double MnWordEst=TFlt::Mx; for (int WordIdN=0; WordIdN<WordIdEstKdV.Len(); WordIdN++){ int WordId=WordIdEstKdV[WordIdN].Key; double WordEst=pow(WordIdEstKdV[WordIdN].Dat, EstExp); if (IntrsWordDs->IsWordId(WordId)){ WordEstIdKdV.Add(TFltIntKd(WordEst, WordId)); MnWordEst=TFlt::GetMn(WordEst, MnWordEst); } } double SumWordEst=0; {for (int WordIdN=0; WordIdN<WordEstIdKdV.Len(); WordIdN++){ SumWordEst+=(WordEstIdKdV[WordIdN].Key-=MnWordEst);}} WordEstIdKdV.Sort(false); {BestWordIdV.Gen(WordEstIdKdV.Len(), 0); SumWordEst*=SumEstPrb; int WordIdN=0; while ((SumWordEst>=0)&&(WordIdN<WordEstIdKdV.Len())){ double WordEst=WordEstIdKdV[WordIdN].Key; int WordId=WordEstIdKdV[WordIdN].Dat; SumWordEst-=WordEst; BestWordIdV.Add(WordId); WordIdN++; }} } void TYFSelBs::SaveTxt( const PSOut& SOut, const PYBs& YBs, const PYDsBs& YDsBs){ PYWordDs NegWordDs=TYDmDs::GetNegWordDs(YNegDsType, YBs, YDsBs); TOLx Lx(SOut, TFSet()|oloFrcEoln|oloSigNum); for (int DocId=0; DocId<DocIdToWordIdEstVV.Len(); DocId++){ TIntFltKdV& WordIdEstKdV=DocIdToWordIdEstVV[DocId]; TFltIntKdV WordEstIdKdV(WordIdEstKdV.Len(), 0); for (int WordIdN=0; WordIdN<WordIdEstKdV.Len(); WordIdN++){ int WordId=WordIdEstKdV[WordIdN].Key; double WordEst=WordIdEstKdV[WordIdN].Dat; WordEstIdKdV.Add(TFltIntKd(WordEst, WordId)); } WordEstIdKdV.Sort(false); Lx.PutVarStr("UrlStr", YBs->GetDocUrlStr(DocId)); Lx.PutVarInt("DocId", DocId); PYWordDs WordDs=YDsBs->GetWordDs(DocId); Lx.PutVar("WordIdEstKdV", true, true); {for (int WordIdN=0; WordIdN<WordEstIdKdV.Len(); WordIdN++){ double WordEst=WordEstIdKdV[WordIdN].Key; int WordId=WordEstIdKdV[WordIdN].Dat; TStr WordStr=YBs->GetWordStr(WordId); double PosWordPrb=WordDs->GetWordPrb(WordId); double NegWordPrb=NegWordDs->GetWordPrb(WordId); Lx.PutQStr(WordStr); Lx.PutTab(); Lx.PutFlt(WordEst); Lx.PutIndent(1); Lx.PutSym(syLBracket); Lx.PutFlt(PosWordPrb); Lx.PutFlt(NegWordPrb); Lx.PutSym(syRBracket); Lx.PutLn(); }} Lx.PutSym(syRBracket); Lx.PutLn(); } } TStr TYFSelBs::GetYFSelTypeStr(const TYFSelType& YFSelType){ switch (YFSelType){ case yfstFix: return "Fix"; case yfstPosPrc: return "PosPrc"; case yfstUnionPrc: return "NegPrc"; default: Fail; return TStr(); } } ///////////////////////////////////////////////// // Yahoo-Inverted-Index TYInvIx::TYInvIx( const double& EstExp, const double& SumEstPrb, const PYBs& YBs, const PYDsBs& YDsBs, const PYFSelBs& YFSelBs, const PNotify& Notify): WordIdToFirstDocIdNH(YBs->GetWords()/2), DocIdVHeap(), AllDocIdV(YBs->GetDocs(), 0){ TNotify::OnNotify(Notify, ntInfo, "Start Creating Inverted Index"); TIntPrV WordIdDocIdPrV(YBs->GetDocs(), 0); TIntV BestWordIdV; int DocId=YBs->FFirstDocId(); while (YBs->FNextDocId(DocId)){ AllDocIdV.Add(DocId); PYWordDs PosWordDs=YDsBs->GetWordDs(DocId); YFSelBs->GetBestWordIdV(DocId, EstExp, SumEstPrb, PosWordDs, BestWordIdV); for (int WordIdN=0; WordIdN<BestWordIdV.Len(); WordIdN++){ int WordId=BestWordIdV[WordIdN]; WordIdDocIdPrV.Add(TIntPr(WordId, DocId)); } } WordIdDocIdPrV.Sort(); DocIdVHeap.Gen(WordIdDocIdPrV.Len()+YBs->GetDocs(), 0); int PrevWordId=-1; for (int WordIdN=0; WordIdN<WordIdDocIdPrV.Len(); WordIdN++){ int WordId=WordIdDocIdPrV[WordIdN].Val1; int DocId=WordIdDocIdPrV[WordIdN].Val2; if (PrevWordId!=WordId){ if (PrevWordId!=-1){DocIdVHeap.Add(TInt(-1));} PrevWordId=WordId; WordIdToFirstDocIdNH.AddDat(TInt(WordId), TInt(DocIdVHeap.Len())); } DocIdVHeap.Add(DocId); } DocIdVHeap.Add(TInt(-1)); TNotify::OnNotify(Notify, ntInfo, "End Creating Inverted Index"); } void TYInvIx::GetDocIdV( const PYWordDs& WordDs, const int& MnDocFq, TIntV& DocIdV){ IAssert(MnDocFq>=0); if (MnDocFq==0){ DocIdV=AllDocIdV; } else { TIntIntH DocIdFqH(100); int MxDocFq=0; int WordIdN=WordDs->FFirstWordId(); int WordId; double WordFq; while (WordDs->FNextWordId(WordIdN, WordId, WordFq)){ if (WordIdToFirstDocIdNH.IsKey(WordId)){ int DocIdN=FFirstDocId(WordId); int DocId; while (FNextWordId(DocIdN, DocId)){ DocIdFqH.AddDat(DocId)+=int(WordFq); MxDocFq=TInt::GetMx(MxDocFq, DocIdFqH.GetDat(DocId)); } } } int NewMnDocFq=(MnDocFq<=MxDocFq) ? MnDocFq : MxDocFq-3; DocIdV.Gen(DocIdFqH.Len(), 0); int DocIdP=DocIdFqH.FFirstKeyId(); while (DocIdFqH.FNextKeyId(DocIdP)){ int DocId=DocIdFqH.GetKey(DocIdP); int DocFq=DocIdFqH[DocIdP]; if (DocFq>=NewMnDocFq){DocIdV.Add(DocId);} } } } void TYInvIx::SaveTxt(const PSOut& SOut, const PYBs& YBs){ TOLx Lx(SOut, TFSet()|oloFrcEoln|oloSigNum); int WordIdToFirstDocIdNP=WordIdToFirstDocIdNH.FFirstKeyId(); while (WordIdToFirstDocIdNH.FNextKeyId(WordIdToFirstDocIdNP)){ int WordId=WordIdToFirstDocIdNH.GetKey(WordIdToFirstDocIdNP); TStr WordStr; if (YBs.Empty()){WordStr=TInt::GetStr(WordId);} else {WordStr=YBs->GetWordStr(WordId);} Lx.PutStr(WordStr); Lx.PutSym(syColon); Lx.PutSym(syLBracket); int DocIdN=FFirstDocId(WordId); int DocId; while (FNextWordId(DocIdN, DocId)){ Lx.PutInt(DocId);} Lx.PutSym(syRBracket); Lx.PutLn(); } } ///////////////////////////////////////////////// // Yahoo-Value-Retriever bool TYValRet::FNextAttrN(int& AttrP, int& AttrN, TTbVal& AttrVal) const { bool IsFNext; double WordFq; double WordPrb; do { IsFNext=WordDs->FNextWordId(AttrP, AttrN, WordFq, WordPrb); if ((IsFNext)&&(WordPrb>MnWordPrb)){AttrVal=TTbVal(WordFq); return true;} } while (IsFNext); return false; } ///////////////////////////////////////////////// // Model-Yahoo-Bayes TMdYBayes::TMdYBayes( const TYNegDsType& _YNegDsType, const TYPriorType& _YPriorType, const PYBs& _YBs, const PYDsBs& _YDsBs, const PYFSelBs& _YFSelBs, const PYInvIx& _YInvIx): TMd(PDmHd(new TYDmHd(_YBs, _YDsBs))), YNegDsType(_YNegDsType), YPriorType(_YPriorType), YBs(_YBs), YDsBs(_YDsBs), YFSelBs(_YFSelBs), YInvIx(_YInvIx), NegWordDs(TYDmDs::GetNegWordDs(YNegDsType, YBs, YDsBs)){ Def(); } PMd TMdYBayes::Load(TSIn& SIn){ TStr TypeNm(SIn); IAssert(TypeNm==TTypeNm<TMdYBayes>()); TYNegDsType YNegDsType=TYNegDsType(int(TInt(SIn))); TYPriorType YPriorType=TYPriorType(int(TInt(SIn))); PYBs YBs(SIn); PYDsBs YDsBs(SIn); PYFSelBs YFSelBs(SIn); PYInvIx YInvIx(SIn); PYWordDs NegWordDs(SIn); SIn.LoadCs(); PMd Md=PMd(new TMdYBayes( YNegDsType, YPriorType, YBs, YDsBs, YFSelBs, YInvIx)); return Md; } void TMdYBayes::Save(TSOut& SOut){ GetTypeNm(*this).Save(SOut); YNegDsType.Save(SOut); YPriorType.Save(SOut); YBs.Save(SOut); YDsBs.Save(SOut); YFSelBs.Save(SOut); YInvIx.Save(SOut); NegWordDs.Save(SOut); SOut.SaveCs(); } PTbValDs TMdYBayes::GetPostrValDs( const PValRet& ValRet, const int& ClassN) const { PYWordDs PosWordDs=YDsBs->GetWordDs(ClassN); PTbValDs PriorValDs=GetPriorValDs(ClassN); TIntFltKdV& WordIdEstKdV=YFSelBs->GetWordIdEstV(ClassN); double LnSumW=log(PriorValDs->GetSumW()); PTbValDs ValDs=new TTbValDs(TTbVal::BoolVals); double NegPriorCPrb=PriorValDs->GetPrb_RelFq(TTbVal::NegVal); double PosPriorCPrb=PriorValDs->GetPrb_RelFq(TTbVal::PosVal); double NegLnPriorCPrb=0; double NegLnPostrCPrb=0; double PosLnPriorCPrb=0; double PosLnPostrCPrb=0; if (NegPriorCPrb!=0){NegLnPostrCPrb=NegLnPriorCPrb=log(NegPriorCPrb);} if (PosPriorCPrb!=0){PosLnPostrCPrb=PosLnPriorCPrb=log(PosPriorCPrb);} int AttrP=ValRet->FFirstAttrN(); int AttrN; TTbVal AVal; while (ValRet->FNextAttrN(AttrP, AttrN, AVal)){ int WordId=AttrN; double WordFq=AVal.GetFlt(); if (YFSelBs->IsWordId(WordIdEstKdV, WordId)){ if (NegPriorCPrb!=0){ double NegAValPrb=NegWordDs->GetWordPrb(WordId); if (NegAValPrb==0){NegLnPostrCPrb+=NegLnPriorCPrb-LnSumW;} else {NegLnPostrCPrb+=log(WordFq*NegAValPrb);} } if (PosPriorCPrb!=0){ double PosAValPrb=PosWordDs->GetWordPrb(WordId); if (PosAValPrb==0){PosLnPostrCPrb+=PosLnPriorCPrb-LnSumW;} else {PosLnPostrCPrb+=log(WordFq*PosAValPrb);} } } } if (NegPriorCPrb!=0){ValDs->AddVal(TTbVal::NegVal, NegLnPostrCPrb);} if (PosPriorCPrb!=0){ValDs->AddVal(TTbVal::PosVal, PosLnPostrCPrb);} ValDs->ExpW(); ValDs->Def(); return ValDs; } PTbValDs TMdYBayes::GetPostrValDs( const PValRet& ValRet, const int& ClassN, TFltIntKdV& WordPrbIdV) const { // same as GetPostrValDs/2 except WordPrbIdV WordPrbIdV.Clr(); PYWordDs PosWordDs=YDsBs->GetWordDs(ClassN); PTbValDs PriorValDs=GetPriorValDs(ClassN); TIntFltKdV& WordIdEstKdV=YFSelBs->GetWordIdEstV(ClassN); double LnSumW=log(PriorValDs->GetSumW()); PTbValDs ValDs=new TTbValDs(TTbVal::BoolVals); double NegPriorCPrb=PriorValDs->GetPrb_RelFq(TTbVal::NegVal); double PosPriorCPrb=PriorValDs->GetPrb_RelFq(TTbVal::PosVal); double NegLnPriorCPrb=0; double NegLnPostrCPrb=0; double PosLnPriorCPrb=0; double PosLnPostrCPrb=0; if (NegPriorCPrb!=0){NegLnPostrCPrb=NegLnPriorCPrb=log(NegPriorCPrb);} if (PosPriorCPrb!=0){PosLnPostrCPrb=PosLnPriorCPrb=log(PosPriorCPrb);} int AttrP=ValRet->FFirstAttrN(); int AttrN; TTbVal AVal; while (ValRet->FNextAttrN(AttrP, AttrN, AVal)){ int WordId=AttrN; double WordFq=AVal.GetFlt(); if (YFSelBs->IsWordId(WordIdEstKdV, WordId)){ if (NegPriorCPrb!=0){ double NegAValPrb=NegWordDs->GetWordPrb(WordId); if (NegAValPrb==0){NegLnPostrCPrb+=NegLnPriorCPrb-LnSumW;} else {NegLnPostrCPrb+=log(WordFq*NegAValPrb);} if (NegAValPrb!=0){ WordPrbIdV.Add(TFltIntKd(-/*WordFq**/NegAValPrb, WordId));} } if (PosPriorCPrb!=0){ double PosAValPrb=PosWordDs->GetWordPrb(WordId); if (PosAValPrb==0){PosLnPostrCPrb+=PosLnPriorCPrb-LnSumW;} else {PosLnPostrCPrb+=log(WordFq*PosAValPrb);} if (PosAValPrb!=0){ WordPrbIdV.Add(TFltIntKd(/*WordFq**/PosAValPrb, WordId));} } } } if (NegPriorCPrb!=0){ValDs->AddVal(TTbVal::NegVal, NegLnPostrCPrb);} if (PosPriorCPrb!=0){ValDs->AddVal(TTbVal::PosVal, PosLnPostrCPrb);} ValDs->ExpW(); ValDs->Def(); WordPrbIdV.Sort(false); return ValDs; }
36.143984
79
0.662592
[ "model" ]
c8ec60333310df78581a653a10850fd4d9e6da14
1,234
hpp
C++
Server/include/Initializers/SSLInitializer.hpp
arokasprz100/Proxy_server
5393613dd2b744814d1151d2aee93767d67646bd
[ "MIT" ]
3
2020-05-18T02:05:34.000Z
2020-05-18T04:42:46.000Z
Server/include/Initializers/SSLInitializer.hpp
arokasprz100/Proxy_server
5393613dd2b744814d1151d2aee93767d67646bd
[ "MIT" ]
null
null
null
Server/include/Initializers/SSLInitializer.hpp
arokasprz100/Proxy_server
5393613dd2b744814d1151d2aee93767d67646bd
[ "MIT" ]
1
2019-06-08T17:07:58.000Z
2019-06-08T17:07:58.000Z
/** * @file SSLInitializer.hpp * @brief This file contains definitions of functions that initialize important OpenSSL variables and call required OpenSSL functions. */ #ifndef SSLInitializer_hpp #define SSLInitializer_hpp #include <openssl/ssl.h> #include <openssl/err.h> #include <string> /** * @class SSLInitializer */ class SSLInitializer final { public: /** * This member function calls required OpenSSL functions and sets up OpenSSL context using which the server will communicate with client if the client to proxy connection is over SSL. * @param certificateFilePath A reference to string object containing the path to the server's certificate file. * @param privateKeyFilePath A reference to string object containing the path to the server's private key file. * @returns Pointer to context created by OpenSSL functions. */ static SSL_CTX* initialize(const std::string& certificateFilePath, const std::string& privateKeyFilePath); private: static void initOpenssl(); static SSL_CTX* prepareContext(); static void configureContextKeyAndCert(SSL_CTX * ctx, const std::string& certificateFilePath, const std::string& privateKeyFilePath); }; #endif // SSLInitializer_hpp
31.641026
184
0.76013
[ "object" ]
c8ec883b84dacc27983ece86d8c2f39c0ecbe6b5
22,540
cc
C++
tensorflow/lite/delegates/gpu/metal/kernels/winograd.cc
TVLIgnacy/tensorflow
242e0a581524b5bba05af0fde052ef677733f2b5
[ "Apache-2.0" ]
1
2021-01-14T15:39:38.000Z
2021-01-14T15:39:38.000Z
tensorflow/lite/delegates/gpu/metal/kernels/winograd.cc
jahnavisrisai/tensorflow
c62635d6633db1d1e633ecb4bb0daf352b775689
[ "Apache-2.0" ]
null
null
null
tensorflow/lite/delegates/gpu/metal/kernels/winograd.cc
jahnavisrisai/tensorflow
c62635d6633db1d1e633ecb4bb0daf352b775689
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/metal/kernels/winograd.h" #include <map> #include <memory> #include <string> #include <utility> #include <vector> #include "absl/strings/str_format.h" #include "tensorflow/lite/delegates/gpu/common/model.h" #include "tensorflow/lite/delegates/gpu/common/shape.h" #include "tensorflow/lite/delegates/gpu/common/types.h" #include "tensorflow/lite/delegates/gpu/common/util.h" #include "tensorflow/lite/delegates/gpu/common/winograd_util.h" #include "tensorflow/lite/delegates/gpu/metal/compute_task_descriptor.h" namespace tflite { namespace gpu { namespace metal { namespace { std::string GetKernelWinograd4x4To36() { std::string c; c += R"( #include <metal_stdlib> using namespace metal; )"; auto bt_mat = BtMatrixForWinograd4x4To6x6(); c += "constant FLT Bt[36] = {\n"; for (int y = 0; y < 6; ++y) { c += "\t"; for (int x = 0; x < 6; ++x) { c += absl::StrFormat("%.10f", bt_mat[y * 6 + x]) + "f, "; } c += "\n"; } c += "};\n"; c += R"( $0 kernel void ComputeFunction($1 uint3 ugid[[thread_position_in_grid]]) { int3 gid = int3(ugid.x * 4, ugid.y * 4, ugid.z); if (ugid.x >= args.tiles_x || ugid.y >= args.tiles_y) return; FLT4 I[6][6]; for (int y = 0; y < 6; ++y) { for (int x = 0; x < 6; ++x) { I[y][x] = FLT4(0.0f); } } const int src_base = gid.z * args.src_tensor.Height() * args.src_tensor.Width(); )"; for (int y = 0; y < 6; ++y) { const std::string s_y = std::to_string(y); c += " {\n"; c += " int coord_y = gid.y + " + s_y + " + args.padding_y;\n"; c += " bool in_y = FLT(coord_y >= 0 && coord_y < " "args.src_tensor.Height());\n"; c += " coord_y = clamp(coord_y, 0, args.src_tensor.Height() - 1);\n"; c += " const int src_adress_y = src_base + coord_y * " "args.src_tensor.Width();\n"; for (int x = 0; x < 6; ++x) { const std::string s_x = std::to_string(x); c += " {\n"; c += " int coord_x = gid.x + " + s_x + " + args.padding_x;\n"; c += " bool in_x = FLT(coord_x >= 0 && coord_x < " "args.src_tensor.Width());\n"; c += " FLT mult = FLT(in_y && in_x);\n"; c += " coord_x = clamp(coord_x, 0, args.src_tensor.Width() - 1);\n"; c += " FLT4 src = args.src_tensor.Read(src_adress_y + coord_x) * " "mult;\n"; c += " I[0][" + s_x + "] += Bt[" + std::to_string(y) + "] * src;\n"; c += " I[1][" + s_x + "] += Bt[" + std::to_string(y + 6) + "] * src;\n"; c += " I[2][" + s_x + "] += Bt[" + std::to_string(y + 12) + "] * src;\n"; c += " I[3][" + s_x + "] += Bt[" + std::to_string(y + 18) + "] * src;\n"; c += " I[4][" + s_x + "] += Bt[" + std::to_string(y + 24) + "] * src;\n"; c += " I[5][" + s_x + "] += Bt[" + std::to_string(y + 30) + "] * src;\n"; c += " }\n"; } c += " }\n"; } c += R"( int dst_x = ugid.y * args.tiles_x + ugid.x; args.dst_tensor.GetAddress(dst_adress, dst_x, 0, gid.z); for (int y = 0; y < 6; ++y) { FLT4 value = I[y][0] + Bt[2] * I[y][2] + Bt[4] * I[y][4]; args.dst_tensor.WriteLinear(value, dst_adress); dst_adress += args.dst_tensor.Width(); value = Bt[7] * I[y][1] + Bt[8] * I[y][2] + Bt[9] * I[y][3] + Bt[10] * I[y][4]; args.dst_tensor.WriteLinear(value, dst_adress); dst_adress += args.dst_tensor.Width(); value = Bt[13] * I[y][1] + Bt[14] * I[y][2] + Bt[15] * I[y][3] + Bt[16] * I[y][4]; args.dst_tensor.WriteLinear(value, dst_adress); dst_adress += args.dst_tensor.Width(); value = Bt[19] * I[y][1] + Bt[20] * I[y][2] + Bt[21] * I[y][3] + Bt[22] * I[y][4]; args.dst_tensor.WriteLinear(value, dst_adress); dst_adress += args.dst_tensor.Width(); value = Bt[25] * I[y][1] + Bt[26] * I[y][2] + Bt[27] * I[y][3] + Bt[28] * I[y][4]; args.dst_tensor.WriteLinear(value, dst_adress); dst_adress += args.dst_tensor.Width(); value = Bt[31] * I[y][1] + Bt[33] * I[y][3] + I[y][5]; args.dst_tensor.WriteLinear(value, dst_adress); dst_adress += args.dst_tensor.Width(); } } )"; return c; } std::string GetKernelWinograd4x4To36TileX6() { std::string c = R"( #include <metal_stdlib> using namespace metal; )"; auto bt_mat = BtMatrixForWinograd4x4To6x6(); c += "constant FLT Bt[36] = {\n"; for (int y = 0; y < 6; ++y) { c += "\t"; for (int x = 0; x < 6; ++x) { c += absl::StrFormat("%.10f", bt_mat[y * 6 + x]) + "f, "; } c += "\n"; } c += "};\n"; c += R"( $0 kernel void ComputeFunction($1 uint3 global_ids[[thread_position_in_grid]]) { int DST_X = global_ids.x; int DST_Y = global_ids.y; int DST_Z = global_ids.z; if (DST_X >= args.tiles_y || DST_Y >= 6 || DST_Z >= args.dst_tensor.Slices()) { return; } int tile_x = (DST_X % args.tiles_x) * 4; int tile_y = (DST_X / args.tiles_x) * 4; FLT4 I0, I1, I2, I3, I4, I5; FLT bt_ar[6]; FLT4 t0 = args.bt_arr.Read(DST_Y * 2 + 0); FLT4 t1 = args.bt_arr.Read(DST_Y * 2 + 1); DST_Y *= 6; bt_ar[0] = t0.x; bt_ar[1] = t0.y; bt_ar[2] = t0.z; bt_ar[3] = t0.w; bt_ar[4] = t1.x; bt_ar[5] = t1.y; )"; auto read_src = [&](const std::string& src, const std::string& xs) { c += " FLT4 " + src + " = args.src_tensor.Read(src_a_" + xs + " + offset) * m" + xs + "_x;\n"; }; for (int x = 0; x < 6; ++x) { const std::string xs = std::to_string(x); c += " int xc" + xs + " = tile_x + args.padding_x + " + xs + ";\n"; c += " FLT m" + xs + "_x = xc" + xs + " >= 0 && xc" + xs + " < args.src_tensor.Width();\n"; c += " bool inx" + xs + " = (xc" + xs + " >= 0 && xc" + xs + " < args.src_tensor.Width());\n"; c += " xc" + xs + " = clamp(xc" + xs + ", 0, args.src_tensor.Width() - 1);\n"; c += " int src_a_" + xs + " = DST_Z * args.src_tensor.Width() * args.src_tensor.Height() + xc" + xs + ";\n"; } c += " {\n"; c += " int yc = tile_y + args.padding_y;\n"; c += " bool iny = (yc >= 0 && yc < args.src_tensor.Height());\n"; c += " yc = clamp(yc, 0, args.src_tensor.Height() - 1);\n"; c += " int offset = yc * args.src_tensor.Width();\n"; c += " FLT bt = bt_ar[0] * FLT(iny);\n"; for (int x = 0; x < 6; ++x) { const std::string xs = std::to_string(x); const std::string src = "src" + xs; read_src(src, xs); c += " I" + xs + " = bt * " + src + ";\n"; } c += " }\n"; for (int y = 1; y < 6; ++y) { const std::string ys = std::to_string(y); c += " {\n"; c += " int yc = tile_y + args.padding_y + (" + ys + ");\n"; c += " bool iny = (yc >= 0 && yc < args.src_tensor.Height());\n"; c += " yc = clamp(yc, 0, args.src_tensor.Height() - 1);\n"; c += " int offset = yc * args.src_tensor.Width();\n"; c += " FLT bt = bt_ar[" + ys + "] * FLT(iny);\n"; for (int x = 0; x < 6; ++x) { const std::string xs = std::to_string(x); const std::string src = "src" + xs; read_src(src, xs); c += " I" + xs + " += bt * " + src + ";\n"; } c += " }\n"; } c += R"( { FLT4 r0 = I0 + Bt[2] * I2 + Bt[4] * I4; args.dst_tensor.Write(r0, DST_X, DST_Y, DST_Z); DST_Y++; } { FLT4 r0 = Bt[7] * I1 + Bt[8] * I2 + Bt[9] * I3 + Bt[10] * I4; args.dst_tensor.Write(r0, DST_X, DST_Y, DST_Z); DST_Y++; } { FLT4 r0 = Bt[13] * I1 + Bt[14] * I2 + Bt[15] * I3 + Bt[16] * I4; args.dst_tensor.Write(r0, DST_X, DST_Y, DST_Z); DST_Y++; } { FLT4 r0 = Bt[19] * I1 + Bt[20] * I2 + Bt[21] * I3 + Bt[22] * I4; args.dst_tensor.Write(r0, DST_X, DST_Y, DST_Z); DST_Y++; } { FLT4 r0 = Bt[25] * I1 + Bt[26] * I2 + Bt[27] * I3 + Bt[28] * I4; args.dst_tensor.Write(r0, DST_X, DST_Y, DST_Z); DST_Y++; } { FLT4 r0 = Bt[31] * I1 + Bt[33] * I3 + I5; args.dst_tensor.Write(r0, DST_X, DST_Y, DST_Z); } } )"; return c; } std::string GetKernelWinograd36To4x4() { std::string c; c += R"( #include <metal_stdlib> using namespace metal; )"; auto at_mat = AtMatrixForWinograd4x4To6x6(); c += "constant FLT At[24] = {\n"; for (int y = 0; y < 4; ++y) { c += "\t"; for (int x = 0; x < 6; ++x) { c += absl::StrFormat("%.10f", at_mat[y * 6 + x]) + "f, "; } c += "\n"; } c += "};\n"; c += R"( $0 kernel void ComputeFunction($1 uint3 global_ids[[thread_position_in_grid]]) { int tile_id = global_ids.x; int Z = static_cast<int>(global_ids.z); int tiles_count_x = (args.dst_tensor.Width() + 3) / 4; int tile_x = (tile_id % tiles_count_x) * 4; int tile_y = (tile_id / tiles_count_x) * 4; if (tile_x >= args.dst_tensor.Width() || tile_y >= args.dst_tensor.Height()) return; int src_adress = Z * args.src_tensor.Height() * args.src_tensor.Width() + tile_id; FLT4 I[4][6]; for (int y = 0; y < 4; ++y) { for (int x = 0; x < 6; ++x) { I[y][x] = 0.0f; } } for (int y = 0; y < 6; ++y) { for (int x = 0; x < 6; ++x, src_adress += args.src_tensor.Width()) { FLT4 src = args.src_tensor.Read(src_adress); I[0][x] += src * At[y]; I[1][x] += src * At[y + 6]; I[2][x] += src * At[y + 12]; I[3][x] += src * At[y + 18]; } } FLT4 bias_val = args.biases.Read(Z); for (int y = 0; y < 4 && tile_y + y < args.dst_tensor.Height(); ++y) { FLT4 t0 = I[y][1] + I[y][2]; FLT4 t1 = I[y][3] + I[y][4]; if (tile_x < args.dst_tensor.Width()) { FLT4 value = I[y][0] + t0 + t1 + bias_val; args.dst_tensor.Write(value, tile_x, tile_y + y, global_ids.z); } FLT4 t2 = I[y][1] - I[y][2]; FLT4 t3 = I[y][3] - I[y][4]; if (tile_x + 1 < args.dst_tensor.Width()) { FLT4 value = t2 * At[7] + t3 * At[9] + bias_val; args.dst_tensor.Write(value, tile_x + 1, tile_y + y, global_ids.z); } if (tile_x + 2 < args.dst_tensor.Width()) { FLT4 value = t0 * At[13] + t1 * At[15] + bias_val; args.dst_tensor.Write(value, tile_x + 2, tile_y + y, global_ids.z); } if (tile_x + 3 < args.dst_tensor.Width()) { FLT4 value = t2 * At[19] + t3 * At[21] + I[y][5] + bias_val; args.dst_tensor.Write(value, tile_x + 3, tile_y + y, global_ids.z); } } } )"; return c; } std::string GetKernelWinograd36To4x4Tile4x1() { std::string c; c += R"( #include <metal_stdlib> using namespace metal; )"; auto at_mat = AtMatrixForWinograd4x4To6x6(); c += "constant FLT At[24] = {\n"; for (int y = 0; y < 4; ++y) { c += "\t"; for (int x = 0; x < 6; ++x) { c += absl::StrFormat("%.10f", at_mat[y * 6 + x]) + "f, "; } c += "\n"; } c += "};\n"; c += R"( $0 kernel void ComputeFunction($1 uint3 global_ids[[thread_position_in_grid]]) { int tile_id = global_ids.x; int DST_Y = global_ids.y; int DST_Z = global_ids.z; int tile_x = (tile_id % args.tiles_x) * 4; int tile_y = (tile_id / args.tiles_x) * 4 + DST_Y; if (tile_x >= args.dst_tensor.Width() || tile_y >= args.dst_tensor.Height() || DST_Z >= args.dst_tensor.Slices()) { return; } FLT4 I0, I1, I2, I3, I4, I5; FLT at_ar[6]; FLT4 t00 = args.at_arr.Read(DST_Y * 2 + 0); FLT4 t01 = args.at_arr.Read(DST_Y * 2 + 1); at_ar[0] = t00.x; at_ar[1] = t00.y; at_ar[2] = t00.z; at_ar[3] = t00.w; at_ar[4] = t01.x; at_ar[5] = t01.y; int src_adress = DST_Z * args.src_tensor.Height() * args.src_tensor.Width() + tile_id; int src_adress_final; { FLT at = at_ar[0]; )"; for (int x = 0; x < 6; ++x) { const std::string yc = std::to_string(x); const std::string src = "src" + std::to_string(x); c += " src_adress_final = src_adress + args.src_tensor.Width() * " + yc + ";\n"; c += " FLT4 " + src + " = args.src_tensor.Read(src_adress_final);\n"; c += " I" + std::to_string(x) + " = at * " + src + ";\n"; } c += " }\n"; for (int y = 1; y < 6; ++y) { c += " {\n"; c += " FLT at = at_ar[" + std::to_string(y) + "];\n"; for (int x = 0; x < 6; ++x) { const std::string yc = std::to_string(y * 6 + x); const std::string src = "src" + std::to_string(x); c += " src_adress_final = src_adress + args.src_tensor.Width() * " + yc + ";\n"; c += " FLT4 " + src + " = args.src_tensor.Read(src_adress_final);\n"; c += " I" + std::to_string(x) + " += at * " + src + ";\n"; } c += " }\n"; } c += R"( FLT4 t0 = I1 + I2; FLT4 t1 = I3 + I4; FLT4 bias_val = args.biases.Read(DST_Z); if (tile_x < args.dst_tensor.Width()) { FLT4 value = I0 + t0 + t1 + bias_val; args.dst_tensor.Write(value, tile_x, tile_y, global_ids.z); } FLT4 t2 = I1 - I2; FLT4 t3 = I3 - I4; if (tile_x + 1 < args.dst_tensor.Width()) { FLT4 value = t2 * At[7] + t3 * At[9] + bias_val; args.dst_tensor.Write(value, tile_x + 1, tile_y, global_ids.z); } if (tile_x + 2 < args.dst_tensor.Width()) { FLT4 value = t0 * At[13] + t1 * At[15] + bias_val; args.dst_tensor.Write(value, tile_x + 2, tile_y, global_ids.z); } if (tile_x + 3 < args.dst_tensor.Width()) { FLT4 value = t2 * At[19] + t3 * At[21] + I5 + bias_val; args.dst_tensor.Write(value, tile_x + 3, tile_y, global_ids.z); } } )"; return c; } } // namespace ComputeTaskDescriptor Winograd4x4To36(const OperationDef& definition, const Winograd4x4To36Attributes& attr) { ComputeTaskDescriptor desc(definition); desc.shader_source = GetKernelWinograd4x4To36(); desc.AddSrcTensor("src_tensor", definition.src_tensors[0]); desc.AddDstTensor("dst_tensor", definition.dst_tensors[0]); desc.args.AddInt("padding_x", -attr.padding.prepended.w); desc.args.AddInt("padding_y", -attr.padding.prepended.h); desc.args.AddInt("tiles_x"); desc.args.AddInt("tiles_y"); desc.update_function = {[attr](const std::vector<BHWC>& src_shapes, const std::vector<BHWC>& dst_shapes, ArgumentsBinder* args) -> absl::Status { int new_width = src_shapes[0].w + attr.padding.prepended.w + attr.padding.appended.w - 2; int new_height = src_shapes[0].h + attr.padding.prepended.h + attr.padding.appended.h - 2; int tiles_x = DivideRoundUp(new_width, 4); int tiles_y = DivideRoundUp(new_height, 4); RETURN_IF_ERROR(args->SetInt("tiles_x", tiles_x)); RETURN_IF_ERROR(args->SetInt("tiles_y", tiles_y)); return absl::OkStatus(); }}; desc.resize_function = [attr](const std::vector<BHWC>& src_shapes, const std::vector<BHWC>& dst_shapes) { const uint3 groups_size{8, 4, 1}; int new_width = src_shapes[0].w + attr.padding.prepended.w + attr.padding.appended.w - 2; int new_height = src_shapes[0].h + attr.padding.prepended.h + attr.padding.appended.h - 2; int grid_x = DivideRoundUp(new_width, 4); int grid_y = DivideRoundUp(new_height, 4); int grid_z = DivideRoundUp(src_shapes[0].c, 4); int groups_x = DivideRoundUp(grid_x, groups_size.x); int groups_y = DivideRoundUp(grid_y, groups_size.y); int groups_z = DivideRoundUp(grid_z, groups_size.z); return std::make_pair(groups_size, uint3{groups_x, groups_y, groups_z}); }; return desc; } ComputeTaskDescriptor Winograd4x4To36TileX6( const OperationDef& definition, const Winograd4x4To36Attributes& attr) { ComputeTaskDescriptor desc(definition); desc.shader_source = GetKernelWinograd4x4To36TileX6(); desc.AddSrcTensor("src_tensor", definition.src_tensors[0]); desc.AddDstTensor("dst_tensor", definition.dst_tensors[0]); std::vector<float> bt_aligned(6 * 8); auto bt_mat = BtMatrixForWinograd4x4To6x6(); for (int y = 0; y < 6; ++y) { for (int x = 0; x < 6; ++x) { bt_aligned[y * 8 + x] = bt_mat[y * 6 + x]; } bt_aligned[y * 8 + 6] = 0.0f; bt_aligned[y * 8 + 7] = 0.0f; } auto data_type = DeduceDataTypeFromPrecision(definition.precision); BufferDescriptor buf_desc; buf_desc.element_type = data_type; buf_desc.element_size = 4; buf_desc.data = GetByteBufferConverted(bt_aligned, data_type); buf_desc.size = buf_desc.data.size(); desc.args.AddObject("bt_arr", absl::make_unique<BufferDescriptor>(std::move(buf_desc))); desc.args.AddInt("padding_x", -attr.padding.prepended.w); desc.args.AddInt("padding_y", -attr.padding.prepended.h); desc.args.AddInt("tiles_x"); desc.args.AddInt("tiles_y"); desc.update_function = {[attr](const std::vector<BHWC>& src_shapes, const std::vector<BHWC>& dst_shapes, ArgumentsBinder* args) -> absl::Status { int new_width = src_shapes[0].w + attr.padding.prepended.w + attr.padding.appended.w - 2; int new_height = src_shapes[0].h + attr.padding.prepended.h + attr.padding.appended.h - 2; int tiles_x = DivideRoundUp(new_width, 4); int tiles_y = DivideRoundUp(new_height, 4); RETURN_IF_ERROR(args->SetInt("tiles_x", tiles_x)); RETURN_IF_ERROR(args->SetInt("tiles_y", tiles_x * tiles_y)); return absl::OkStatus(); }}; desc.resize_function = [](const std::vector<BHWC>& src_shapes, const std::vector<BHWC>& dst_shapes) { const uint3 groups_size{4, 6, 1}; int grid_x = dst_shapes[0].w; int grid_y = 6; int grid_z = DivideRoundUp(dst_shapes[0].c, 4); int groups_x = DivideRoundUp(grid_x, groups_size.x); int groups_y = DivideRoundUp(grid_y, groups_size.y); int groups_z = DivideRoundUp(grid_z, groups_size.z); return std::make_pair(groups_size, uint3{groups_x, groups_y, groups_z}); }; return desc; } ComputeTaskDescriptor Winograd36To4x4(const OperationDef& definition, const Winograd36To4x4Attributes& attr) { ComputeTaskDescriptor desc(definition); desc.shader_source = GetKernelWinograd36To4x4(); desc.AddSrcTensor("src_tensor", definition.src_tensors[0]); desc.AddDstTensor("dst_tensor", definition.dst_tensors[0]); auto data_type = DeduceDataTypeFromPrecision(definition.precision); BufferDescriptor bias_desc; bias_desc.element_type = data_type; bias_desc.element_size = 4; bias_desc.data = GetByteBufferConvertedResized( attr.biases.data, data_type, AlignByN(attr.output_shape.c, 4)); bias_desc.size = bias_desc.data.size(); desc.args.AddObject( "biases", absl::make_unique<BufferDescriptor>(std::move(bias_desc))); desc.resize_function = [](const std::vector<BHWC>& src_shapes, const std::vector<BHWC>& dst_shapes) { const uint3 groups_size{32, 1, 1}; int grid_x = src_shapes[0].w; int grid_y = 1; int grid_z = DivideRoundUp(src_shapes[0].c, 4); int groups_x = DivideRoundUp(grid_x, groups_size.x); int groups_y = DivideRoundUp(grid_y, groups_size.y); int groups_z = DivideRoundUp(grid_z, groups_size.z); return std::make_pair(groups_size, uint3{groups_x, groups_y, groups_z}); }; return desc; } ComputeTaskDescriptor Winograd36To4x4Tile4x1( const OperationDef& definition, const Winograd36To4x4Attributes& attr) { ComputeTaskDescriptor desc(definition); desc.shader_source = GetKernelWinograd36To4x4Tile4x1(); desc.AddSrcTensor("src_tensor", definition.src_tensors[0]); desc.AddDstTensor("dst_tensor", definition.dst_tensors[0]); std::vector<float> at_aligned(4 * 8); auto at_mat = AtMatrixForWinograd4x4To6x6(); for (int y = 0; y < 4; ++y) { for (int x = 0; x < 6; ++x) { at_aligned[y * 8 + x] = at_mat[y * 6 + x]; } at_aligned[y * 8 + 6] = 0.0f; at_aligned[y * 8 + 7] = 0.0f; } auto data_type = DeduceDataTypeFromPrecision(definition.precision); BufferDescriptor bias_desc; bias_desc.element_type = data_type; bias_desc.element_size = 4; bias_desc.data = GetByteBufferConvertedResized( attr.biases.data, data_type, AlignByN(attr.output_shape.c, 4)); bias_desc.size = bias_desc.data.size(); desc.args.AddObject( "biases", absl::make_unique<BufferDescriptor>(std::move(bias_desc))); BufferDescriptor buf_desc; buf_desc.element_type = data_type; buf_desc.element_size = 4; buf_desc.data = GetByteBufferConverted(at_aligned, data_type); buf_desc.size = buf_desc.data.size(); desc.args.AddObject("at_arr", absl::make_unique<BufferDescriptor>(std::move(buf_desc))); desc.args.AddInt("tiles_x"); desc.args.AddInt("tiles_y"); desc.update_function = {[attr](const std::vector<BHWC>& src_shapes, const std::vector<BHWC>& dst_shapes, ArgumentsBinder* args) -> absl::Status { const int tiles_x = DivideRoundUp(dst_shapes[0].w, 4); const int tiles_y = DivideRoundUp(dst_shapes[0].h, 4); RETURN_IF_ERROR(args->SetInt("tiles_x", tiles_x)); RETURN_IF_ERROR(args->SetInt("tiles_y", tiles_y)); return absl::OkStatus(); }}; desc.resize_function = [](const std::vector<BHWC>& src_shapes, const std::vector<BHWC>& dst_shapes) { const uint3 groups_size{8, 4, 1}; const int tiles_x = DivideRoundUp(dst_shapes[0].w, 4); const int tiles_y = DivideRoundUp(dst_shapes[0].h, 4); int grid_x = tiles_x * tiles_y; int grid_y = 4; int grid_z = DivideRoundUp(dst_shapes[0].c, 4); int groups_x = DivideRoundUp(grid_x, groups_size.x); int groups_y = DivideRoundUp(grid_y, groups_size.y); int groups_z = DivideRoundUp(grid_z, groups_size.z); return std::make_pair(groups_size, uint3{groups_x, groups_y, groups_z}); }; return desc; } } // namespace metal } // namespace gpu } // namespace tflite
35.384615
117
0.577462
[ "shape", "vector", "model" ]
c8efea858ca5d5896aa217fdd5fe559ac6f78453
27,401
cpp
C++
Firmware/Marlin/src/gcode/calibrate/G425.cpp
jhNsXO/UnifiedFirmware
a3649d67d9fa6219c7fb58ab9e18594b1b0a24df
[ "Info-ZIP" ]
97
2020-09-14T13:35:17.000Z
2022-03-28T20:15:49.000Z
Firmware/Marlin/src/gcode/calibrate/G425.cpp
jhNsXO/UnifiedFirmware
a3649d67d9fa6219c7fb58ab9e18594b1b0a24df
[ "Info-ZIP" ]
8
2020-11-11T21:01:38.000Z
2022-01-22T01:22:10.000Z
Firmware/Marlin/src/gcode/calibrate/G425.cpp
jhNsXO/UnifiedFirmware
a3649d67d9fa6219c7fb58ab9e18594b1b0a24df
[ "Info-ZIP" ]
49
2020-09-22T09:33:37.000Z
2022-03-19T21:23:04.000Z
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "../../MarlinCore.h" #if ENABLED(CALIBRATION_GCODE) #include "../gcode.h" #if ENABLED(BACKLASH_GCODE) #include "../../feature/backlash.h" #endif #include "../../lcd/marlinui.h" #include "../../module/motion.h" #include "../../module/planner.h" #include "../../module/tool_change.h" #include "../../module/endstops.h" #include "../../feature/bedlevel/bedlevel.h" #if !AXIS_CAN_CALIBRATE(X) #undef CALIBRATION_MEASURE_LEFT #undef CALIBRATION_MEASURE_RIGHT #endif #if !AXIS_CAN_CALIBRATE(Y) #undef CALIBRATION_MEASURE_FRONT #undef CALIBRATION_MEASURE_BACK #endif #if !AXIS_CAN_CALIBRATE(Z) #undef CALIBRATION_MEASURE_AT_TOP_EDGES #endif /** * G425 backs away from the calibration object by various distances * depending on the confidence level: * * UNKNOWN - No real notion on where the calibration object is on the bed * UNCERTAIN - Measurement may be uncertain due to backlash * CERTAIN - Measurement obtained with backlash compensation */ #ifndef CALIBRATION_MEASUREMENT_UNKNOWN #define CALIBRATION_MEASUREMENT_UNKNOWN 5.0 // mm #endif #ifndef CALIBRATION_MEASUREMENT_UNCERTAIN #define CALIBRATION_MEASUREMENT_UNCERTAIN 1.0 // mm #endif #ifndef CALIBRATION_MEASUREMENT_CERTAIN #define CALIBRATION_MEASUREMENT_CERTAIN 0.5 // mm #endif #if BOTH(CALIBRATION_MEASURE_LEFT, CALIBRATION_MEASURE_RIGHT) #define HAS_X_CENTER 1 #endif #if HAS_Y_AXIS && BOTH(CALIBRATION_MEASURE_FRONT, CALIBRATION_MEASURE_BACK) #define HAS_Y_CENTER 1 #endif #if LINEAR_AXES >= 4 && BOTH(CALIBRATION_MEASURE_IMIN, CALIBRATION_MEASURE_IMAX) #define HAS_I_CENTER 1 #endif #if LINEAR_AXES >= 5 && BOTH(CALIBRATION_MEASURE_JMIN, CALIBRATION_MEASURE_JMAX) #define HAS_J_CENTER 1 #endif #if LINEAR_AXES >= 6 && BOTH(CALIBRATION_MEASURE_KMIN, CALIBRATION_MEASURE_KMAX) #define HAS_K_CENTER 1 #endif enum side_t : uint8_t { TOP, RIGHT, FRONT, LEFT, BACK, NUM_SIDES, LIST_N(DOUBLE(SUB3(LINEAR_AXES)), IMINIMUM, IMAXIMUM, JMINIMUM, JMAXIMUM, KMINIMUM, KMAXIMUM) }; static constexpr xyz_pos_t true_center CALIBRATION_OBJECT_CENTER; static constexpr xyz_float_t dimensions CALIBRATION_OBJECT_DIMENSIONS; static constexpr xy_float_t nod = { CALIBRATION_NOZZLE_OUTER_DIAMETER, CALIBRATION_NOZZLE_OUTER_DIAMETER }; struct measurements_t { xyz_pos_t obj_center = true_center; // Non-static must be assigned from xyz_pos_t float obj_side[NUM_SIDES], backlash[NUM_SIDES]; xyz_float_t pos_error; xy_float_t nozzle_outer_dimension = nod; }; #if ENABLED(BACKLASH_GCODE) #define TEMPORARY_BACKLASH_CORRECTION(value) REMEMBER(tbst, backlash.correction, value) #else #define TEMPORARY_BACKLASH_CORRECTION(value) #endif #if ENABLED(BACKLASH_GCODE) && defined(BACKLASH_SMOOTHING_MM) #define TEMPORARY_BACKLASH_SMOOTHING(value) REMEMBER(tbsm, backlash.smoothing_mm, value) #else #define TEMPORARY_BACKLASH_SMOOTHING(value) #endif inline void calibration_move() { do_blocking_move_to((xyz_pos_t)current_position, MMM_TO_MMS(CALIBRATION_FEEDRATE_TRAVEL)); } /** * Move to the exact center above the calibration object * * m in - Measurement record * uncertainty in - How far away from the object top to park */ inline void park_above_object(measurements_t &m, const float uncertainty) { // Move to safe distance above calibration object current_position.z = m.obj_center.z + dimensions.z / 2 + uncertainty; calibration_move(); // Move to center of calibration object in XY current_position = xy_pos_t(m.obj_center); calibration_move(); } #if HAS_MULTI_HOTEND inline void set_nozzle(measurements_t &m, const uint8_t extruder) { if (extruder != active_extruder) { park_above_object(m, CALIBRATION_MEASUREMENT_UNKNOWN); tool_change(extruder); } } #endif #if HAS_HOTEND_OFFSET inline void normalize_hotend_offsets() { LOOP_S_L_N(e, 1, HOTENDS) hotend_offset[e] -= hotend_offset[0]; hotend_offset[0].reset(); } #endif #if !PIN_EXISTS(CALIBRATION) #include "../../module/probe.h" #endif inline bool read_calibration_pin() { return ( #if PIN_EXISTS(CALIBRATION) READ(CALIBRATION_PIN) != CALIBRATION_PIN_INVERTING #else PROBE_TRIGGERED() #endif ); } /** * Move along axis in the specified dir until the probe value becomes stop_state, * then return the axis value. * * axis in - Axis along which the measurement will take place * dir in - Direction along that axis (-1 or 1) * stop_state in - Move until probe pin becomes this value * fast in - Fast vs. precise measurement */ float measuring_movement(const AxisEnum axis, const int dir, const bool stop_state, const bool fast) { const float step = fast ? 0.25 : CALIBRATION_MEASUREMENT_RESOLUTION; const feedRate_t mms = fast ? MMM_TO_MMS(CALIBRATION_FEEDRATE_FAST) : MMM_TO_MMS(CALIBRATION_FEEDRATE_SLOW); const float limit = fast ? 50 : 5; destination = current_position; for (float travel = 0; travel < limit; travel += step) { destination[axis] += dir * step; do_blocking_move_to((xyz_pos_t)destination, mms); planner.synchronize(); if (read_calibration_pin() == stop_state) break; } return destination[axis]; } /** * Move along axis until the probe is triggered. Move toolhead to its starting * point and return the measured value. * * axis in - Axis along which the measurement will take place * dir in - Direction along that axis (-1 or 1) * stop_state in - Move until probe pin becomes this value * backlash_ptr in/out - When not nullptr, measure and record axis backlash * uncertainty in - If uncertainty is CALIBRATION_MEASUREMENT_UNKNOWN, do a fast probe. */ inline float measure(const AxisEnum axis, const int dir, const bool stop_state, float * const backlash_ptr, const float uncertainty) { const bool fast = uncertainty == CALIBRATION_MEASUREMENT_UNKNOWN; // Save the current position of the specified axis const float start_pos = current_position[axis]; // Take a measurement. Only the specified axis will be affected. const float measured_pos = measuring_movement(axis, dir, stop_state, fast); // Measure backlash if (backlash_ptr && !fast) { const float release_pos = measuring_movement(axis, -dir, !stop_state, fast); *backlash_ptr = ABS(release_pos - measured_pos); } // Move back to the starting position destination = current_position; destination[axis] = start_pos; do_blocking_move_to((xyz_pos_t)destination, MMM_TO_MMS(CALIBRATION_FEEDRATE_TRAVEL)); return measured_pos; } /** * Probe one side of the calibration object * * m in/out - Measurement record, m.obj_center and m.obj_side will be updated. * uncertainty in - How far away from the calibration object to begin probing * side in - Side of probe where probe will occur * probe_top_at_edge in - When probing sides, probe top of calibration object nearest edge * to find out height of edge */ inline void probe_side(measurements_t &m, const float uncertainty, const side_t side, const bool probe_top_at_edge=false) { const xyz_float_t dimensions = CALIBRATION_OBJECT_DIMENSIONS; AxisEnum axis; float dir = 1; park_above_object(m, uncertainty); switch (side) { #if AXIS_CAN_CALIBRATE(X) case RIGHT: dir = -1; case LEFT: axis = X_AXIS; break; #endif #if LINEAR_AXES >= 2 && AXIS_CAN_CALIBRATE(Y) case BACK: dir = -1; case FRONT: axis = Y_AXIS; break; #endif #if HAS_Z_AXIS && AXIS_CAN_CALIBRATE(Z) case TOP: { const float measurement = measure(Z_AXIS, -1, true, &m.backlash[TOP], uncertainty); m.obj_center.z = measurement - dimensions.z / 2; m.obj_side[TOP] = measurement; return; } #endif #if LINEAR_AXES >= 4 && AXIS_CAN_CALIBRATE(I) case IMINIMUM: dir = -1; case IMAXIMUM: axis = I_AXIS; break; #endif #if LINEAR_AXES >= 5 && AXIS_CAN_CALIBRATE(J) case JMINIMUM: dir = -1; case JMAXIMUM: axis = J_AXIS; break; #endif #if LINEAR_AXES >= 6 && AXIS_CAN_CALIBRATE(K) case KMINIMUM: dir = -1; case KMAXIMUM: axis = K_AXIS; break; #endif default: return; } if (probe_top_at_edge) { #if AXIS_CAN_CALIBRATE(Z) // Probe top nearest the side we are probing current_position[axis] = m.obj_center[axis] + (-dir) * (dimensions[axis] / 2 - m.nozzle_outer_dimension[axis]); calibration_move(); m.obj_side[TOP] = measure(Z_AXIS, -1, true, &m.backlash[TOP], uncertainty); m.obj_center.z = m.obj_side[TOP] - dimensions.z / 2; #endif } if ((AXIS_CAN_CALIBRATE(X) && axis == X_AXIS) || (AXIS_CAN_CALIBRATE(Y) && axis == Y_AXIS)) { // Move to safe distance to the side of the calibration object current_position[axis] = m.obj_center[axis] + (-dir) * (dimensions[axis] / 2 + m.nozzle_outer_dimension[axis] / 2 + uncertainty); calibration_move(); // Plunge below the side of the calibration object and measure current_position.z = m.obj_side[TOP] - (CALIBRATION_NOZZLE_TIP_HEIGHT) * 0.7f; calibration_move(); const float measurement = measure(axis, dir, true, &m.backlash[side], uncertainty); m.obj_center[axis] = measurement + dir * (dimensions[axis] / 2 + m.nozzle_outer_dimension[axis] / 2); m.obj_side[side] = measurement; } } /** * Probe all sides of the calibration calibration object * * m in/out - Measurement record: center, backlash and error values be updated. * uncertainty in - How far away from the calibration object to begin probing */ inline void probe_sides(measurements_t &m, const float uncertainty) { #if ENABLED(CALIBRATION_MEASURE_AT_TOP_EDGES) constexpr bool probe_top_at_edge = true; #else // Probing at the exact center only works if the center is flat. Probing on a washer // or bolt will require probing the top near the side edges, away from the center. constexpr bool probe_top_at_edge = false; probe_side(m, uncertainty, TOP); #endif TERN_(CALIBRATION_MEASURE_RIGHT, probe_side(m, uncertainty, RIGHT, probe_top_at_edge)); TERN_(CALIBRATION_MEASURE_FRONT, probe_side(m, uncertainty, FRONT, probe_top_at_edge)); TERN_(CALIBRATION_MEASURE_LEFT, probe_side(m, uncertainty, LEFT, probe_top_at_edge)); TERN_(CALIBRATION_MEASURE_BACK, probe_side(m, uncertainty, BACK, probe_top_at_edge)); TERN_(CALIBRATION_MEASURE_IMIN, probe_side(m, uncertainty, IMINIMUM, probe_top_at_edge)); TERN_(CALIBRATION_MEASURE_IMAX, probe_side(m, uncertainty, IMAXIMUM, probe_top_at_edge)); TERN_(CALIBRATION_MEASURE_JMIN, probe_side(m, uncertainty, JMINIMUM, probe_top_at_edge)); TERN_(CALIBRATION_MEASURE_JMAX, probe_side(m, uncertainty, JMAXIMUM, probe_top_at_edge)); TERN_(CALIBRATION_MEASURE_KMIN, probe_side(m, uncertainty, KMINIMUM, probe_top_at_edge)); TERN_(CALIBRATION_MEASURE_KMAX, probe_side(m, uncertainty, KMAXIMUM, probe_top_at_edge)); // Compute the measured center of the calibration object. TERN_(HAS_X_CENTER, m.obj_center.x = (m.obj_side[LEFT] + m.obj_side[RIGHT]) / 2); TERN_(HAS_Y_CENTER, m.obj_center.y = (m.obj_side[FRONT] + m.obj_side[BACK]) / 2); TERN_(HAS_I_CENTER, m.obj_center.i = (m.obj_side[IMINIMUM] + m.obj_side[IMAXIMUM]) / 2); TERN_(HAS_J_CENTER, m.obj_center.j = (m.obj_side[JMINIMUM] + m.obj_side[JMAXIMUM]) / 2); TERN_(HAS_K_CENTER, m.obj_center.k = (m.obj_side[KMINIMUM] + m.obj_side[KMAXIMUM]) / 2); // Compute the outside diameter of the nozzle at the height // at which it makes contact with the calibration object TERN_(HAS_X_CENTER, m.nozzle_outer_dimension.x = m.obj_side[RIGHT] - m.obj_side[LEFT] - dimensions.x); TERN_(HAS_Y_CENTER, m.nozzle_outer_dimension.y = m.obj_side[BACK] - m.obj_side[FRONT] - dimensions.y); park_above_object(m, uncertainty); // The difference between the known and the measured location // of the calibration object is the positional error LINEAR_AXIS_CODE( m.pos_error.x = TERN0(HAS_X_CENTER, true_center.x - m.obj_center.x), m.pos_error.y = TERN0(HAS_Y_CENTER, true_center.y - m.obj_center.y), m.pos_error.z = true_center.z - m.obj_center.z, m.pos_error.i = TERN0(HAS_I_CENTER, true_center.i - m.obj_center.i), m.pos_error.j = TERN0(HAS_J_CENTER, true_center.j - m.obj_center.j), m.pos_error.k = TERN0(HAS_K_CENTER, true_center.k - m.obj_center.k) ); } #if ENABLED(CALIBRATION_REPORTING) inline void report_measured_faces(const measurements_t &m) { SERIAL_ECHOLNPGM("Sides:"); #if HAS_Z_AXIS && AXIS_CAN_CALIBRATE(Z) SERIAL_ECHOLNPAIR(" Top: ", m.obj_side[TOP]); #endif #if ENABLED(CALIBRATION_MEASURE_LEFT) SERIAL_ECHOLNPAIR(" Left: ", m.obj_side[LEFT]); #endif #if ENABLED(CALIBRATION_MEASURE_RIGHT) SERIAL_ECHOLNPAIR(" Right: ", m.obj_side[RIGHT]); #endif #if HAS_Y_AXIS #if ENABLED(CALIBRATION_MEASURE_FRONT) SERIAL_ECHOLNPAIR(" Front: ", m.obj_side[FRONT]); #endif #if ENABLED(CALIBRATION_MEASURE_BACK) SERIAL_ECHOLNPAIR(" Back: ", m.obj_side[BACK]); #endif #endif #if LINEAR_AXES >= 4 #if ENABLED(CALIBRATION_MEASURE_IMIN) SERIAL_ECHOLNPAIR(" " STR_I_MIN ": ", m.obj_side[IMINIMUM]); #endif #if ENABLED(CALIBRATION_MEASURE_IMAX) SERIAL_ECHOLNPAIR(" " STR_I_MAX ": ", m.obj_side[IMAXIMUM]); #endif #endif #if LINEAR_AXES >= 5 #if ENABLED(CALIBRATION_MEASURE_JMIN) SERIAL_ECHOLNPAIR(" " STR_J_MIN ": ", m.obj_side[JMINIMUM]); #endif #if ENABLED(CALIBRATION_MEASURE_JMAX) SERIAL_ECHOLNPAIR(" " STR_J_MAX ": ", m.obj_side[JMAXIMUM]); #endif #endif #if LINEAR_AXES >= 6 #if ENABLED(CALIBRATION_MEASURE_KMIN) SERIAL_ECHOLNPAIR(" " STR_K_MIN ": ", m.obj_side[KMINIMUM]); #endif #if ENABLED(CALIBRATION_MEASURE_KMAX) SERIAL_ECHOLNPAIR(" " STR_K_MAX ": ", m.obj_side[KMAXIMUM]); #endif #endif SERIAL_EOL(); } inline void report_measured_center(const measurements_t &m) { SERIAL_ECHOLNPGM("Center:"); #if HAS_X_CENTER SERIAL_ECHOLNPAIR_P(SP_X_STR, m.obj_center.x); #endif #if HAS_Y_CENTER SERIAL_ECHOLNPAIR_P(SP_Y_STR, m.obj_center.y); #endif SERIAL_ECHOLNPAIR_P(SP_Z_STR, m.obj_center.z); #if HAS_I_CENTER SERIAL_ECHOLNPAIR_P(SP_I_STR, m.obj_center.i); #endif #if HAS_J_CENTER SERIAL_ECHOLNPAIR_P(SP_J_STR, m.obj_center.j); #endif #if HAS_K_CENTER SERIAL_ECHOLNPAIR_P(SP_K_STR, m.obj_center.k); #endif SERIAL_EOL(); } inline void report_measured_backlash(const measurements_t &m) { SERIAL_ECHOLNPGM("Backlash:"); #if AXIS_CAN_CALIBRATE(X) #if ENABLED(CALIBRATION_MEASURE_LEFT) SERIAL_ECHOLNPAIR(" Left: ", m.backlash[LEFT]); #endif #if ENABLED(CALIBRATION_MEASURE_RIGHT) SERIAL_ECHOLNPAIR(" Right: ", m.backlash[RIGHT]); #endif #endif #if HAS_Y_AXIS && AXIS_CAN_CALIBRATE(Y) #if ENABLED(CALIBRATION_MEASURE_FRONT) SERIAL_ECHOLNPAIR(" Front: ", m.backlash[FRONT]); #endif #if ENABLED(CALIBRATION_MEASURE_BACK) SERIAL_ECHOLNPAIR(" Back: ", m.backlash[BACK]); #endif #endif #if HAS_Z_AXIS && AXIS_CAN_CALIBRATE(Z) SERIAL_ECHOLNPAIR(" Top: ", m.backlash[TOP]); #endif #if LINEAR_AXES >= 4 && AXIS_CAN_CALIBRATE(I) #if ENABLED(CALIBRATION_MEASURE_IMIN) SERIAL_ECHOLNPAIR(" " STR_I_MIN ": ", m.backlash[IMINIMUM]); #endif #if ENABLED(CALIBRATION_MEASURE_IMAX) SERIAL_ECHOLNPAIR(" " STR_I_MAX ": ", m.backlash[IMAXIMUM]); #endif #endif #if LINEAR_AXES >= 5 && AXIS_CAN_CALIBRATE(J) #if ENABLED(CALIBRATION_MEASURE_JMIN) SERIAL_ECHOLNPAIR(" " STR_J_MIN ": ", m.backlash[JMINIMUM]); #endif #if ENABLED(CALIBRATION_MEASURE_JMAX) SERIAL_ECHOLNPAIR(" " STR_J_MAX ": ", m.backlash[JMAXIMUM]); #endif #endif #if LINEAR_AXES >= 6 && AXIS_CAN_CALIBRATE(K) #if ENABLED(CALIBRATION_MEASURE_KMIN) SERIAL_ECHOLNPAIR(" " STR_K_MIN ": ", m.backlash[KMINIMUM]); #endif #if ENABLED(CALIBRATION_MEASURE_KMAX) SERIAL_ECHOLNPAIR(" " STR_K_MAX ": ", m.backlash[KMAXIMUM]); #endif #endif SERIAL_EOL(); } inline void report_measured_positional_error(const measurements_t &m) { SERIAL_CHAR('T'); SERIAL_ECHO(active_extruder); SERIAL_ECHOLNPGM(" Positional Error:"); #if HAS_X_CENTER && AXIS_CAN_CALIBRATE(X) SERIAL_ECHOLNPAIR_P(SP_X_STR, m.pos_error.x); #endif #if HAS_Y_CENTER && AXIS_CAN_CALIBRATE(Y) SERIAL_ECHOLNPAIR_P(SP_Y_STR, m.pos_error.y); #endif #if HAS_Z_AXIS && AXIS_CAN_CALIBRATE(Z) SERIAL_ECHOLNPAIR_P(SP_Z_STR, m.pos_error.z); #endif #if HAS_I_CENTER && AXIS_CAN_CALIBRATE(I) SERIAL_ECHOLNPAIR_P(SP_I_STR, m.pos_error.i); #endif #if HAS_J_CENTER && AXIS_CAN_CALIBRATE(J) SERIAL_ECHOLNPAIR_P(SP_J_STR, m.pos_error.j); #endif #if HAS_K_CENTER && AXIS_CAN_CALIBRATE(K) SERIAL_ECHOLNPAIR_P(SP_Z_STR, m.pos_error.z); #endif SERIAL_EOL(); } inline void report_measured_nozzle_dimensions(const measurements_t &m) { SERIAL_ECHOLNPGM("Nozzle Tip Outer Dimensions:"); #if HAS_X_CENTER SERIAL_ECHOLNPAIR_P(SP_X_STR, m.nozzle_outer_dimension.x); #endif #if HAS_Y_CENTER SERIAL_ECHOLNPAIR_P(SP_Y_STR, m.nozzle_outer_dimension.y); #endif SERIAL_EOL(); UNUSED(m); } #if HAS_HOTEND_OFFSET // // This function requires normalize_hotend_offsets() to be called // inline void report_hotend_offsets() { LOOP_S_L_N(e, 1, HOTENDS) SERIAL_ECHOLNPAIR_P(PSTR("T"), e, PSTR(" Hotend Offset X"), hotend_offset[e].x, SP_Y_STR, hotend_offset[e].y, SP_Z_STR, hotend_offset[e].z); } #endif #endif // CALIBRATION_REPORTING /** * Probe around the calibration object to measure backlash * * m in/out - Measurement record, updated with new readings * uncertainty in - How far away from the object to begin probing */ inline void calibrate_backlash(measurements_t &m, const float uncertainty) { // Backlash compensation should be off while measuring backlash { // New scope for TEMPORARY_BACKLASH_CORRECTION TEMPORARY_BACKLASH_CORRECTION(all_off); TEMPORARY_BACKLASH_SMOOTHING(0.0f); probe_sides(m, uncertainty); #if ENABLED(BACKLASH_GCODE) #if HAS_X_CENTER backlash.distance_mm.x = (m.backlash[LEFT] + m.backlash[RIGHT]) / 2; #elif ENABLED(CALIBRATION_MEASURE_LEFT) backlash.distance_mm.x = m.backlash[LEFT]; #elif ENABLED(CALIBRATION_MEASURE_RIGHT) backlash.distance_mm.x = m.backlash[RIGHT]; #endif #if HAS_Y_CENTER backlash.distance_mm.y = (m.backlash[FRONT] + m.backlash[BACK]) / 2; #elif ENABLED(CALIBRATION_MEASURE_FRONT) backlash.distance_mm.y = m.backlash[FRONT]; #elif ENABLED(CALIBRATION_MEASURE_BACK) backlash.distance_mm.y = m.backlash[BACK]; #endif TERN_(HAS_Z_AXIS, if (AXIS_CAN_CALIBRATE(Z)) backlash.distance_mm.z = m.backlash[TOP]); #if HAS_I_CENTER backlash.distance_mm.i = (m.backlash[IMINIMUM] + m.backlash[IMAXIMUM]) / 2; #elif ENABLED(CALIBRATION_MEASURE_IMIN) backlash.distance_mm.i = m.backlash[IMINIMUM]; #elif ENABLED(CALIBRATION_MEASURE_IMAX) backlash.distance_mm.i = m.backlash[IMAXIMUM]; #endif #if HAS_J_CENTER backlash.distance_mm.j = (m.backlash[JMINIMUM] + m.backlash[JMAXIMUM]) / 2; #elif ENABLED(CALIBRATION_MEASURE_JMIN) backlash.distance_mm.j = m.backlash[JMINIMUM]; #elif ENABLED(CALIBRATION_MEASURE_JMAX) backlash.distance_mm.j = m.backlash[JMAXIMUM]; #endif #if HAS_K_CENTER backlash.distance_mm.k = (m.backlash[KMINIMUM] + m.backlash[KMAXIMUM]) / 2; #elif ENABLED(CALIBRATION_MEASURE_KMIN) backlash.distance_mm.k = m.backlash[KMINIMUM]; #elif ENABLED(CALIBRATION_MEASURE_KMAX) backlash.distance_mm.k = m.backlash[KMAXIMUM]; #endif #endif // BACKLASH_GCODE } #if ENABLED(BACKLASH_GCODE) // Turn on backlash compensation and move in all // allowed directions to take up any backlash { // New scope for TEMPORARY_BACKLASH_CORRECTION TEMPORARY_BACKLASH_CORRECTION(all_on); TEMPORARY_BACKLASH_SMOOTHING(0.0f); const xyz_float_t move = LINEAR_AXIS_ARRAY( AXIS_CAN_CALIBRATE(X) * 3, AXIS_CAN_CALIBRATE(Y) * 3, AXIS_CAN_CALIBRATE(Z) * 3, AXIS_CAN_CALIBRATE(I) * 3, AXIS_CAN_CALIBRATE(J) * 3, AXIS_CAN_CALIBRATE(K) * 3 ); current_position += move; calibration_move(); current_position -= move; calibration_move(); } #endif } inline void update_measurements(measurements_t &m, const AxisEnum axis) { current_position[axis] += m.pos_error[axis]; m.obj_center[axis] = true_center[axis]; m.pos_error[axis] = 0; } /** * Probe around the calibration object. Adjust the position and toolhead offset * using the deviation from the known position of the calibration object. * * m in/out - Measurement record, updated with new readings * uncertainty in - How far away from the object to begin probing * extruder in - What extruder to probe * * Prerequisites: * - Call calibrate_backlash() beforehand for best accuracy */ inline void calibrate_toolhead(measurements_t &m, const float uncertainty, const uint8_t extruder) { TEMPORARY_BACKLASH_CORRECTION(all_on); TEMPORARY_BACKLASH_SMOOTHING(0.0f); TERN(HAS_MULTI_HOTEND, set_nozzle(m, extruder), UNUSED(extruder)); probe_sides(m, uncertainty); // Adjust the hotend offset #if HAS_HOTEND_OFFSET if (ENABLED(HAS_X_CENTER) && AXIS_CAN_CALIBRATE(X)) hotend_offset[extruder].x += m.pos_error.x; if (ENABLED(HAS_Y_CENTER) && AXIS_CAN_CALIBRATE(Y)) hotend_offset[extruder].y += m.pos_error.y; if (AXIS_CAN_CALIBRATE(Z)) hotend_offset[extruder].z += m.pos_error.z; normalize_hotend_offsets(); #endif // Correct for positional error, so the object // is at the known actual spot planner.synchronize(); if (ENABLED(HAS_X_CENTER) && AXIS_CAN_CALIBRATE(X)) update_measurements(m, X_AXIS); if (ENABLED(HAS_Y_CENTER) && AXIS_CAN_CALIBRATE(Y)) update_measurements(m, Y_AXIS); if (AXIS_CAN_CALIBRATE(Z)) update_measurements(m, Z_AXIS); TERN_(HAS_I_CENTER, update_measurements(m, I_AXIS)); TERN_(HAS_J_CENTER, update_measurements(m, J_AXIS)); TERN_(HAS_K_CENTER, update_measurements(m, K_AXIS)); sync_plan_position(); } /** * Probe around the calibration object for all toolheads, adjusting the coordinate * system for the first nozzle and the nozzle offset for subsequent nozzles. * * m in/out - Measurement record, updated with new readings * uncertainty in - How far away from the object to begin probing */ inline void calibrate_all_toolheads(measurements_t &m, const float uncertainty) { TEMPORARY_BACKLASH_CORRECTION(all_on); TEMPORARY_BACKLASH_SMOOTHING(0.0f); HOTEND_LOOP() calibrate_toolhead(m, uncertainty, e); TERN_(HAS_HOTEND_OFFSET, normalize_hotend_offsets()); TERN_(HAS_MULTI_HOTEND, set_nozzle(m, 0)); } /** * Perform a full auto-calibration routine: * * 1) For each nozzle, touch top and sides of object to determine object position and * nozzle offsets. Do a fast but rough search over a wider area. * 2) With the first nozzle, touch top and sides of object to determine backlash values * for all axis (if BACKLASH_GCODE is enabled) * 3) For each nozzle, touch top and sides of object slowly to determine precise * position of object. Adjust coordinate system and nozzle offsets so probed object * location corresponds to known object location with a high degree of precision. */ inline void calibrate_all() { measurements_t m; TERN_(HAS_HOTEND_OFFSET, reset_hotend_offsets()); TEMPORARY_BACKLASH_CORRECTION(all_on); TEMPORARY_BACKLASH_SMOOTHING(0.0f); // Do a fast and rough calibration of the toolheads calibrate_all_toolheads(m, CALIBRATION_MEASUREMENT_UNKNOWN); TERN_(BACKLASH_GCODE, calibrate_backlash(m, CALIBRATION_MEASUREMENT_UNCERTAIN)); // Cycle the toolheads so the servos settle into their "natural" positions #if HAS_MULTI_HOTEND HOTEND_LOOP() set_nozzle(m, e); #endif // Do a slow and precise calibration of the toolheads calibrate_all_toolheads(m, CALIBRATION_MEASUREMENT_UNCERTAIN); current_position.x = X_CENTER; calibration_move(); // Park nozzle away from calibration object } /** * G425: Perform calibration with calibration object. * * B - Perform calibration of backlash only. * T<extruder> - Perform calibration of toolhead only. * V - Probe object and print position, error, backlash and hotend offset. * U - Uncertainty, how far to start probe away from the object (mm) * * no args - Perform entire calibration sequence (backlash + position on all toolheads) */ void GcodeSuite::G425() { #ifdef CALIBRATION_SCRIPT_PRE GcodeSuite::process_subcommands_now_P(PSTR(CALIBRATION_SCRIPT_PRE)); #endif if (homing_needed_error()) return; TEMPORARY_BED_LEVELING_STATE(false); SET_SOFT_ENDSTOP_LOOSE(true); measurements_t m; const float uncertainty = parser.floatval('U', CALIBRATION_MEASUREMENT_UNCERTAIN); if (parser.seen_test('B')) calibrate_backlash(m, uncertainty); else if (parser.seen_test('T')) calibrate_toolhead(m, uncertainty, parser.intval('T', active_extruder)); #if ENABLED(CALIBRATION_REPORTING) else if (parser.seen('V')) { probe_sides(m, uncertainty); SERIAL_EOL(); report_measured_faces(m); report_measured_center(m); report_measured_backlash(m); report_measured_nozzle_dimensions(m); report_measured_positional_error(m); #if HAS_HOTEND_OFFSET normalize_hotend_offsets(); report_hotend_offsets(); #endif } #endif else calibrate_all(); SET_SOFT_ENDSTOP_LOOSE(false); #ifdef CALIBRATION_SCRIPT_POST GcodeSuite::process_subcommands_now_P(PSTR(CALIBRATION_SCRIPT_POST)); #endif } #endif // CALIBRATION_GCODE
36.38911
148
0.705084
[ "object", "3d" ]
c8f0af9f25e1aa1a676e541c716bb1fdb42a9d68
15,620
cpp
C++
plugins/icp_relay_plugin/session.cpp
tianyalangzi/eocs
83ba0a8cdcdcdac0aad6726ffffd87f558133e0f
[ "MIT" ]
null
null
null
plugins/icp_relay_plugin/session.cpp
tianyalangzi/eocs
83ba0a8cdcdcdac0aad6726ffffd87f558133e0f
[ "MIT" ]
1
2019-01-03T07:36:43.000Z
2019-01-03T07:36:43.000Z
plugins/icp_relay_plugin/session.cpp
tianyalangzi/eocs
83ba0a8cdcdcdac0aad6726ffffd87f558133e0f
[ "MIT" ]
null
null
null
#include "session.hpp" #include <appbase/application.hpp> #include "icp_relay.hpp" namespace icp { // Creating session from server socket acceptance session::session(tcp::socket socket, relay_ptr relay) : ios_(socket.get_io_service()), resolver_(socket.get_io_service()), ws_(std::make_unique<ws::stream<tcp::socket>>(std::move(socket))), strand_(ws_->get_executor()), relay_(relay) { session_id_ = next_session_id(); set_socket_options(); ws_->binary(true); wlog("open session ${id}", ("id", session_id_)); } void session::do_accept() { ws_->async_accept(boost::asio::bind_executor(strand_, [this, self=shared_from_this()](boost::system::error_code ec) { if (ec) { return on_error(ec, "accept"); } do_hello(); do_read(); })); } // Creating outgoing session session::session(const string& peer, boost::asio::io_context& ioc, relay_ptr relay) : ios_(ioc), resolver_(ioc), ws_(std::make_unique<ws::stream<tcp::socket>>(ioc)), strand_(ws_->get_executor()), relay_(relay) { session_id_ = next_session_id(); ws_->binary(true); wlog("open session ${id}", ("id", session_id_)); peer_ = peer; auto c = peer.find(':'); remote_host_ = peer.substr(0, c); remote_port_ = peer.substr(c+1, peer.size()); } void session::do_connect() { resolver_.async_resolve(remote_host_, remote_port_, boost::asio::bind_executor(strand_, [this, self=shared_from_this()](boost::system::error_code ec, tcp::resolver::results_type results) { if (ec) { return on_error(ec, "resolve"); } // connect boost::asio::async_connect(ws_->next_layer(), results.begin(), results.end(), boost::asio::bind_executor(strand_, std::bind(&session::on_connect, self, std::placeholders::_1) ) ); }) ); } void session::on_connect(boost::system::error_code ec) { if (ec) { return on_error(ec, "connect"); } set_socket_options(); // handshake ws_->async_handshake(remote_host_, "/", boost::asio::bind_executor(strand_, [this, self=shared_from_this()](boost::system::error_code ec) { if (ec) { return on_error(ec, "handshake"); } do_hello(); do_read(); }) ); } session::~session() { wlog("close session ${n}", ("n", session_id_)); std::weak_ptr<relay> r = relay_; app().get_io_service().post([r, s=this] { if (auto relay = r.lock()) relay->on_session_close(s); }); } int session::next_session_id() { static int session_count = 0; return ++session_count; } void session::set_socket_options() { try { /** to minimize latency when sending short messages */ ws_->next_layer().set_option(boost::asio::ip::tcp::no_delay(true)); /** to minimize latency when sending large 1MB blocks, the send buffer should not have to * wait for an "ack", making this larger could result in higher latency for smaller urgent * messages. */ ws_->next_layer().set_option(boost::asio::socket_base::send_buffer_size(1024*1024)); ws_->next_layer().set_option(boost::asio::socket_base::receive_buffer_size(1024*1024)); } catch (...) { elog("uncaught exception on set socket options"); } } void session::on_error(boost::system::error_code ec, const char* what) { try { verify_strand_in_this_thread(strand_, __func__, __LINE__); elog("${w}: ${m}", ("w", what)("m", ec.message())); // TODO ws_->next_layer().close(); } catch (...) { elog("uncaught exception on close"); } } void session::close() { try { ws_->next_layer().close(); } catch (...) { elog("uncaught exception on close"); } } void session::post(std::function<void()> callback) { ios_.post(boost::asio::bind_executor(strand_, callback)); } void session::do_hello() { hello hello_msg; hello_msg.id = relay_->id_; hello_msg.chain_id = app().get_plugin<chain_plugin>().get_chain_id(); hello_msg.contract = relay_->local_contract_; hello_msg.peer_contract = relay_->peer_contract_; send(hello_msg); sent_remote_hello_ = true; } void session::do_read() { ws_->async_read(in_buffer_, boost::asio::bind_executor(strand_, [this, self=shared_from_this()](boost::system::error_code ec, std::size_t bytes_transferred) { if (ec == ws::error::closed) return on_error(ec, "close on read"); else if (ec) return on_error(ec, "read"); try { auto data = boost::asio::buffer_cast<char const*>(boost::beast::buffers_front(in_buffer_.data())); auto size = boost::asio::buffer_size(in_buffer_.data()); fc::datastream<const char*> ds(data, size); icp_message msg; fc::raw::unpack(ds, msg); on_message(msg); in_buffer_.consume(ds.tellp()); wait_on_app(); } catch (...) { wlog("close bad payload"); try { ws_->close(boost::beast::websocket::close_code::bad_payload); } catch ( ... ) { elog("uncaught exception on close"); } } }) ); } /** If we just call do_read here then this thread might run ahead of * the main thread, instead we post an event to main which will then * post a new read event when ready. * * This also keeps the "shared pointer" alive in the callback preventing * the connection from being closed. */ void session::wait_on_app() { app().get_io_service().post( boost::asio::bind_executor(strand_, [self = shared_from_this()] { self->do_read(); }) ); } bool session::send_ping() { auto delta_t = fc::time_point::now() - last_sent_ping_.sent; if (delta_t < fc::seconds(3)) return false; if (not local_head_.valid()) { // wlog("local head: ${h}", ("h", local_head_)); app().get_io_service().post( boost::asio::bind_executor(strand_, [this, self = shared_from_this()] { relay_->update_local_head(true); maybe_send_next_message(); }) ); last_sent_ping_.sent = fc::time_point::now(); return false; } if (last_sent_ping_.code == fc::sha256()) { last_sent_ping_.sent = fc::time_point::now(); last_sent_ping_.code = fc::sha256::hash(last_sent_ping_.sent); /// TODO: make this more random last_sent_ping_.head_instance = local_head_; send(last_sent_ping_); // wlog("send_ping"); } return true; } bool session::send_pong() { if (last_recv_ping_.code == fc::sha256()) return false; send(pong{fc::time_point::now(), last_recv_ping_.code}); last_recv_ping_.code = fc::sha256(); // reset return true; } void session::send() { try { verify_strand_in_this_thread(strand_, __func__, __LINE__); state_ = sending_state; ws_->async_write(boost::asio::buffer(out_buffer_), boost::asio::bind_executor(strand_, [this, self=shared_from_this()](boost::system::error_code ec, std::size_t bytes_transferred) { verify_strand_in_this_thread(strand_, __func__, __LINE__); if (ec) { ws_->next_layer().close(); return on_error(ec, "write"); } state_ = idle_state; out_buffer_.resize(0); maybe_send_next_message(); }) ); } FC_LOG_AND_RETHROW() } void session::send(const icp_message& msg) { try { auto ps = fc::raw::pack_size(msg); out_buffer_.resize(ps); fc::datastream<char*> ds(out_buffer_.data(), ps); fc::raw::pack(ds, msg); send(); } FC_LOG_AND_RETHROW() } void session::buffer_send(icp_message&& msg) { msg_buffer_.push_back(move(msg)); } void session::maybe_send_next_message() { verify_strand_in_this_thread(strand_, __func__, __LINE__); if (state_ == sending_state) return; // in process of sending if (out_buffer_.size()) return; // in process of sending if (!recv_remote_hello_ || !sent_remote_hello_) return; if (send_pong()) return; if (send_ping()) return; // ilog("msg buffer count: ${n}", ("n", msg_buffer_.size())); if (not msg_buffer_.empty()) { auto msg = msg_buffer_.front(); send(msg); msg_buffer_.pop_front(); } // TODO } void session::update_local_head(const head& h) { local_head_ = h; } void session::on_message(const icp_message& msg) { try { switch (msg.which()) { case icp_message::tag<hello>::value: // wlog("on hello"); on(msg.get<hello>()); break; case icp_message::tag<ping>::value: // wlog("on ping"); on(msg.get<ping>()); break; case icp_message::tag<pong>::value: // wlog("on pong"); on(msg.get<pong>()); break; case icp_message::tag<channel_seed>::value: // wlog("on channel_seed"); on(msg.get<channel_seed>()); break; case icp_message::tag<head_notice>::value: // wlog("on head_notice"); on(msg.get<head_notice>()); break; case icp_message::tag<block_header_with_merkle_path>::value: // wlog("on block_header_with_merkle_path"); on(msg.get<block_header_with_merkle_path>()); break; case icp_message::tag<icp_actions>::value: // wlog("on icp_actions"); on(msg.get<icp_actions>()); break; case icp_message::tag<packet_receipt_request>::value: // wlog("on packet_receipt_request"); on(msg.get<packet_receipt_request>()); break; default: wlog("bad message received"); ws_->close(boost::beast::websocket::close_code::bad_payload); return; } maybe_send_next_message(); } catch (const fc::exception& e) { elog("${e}", ("e", e.to_detail_string())); ws_->close(boost::beast::websocket::close_code::bad_payload); } } void session::check_for_redundant_connection() { app().get_io_service().post([self=shared_from_this()] { self->relay_->for_each_session([self](auto s) { if (s != self && s->peer_id_ == self->peer_id_) { self->close(); } }); }); } void session::on(const hello& hi) { // ilog("received hello: peer id ${id}, peer chain id ${chain_id}, peer icp contract ${contract}, refer to my contract ${peer_contract}", ("id", hi.id)("chain_id", hi.chain_id)("contract", hi.contract)("peer_contract", hi.peer_contract)); recv_remote_hello_ = true; if (hi.chain_id != relay_->peer_chain_id_) { elog("bad peer: wrong chain id"); return close(); } if (hi.id == relay_->id_) { // connect to self return close(); } peer_id_ = hi.id; check_for_redundant_connection(); } void session::on(const ping& p) { last_recv_ping_ = p; last_recv_ping_time_ = fc::time_point::now(); // wlog("on ping: ${v}", ("v", p.head.valid())); if (not p.head_instance.valid()) return; app().get_io_service().post([=, self=shared_from_this()] { if (not relay_->peer_head_.valid()) { relay_->clear_cache_block_state(); } relay_->peer_head_ = p.head_instance; // TODO: check validity }); } void session::on(const pong& p) { if (p.code != last_sent_ping_.code) { close(); return; } last_sent_ping_.code = fc::sha256(); // reset } void session::on(const channel_seed& s) { auto data = fc::raw::pack(bytes_data{fc::raw::pack(s.seed)}); app().get_io_service().post([=, self=shared_from_this()] { action a; a.name = ACTION_OPENCHANNEL; a.data = data; // ilog("data: ${d}", ("d", a.data)); a.authorization.push_back(permission_level{relay_->local_contract_, permission_name("active")}); relay_->push_transaction(vector<action>{a}); }); } void session::on(const head_notice& h) { // wlog("recv head: ${v}", ("v", h.head.valid())); if (not h.head_instance.valid()) return; app().get_io_service().post([=, self=shared_from_this()] { if (not relay_->peer_head_.valid()) { relay_->clear_cache_block_state(); } relay_->peer_head_ = h.head_instance; // TODO: check validity }); } void session::on(const block_header_with_merkle_path& b) { auto ro = relay_->get_read_only_api(); auto head = ro.get_head(); if (not head) { elog("local head not found, maybe icp channel not opened"); return; } auto first_num = b.block_header.block_num; if (not b.merkle_path.empty()) { first_num = block_header::num_from_id(b.merkle_path.front()); } // wlog("block_header_with_merkle_path: ${n1} -> ${n2}, head: ${h}", ("n1", first_num)("n2", b.block_header.block_num)("h", head->head_block_num)); if (first_num != head->head_block_num) { // elog("unlinkable block: has ${has}, got ${got}", ("has", head->head_block_num)("got", first_num)); return; } // TODO: more check and workaround auto data = fc::raw::pack(bytes_data{fc::raw::pack(b)}); app().get_io_service().post([=, self=shared_from_this()] { action a; a.name = ACTION_ADDBLOCKS; a.data = data; relay_->push_transaction(vector<action>{a}, [this, self](bool success) { if (success) relay_->update_local_head(); }); }); } void session::on(const icp_actions& ia) { auto block_id = ia.block_header_instance.id(); auto block_num = ia.block_header_instance.block_num(); recv_transaction rt{block_num, block_id, ia.start_packet_seq, ia.start_receipt_seq}; auto ro = relay_->get_read_only_api(); auto r = ro.get_block(read_only::get_block_params{block_id}); if (r.block.is_null()) { // not exist auto data = fc::raw::pack(bytes_data{fc::raw::pack(ia.block_header_instance)}); action a; a.name = ACTION_ADDBLOCK; a.data = data; rt.action_add_block = a; } for (auto& p: ia.packet_actions) { auto& s = p.second; action a; a.name = s.peer_action; a.data = fc::raw::pack(icp_action{fc::raw::pack(s.action_instance), fc::raw::pack(s.action_receipt_instance), block_id, fc::raw::pack(ia.action_digests)}); rt.packet_actions.emplace_back(p.first, a); } for (auto& r: ia.receipt_actions) { auto& s = r.second; action a; a.name = s.peer_action; a.data = fc::raw::pack(icp_action{fc::raw::pack(s.action_instance), fc::raw::pack(s.action_receipt_instance), block_id, fc::raw::pack(ia.action_digests)}); rt.receipt_actions.emplace_back(r.first, a); } for (auto& c: ia.receiptend_actions) { action a; a.name = c.peer_action; a.data = fc::raw::pack(icp_action{fc::raw::pack(c.action_instance), fc::raw::pack(c.action_receipt_instance), block_id, fc::raw::pack(ia.action_digests)}); rt.receiptend_actions.emplace_back(a); } app().get_io_service().post([=, self=shared_from_this()]() mutable { relay_->handle_icp_actions(move(rt)); }); } void session::on(const packet_receipt_request& req) { // TOOD: pre-check app().get_io_service().post([=, self=shared_from_this()] { action a; a.name = ACTION_GENPROOF; a.data = fc::raw::pack(req); relay_->push_transaction(vector<action>{a}); }); } }
31.115538
241
0.604481
[ "vector" ]
c8f20accf01a1ed44242a6a3a168e49965a2f97d
8,261
cc
C++
chrome/browser/ui/extensions/application_launch_web_app.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-11-28T10:46:52.000Z
2019-11-28T10:46:52.000Z
chrome/browser/ui/extensions/application_launch_web_app.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/extensions/application_launch_web_app.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/extensions/application_launch_web_app.h" #include <string> #include "apps/launcher.h" #include "base/metrics/histogram.h" #include "chrome/browser/app_mode/app_mode_utils.h" #include "chrome/browser/extensions/launch_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/extensions/app_launch_params.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/web_applications/web_app.h" #include "chrome/common/extensions/manifest_handlers/app_launch_info.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/renderer_preferences.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/extension.h" #include "ui/base/window_open_disposition.h" #include "ui/gfx/geometry/rect.h" #if defined(OS_MACOSX) #include "chrome/browser/ui/browser_commands_mac.h" #endif using content::WebContents; using extensions::Extension; using extensions::ExtensionPrefs; using extensions::ExtensionRegistry; namespace { const Extension* GetExtension(const AppLaunchParams& params) { if (params.extension_id.empty()) return NULL; ExtensionRegistry* registry = ExtensionRegistry::Get(params.profile); return registry->GetExtensionById(params.extension_id, ExtensionRegistry::ENABLED | ExtensionRegistry::DISABLED | ExtensionRegistry::TERMINATED); } ui::WindowShowState DetermineWindowShowState( Profile* profile, extensions::LaunchContainer container, const Extension* extension) { if (!extension || container != extensions::LAUNCH_CONTAINER_WINDOW) return ui::SHOW_STATE_DEFAULT; if (chrome::IsRunningInForcedAppMode()) return ui::SHOW_STATE_FULLSCREEN; #if defined(USE_ASH) // In ash, LAUNCH_TYPE_FULLSCREEN launches in a maximized app window and // LAUNCH_TYPE_WINDOW launches in a normal app window. extensions::LaunchType launch_type = extensions::GetLaunchType(ExtensionPrefs::Get(profile), extension); if (launch_type == extensions::LAUNCH_TYPE_FULLSCREEN) return ui::SHOW_STATE_MAXIMIZED; else if (launch_type == extensions::LAUNCH_TYPE_WINDOW) return ui::SHOW_STATE_NORMAL; #endif return ui::SHOW_STATE_DEFAULT; } } // namespace WebContents* OpenWebAppWindow(const AppLaunchParams& params, const GURL& url) { Profile* const profile = params.profile; const Extension* const extension = GetExtension(params); std::string app_name = extension ? web_app::GenerateApplicationNameFromExtensionId(extension->id()) : web_app::GenerateApplicationNameFromURL(url); gfx::Rect initial_bounds; if (!params.override_bounds.IsEmpty()) { initial_bounds = params.override_bounds; } else if (extension) { initial_bounds.set_width( extensions::AppLaunchInfo::GetLaunchWidth(extension)); initial_bounds.set_height( extensions::AppLaunchInfo::GetLaunchHeight(extension)); } Browser::CreateParams browser_params( Browser::CreateParams::CreateForApp(app_name, true /* trusted_source */, initial_bounds, profile, params.desktop_type)); browser_params.initial_show_state = DetermineWindowShowState(profile, params.container, extension); Browser* browser = new Browser(browser_params); WebContents* web_contents = chrome::AddSelectedTabWithURL( browser, url, ui::PAGE_TRANSITION_AUTO_TOPLEVEL); web_contents->GetMutableRendererPrefs()->can_accept_load_drops = false; web_contents->GetRenderViewHost()->SyncRendererPrefs(); browser->window()->Show(); // TODO(jcampan): http://crbug.com/8123 we should not need to set the initial // focus explicitly. web_contents->SetInitialFocus(); return web_contents; } WebContents* OpenWebAppTab(const AppLaunchParams& launch_params, const GURL& url) { const Extension* extension = GetExtension(launch_params); CHECK(extension); Profile* const profile = launch_params.profile; WindowOpenDisposition disposition = launch_params.disposition; Browser* browser = chrome::FindTabbedBrowser(profile, false, launch_params.desktop_type); WebContents* contents = NULL; if (!browser) { // No browser for this profile, need to open a new one. browser = new Browser(Browser::CreateParams(Browser::TYPE_TABBED, profile, launch_params.desktop_type)); browser->window()->Show(); // There's no current tab in this browser window, so add a new one. disposition = NEW_FOREGROUND_TAB; } else { // For existing browser, ensure its window is shown and activated. browser->window()->Show(); browser->window()->Activate(); } extensions::LaunchType launch_type = extensions::GetLaunchType(ExtensionPrefs::Get(profile), extension); UMA_HISTOGRAM_ENUMERATION("Extensions.AppTabLaunchType", launch_type, 100); int add_type = TabStripModel::ADD_ACTIVE; if (launch_type == extensions::LAUNCH_TYPE_PINNED) add_type |= TabStripModel::ADD_PINNED; chrome::NavigateParams params(browser, url, ui::PAGE_TRANSITION_AUTO_TOPLEVEL); params.tabstrip_add_types = add_type; params.disposition = disposition; if (disposition == CURRENT_TAB) { WebContents* existing_tab = browser->tab_strip_model()->GetActiveWebContents(); TabStripModel* model = browser->tab_strip_model(); int tab_index = model->GetIndexOfWebContents(existing_tab); existing_tab->OpenURL(content::OpenURLParams( url, content::Referrer(existing_tab->GetURL(), blink::WebReferrerPolicyDefault), disposition, ui::PAGE_TRANSITION_LINK, false)); // Reset existing_tab as OpenURL() may have clobbered it. existing_tab = browser->tab_strip_model()->GetActiveWebContents(); if (params.tabstrip_add_types & TabStripModel::ADD_PINNED) { model->SetTabPinned(tab_index, true); // Pinning may have moved the tab. tab_index = model->GetIndexOfWebContents(existing_tab); } if (params.tabstrip_add_types & TabStripModel::ADD_ACTIVE) model->ActivateTabAt(tab_index, true); contents = existing_tab; } else { chrome::Navigate(&params); contents = params.target_contents; } // On Chrome OS the host desktop type for a browser window is always set to // HOST_DESKTOP_TYPE_ASH. On Windows 8 it is only the case for Chrome ASH // in metro mode. if (browser->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH) { // In ash, LAUNCH_FULLSCREEN launches in the OpenApplicationWindow function // i.e. it should not reach here. DCHECK(launch_type != extensions::LAUNCH_TYPE_FULLSCREEN); } else { // TODO(skerner): If we are already in full screen mode, and the user // set the app to open as a regular or pinned tab, what should happen? // Today we open the tab, but stay in full screen mode. Should we leave // full screen mode in this case? if (launch_type == extensions::LAUNCH_TYPE_FULLSCREEN && !browser->window()->IsFullscreen()) { #if defined(OS_MACOSX) chrome::ToggleFullscreenWithToolbarOrFallback(browser); #else chrome::ToggleFullscreenMode(browser); #endif } } return contents; }
39.151659
80
0.688658
[ "geometry", "model" ]
c8f2a91be3a509b9cc8921aebb18eb12072f95fd
4,064
cpp
C++
src/caffe/layers/siamese_logistic_loss_layer.cpp
NicoleWang/caffe-for-rfcn
fafed9bac1b1ccb46ac11d1790f1ca4f86ce0d0d
[ "BSD-2-Clause" ]
null
null
null
src/caffe/layers/siamese_logistic_loss_layer.cpp
NicoleWang/caffe-for-rfcn
fafed9bac1b1ccb46ac11d1790f1ca4f86ce0d0d
[ "BSD-2-Clause" ]
null
null
null
src/caffe/layers/siamese_logistic_loss_layer.cpp
NicoleWang/caffe-for-rfcn
fafed9bac1b1ccb46ac11d1790f1ca4f86ce0d0d
[ "BSD-2-Clause" ]
null
null
null
#include <algorithm> #include <cmath> #include <vector> #include "caffe/layers/siamese_logistic_loss_layer.hpp" #include "caffe/util/math_functions.hpp" #define DEBUG_INFO #undef DEBUG_INFO namespace caffe { template <typename Dtype> void SiameseLogisticLossLayer<Dtype>::Reshape( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { LossLayer<Dtype>::Reshape(bottom, top); int count = bottom[0]->count(); CHECK_EQ(bottom[0]->count(), bottom[1]->count()); eyv_.ReshapeLike(*bottom[0]); } template <typename Dtype> void SiameseLogisticLossLayer<Dtype>::Forward_cpu( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { //bottom[1]->Reshape(bottom[0]->count(), 1, 1, 1); Dtype* bottom_data = bottom[0]->mutable_cpu_data(); const Dtype* bottom_label = bottom[1]->cpu_data(); const Dtype* weight_data = bottom[2]->cpu_data(); #ifdef DEBUG_INFO std::cout << "bottom data: " << std::endl; for (int i = 0; i < bottom[0]->count(); ++i){ std::cout << i << ": " << bottom_data[i] << " "; } std::cout << std::endl; #endif #if 0 std::cout << "label data: " << std::endl; for (int i = 0; i < bottom[0]->count(); ++i){ std::cout << i << ": " << bottom_label[i] << " "; } std::cout << std::endl; #endif // Dtype* yv_data = new Dtype[bottom[0]->count()]; Dtype* yv_data = eyv_.mutable_cpu_data(); caffe_mul<Dtype>(bottom[0]->count(), bottom_data, bottom_label, yv_data); caffe_scal<Dtype>(bottom[0]->count(), (Dtype)(-1.0), yv_data); caffe_exp<Dtype>(bottom[0]->count(), yv_data, yv_data); //caffe_add_scalar<Dtype>(bottom[0]->count(), (Dtype)1.0, yv_data); int num = bottom[0]->num(); int dim = bottom[0]->count() / bottom[0]->num(); Dtype loss = 0; for (int i = 0; i < bottom[0]->count(); ++i) { loss += (weight_data[i] * log(yv_data[i] + 1)); } top[0]->mutable_cpu_data()[0] = (Dtype)(1.0) * loss / bottom[0]->num(); //delete [] yv_data; } template <typename Dtype> void SiameseLogisticLossLayer<Dtype>::Backward_cpu( const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[1]) { LOG(FATAL) << this->type() << " Layer cannot backpropagate to label inputs."; } Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); if (propagate_down[0]) { Dtype* bottom_data = bottom[0]->mutable_cpu_data(); const Dtype* bottom_label = bottom[1]->cpu_data(); const Dtype* weight_data = bottom[2]->cpu_data(); //Dtype* yv_data = new Dtype[bottom[0]->count()]; const Dtype* yv_data = eyv_.cpu_data(); //caffe_mul<Dtype>(bottom[0]->count(), bottom_data, bottom_label, yv_data); //caffe_exp<Dtype>(bottom[0]->count(), yv_data, yv_data); //caffe_add_scalar<Dtype>(bottom[0]->count(), (Dtype)1.0, yv_data); int num = bottom[0]->num(); int dim = bottom[0]->count() / bottom[0]->num(); caffe_set(bottom[0]->count(), Dtype(0), bottom_diff); const Dtype scale = top[0]->cpu_diff()[0]; for (int i = 0; i < bottom[0]->count(); ++i) { Dtype label = bottom_label[i]; bottom_diff[i] = weight_data[i] * (Dtype)(-1.0) * label * yv_data[i] / (yv_data[i] + 1) / bottom[0]->num(); //std::cout << "label: " << label << " bottom data: " << bottom_data[i] << " diff: " << bottom_diff[i] << std::endl; } //delete [] yv_data; } #if 0 std::cout << "bottom diff: " << std::endl; for (int i = 0; i < bottom[0]->count(); ++i){ std::cout << i << ": " << bottom_diff[i] << " "; } std::cout << std::endl; #endif #if 0 std::cout << "BACK DIFF: " << std::endl; const Dtype* tdiff = bottom[0]->cpu_diff(); Dtype sum = 0.0; for (int i = 0; i < bottom[0]->count(); ++i){ sum += (tdiff[i] * tdiff[i]); std::cout << tdiff[i] << " " ; } std::cout << "loss diff: " << std::sqrt(sum) << std::endl; #endif } INSTANTIATE_CLASS(SiameseLogisticLossLayer); REGISTER_LAYER_CLASS(SiameseLogisticLoss); } // namespace caffe
34.440678
125
0.601378
[ "vector" ]
c8f95dab5ff1e0f542ca8afc5dfa9578f87ea4c8
2,526
hh
C++
src/blas/axpy.hh
hmatuschek/linalg
b4b8337ba001b24572f13349cc5804a416bfe5a7
[ "MIT" ]
1
2016-05-24T15:27:52.000Z
2016-05-24T15:27:52.000Z
src/blas/axpy.hh
hmatuschek/linalg
b4b8337ba001b24572f13349cc5804a416bfe5a7
[ "MIT" ]
null
null
null
src/blas/axpy.hh
hmatuschek/linalg
b4b8337ba001b24572f13349cc5804a416bfe5a7
[ "MIT" ]
null
null
null
#ifndef __LINALG_BLAS_AXPY_HH__ #define __LINALG_BLAS_AXPY_HH__ #include <vector.hh> #include <simd.hh> namespace Linalg { namespace Blas { /** * SIMD implementation of @c Linalg::Blas::axpy for dense vectors. * * @ingroup blas_internal */ template <class Scalar> inline void __axpy_dense(const Scalar &alpha, size_t N, const Scalar *x, Scalar *y) throw () { typename SIMDTraits<Scalar>::uvector alpha_vec; const typename SIMDTraits<Scalar>::uvector *x_ptr = (const typename SIMDTraits<Scalar>::uvector *)x; typename SIMDTraits<Scalar>::uvector *y_ptr = (typename SIMDTraits<Scalar>::uvector *)y; size_t N_elm = SIMDTraits<Scalar>::num_elements; size_t N_steps = N/N_elm; size_t N_rem = N%N_elm; // Initialize alpha_vector for (size_t i=0; i<N_elm; i++) alpha_vec.d[i] = alpha; // Perform on vectors: for (size_t i=0; i<N_steps; i++, x_ptr++, y_ptr++) y_ptr->v += alpha_vec.v * x_ptr->v; // Perform on remaining elements for (size_t i=0; i<N_rem; i++) y_ptr->d[i] += alpha*x_ptr->d[i]; } /** * Direct implementation of @c Linalg::Blas::axpy for non-dense vectors. * * @ingroup blas_internal */ template <class Scalar> inline void __axpy_incremental(const Scalar &alpha, size_t N, const Scalar *x, size_t x_inc, Scalar *y, size_t y_inc) throw () { for (size_t i=0; i<N; i++, x+=x_inc, y+=y_inc) { (*y) += alpha * (*x); } } /** * Computes \f$y' = \alpha x + y\f$ with x,y being vectors of same dimension. * * This function calls @c Linalg::Blas::__axpy_dense if both vectors are stored densly, otherwise * @c Linalg::Blas::__axpy_incremental is called. * * @note In contrast to @c Linalg::Blas::axpy, this function does no dimension check on the vectors. * * @ingroup blas_internal */ template<class Scalar> inline void __axpy(const Scalar &alpha, const Vector<Scalar> &x, Vector<Scalar> &y) throw () { if (0.0 == alpha) return; if ( (1 == x.strides()[0]) && (1 == y.strides()[0])) __axpy_dense(alpha, x.dim(), x.ptr(), y.ptr()); else __axpy_incremental(alpha, x.dim(), x.ptr(), x.strides()[0], y.ptr(), y.strides()[0]); } /** * Computes \f$y' = \alpha x + y\f$ with x,y being vectors of same dimension. * * @throws ShapeError If dim(x) != dim(y). * * @ingroup blas1 */ template<class Scalar> inline void axpy(const Scalar &alpha, const Vector<Scalar> &x, Vector<Scalar> &y) throw (ShapeError) { LINALG_SHAPE_ASSERT(x.dim() == y.dim()); __axpy(alpha, x, y); } } } #endif // __LINALG_BLAS_AXPY_HH__
24.288462
102
0.659541
[ "vector" ]
c8fe0afa66a3d632fcbaa9e6d41de3bf4785156c
1,358
hpp
C++
src/ChemicalFormula.hpp
pavoljuhas/liga
53896275e9df0a916ba6219b407ce3777ce7ba2d
[ "BSD-3-Clause" ]
1
2021-06-02T18:56:27.000Z
2021-06-02T18:56:27.000Z
src/ChemicalFormula.hpp
pavoljuhas/liga
53896275e9df0a916ba6219b407ce3777ce7ba2d
[ "BSD-3-Clause" ]
2
2021-06-01T18:08:36.000Z
2022-01-13T18:28:19.000Z
src/ChemicalFormula.hpp
pavoljuhas/liga
53896275e9df0a916ba6219b407ce3777ce7ba2d
[ "BSD-3-Clause" ]
3
2021-05-24T00:30:04.000Z
2021-11-13T01:13:42.000Z
/*********************************************************************** * * Liga Algorithm for structure determination from pair distances * Pavol Juhas * (c) 2009 Trustees of the Columbia University * in the City of New York. All rights reserved. * * See AUTHORS.txt for a list of people who contributed. * See LICENSE.txt for license information. * ************************************************************************ * * ChemicalFormula * * Comments: Storage and manipulation of ChemicalFormula. * ***********************************************************************/ #ifndef CHEMICALFORMULA_HPP_INCLUDED #define CHEMICALFORMULA_HPP_INCLUDED #include <utility> #include <vector> #include <string> class ChemicalFormula : public std::vector< std::pair<std::string,int> > { public: // Constructors ChemicalFormula(); ChemicalFormula(const std::string&); // Methods /// total count of elements int countElements() const; /// expand to a vector of elements std::vector<std::string> expand() const; /// initialize from a string void fromString(const std::string&); /// convert to a string std::string toString(std::string separator="") const; }; #endif // CHEMICALFORMULA_HPP_INCLUDED
28.291667
72
0.544183
[ "vector" ]
7401552525c5b3a8696a7e5168e2f1b19abb4a4c
6,733
hpp
C++
openstudiocore/src/analysis/DakotaParametersFile_Impl.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/analysis/DakotaParametersFile_Impl.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/analysis/DakotaParametersFile_Impl.hpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #ifndef ANALYSIS_DAKOTAPARAMETERSFILE_IMPL_HPP #define ANALYSIS_DAKOTAPARAMETERSFILE_IMPL_HPP #include "AnalysisAPI.hpp" #include "DakotaParametersFile.hpp" #include <boost/regex.hpp> namespace openstudio { namespace analysis { class DakotaParametersFile; namespace detail { /** DakotaParametersFile_Impl is the implementation class for DakotaParametersFile. */ class ANALYSIS_API DakotaParametersFile_Impl : public std::enable_shared_from_this<DakotaParametersFile_Impl> { public: /** @name Constructors and Destructors */ //@{ DakotaParametersFile_Impl(std::istream& is); //@} /** @name Getters */ //@{ int numVariables() const; int numContinuousDesignVariables() const; int numDiscreteDesignIntegerVariables() const; std::vector<double> continuousDesignVariableValues() const; std::vector<double> uncertainNormalVariableValues() const; std::vector<double> uncertainLognormalVariableValues() const; std::vector<double> uncertainUniformVariableValues() const; std::vector<double> uncertainLoguniformVariableValues() const; std::vector<double> uncertainTriangularVariableValues() const; std::vector<double> uncertainExponentialVariableValues() const; std::vector<double> uncertainBetaVariableValues() const; std::vector<double> uncertainGammaVariableValues() const; std::vector<double> uncertainGumbelVariableValues() const; std::vector<double> uncertainFrechetVariableValues() const; std::vector<double> uncertainWeibullVariableValues() const; std::vector<double> uncertainHistogramBinVariableValues() const; std::vector<int> discreteDesignIntegerVariableValues() const; std::vector<int> uncertainPoissonVariableValues() const; std::vector<int> uncertainBinomialVariableValues() const; std::vector<int> uncertainNegativeBinomialVariableValues() const; std::vector<int> uncertainGeometricVariableValues() const; std::vector<int> uncertainHypergeometricVariableValues() const; std::vector<int> uncertainHistogramPointVariableValues() const; int numFunctions() const; /** Return the string description of function i, index starting at 0. */ DakotaFunctionType getFunctionType(int i) const; /** Returns true if Dakota expects to receive the value of function i, index starting at 0. */ bool getFunctionValueRequired(int i) const; //@} /** @name Type Casting */ //@{ /** Get a public object that wraps this impl.*/ template<typename T> T getPublicObject() const { T result(std::dynamic_pointer_cast<typename T::ImplType>( std::const_pointer_cast<DakotaParametersFile_Impl>(shared_from_this()))); return result; } //@} private: REGISTER_LOGGER("openstudio.analysis.DakotaParametersFile"); std::vector<double> m_continuousDesignVariableValues; std::vector<int> m_discreteDesignIntegerVariableValues; std::vector<double> m_uncertainNormalVariableValues; std::vector<double> m_uncertainLognormalVariableValues; std::vector<double> m_uncertainUniformVariableValues; std::vector<double> m_uncertainLoguniformVariableValues; std::vector<double> m_uncertainTriangularVariableValues; std::vector<double> m_uncertainExponentialVariableValues; std::vector<double> m_uncertainBetaVariableValues; std::vector<double> m_uncertainGammaVariableValues; std::vector<double> m_uncertainGumbelVariableValues; std::vector<double> m_uncertainFrechetVariableValues; std::vector<double> m_uncertainWeibullVariableValues; std::vector<double> m_uncertainHistogramBinVariableValues; std::vector<int> m_uncertainPoissonVariableValues; std::vector<int> m_uncertainBinomialVariableValues; std::vector<int> m_uncertainNegativeBinomialVariableValues; std::vector<int> m_uncertainGeometricVariableValues; std::vector<int> m_uncertainHypergeometricVariableValues; std::vector<int> m_uncertainHistogramPointVariableValues; std::vector< std::pair<DakotaFunctionType, int> > m_functionASVs; bool load(std::istream& is); boost::regex variablesRegex() const; boost::regex continuousDesignVariableRegex() const; boost::regex uncertainNormalVariableRegex() const; boost::regex uncertainLognormalVariableRegex() const; boost::regex uncertainUniformVariableRegex() const; boost::regex uncertainLoguniformVariableRegex() const; boost::regex uncertainTriangularVariableRegex() const; boost::regex uncertainExponentialVariableRegex() const; boost::regex uncertainBetaVariableRegex() const; boost::regex uncertainGammaVariableRegex() const; boost::regex uncertainGumbelVariableRegex() const; boost::regex uncertainFrechetVariableRegex() const; boost::regex uncertainWeibullVariableRegex() const; boost::regex uncertainHistogramBinVariableRegex() const; boost::regex discreteDesignIntegerVariableRegex() const; boost::regex uncertainPoissonVariableRegex() const; boost::regex uncertainBinomialVariableRegex() const; boost::regex uncertainNegativeBinomialVariableRegex() const; boost::regex uncertainGeometricVariableRegex() const; boost::regex uncertainHypergeometricVariableRegex() const; boost::regex uncertainHistogramPointVariableRegex() const; boost::regex functionsRegex() const; boost::regex functionASVRegex() const; }; } // detail } // analysis } // openstudio #endif // ANALYSIS_DAKOTAPARAMETERSFILE_IMPL_HPP
38.695402
114
0.717214
[ "object", "vector" ]
740529fe4b7a3e2e503c19bd1d704126c648732d
17,857
cpp
C++
aten/src/ATen/native/Histogram.cpp
abishekvashok/pytorch
d4ae7896554d156732de34c3d3600050f9cb18ec
[ "Intel" ]
1
2020-11-18T11:52:35.000Z
2020-11-18T11:52:35.000Z
aten/src/ATen/native/Histogram.cpp
abishekvashok/pytorch
d4ae7896554d156732de34c3d3600050f9cb18ec
[ "Intel" ]
1
2021-04-07T18:15:29.000Z
2021-04-07T18:15:29.000Z
aten/src/ATen/native/Histogram.cpp
abishekvashok/pytorch
d4ae7896554d156732de34c3d3600050f9cb18ec
[ "Intel" ]
null
null
null
#include <ATen/ATen.h> #include <ATen/Dispatch.h> #include <ATen/NativeFunctions.h> #include <ATen/native/Histogram.h> #include <ATen/native/Resize.h> #include <numeric> #include <tuple> #include <vector> #include <functional> #include <c10/util/ArrayRef.h> #include <c10/core/ScalarType.h> #include <c10/core/DefaultDtype.h> /* Implements a numpy-like histogramdd function running on cpu * https://numpy.org/doc/stable/reference/generated/numpy.histogramdd.html * * See the docstr for torch.histogramdd in torch/functional.py for further explanation. * * - torch.histogramdd(input, bins, range=None, weight=None, density=False) * input - tensor with shape (M, N). input is interpreted as M coordinates in N-dimensional space. * If a tensor with more than 2 dimensions is passed, all but the last dimension will be flattened. * bins - int[] of length N or tensor list of length N. If int[], defines the number of equal-width bins * in each dimension. If tensor list, defines the sequences of bin edges, including rightmost edges, * for each dimension. * range - float[] of length 2 * N, optional. If specified, defines the leftmost and rightmost bin edges * for each dimension. * weight - tensor, optional. If provided, weight should have the same shape as input excluding its last dimension. * Each N-dimensional value in input contributes its associated weight towards its bin's result. * If weight is not specified, each value has weight 1 by default. * density - bool, optional. If false (default), the result will contain the total count (weight) in each bin. * If True, each count (weight) is divided by the total count (total weight), then divided by the * volume of its associated bin. * * Returns: * hist - N-dimensional tensor containing the values of the histogram. * bin_edges - tensor list of length N containing the edges of the histogram bins in each dimension. * Bins include their left edge and exclude their right edge, with the exception of the * rightmost bin in each dimension which includes both of its edges. * * Restrictions are defined in histogram_check_inputs() and in select_outer_bin_edges(). */ namespace at { namespace native { DEFINE_DISPATCH(histogramdd_stub); DEFINE_DISPATCH(histogramdd_linear_stub); namespace { /* Checks properties of input tensors input, bins, and weight. */ void histogramdd_check_inputs(const Tensor& input, const TensorList& bins, const c10::optional<Tensor>& weight) { TORCH_CHECK(input.dim() >= 2, "torch.histogramdd: input tensor should have at least 2 dimensions, but got ", input.dim()); const int64_t N = input.size(-1); TORCH_CHECK(bins.size() == N, "torch.histogramdd: expected ", N, " sequences of bin edges for a ", N, "-dimensional histogram but got ", bins.size()); auto input_dtype = input.dtype(); for (int64_t dim = 0; dim < N; dim++) { const Tensor& dim_bins = bins[dim]; auto bins_dtype = dim_bins.dtype(); TORCH_CHECK(input_dtype == bins_dtype, "torch.histogramdd: input tensor and bins tensors should", " have the same dtype, but got input with dtype ", input_dtype, " and bins for dimension ", dim, " with dtype ", bins_dtype); const int64_t dim_bins_dim = dim_bins.dim(); TORCH_CHECK(dim_bins_dim == 1, "torch.histogramdd: bins tensor should have one dimension,", " but got ", dim_bins_dim, " dimensions in the bins tensor for dimension ", dim); const int64_t numel = dim_bins.numel(); TORCH_CHECK(numel > 0, "torch.histogramdd: bins tensor should have at least 1 element,", " but got ", numel, " elements in the bins tensor for dimension ", dim); } if (weight.has_value()) { TORCH_CHECK(input.dtype() == weight.value().dtype(), "torch.histogramdd: if weight tensor is provided," " input tensor and weight tensor should have the same dtype, but got input(", input.dtype(), ")", ", and weight(", weight.value().dtype(), ")"); /* If a weight tensor is provided, we expect its shape to match that of * the input tensor excluding its innermost dimension N. */ auto input_sizes = input.sizes().vec(); input_sizes.pop_back(); auto weight_sizes = weight.value().sizes().vec(); if (weight_sizes.empty()) { // correctly handle scalars weight_sizes = {1}; } TORCH_CHECK(input_sizes == weight_sizes, "torch.histogramdd: if weight tensor is provided it should have" " the same shape as the input tensor excluding its innermost dimension, but got input with shape ", input.sizes(), " and weight with shape ", weight.value().sizes()); } } /* Checks properties of output tensors hist and bin_edges, then resizes them. */ void histogramdd_prepare_out(const Tensor& input, const std::vector<int64_t>& bin_ct, const Tensor& hist, const TensorList& bin_edges) { const int64_t N = input.size(-1); TORCH_INTERNAL_ASSERT((int64_t)bin_ct.size() == N); TORCH_INTERNAL_ASSERT((int64_t)bin_edges.size() == N); TORCH_CHECK(input.dtype() == hist.dtype(), "torch.histogram: input tensor and hist tensor should", " have the same dtype, but got input ", input.dtype(), " and hist ", hist.dtype()); for (int64_t dim = 0; dim < N; dim++) { TORCH_CHECK(input.dtype() == bin_edges[dim].dtype(), "torch.histogram: input tensor and bin_edges tensor should", " have the same dtype, but got input ", input.dtype(), " and bin_edges ", bin_edges[dim].dtype(), " for dimension ", dim); TORCH_CHECK(bin_ct[dim] > 0, "torch.histogram(): bins must be > 0, but got ", bin_ct[dim], " for dimension ", dim); at::native::resize_output(bin_edges[dim], bin_ct[dim] + 1); } at::native::resize_output(hist, bin_ct); } void histogramdd_prepare_out(const Tensor& input, TensorList bins, const Tensor& hist, const TensorList& bin_edges) { std::vector<int64_t> bin_ct(bins.size()); std::transform(bins.begin(), bins.end(), bin_ct.begin(), [](Tensor t) { return t.numel() - 1; }); histogramdd_prepare_out(input, bin_ct, hist, bin_edges); } template<typename scalar_t> void infer_bin_edges_from_input(const Tensor& input, const int64_t N, std::vector<double> &leftmost_edges, std::vector<double> &rightmost_edges) { // Calls aminmax on input with dim=0, reducing all but the innermost dimension of input. Tensor min, max; std::tie(min, max) = aminmax(input, 0); TORCH_INTERNAL_ASSERT(min.is_contiguous() && max.is_contiguous()); const scalar_t *min_data = min.data_ptr<scalar_t>(); std::copy(min_data, min_data + N, leftmost_edges.begin()); const scalar_t *max_data = max.data_ptr<scalar_t>(); std::copy(max_data, max_data + N, rightmost_edges.begin()); } /* Determines the outermost bin edges. For simplicity when calling into aminmax, * assumes that input has already been reshaped to (M, N). */ std::pair<std::vector<double>, std::vector<double>> select_outer_bin_edges(const Tensor& input, c10::optional<c10::ArrayRef<double>> range) { TORCH_INTERNAL_ASSERT(input.dim() == 2, "expected input to have shape (M, N)"); const int64_t N = input.size(-1); // Default ranges for empty input matching numpy.histogram's default std::vector<double> leftmost_edges(N, 0.); std::vector<double> rightmost_edges(N, 1.); if (range.has_value()) { // range is specified TORCH_CHECK((int64_t)range.value().size() == 2 * N, "torch.histogramdd: for a ", N, "-dimensional histogram", " range should have ", 2 * N, " elements, but got ", range.value().size()); for (int64_t dim = 0; dim < N; dim++) { leftmost_edges[dim] = range.value()[2 * dim]; rightmost_edges[dim] = range.value()[2 * dim + 1]; } } else if (input.numel() > 0) { // non-empty input AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "histogramdd", [&]() { infer_bin_edges_from_input<scalar_t>(input, N, leftmost_edges, rightmost_edges); }); } for (int64_t dim = 0; dim < N; dim++) { double leftmost_edge = leftmost_edges[dim]; double rightmost_edge = rightmost_edges[dim]; TORCH_CHECK(std::isfinite(leftmost_edge) && std::isfinite(rightmost_edge), "torch.histogramdd: dimension ", dim, "'s range [", leftmost_edge, ", ", rightmost_edge, "] is not finite"); TORCH_CHECK(leftmost_edge <= rightmost_edge, "torch.histogramdd: min should not exceed max, but got", " min ", leftmost_edge, " max ", rightmost_edge, " for dimension ", dim); // Expand empty range to match numpy behavior and avoid division by 0 in normalization if (leftmost_edge == rightmost_edge) { leftmost_edges[dim] -= 0.5; rightmost_edges[dim] += 0.5; } } return std::make_pair(leftmost_edges, rightmost_edges); } /* histc's version of the logic for outermost bin edges. */ std::pair<double, double> histc_select_outer_bin_edges(const Tensor& input, const Scalar& min, const Scalar& max) { double leftmost_edge = min.to<double>(); double rightmost_edge = max.to<double>(); if (leftmost_edge == rightmost_edge) { auto extrema = _aminmax(input); leftmost_edge = std::get<0>(extrema).item<double>(); rightmost_edge = std::get<1>(extrema).item<double>(); } if (leftmost_edge == rightmost_edge) { leftmost_edge -= 1; rightmost_edge += 1; } TORCH_CHECK(!(std::isinf(leftmost_edge) || std::isinf(rightmost_edge) || std::isnan(leftmost_edge) || std::isnan(rightmost_edge)), "torch.histc: range of [", leftmost_edge, ", ", rightmost_edge, "] is not finite"); TORCH_CHECK(leftmost_edge < rightmost_edge, "torch.histc: max must be larger than min"); return std::make_pair(leftmost_edge, rightmost_edge); } } // namespace std::vector<Tensor> allocate_bin_edges_tensors(const Tensor& self) { TORCH_CHECK(self.dim() >= 2, "torch.histogramdd: input tensor should have at least 2 dimensions"); const int64_t N = self.size(-1); std::vector<Tensor> bin_edges_out(N); for (int64_t dim = 0; dim < N; dim++) { bin_edges_out[dim] = at::empty({0}, self.options(), MemoryFormat::Contiguous); } return bin_edges_out; } /* Versions of histogramdd in which bins is a Tensor[] defining the sequences of bin edges. */ Tensor& histogramdd_out_cpu(const Tensor& self, TensorList bins, const c10::optional<Tensor>& weight, bool density, Tensor& hist, TensorList& bin_edges) { histogramdd_check_inputs(self, bins, weight); histogramdd_prepare_out(self, bins, hist, bin_edges); for (size_t dim = 0; dim < bins.size(); dim++) { bin_edges[dim].copy_(bins[dim]); } histogramdd_stub(self.device().type(), self, weight, density, hist, bin_edges); return hist; } Tensor histogramdd_cpu(const Tensor& self, TensorList bins, const c10::optional<Tensor>& weight, bool density) { Tensor hist = at::empty({0}, self.options(), MemoryFormat::Contiguous); std::vector<Tensor> bin_edges_out = allocate_bin_edges_tensors(self); TensorList bin_edges_out_tl(bin_edges_out); histogramdd_out_cpu(self, bins, weight, density, hist, bin_edges_out_tl); return hist; } /* Versions of histogramdd in which bins is an int[] * defining the number of bins in each dimension. */ std::vector<Tensor>& histogramdd_bin_edges_out_cpu(const Tensor& self, IntArrayRef bin_ct, c10::optional<c10::ArrayRef<double>> range, const c10::optional<Tensor>& weight, bool density, std::vector<Tensor>& bin_edges_out) { TensorList bin_edges_out_tl(bin_edges_out); const int64_t N = self.size(-1); const int64_t M = std::accumulate(self.sizes().begin(), self.sizes().end() - 1, (int64_t)1, std::multiplies<int64_t>()); Tensor reshaped_self = self.reshape({ M, N }); auto outer_bin_edges = select_outer_bin_edges(reshaped_self, range); for (int64_t dim = 0; dim < N; dim++) { linspace_out(outer_bin_edges.first[dim], outer_bin_edges.second[dim], bin_ct[dim] + 1, bin_edges_out[dim]); } return bin_edges_out; } std::vector<Tensor> histogramdd_bin_edges_cpu(const Tensor& self, IntArrayRef bin_ct, c10::optional<c10::ArrayRef<double>> range, const c10::optional<Tensor>& weight, bool density) { std::vector<Tensor> bin_edges_out = allocate_bin_edges_tensors(self); return histogramdd_bin_edges_out_cpu(self, bin_ct, range, weight, density, bin_edges_out); } Tensor& histogramdd_out_cpu(const Tensor& self, IntArrayRef bin_ct, c10::optional<c10::ArrayRef<double>> range, const c10::optional<Tensor>& weight, bool density, Tensor& hist, TensorList& bin_edges) { std::vector<Tensor> bins = histogramdd_bin_edges_cpu(self, bin_ct, range, weight, density); histogramdd_check_inputs(self, bins, weight); histogramdd_prepare_out(self, bins, hist, bin_edges); for (size_t dim = 0; dim < bins.size(); dim++) { bin_edges[dim].copy_(bins[dim]); } histogramdd_linear_stub(self.device().type(), self, weight, density, hist, bin_edges, true); return hist; } Tensor histogramdd_cpu(const Tensor& self, IntArrayRef bin_ct, c10::optional<c10::ArrayRef<double>> range, const c10::optional<Tensor>& weight, bool density) { Tensor hist = at::empty({0}, self.options(), MemoryFormat::Contiguous); std::vector<Tensor> bin_edges_out = allocate_bin_edges_tensors(self); TensorList bin_edges_out_tl(bin_edges_out); histogramdd_out_cpu(self, bin_ct, range, weight, density, hist, bin_edges_out_tl); return hist; } /* Versions of histogram in which bins is a Tensor defining the sequence of bin edges. */ std::tuple<Tensor&, Tensor&> histogram_out_cpu(const Tensor& self, const Tensor& bins, const c10::optional<Tensor>& weight, bool density, Tensor& hist, Tensor& bin_edges) { Tensor reshaped_self = self.reshape({ self.numel(), 1 }); c10::optional<Tensor> reshaped_weight = weight.has_value() ? weight.value().reshape({ weight.value().numel() }) : weight; TensorList bins_in = bins; TensorList bins_out = bin_edges; histogramdd_out_cpu(reshaped_self, bins_in, reshaped_weight, density, hist, bins_out); return std::forward_as_tuple(hist, bin_edges); } std::tuple<Tensor, Tensor> histogram_cpu(const Tensor& self, const Tensor& bins, const c10::optional<Tensor>& weight, bool density) { Tensor hist = at::empty({0}, self.options(), MemoryFormat::Contiguous); Tensor bin_edges = at::empty({0}, bins.options(), MemoryFormat::Contiguous); return histogram_out_cpu(self, bins, weight, density, hist, bin_edges); } /* Versions of histogram in which bins is an integer specifying the number of equal-width bins. */ std::tuple<Tensor&, Tensor&> histogram_out_cpu(const Tensor& self, int64_t bin_ct, c10::optional<c10::ArrayRef<double>> range, const c10::optional<Tensor>& weight, bool density, Tensor& hist, Tensor& bin_edges) { Tensor reshaped_self = self.reshape({ self.numel(), 1 }); c10::optional<Tensor> reshaped_weight = weight.has_value() ? weight.value().reshape({ weight.value().numel() }) : weight; TensorList bins_in = bin_edges; TensorList bins_out = bin_edges; histogramdd_prepare_out(reshaped_self, std::vector<int64_t>{bin_ct}, hist, bins_out); auto outer_bin_edges = select_outer_bin_edges(reshaped_self, range); linspace_out(outer_bin_edges.first[0], outer_bin_edges.second[0], bin_ct + 1, bin_edges); histogramdd_check_inputs(reshaped_self, bins_in, reshaped_weight); histogramdd_linear_stub(reshaped_self.device().type(), reshaped_self, reshaped_weight, density, hist, bin_edges, true); return std::forward_as_tuple(hist, bin_edges); } std::tuple<Tensor, Tensor> histogram_cpu(const Tensor& self, int64_t bin_ct, c10::optional<c10::ArrayRef<double>> range, const c10::optional<Tensor>& weight, bool density) { Tensor hist = at::empty({0}, self.options(), MemoryFormat::Contiguous); Tensor bin_edges_out = at::empty({0}, self.options()); return histogram_out_cpu(self, bin_ct, range, weight, density, hist, bin_edges_out); } /* Narrowed interface for the legacy torch.histc function. */ Tensor& histogram_histc_cpu_out(const Tensor& self, int64_t bin_ct, const Scalar& min, const Scalar& max, Tensor& hist) { Tensor bin_edges = at::empty({0}, self.options()); Tensor reshaped = self.reshape({ self.numel(), 1 }); TensorList bins_in = bin_edges; TensorList bins_out = bin_edges; histogramdd_prepare_out(reshaped, std::vector<int64_t>{bin_ct}, hist, bins_out); auto outer_bin_edges = histc_select_outer_bin_edges(self, min, max); linspace_out(outer_bin_edges.first, outer_bin_edges.second, bin_ct + 1, bin_edges); histogramdd_check_inputs(reshaped, bins_in, {}); histogramdd_linear_stub(reshaped.device().type(), reshaped, c10::optional<Tensor>(), false, hist, bin_edges, false); return hist; } Tensor histogram_histc_cpu(const Tensor& self, int64_t bin_ct, const Scalar& min, const Scalar& max) { Tensor hist = at::empty({0}, self.options(), MemoryFormat::Contiguous); return histogram_histc_cpu_out(self, bin_ct, min, max, hist); } }} // namespace at::native
43.553659
123
0.674469
[ "shape", "vector", "transform" ]
74090edf70e17c99e5a178706bc042466fa330cd
5,867
hpp
C++
allocore/allocore/protocol/al_Serialize.hpp
donghaoren/AlloSystem
7674cc8597e470a355a5dab1dac9191c2c2e8086
[ "BSD-3-Clause" ]
null
null
null
allocore/allocore/protocol/al_Serialize.hpp
donghaoren/AlloSystem
7674cc8597e470a355a5dab1dac9191c2c2e8086
[ "BSD-3-Clause" ]
null
null
null
allocore/allocore/protocol/al_Serialize.hpp
donghaoren/AlloSystem
7674cc8597e470a355a5dab1dac9191c2c2e8086
[ "BSD-3-Clause" ]
null
null
null
#ifndef INCLUDE_AL_SERIALIZE_HPP #define INCLUDE_AL_SERIALIZE_HPP /* Allocore -- Multimedia / virtual environment application class library Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB. Copyright (C) 2012. The Regents of the University of California. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the University of California 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. File description: This is a C++ wrapper around the C serialization structs/functions. File author(s): Lance Putnam, 2010, putnam.lance@gmail.com */ #include "al_Serialize.h" #include <vector> #include <string> namespace al{ namespace ser{ template<class T> inline uint32_t encode(char * b, const T * v, uint32_t n){ return 0; } template<> inline uint32_t encode(char * b, const float * v, uint32_t n){ return serEncodeFloat32(b, v, n); } template<> inline uint32_t encode(char * b, const double * v, uint32_t n){ return serEncodeFloat64(b, v, n); } template<> inline uint32_t encode(char * b, const char * v, uint32_t n){ return serEncodeInt8(b, (const int8_t *)v, n); } template<> inline uint32_t encode(char * b, const int8_t * v, uint32_t n){ return serEncodeInt8(b, v, n); } template<> inline uint32_t encode(char * b, const int16_t * v, uint32_t n){ return serEncodeInt16(b, v, n); } template<> inline uint32_t encode(char * b, const int32_t * v, uint32_t n){ return serEncodeInt32(b, v, n); } template<> inline uint32_t encode(char * b, const int64_t * v, uint32_t n){ return serEncodeInt64(b, v, n); } template<> inline uint32_t encode(char * b, const bool * v, uint32_t n){ return serEncodeUInt8(b, (const uint8_t *)v, n); } template<> inline uint32_t encode(char * b, const uint8_t * v, uint32_t n){ return serEncodeUInt8(b, v, n); } template<> inline uint32_t encode(char * b, const uint16_t * v, uint32_t n){ return serEncodeUInt16(b, v, n); } template<> inline uint32_t encode(char * b, const uint32_t * v, uint32_t n){ return serEncodeUInt32(b, v, n); } template<> inline uint32_t encode(char * b, const uint64_t * v, uint32_t n){ return serEncodeUInt64(b, v, n); } template<class T> uint8_t getType(); template<> inline uint8_t getType<float >(){ return 'f'; } template<> inline uint8_t getType<double >(){ return 'd'; } template<> inline uint8_t getType<bool >(){ return 't'; } template<> inline uint8_t getType<uint8_t >(){ return 't'; } template<> inline uint8_t getType<uint16_t>(){ return 'T'; } template<> inline uint8_t getType<uint32_t>(){ return 'u'; } template<> inline uint8_t getType<uint64_t>(){ return 'U'; } template<> inline uint8_t getType<int8_t >(){ return 'h'; } template<> inline uint8_t getType<int16_t >(){ return 'H'; } template<> inline uint8_t getType<int32_t >(){ return 'i'; } template<> inline uint8_t getType<int64_t >(){ return 'I'; } } // ser:: /// struct Serializer{ template <class T> Serializer& operator<< (T v); Serializer& operator<< (const char * v); Serializer& operator<< (const std::string& v); template <class T> Serializer& add(const T * v, uint32_t num); const std::vector<char>& buf() const; private: std::vector<char> mBuf, mTemp; template <class T> void checkSize(uint32_t n=1); }; /// struct Deserializer{ Deserializer(const std::vector<char>& b); Deserializer(const char * b, uint32_t n); template <class T> Deserializer& operator>> (T& v); Deserializer& operator>> (char * v); Deserializer& operator>> (std::string& v); const std::vector<char>& buf() const; private: int mStart; std::vector<char> mBuf; char * bufDec(); }; // ============================================================================= // Implementation // ============================================================================= template <class T> Serializer& Serializer::operator<< (T v){ return add(&v, 1); } template <class T> Serializer& Serializer::add(const T * v, uint32_t num){ checkSize<T>(num); uint32_t n = ser::encode(&mTemp[0], v, num); mBuf.insert(mBuf.end(), mTemp.begin(), mTemp.begin()+n); return *this; } template <class T> void Serializer::checkSize(uint32_t n){ uint32_t need = n*sizeof(T) + serHeaderSize(); if(mTemp.size() < need) mTemp.resize(need); } template <class T> Deserializer& Deserializer::operator>> (T& v){ uint32_t n = serDecode(bufDec(), &v); mStart += n; return *this; } //template <class T> //Deserializer& decode(const T * v, uint32_t num){ // uint32_t n = decode(bufDec(), v); // return *this; //} } // al:: #endif
34.715976
123
0.698994
[ "vector" ]
74115de43ea222803b3b559da6d520c36b509523
2,716
cpp
C++
codechef/aug16/long_aug/long41.cpp
Abhinavlamba/competitive-programming
fdf26f55e5559cde32651ef91f1927b1137442f9
[ "MIT" ]
1
2020-05-12T04:28:55.000Z
2020-05-12T04:28:55.000Z
codechef/aug16/long_aug/long41.cpp
devkant/competitive-programming
fdf26f55e5559cde32651ef91f1927b1137442f9
[ "MIT" ]
null
null
null
codechef/aug16/long_aug/long41.cpp
devkant/competitive-programming
fdf26f55e5559cde32651ef91f1927b1137442f9
[ "MIT" ]
5
2017-10-22T06:04:17.000Z
2020-08-04T11:08:47.000Z
#include <bits/stdc++.h> using namespace std; int main() { typedef long long lg; lg times,i,j,k,p,n,m; scanf("%lld",&times); for(i=0;i<times;i++){ scanf("%lld%lld",&n,&m); vector<int> arr[n+1]; int colors[n+1]; int rel[n+1][n+1]; for(j=0;j<=n;j++){ for(k=0;k<=n;k++){ rel[j][k]=0; } } lg count[n+1],parent[n+1]; for(j=0;j<=n;j++){ count[j]=0; colors[j]=0; } for(j=0;j<m;j++){ lg t1,t2; scanf("%lld%lld",&t1,&t2); rel[t1][t2]=1; rel[t2][t1]=1; } //now forming reverse graph int flag11=0; for(j=1;j<=n;j++){ flag11=0; for(k=1;k<=n;k++){ if(rel[j][k]==0){ if(j!=k) arr[j].push_back(k); }else{ //flag11=1; } } if(flag11==0){ //printf("for j== %lld,flag is %d\n",j,flag11 ); break; } } int flag=0; for(int j1=1;j1<=n;j1++){ if(colors[j1]!=0){ continue; } flag=0; queue<int> q; q.push(j1); if(flag11==1){ while(!q.empty()){ int poped=q.front(); q.pop(); if(colors[poped]==0){ colors[poped]=1; } flag=0; int c_temp=colors[poped]; for(j=0;j<arr[poped].size();j++){ int t=arr[poped][j]; if(colors[t]==c_temp){ flag=1; break; }else if(colors[t]==0){ if(c_temp==1){ colors[t]=2; }else{ colors[t]=1; } q.push(t); } } if(flag==1){ //cout<<"break1 "<<endl; break; } } }else{// //cout<<"break2 "<<endl; flag=1; break; } if(flag==1){ break; } } /*cout<<"colors : "; for(j=1;j<=n;j++){ cout<<colors[j]<<" "; } cout<<endl; for(int j=1;j<=n;j++){ for(int i1=0; i1<arr[j].size(); ++i1) cout <<arr[j][i1] << ' '; printf("\n"); }*/ if(flag==0){ printf("YES\n"); }else{ printf("NO\n"); } } return 0; } /* 3 3 2 1 2 2 3 4 3 1 2 2 3 2 4 6 7 1 2 1 3 2 3 2 4 4 5 4 6 5 6 */
15.258427
56
0.31701
[ "vector" ]
741384e606160a09683555065dcb77ad72eae90d
27,051
cpp
C++
Source/CNTK/ModelEditLanguage.cpp
sunkwei/CNTK
08691e97707538b110ca71bce4ad06c46d840517
[ "Intel" ]
6
2019-08-18T05:29:09.000Z
2021-01-19T09:58:45.000Z
Source/CNTK/ModelEditLanguage.cpp
Omar-Belghaouti/CNTK
422f710242c602b2660a634f2234abf5aaf5b337
[ "RSA-MD" ]
null
null
null
Source/CNTK/ModelEditLanguage.cpp
Omar-Belghaouti/CNTK
422f710242c602b2660a634f2234abf5aaf5b337
[ "RSA-MD" ]
1
2019-03-20T21:44:46.000Z
2019-03-20T21:44:46.000Z
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // // NetworkDescriptionLanguage.cpp : Code used to interpret the Network Description Language. // #define _CRT_SECURE_NO_WARNINGS // "secure" CRT not available on all platforms --add this at the top of all CPP files that give "function or variable may be unsafe" warnings #include "ModelEditLanguage.h" #include "ConvolutionalNodes.h" #include "InputAndParamNodes.h" #include <map> namespace Microsoft { namespace MSR { namespace CNTK { // EqualInsensitive - check to see if two nodes are equal up to the length of the first string (must be at least half as long as actual node name) // TODO: Allowing partial matches seems misguided. We should discourage that, or just remove it. // string1 - [in,out] string to compare, if comparision is equal insensitive but not sensitive, will replace with sensitive version // string2 - second string to compare // alternate - alternate naming of the string // return - true if strings are equal insensitive and modifies string1 to sensitive version if different bool EqualInsensitive(std::string& string1, const char* string2, const char* alternate /*=NULL*/) { bool equal = !_strnicmp(string1.c_str(), string2, string1.size()); // don't allow partial matches that are less than half the string if (equal && string1.size() < strlen(string2) / 2) equal = false; // if we have a (partial) match replace with the full name if (equal && strcmp(string1.c_str(), string2)) string1 = string2; if (!equal && alternate != NULL) { equal = !_strnicmp(string1.c_str(), alternate, string1.size()); // don't allow partial matches that are less than half the string if (equal && string1.size() < strlen(alternate) / 2) equal = false; // if we have a match of the alternate string replace with the full name if (equal) string1 = string2; } return equal; } // MELProperty - the properties for SetProperty enum MELProperty { melPropNull, melPropParameterUpdateRequired, melPropLearningRateMultiplier, melPropFeature, melPropLabel, melPropFinalCriterion, melPropEvaluation, melPropOutput, melPropRecurrent }; // SetGroupTag - Set the group tag on a node // nodeProp - node on which the property will be set/cleared // grouptag - node will be added to/removed from this group // set - true if property is to be added, false if property is deleted template <typename ElemType> void MELScript<ElemType>::SetGroupTag(ComputationNodeBasePtr nodeProp, ComputationNetworkPtr cn, const std::wstring& groupTag, bool set) { if (set) cn->AddToNodeGroup(groupTag, nodeProp); else cn->RemoveFromNodeGroup(groupTag, nodeProp); } // ProcessNDLScript - Process the NDL script // netNdl - netNDL structure // ndlPassUntil - complete processing through this pass, all passes if ndlPassAll // fullValidate - validate as a complete network? (false if this might be a snippet of a full network) template <typename ElemType> void MELScript<ElemType>::ProcessNDLScript(NetNdl<ElemType>* netNdl, NDLPass ndlPassUntil, bool fullValidate) { NDLUtil<ElemType> ndlUtil(netNdl->cn); ndlUtil.ProcessNDLScript(netNdl, ndlPassUntil, fullValidate); } // CallFunction - call the MEL function // name - name of the function to call // params - parameters to the function template <typename ElemType> void MELScript<ElemType>::CallFunction(const std::string& p_name, const ConfigParamList& params) { std::string name = p_name; if (EqualInsensitive(name, "CreateModel")) // create a blank model { size_t numFixedParams = 0, numOptionalParams = 0; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters: CreateModel(). newly created model always becomes the new default."); auto cn = make_shared<ComputationNetwork>(CPUDEVICE); OverrideModelNameAndSetDefaultModel(cn); } if (EqualInsensitive(name, "CreateModelWithName")) // create a blank model { size_t numFixedParams = 1, numOptionalParams = 0; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters: CreateModelWithName(modelName). newly created model always becomes the new default."); auto cn = make_shared<ComputationNetwork>(CPUDEVICE); OverrideModelNameAndSetDefaultModel(cn, params[0]); } else if (EqualInsensitive(name, "LoadModel")) { size_t numFixedParams = 1, numOptionalParams = 1; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters: LoadModel(modelFileName, [format=cntk]). newly loaded model always becomes the new default."); std::wstring modelFormat = GetOptionalModelFormat(params, numFixedParams); auto cn = make_shared<ComputationNetwork>(CPUDEVICE); cn->Load<ElemType>(params[0]); OverrideModelNameAndSetDefaultModel(cn); } else if (EqualInsensitive(name, "LoadModelWithName")) { size_t numFixedParams = 2, numOptionalParams = 1; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters: LoadModelWithName(modelName, modelFileName, [format=cntk]). newly loaded model always becomes the new default."); std::wstring modelFormat = GetOptionalModelFormat(params, numFixedParams); auto cn = make_shared<ComputationNetwork>(CPUDEVICE); #if 1 // support for a specific kind of legacy format, for the sole purpose of allowing users to convert (=load & save) them if (modelFormat == L"cntk_legacy_no_tensorlib") { cn->Read<ElemType>(params[1]); for (auto node : cn->FeatureNodes()) node->SetDims(TensorShape(node->GetSampleMatrixNumRows()), node->HasMBLayout()); // pre-tensorlib InputValues had incorrect tensor dimensions cn->CompileNetwork(); } else #endif cn->Load<ElemType>(params[1]); OverrideModelNameAndSetDefaultModel(cn, params[0]); } else if (EqualInsensitive(name, "LoadNDLSnippet")) { size_t numFixedParams = 2, numOptionalParams = 1; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters: LoadNDLSnippet(modelName, ndlsnippet)."); string modelName = params[0]; wstring ndlSnippetFileName = params[1]; auto cn = make_shared<ComputationNetwork>(CPUDEVICE); NDLScript<ElemType> script; ConfigParameters ndlScript(script.ReadConfigFile(ndlSnippetFileName)); // check for a section of the snippet file we wish to read std::string section = GetOptionalSnippetSection(params, numFixedParams); if (!section.empty()) { if (!ndlScript.Exists(section)) { RuntimeError("Section %s specified in optional parameter was not found in the %ls file\n", section.c_str(), ndlSnippetFileName.c_str()); } ConfigValue ndlSnippet = ndlScript(section); EvaluateNDLSnippet(ndlSnippet, cn); } else { script.LoadConfigFile(ndlSnippetFileName); } OverrideModelNameAndSetDefaultModel(cn, modelName); } else if (EqualInsensitive(name, "SaveDefaultModel")) { size_t numFixedParams = 1, numOptionalParams = 1; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters: SaveDefaultModel(modelFileName, [format=cntk])."); std::wstring modelFormat = GetOptionalModelFormat(params, numFixedParams); std::wstring fileName = params[0]; auto cn = m_netNdlDefault->cn; if (cn == NULL) RuntimeError("SaveDefaultModel can only be called after a default name exists (i.e., at least one model is loaded.)"); // validate the network before we save it out ProcessNDLScript(m_netNdlDefault, ndlPassAll, true); cn->SaveEdited(fileName); } else if (EqualInsensitive(name, "SaveModel")) { size_t numFixedParams = 2, numOptionalParams = 1; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters: SaveModel(modelName, modelFileName, [format=cntk])."); std::wstring modelFormat = GetOptionalModelFormat(params, numFixedParams); std::string modelName = params[0]; std::wstring fileName = params[1]; NetNdl<ElemType>* netNdl = &m_mapNameToNetNdl[modelName]; if (netNdl->cn == NULL) RuntimeError("SaveModel can only be called after a network has been setup, no active model named %s.", modelName.c_str()); // validate and finish the second pass through NDL if any in-line NDL was defined ProcessNDLScript(netNdl, ndlPassAll, true); netNdl->cn->SaveEdited(fileName); } else if (EqualInsensitive(name, "SetDefaultModel")) { size_t numFixedParams = 1, numOptionalParams = 0; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters: SetDefaultModel(modelName)"); SetExistingModelAsDefault(params[0]); } else if (EqualInsensitive(name, "UnloadModel")) { // UnloadModel takes a variable number of parameters, all expected to be model names for (int i = 0; i < params.size(); ++i) { string modelName = params[i]; auto found = m_mapNameToNetNdl.find(modelName); if (found != m_mapNameToNetNdl.end()) { found->second.Clear(); // if this was the default model, clear it out if (&(found->second) == m_netNdlDefault) m_netNdlDefault = nullptr; m_mapNameToNetNdl.erase(found); } else fprintf(stderr, "WARNING: model %s does not exist.", modelName.c_str()); } } else if (EqualInsensitive(name, "DumpModel", "Dump")) { size_t numFixedParams = 2, numOptionalParams = 1; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters: DumpNetwork(modelName, fileName, [includeData=false|true])"); bool includeData = GetOptionalIncludeDataValue(params, numFixedParams); std::string modelName = params[0]; std::wstring fileName = params[1]; auto found = m_mapNameToNetNdl.find(modelName); if (found == m_mapNameToNetNdl.end()) RuntimeError("Model %s does not exist. Cannot dump non-existant model.", modelName.c_str()); else { NetNdl<ElemType>* netNdl = &found->second; ProcessNDLScript(netNdl, ndlPassAll, true); found->second.cn->DumpAllNodesToFile(includeData, true, fileName); } } else if (EqualInsensitive(name, "DumpNode")) { size_t numFixedParams = 2, numOptionalParams = 1; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters: DumpNode(nodeName, fileName, [includeData=false|true])"); bool includeData = GetOptionalIncludeDataValue(params, numFixedParams); std::wstring fileName = params[1]; NetNdl<ElemType>* netNdl; vector<ComputationNodeBasePtr> nodes = FindSymbols(params[0], netNdl); ProcessNDLScript(netNdl, ndlPassAll); netNdl->cn->DumpNodeInfoToFile(nodes, includeData, true, fileName); } else if (EqualInsensitive(name, "CopyNode", "Copy")) { size_t numFixedParams = 2, numOptionalParams = 1; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters are: CopyNode(fromNode, toNode, [copy=all|value])"); CopyNodeFlags copyFlags = GetOptionalCopyNodeFlags(params, numFixedParams); std::string from = params[0]; std::string to = params[1]; CopyNodes(from, to, copyFlags); } else if (EqualInsensitive(name, "CopySubTree")) { size_t numFixedParams = 3, numOptionalParams = 1; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters are: CopySubTree(fromNode, toNetwork, toNodeNamePrefix, [copy=all|value])"); CopyNodeFlags copyFlags = GetOptionalCopyNodeFlags(params, numFixedParams); std::string from = params[0]; std::string to = params[1]; std::string prefix = params[2]; CopySubTree(from, to, prefix, copyFlags); } else if (EqualInsensitive(name, "CopyNodeInputs", "CopyInputs")) { size_t numFixedParams = 2, numOptionalParams = 0; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters are: CopyNodeInputs(fromNode, toNode)"); // get the nodes NetNdl<ElemType>* netNdlTo; NetNdl<ElemType>* netNdlFrom; vector<GenNameValue> names = GenerateNames(params[0], params[1], netNdlFrom, netNdlTo); if (netNdlFrom != netNdlTo) RuntimeError("CopyInputs requires two symbols from the same network, %s and %s belong to different networks", params[0].c_str(), params[1].c_str()); ProcessNDLScript(netNdlFrom, ndlPassAll); for (GenNameValue name : names) { auto& node = name.first; std::wstring nodeName = node->NodeName(); std::wstring toNodeName = name.second; netNdlTo->cn->CopyNode(*netNdlFrom->cn, nodeName, toNodeName, CopyNodeFlags::copyNodeInputLinks); } } else if (EqualInsensitive(name, "SetNodeInput", "SetInput")) { size_t numFixedParams = 3, numOptionalParams = 0; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters are: SetNodeInput(toNode, inputID(0-based), inputNodeName)"); // get the nodes NetNdl<ElemType>* netNdlTo; NetNdl<ElemType>* netNdlFrom; vector<ComputationNodeBasePtr> nodeTo = FindSymbols(params[0], netNdlTo); vector<ComputationNodeBasePtr> nodeFrom = FindSymbols(params[2], netNdlFrom); int inputNum = params[1]; if (netNdlTo != netNdlFrom) RuntimeError("SetNodeInput() requires two symbols from the same network, %s and %s belong to different networks", params[0].c_str(), params[2].c_str()); if (nodeFrom.size() != 1) RuntimeError("SetNodeInput() must have a single value input, %s doesn't represent one item", params[0].c_str()); if (nodeTo.size() < 1) RuntimeError("SetNodeInput() must have at least one target, %s doesn't represent any items", params[2].c_str()); // process outstanding NDL scripts ensuring that the inputs have all been resolved ProcessNDLScript(netNdlFrom, ndlPassResolve); for (auto& node : nodeTo) { node->SetInput(inputNum, nodeFrom[0]); } } else if (EqualInsensitive(name, "SetNodeInputs", "SetInputs")) { if (params.size() > 4 || params.size() < 2) RuntimeError("Invalid number of parameters. Valid parameters are: SetNodeInputs(toNode, inputNodeName1, [inputNodeName2, inputNodeName3])"); // get the nodes NetNdl<ElemType>* netNdlTo; vector<ComputationNodeBasePtr> nodeTo = FindSymbols(params[0], netNdlTo); if (nodeTo.size() != 1) RuntimeError("SetNodeInputs() must have exactly one target, %s doesn't represent any node.", params[0].c_str()); vector<ComputationNodeBasePtr> inputNodes; inputNodes.resize(params.size() - 1); // process outstanding NDL scripts ensuring that the inputs have all been resolved ProcessNDLScript(netNdlTo, ndlPassResolve); for (int i = 1; i < params.size(); i++) { NetNdl<ElemType>* netNdlFrom; vector<ComputationNodeBasePtr> nodeFrom = FindSymbols(params[i], netNdlFrom); if (netNdlTo != netNdlFrom) RuntimeError("SetNodeInputs() requires all symbols from the same network, %s and %s belong to different networks", params[0].c_str(), params[i].c_str()); if (nodeFrom.size() != 1) RuntimeError("SetNodeInputs() each input node should be translated to one node name. %s is translated to multiple node names.", params[i].c_str()); inputNodes[i - 1] = nodeFrom[0]; } nodeTo[0]->AttachInputs(inputNodes); } else if (EqualInsensitive(name, "SetProperty")) { if (params.size() != 3) RuntimeError("Invalid number of parameters: Valid parameters are: SetProperty(toNode, propertyName, propertyValue)"); std::string propName = params[1]; MELProperty prop = melPropNull; #if 1 // legacy // legacy names for some properties if (EqualInsensitive(propName, "finalCriterion", "Criteria")) propName = "criterion"; else if (EqualInsensitive(propName, "eval")) propName = "evaluation"; // legacy property that now works differently else if (EqualInsensitive(propName, "needGradient", "needsGradient") || EqualInsensitive(propName, "computeGradient")) prop = melPropParameterUpdateRequired; // for backward compatibility else #endif // map property name to property enum // Please keep this table sorted. if (EqualInsensitive(propName, "criterion")) prop = melPropFinalCriterion; else if (EqualInsensitive(propName, "evaluation")) prop = melPropEvaluation; else if (EqualInsensitive(propName, "feature")) prop = melPropFeature; else if (EqualInsensitive(propName, "label")) prop = melPropLabel; else if (EqualInsensitive(propName, "learningRateMultiplier")) prop = melPropLearningRateMultiplier; else if (EqualInsensitive(propName, "output")) prop = melPropOutput; else if (EqualInsensitive(propName, "recurrent")) prop = melPropRecurrent; else InvalidArgument("Invalid property, %s, is not supported", propName.c_str()); // get the nodes NetNdl<ElemType>* netNdl; vector<ComputationNodeBasePtr> nodes = FindSymbols(params[0], netNdl); // this probabably won't do anything, but make sure all NDL has been created ProcessNDLScript(netNdl, ndlPassInitial, false); auto cn = netNdl->cn; for (auto& node : nodes) { switch (prop) { case melPropParameterUpdateRequired: // for backward compatibility { node->SetLearningRateMultiplier((bool)params[2] ? 1.0f : 0); break; } case melPropLearningRateMultiplier: { node->SetLearningRateMultiplier((float)params[2]); break; } case melPropFeature: { bool set = params[2]; SetGroupTag(node, cn, L"feature", set); break; } case melPropLabel: { bool set = params[2]; SetGroupTag(node, cn, L"label", set); break; } case melPropFinalCriterion: { bool set = params[2]; SetGroupTag(node, cn, L"criterion", set); break; } case melPropEvaluation: { bool set = params[2]; SetGroupTag(node, cn, L"evaluation", set); break; } case melPropOutput: { bool set = params[2]; SetGroupTag(node, cn, L"output", set); break; } case melPropRecurrent: { // what to do here? break; } default: { RuntimeError("Invalid property, %s, is not supported", propName.c_str()); break; } } } } else if (EqualInsensitive(name, "SetPropertyForSubTree")) { size_t numFixedParams = 3, numOptionalParams = 0; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters are: SetPropertyForSubTree(rootNodeName, propertyName, propertyValue)"); std::string propName = params[1]; MELProperty prop = melPropNull; if (EqualInsensitive(propName, "needGradient", "needsGradient") || EqualInsensitive(propName, "computeGradient")) { prop = melPropParameterUpdateRequired; // for backward compatability } else if (EqualInsensitive(propName, "learningRateMultiplier")) { prop = melPropLearningRateMultiplier; } else { RuntimeError("Invalid property, %s, is not supported", propName.c_str()); } // get the nodes NetNdl<ElemType>* netNdl; vector<ComputationNodeBasePtr> nodes = FindSymbols(params[0], netNdl); // make sure all NDL links have been resolved ProcessNDLScript(netNdl, ndlPassResolve); for (auto& node : nodes) { switch (prop) { case melPropParameterUpdateRequired: //for backward compatibility { float learningRateMultiplier = (bool)params[2] ? 1.0f : 0; netNdl->cn->SetLearnableNodesBelowLearningRateMultiplier(learningRateMultiplier, node); break; } case melPropLearningRateMultiplier: { float learningRateMultiplier = (float)params[2]; netNdl->cn->SetLearnableNodesBelowLearningRateMultiplier(learningRateMultiplier, node); break; } default: { RuntimeError("Invalid property, %s, is not supported", propName.c_str()); break; } } } } else if (EqualInsensitive(name, "RemoveNode", "Remove") || EqualInsensitive(name, "DeleteNode", "Delete")) { std::map<NetNdl<ElemType>*, bool> processed; // remove takes a variable number of parameters, all expected to be node names or wildcard patterns for (int i = 0; i < params.size(); ++i) { // get the nodes NetNdl<ElemType>* netNdl; vector<ComputationNodeBasePtr> nodes = FindSymbols(params[i], netNdl); // make sure all NDL has been processed in case we are removing some of them... // only process each network once, because validates will start failing after first delete if (processed.find(netNdl) == processed.end()) { ProcessNDLScript(netNdl, ndlPassAll, false); processed[netNdl] = true; } if (nodes.size() < 1) RuntimeError("Delete must have at least one target, %s doesn't represent any items", params[i].c_str()); for (const auto& node : nodes) { netNdl->cn->DeleteNode(node->NodeName()); } } } else if (EqualInsensitive(name, "Rename")) { size_t numFixedParams = 2, numOptionalParams = 0; if (params.size() > numFixedParams + numOptionalParams || params.size() < numFixedParams) RuntimeError("Invalid number of parameters. Valid parameters are Rename(oldNodeName, newNodeName)"); // get the nodes NetNdl<ElemType>* netNdlTo; NetNdl<ElemType>* netNdlFrom; vector<GenNameValue> nodeNames = GenerateNames(params[0], params[1], netNdlFrom, netNdlTo); if (netNdlFrom != netNdlTo) RuntimeError("CopyInputs requires two symbols from the same network, %s and %s belong to different networks", params[0].c_str(), params[1].c_str()); // process everything in case these nodes may have tags on them ProcessNDLScript(netNdlFrom, ndlPassAll); // now we have the original nodeNames from the input symbol, generate the output nodeNames for (GenNameValue nodeName : nodeNames) { auto& node = nodeName.first; netNdlFrom->cn->RenameNode(node, nodeName.second); } } else if (EqualInsensitive(name, "ReviseParameter")) { typedef LearnableParameter<ElemType> LearnableParameterNode; if (params.size() != 2) RuntimeError("Invalid number of parameters: Valid parameters are: ReviseParameter(nodeName, nodeParametersInASCIIPathName)"); std::string nodeName = params[0]; std::string paramPath = params[1]; NetNdl<ElemType>* netNdl; vector<ComputationNodeBasePtr> nodes = FindSymbols(params[0], netNdl); for (auto& pNodes : nodes) { if (pNodes->OperationName() != LearnableParameter<ElemType>::TypeName()) { fprintf(stderr, "WARNING: you want to change the parameter of node (%ls), but it is not a learnable parameter (it is a %ls node). Skipping this node\n", pNodes->NodeName().c_str(), pNodes->OperationName().c_str()); continue; } shared_ptr<LearnableParameterNode> pParamNode = std::dynamic_pointer_cast<LearnableParameterNode>(pNodes); pParamNode->ReviseFromFile(msra::strfun::utf16(paramPath)); fprintf(stderr, "Revise node %ls using parameter file %s\n", pNodes->NodeName().c_str(), paramPath.c_str()); } } else { RuntimeError("Unknown Editor function %s", name.c_str()); } } template class MELScript<float>; template class MELScript<double>; } } }
43.771845
187
0.634875
[ "vector", "model" ]
7416e36817bf3a25dd1f67e3bba862bdaaa95b52
4,016
cpp
C++
src/OpcUaClient/ClientService/ClientServiceBrowse.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
108
2018-10-08T17:03:32.000Z
2022-03-21T00:52:26.000Z
src/OpcUaClient/ClientService/ClientServiceBrowse.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
287
2018-09-18T14:59:12.000Z
2022-01-13T12:28:23.000Z
src/OpcUaClient/ClientService/ClientServiceBrowse.cpp
gianricardo/OpcUaStack
ccdef574175ffe8b7e82b886abc5e5403968b280
[ "Apache-2.0" ]
32
2018-10-19T14:35:03.000Z
2021-11-12T09:36:46.000Z
/* Copyright 2016 Kai Huebl (kai@huebl-sgh.de) Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser Datei nur in Übereinstimmung mit der Lizenz erlaubt. Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0. Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart, erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend. Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen im Rahmen der Lizenz finden Sie in der Lizenz. Autor: Kai Huebl (kai@huebl-sgh.de) */ #include "OpcUaStackCore/Base/ObjectPool.h" #include "OpcUaClient/ClientCommand/CommandBrowse.h" #include "OpcUaClient/ClientService/ClientServiceBrowse.h" using namespace OpcUaStackCore; namespace OpcUaClient { ClientServiceBrowse::ClientServiceBrowse(void) : ClientServiceBase() , browseCompleted_() { } ClientServiceBrowse::~ClientServiceBrowse(void) { } ClientServiceBase::SPtr ClientServiceBrowse::createClientService(void) { return constructSPtr<ClientServiceBrowse>(); } bool ClientServiceBrowse::run(ClientServiceManager& clientServiceManager, CommandBase::SPtr& commandBase) { OpcUaStatusCode statusCode; CommandBrowse::SPtr commandBrowse = boost::static_pointer_cast<CommandBrowse>(commandBase); // create new or get existing client object ClientAccessObject::SPtr clientAccessObject; clientAccessObject = clientServiceManager.getClientAccessObject(commandBrowse->session()); if (clientAccessObject.get() == nullptr) { std::stringstream ss; ss << "get client access object failed:" << " Session=" << commandBrowse->session(); errorMessage(ss.str()); return false; } // check session if (clientAccessObject->sessionService_.get() == nullptr) { std::stringstream ss; ss << "session object not exist: " << " Session=" << commandBrowse->session(); return false; } // get or create view service ViewService::SPtr viewService; viewService = clientAccessObject->createViewService(); if (viewService.get() == nullptr) { std::stringstream ss; ss << "get client view service failed" << " Session=" << commandBrowse->session(); errorMessage(ss.str()); return false; } // browse opc ua server information model ViewServiceBrowse viewServiceBrowse; viewServiceBrowse.viewService(viewService); viewServiceBrowse.nodeIdVec(commandBrowse->nodeIdVec()); viewServiceBrowse.direction(commandBrowse->direction()); viewServiceBrowse.recursive(commandBrowse->recursive()); viewServiceBrowse.viewServiceBrowseIf(this); viewServiceBrowse.asyncBrowse(); // wait for the end of the browse command browseCompleted_.waitForCondition(); return true; } void ClientServiceBrowse::viewServiceBrowseDone(OpcUaStatusCode statusCode) { browseCompleted_.conditionTrue(); std::cout << OpcUaStatusCodeMap::shortString(statusCode) << std::endl; } void ClientServiceBrowse::viewServiceBrowseResult( OpcUaStatusCode statusCode, OpcUaNodeId::SPtr& nodeId, ReferenceDescription::Vec& referenceDescriptionVec ) { std::cout << nodeId->toString() << " " << OpcUaStatusCodeMap::shortString(statusCode) << std::endl; ReferenceDescription::Vec::iterator it; for (it = referenceDescriptionVec.begin(); it != referenceDescriptionVec.end(); it++) { ReferenceDescription::SPtr referenceDescription = *it; std::cout << " " << " " << referenceDescription->nodeClass() << " " << referenceDescription->expandedNodeId()->toString() << " " << referenceDescription->typeDefinition()->toString() << " " << referenceDescription->referenceTypeId()->toString() << " " << (referenceDescription->isForward() == 0x01 ? "true" : "true") << " " << referenceDescription->displayName().toString() << " " << referenceDescription->browseName().toString() << std::endl; } } }
31.375
101
0.733566
[ "object", "model" ]
741767f02cbe8a6e97488ccc2e2ec7f37b6f7e44
5,846
cpp
C++
tests/test_random.cpp
robertu94/nvcomp
5d5c194f3449486d989057f632d10954b8d11d75
[ "BSD-3-Clause" ]
256
2020-08-03T17:40:07.000Z
2022-03-30T15:43:10.000Z
tests/test_random.cpp
robertu94/nvcomp
5d5c194f3449486d989057f632d10954b8d11d75
[ "BSD-3-Clause" ]
44
2020-08-11T06:04:23.000Z
2022-03-30T23:34:44.000Z
tests/test_random.cpp
robertu94/nvcomp
5d5c194f3449486d989057f632d10954b8d11d75
[ "BSD-3-Clause" ]
49
2020-08-04T16:03:32.000Z
2022-03-24T10:15:02.000Z
/* * Copyright (c) 2018-2020, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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. */ #define CATCH_CONFIG_MAIN #ifndef VERBOSE #define VERBOSE 0 #endif #include "test_common.h" #include <vector> template <typename T> void test_random( int max_val, int max_run, size_t chunk_size, int numRLEs, int numDeltas, int bitPacking) { // generate random data std::vector<T> data; int seed = (max_val ^ max_run ^ chunk_size); random_runs(data, (T)max_val, (T)max_run, seed); test<T>(data, chunk_size, numRLEs, numDeltas, bitPacking); } TEST_CASE("small-R-int", "[small]") { test_random<int>(10, 10, 10000, 1, 0, 0); } TEST_CASE("small-D-int", "[small]") { test_random<int>(10, 10, 10000, 0, 1, 0); } TEST_CASE("small-b-int", "[small][bp]") { test_random<int>(10, 10, 10000, 0, 0, 1); } TEST_CASE("small-RD-int", "[small]") { test_random<int>(10, 10, 10000, 1, 1, 0); } TEST_CASE("small-Db-int", "[small][bp]") { test_random<int>(10, 10, 10000, 0, 1, 1); } TEST_CASE("small-Rb-int", "[small][bp]") { test_random<int>(10, 10, 10000, 1, 0, 1); } TEST_CASE("small-RR-int", "[small]") { test_random<int>(10, 10, 10000, 2, 0, 0); } TEST_CASE("small-DD-int", "[small]") { test_random<int>(10, 10, 10000, 0, 2, 0); } TEST_CASE("small-RDR-int", "[small]") { test_random<int>(10, 10, 10000, 2, 1, 0); } TEST_CASE("small-RDb-int", "[small][bp]") { test_random<int>(10, 10, 10000, 1, 1, 1); } TEST_CASE("small-RRb-int", "[small][bp]") { test_random<int>(10, 10, 10000, 2, 0, 1); } TEST_CASE("small-DDb-int", "[small][bp]") { test_random<int>(10, 10, 10000, 0, 2, 1); } TEST_CASE("small-RDRb-int", "[small][bp]") { test_random<int>(10, 10, 10000, 2, 1, 1); } TEST_CASE("small-RDDb-int", "[small][bp]") { test_random<int>(10, 10, 10000, 1, 2, 1); } TEST_CASE("small-RDRDb-int", "[small][bp]") { test_random<int>(10, 10, 10000, 2, 2, 1); } TEST_CASE("small-RDRRb-int", "[small][bp]") { test_random<int>(10, 10, 10000, 3, 1, 1); } TEST_CASE("large-b-int", "[large][bp]") { test_random<int>(10000, 1000, 10000000, 0, 0, 1); } TEST_CASE("large-R-int", "[large]") { test_random<int>(10000, 1000, 10000000, 1, 0, 0); } TEST_CASE("large-RD-int", "[large]") { test_random<int>(10000, 1000, 10000000, 1, 1, 0); } TEST_CASE("large-RDR-int", "[large]") { test_random<int>(10000, 1000, 10000000, 2, 1, 0); } TEST_CASE("large-Rb-int", "[large][bp]") { test_random<int>(10000, 1000, 10000000, 1, 0, 1); } TEST_CASE("large-Db-int", "[large][bp]") { test_random<int>(10000, 1000, 10000000, 0, 1, 1); } TEST_CASE("large-RDb-int", "[large][bp]") { test_random<int>(10000, 1000, 10000000, 1, 1, 1); } TEST_CASE("large-RRb-int", "[large][bp]") { test_random<int>(10000, 1000, 10000000, 2, 0, 1); } TEST_CASE("large-DDb-int", "[large][bp]") { test_random<int>(10000, 1000, 10000000, 0, 2, 1); } TEST_CASE("large-RDRb-int", "[large][bp]") { test_random<int>(10000, 1000, 10000000, 2, 1, 1); } TEST_CASE("large-RDDb-int", "[large][bp]") { test_random<int>(10000, 1000, 10000000, 1, 2, 1); } // long long TEST_CASE("small-R-ll", "[small]") { test_random<int64_t>(10, 10, 10000, 1, 0, 0); } TEST_CASE("small-RD-ll", "[small]") { test_random<int64_t>(10, 10, 10000, 1, 1, 0); } TEST_CASE("small-RDR-ll", "[small]") { test_random<int64_t>(10, 10, 10000, 2, 1, 0); } TEST_CASE("small-Rb-ll", "[small][bp]") { test_random<int64_t>(10, 10, 10000, 1, 0, 1); } TEST_CASE("small-RDb-ll", "[small][bp]") { test_random<int64_t>(10, 10, 10000, 1, 1, 1); } TEST_CASE("small-RDRb-ll", "[small][bp]") { test_random<int64_t>(10, 10, 10000, 2, 1, 1); } TEST_CASE("large-R-ll", "[large]") { test_random<int64_t>(10000, 1000, 10000000, 1, 0, 0); } TEST_CASE("large-RD-ll", "[large]") { test_random<int64_t>(10000, 1000, 10000000, 1, 1, 0); } TEST_CASE("large-RDR-ll", "[large]") { test_random<int64_t>(10000, 1000, 10000000, 2, 1, 0); } TEST_CASE("large-Rb-ll", "[large][bp]") { test_random<int64_t>(10000, 1000, 10000000, 1, 0, 1); } TEST_CASE("large-RDb-ll", "[large][bp]") { test_random<int64_t>(10000, 1000, 10000000, 1, 1, 1); } TEST_CASE("large-RDRb-ll", "[large][bp]") { test_random<int64_t>(10000, 1000, 10000000, 2, 1, 1); } TEST_CASE("large-RLE-expand", "[large][bp]") { const int n = 100 * 1000 * 1000; const int val = 74252534; std::vector<int> data(n, val); test(data, n, 1, 0, 1); }
26.098214
74
0.656346
[ "vector" ]
7418607bd5d19a9bebd910e1f32dd59f77201542
77,863
cpp
C++
src/TritonRoute/src/dr/FlexDR.cpp
ravi-varadarajan/OpenROAD
dc228c6a539157349d9391d893ed255b51dd4f64
[ "BSD-3-Clause-Clear" ]
null
null
null
src/TritonRoute/src/dr/FlexDR.cpp
ravi-varadarajan/OpenROAD
dc228c6a539157349d9391d893ed255b51dd4f64
[ "BSD-3-Clause-Clear" ]
null
null
null
src/TritonRoute/src/dr/FlexDR.cpp
ravi-varadarajan/OpenROAD
dc228c6a539157349d9391d893ed255b51dd4f64
[ "BSD-3-Clause-Clear" ]
null
null
null
/* Authors: Lutong Wang and Bangqi Xu */ /* * Copyright (c) 2019, The Regents of the University of California * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University 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 REGENTS 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 <omp.h> #include <boost/io/ios_state.hpp> #include <chrono> #include <fstream> #include <sstream> #include "db/infra/frTime.h" #include "dr/FlexDR.h" #include "dr/FlexDR_graphics.h" #include "frProfileTask.h" #include "gc/FlexGC.h" using namespace std; using namespace fr; FlexDR::FlexDR(frDesign* designIn, Logger* loggerIn, odb::dbDatabase* dbIn) : design_(designIn), logger_(loggerIn), db_(dbIn) { } FlexDR::~FlexDR() { } void FlexDR::setDebug(frDebugSettings* settings) { bool on = settings->debugDR; graphics_ = on && FlexDRGraphics::guiActive() ? std::make_unique<FlexDRGraphics>(settings, design_, db_, logger_) : nullptr; } int FlexDRWorker::main(frDesign* design) { ProfileTask profile("DR:main"); using namespace std::chrono; high_resolution_clock::time_point t0 = high_resolution_clock::now(); if (VERBOSE > 1) { frBox scaledBox; stringstream ss; ss << endl << "start DR worker (BOX) " << "( " << routeBox_.left() * 1.0 / getTech()->getDBUPerUU() << " " << routeBox_.bottom() * 1.0 / getTech()->getDBUPerUU() << " ) ( " << routeBox_.right() * 1.0 / getTech()->getDBUPerUU() << " " << routeBox_.top() * 1.0 / getTech()->getDBUPerUU() << " )" << endl; cout << ss.str() << flush; } init(design); high_resolution_clock::time_point t1 = high_resolution_clock::now(); if (!skipRouting_) { FlexGCWorker gcWorker(design->getTech(), logger_, this); gcWorker.setExtBox(getExtBox()); gcWorker.setDrcBox(getDrcBox()); gcWorker.init(design); gcWorker.setEnableSurgicalFix(true); route_queue(gcWorker); } high_resolution_clock::time_point t2 = high_resolution_clock::now(); cleanup(); high_resolution_clock::time_point t3 = high_resolution_clock::now(); duration<double> time_span0 = duration_cast<duration<double>>(t1 - t0); duration<double> time_span1 = duration_cast<duration<double>>(t2 - t1); duration<double> time_span2 = duration_cast<duration<double>>(t3 - t2); if (VERBOSE > 1) { stringstream ss; ss << "time (INIT/ROUTE/POST) " << time_span0.count() << " " << time_span1.count() << " " << time_span2.count() << " " << endl; cout << ss.str() << flush; } return 0; } void FlexDR::initFromTA() { // initialize lists for (auto& net : getDesign()->getTopBlock()->getNets()) { for (auto& guide : net->getGuides()) { for (auto& connFig : guide->getRoutes()) { if (connFig->typeId() == frcPathSeg) { unique_ptr<frShape> ps = make_unique<frPathSeg>( *(static_cast<frPathSeg*>(connFig.get()))); frPoint bp, ep; static_cast<frPathSeg*>(ps.get())->getPoints(bp, ep); if (ep.x() - bp.x() + ep.y() - bp.y() == 1) { ; // skip TA dummy segment } else { net->addShape(std::move(ps)); } } else { cout << "Error: initFromTA unsupported shape" << endl; } } } } } void FlexDR::initGCell2BoundaryPin() { // initiailize size frBox dieBox; getDesign()->getTopBlock()->getDieBox(dieBox); auto gCellPatterns = getDesign()->getTopBlock()->getGCellPatterns(); auto& xgp = gCellPatterns.at(0); auto& ygp = gCellPatterns.at(1); auto tmpVec = vector<map<frNet*, set<pair<frPoint, frLayerNum>>, frBlockObjectComp>>( (int) ygp.getCount()); gcell2BoundaryPin_ = vector< vector<map<frNet*, set<pair<frPoint, frLayerNum>>, frBlockObjectComp>>>( (int) xgp.getCount(), tmpVec); for (auto& net : getDesign()->getTopBlock()->getNets()) { auto netPtr = net.get(); for (auto& guide : net->getGuides()) { for (auto& connFig : guide->getRoutes()) { if (connFig->typeId() == frcPathSeg) { auto ps = static_cast<frPathSeg*>(connFig.get()); frLayerNum layerNum; frPoint bp, ep; ps->getPoints(bp, ep); layerNum = ps->getLayerNum(); // skip TA dummy segment if (ep.x() - bp.x() + ep.y() - bp.y() == 1 || ep.x() - bp.x() + ep.y() - bp.y() == 0) { continue; } frPoint idx1, idx2; getDesign()->getTopBlock()->getGCellIdx(bp, idx1); getDesign()->getTopBlock()->getGCellIdx(ep, idx2); // update gcell2BoundaryPin // horizontal if (bp.y() == ep.y()) { int x1 = idx1.x(); int x2 = idx2.x(); int y = idx1.y(); for (auto x = x1; x <= x2; ++x) { frBox gcellBox; getDesign()->getTopBlock()->getGCellBox(frPoint(x, y), gcellBox); frCoord leftBound = gcellBox.left(); frCoord rightBound = gcellBox.right(); bool hasLeftBound = true; bool hasRightBound = true; if (bp.x() < leftBound) { hasLeftBound = true; } else { hasLeftBound = false; } if (ep.x() >= rightBound) { hasRightBound = true; } else { hasRightBound = false; } if (hasLeftBound) { frPoint boundaryPt(leftBound, bp.y()); gcell2BoundaryPin_[x][y][netPtr].insert( make_pair(boundaryPt, layerNum)); } if (hasRightBound) { frPoint boundaryPt(rightBound, ep.y()); gcell2BoundaryPin_[x][y][netPtr].insert( make_pair(boundaryPt, layerNum)); } } } else if (bp.x() == ep.x()) { int x = idx1.x(); int y1 = idx1.y(); int y2 = idx2.y(); for (auto y = y1; y <= y2; ++y) { frBox gcellBox; getDesign()->getTopBlock()->getGCellBox(frPoint(x, y), gcellBox); frCoord bottomBound = gcellBox.bottom(); frCoord topBound = gcellBox.top(); bool hasBottomBound = true; bool hasTopBound = true; if (bp.y() < bottomBound) { hasBottomBound = true; } else { hasBottomBound = false; } if (ep.y() >= topBound) { hasTopBound = true; } else { hasTopBound = false; } if (hasBottomBound) { frPoint boundaryPt(bp.x(), bottomBound); gcell2BoundaryPin_[x][y][netPtr].insert( make_pair(boundaryPt, layerNum)); } if (hasTopBound) { frPoint boundaryPt(ep.x(), topBound); gcell2BoundaryPin_[x][y][netPtr].insert( make_pair(boundaryPt, layerNum)); } } } else { cout << "Error: non-orthogonal pathseg in initGCell2BoundryPin\n"; } } } } } } frCoord FlexDR::init_via2viaMinLen_minimumcut1(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2) { if (!(viaDef1 && viaDef2)) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isH = (getTech()->getLayer(lNum)->getDir() == frPrefRoutingDirEnum::frcHorzPrefRoutingDir); bool isVia1Above = false; frVia via1(viaDef1); frBox viaBox1, cutBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); isVia1Above = true; } else { via1.getLayer2BBox(viaBox1); isVia1Above = false; } via1.getCutBBox(cutBox1); auto width1 = viaBox1.width(); auto length1 = viaBox1.length(); bool isVia2Above = false; frVia via2(viaDef2); frBox viaBox2, cutBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); isVia2Above = true; } else { via2.getLayer2BBox(viaBox2); isVia2Above = false; } via2.getCutBBox(cutBox2); auto width2 = viaBox2.width(); auto length2 = viaBox2.length(); for (auto& con : getTech()->getLayer(lNum)->getMinimumcutConstraints()) { if ((!con->hasLength() || (con->hasLength() && length1 > con->getLength())) && width1 > con->getWidth()) { bool checkVia2 = false; if (!con->hasConnection()) { checkVia2 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia2Above) { checkVia2 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia2Above) { checkVia2 = true; } } if (!checkVia2) { continue; } if (isH) { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox2.right() - 0 + 0 - viaBox1.left(), viaBox1.right() - 0 + 0 - cutBox2.left())); } else { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox2.top() - 0 + 0 - viaBox1.bottom(), viaBox1.top() - 0 + 0 - cutBox2.bottom())); } } // check via1cut to via2metal if ((!con->hasLength() || (con->hasLength() && length2 > con->getLength())) && width2 > con->getWidth()) { bool checkVia1 = false; if (!con->hasConnection()) { checkVia1 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia1Above) { checkVia1 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia1Above) { checkVia1 = true; } } if (!checkVia1) { continue; } if (isH) { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox1.right() - 0 + 0 - viaBox2.left(), viaBox2.right() - 0 + 0 - cutBox1.left())); } else { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox1.top() - 0 + 0 - viaBox2.bottom(), viaBox2.top() - 0 + 0 - cutBox1.bottom())); } } } return sol; } bool FlexDR::init_via2viaMinLen_minimumcut2(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2) { if (!(viaDef1 && viaDef2)) { return true; } // skip if same-layer via if (viaDef1 == viaDef2) { return true; } bool sol = true; bool isVia1Above = false; frVia via1(viaDef1); frBox viaBox1, cutBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); isVia1Above = true; } else { via1.getLayer2BBox(viaBox1); isVia1Above = false; } via1.getCutBBox(cutBox1); auto width1 = viaBox1.width(); bool isVia2Above = false; frVia via2(viaDef2); frBox viaBox2, cutBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); isVia2Above = true; } else { via2.getLayer2BBox(viaBox2); isVia2Above = false; } via2.getCutBBox(cutBox2); auto width2 = viaBox2.width(); for (auto& con : getTech()->getLayer(lNum)->getMinimumcutConstraints()) { if (con->hasLength()) { continue; } // check via2cut to via1metal if (width1 > con->getWidth()) { bool checkVia2 = false; if (!con->hasConnection()) { checkVia2 = true; } else { // has length rule if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia2Above) { checkVia2 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia2Above) { checkVia2 = true; } } if (!checkVia2) { continue; } sol = false; break; } // check via1cut to via2metal if (width2 > con->getWidth()) { bool checkVia1 = false; if (!con->hasConnection()) { checkVia1 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia1Above) { checkVia1 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia1Above) { checkVia1 = true; } } if (!checkVia1) { continue; } sol = false; break; } } return sol; } frCoord FlexDR::init_via2viaMinLen_minSpc(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2) { if (!(viaDef1 && viaDef2)) { // cout <<"hehehehehe" <<endl; return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isH = (getTech()->getLayer(lNum)->getDir() == frPrefRoutingDirEnum::frcHorzPrefRoutingDir); frCoord defaultWidth = getTech()->getLayer(lNum)->getWidth(); frVia via1(viaDef1); frBox viaBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } auto width1 = viaBox1.width(); bool isVia1Fat = isH ? (viaBox1.top() - viaBox1.bottom() > defaultWidth) : (viaBox1.right() - viaBox1.left() > defaultWidth); auto prl1 = isH ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); frVia via2(viaDef2); frBox viaBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); } else { via2.getLayer2BBox(viaBox2); } auto width2 = viaBox2.width(); bool isVia2Fat = isH ? (viaBox2.top() - viaBox2.bottom() > defaultWidth) : (viaBox2.right() - viaBox2.left() > defaultWidth); auto prl2 = isH ? (viaBox2.top() - viaBox2.bottom()) : (viaBox2.right() - viaBox2.left()); frCoord reqDist = 0; if (isVia1Fat && isVia2Fat) { auto con = getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find( max(width1, width2), min(prl1, prl2)); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find( width1, width2, min(prl1, prl2)); } } if (isH) { reqDist += max((viaBox1.right() - 0), (0 - viaBox1.left())); reqDist += max((viaBox2.right() - 0), (0 - viaBox2.left())); } else { reqDist += max((viaBox1.top() - 0), (0 - viaBox1.bottom())); reqDist += max((viaBox2.top() - 0), (0 - viaBox2.bottom())); } sol = max(sol, reqDist); } // check min len in layer2 if two vias are in same layer if (viaDef1 != viaDef2) { return sol; } if (viaDef1->getLayer1Num() == lNum) { via1.getLayer2BBox(viaBox1); lNum = lNum + 2; } else { via1.getLayer1BBox(viaBox1); lNum = lNum - 2; } width1 = viaBox1.width(); prl1 = isH ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); reqDist = 0; auto con = getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find( max(width1, width2), prl1); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find( width1, width2, prl1); } } if (isH) { reqDist += (viaBox1.right() - 0) + (0 - viaBox1.left()); } else { reqDist += (viaBox1.top() - 0) + (0 - viaBox1.bottom()); } sol = max(sol, reqDist); return sol; } void FlexDR::init_via2viaMinLen() { auto bottomLayerNum = getTech()->getBottomLayerNum(); auto topLayerNum = getTech()->getTopLayerNum(); auto& via2viaMinLen = via_data_.via2viaMinLen; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } vector<frCoord> via2viaMinLenTmp(4, 0); vector<bool> via2viaZeroLen(4, true); via2viaMinLen.push_back(make_pair(via2viaMinLenTmp, via2viaZeroLen)); } // check prl int i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getTech()->getTopLayerNum() >= lNum + 1) { upVia = getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } (via2viaMinLen[i].first)[0] = max((via2viaMinLen[i].first)[0], init_via2viaMinLen_minSpc(lNum, downVia, downVia)); (via2viaMinLen[i].first)[1] = max((via2viaMinLen[i].first)[1], init_via2viaMinLen_minSpc(lNum, downVia, upVia)); (via2viaMinLen[i].first)[2] = max((via2viaMinLen[i].first)[2], init_via2viaMinLen_minSpc(lNum, upVia, downVia)); (via2viaMinLen[i].first)[3] = max((via2viaMinLen[i].first)[3], init_via2viaMinLen_minSpc(lNum, upVia, upVia)); i++; } // check minimumcut i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getTech()->getTopLayerNum() >= lNum + 1) { upVia = getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } vector<frCoord> via2viaMinLenTmp(4, 0); (via2viaMinLen[i].first)[0] = max((via2viaMinLen[i].first)[0], init_via2viaMinLen_minimumcut1(lNum, downVia, downVia)); (via2viaMinLen[i].first)[1] = max((via2viaMinLen[i].first)[1], init_via2viaMinLen_minimumcut1(lNum, downVia, upVia)); (via2viaMinLen[i].first)[2] = max((via2viaMinLen[i].first)[2], init_via2viaMinLen_minimumcut1(lNum, upVia, downVia)); (via2viaMinLen[i].first)[3] = max((via2viaMinLen[i].first)[3], init_via2viaMinLen_minimumcut1(lNum, upVia, upVia)); (via2viaMinLen[i].second)[0] = (via2viaMinLen[i].second)[0] && init_via2viaMinLen_minimumcut2(lNum, downVia, downVia); (via2viaMinLen[i].second)[1] = (via2viaMinLen[i].second)[1] && init_via2viaMinLen_minimumcut2(lNum, downVia, upVia); (via2viaMinLen[i].second)[2] = (via2viaMinLen[i].second)[2] && init_via2viaMinLen_minimumcut2(lNum, upVia, downVia); (via2viaMinLen[i].second)[3] = (via2viaMinLen[i].second)[3] && init_via2viaMinLen_minimumcut2(lNum, upVia, upVia); i++; } } frCoord FlexDR::init_via2viaMinLenNew_minimumcut1(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2, bool isCurrDirY) { if (!(viaDef1 && viaDef2)) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isCurrDirX = !isCurrDirY; bool isVia1Above = false; frVia via1(viaDef1); frBox viaBox1, cutBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); isVia1Above = true; } else { via1.getLayer2BBox(viaBox1); isVia1Above = false; } via1.getCutBBox(cutBox1); auto width1 = viaBox1.width(); auto length1 = viaBox1.length(); bool isVia2Above = false; frVia via2(viaDef2); frBox viaBox2, cutBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); isVia2Above = true; } else { via2.getLayer2BBox(viaBox2); isVia2Above = false; } via2.getCutBBox(cutBox2); auto width2 = viaBox2.width(); auto length2 = viaBox2.length(); for (auto& con : getTech()->getLayer(lNum)->getMinimumcutConstraints()) { // check via2cut to via1metal // no length OR metal1 shape satisfies --> check via2 if ((!con->hasLength() || (con->hasLength() && length1 > con->getLength())) && width1 > con->getWidth()) { bool checkVia2 = false; if (!con->hasConnection()) { checkVia2 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia2Above) { checkVia2 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia2Above) { checkVia2 = true; } } if (!checkVia2) { continue; } if (isCurrDirX) { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox2.right() - 0 + 0 - viaBox1.left(), viaBox1.right() - 0 + 0 - cutBox2.left())); } else { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox2.top() - 0 + 0 - viaBox1.bottom(), viaBox1.top() - 0 + 0 - cutBox2.bottom())); } } // check via1cut to via2metal if ((!con->hasLength() || (con->hasLength() && length2 > con->getLength())) && width2 > con->getWidth()) { bool checkVia1 = false; if (!con->hasConnection()) { checkVia1 = true; } else { if (con->getConnection() == frMinimumcutConnectionEnum::FROMABOVE && isVia1Above) { checkVia1 = true; } else if (con->getConnection() == frMinimumcutConnectionEnum::FROMBELOW && !isVia1Above) { checkVia1 = true; } } if (!checkVia1) { continue; } if (isCurrDirX) { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox1.right() - 0 + 0 - viaBox2.left(), viaBox2.right() - 0 + 0 - cutBox1.left())); } else { sol = max(sol, (con->hasLength() ? con->getDistance() : 0) + max(cutBox1.top() - 0 + 0 - viaBox2.bottom(), viaBox2.top() - 0 + 0 - cutBox1.bottom())); } } } return sol; } frCoord FlexDR::init_via2viaMinLenNew_minSpc(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2, bool isCurrDirY) { if (!(viaDef1 && viaDef2)) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isCurrDirX = !isCurrDirY; frCoord defaultWidth = getTech()->getLayer(lNum)->getWidth(); frVia via1(viaDef1); frBox viaBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } auto width1 = viaBox1.width(); bool isVia1Fat = isCurrDirX ? (viaBox1.top() - viaBox1.bottom() > defaultWidth) : (viaBox1.right() - viaBox1.left() > defaultWidth); auto prl1 = isCurrDirX ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); frVia via2(viaDef2); frBox viaBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); } else { via2.getLayer2BBox(viaBox2); } auto width2 = viaBox2.width(); bool isVia2Fat = isCurrDirX ? (viaBox2.top() - viaBox2.bottom() > defaultWidth) : (viaBox2.right() - viaBox2.left() > defaultWidth); auto prl2 = isCurrDirX ? (viaBox2.top() - viaBox2.bottom()) : (viaBox2.right() - viaBox2.left()); frCoord reqDist = 0; if (isVia1Fat && isVia2Fat) { auto con = getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find( max(width1, width2), min(prl1, prl2)); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find( width1, width2, min(prl1, prl2)); } } if (isCurrDirX) { reqDist += max((viaBox1.right() - 0), (0 - viaBox1.left())); reqDist += max((viaBox2.right() - 0), (0 - viaBox2.left())); } else { reqDist += max((viaBox1.top() - 0), (0 - viaBox1.bottom())); reqDist += max((viaBox2.top() - 0), (0 - viaBox2.bottom())); } sol = max(sol, reqDist); } // check min len in layer2 if two vias are in same layer if (viaDef1 != viaDef2) { return sol; } if (viaDef1->getLayer1Num() == lNum) { via1.getLayer2BBox(viaBox1); lNum = lNum + 2; } else { via1.getLayer1BBox(viaBox1); lNum = lNum - 2; } width1 = viaBox1.width(); prl1 = isCurrDirX ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); reqDist = 0; auto con = getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find( max(width1, width2), prl1); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find( width1, width2, prl1); } } if (isCurrDirX) { reqDist += (viaBox1.right() - 0) + (0 - viaBox1.left()); } else { reqDist += (viaBox1.top() - 0) + (0 - viaBox1.bottom()); } sol = max(sol, reqDist); return sol; } frCoord FlexDR::init_via2viaMinLenNew_cutSpc(frLayerNum lNum, frViaDef* viaDef1, frViaDef* viaDef2, bool isCurrDirY) { if (!(viaDef1 && viaDef2)) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing frVia via1(viaDef1); frBox viaBox1, cutBox1; if (viaDef1->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } via1.getCutBBox(cutBox1); frVia via2(viaDef2); frBox viaBox2, cutBox2; if (viaDef2->getLayer1Num() == lNum) { via2.getLayer1BBox(viaBox2); } else { via2.getLayer2BBox(viaBox2); } via2.getCutBBox(cutBox2); // same layer (use samenet rule if exist, otherwise use diffnet rule) if (viaDef1->getCutLayerNum() == viaDef2->getCutLayerNum()) { auto samenetCons = getTech()->getLayer(viaDef1->getCutLayerNum())->getCutSpacing(true); auto diffnetCons = getTech()->getLayer(viaDef1->getCutLayerNum())->getCutSpacing(false); if (!samenetCons.empty()) { // check samenet spacing rule if exists for (auto con : samenetCons) { if (con == nullptr) { continue; } // filter rule, assuming default via will never trigger cutArea if (con->hasSecondLayer() || con->isAdjacentCuts() || con->isParallelOverlap() || con->isArea() || !con->hasSameNet()) { continue; } auto reqSpcVal = con->getCutSpacing(); if (!con->hasCenterToCenter()) { reqSpcVal += isCurrDirY ? (cutBox1.top() - cutBox1.bottom()) : (cutBox1.right() - cutBox1.left()); } sol = max(sol, reqSpcVal); } } else { // check diffnet spacing rule // filter rule, assuming default via will never trigger cutArea for (auto con : diffnetCons) { if (con == nullptr) { continue; } if (con->hasSecondLayer() || con->isAdjacentCuts() || con->isParallelOverlap() || con->isArea() || con->hasSameNet()) { continue; } auto reqSpcVal = con->getCutSpacing(); if (!con->hasCenterToCenter()) { reqSpcVal += isCurrDirY ? (cutBox1.top() - cutBox1.bottom()) : (cutBox1.right() - cutBox1.left()); } sol = max(sol, reqSpcVal); } } // TODO: diff layer } else { auto layerNum1 = viaDef1->getCutLayerNum(); auto layerNum2 = viaDef2->getCutLayerNum(); frCutSpacingConstraint* samenetCon = nullptr; if (getTech()->getLayer(layerNum1)->hasInterLayerCutSpacing(layerNum2, true)) { samenetCon = getTech()->getLayer(layerNum1)->getInterLayerCutSpacing( layerNum2, true); } if (getTech()->getLayer(layerNum2)->hasInterLayerCutSpacing(layerNum1, true)) { if (samenetCon) { cout << "Warning: duplicate diff layer samenet cut spacing, skipping " "cut spacing from " << layerNum2 << " to " << layerNum1 << endl; } else { samenetCon = getTech()->getLayer(layerNum2)->getInterLayerCutSpacing( layerNum1, true); } } if (samenetCon == nullptr) { if (getTech()->getLayer(layerNum1)->hasInterLayerCutSpacing(layerNum2, false)) { samenetCon = getTech()->getLayer(layerNum1)->getInterLayerCutSpacing( layerNum2, false); } if (getTech()->getLayer(layerNum2)->hasInterLayerCutSpacing(layerNum1, false)) { if (samenetCon) { cout << "Warning: duplicate diff layer diffnet cut spacing, skipping " "cut spacing from " << layerNum2 << " to " << layerNum1 << endl; } else { samenetCon = getTech()->getLayer(layerNum2)->getInterLayerCutSpacing( layerNum1, false); } } } if (samenetCon) { // filter rule, assuming default via will never trigger cutArea auto reqSpcVal = samenetCon->getCutSpacing(); if (reqSpcVal == 0) { ; } else { if (!samenetCon->hasCenterToCenter()) { reqSpcVal += isCurrDirY ? (cutBox1.top() - cutBox1.bottom()) : (cutBox1.right() - cutBox1.left()); } } sol = max(sol, reqSpcVal); } } return sol; } void FlexDR::init_via2viaMinLenNew() { auto bottomLayerNum = getTech()->getBottomLayerNum(); auto topLayerNum = getTech()->getTopLayerNum(); auto& via2viaMinLenNew = via_data_.via2viaMinLenNew; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } vector<frCoord> via2viaMinLenTmp(8, 0); via2viaMinLenNew.push_back(via2viaMinLenTmp); } // check prl int i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getTech()->getTopLayerNum() >= lNum + 1) { upVia = getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } via2viaMinLenNew[i][0] = max(via2viaMinLenNew[i][0], init_via2viaMinLenNew_minSpc(lNum, downVia, downVia, false)); via2viaMinLenNew[i][1] = max(via2viaMinLenNew[i][1], init_via2viaMinLenNew_minSpc(lNum, downVia, downVia, true)); via2viaMinLenNew[i][2] = max(via2viaMinLenNew[i][2], init_via2viaMinLenNew_minSpc(lNum, downVia, upVia, false)); via2viaMinLenNew[i][3] = max(via2viaMinLenNew[i][3], init_via2viaMinLenNew_minSpc(lNum, downVia, upVia, true)); via2viaMinLenNew[i][4] = max(via2viaMinLenNew[i][4], init_via2viaMinLenNew_minSpc(lNum, upVia, downVia, false)); via2viaMinLenNew[i][5] = max(via2viaMinLenNew[i][5], init_via2viaMinLenNew_minSpc(lNum, upVia, downVia, true)); via2viaMinLenNew[i][6] = max(via2viaMinLenNew[i][6], init_via2viaMinLenNew_minSpc(lNum, upVia, upVia, false)); via2viaMinLenNew[i][7] = max(via2viaMinLenNew[i][7], init_via2viaMinLenNew_minSpc(lNum, upVia, upVia, true)); i++; } // check minimumcut i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getTech()->getTopLayerNum() >= lNum + 1) { upVia = getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } via2viaMinLenNew[i][0] = max(via2viaMinLenNew[i][0], init_via2viaMinLenNew_minimumcut1(lNum, downVia, downVia, false)); via2viaMinLenNew[i][1] = max(via2viaMinLenNew[i][1], init_via2viaMinLenNew_minimumcut1(lNum, downVia, downVia, true)); via2viaMinLenNew[i][2] = max(via2viaMinLenNew[i][2], init_via2viaMinLenNew_minimumcut1(lNum, downVia, upVia, false)); via2viaMinLenNew[i][3] = max(via2viaMinLenNew[i][3], init_via2viaMinLenNew_minimumcut1(lNum, downVia, upVia, true)); via2viaMinLenNew[i][4] = max(via2viaMinLenNew[i][4], init_via2viaMinLenNew_minimumcut1(lNum, upVia, downVia, false)); via2viaMinLenNew[i][5] = max(via2viaMinLenNew[i][5], init_via2viaMinLenNew_minimumcut1(lNum, upVia, downVia, true)); via2viaMinLenNew[i][6] = max(via2viaMinLenNew[i][6], init_via2viaMinLenNew_minimumcut1(lNum, upVia, upVia, false)); via2viaMinLenNew[i][7] = max(via2viaMinLenNew[i][7], init_via2viaMinLenNew_minimumcut1(lNum, upVia, upVia, true)); i++; } // check cut spacing i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getTech()->getTopLayerNum() >= lNum + 1) { upVia = getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } via2viaMinLenNew[i][0] = max(via2viaMinLenNew[i][0], init_via2viaMinLenNew_cutSpc(lNum, downVia, downVia, false)); via2viaMinLenNew[i][1] = max(via2viaMinLenNew[i][1], init_via2viaMinLenNew_cutSpc(lNum, downVia, downVia, true)); via2viaMinLenNew[i][2] = max(via2viaMinLenNew[i][2], init_via2viaMinLenNew_cutSpc(lNum, downVia, upVia, false)); via2viaMinLenNew[i][3] = max(via2viaMinLenNew[i][3], init_via2viaMinLenNew_cutSpc(lNum, downVia, upVia, true)); via2viaMinLenNew[i][4] = max(via2viaMinLenNew[i][4], init_via2viaMinLenNew_cutSpc(lNum, upVia, downVia, false)); via2viaMinLenNew[i][5] = max(via2viaMinLenNew[i][5], init_via2viaMinLenNew_cutSpc(lNum, upVia, downVia, true)); via2viaMinLenNew[i][6] = max(via2viaMinLenNew[i][6], init_via2viaMinLenNew_cutSpc(lNum, upVia, upVia, false)); via2viaMinLenNew[i][7] = max(via2viaMinLenNew[i][7], init_via2viaMinLenNew_cutSpc(lNum, upVia, upVia, true)); i++; } } void FlexDR::init_halfViaEncArea() { auto bottomLayerNum = getTech()->getBottomLayerNum(); auto topLayerNum = getTech()->getTopLayerNum(); auto& halfViaEncArea = via_data_.halfViaEncArea; for (int i = bottomLayerNum; i <= topLayerNum; i++) { if (getTech()->getLayer(i)->getType() != frLayerTypeEnum::ROUTING) { continue; } if (i + 1 <= topLayerNum && getTech()->getLayer(i + 1)->getType() == frLayerTypeEnum::CUT) { auto viaDef = getTech()->getLayer(i + 1)->getDefaultViaDef(); frVia via(viaDef); frBox layer1Box; frBox layer2Box; via.getLayer1BBox(layer1Box); via.getLayer2BBox(layer2Box); auto layer1HalfArea = layer1Box.width() * layer1Box.length() / 2; auto layer2HalfArea = layer2Box.width() * layer2Box.length() / 2; halfViaEncArea.push_back(make_pair(layer1HalfArea, layer2HalfArea)); } else { halfViaEncArea.push_back(make_pair(0, 0)); } } } frCoord FlexDR::init_via2turnMinLen_minSpc(frLayerNum lNum, frViaDef* viaDef, bool isCurrDirY) { if (!viaDef) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isCurrDirX = !isCurrDirY; frCoord defaultWidth = getTech()->getLayer(lNum)->getWidth(); frVia via1(viaDef); frBox viaBox1; if (viaDef->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } auto width1 = viaBox1.width(); bool isVia1Fat = isCurrDirX ? (viaBox1.top() - viaBox1.bottom() > defaultWidth) : (viaBox1.right() - viaBox1.left() > defaultWidth); auto prl1 = isCurrDirX ? (viaBox1.top() - viaBox1.bottom()) : (viaBox1.right() - viaBox1.left()); frCoord reqDist = 0; if (isVia1Fat) { auto con = getTech()->getLayer(lNum)->getMinSpacing(); if (con) { if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) { reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing(); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) { reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find( max(width1, defaultWidth), prl1); } else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) { reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find( width1, defaultWidth, prl1); } } if (isCurrDirX) { reqDist += max((viaBox1.right() - 0), (0 - viaBox1.left())); reqDist += defaultWidth; } else { reqDist += max((viaBox1.top() - 0), (0 - viaBox1.bottom())); reqDist += defaultWidth; } sol = max(sol, reqDist); } return sol; } frCoord FlexDR::init_via2turnMinLen_minStp(frLayerNum lNum, frViaDef* viaDef, bool isCurrDirY) { if (!viaDef) { return 0; } frCoord sol = 0; // check min len in lNum assuming pre dir routing bool isCurrDirX = !isCurrDirY; frCoord defaultWidth = getTech()->getLayer(lNum)->getWidth(); frVia via1(viaDef); frBox viaBox1; if (viaDef->getLayer1Num() == lNum) { via1.getLayer1BBox(viaBox1); } else { via1.getLayer2BBox(viaBox1); } bool isVia1Fat = isCurrDirX ? (viaBox1.top() - viaBox1.bottom() > defaultWidth) : (viaBox1.right() - viaBox1.left() > defaultWidth); frCoord reqDist = 0; if (isVia1Fat) { auto con = getTech()->getLayer(lNum)->getMinStepConstraint(); if (con && con->hasMaxEdges()) { // currently only consider maxedge violation reqDist = con->getMinStepLength(); if (isCurrDirX) { reqDist += max((viaBox1.right() - 0), (0 - viaBox1.left())); reqDist += defaultWidth; } else { reqDist += max((viaBox1.top() - 0), (0 - viaBox1.bottom())); reqDist += defaultWidth; } sol = max(sol, reqDist); } } return sol; } void FlexDR::init_via2turnMinLen() { auto bottomLayerNum = getTech()->getBottomLayerNum(); auto topLayerNum = getTech()->getTopLayerNum(); auto& via2turnMinLen = via_data_.via2turnMinLen; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } vector<frCoord> via2turnMinLenTmp(4, 0); via2turnMinLen.push_back(via2turnMinLenTmp); } // check prl int i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getTech()->getTopLayerNum() >= lNum + 1) { upVia = getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } via2turnMinLen[i][0] = max( via2turnMinLen[i][0], init_via2turnMinLen_minSpc(lNum, downVia, false)); via2turnMinLen[i][1] = max(via2turnMinLen[i][1], init_via2turnMinLen_minSpc(lNum, downVia, true)); via2turnMinLen[i][2] = max(via2turnMinLen[i][2], init_via2turnMinLen_minSpc(lNum, upVia, false)); via2turnMinLen[i][3] = max(via2turnMinLen[i][3], init_via2turnMinLen_minSpc(lNum, upVia, true)); i++; } // check minstep i = 0; for (auto lNum = bottomLayerNum; lNum <= topLayerNum; lNum++) { if (getTech()->getLayer(lNum)->getType() != frLayerTypeEnum::ROUTING) { continue; } frViaDef* downVia = nullptr; frViaDef* upVia = nullptr; if (getTech()->getBottomLayerNum() <= lNum - 1) { downVia = getTech()->getLayer(lNum - 1)->getDefaultViaDef(); } if (getTech()->getTopLayerNum() >= lNum + 1) { upVia = getTech()->getLayer(lNum + 1)->getDefaultViaDef(); } vector<frCoord> via2turnMinLenTmp(4, 0); via2turnMinLen[i][0] = max( via2turnMinLen[i][0], init_via2turnMinLen_minStp(lNum, downVia, false)); via2turnMinLen[i][1] = max(via2turnMinLen[i][1], init_via2turnMinLen_minStp(lNum, downVia, true)); via2turnMinLen[i][2] = max(via2turnMinLen[i][2], init_via2turnMinLen_minStp(lNum, upVia, false)); via2turnMinLen[i][3] = max(via2turnMinLen[i][3], init_via2turnMinLen_minStp(lNum, upVia, true)); i++; } } void FlexDR::init() { ProfileTask profile("DR:init"); frTime t; if (VERBOSE > 0) { logger_->info(DRT, 187, "start routing data preparation"); } initGCell2BoundaryPin(); getRegionQuery()->initDRObj(); // first init in postProcess init_halfViaEncArea(); init_via2viaMinLen(); init_via2viaMinLenNew(); init_via2turnMinLen(); if (VERBOSE > 0) { t.print(logger_); } } void FlexDR::removeGCell2BoundaryPin() { gcell2BoundaryPin_.clear(); gcell2BoundaryPin_.shrink_to_fit(); } map<frNet*, set<pair<frPoint, frLayerNum>>, frBlockObjectComp> FlexDR::initDR_mergeBoundaryPin(int startX, int startY, int size, const frBox& routeBox) { map<frNet*, set<pair<frPoint, frLayerNum>>, frBlockObjectComp> bp; auto gCellPatterns = getDesign()->getTopBlock()->getGCellPatterns(); auto& xgp = gCellPatterns.at(0); auto& ygp = gCellPatterns.at(1); for (int i = startX; i < (int) xgp.getCount() && i < startX + size; i++) { for (int j = startY; j < (int) ygp.getCount() && j < startY + size; j++) { auto& currBp = gcell2BoundaryPin_[i][j]; for (auto& [net, s] : currBp) { for (auto& [pt, lNum] : s) { if (pt.x() == routeBox.left() || pt.x() == routeBox.right() || pt.y() == routeBox.bottom() || pt.y() == routeBox.top()) { bp[net].insert(make_pair(pt, lNum)); } } } } } return bp; } void FlexDR::getBatchInfo(int& batchStepX, int& batchStepY) { batchStepX = 2; batchStepY = 2; } void FlexDR::searchRepair(int iter, int size, int offset, int mazeEndIter, frUInt4 workerDRCCost, frUInt4 workerMarkerCost, int ripupMode, bool followGuide) { std::string profile_name("DR:searchRepair"); profile_name += std::to_string(iter); ProfileTask profile(profile_name.c_str()); if (iter > END_ITERATION) { return; } if (ripupMode != 1 && getDesign()->getTopBlock()->getMarkers().size() == 0) { return; } if (iter < 3) FIXEDSHAPECOST = ROUTESHAPECOST; else if (iter < 10) FIXEDSHAPECOST = 2 * ROUTESHAPECOST; else if (iter < 15) FIXEDSHAPECOST = 3 * ROUTESHAPECOST; else if (iter < 20) FIXEDSHAPECOST = 4 * ROUTESHAPECOST; else if (iter < 30) FIXEDSHAPECOST = 10 * ROUTESHAPECOST; else if (iter < 40) FIXEDSHAPECOST = 50 * ROUTESHAPECOST; else FIXEDSHAPECOST = 100 * ROUTESHAPECOST; if (iter == 40) MARKERDECAY = 0.99; if (iter == 50) MARKERDECAY = 0.999; frTime t; if (VERBOSE > 0) { string suffix; if (iter == 1 || (iter > 20 && iter % 10 == 1)) { suffix = "st"; } else if (iter == 2 || (iter > 20 && iter % 10 == 2)) { suffix = "nd"; } else if (iter == 3 || (iter > 20 && iter % 10 == 3)) { suffix = "rd"; } else { suffix = "th"; } logger_->info( DRT, 195, "start {}{} optimization iteration ...", iter, suffix); } if (graphics_) { graphics_->startIter(iter); } frBox dieBox; getDesign()->getTopBlock()->getDieBox(dieBox); auto gCellPatterns = getDesign()->getTopBlock()->getGCellPatterns(); auto& xgp = gCellPatterns.at(0); auto& ygp = gCellPatterns.at(1); int clipSize = size; int cnt = 0; int tot = (((int) xgp.getCount() - 1 - offset) / clipSize + 1) * (((int) ygp.getCount() - 1 - offset) / clipSize + 1); int prev_perc = 0; bool isExceed = false; vector<unique_ptr<FlexDRWorker>> uworkers; int batchStepX, batchStepY; getBatchInfo(batchStepX, batchStepY); vector<vector<vector<unique_ptr<FlexDRWorker>>>> workers(batchStepX * batchStepY); int xIdx = 0, yIdx = 0; for (int i = offset; i < (int) xgp.getCount(); i += clipSize) { for (int j = offset; j < (int) ygp.getCount(); j += clipSize) { auto worker = make_unique<FlexDRWorker>(&via_data_, getTech(), logger_); frBox routeBox1; getDesign()->getTopBlock()->getGCellBox(frPoint(i, j), routeBox1); frBox routeBox2; const int max_i = min((int) xgp.getCount() - 1, i + clipSize - 1); const int max_j = min((int) ygp.getCount(), j + clipSize - 1); getDesign()->getTopBlock()->getGCellBox(frPoint(max_i, max_j), routeBox2); frBox routeBox(routeBox1.left(), routeBox1.bottom(), routeBox2.right(), routeBox2.top()); frBox extBox; frBox drcBox; routeBox.bloat(MTSAFEDIST, extBox); routeBox.bloat(DRCSAFEDIST, drcBox); worker->setRouteBox(routeBox); worker->setExtBox(extBox); worker->setDrcBox(drcBox); worker->setGCellBox(frBox(i, j, max_i, max_j)); worker->setMazeEndIter(mazeEndIter); worker->setDRIter(iter); if (!iter) { // if (routeBox.left() == 441000 && routeBox.bottom() == 816100) { // cout << "@@@ debug: " << i << " " << j << endl; // } // set boundary pin auto bp = initDR_mergeBoundaryPin(i, j, size, routeBox); worker->setDRIter(0, bp); } worker->setRipupMode(ripupMode); worker->setFollowGuide(followGuide); // TODO: only pass to relevant workers worker->setGraphics(graphics_.get()); worker->setCost(workerDRCCost, workerMarkerCost); int batchIdx = (xIdx % batchStepX) * batchStepY + yIdx % batchStepY; if (workers[batchIdx].empty() || (int) workers[batchIdx].back().size() >= BATCHSIZE) { workers[batchIdx].push_back(vector<unique_ptr<FlexDRWorker>>()); } workers[batchIdx].back().push_back(std::move(worker)); yIdx++; } yIdx = 0; xIdx++; } omp_set_num_threads(MAX_THREADS); // parallel execution for (auto& workerBatch : workers) { ProfileTask profile("DR:checkerboard"); for (auto& workersInBatch : workerBatch) { { ProfileTask profile("DR:batch"); // multi thread #pragma omp parallel for schedule(dynamic) for (int i = 0; i < (int) workersInBatch.size(); i++) { workersInBatch[i]->main(getDesign()); #pragma omp critical { cnt++; if (VERBOSE > 0) { if (cnt * 1.0 / tot >= prev_perc / 100.0 + 0.1 && prev_perc < 90) { if (prev_perc == 0 && t.isExceed(0)) { isExceed = true; } prev_perc += 10; // if (true) { if (isExceed) { logger_->report(" completing {}% with {} violations", prev_perc, getDesign()->getTopBlock()->getNumMarkers()); logger_->report(" {}", t); } } } } } } { ProfileTask profile("DR:end_batch"); // single thread for (int i = 0; i < (int) workersInBatch.size(); i++) { workersInBatch[i]->end(getDesign()); } workersInBatch.clear(); } } } if (!iter) { removeGCell2BoundaryPin(); } if (VERBOSE > 0) { if (cnt * 1.0 / tot >= prev_perc / 100.0 + 0.1 && prev_perc >= 90) { if (prev_perc == 0 && t.isExceed(0)) { isExceed = true; } prev_perc += 10; // if (true) { if (isExceed) { logger_->report(" completing {}% with {} violations", prev_perc, getDesign()->getTopBlock()->getNumMarkers()); logger_->report(" {}", t); } } } checkConnectivity(iter); numViols_.push_back(getDesign()->getTopBlock()->getNumMarkers()); if (VERBOSE > 0) { logger_->info(DRT, 199, " number of violations = {}", getDesign()->getTopBlock()->getNumMarkers()); t.print(logger_); cout << flush; } end(); } void FlexDR::end(bool writeMetrics) { vector<unsigned long long> wlen(getTech()->getLayers().size(), 0); vector<unsigned long long> sCut(getTech()->getLayers().size(), 0); vector<unsigned long long> mCut(getTech()->getLayers().size(), 0); unsigned long long totWlen = 0; unsigned long long totSCut = 0; unsigned long long totMCut = 0; frPoint bp, ep; for (auto& net : getDesign()->getTopBlock()->getNets()) { for (auto& shape : net->getShapes()) { if (shape->typeId() == frcPathSeg) { auto obj = static_cast<frPathSeg*>(shape.get()); obj->getPoints(bp, ep); auto lNum = obj->getLayerNum(); frCoord psLen = ep.x() - bp.x() + ep.y() - bp.y(); wlen[lNum] += psLen; totWlen += psLen; } } for (auto& via : net->getVias()) { auto lNum = via->getViaDef()->getCutLayerNum(); if (via->getViaDef()->isMultiCut()) { ++mCut[lNum]; ++totMCut; } else { ++sCut[lNum]; ++totSCut; } } } if (writeMetrics) { logger_->metric("drt::wire length::total", totWlen / getDesign()->getTopBlock()->getDBUPerUU()); logger_->metric("drt::vias::total", totSCut + totMCut); } if (VERBOSE > 0) { logger_->report("total wire length = {} um", totWlen / getDesign()->getTopBlock()->getDBUPerUU()); for (int i = getTech()->getBottomLayerNum(); i <= getTech()->getTopLayerNum(); i++) { if (getTech()->getLayer(i)->getType() == frLayerTypeEnum::ROUTING) { logger_->report("total wire length on LAYER {} = {} um", getTech()->getLayer(i)->getName(), wlen[i] / getDesign()->getTopBlock()->getDBUPerUU()); } } logger_->report("total number of vias = {}", totSCut + totMCut); if (totMCut > 0) { logger_->report("total number of multi-cut vias = {} ({:5.1f}%)", totMCut, totMCut * 100.0 / (totSCut + totMCut)); logger_->report("total number of single-cut vias = {} ({:5.1f}%)", totSCut, totSCut * 100.0 / (totSCut + totMCut)); } logger_->report("up-via summary (total {}):", totSCut + totMCut); int nameLen = 0; for (int i = getTech()->getBottomLayerNum(); i <= getTech()->getTopLayerNum(); i++) { if (getTech()->getLayer(i)->getType() == frLayerTypeEnum::CUT) { nameLen = max(nameLen, (int) getTech()->getLayer(i - 1)->getName().size()); } } int maxL = 1 + nameLen + 4 + (int) to_string(totSCut).length(); if (totMCut) { maxL += 9 + 4 + (int) to_string(totMCut).length() + 9 + 4 + (int) to_string(totSCut + totMCut).length(); } std::ostringstream msg; if (totMCut) { msg << " " << setw(nameLen + 4 + (int) to_string(totSCut).length() + 9) << "single-cut"; msg << setw(4 + (int) to_string(totMCut).length() + 9) << "multi-cut" << setw(4 + (int) to_string(totSCut + totMCut).length()) << "total"; } msg << endl; for (int i = 0; i < maxL; i++) { msg << "-"; } msg << endl; for (int i = getTech()->getBottomLayerNum(); i <= getTech()->getTopLayerNum(); i++) { if (getTech()->getLayer(i)->getType() == frLayerTypeEnum::CUT) { msg << " " << setw(nameLen) << getTech()->getLayer(i - 1)->getName() << " " << setw((int) to_string(totSCut).length()) << sCut[i]; if (totMCut) { msg << " (" << setw(5) << (double) ((sCut[i] + mCut[i]) ? sCut[i] * 100.0 / (sCut[i] + mCut[i]) : 0.0) << "%)"; msg << " " << setw((int) to_string(totMCut).length()) << mCut[i] << " (" << setw(5) << (double) ((sCut[i] + mCut[i]) ? mCut[i] * 100.0 / (sCut[i] + mCut[i]) : 0.0) << "%)" << " " << setw((int) to_string(totSCut + totMCut).length()) << sCut[i] + mCut[i]; } msg << endl; } } for (int i = 0; i < maxL; i++) { msg << "-"; } msg << endl; msg << " " << setw(nameLen) << "" << " " << setw((int) to_string(totSCut).length()) << totSCut; if (totMCut) { msg << " (" << setw(5) << (double) ((totSCut + totMCut) ? totSCut * 100.0 / (totSCut + totMCut) : 0.0) << "%)"; msg << " " << setw((int) to_string(totMCut).length()) << totMCut << " (" << setw(5) << (double) ((totSCut + totMCut) ? totMCut * 100.0 / (totSCut + totMCut) : 0.0) << "%)" << " " << setw((int) to_string(totSCut + totMCut).length()) << totSCut + totMCut; } msg << endl << endl; logger_->report("{}", msg.str()); } } void FlexDR::reportDRC() { double dbu = getTech()->getDBUPerUU(); if (DRC_RPT_FILE == string("")) { if (VERBOSE > 0) { cout << "Waring: no DRC report specified, skipped writing DRC report" << endl; } return; } ofstream drcRpt(DRC_RPT_FILE.c_str()); if (drcRpt.is_open()) { for (auto& marker : getDesign()->getTopBlock()->getMarkers()) { auto con = marker->getConstraint(); drcRpt << " violation type: "; if (con) { switch (con->typeId()) { case frConstraintTypeEnum::frcShortConstraint: { if (getTech()->getLayer(marker->getLayerNum())->getType() == frLayerTypeEnum::ROUTING) { drcRpt << "Short"; } else if (getTech()->getLayer(marker->getLayerNum())->getType() == frLayerTypeEnum::CUT) { drcRpt << "CShort"; } break; } case frConstraintTypeEnum::frcMinWidthConstraint: drcRpt << "MinWid"; break; case frConstraintTypeEnum::frcSpacingConstraint: drcRpt << "MetSpc"; break; case frConstraintTypeEnum::frcSpacingEndOfLineConstraint: drcRpt << "EOLSpc"; break; case frConstraintTypeEnum::frcSpacingTablePrlConstraint: drcRpt << "MetSpc"; break; case frConstraintTypeEnum::frcCutSpacingConstraint: drcRpt << "CutSpc"; break; case frConstraintTypeEnum::frcMinStepConstraint: drcRpt << "MinStp"; break; case frConstraintTypeEnum::frcNonSufficientMetalConstraint: drcRpt << "NSMet"; break; case frConstraintTypeEnum::frcSpacingSamenetConstraint: drcRpt << "MetSpc"; break; case frConstraintTypeEnum::frcOffGridConstraint: drcRpt << "OffGrid"; break; case frConstraintTypeEnum::frcMinEnclosedAreaConstraint: drcRpt << "MinHole"; break; case frConstraintTypeEnum::frcAreaConstraint: drcRpt << "MinArea"; break; case frConstraintTypeEnum::frcLef58CornerSpacingConstraint: drcRpt << "CornerSpc"; break; case frConstraintTypeEnum::frcLef58CutSpacingConstraint: drcRpt << "CutSpc"; break; case frConstraintTypeEnum::frcLef58RectOnlyConstraint: drcRpt << "RectOnly"; break; case frConstraintTypeEnum::frcLef58RightWayOnGridOnlyConstraint: drcRpt << "RightWayOnGridOnly"; break; case frConstraintTypeEnum::frcLef58MinStepConstraint: drcRpt << "MinStp"; break; case frConstraintTypeEnum::frcSpacingTableInfluenceConstraint: drcRpt << "MetSpcInf"; break; case frConstraintTypeEnum::frcSpacingEndOfLineParallelEdgeConstraint: drcRpt << "SpacingEndOfLineParallelEdge"; break; case frConstraintTypeEnum::frcSpacingTableConstraint: drcRpt << "SpacingTable"; break; case frConstraintTypeEnum::frcSpacingTableTwConstraint: drcRpt << "SpacingTableTw"; break; case frConstraintTypeEnum::frcLef58SpacingTableConstraint: drcRpt << "Lef58SpacingTable"; break; case frConstraintTypeEnum::frcLef58CutSpacingTableConstraint: drcRpt << "Lef58CutSpacingTable"; break; case frConstraintTypeEnum::frcLef58CutSpacingTablePrlConstraint: drcRpt << "Lef58CutSpacingTablePrl"; break; case frConstraintTypeEnum::frcLef58CutSpacingTableLayerConstraint: drcRpt << "Lef58CutSpacingTableLayer"; break; case frConstraintTypeEnum::frcLef58CutSpacingParallelWithinConstraint: drcRpt << "Lef58CutSpacingParallelWithin"; break; case frConstraintTypeEnum::frcLef58CutSpacingAdjacentCutsConstraint: drcRpt << "Lef58CutSpacingAdjacentCuts"; break; case frConstraintTypeEnum::frcLef58CutSpacingLayerConstraint: drcRpt << "Lef58CutSpacingLayer"; break; case frConstraintTypeEnum::frcMinimumcutConstraint: drcRpt << "Minimumcut"; break; case frConstraintTypeEnum:: frcLef58CornerSpacingConcaveCornerConstraint: drcRpt << "Lef58CornerSpacingConcaveCorner"; break; case frConstraintTypeEnum:: frcLef58CornerSpacingConvexCornerConstraint: drcRpt << "Lef58CornerSpacingConvexCorner"; break; case frConstraintTypeEnum::frcLef58CornerSpacingSpacingConstraint: drcRpt << "Lef58CornerSpacingSpacing"; break; case frConstraintTypeEnum::frcLef58CornerSpacingSpacing1DConstraint: drcRpt << "Lef58CornerSpacingSpacing1D"; break; case frConstraintTypeEnum::frcLef58CornerSpacingSpacing2DConstraint: drcRpt << "Lef58CornerSpacingSpacing2D"; break; case frConstraintTypeEnum::frcLef58SpacingEndOfLineConstraint: drcRpt << "Lef58SpacingEndOfLine"; break; case frConstraintTypeEnum::frcLef58SpacingEndOfLineWithinConstraint: drcRpt << "Lef58SpacingEndOfLineWithin"; break; case frConstraintTypeEnum:: frcLef58SpacingEndOfLineWithinEndToEndConstraint: drcRpt << "Lef58SpacingEndOfLineWithinEndToEnd"; break; case frConstraintTypeEnum:: frcLef58SpacingEndOfLineWithinEncloseCutConstraint: drcRpt << "Lef58SpacingEndOfLineWithinEncloseCut"; break; case frConstraintTypeEnum:: frcLef58SpacingEndOfLineWithinParallelEdgeConstraint: drcRpt << "Lef58SpacingEndOfLineWithinParallelEdge"; break; case frConstraintTypeEnum:: frcLef58SpacingEndOfLineWithinMaxMinLengthConstraint: drcRpt << "Lef58SpacingEndOfLineWithinMaxMinLength"; break; case frConstraintTypeEnum::frcLef58CutClassConstraint: drcRpt << "Lef58CutClass"; break; case frConstraintTypeEnum::frcRecheckConstraint: drcRpt << "Recheck"; break; case frConstraintTypeEnum::frcLef58EolExtensionConstraint: drcRpt << "Lef58EolExtension"; break; case frConstraintTypeEnum::frcLef58EolKeepOutConstraint: drcRpt << "Lef58EolKeepOut"; break; } } else { drcRpt << "nullptr"; } drcRpt << endl; // get source(s) of violation drcRpt << " srcs: "; for (auto src : marker->getSrcs()) { if (src) { switch (src->typeId()) { case frcNet: drcRpt << (static_cast<frNet*>(src))->getName() << " "; break; case frcInstTerm: { frInstTerm* instTerm = (static_cast<frInstTerm*>(src)); drcRpt << instTerm->getInst()->getName() << "/" << instTerm->getTerm()->getName() << " "; break; } case frcTerm: { frTerm* term = (static_cast<frTerm*>(src)); drcRpt << "PIN/" << term->getName() << " "; break; } case frcInstBlockage: { frInstBlockage* instBlockage = (static_cast<frInstBlockage*>(src)); drcRpt << instBlockage->getInst()->getName() << "/OBS" << " "; break; } case frcBlockage: { drcRpt << "PIN/OBS" << " "; break; } default: std::cout << "Error: unexpected src type in marker\n"; } } } drcRpt << "\n"; // get violation bbox frBox bbox; marker->getBBox(bbox); drcRpt << " bbox = ( " << bbox.left() / dbu << ", " << bbox.bottom() / dbu << " ) - ( " << bbox.right() / dbu << ", " << bbox.top() / dbu << " ) on Layer "; if (getTech()->getLayer(marker->getLayerNum())->getType() == frLayerTypeEnum::CUT && marker->getLayerNum() - 1 >= getTech()->getBottomLayerNum()) { drcRpt << getTech()->getLayer(marker->getLayerNum() - 1)->getName() << "\n"; } else { drcRpt << getTech()->getLayer(marker->getLayerNum())->getName() << "\n"; } } } else { cout << "Error: Fail to open DRC report file\n"; } } int FlexDR::main() { ProfileTask profile("DR:main"); init(); frTime t; if (VERBOSE > 0) { logger_->info(DRT, 194, "start detail routing ..."); } int iterNum = 0; searchRepair( iterNum++ /* 0 */, 7, 0, 3, ROUTESHAPECOST, 0 /*MAARKERCOST*/, 1, true); searchRepair(iterNum++ /* 1 */, 7, -2, 3, ROUTESHAPECOST, ROUTESHAPECOST /*MAARKERCOST*/, 1, true); searchRepair(iterNum++ /* 2 */, 7, -5, 3, ROUTESHAPECOST, ROUTESHAPECOST /*MAARKERCOST*/, 1, true); searchRepair( iterNum++ /* 3 */, 7, 0, 8, ROUTESHAPECOST, MARKERCOST, 0, false); searchRepair( iterNum++ /* 4 */, 7, -1, 8, ROUTESHAPECOST, MARKERCOST, 0, false); searchRepair( iterNum++ /* 5 */, 7, -2, 8, ROUTESHAPECOST, MARKERCOST, 0, false); searchRepair( iterNum++ /* 6 */, 7, -3, 8, ROUTESHAPECOST, MARKERCOST, 0, false); searchRepair( iterNum++ /* 7 */, 7, -4, 8, ROUTESHAPECOST, MARKERCOST, 0, false); searchRepair( iterNum++ /* 8 */, 7, -5, 8, ROUTESHAPECOST, MARKERCOST, 0, false); searchRepair( iterNum++ /* 9 */, 7, -6, 8, ROUTESHAPECOST, MARKERCOST, 0, false); searchRepair( iterNum++ /* 10 */, 7, 0, 8, ROUTESHAPECOST * 2, MARKERCOST, 0, false); searchRepair( iterNum++ /* 11 */, 7, -1, 8, ROUTESHAPECOST * 2, MARKERCOST, 0, false); searchRepair( iterNum++ /* 12 */, 7, -2, 8, ROUTESHAPECOST * 2, MARKERCOST, 0, false); searchRepair( iterNum++ /* 13 */, 7, -3, 8, ROUTESHAPECOST * 2, MARKERCOST, 0, false); searchRepair( iterNum++ /* 14 */, 7, -4, 8, ROUTESHAPECOST * 2, MARKERCOST, 0, false); searchRepair( iterNum++ /* 15 */, 7, -5, 8, ROUTESHAPECOST * 2, MARKERCOST, 0, false); searchRepair( iterNum++ /* 16 */, 7, -6, 8, ROUTESHAPECOST * 2, MARKERCOST, 0, false); searchRepair( iterNum++ /* 17 - ra'*/, 7, -3, 8, ROUTESHAPECOST, MARKERCOST, 1, false); searchRepair( iterNum++ /* 18 */, 7, 0, 8, ROUTESHAPECOST * 4, MARKERCOST, 0, false); searchRepair( iterNum++ /* 19 */, 7, -1, 8, ROUTESHAPECOST * 4, MARKERCOST, 0, false); searchRepair( iterNum++ /* 20 */, 7, -2, 8, ROUTESHAPECOST * 4, MARKERCOST, 0, false); searchRepair( iterNum++ /* 21 */, 7, -3, 8, ROUTESHAPECOST * 4, MARKERCOST, 0, false); searchRepair( iterNum++ /* 22 */, 7, -4, 8, ROUTESHAPECOST * 4, MARKERCOST, 0, false); searchRepair( iterNum++ /* 23 */, 7, -5, 8, ROUTESHAPECOST * 4, MARKERCOST, 0, false); searchRepair( iterNum++ /* 24 */, 7, -6, 8, ROUTESHAPECOST * 4, MARKERCOST, 0, false); searchRepair( iterNum++ /* 25 - ra'*/, 5, -2, 8, ROUTESHAPECOST, MARKERCOST, 1, false); searchRepair(iterNum++ /* 26 */, 7, 0, 8, ROUTESHAPECOST * 8, MARKERCOST * 2, 0, false); searchRepair(iterNum++ /* 27 */, 7, -1, 8, ROUTESHAPECOST * 8, MARKERCOST * 2, 0, false); searchRepair(iterNum++ /* 28 */, 7, -2, 8, ROUTESHAPECOST * 8, MARKERCOST * 2, 0, false); searchRepair(iterNum++ /* 29 */, 7, -3, 8, ROUTESHAPECOST * 8, MARKERCOST * 2, 0, false); searchRepair(iterNum++ /* 30 */, 7, -4, 8, ROUTESHAPECOST * 8, MARKERCOST * 2, 0, false); searchRepair(iterNum++ /* 31 */, 7, -5, 8, ROUTESHAPECOST * 8, MARKERCOST * 2, 0, false); searchRepair(iterNum++ /* 32 */, 7, -6, 8, ROUTESHAPECOST * 8, MARKERCOST * 2, 0, false); searchRepair( iterNum++ /* 33 - ra'*/, 3, -1, 8, ROUTESHAPECOST, MARKERCOST, 1, false); searchRepair(iterNum++ /* 34 */, 7, 0, 8, ROUTESHAPECOST * 16, MARKERCOST * 4, 0, false); searchRepair(iterNum++ /* 35 */, 7, -1, 8, ROUTESHAPECOST * 16, MARKERCOST * 4, 0, false); searchRepair(iterNum++ /* 36 */, 7, -2, 8, ROUTESHAPECOST * 16, MARKERCOST * 4, 0, false); searchRepair(iterNum++ /* 37 */, 7, -3, 8, ROUTESHAPECOST * 16, MARKERCOST * 4, 0, false); searchRepair(iterNum++ /* 38 */, 7, -4, 8, ROUTESHAPECOST * 16, MARKERCOST * 4, 0, false); searchRepair(iterNum++ /* 39 */, 7, -5, 8, ROUTESHAPECOST * 16, MARKERCOST * 4, 0, false); searchRepair(iterNum++ /* 40 */, 7, -6, 8, ROUTESHAPECOST * 16, MARKERCOST * 4, 0, false); searchRepair( iterNum++ /* 41 - ra'*/, 3, -2, 8, ROUTESHAPECOST, MARKERCOST, 1, false); searchRepair(iterNum++ /* 42 */, 7, 0, 16, ROUTESHAPECOST * 16, MARKERCOST * 4, 0, false); searchRepair(iterNum++ /* 43 */, 7, -1, 16, ROUTESHAPECOST * 16, MARKERCOST * 4, 0, false); searchRepair(iterNum++ /* 44 */, 7, -2, 16, ROUTESHAPECOST * 16, MARKERCOST * 4, 0, false); searchRepair(iterNum++ /* 45 */, 7, -3, 16, ROUTESHAPECOST * 16, MARKERCOST * 4, 0, false); searchRepair(iterNum++ /* 46 */, 7, -4, 16, ROUTESHAPECOST * 16, MARKERCOST * 4, 0, false); searchRepair(iterNum++ /* 47 */, 7, -5, 16, ROUTESHAPECOST * 16, MARKERCOST * 4, 0, false); searchRepair(iterNum++ /* 48 */, 7, -6, 16, ROUTESHAPECOST * 16, MARKERCOST * 4, 0, false); searchRepair( iterNum++ /* 49 - ra'*/, 3, -0, 8, ROUTESHAPECOST, MARKERCOST, 1, false); searchRepair(iterNum++ /* 50 */, 7, 0, 32, ROUTESHAPECOST * 32, MARKERCOST * 8, 0, false); searchRepair(iterNum++ /* 51 */, 7, -1, 32, ROUTESHAPECOST * 32, MARKERCOST * 8, 0, false); searchRepair(iterNum++ /* 52 */, 7, -2, 32, ROUTESHAPECOST * 32, MARKERCOST * 8, 0, false); searchRepair(iterNum++ /* 53 */, 7, -3, 32, ROUTESHAPECOST * 32, MARKERCOST * 8, 0, false); searchRepair(iterNum++ /* 54 */, 7, -4, 32, ROUTESHAPECOST * 32, MARKERCOST * 8, 0, false); searchRepair(iterNum++ /* 55 */, 7, -5, 32, ROUTESHAPECOST * 32, MARKERCOST * 8, 0, false); searchRepair(iterNum++ /* 56 */, 7, -6, 32, ROUTESHAPECOST * 32, MARKERCOST * 8, 0, false); searchRepair( iterNum++ /* 57 - ra'*/, 3, -1, 8, ROUTESHAPECOST, MARKERCOST, 1, false); searchRepair(iterNum++ /* 58 */, 7, 0, 64, ROUTESHAPECOST * 64, MARKERCOST * 16, 0, false); searchRepair(iterNum++ /* 59 */, 7, -1, 64, ROUTESHAPECOST * 64, MARKERCOST * 16, 0, false); searchRepair(iterNum++ /* 60 */, 7, -2, 64, ROUTESHAPECOST * 64, MARKERCOST * 16, 0, false); searchRepair(iterNum++ /* 61 */, 7, -3, 64, ROUTESHAPECOST * 64, MARKERCOST * 16, 0, false); searchRepair(iterNum++ /* 56 */, 7, -4, 64, ROUTESHAPECOST * 64, MARKERCOST * 16, 0, false); searchRepair(iterNum++ /* 62 */, 7, -5, 64, ROUTESHAPECOST * 64, MARKERCOST * 16, 0, false); searchRepair(iterNum++ /* 63 */, 7, -6, 64, ROUTESHAPECOST * 64, MARKERCOST * 16, 0, false); if (DRC_RPT_FILE != string("")) { reportDRC(); } if (VERBOSE > 0) { logger_->info(DRT, 198, "complete detail routing"); end(/* writeMetrics */ true); } if (VERBOSE > 0) { t.print(logger_); cout << endl; } return 0; }
33.809379
80
0.535068
[ "shape", "vector" ]
741c7d73297256fdf51eb56b9f567be26922683d
24,961
cpp
C++
Plugins/VRExpansionPlugin/VRExpansionPlugin/Source/VRExpansionPlugin/Private/VRGestureComponent.cpp
michaelcawood/PhoenixGene_VRExp
94ebe7cba181b9bf4801fd69fbb947a9c93b5efa
[ "MIT" ]
null
null
null
Plugins/VRExpansionPlugin/VRExpansionPlugin/Source/VRExpansionPlugin/Private/VRGestureComponent.cpp
michaelcawood/PhoenixGene_VRExp
94ebe7cba181b9bf4801fd69fbb947a9c93b5efa
[ "MIT" ]
null
null
null
Plugins/VRExpansionPlugin/VRExpansionPlugin/Source/VRExpansionPlugin/Private/VRGestureComponent.cpp
michaelcawood/PhoenixGene_VRExp
94ebe7cba181b9bf4801fd69fbb947a9c93b5efa
[ "MIT" ]
null
null
null
#include "VRGestureComponent.h" #include "TimerManager.h" DECLARE_CYCLE_STAT(TEXT("TickGesture ~ TickingGesture"), STAT_TickGesture, STATGROUP_TickGesture); UVRGestureComponent::UVRGestureComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PrimaryComponentTick.bCanEverTick = false; //PrimaryComponentTick.bStartWithTickEnabled = false; //PrimaryComponentTick.TickGroup = TG_PrePhysics; //PrimaryComponentTick.bTickEvenWhenPaused = false; maxSlope = 3;// INT_MAX; //globalThreshold = 10.0f; SameSampleTolerance = 0.1f; bGestureChanged = false; MirroringHand = EVRGestureMirrorMode::GES_NoMirror; bDrawSplinesCurved = true; bGetGestureInWorldSpace = true; SplineMeshScaler = FVector2D(1.f); } void UGesturesDatabase::FillSplineWithGesture(FVRGesture &Gesture, USplineComponent * SplineComponent, bool bCenterPointsOnSpline, bool bScaleToBounds, float OptionalBounds, bool bUseCurvedPoints, bool bFillInSplineMeshComponents, UStaticMesh * Mesh, UMaterial * MeshMat) { if (!SplineComponent || Gesture.Samples.Num() < 2) return; UWorld* InWorld = GEngine->GetWorldFromContextObject(SplineComponent, EGetWorldErrorMode::LogAndReturnNull); if (!InWorld) return; SplineComponent->ClearSplinePoints(false); FVector PointOffset = FVector::ZeroVector; float Scaler = 1.0f; if (bScaleToBounds && OptionalBounds > 0.0f) { Scaler = OptionalBounds / Gesture.GestureSize.GetSize().GetMax(); } if (bCenterPointsOnSpline) { PointOffset = -Gesture.GestureSize.GetCenter(); } int curIndex = 0; for (int i = Gesture.Samples.Num() - 1; i >= 0; --i) { SplineComponent->AddSplinePoint((Gesture.Samples[i] + PointOffset) * Scaler, ESplineCoordinateSpace::Local, false); curIndex++; SplineComponent->SetSplinePointType(curIndex, bUseCurvedPoints ? ESplinePointType::Curve : ESplinePointType::Linear, false); } // Update spline now SplineComponent->UpdateSpline(); if (bFillInSplineMeshComponents && Mesh != nullptr && MeshMat != nullptr) { TArray<USplineMeshComponent *> CurrentSplineChildren; TArray<USceneComponent*> Children; SplineComponent->GetChildrenComponents(false, Children); for (auto Child : Children) { USplineMeshComponent* SplineMesh = Cast<USplineMeshComponent>(Child); if (SplineMesh != nullptr && !SplineMesh->IsPendingKill()) { CurrentSplineChildren.Add(SplineMesh); } } if (CurrentSplineChildren.Num() > SplineComponent->GetNumberOfSplinePoints() - 1) { int diff = CurrentSplineChildren.Num() - (CurrentSplineChildren.Num() - (SplineComponent->GetNumberOfSplinePoints() -1)); for (int i = CurrentSplineChildren.Num()- 1; i >= diff; --i) { if (!CurrentSplineChildren[i]->IsBeingDestroyed()) { CurrentSplineChildren[i]->SetVisibility(false); CurrentSplineChildren[i]->Modify(); CurrentSplineChildren[i]->DestroyComponent(); CurrentSplineChildren.RemoveAt(i); } } } else { for (int i = CurrentSplineChildren.Num(); i < SplineComponent->GetNumberOfSplinePoints() -1; ++i) { USplineMeshComponent * newSplineMesh = NewObject<USplineMeshComponent>(SplineComponent); newSplineMesh->RegisterComponentWithWorld(InWorld); newSplineMesh->SetMobility(EComponentMobility::Movable); CurrentSplineChildren.Add(newSplineMesh); newSplineMesh->SetStaticMesh(Mesh); newSplineMesh->SetMaterial(0, (UMaterialInterface*)MeshMat); newSplineMesh->AttachToComponent(SplineComponent, FAttachmentTransformRules::SnapToTargetIncludingScale); newSplineMesh->SetVisibility(true); } } for(int i=0; i<SplineComponent->GetNumberOfSplinePoints() - 1; i++) { CurrentSplineChildren[i]->SetStartAndEnd(SplineComponent->GetLocationAtSplinePoint(i, ESplineCoordinateSpace::Local), SplineComponent->GetTangentAtSplinePoint(i, ESplineCoordinateSpace::Local), SplineComponent->GetLocationAtSplinePoint(i + 1, ESplineCoordinateSpace::Local), SplineComponent->GetTangentAtSplinePoint(i + 1, ESplineCoordinateSpace::Local), true); } } } void UVRGestureComponent::BeginRecording(bool bRunDetection, bool bFlattenGesture, bool bDrawGesture, bool bDrawAsSpline, int SamplingHTZ, int SampleBufferSize, float ClampingTolerance) { RecordingBufferSize = SampleBufferSize; RecordingDelta = 1.0f / SamplingHTZ; RecordingClampingTolerance = ClampingTolerance; bDrawRecordingGesture = bDrawGesture; bDrawRecordingGestureAsSpline = bDrawAsSpline; bRecordingFlattenGesture = bFlattenGesture; GestureLog.GestureSize.Init(); // Reinit the drawing spline if (!bDrawAsSpline || !bDrawGesture) RecordingGestureDraw.Clear(); // Not drawing or not as a spline, remove the components if they exist else { RecordingGestureDraw.Reset(); // Otherwise just clear points and hide mesh components if (RecordingGestureDraw.SplineComponent == nullptr) { RecordingGestureDraw.SplineComponent = NewObject<USplineComponent>(GetAttachParent()); RecordingGestureDraw.SplineComponent->RegisterComponentWithWorld(GetWorld()); RecordingGestureDraw.SplineComponent->SetMobility(EComponentMobility::Movable); RecordingGestureDraw.SplineComponent->AttachToComponent(GetAttachParent(), FAttachmentTransformRules::KeepRelativeTransform); RecordingGestureDraw.SplineComponent->ClearSplinePoints(true); } } // Reset does the reserve already GestureLog.Samples.Reset(RecordingBufferSize); CurrentState = bRunDetection ? EVRGestureState::GES_Detecting : EVRGestureState::GES_Recording; if (TargetCharacter != nullptr) { OriginatingTransform = TargetCharacter->OffsetComponentToWorld; } else if (AVRBaseCharacter * own = Cast<AVRBaseCharacter>(GetOwner())) { TargetCharacter = own; OriginatingTransform = TargetCharacter->OffsetComponentToWorld; } else OriginatingTransform = this->GetComponentTransform(); StartVector = OriginatingTransform.InverseTransformPosition(this->GetComponentLocation()); this->SetComponentTickEnabled(true); if (!TickGestureTimer_Handle.IsValid()) GetWorld()->GetTimerManager().SetTimer(TickGestureTimer_Handle, this, &UVRGestureComponent::TickGesture, RecordingDelta, true); } void UVRGestureComponent::CaptureGestureFrame() { FVector NewSample = OriginatingTransform.InverseTransformPosition(this->GetComponentLocation()) - StartVector; if (bRecordingFlattenGesture) NewSample.X = 0; if (RecordingClampingTolerance > 0.0f) { NewSample.X = FMath::GridSnap(NewSample.X, RecordingClampingTolerance); NewSample.Y = FMath::GridSnap(NewSample.Y, RecordingClampingTolerance); NewSample.Z = FMath::GridSnap(NewSample.Z, RecordingClampingTolerance); } // Add in newest sample at beginning (reverse order) if (NewSample != FVector::ZeroVector && (GestureLog.Samples.Num() < 1 || !GestureLog.Samples[0].Equals(NewSample, SameSampleTolerance))) { bool bClearLatestSpline = false; // Pop off oldest sample if (GestureLog.Samples.Num() >= RecordingBufferSize) { GestureLog.Samples.Pop(false); bClearLatestSpline = true; } GestureLog.GestureSize.Max.X = FMath::Max(NewSample.X, GestureLog.GestureSize.Max.X); GestureLog.GestureSize.Max.Y = FMath::Max(NewSample.Y, GestureLog.GestureSize.Max.Y); GestureLog.GestureSize.Max.Z = FMath::Max(NewSample.Z, GestureLog.GestureSize.Max.Z); GestureLog.GestureSize.Min.X = FMath::Min(NewSample.X, GestureLog.GestureSize.Min.X); GestureLog.GestureSize.Min.Y = FMath::Min(NewSample.Y, GestureLog.GestureSize.Min.Y); GestureLog.GestureSize.Min.Z = FMath::Min(NewSample.Z, GestureLog.GestureSize.Min.Z); if (bDrawRecordingGesture && bDrawRecordingGestureAsSpline && SplineMesh != nullptr && SplineMaterial != nullptr) { if (bClearLatestSpline) RecordingGestureDraw.ClearLastPoint(); RecordingGestureDraw.SplineComponent->AddSplinePoint(NewSample, ESplineCoordinateSpace::Local, false); int SplineIndex = RecordingGestureDraw.SplineComponent->GetNumberOfSplinePoints() - 1; RecordingGestureDraw.SplineComponent->SetSplinePointType(SplineIndex, bDrawSplinesCurved ? ESplinePointType::Curve : ESplinePointType::Linear, true); bool bFoundEmptyMesh = false; USplineMeshComponent * MeshComp = nullptr; int MeshIndex = 0; for (int i = 0; i < RecordingGestureDraw.SplineMeshes.Num(); i++) { MeshIndex = i; MeshComp = RecordingGestureDraw.SplineMeshes[i]; if (MeshComp == nullptr) { RecordingGestureDraw.SplineMeshes[i] = NewObject<USplineMeshComponent>(RecordingGestureDraw.SplineComponent); MeshComp = RecordingGestureDraw.SplineMeshes[i]; MeshComp->RegisterComponentWithWorld(GetWorld()); MeshComp->SetMobility(EComponentMobility::Movable); MeshComp->SetStaticMesh(SplineMesh); MeshComp->SetMaterial(0, (UMaterialInterface*)SplineMaterial); bFoundEmptyMesh = true; break; } else if (!MeshComp->IsVisible()) { bFoundEmptyMesh = true; break; } } if (!bFoundEmptyMesh) { USplineMeshComponent * newSplineMesh = NewObject<USplineMeshComponent>(RecordingGestureDraw.SplineComponent); MeshComp = newSplineMesh; MeshComp->RegisterComponentWithWorld(GetWorld()); MeshComp->SetMobility(EComponentMobility::Movable); RecordingGestureDraw.SplineMeshes.Add(MeshComp); MeshIndex = RecordingGestureDraw.SplineMeshes.Num() - 1; MeshComp->SetStaticMesh(SplineMesh); MeshComp->SetMaterial(0, (UMaterialInterface*)SplineMaterial); if (!bGetGestureInWorldSpace && TargetCharacter) MeshComp->AttachToComponent(TargetCharacter->GetRootComponent(), FAttachmentTransformRules::KeepRelativeTransform); } if (MeshComp != nullptr) { // Fill in last mesh component tangent and end pos if (RecordingGestureDraw.LastIndexSet != MeshIndex && RecordingGestureDraw.SplineMeshes[RecordingGestureDraw.LastIndexSet] != nullptr) { RecordingGestureDraw.SplineMeshes[RecordingGestureDraw.LastIndexSet]->SetEndPosition(NewSample, false); RecordingGestureDraw.SplineMeshes[RecordingGestureDraw.LastIndexSet]->SetEndTangent(RecordingGestureDraw.SplineComponent->GetTangentAtSplinePoint(SplineIndex, ESplineCoordinateSpace::Local), true); } MeshComp->SetStartScale(SplineMeshScaler); MeshComp->SetEndScale(SplineMeshScaler); MeshComp->SetStartAndEnd(NewSample, RecordingGestureDraw.SplineComponent->GetTangentAtSplinePoint(SplineIndex, ESplineCoordinateSpace::Local), NewSample, FVector::ZeroVector, true); if (bGetGestureInWorldSpace) MeshComp->SetWorldLocationAndRotation(OriginatingTransform.TransformPosition(StartVector), OriginatingTransform.GetRotation()); else MeshComp->SetRelativeLocationAndRotation(/*OriginatingTransform.TransformPosition(*/StartVector/*)*/, FQuat::Identity/*OriginatingTransform.GetRotation()*/); RecordingGestureDraw.LastIndexSet = MeshIndex; MeshComp->SetVisibility(true); } } GestureLog.Samples.Insert(NewSample, 0); bGestureChanged = true; } } void UVRGestureComponent::TickGesture() { SCOPE_CYCLE_COUNTER(STAT_TickGesture); switch (CurrentState) { case EVRGestureState::GES_Detecting: { CaptureGestureFrame(); RecognizeGesture(GestureLog); bGestureChanged = false; }break; case EVRGestureState::GES_Recording: { CaptureGestureFrame(); }break; case EVRGestureState::GES_None: default: {}break; } if (bDrawRecordingGesture) { if (!bDrawRecordingGestureAsSpline) { FTransform DrawTransform = FTransform(StartVector) * OriginatingTransform; // Setting the lifetime to the recording htz now, should remove the flicker. DrawDebugGesture(this, DrawTransform, GestureLog, FColor::White, false, 0, RecordingDelta, 0.0f); } } } void UVRGestureComponent::RecognizeGesture(FVRGesture inputGesture) { if (!GesturesDB || inputGesture.Samples.Num() < 1 || !bGestureChanged) return; float minDist = MAX_FLT; int OutGestureIndex = -1; bool bMirrorGesture = false; FVector Size = inputGesture.GestureSize.GetSize(); float Scaler = GesturesDB->TargetGestureScale / Size.GetMax(); float FinalScaler = Scaler; for (int i = 0; i < GesturesDB->Gestures.Num(); i++) { FVRGesture &exampleGesture = GesturesDB->Gestures[i]; if (!exampleGesture.GestureSettings.bEnabled || exampleGesture.Samples.Num() < 1 || inputGesture.Samples.Num() < exampleGesture.GestureSettings.Minimum_Gesture_Length) continue; FinalScaler = exampleGesture.GestureSettings.bEnableScaling ? Scaler : 1.f; bMirrorGesture = (MirroringHand != EVRGestureMirrorMode::GES_NoMirror && MirroringHand != EVRGestureMirrorMode::GES_MirrorBoth && MirroringHand == exampleGesture.GestureSettings.MirrorMode); if (GetGestureDistance(inputGesture.Samples[0] * FinalScaler, exampleGesture.Samples[0], bMirrorGesture) < FMath::Square(exampleGesture.GestureSettings.firstThreshold)) { float d = dtw(inputGesture, exampleGesture, bMirrorGesture, FinalScaler) / (exampleGesture.Samples.Num()); if (d < minDist && d < FMath::Square(exampleGesture.GestureSettings.FullThreshold)) { minDist = d; OutGestureIndex = i; } } else if (exampleGesture.GestureSettings.MirrorMode == EVRGestureMirrorMode::GES_MirrorBoth) { bMirrorGesture = true; if (GetGestureDistance(inputGesture.Samples[0] * FinalScaler, exampleGesture.Samples[0], bMirrorGesture) < FMath::Square(exampleGesture.GestureSettings.firstThreshold)) { float d = dtw(inputGesture, exampleGesture, bMirrorGesture, FinalScaler) / (exampleGesture.Samples.Num()); if (d < minDist && d < FMath::Square(exampleGesture.GestureSettings.FullThreshold)) { minDist = d; OutGestureIndex = i; } } } /*if (exampleGesture.MirrorMode == EVRGestureMirrorMode::GES_MirrorBoth) { bMirrorGesture = true; if (GetGestureDistance(inputGesture.Samples[0], exampleGesture.Samples[0], bMirrorGesture) < FMath::Square(exampleGesture.GestureSettings.firstThreshold)) { float d = dtw(inputGesture, exampleGesture, bMirrorGesture) / (exampleGesture.Samples.Num()); if (d < minDist && d < FMath::Square(exampleGesture.GestureSettings.FullThreshold)) { minDist = d; OutGestureIndex = i; } } }*/ } if (/*minDist < FMath::Square(globalThreshold) && */OutGestureIndex != -1) { OnGestureDetected(GesturesDB->Gestures[OutGestureIndex].GestureType, /*minDist,*/ GesturesDB->Gestures[OutGestureIndex].Name, OutGestureIndex, GesturesDB); OnGestureDetected_Bind.Broadcast(GesturesDB->Gestures[OutGestureIndex].GestureType, /*minDist,*/ GesturesDB->Gestures[OutGestureIndex].Name, OutGestureIndex, GesturesDB); ClearRecording(); // Clear the recording out, we don't want to detect this gesture again with the same data RecordingGestureDraw.Reset(); } } float UVRGestureComponent::dtw(FVRGesture seq1, FVRGesture seq2, bool bMirrorGesture, float Scaler) { // #TODO: Skip copying the array and reversing it in the future, we only ever use the reversed value. // So pre-reverse it and keep it stored like that on init. When we do the initial sample we can check off of the first index instead of last then // Should also be able to get SizeSquared for values and compared to squared thresholds instead of doing the full SQRT calc. // Getting number of average samples recorded over of a gesture (top down) may be able to achieve a basic % completed check // to see how far into detecting a gesture we are, this would require ignoring the last position threshold though.... int RowCount = seq1.Samples.Num() + 1; int ColumnCount = seq2.Samples.Num() + 1; TArray<float> LookupTable; LookupTable.AddZeroed(ColumnCount * RowCount); TArray<int> SlopeI; SlopeI.AddZeroed(ColumnCount * RowCount); TArray<int> SlopeJ; SlopeJ.AddZeroed(ColumnCount * RowCount); for (int i = 1; i < (ColumnCount * RowCount); i++) { LookupTable[i] = MAX_FLT; } // Don't need to do this, it is already handled by add zeroed //tab[0, 0] = 0; int icol = 0, icolneg = 0; // Dynamic computation of the DTW matrix. for (int i = 1; i < RowCount; i++) { for (int j = 1; j < ColumnCount; j++) { icol = i * ColumnCount; icolneg = icol - ColumnCount;// (i - 1) * ColumnCount; if ( LookupTable[icol + (j - 1)] < LookupTable[icolneg + (j - 1)] && LookupTable[icol + (j - 1)] < LookupTable[icolneg + j] && SlopeI[icol + (j - 1)] < maxSlope) { LookupTable[icol + j] = GetGestureDistance(seq1.Samples[i - 1] * Scaler, seq2.Samples[j - 1], bMirrorGesture) + LookupTable[icol + j - 1]; SlopeI[icol + j] = SlopeJ[icol + j - 1] + 1; SlopeJ[icol + j] = 0; } else if ( LookupTable[icolneg + j] < LookupTable[icolneg + j - 1] && LookupTable[icolneg + j] < LookupTable[icol + j - 1] && SlopeJ[icolneg + j] < maxSlope) { LookupTable[icol + j] = GetGestureDistance(seq1.Samples[i - 1] * Scaler, seq2.Samples[j - 1], bMirrorGesture) + LookupTable[icolneg + j]; SlopeI[icol + j] = 0; SlopeJ[icol + j] = SlopeJ[icolneg + j] + 1; } else { LookupTable[icol + j] = GetGestureDistance(seq1.Samples[i - 1] * Scaler, seq2.Samples[j - 1], bMirrorGesture) + LookupTable[icolneg + j - 1]; SlopeI[icol + j] = 0; SlopeJ[icol + j] = 0; } } } // Find best between seq2 and an ending (postfix) of seq1. float bestMatch = FLT_MAX; for (int i = 1; i < seq1.Samples.Num() + 1/* - seq2.Minimum_Gesture_Length*/; i++) { if (LookupTable[(i*ColumnCount) + seq2.Samples.Num()] < bestMatch) bestMatch = LookupTable[(i*ColumnCount) + seq2.Samples.Num()]; } return bestMatch; } void UVRGestureComponent::DrawDebugGesture(UObject* WorldContextObject, FTransform &StartTransform, FVRGesture GestureToDraw, FColor const& Color, bool bPersistentLines, uint8 DepthPriority, float LifeTime, float Thickness) { #if ENABLE_DRAW_DEBUG UWorld* InWorld = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull); if (InWorld != nullptr) { // no debug line drawing on dedicated server if (GEngine->GetNetMode(InWorld) != NM_DedicatedServer && GestureToDraw.Samples.Num() > 1) { bool bMirrorGesture = (MirroringHand != EVRGestureMirrorMode::GES_NoMirror && MirroringHand == GestureToDraw.GestureSettings.MirrorMode); FVector MirrorVector = FVector(1.f, -1.f, 1.f); // Only mirroring on Y axis to flip Left/Right // this means foreground lines can't be persistent ULineBatchComponent* const LineBatcher = (InWorld ? ((DepthPriority == SDPG_Foreground) ? InWorld->ForegroundLineBatcher : ((bPersistentLines || (LifeTime > 0.f)) ? InWorld->PersistentLineBatcher : InWorld->LineBatcher)) : NULL); if (LineBatcher != NULL) { float const LineLifeTime = (LifeTime > 0.f) ? LifeTime : LineBatcher->DefaultLifeTime; TArray<FBatchedLine> Lines; FBatchedLine Line; Line.Color = Color; Line.Thickness = Thickness; Line.RemainingLifeTime = LineLifeTime; Line.DepthPriority = DepthPriority; FVector FirstLoc = bMirrorGesture ? GestureToDraw.Samples[GestureToDraw.Samples.Num() - 1] * MirrorVector : GestureToDraw.Samples[GestureToDraw.Samples.Num() - 1]; for (int i = GestureToDraw.Samples.Num() - 2; i >= 0; --i) { Line.Start = bMirrorGesture ? GestureToDraw.Samples[i] * MirrorVector : GestureToDraw.Samples[i]; Line.End = FirstLoc; FirstLoc = Line.Start; Line.End = StartTransform.TransformPosition(Line.End); Line.Start = StartTransform.TransformPosition(Line.Start); Lines.Add(Line); } LineBatcher->DrawLines(Lines); } } } #endif } void UGesturesDatabase::RecalculateGestures(bool bScaleToDatabase) { for (int i = 0; i < Gestures.Num(); ++i) { Gestures[i].CalculateSizeOfGesture(bScaleToDatabase, TargetGestureScale); } } bool UGesturesDatabase::ImportSplineAsGesture(USplineComponent * HostSplineComponent, FString GestureName, bool bKeepSplineCurves, float SegmentLen, bool bScaleToDatabase) { FVRGesture NewGesture; if (HostSplineComponent->GetNumberOfSplinePoints() < 2) return false; NewGesture.Name = GestureName; FVector FirstPointPos = HostSplineComponent->GetLocationAtSplinePoint(0, ESplineCoordinateSpace::Local); float LastDistance = 0.f; float ThisDistance = 0.f; FVector LastDistanceV; FVector ThisDistanceV; FVector DistNormal; float DistAlongSegment = 0.f; // Realign to xForward on the gesture, normally splines lay out as X to the right FTransform Realignment = FTransform(FRotator(0.f, 90.f, 0.f), -FirstPointPos); // Prefill the first point NewGesture.Samples.Add(Realignment.TransformPosition(HostSplineComponent->GetLocationAtSplinePoint(HostSplineComponent->GetNumberOfSplinePoints() - 1, ESplineCoordinateSpace::Local))); // Inserting in reverse order -2 so we start one down for (int i = HostSplineComponent->GetNumberOfSplinePoints() - 2; i >= 0; --i) { if (bKeepSplineCurves) { LastDistance = HostSplineComponent->GetDistanceAlongSplineAtSplinePoint(i + 1); ThisDistance = HostSplineComponent->GetDistanceAlongSplineAtSplinePoint(i); DistAlongSegment = FMath::Abs(ThisDistance - LastDistance); } else { LastDistanceV = Realignment.TransformPosition(HostSplineComponent->GetLocationAtSplinePoint(i + 1, ESplineCoordinateSpace::Local)); ThisDistanceV = Realignment.TransformPosition(HostSplineComponent->GetLocationAtSplinePoint(i, ESplineCoordinateSpace::Local)); DistAlongSegment = FVector::Dist(ThisDistanceV, LastDistanceV); DistNormal = ThisDistanceV - LastDistanceV; DistNormal.Normalize(); } float SegmentCount = FMath::FloorToFloat(DistAlongSegment / SegmentLen); float OverFlow = FMath::Fmod(DistAlongSegment, SegmentLen); if (SegmentCount < 1) { SegmentCount++; } float DistPerSegment = (DistAlongSegment / SegmentCount); for (int j = 0; j < SegmentCount; j++) { if (j == SegmentCount - 1 && i > 0) DistPerSegment += OverFlow; if (bKeepSplineCurves) { LastDistance -= DistPerSegment; if (j == SegmentCount - 1 && i > 0) { LastDistance = ThisDistance; } FVector loc = Realignment.TransformPosition(HostSplineComponent->GetLocationAtDistanceAlongSpline(LastDistance, ESplineCoordinateSpace::Local)); if (!loc.IsNearlyZero()) NewGesture.Samples.Add(loc); } else { LastDistanceV += DistPerSegment * DistNormal; if (j == SegmentCount - 1 && i > 0) { LastDistanceV = ThisDistanceV; } if (!LastDistanceV.IsNearlyZero()) NewGesture.Samples.Add(LastDistanceV); } } } NewGesture.CalculateSizeOfGesture(bScaleToDatabase, this->TargetGestureScale); Gestures.Add(NewGesture); return true; } void FVRGestureSplineDraw::ClearLastPoint() { SplineComponent->RemoveSplinePoint(0, false); if (SplineMeshes.Num() < NextIndexCleared + 1) NextIndexCleared = 0; SplineMeshes[NextIndexCleared]->SetVisibility(false); NextIndexCleared++; } void FVRGestureSplineDraw::Reset() { if (SplineComponent != nullptr) SplineComponent->ClearSplinePoints(true); for (int i = SplineMeshes.Num() - 1; i >= 0; --i) { if (SplineMeshes[i] != nullptr) SplineMeshes[i]->SetVisibility(false); else SplineMeshes.RemoveAt(i); } LastIndexSet = 0; NextIndexCleared = 0; } void FVRGestureSplineDraw::Clear() { for (int i = 0; i < SplineMeshes.Num(); ++i) { if (SplineMeshes[i] != nullptr && !SplineMeshes[i]->IsBeingDestroyed()) { SplineMeshes[i]->Modify(); SplineMeshes[i]->DestroyComponent(); } } SplineMeshes.Empty(); if (SplineComponent != nullptr) { SplineComponent->DestroyComponent(); SplineComponent = nullptr; } LastIndexSet = 0; NextIndexCleared = 0; } FVRGestureSplineDraw::FVRGestureSplineDraw() { SplineComponent = nullptr; NextIndexCleared = 0; LastIndexSet = 0; } FVRGestureSplineDraw::~FVRGestureSplineDraw() { Clear(); } void UVRGestureComponent::BeginDestroy() { Super::BeginDestroy(); RecordingGestureDraw.Clear(); if (TickGestureTimer_Handle.IsValid()) { GetWorld()->GetTimerManager().ClearTimer(TickGestureTimer_Handle); } } void UVRGestureComponent::RecalculateGestureSize(FVRGesture & InputGesture, UGesturesDatabase * GestureDB) { if (GestureDB != nullptr) InputGesture.CalculateSizeOfGesture(true, GestureDB->TargetGestureScale); else InputGesture.CalculateSizeOfGesture(false); } FVRGesture UVRGestureComponent::EndRecording() { if (TickGestureTimer_Handle.IsValid()) { GetWorld()->GetTimerManager().ClearTimer(TickGestureTimer_Handle); } this->SetComponentTickEnabled(false); CurrentState = EVRGestureState::GES_None; // Reset the recording gesture RecordingGestureDraw.Reset(); return GestureLog; } void UVRGestureComponent::ClearRecording() { GestureLog.Samples.Reset(RecordingBufferSize); } void UVRGestureComponent::SaveRecording(FVRGesture &Recording, FString RecordingName, bool bScaleRecordingToDatabase) { if (GesturesDB) { Recording.CalculateSizeOfGesture(bScaleRecordingToDatabase, GesturesDB->TargetGestureScale); Recording.Name = RecordingName; GesturesDB->Gestures.Add(Recording); } }
34.053206
271
0.74388
[ "mesh" ]
741d4a17ee19674aba4f35a63dc7df1756c5be41
3,087
cxx
C++
src/protocol/HTTPResponseParser.cxx
DaRoli/openkit-native
cf3fd1d9816a0df11d98b5345dd03105c1654ea6
[ "Apache-2.0" ]
null
null
null
src/protocol/HTTPResponseParser.cxx
DaRoli/openkit-native
cf3fd1d9816a0df11d98b5345dd03105c1654ea6
[ "Apache-2.0" ]
null
null
null
src/protocol/HTTPResponseParser.cxx
DaRoli/openkit-native
cf3fd1d9816a0df11d98b5345dd03105c1654ea6
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2018 Dynatrace LLC * * 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 "HTTPResponseParser.h" #include <cctype> #include <algorithm> using namespace protocol; static constexpr char HTTP_HEADER_LINE_KEY_VALUE_SEPARATOR = ':'; static constexpr char HTTP_HEADER_LINE_VALUE_SEPARATOR = ','; HTTPResponseParser::HTTPResponseParser() : mResponseHeaders() , mResponseBody() { } size_t HTTPResponseParser::responseHeaderData(const char *buffer, size_t elementSize, size_t numberOfElements) { // convert response line into STL string auto responseLine = std::string(buffer, elementSize * numberOfElements); // split up response header line auto separatorPosition = responseLine.find(HTTP_HEADER_LINE_KEY_VALUE_SEPARATOR); if (separatorPosition != std::string::npos) { // found the separator - split into key and value auto key = responseLine.substr(0, separatorPosition); auto valueString = responseLine.substr(separatorPosition + 1); // strip optional whitespace character HTTPResponseParser::stripWhitespaces(valueString); // key is case insensitive std::transform(key.begin(), key.end(), key.begin(), [](unsigned char c) { return static_cast<char>(std::tolower(c)); }); auto responseKeyIterator = mResponseHeaders.find(key); if (responseKeyIterator == mResponseHeaders.end()) { // key not yet present responseKeyIterator = mResponseHeaders.insert({ key, std::vector<std::string>() }).first; } // move over previously parsed values responseKeyIterator->second.push_back(valueString); } // in any case return the number of bytes processed return elementSize * numberOfElements; } size_t HTTPResponseParser::responseBodyData(const char* buffer, size_t elementSize, size_t numberOfElements) { mResponseBody.append(buffer, elementSize * numberOfElements); return elementSize * numberOfElements; } const Response::ResponseHeaders& HTTPResponseParser::getResponseHeaders() const { return mResponseHeaders; } const std::string& HTTPResponseParser::getResponseBody() const { return mResponseBody; } bool HTTPResponseParser::isWhitespace(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; } void HTTPResponseParser::stripWhitespaces(std::string& str) { auto begin = str.cbegin(); auto end = str.cend(); // strip leading whitespace while (begin < end && isWhitespace(*begin)) { begin++; } // strip trailing whitespaces end -= 1; while (end > begin && isWhitespace(*end)) { end--; } end += 1; // assign final result str = end > begin ? std::string(begin, end) : std::string(); }
28.063636
122
0.737933
[ "vector", "transform" ]
741e112587845a05fbdf970ddba9c5611cf7049a
621
hpp
C++
FootSoldier.hpp
zhra2zaid/wargame
15a719f286cce7c38da1461b1ab80a3a5b942fc0
[ "MIT" ]
null
null
null
FootSoldier.hpp
zhra2zaid/wargame
15a719f286cce7c38da1461b1ab80a3a5b942fc0
[ "MIT" ]
null
null
null
FootSoldier.hpp
zhra2zaid/wargame
15a719f286cce7c38da1461b1ab80a3a5b942fc0
[ "MIT" ]
null
null
null
#ifndef UNTITLED_FOOTSOLDIER_HPP #define UNTITLED_FOOTSOLDIER_HPP #include "Soldier.hpp" //#define MAX_HEALTH 100 //#define HIT_DAMAGE 10 //namespace WarGame{ class FootSoldier : public Soldier{ public: FootSoldier(int id): Soldier(100,10,id){} ~FootSoldier() { delete this; } int activate(std::vector<std::vector<Soldier*>> &board, int row, int col) override; int get_id() override; void return_to_max_health() override; double dist(std::pair<int, int> from, std::pair<int, int> to); }; #endif //}
22.178571
91
0.600644
[ "vector" ]
741efe9afabf89c196d0f1855099ddeeda01fc87
16,849
cpp
C++
src/mongo/client/fetcher.cpp
xiaobluesky/mongo
40d3940dee184100e1c8a1ac449cddeaf7828d2c
[ "Apache-2.0" ]
2
2021-08-19T12:41:45.000Z
2021-08-19T12:48:10.000Z
src/mongo/client/fetcher.cpp
koooex/roboshell
dc1b3b149202e6d35ff2ef79986ff74fe87b45e2
[ "Apache-2.0" ]
null
null
null
src/mongo/client/fetcher.cpp
koooex/roboshell
dc1b3b149202e6d35ff2ef79986ff74fe87b45e2
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2015 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kExecutor #include "mongo/platform/basic.h" #include "mongo/client/fetcher.h" #include <ostream> #include <utility> #include "mongo/db/jsobj.h" #include "mongo/db/namespace_string.h" #include "mongo/rpc/get_status_from_command_result.h" #include "mongo/util/assert_util.h" #include "mongo/util/destructor_guard.h" #include "mongo/util/log.h" #include "mongo/util/mongoutils/str.h" namespace mongo { namespace { using executor::RemoteCommandRequest; using executor::RemoteCommandResponse; using RemoteCommandCallbackArgs = executor::TaskExecutor::RemoteCommandCallbackArgs; const char* kCursorFieldName = "cursor"; const char* kCursorIdFieldName = "id"; const char* kNamespaceFieldName = "ns"; const char* kFirstBatchFieldName = "firstBatch"; const char* kNextBatchFieldName = "nextBatch"; /** * Parses cursor response in command result for cursor ID, namespace and documents. * 'batchFieldName' will be 'firstBatch' for the initial remote command invocation and * 'nextBatch' for getMore. */ Status parseCursorResponse(const BSONObj& obj, const std::string& batchFieldName, Fetcher::QueryResponse* batchData) { invariant(obj.isOwned()); invariant(batchFieldName == kFirstBatchFieldName || batchFieldName == kNextBatchFieldName); invariant(batchData); BSONElement cursorElement = obj.getField(kCursorFieldName); if (cursorElement.eoo()) { return Status(ErrorCodes::FailedToParse, str::stream() << "cursor response must contain '" << kCursorFieldName << "' field: " << obj); } if (!cursorElement.isABSONObj()) { return Status( ErrorCodes::FailedToParse, str::stream() << "'" << kCursorFieldName << "' field must be an object: " << obj); } BSONObj cursorObj = cursorElement.Obj(); BSONElement cursorIdElement = cursorObj.getField(kCursorIdFieldName); if (cursorIdElement.eoo()) { return Status(ErrorCodes::FailedToParse, str::stream() << "cursor response must contain '" << kCursorFieldName << "." << kCursorIdFieldName << "' field: " << obj); } if (cursorIdElement.type() != mongo::NumberLong) { return Status(ErrorCodes::FailedToParse, str::stream() << "'" << kCursorFieldName << "." << kCursorIdFieldName << "' field must be a 'long' but was a '" << typeName(cursorIdElement.type()) << "': " << obj); } batchData->cursorId = cursorIdElement.numberLong(); BSONElement namespaceElement = cursorObj.getField(kNamespaceFieldName); if (namespaceElement.eoo()) { return Status(ErrorCodes::FailedToParse, str::stream() << "cursor response must contain " << "'" << kCursorFieldName << "." << kNamespaceFieldName << "' field: " << obj); } if (namespaceElement.type() != mongo::String) { return Status(ErrorCodes::FailedToParse, str::stream() << "'" << kCursorFieldName << "." << kNamespaceFieldName << "' field must be a string: " << obj); } NamespaceString tempNss(namespaceElement.valuestrsafe()); if (!tempNss.isValid()) { return Status(ErrorCodes::BadValue, str::stream() << "'" << kCursorFieldName << "." << kNamespaceFieldName << "' contains an invalid namespace: " << obj); } batchData->nss = tempNss; BSONElement batchElement = cursorObj.getField(batchFieldName); if (batchElement.eoo()) { return Status(ErrorCodes::FailedToParse, str::stream() << "cursor response must contain '" << kCursorFieldName << "." << batchFieldName << "' field: " << obj); } if (!batchElement.isABSONObj()) { return Status(ErrorCodes::FailedToParse, str::stream() << "'" << kCursorFieldName << "." << batchFieldName << "' field must be an array: " << obj); } BSONObj batchObj = batchElement.Obj(); for (auto itemElement : batchObj) { if (!itemElement.isABSONObj()) { return Status(ErrorCodes::FailedToParse, str::stream() << "found non-object " << itemElement << " in " << "'" << kCursorFieldName << "." << batchFieldName << "' field: " << obj); } batchData->documents.push_back(itemElement.Obj()); } for (auto& doc : batchData->documents) { doc.shareOwnershipWith(obj); } return Status::OK(); } } // namespace Fetcher::Fetcher(executor::TaskExecutor* executor, const HostAndPort& source, const std::string& dbname, const BSONObj& findCmdObj, const CallbackFn& work, const BSONObj& metadata, Milliseconds timeout, std::unique_ptr<RemoteCommandRetryScheduler::RetryPolicy> firstCommandRetryPolicy) : _executor(executor), _source(source), _dbname(dbname), _cmdObj(findCmdObj.getOwned()), _metadata(metadata.getOwned()), _work(work), _timeout(timeout), _firstRemoteCommandScheduler( _executor, RemoteCommandRequest(_source, _dbname, _cmdObj, _metadata, nullptr, _timeout), stdx::bind(&Fetcher::_callback, this, stdx::placeholders::_1, kFirstBatchFieldName), std::move(firstCommandRetryPolicy)) { uassert(ErrorCodes::BadValue, "callback function cannot be null", work); } Fetcher::~Fetcher() { DESTRUCTOR_GUARD(shutdown(); join();); } HostAndPort Fetcher::getSource() const { return _source; } BSONObj Fetcher::getCommandObject() const { return _cmdObj; } BSONObj Fetcher::getMetadataObject() const { return _metadata; } Milliseconds Fetcher::getTimeout() const { return _timeout; } std::string Fetcher::toString() const { return getDiagnosticString(); } std::string Fetcher::getDiagnosticString() const { stdx::lock_guard<stdx::mutex> lk(_mutex); str::stream output; output << "Fetcher"; output << " source: " << _source.toString(); output << " database: " << _dbname; output << " query: " << _cmdObj; output << " query metadata: " << _metadata; output << " active: " << _isActive_inlock(); output << " timeout: " << _timeout; output << " shutting down?: " << _isShuttingDown_inlock(); output << " first: " << _first; output << " firstCommandScheduler: " << _firstRemoteCommandScheduler.toString(); if (_getMoreCallbackHandle.isValid()) { output << " getMoreHandle.valid: " << _getMoreCallbackHandle.isValid(); output << " getMoreHandle.cancelled: " << _getMoreCallbackHandle.isCanceled(); } return output; } bool Fetcher::isActive() const { stdx::lock_guard<stdx::mutex> lk(_mutex); return _isActive_inlock(); } bool Fetcher::_isActive_inlock() const { return State::kRunning == _state || State::kShuttingDown == _state; } Status Fetcher::schedule() { stdx::lock_guard<stdx::mutex> lock(_mutex); switch (_state) { case State::kPreStart: _state = State::kRunning; break; case State::kRunning: return Status(ErrorCodes::InternalError, "fetcher already started"); case State::kShuttingDown: return Status(ErrorCodes::ShutdownInProgress, "fetcher shutting down"); case State::kComplete: return Status(ErrorCodes::ShutdownInProgress, "fetcher completed"); } auto status = _firstRemoteCommandScheduler.startup(); if (!status.isOK()) { _state = State::kComplete; return status; } return Status::OK(); } void Fetcher::shutdown() { stdx::lock_guard<stdx::mutex> lock(_mutex); switch (_state) { case State::kPreStart: // Transition directly from PreStart to Complete if not started yet. _state = State::kComplete; return; case State::kRunning: _state = State::kShuttingDown; break; case State::kShuttingDown: case State::kComplete: // Nothing to do if we are already in ShuttingDown or Complete state. return; } _firstRemoteCommandScheduler.shutdown(); if (_getMoreCallbackHandle) { _executor->cancel(_getMoreCallbackHandle); } } void Fetcher::join() { stdx::unique_lock<stdx::mutex> lk(_mutex); _condition.wait(lk, [this]() { return !_isActive_inlock(); }); } Fetcher::State Fetcher::getState_forTest() const { stdx::lock_guard<stdx::mutex> lk(_mutex); return _state; } bool Fetcher::_isShuttingDown() const { stdx::lock_guard<stdx::mutex> lk(_mutex); return _isShuttingDown_inlock(); } bool Fetcher::_isShuttingDown_inlock() const { return State::kShuttingDown == _state; } Status Fetcher::_scheduleGetMore(const BSONObj& cmdObj) { stdx::lock_guard<stdx::mutex> lk(_mutex); if (_isShuttingDown_inlock()) { return Status(ErrorCodes::CallbackCanceled, "fetcher was shut down after previous batch was processed"); } StatusWith<executor::TaskExecutor::CallbackHandle> scheduleResult = _executor->scheduleRemoteCommand( RemoteCommandRequest(_source, _dbname, cmdObj, _metadata, nullptr, _timeout), stdx::bind(&Fetcher::_callback, this, stdx::placeholders::_1, kNextBatchFieldName)); if (!scheduleResult.isOK()) { return scheduleResult.getStatus(); } _getMoreCallbackHandle = scheduleResult.getValue(); return Status::OK(); } void Fetcher::_callback(const RemoteCommandCallbackArgs& rcbd, const char* batchFieldName) { if (!rcbd.response.isOK()) { _work(StatusWith<Fetcher::QueryResponse>(rcbd.response.status), nullptr, nullptr); _finishCallback(); return; } if (_isShuttingDown()) { _work(Status(ErrorCodes::CallbackCanceled, "fetcher shutting down"), nullptr, nullptr); _finishCallback(); return; } const BSONObj& queryResponseObj = rcbd.response.data; Status status = getStatusFromCommandResult(queryResponseObj); if (!status.isOK()) { _work(StatusWith<Fetcher::QueryResponse>(status), nullptr, nullptr); _finishCallback(); return; } QueryResponse batchData; status = parseCursorResponse(queryResponseObj, batchFieldName, &batchData); if (!status.isOK()) { _work(StatusWith<Fetcher::QueryResponse>(status), nullptr, nullptr); _finishCallback(); return; } batchData.otherFields.metadata = std::move(rcbd.response.metadata); batchData.elapsedMillis = rcbd.response.elapsedMillis.value_or(Milliseconds{0}); { stdx::lock_guard<stdx::mutex> lk(_mutex); batchData.first = _first; _first = false; } NextAction nextAction = NextAction::kNoAction; if (!batchData.cursorId) { _work(StatusWith<QueryResponse>(batchData), &nextAction, nullptr); _finishCallback(); return; } nextAction = NextAction::kGetMore; BSONObjBuilder bob; _work(StatusWith<QueryResponse>(batchData), &nextAction, &bob); // Callback function _work may modify nextAction to request the fetcher // not to schedule a getMore command. if (nextAction != NextAction::kGetMore) { _sendKillCursors(batchData.cursorId, batchData.nss); _finishCallback(); return; } // Callback function may also disable the fetching of additional data by not filling in the // BSONObjBuilder for the getMore command. auto cmdObj = bob.obj(); if (cmdObj.isEmpty()) { _sendKillCursors(batchData.cursorId, batchData.nss); _finishCallback(); return; } status = _scheduleGetMore(cmdObj); if (!status.isOK()) { nextAction = NextAction::kNoAction; _work(StatusWith<Fetcher::QueryResponse>(status), nullptr, nullptr); _sendKillCursors(batchData.cursorId, batchData.nss); _finishCallback(); return; } } void Fetcher::_sendKillCursors(const CursorId id, const NamespaceString& nss) { if (id) { auto logKillCursorsResult = [](const RemoteCommandCallbackArgs& args) { if (!args.response.isOK()) { warning() << "killCursors command task failed: " << redact(args.response.status); return; } auto status = getStatusFromCommandResult(args.response.data); if (!status.isOK()) { warning() << "killCursors command failed: " << redact(status); } }; auto cmdObj = BSON("killCursors" << nss.coll() << "cursors" << BSON_ARRAY(id)); auto scheduleResult = _executor->scheduleRemoteCommand( RemoteCommandRequest(_source, _dbname, cmdObj, nullptr), logKillCursorsResult); if (!scheduleResult.isOK()) { warning() << "failed to schedule killCursors command: " << redact(scheduleResult.getStatus()); } } } void Fetcher::_finishCallback() { // After running callback function, clear '_work' to release any resources that might be held by // this function object. // '_work' must be moved to a temporary copy and destroyed outside the lock in case there is any // logic that's invoked at the function object's destruction that might call into this Fetcher. // 'tempWork' must be declared before lock guard 'lk' so that it is destroyed outside the lock. Fetcher::CallbackFn tempWork; stdx::lock_guard<stdx::mutex> lk(_mutex); invariant(State::kComplete != _state); _state = State::kComplete; _first = false; _condition.notify_all(); invariant(_work); std::swap(_work, tempWork); } std::ostream& operator<<(std::ostream& os, const Fetcher::State& state) { switch (state) { case Fetcher::State::kPreStart: return os << "PreStart"; case Fetcher::State::kRunning: return os << "Running"; case Fetcher::State::kShuttingDown: return os << "ShuttingDown"; case Fetcher::State::kComplete: return os << "Complete"; } MONGO_UNREACHABLE; } } // namespace mongo
36.469697
100
0.606208
[ "object" ]
742311ae6f1b19f639aeabe3082a7f1dfab7b965
34,942
cpp
C++
dali-toolkit/internal/controls/slider/slider-impl.cpp
Coquinho/dali-toolkit
8fea8f2ae64923690519e0de039ce4af51271d9f
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
dali-toolkit/internal/controls/slider/slider-impl.cpp
Coquinho/dali-toolkit
8fea8f2ae64923690519e0de039ce4af51271d9f
[ "Apache-2.0", "BSD-3-Clause" ]
1
2020-10-19T15:47:43.000Z
2020-10-19T15:47:43.000Z
dali-toolkit/internal/controls/slider/slider-impl.cpp
expertisesolutions/dali-toolkit
eac3e6ee30183868f1af12addd94e7f2fc467ed7
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali-toolkit/internal/controls/slider/slider-impl.h> // EXTERNAL INCLUDES #include <cstring> // for strcmp #include <sstream> #include <limits> #include <dali/public-api/events/touch-event.h> #include <dali/public-api/object/type-registry.h> #include <dali/public-api/object/type-registry-helper.h> // INTERNAL INCLUDES #include <dali-toolkit/devel-api/asset-manager/asset-manager.h> #include <dali-toolkit/public-api/visuals/image-visual-properties.h> #include <dali-toolkit/public-api/controls/control-impl.h> #include <dali-toolkit/public-api/controls/image-view/image-view.h> using namespace Dali; namespace Dali { namespace Toolkit { namespace Internal { namespace // Unnamed namespace { BaseHandle Create() { return Dali::Toolkit::Slider::New(); } // Setup properties, signals and actions using the type-registry. DALI_TYPE_REGISTRATION_BEGIN( Toolkit::Slider, Toolkit::Control, Create ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "lowerBound", FLOAT, LOWER_BOUND ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "upperBound", FLOAT, UPPER_BOUND ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "value", FLOAT, VALUE ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "trackVisual", MAP, TRACK_VISUAL ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "handleVisual", MAP, HANDLE_VISUAL ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "progressVisual", MAP, PROGRESS_VISUAL ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "popupVisual", MAP, POPUP_VISUAL ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "popupArrowVisual", MAP, POPUP_ARROW_VISUAL ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "disabledColor", VECTOR4, DISABLED_COLOR ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "valuePrecision", INTEGER, VALUE_PRECISION ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "showPopup", BOOLEAN, SHOW_POPUP ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "showValue", BOOLEAN, SHOW_VALUE ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "marks", ARRAY, MARKS ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "snapToMarks", BOOLEAN, SNAP_TO_MARKS ) DALI_PROPERTY_REGISTRATION( Toolkit, Slider, "markTolerance", FLOAT, MARK_TOLERANCE ) DALI_SIGNAL_REGISTRATION( Toolkit, Slider, "valueChanged", SIGNAL_VALUE_CHANGED ) DALI_SIGNAL_REGISTRATION( Toolkit, Slider, "mark", SIGNAL_MARK ) DALI_TYPE_REGISTRATION_END() const float MARK_SNAP_TOLERANCE = 0.05f; // 5% of slider width const int VALUE_VIEW_SHOW_DURATION = 1000; // millisec const int VALUE_VIEW_SHOW_DURATION_LONG = 2000; // millisec const float VALUE_VERTICAL_OFFSET = 48.0f; const float DEFAULT_WIDTH = 0.0f; const float DEFAULT_HEIGHT = 27.0f; const float DEFAULT_HIT_HEIGHT = 72.0f; const float DEFAULT_HANDLE_HEIGHT = DEFAULT_HIT_HEIGHT; const float POPUP_TEXT_PADDING = 10.0f; const char* SKINNED_TRACK_VISUAL_FILE_NAME = "slider-skin.9.png"; const char* SKINNED_HANDLE_VISUAL_FILE_NAME = "slider-skin-handle.png"; const char* SKINNED_PROGRESS_VISUAL_FILE_NAME = "slider-skin-progress.9.png"; const char* SKINNED_POPUP_VISUAL_FILE_NAME = "slider-popup.9.png"; const char* SKINNED_POPUP_ARROW_VISUAL_FILE_NAME = "slider-popup-arrow.png"; const Vector2 DEFAULT_HIT_REGION( DEFAULT_WIDTH, DEFAULT_HIT_HEIGHT ); const Vector2 DEFAULT_TRACK_REGION( DEFAULT_WIDTH, DEFAULT_HEIGHT ); const Vector2 DEFAULT_HANDLE_SIZE( DEFAULT_HANDLE_HEIGHT, DEFAULT_HANDLE_HEIGHT ); const Vector4 DEFAULT_DISABLED_COLOR( 0.5f, 0.5f, 0.5f, 1.0f ); const float VALUE_POPUP_MARGIN = 10.0f; const float VALUE_POPUP_HEIGHT = 81.0f; const float VALUE_POPUP_MIN_WIDTH = 54.0f; const float DEFAULT_LOWER_BOUND = 0.0f; const float DEFAULT_UPPER_BOUND = 1.0f; const float DEFAULT_VALUE = 0.0f; const int DEFAULT_VALUE_PRECISION = 0; const bool DEFAULT_SHOW_POPUP = false; const bool DEFAULT_SHOW_VALUE = true; const bool DEFAULT_ENABLED = true; const bool DEFAULT_SNAP_TO_MARKS = false; } // Unnamed namespace /////////////////////////////////////////////////////////////////////////////////////////////////// // Slider /////////////////////////////////////////////////////////////////////////////////////////////////// Dali::Toolkit::Slider Slider::New() { // Create the implementation SliderPtr slider( new Slider() ); // Pass ownership to CustomActor via derived handle Dali::Toolkit::Slider handle( *slider ); // Second-phase init of the implementation // This can only be done after the CustomActor connection has been made... slider->Initialize(); return handle; } Slider::Slider() : Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ), mState( NORMAL ), mPopupVisual(""), mPopupArrowVisual(""), mTrackVisual(""), mHandleVisual(""), mProgressVisual(""), mPopupMap(), mTrackMap(), mHandleMap(), mPopupArrowMap(), mDisabledColor( 0.0f, 0.0f, 0.0f, 0.0f ), mHitRegion( 0.0f, 0.0f ), mTrackRegion( 0.0f, 0.0f ), mHandleSize( 0.0f, 0.0f ), mLowerBound( 0.0f ), mUpperBound( 0.0f ), mValue( 0.0f ), mMarkTolerance( 0.0f ), mValuePrecision( 0 ), mShowPopup( false ), mShowValue( false ), mSnapToMarks( false ) { } Slider::~Slider() { } void Slider::OnInitialize() { // Setup CreateChildren(); // Properties Actor self = Self(); SetHitRegion( DEFAULT_HIT_REGION ); SetTrackRegion( DEFAULT_TRACK_REGION ); SetHandleSize( DEFAULT_HANDLE_SIZE ); const std::string imageDirPath = AssetManager::GetDaliImagePath(); SetTrackVisual( imageDirPath + SKINNED_TRACK_VISUAL_FILE_NAME ); SetHandleVisual( imageDirPath + SKINNED_HANDLE_VISUAL_FILE_NAME ); SetProgressVisual( imageDirPath + SKINNED_PROGRESS_VISUAL_FILE_NAME ); SetPopupVisual( imageDirPath + SKINNED_POPUP_VISUAL_FILE_NAME ); SetPopupArrowVisual( imageDirPath + SKINNED_POPUP_ARROW_VISUAL_FILE_NAME ); SetShowPopup( DEFAULT_SHOW_POPUP ); SetShowValue( DEFAULT_SHOW_VALUE ); SetEnabled( DEFAULT_ENABLED ); SetDisabledColor( DEFAULT_DISABLED_COLOR ); SetSnapToMarks( DEFAULT_SNAP_TO_MARKS ); SetMarkTolerance( MARK_SNAP_TOLERANCE ); SetLowerBound( DEFAULT_LOWER_BOUND ); SetUpperBound( DEFAULT_UPPER_BOUND ); UpdateSkin(); SetValuePrecision( DEFAULT_VALUE_PRECISION ); mValue = DEFAULT_VALUE; DisplayValue( mValue, false ); // Run this last to display the correct value // Size the Slider actor to a default self.SetProperty( Actor::Property::SIZE, Vector2( DEFAULT_HIT_REGION.x, DEFAULT_HIT_REGION.y ) ); // Connect to the touch signal self.TouchedSignal().Connect( this, &Slider::OnTouch ); } void Slider::OnRelayout( const Vector2& size, RelayoutContainer& container ) { SetHitRegion( Vector2( size.x, GetHitRegion().y ) ); // Factor in handle overshoot into size of backing SetTrackRegion( Vector2( size.x - GetHandleSize().x, GetTrackRegion().y ) ); Control::OnRelayout( size, container ); } bool Slider::OnTouch(Actor actor, const TouchEvent& touch) { if( mState != DISABLED ) { const PointState::Type touchState = touch.GetState(0); if( touchState == PointState::DOWN ) { mState = PRESSED; float percentage = MapPercentage( touch.GetLocalPosition( 0 ) ); float value = MapBounds( ( GetSnapToMarks() ) ? SnapToMark( percentage ) : MarkFilter( percentage ), GetLowerBound(), GetUpperBound() ); SetValue( value ); DisplayPopup( value ); } else if( touchState == PointState::UP ) { if( mState == PRESSED ) { mState = NORMAL; mSlidingFinishedSignal.Emit( Toolkit::Slider::DownCast( Self() ), GetValue() ); } } } return false; } void Slider::OnPan( Actor actor, const PanGesture& gesture ) { // gesture.position is in local actor coordinates if( mState != DISABLED ) { switch( gesture.GetState() ) { case GestureState::CONTINUING: { if( mState == PRESSED ) { float value = MapBounds( MarkFilter ( MapPercentage( gesture.GetPosition() ) ), GetLowerBound(), GetUpperBound() ); SetValue( value ); DisplayPopup( value ); } break; } case GestureState::FINISHED: { if( mState == PRESSED ) { if( GetSnapToMarks() ) { float value = MapBounds( SnapToMark( MapPercentage( gesture.GetPosition() ) ), GetLowerBound(), GetUpperBound() ); SetValue( value ); DisplayPopup( value ); } mSlidingFinishedSignal.Emit( Toolkit::Slider::DownCast( Self() ), GetValue() ); } mState = NORMAL; break; } default: { break; } } } } float Slider::HitSpaceToDomain( float x ) { float halfRegionWidth = GetHitRegion().x * 0.5f; float halfDomainWidth = ( mDomain.to.x - mDomain.from.x ) * 0.5f; float endDiff = halfRegionWidth - halfDomainWidth; return x - endDiff; } float Slider::MapPercentage( const Vector2& point ) { return Clamp( ( HitSpaceToDomain( point.x ) - mDomain.from.x ) / ( mDomain.to.x - mDomain.from.x ), 0.0f, 1.0f ); } float Slider::MapValuePercentage( float value ) { return ( value - GetLowerBound() ) / ( GetUpperBound() - GetLowerBound() ); } float Slider::MapBounds( float percent, float lowerBound, float upperBound ) { return lowerBound + percent * ( upperBound - lowerBound ); } Slider::Domain Slider::CalcDomain( const Vector2& currentSize ) { return Domain( Vector2( 0.0f, 0.0f ), currentSize ); } void Slider::DisplayValue( float value, bool raiseSignals ) { float clampedValue = Clamp( value, GetLowerBound(), GetUpperBound() ); float percent = MapValuePercentage( clampedValue ); float x = mDomain.from.x + percent * ( mDomain.to.x - mDomain.from.x ); mHandle.SetProperty( Actor::Property::POSITION_X, x ); // Progress bar if( mProgress ) { mProgress.SetProperty( Actor::Property::SIZE, Vector2( x, GetTrackRegion().y ) ); } // Signals if( raiseSignals ) { Toolkit::Slider self = Toolkit::Slider::DownCast( Self() ); mValueChangedSignal.Emit( self, clampedValue ); int markIndex; if( MarkReached( percent, markIndex ) ) { mMarkReachedSignal.Emit( self, markIndex ); } } if( mHandleValueTextLabel ) { std::stringstream ss; ss.precision( GetValuePrecision() ); ss << std::fixed << clampedValue; std::string label = mHandleValueTextLabel.GetProperty<std::string>( Toolkit::TextLabel::Property::TEXT ); if( label.compare(ss.str()) ) { mHandleValueTextLabel.SetProperty( Toolkit::TextLabel::Property::TEXT, ss.str() ); } } } void Slider::SetMarks( const MarkList& marks ) { mMarks = marks; } const Slider::MarkList& Slider::GetMarks() const { return mMarks; } void Slider::SetSnapToMarks( bool snap ) { mSnapToMarks = snap; } bool Slider::GetSnapToMarks() const { return mSnapToMarks; } Actor Slider::CreateHitRegion() { Actor hitRegion = Actor::New(); hitRegion.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); hitRegion.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); hitRegion.TouchedSignal().Connect( this, &Slider::OnTouch ); return hitRegion; } Toolkit::ImageView Slider::CreateTrack() { Toolkit::ImageView track = Toolkit::ImageView::New(); track.SetProperty( Dali::Actor::Property::NAME,"SliderTrack"); track.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); track.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); return track; } void Slider::SetTrackVisual( const std::string& filename ) { if( mHandle && ( filename.size() > 0 ) ) { mTrack.SetImage( filename ); mTrackVisual = filename; } } void Slider::SetTrackVisual( Property::Map map ) { Property::Value* imageValue = map.Find( "url" ); if( imageValue ) { mTrackVisual.clear(); std::string filename; if( imageValue->Get( filename ) ) { if( mTrack && ( filename.size() > 0 ) ) { mTrack.SetImage( filename ); mTrackMap = map; } } } Property::Value* sizeValue = map.Find( "size" ); if( sizeValue ) { Vector2 size; if( sizeValue->Get( size ) ) { mTrackRegion = size; if( mTrack ) { mTrack.SetProperty( Actor::Property::SIZE, mTrackRegion ); } ResizeProgressRegion( Vector2( 0.0f, mTrackRegion.y ) ); mDomain = CalcDomain( mTrackRegion ); // Set the progress bar to correct width DisplayValue( GetValue(), false ); } } } std::string Slider::GetTrackVisual() { return mTrackVisual; } Toolkit::ImageView Slider::CreateProgress() { Toolkit::ImageView progress = Toolkit::ImageView::New(); progress.SetProperty( Dali::Actor::Property::NAME,"SliderProgress"); progress.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT ); progress.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER_LEFT ); return progress; } void Slider::SetProgressVisual( const std::string& filename ) { if( mProgress && ( filename.size() > 0 ) ) { mProgress.SetImage( filename ); mProgressVisual = filename; } } void Slider::SetProgressVisual( Property::Map map ) { Property::Value* imageValue = map.Find( "url" ); if( imageValue ) { mProgressVisual.clear(); std::string filename; if( imageValue->Get( filename ) ) { if( mProgress && ( filename.size() > 0 ) ) { mProgress.SetImage( filename ); mProgressMap = map; } } } } std::string Slider::GetProgressVisual() { return mProgressVisual; } void Slider::SetPopupVisual( const std::string& filename ) { mPopupVisual = filename; } void Slider::SetPopupVisual( Property::Map map ) { Property::Value* imageValue = map.Find( "url" ); if( imageValue ) { mPopupVisual.clear(); std::string filename; if( imageValue->Get( filename ) ) { if( mPopup && ( filename.size() > 0 ) ) { mPopup.SetImage( filename ); mPopupMap = map; } } } } std::string Slider::GetPopupVisual() { return mPopupVisual; } void Slider::CreatePopupImage( const std::string& filename ) { if( mPopup && ( filename.size() > 0 ) ) { Property::Map map; map[Toolkit::ImageVisual::Property::URL] = filename; mPopup.SetProperty( Toolkit::ImageView::Property::IMAGE, map ); } } void Slider::SetPopupArrowVisual( const std::string& filename ) { mPopupArrowVisual = filename; } void Slider::SetPopupArrowVisual( Property::Map map ) { Property::Value* imageValue = map.Find( "url" ); if( imageValue ) { mPopupArrowVisual.clear(); std::string filename; if( imageValue->Get( filename ) ) { if( mPopupArrow && ( filename.size() > 0 ) ) { mPopupArrow.SetImage( filename ); mPopupArrowMap = map; } } } } std::string Slider::GetPopupArrowVisual() { return mPopupArrowVisual; } void Slider::CreatePopupArrowImage( const std::string& filename ) { if( mPopupArrow && ( filename.size() > 0 ) ) { Property::Map map; map[Toolkit::ImageVisual::Property::URL] = filename; mPopupArrow.SetProperty( Toolkit::ImageView::Property::IMAGE, map ); } } void Slider::ResizeProgressRegion( const Vector2& region ) { if( mProgress ) { mProgress.SetProperty( Actor::Property::SIZE, region ); } } Toolkit::ImageView Slider::CreateHandle() { Toolkit::ImageView handle = Toolkit::ImageView::New(); handle.SetProperty( Dali::Actor::Property::NAME,"SliderHandle"); handle.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER_LEFT ); handle.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); return handle; } Toolkit::ImageView Slider::CreatePopupArrow() { Toolkit::ImageView arrow = Toolkit::ImageView::New(); arrow.SetStyleName("SliderPopupArrow"); arrow.SetProperty( Dali::Actor::Property::NAME,"SliderPopupArrow"); arrow.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_CENTER ); arrow.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER ); return arrow; } Toolkit::TextLabel Slider::CreatePopupText() { Toolkit::TextLabel textLabel = Toolkit::TextLabel::New(); textLabel.SetProperty( Dali::Actor::Property::NAME, "SliderPopupTextLabel" ); textLabel.SetStyleName( "SliderPopupTextLabel" ); textLabel.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); textLabel.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); textLabel.SetResizePolicy( ResizePolicy::USE_NATURAL_SIZE, Dimension::ALL_DIMENSIONS ); textLabel.SetProperty( Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER" ); textLabel.SetProperty( Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT, "CENTER" ); textLabel.SetProperty( Actor::Property::PADDING, Padding( POPUP_TEXT_PADDING, POPUP_TEXT_PADDING, 0.0f, 0.0f ) ); return textLabel; } Toolkit::ImageView Slider::CreatePopup() { Toolkit::ImageView popup = Toolkit::ImageView::New(); popup.SetProperty( Dali::Actor::Property::NAME, "SliderPopup" ); popup.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER ); popup.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER ); popup.SetResizePolicy( ResizePolicy::FIT_TO_CHILDREN, Dimension::WIDTH ); mValueTextLabel = CreatePopupText(); popup.Add( mValueTextLabel ); return popup; } void Slider::SetHandleVisual( const std::string& filename ) { if( mHandle && ( filename.size() > 0 ) ) { mHandle.SetImage( filename ); mHandleVisual = filename; } } void Slider::SetHandleVisual( Property::Map map ) { Property::Value* imageValue = map.Find( "url" ); if( imageValue ) { mHandleVisual.clear(); std::string filename; if( imageValue->Get( filename ) ) { if( mHandle && ( filename.size() > 0 ) ) { mHandle.SetImage( filename ); mHandleMap = map; } } } Property::Value* sizeValue = map.Find( "size" ); if( sizeValue ) { Vector2 size; if( sizeValue->Get( size ) ) { mHandleSize = size; ResizeHandleSize( mHandleSize ); Vector2 hitRegion = GetHitRegion(); hitRegion.x += mHandleSize.x; SetHitRegion( hitRegion ); } } } std::string Slider::GetHandleVisual() { return mHandleVisual; } void Slider::ResizeHandleSize( const Vector2& size ) { if( mHandle ) { mHandle.SetProperty( Actor::Property::SIZE, size ); } } void Slider::CreateHandleValueDisplay() { if( mHandle && !mHandleValueTextLabel ) { mHandleValueTextLabel = Toolkit::TextLabel::New(); mHandleValueTextLabel.SetProperty( Dali::Actor::Property::NAME,"SliderHandleTextLabel"); mHandleValueTextLabel.SetStyleName("SliderHandleTextLabel"); mHandleValueTextLabel.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER ); mHandleValueTextLabel.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER ); mHandleValueTextLabel.SetProperty( Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER" ); mHandleValueTextLabel.SetProperty( Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT, "CENTER" ); mHandle.Add( mHandleValueTextLabel ); } } void Slider::DestroyHandleValueDisplay() { UnparentAndReset(mHandleValueTextLabel); } Actor Slider::CreateValueDisplay() { Actor popup = Actor::New(); popup.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER ); popup.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER ); mPopupArrow = CreatePopupArrow(); popup.Add( mPopupArrow ); mPopup = CreatePopup(); mPopup.SetProperty( Actor::Property::SIZE, Vector2( 0.0f, VALUE_POPUP_HEIGHT ) ); mPopupArrow.Add( mPopup ); return popup; } Toolkit::Slider::ValueChangedSignalType& Slider::ValueChangedSignal() { return mValueChangedSignal; } Toolkit::Slider::ValueChangedSignalType& Slider::SlidingFinishedSignal() { return mSlidingFinishedSignal; } Toolkit::Slider::MarkReachedSignalType& Slider::MarkReachedSignal() { return mMarkReachedSignal; } void Slider::UpdateSkin() { switch( mState ) { case NORMAL: { mTrack.SetProperty( Actor::Property::COLOR, Color::WHITE ); mHandle.SetProperty( Actor::Property::COLOR, Color::WHITE ); mProgress.SetProperty( Actor::Property::COLOR, Color::WHITE ); break; } case DISABLED: { Vector4 disabledColor = GetDisabledColor(); mTrack.SetProperty( Actor::Property::COLOR, disabledColor ); mHandle.SetProperty( Actor::Property::COLOR, disabledColor ); mProgress.SetProperty( Actor::Property::COLOR, disabledColor ); break; } case PRESSED: { break; } case FOCUSED: { break; } } } void Slider::CreateChildren() { Actor self = Self(); // Hit region mHitArea = CreateHitRegion(); mPanDetector = PanGestureDetector::New(); mPanDetector.Attach( mHitArea ); mPanDetector.DetectedSignal().Connect( this, &Slider::OnPan ); self.Add( mHitArea ); // Track mTrack = CreateTrack(); self.Add( mTrack ); // Progress bar mProgress = CreateProgress(); mTrack.Add( mProgress ); // Handle mHandle = CreateHandle(); mProgress.Add( mHandle ); } void Slider::SetHitRegion( const Vector2& size ) { mHitRegion = size; if( mHitArea ) { mHitArea.SetProperty( Actor::Property::SIZE, mHitRegion ); } } const Vector2& Slider::GetHitRegion() const { return mHitRegion; } void Slider::AddPopup() { if( !mValueDisplay ) { mValueDisplay = CreateValueDisplay(); mValueDisplay.SetProperty( Actor::Property::VISIBLE, false ); mHandle.Add( mValueDisplay ); CreatePopupImage( GetPopupVisual() ); CreatePopupArrowImage( GetPopupArrowVisual() ); mValueTimer = Timer::New( VALUE_VIEW_SHOW_DURATION ); mValueTimer.TickSignal().Connect( this, &Slider::HideValueView ); } } void Slider::RemovePopup() { if( mValueDisplay ) { mPopup.Unparent(); mPopup.Reset(); mPopupArrow.Unparent(); mPopupArrow.Reset(); mValueDisplay.Unparent(); mValueDisplay.Reset(); mValueTimer.TickSignal().Disconnect( this, &Slider::HideValueView ); mValueTimer.Reset(); } } float Slider::MarkFilter( float value ) { const float MARK_TOLERANCE = GetMarkTolerance(); float mark; for( MarkList::SizeType i = 0; i < mMarks.Count(); ++i) { const Property::Value& propertyValue = mMarks[i]; propertyValue.Get( mark ); mark = MapValuePercentage( mark ); // If close to a mark, return the mark if( fabsf( mark - value ) < MARK_TOLERANCE ) { return mark; } } return value; } float Slider::SnapToMark( float value ) { float closestMark = value; float closestDist = std::numeric_limits<float>::max(); float mark; for( MarkList::SizeType i = 0; i < mMarks.Count(); ++i) { const Property::Value& propertyValue = mMarks[i]; propertyValue.Get( mark ); mark = MapValuePercentage( mark ); float dist = fabsf( mark - value ); if( dist < closestDist ) { closestDist = dist; closestMark = mark; } } return closestMark; } bool Slider::MarkReached( float value, int& outIndex ) { const float MARK_TOLERANCE = GetMarkTolerance(); // Binary search int head = 0, tail = mMarks.Size() - 1; int current; float mark; while( head <= tail ) { current = head + ( tail - head ) / 2; const Property::Value& propertyValue = mMarks[ current ]; propertyValue.Get( mark ); mark = MapValuePercentage( mark ); if( fabsf( mark - value ) < MARK_TOLERANCE ) { outIndex = current; return true; } if( value < mark ) { tail = current - 1; } else { head = current + 1; } } return false; } bool Slider::HideValueView() { if( mValueDisplay ) { mValueDisplay.SetProperty( Actor::Property::VISIBLE, false ); } return false; } void Slider::SetLowerBound( float bound ) { mLowerBound = bound; DisplayValue( GetValue(), false ); } float Slider::GetLowerBound() const { return mLowerBound; } void Slider::SetUpperBound( float bound ) { mUpperBound = bound; DisplayValue( GetValue(), false ); } float Slider::GetUpperBound() const { return mUpperBound; } void Slider::SetValue( float value ) { mValue = value; DisplayValue( mValue, true ); } float Slider::GetValue() const { return mValue; } void Slider::SetTrackRegion( const Vector2& region ) { mTrackRegion = region; if( mTrack ) { mTrack.SetProperty( Actor::Property::SIZE, mTrackRegion ); } ResizeProgressRegion( Vector2( 0.0f, mTrackRegion.y ) ); mDomain = CalcDomain( mTrackRegion ); DisplayValue( GetValue(), false ); // Set the progress bar to correct width } const Vector2& Slider::GetTrackRegion() const { return mTrackRegion; } void Slider::SetHandleSize( const Vector2& size ) { mHandleSize = size; ResizeHandleSize( mHandleSize ); Vector2 hitRegion = GetHitRegion(); hitRegion.x += mHandleSize.x; SetHitRegion( hitRegion ); } const Vector2& Slider::GetHandleSize() const { return mHandleSize; } void Slider::SetDisabledColor( const Vector4& color ) { mDisabledColor = color; UpdateSkin(); } Vector4 Slider::GetDisabledColor() const { return mDisabledColor; } void Slider::SetValuePrecision( int precision ) { mValuePrecision = precision; } int Slider::GetValuePrecision() const { return mValuePrecision; } void Slider::SetShowPopup( bool showPopup ) { mShowPopup = showPopup; // Value display if( mShowPopup ) { AddPopup(); } else { RemovePopup(); } } bool Slider::GetShowPopup() const { return mShowPopup; } void Slider::SetShowValue( bool showValue ) { mShowValue = showValue; if( mShowValue ) { CreateHandleValueDisplay(); } else { DestroyHandleValueDisplay(); } } bool Slider::GetShowValue() const { return mShowValue; } void Slider::SetEnabled( bool enabled ) { if( enabled ) { mState = NORMAL; } else { mState = DISABLED; } UpdateSkin(); } bool Slider::IsEnabled() const { return mState != DISABLED; } void Slider::SetMarkTolerance( float tolerance ) { mMarkTolerance = tolerance; } float Slider::GetMarkTolerance() const { return mMarkTolerance; } // Static class method to support script connecting signals bool Slider::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor ) { Dali::BaseHandle handle( object ); bool connected = true; Toolkit::Slider slider = Toolkit::Slider::DownCast( handle ); if( 0 == strcmp( signalName.c_str(), SIGNAL_VALUE_CHANGED ) ) { slider.ValueChangedSignal().Connect( tracker, functor ); } else if( 0 == strcmp( signalName.c_str(), SIGNAL_MARK ) ) { slider.MarkReachedSignal().Connect( tracker, functor ); } else { // signalName does not match any signal connected = false; } return connected; } void Slider::DisplayPopup( float value ) { // Value displayDoConnectSignal if( mValueTextLabel ) { std::stringstream ss; ss.precision( GetValuePrecision() ); ss << std::fixed << value; mValueTextLabel.SetProperty( Toolkit::TextLabel::Property::TEXT, ss.str() ); if( mValueDisplay ) { mValueDisplay.SetProperty( Actor::Property::VISIBLE, true ); mValueTimer.SetInterval( VALUE_VIEW_SHOW_DURATION ); } } } void Slider::SetProperty( BaseObject* object, Property::Index propertyIndex, const Property::Value& value ) { Toolkit::Slider slider = Toolkit::Slider::DownCast( Dali::BaseHandle( object ) ); if ( slider ) { Slider& sliderImpl( GetImpl( slider ) ); switch ( propertyIndex ) { case Toolkit::Slider::Property::LOWER_BOUND: { sliderImpl.SetLowerBound( value.Get< float >() ); break; } case Toolkit::Slider::Property::UPPER_BOUND: { sliderImpl.SetUpperBound( value.Get< float >() ); break; } case Toolkit::Slider::Property::VALUE: { sliderImpl.SetValue( value.Get< float >() ); break; } case Toolkit::Slider::Property::TRACK_VISUAL: { Property::Map map; if( value.Get( map ) ) { sliderImpl.SetTrackVisual( map ); } break; } case Toolkit::Slider::Property::HANDLE_VISUAL: { Property::Map map; if( value.Get( map ) ) { sliderImpl.SetHandleVisual( map ); } break; } case Toolkit::Slider::Property::PROGRESS_VISUAL: { Property::Map map; if( value.Get( map ) ) { sliderImpl.SetProgressVisual( map ); } break; } case Toolkit::Slider::Property::POPUP_VISUAL: { std::string imageUrl; if( value.Get( imageUrl ) ) { sliderImpl.SetPopupVisual( imageUrl ); } // If it is not a string, then get a Property::Map from the property if possible. Property::Map map; if( value.Get( map ) ) { sliderImpl.SetPopupVisual( map ); } break; } case Toolkit::Slider::Property::POPUP_ARROW_VISUAL: { Property::Map map; if( value.Get( map ) ) { sliderImpl.SetPopupArrowVisual( map ); } break; } case Toolkit::Slider::Property::DISABLED_COLOR: { sliderImpl.SetDisabledColor( value.Get< Vector4 >() ); break; } case Toolkit::Slider::Property::VALUE_PRECISION: { sliderImpl.SetValuePrecision( value.Get< int >() ); break; } case Toolkit::Slider::Property::SHOW_POPUP: { sliderImpl.SetShowPopup( value.Get< bool >() ); break; } case Toolkit::Slider::Property::SHOW_VALUE: { sliderImpl.SetShowValue( value.Get< bool >() ); break; } case Toolkit::Slider::Property::MARKS: { sliderImpl.SetMarks( value.Get< Property::Array >() ); break; } case Toolkit::Slider::Property::SNAP_TO_MARKS: { sliderImpl.SetSnapToMarks( value.Get< bool >() ); break; } case Toolkit::Slider::Property::MARK_TOLERANCE: { sliderImpl.SetMarkTolerance( value.Get< float >() ); break; } } } } Property::Value Slider::GetProperty( BaseObject* object, Property::Index propertyIndex ) { Property::Value value; Toolkit::Slider slider = Toolkit::Slider::DownCast( Dali::BaseHandle( object ) ); if ( slider ) { Slider& sliderImpl( GetImpl( slider ) ); switch ( propertyIndex ) { case Toolkit::Slider::Property::LOWER_BOUND: { value = sliderImpl.GetLowerBound(); break; } case Toolkit::Slider::Property::UPPER_BOUND: { value = sliderImpl.GetUpperBound(); break; } case Toolkit::Slider::Property::VALUE: { value = sliderImpl.GetValue(); break; } case Toolkit::Slider::Property::TRACK_VISUAL: { if( !sliderImpl.mTrackVisual.empty() ) { value = sliderImpl.GetTrackVisual(); } else if( !sliderImpl.mTrackMap.Empty() ) { value = sliderImpl.mTrackMap; } break; } case Toolkit::Slider::Property::HANDLE_VISUAL: { if( !sliderImpl.mHandleVisual.empty() ) { value = sliderImpl.GetHandleVisual(); } else if( !sliderImpl.mHandleMap.Empty() ) { value = sliderImpl.mHandleMap; } break; } case Toolkit::Slider::Property::PROGRESS_VISUAL: { if( !sliderImpl.mProgressVisual.empty() ) { value = sliderImpl.GetProgressVisual(); } else if( !sliderImpl.mProgressMap.Empty() ) { value = sliderImpl.mProgressMap; } break; } case Toolkit::Slider::Property::POPUP_VISUAL: { if( !sliderImpl.mPopupVisual.empty() ) { value = sliderImpl.GetPopupVisual(); } else if( !sliderImpl.mPopupMap.Empty() ) { value = sliderImpl.mPopupMap; } break; } case Toolkit::Slider::Property::POPUP_ARROW_VISUAL: { if( !sliderImpl.mPopupArrowVisual.empty() ) { value = sliderImpl.GetPopupArrowVisual(); } else if( !sliderImpl.mPopupArrowMap.Empty() ) { value = sliderImpl.mPopupArrowMap; } break; } case Toolkit::Slider::Property::DISABLED_COLOR: { value = sliderImpl.GetDisabledColor(); break; } case Toolkit::Slider::Property::VALUE_PRECISION: { value = sliderImpl.GetValuePrecision(); break; } case Toolkit::Slider::Property::SHOW_POPUP: { value = sliderImpl.GetShowPopup(); break; } case Toolkit::Slider::Property::SHOW_VALUE: { value = sliderImpl.GetShowValue(); break; } case Toolkit::Slider::Property::MARKS: { Property::Value value1( Property::ARRAY ); Property::Array* markArray = value1.GetArray(); if( markArray ) { *markArray = sliderImpl.GetMarks(); } value = value1; break; } case Toolkit::Slider::Property::SNAP_TO_MARKS: { value = sliderImpl.GetSnapToMarks(); break; } case Toolkit::Slider::Property::MARK_TOLERANCE: { value = sliderImpl.GetMarkTolerance(); break; } } } return value; } } // namespace Internal } // namespace Toolkit } // namespace Dali
24.659139
144
0.648904
[ "object" ]
7425a1a4ea870258fb43a881c75ff6ede10ac64b
926
cpp
C++
cpp/66_plusOne.cpp
zzy2008/Leetcode
b75d9fe8b49afe940aa63004671337898a4ce733
[ "MIT" ]
null
null
null
cpp/66_plusOne.cpp
zzy2008/Leetcode
b75d9fe8b49afe940aa63004671337898a4ce733
[ "MIT" ]
null
null
null
cpp/66_plusOne.cpp
zzy2008/Leetcode
b75d9fe8b49afe940aa63004671337898a4ce733
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; vector<int> plusOne(vector<int> &digits) { int n = digits.size(); for (int i = n - 1; i >= 0; i--) { if (digits[i] == 9) digits[i] = 0; else { digits[i] += 1; return digits; } } if (digits.front() == 0) digits.insert(digits.begin(), 1); return digits; } int main() { int a[4] = {1, 2, 3, 4}; int b[5] = {1, 3, 2, 9}; int c[5] = {9, 9, 9, 9}; vector<int> nums1(a, a + 4); vector<int> nums2(b, b + 4); vector<int> nums3(c, c + 4); plusOne(nums1); plusOne(nums2); plusOne(nums3); for (int i = 0; i <= nums1.size() - 1; i++) cout << nums1[i] << " "; cout << endl; for (int i = 0; i <= nums2.size() - 1; i++) cout << nums2[i] << " "; cout << endl; for (int i = 0; i <= nums3.size() - 1; i++) cout << nums3[i] << " "; cout << endl; }
28.060606
72
0.463283
[ "vector" ]
742a6c556df8530ddaff34ea86c43176a59a20f4
1,080
cpp
C++
Codeforces/C++/1560B.cpp
shresth12-jain/HacktoberFest2021
43bd5d99668c104f89f3efef5313e4ddadd9931a
[ "Apache-2.0" ]
11
2021-10-01T06:53:31.000Z
2022-02-05T20:36:20.000Z
Codeforces/C++/1560B.cpp
shresth12-jain/HacktoberFest2021
43bd5d99668c104f89f3efef5313e4ddadd9931a
[ "Apache-2.0" ]
37
2021-10-01T06:54:01.000Z
2021-10-20T18:02:31.000Z
Codeforces/C++/1560B.cpp
shresth12-jain/HacktoberFest2021
43bd5d99668c104f89f3efef5313e4ddadd9931a
[ "Apache-2.0" ]
110
2021-10-01T06:51:28.000Z
2021-10-31T18:00:55.000Z
#include <bits/stdc++.h> #include <iostream> using namespace std; #define all(v) ((v).begin()), ((v).end()) #define sz(v) ((int)((v).size())) #define rep(i, v) for (int i = 0; i < sz(v); ++i) #define lp(i, n) for (int i = 0; i < (int)(n); ++i) #define lpi(i, j, n) for (int i = (j); i < (int)(n); ++i) #define lpi(i, j, n) for (int i = (j); i < (int)(n); ++i) typedef vector<int> vi; typedef long long ll; /*********************************/ int main() { ios_base ::sync_with_stdio(false); cin.tie(NULL); ll t; cin >> t; while (t--) { ll a, b, c; cin >> a >> b >> c; vector<long long int> v; v.emplace_back(a); v.emplace_back(b); v.emplace_back(c); ll temp = *max_element(all(v)); if (abs(a - b) * 2 < temp) { cout << -1 << endl; } else { if (abs(a - b) < c) { cout << c - abs(a - b) << endl; } else cout << c + abs(a - b) << endl; } } return 0; }
22.5
57
0.409259
[ "vector" ]
742b72003f815ea9e9d3b456967963c45d2a64de
22,494
cc
C++
chrome/browser/net/system_network_context_manager_browsertest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/net/system_network_context_manager_browsertest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/net/system_network_context_manager_browsertest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/net/system_network_context_manager.h" #include <string> #include <vector> #include "base/feature_list.h" #include "base/optional.h" #include "base/test/scoped_feature_list.h" #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/net/dns_util.h" #include "chrome/browser/net/stub_resolver_config_reader.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_features.h" #include "chrome/common/pref_names.h" #include "chrome/test/base/in_process_browser_test.h" #include "components/prefs/pref_service.h" #include "components/version_info/version_info.h" #include "content/public/common/user_agent.h" #include "services/network/public/cpp/network_service_buildflags.h" #include "services/network/public/mojom/network_context.mojom.h" #include "services/network/public/mojom/network_service.mojom.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/public/common/features.h" #if BUILDFLAG(BUILTIN_CERT_VERIFIER_FEATURE_SUPPORTED) #include "chrome/browser/policy/policy_test_utils.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/policy_constants.h" #include "net/base/features.h" #endif #if defined(OS_WIN) #include "base/win/win_util.h" #endif namespace { void GetStubResolverConfig( bool force_check_parental_controls_for_automatic_mode, bool* insecure_stub_resolver_enabled, net::DnsConfig::SecureDnsMode* secure_dns_mode, std::vector<net::DnsOverHttpsServerConfig>* dns_over_https_servers) { dns_over_https_servers->clear(); SystemNetworkContextManager::GetStubResolverConfigReader()->GetConfiguration( force_check_parental_controls_for_automatic_mode, insecure_stub_resolver_enabled, secure_dns_mode, dns_over_https_servers); } // Checks that the values returned by GetStubResolverConfigForTesting() match // |async_dns_feature_enabled| (With empty DNS over HTTPS prefs). Then sets // various DoH modes and DoH template strings and makes sure the settings are // respected. void RunStubResolverConfigTests(bool async_dns_feature_enabled) { // Mark as not enterprise managed. #if defined(OS_WIN) base::win::ScopedDomainStateForTesting scoped_domain(false); #endif // Check initial state. bool insecure_stub_resolver_enabled = !async_dns_feature_enabled; net::DnsConfig::SecureDnsMode secure_dns_mode; std::vector<net::DnsOverHttpsServerConfig> dns_over_https_servers; GetStubResolverConfig( false /* force_check_parental_controls_for_automatic_mode */, &insecure_stub_resolver_enabled, &secure_dns_mode, &dns_over_https_servers); EXPECT_EQ(async_dns_feature_enabled, insecure_stub_resolver_enabled); if (base::FeatureList::IsEnabled(features::kDnsOverHttps)) { EXPECT_EQ(net::DnsConfig::SecureDnsMode::AUTOMATIC, secure_dns_mode); } else { EXPECT_EQ(net::DnsConfig::SecureDnsMode::OFF, secure_dns_mode); } EXPECT_TRUE(dns_over_https_servers.empty()); std::string good_post_template = "https://foo.test/"; std::string good_get_template = "https://bar.test/dns-query{?dns}"; std::string bad_template = "dns-query{?dns}"; std::string good_then_bad_template = good_get_template + " " + bad_template; std::string bad_then_good_template = bad_template + " " + good_get_template; std::string multiple_good_templates = " " + good_get_template + " " + good_post_template + " "; PrefService* local_state = g_browser_process->local_state(); local_state->SetString(prefs::kDnsOverHttpsMode, chrome_browser_net::kDnsOverHttpsModeSecure); local_state->SetString(prefs::kDnsOverHttpsTemplates, bad_template); GetStubResolverConfig( false /* force_check_parental_controls_for_automatic_mode */, &insecure_stub_resolver_enabled, &secure_dns_mode, &dns_over_https_servers); EXPECT_EQ(async_dns_feature_enabled, insecure_stub_resolver_enabled); EXPECT_EQ(net::DnsConfig::SecureDnsMode::SECURE, secure_dns_mode); EXPECT_TRUE(dns_over_https_servers.empty()); local_state->SetString(prefs::kDnsOverHttpsTemplates, good_post_template); GetStubResolverConfig( false /* force_check_parental_controls_for_automatic_mode */, &insecure_stub_resolver_enabled, &secure_dns_mode, &dns_over_https_servers); EXPECT_EQ(async_dns_feature_enabled, insecure_stub_resolver_enabled); EXPECT_EQ(net::DnsConfig::SecureDnsMode::SECURE, secure_dns_mode); ASSERT_EQ(1u, dns_over_https_servers.size()); EXPECT_EQ(good_post_template, dns_over_https_servers.at(0).server_template); EXPECT_EQ(true, dns_over_https_servers.at(0).use_post); local_state->SetString(prefs::kDnsOverHttpsMode, chrome_browser_net::kDnsOverHttpsModeAutomatic); local_state->SetString(prefs::kDnsOverHttpsTemplates, bad_template); GetStubResolverConfig( false /* force_check_parental_controls_for_automatic_mode */, &insecure_stub_resolver_enabled, &secure_dns_mode, &dns_over_https_servers); EXPECT_EQ(async_dns_feature_enabled, insecure_stub_resolver_enabled); EXPECT_EQ(net::DnsConfig::SecureDnsMode::AUTOMATIC, secure_dns_mode); EXPECT_TRUE(dns_over_https_servers.empty()); local_state->SetString(prefs::kDnsOverHttpsTemplates, good_then_bad_template); GetStubResolverConfig( false /* force_check_parental_controls_for_automatic_mode */, &insecure_stub_resolver_enabled, &secure_dns_mode, &dns_over_https_servers); EXPECT_EQ(async_dns_feature_enabled, insecure_stub_resolver_enabled); EXPECT_EQ(net::DnsConfig::SecureDnsMode::AUTOMATIC, secure_dns_mode); ASSERT_EQ(1u, dns_over_https_servers.size()); EXPECT_EQ(good_get_template, dns_over_https_servers.at(0).server_template); EXPECT_FALSE(dns_over_https_servers.at(0).use_post); local_state->SetString(prefs::kDnsOverHttpsTemplates, bad_then_good_template); GetStubResolverConfig( false /* force_check_parental_controls_for_automatic_mode */, &insecure_stub_resolver_enabled, &secure_dns_mode, &dns_over_https_servers); EXPECT_EQ(async_dns_feature_enabled, insecure_stub_resolver_enabled); EXPECT_EQ(net::DnsConfig::SecureDnsMode::AUTOMATIC, secure_dns_mode); ASSERT_EQ(1u, dns_over_https_servers.size()); EXPECT_EQ(good_get_template, dns_over_https_servers.at(0).server_template); EXPECT_FALSE(dns_over_https_servers.at(0).use_post); local_state->SetString(prefs::kDnsOverHttpsTemplates, multiple_good_templates); GetStubResolverConfig( false /* force_check_parental_controls_for_automatic_mode */, &insecure_stub_resolver_enabled, &secure_dns_mode, &dns_over_https_servers); EXPECT_EQ(async_dns_feature_enabled, insecure_stub_resolver_enabled); EXPECT_EQ(net::DnsConfig::SecureDnsMode::AUTOMATIC, secure_dns_mode); ASSERT_EQ(2u, dns_over_https_servers.size()); EXPECT_EQ(good_get_template, dns_over_https_servers.at(0).server_template); EXPECT_FALSE(dns_over_https_servers.at(0).use_post); EXPECT_EQ(good_post_template, dns_over_https_servers.at(1).server_template); EXPECT_TRUE(dns_over_https_servers.at(1).use_post); local_state->SetString(prefs::kDnsOverHttpsMode, chrome_browser_net::kDnsOverHttpsModeOff); local_state->SetString(prefs::kDnsOverHttpsTemplates, good_get_template); GetStubResolverConfig( false /* force_check_parental_controls_for_automatic_mode */, &insecure_stub_resolver_enabled, &secure_dns_mode, &dns_over_https_servers); EXPECT_EQ(async_dns_feature_enabled, insecure_stub_resolver_enabled); EXPECT_EQ(net::DnsConfig::SecureDnsMode::OFF, secure_dns_mode); EXPECT_TRUE(dns_over_https_servers.empty()); local_state->SetString(prefs::kDnsOverHttpsMode, "no_match"); GetStubResolverConfig( false /* force_check_parental_controls_for_automatic_mode */, &insecure_stub_resolver_enabled, &secure_dns_mode, &dns_over_https_servers); EXPECT_EQ(async_dns_feature_enabled, insecure_stub_resolver_enabled); EXPECT_EQ(net::DnsConfig::SecureDnsMode::OFF, secure_dns_mode); EXPECT_TRUE(dns_over_https_servers.empty()); // Test case with policy BuiltInDnsClientEnabled enabled. The DoH fields // should be unaffected. local_state->Set(prefs::kBuiltInDnsClientEnabled, base::Value(!async_dns_feature_enabled)); GetStubResolverConfig( false /* force_check_parental_controls_for_automatic_mode */, &insecure_stub_resolver_enabled, &secure_dns_mode, &dns_over_https_servers); EXPECT_EQ(!async_dns_feature_enabled, insecure_stub_resolver_enabled); EXPECT_EQ(net::DnsConfig::SecureDnsMode::OFF, secure_dns_mode); EXPECT_TRUE(dns_over_https_servers.empty()); } } // namespace using SystemNetworkContextManagerBrowsertest = InProcessBrowserTest; IN_PROC_BROWSER_TEST_F(SystemNetworkContextManagerBrowsertest, StubResolverDefaultConfig) { RunStubResolverConfigTests(base::FeatureList::IsEnabled(features::kAsyncDns)); } IN_PROC_BROWSER_TEST_F(SystemNetworkContextManagerBrowsertest, StaticAuthParams) { // Test defaults. network::mojom::HttpAuthStaticParamsPtr static_params = SystemNetworkContextManager::GetHttpAuthStaticParamsForTesting(); EXPECT_THAT(static_params->supported_schemes, testing::ElementsAre("basic", "digest", "ntlm", "negotiate")); EXPECT_EQ("", static_params->gssapi_library_name); // Test that prefs are reflected in params. PrefService* local_state = g_browser_process->local_state(); local_state->SetString(prefs::kAuthSchemes, "basic"); static_params = SystemNetworkContextManager::GetHttpAuthStaticParamsForTesting(); EXPECT_THAT(static_params->supported_schemes, testing::ElementsAre("basic")); #if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_CHROMEOS) const char dev_null[] = "/dev/null"; local_state->SetString(prefs::kGSSAPILibraryName, dev_null); static_params = SystemNetworkContextManager::GetHttpAuthStaticParamsForTesting(); EXPECT_EQ(dev_null, static_params->gssapi_library_name); #endif } IN_PROC_BROWSER_TEST_F(SystemNetworkContextManagerBrowsertest, AuthParams) { // Test defaults. network::mojom::HttpAuthDynamicParamsPtr dynamic_params = SystemNetworkContextManager::GetHttpAuthDynamicParamsForTesting(); EXPECT_EQ(false, dynamic_params->negotiate_disable_cname_lookup); EXPECT_EQ(false, dynamic_params->enable_negotiate_port); EXPECT_EQ("", dynamic_params->server_allowlist); EXPECT_EQ("", dynamic_params->delegate_allowlist); EXPECT_FALSE(dynamic_params->delegate_by_kdc_policy); PrefService* local_state = g_browser_process->local_state(); local_state->SetBoolean(prefs::kDisableAuthNegotiateCnameLookup, true); dynamic_params = SystemNetworkContextManager::GetHttpAuthDynamicParamsForTesting(); EXPECT_EQ(true, dynamic_params->negotiate_disable_cname_lookup); EXPECT_EQ(false, dynamic_params->enable_negotiate_port); EXPECT_EQ("", dynamic_params->server_allowlist); EXPECT_EQ("", dynamic_params->delegate_allowlist); EXPECT_FALSE(dynamic_params->delegate_by_kdc_policy); local_state->SetBoolean(prefs::kEnableAuthNegotiatePort, true); dynamic_params = SystemNetworkContextManager::GetHttpAuthDynamicParamsForTesting(); EXPECT_EQ(true, dynamic_params->negotiate_disable_cname_lookup); EXPECT_EQ(true, dynamic_params->enable_negotiate_port); EXPECT_EQ("", dynamic_params->server_allowlist); EXPECT_EQ("", dynamic_params->delegate_allowlist); EXPECT_FALSE(dynamic_params->delegate_by_kdc_policy); const char kServerAllowList[] = "foo"; local_state->SetString(prefs::kAuthServerWhitelist, kServerAllowList); dynamic_params = SystemNetworkContextManager::GetHttpAuthDynamicParamsForTesting(); EXPECT_EQ(true, dynamic_params->negotiate_disable_cname_lookup); EXPECT_EQ(true, dynamic_params->enable_negotiate_port); EXPECT_EQ(kServerAllowList, dynamic_params->server_allowlist); EXPECT_EQ("", dynamic_params->delegate_allowlist); const char kDelegateAllowList[] = "bar, baz"; local_state->SetString(prefs::kAuthNegotiateDelegateWhitelist, kDelegateAllowList); dynamic_params = SystemNetworkContextManager::GetHttpAuthDynamicParamsForTesting(); EXPECT_EQ(true, dynamic_params->negotiate_disable_cname_lookup); EXPECT_EQ(true, dynamic_params->enable_negotiate_port); EXPECT_EQ(kServerAllowList, dynamic_params->server_allowlist); EXPECT_EQ(kDelegateAllowList, dynamic_params->delegate_allowlist); EXPECT_FALSE(dynamic_params->delegate_by_kdc_policy); #if defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_CHROMEOS) local_state->SetBoolean(prefs::kAuthNegotiateDelegateByKdcPolicy, true); dynamic_params = SystemNetworkContextManager::GetHttpAuthDynamicParamsForTesting(); EXPECT_EQ(true, dynamic_params->negotiate_disable_cname_lookup); EXPECT_EQ(true, dynamic_params->enable_negotiate_port); EXPECT_EQ(kServerAllowList, dynamic_params->server_allowlist); EXPECT_EQ(kDelegateAllowList, dynamic_params->delegate_allowlist); EXPECT_TRUE(dynamic_params->delegate_by_kdc_policy); #endif // defined(OS_LINUX) || defined(OS_MACOSX) || defined(OS_CHROMEOS) #if defined(OS_CHROMEOS) // The kerberos.enabled pref is false and the device is not Active Directory // managed by default. EXPECT_EQ(false, dynamic_params->allow_gssapi_library_load); local_state->SetBoolean(prefs::kKerberosEnabled, true); dynamic_params = SystemNetworkContextManager::GetHttpAuthDynamicParamsForTesting(); EXPECT_EQ(true, dynamic_params->allow_gssapi_library_load); #endif // defined(OS_CHROMEOS) } class SystemNetworkContextManagerStubResolverBrowsertest : public SystemNetworkContextManagerBrowsertest, public testing::WithParamInterface<bool> { public: SystemNetworkContextManagerStubResolverBrowsertest() { scoped_feature_list_.InitWithFeatureState(features::kAsyncDns, GetParam()); } ~SystemNetworkContextManagerStubResolverBrowsertest() override {} void SetUpOnMainThread() override {} private: base::test::ScopedFeatureList scoped_feature_list_; }; IN_PROC_BROWSER_TEST_P(SystemNetworkContextManagerStubResolverBrowsertest, StubResolverConfig) { RunStubResolverConfigTests(GetParam()); } INSTANTIATE_TEST_SUITE_P(All, SystemNetworkContextManagerStubResolverBrowsertest, ::testing::Bool()); class SystemNetworkContextManagerReferrersFeatureBrowsertest : public SystemNetworkContextManagerBrowsertest, public testing::WithParamInterface<bool> { public: SystemNetworkContextManagerReferrersFeatureBrowsertest() { scoped_feature_list_.InitWithFeatureState(features::kNoReferrers, GetParam()); } ~SystemNetworkContextManagerReferrersFeatureBrowsertest() override {} void SetUpOnMainThread() override {} private: base::test::ScopedFeatureList scoped_feature_list_; }; // Tests that toggling the kNoReferrers feature correctly changes the default // value of the kEnableReferrers pref. IN_PROC_BROWSER_TEST_P(SystemNetworkContextManagerReferrersFeatureBrowsertest, TestDefaultReferrerReflectsFeatureValue) { ASSERT_TRUE(!!g_browser_process); PrefService* local_state = g_browser_process->local_state(); ASSERT_TRUE(!!local_state); EXPECT_NE(local_state->GetBoolean(prefs::kEnableReferrers), GetParam()); } INSTANTIATE_TEST_SUITE_P(All, SystemNetworkContextManagerReferrersFeatureBrowsertest, ::testing::Bool()); class SystemNetworkContextManagerFreezeQUICUaBrowsertest : public SystemNetworkContextManagerBrowsertest, public testing::WithParamInterface<bool> { public: SystemNetworkContextManagerFreezeQUICUaBrowsertest() { scoped_feature_list_.InitWithFeatureState(blink::features::kFreezeUserAgent, GetParam()); } ~SystemNetworkContextManagerFreezeQUICUaBrowsertest() override {} void SetUpOnMainThread() override {} private: base::test::ScopedFeatureList scoped_feature_list_; }; bool ContainsSubstring(std::string super, std::string sub) { return super.find(sub) != std::string::npos; } IN_PROC_BROWSER_TEST_P(SystemNetworkContextManagerFreezeQUICUaBrowsertest, QUICUaConfig) { network::mojom::NetworkContextParamsPtr network_context_params = g_browser_process->system_network_context_manager() ->CreateDefaultNetworkContextParams(); std::string quic_ua = network_context_params->quic_user_agent_id; if (GetParam()) { // if the UA Freeze feature is turned on EXPECT_EQ("", quic_ua); } else { EXPECT_TRUE(ContainsSubstring(quic_ua, chrome::GetChannelName())); EXPECT_TRUE(ContainsSubstring( quic_ua, version_info::GetProductNameAndVersionForUserAgent())); EXPECT_TRUE(ContainsSubstring(quic_ua, content::BuildOSCpuInfo(false))); } } INSTANTIATE_TEST_SUITE_P(All, SystemNetworkContextManagerFreezeQUICUaBrowsertest, ::testing::Bool()); class SystemNetworkContextManagerWPADQuickCheckBrowsertest : public SystemNetworkContextManagerBrowsertest, public testing::WithParamInterface<bool> { public: SystemNetworkContextManagerWPADQuickCheckBrowsertest() = default; ~SystemNetworkContextManagerWPADQuickCheckBrowsertest() override = default; }; IN_PROC_BROWSER_TEST_P(SystemNetworkContextManagerWPADQuickCheckBrowsertest, WPADQuickCheckPref) { PrefService* local_state = g_browser_process->local_state(); local_state->SetBoolean(prefs::kQuickCheckEnabled, GetParam()); network::mojom::NetworkContextParamsPtr network_context_params = g_browser_process->system_network_context_manager() ->CreateDefaultNetworkContextParams(); EXPECT_EQ(GetParam(), network_context_params->pac_quick_check_enabled); } INSTANTIATE_TEST_SUITE_P(All, SystemNetworkContextManagerWPADQuickCheckBrowsertest, ::testing::Bool()); class SystemNetworkContextManagerCertificateTransparencyBrowsertest : public SystemNetworkContextManagerBrowsertest, public testing::WithParamInterface<base::Optional<bool>> { public: SystemNetworkContextManagerCertificateTransparencyBrowsertest() { SystemNetworkContextManager::SetEnableCertificateTransparencyForTesting( GetParam()); } ~SystemNetworkContextManagerCertificateTransparencyBrowsertest() override { SystemNetworkContextManager::SetEnableCertificateTransparencyForTesting( base::nullopt); } }; #if BUILDFLAG(IS_CT_SUPPORTED) IN_PROC_BROWSER_TEST_P( SystemNetworkContextManagerCertificateTransparencyBrowsertest, CertificateTransparencyConfig) { network::mojom::NetworkContextParamsPtr context_params = g_browser_process->system_network_context_manager() ->CreateDefaultNetworkContextParams(); const bool kDefault = #if BUILDFLAG(GOOGLE_CHROME_BRANDING) && defined(OFFICIAL_BUILD) && \ !defined(OS_ANDROID) true; #else false; #endif EXPECT_EQ(GetParam().value_or(kDefault), context_params->enforce_chrome_ct_policy); EXPECT_NE(GetParam().value_or(kDefault), context_params->ct_logs.empty()); if (GetParam().value_or(kDefault)) { bool has_google_log = false; bool has_disqualified_log = false; for (const auto& ct_log : context_params->ct_logs) { has_google_log |= ct_log->operated_by_google; has_disqualified_log |= ct_log->disqualified_at.has_value(); } EXPECT_TRUE(has_google_log); EXPECT_TRUE(has_disqualified_log); } } #endif INSTANTIATE_TEST_SUITE_P( All, SystemNetworkContextManagerCertificateTransparencyBrowsertest, ::testing::Values(base::nullopt, true, false)); #if BUILDFLAG(BUILTIN_CERT_VERIFIER_FEATURE_SUPPORTED) class SystemNetworkContextServiceCertVerifierBuiltinFeaturePolicyTest : public policy::PolicyTest, public testing::WithParamInterface<bool> { public: void SetUpInProcessBrowserTestFixture() override { scoped_feature_list_.InitWithFeatureState( net::features::kCertVerifierBuiltinFeature, /*enabled=*/GetParam()); policy::PolicyTest::SetUpInProcessBrowserTestFixture(); } private: base::test::ScopedFeatureList scoped_feature_list_; }; IN_PROC_BROWSER_TEST_P( SystemNetworkContextServiceCertVerifierBuiltinFeaturePolicyTest, Test) { // If no BuiltinCertificateVerifierEnabled policy is set, the // use_builtin_cert_verifier param should be set from the feature flag. EXPECT_EQ( GetParam() ? network::mojom::NetworkContextParams::CertVerifierImpl::kBuiltin : network::mojom::NetworkContextParams::CertVerifierImpl::kSystem, g_browser_process->system_network_context_manager() ->CreateDefaultNetworkContextParams() ->use_builtin_cert_verifier); #if BUILDFLAG(BUILTIN_CERT_VERIFIER_POLICY_SUPPORTED) // If the BuiltinCertificateVerifierEnabled policy is set it should override // the feature flag. policy::PolicyMap policies; SetPolicy(&policies, policy::key::kBuiltinCertificateVerifierEnabled, std::make_unique<base::Value>(true)); UpdateProviderPolicy(policies); EXPECT_EQ(network::mojom::NetworkContextParams::CertVerifierImpl::kBuiltin, g_browser_process->system_network_context_manager() ->CreateDefaultNetworkContextParams() ->use_builtin_cert_verifier); SetPolicy(&policies, policy::key::kBuiltinCertificateVerifierEnabled, std::make_unique<base::Value>(false)); UpdateProviderPolicy(policies); EXPECT_EQ(network::mojom::NetworkContextParams::CertVerifierImpl::kSystem, g_browser_process->system_network_context_manager() ->CreateDefaultNetworkContextParams() ->use_builtin_cert_verifier); #endif // BUILDFLAG(BUILTIN_CERT_VERIFIER_POLICY_SUPPORTED) } INSTANTIATE_TEST_SUITE_P( All, SystemNetworkContextServiceCertVerifierBuiltinFeaturePolicyTest, ::testing::Bool()); #endif // BUILDFLAG(BUILTIN_CERT_VERIFIER_FEATURE_SUPPORTED)
42.683112
80
0.777585
[ "vector" ]
743560c07a87597cd243754b73cb2640bb86c4d6
4,398
cpp
C++
openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateGasEquipment.cpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateGasEquipment.cpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateGasEquipment.cpp
zhouchong90/OpenStudio
f8570cb8297547b5e9cc80fde539240d8f7b9c24
[ "BSL-1.0", "blessing" ]
null
null
null
/********************************************************************** * Copyright (c) 2008-2014, Alliance for Sustainable Energy. * All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********************************************************************/ #include "../ForwardTranslator.hpp" #include "../../model/Model.hpp" #include "../../model/GasEquipment.hpp" #include "../../model/GasEquipment_Impl.hpp" #include "../../model/GasEquipmentDefinition.hpp" #include "../../model/GasEquipmentDefinition_Impl.hpp" #include "../../model/Space.hpp" #include "../../model/Space_Impl.hpp" #include "../../model/SpaceType.hpp" #include "../../model/SpaceType_Impl.hpp" #include "../../model/ThermalZone.hpp" #include "../../model/ThermalZone_Impl.hpp" #include "../../model/Schedule.hpp" #include "../../model/Schedule_Impl.hpp" #include "../../model/LifeCycleCost.hpp" #include <utilities/idd/GasEquipment_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> using namespace openstudio::model; using namespace std; namespace openstudio { namespace energyplus { boost::optional<IdfObject> ForwardTranslator::translateGasEquipment( GasEquipment& modelObject ) { IdfObject idfObject(openstudio::IddObjectType::GasEquipment); m_idfObjects.push_back(idfObject); for (LifeCycleCost lifeCycleCost : modelObject.lifeCycleCosts()){ translateAndMapModelObject(lifeCycleCost); } GasEquipmentDefinition definition = modelObject.gasEquipmentDefinition(); idfObject.setString(GasEquipmentFields::Name, modelObject.name().get()); boost::optional<Space> space = modelObject.space(); boost::optional<SpaceType> spaceType = modelObject.spaceType(); if (space){ boost::optional<ThermalZone> thermalZone = space->thermalZone(); if (thermalZone){ idfObject.setString(GasEquipmentFields::ZoneorZoneListName, thermalZone->name().get()); } }else if(spaceType){ idfObject.setString(GasEquipmentFields::ZoneorZoneListName, spaceType->name().get()); } boost::optional<Schedule> schedule = modelObject.schedule(); if (schedule){ idfObject.setString(GasEquipmentFields::ScheduleName, schedule->name().get()); } idfObject.setString(GasEquipmentFields::DesignLevelCalculationMethod, definition.designLevelCalculationMethod()); double multiplier = modelObject.multiplier(); OptionalDouble d = definition.designLevel(); if (d){ idfObject.setDouble(GasEquipmentFields::DesignLevel, (*d)*multiplier); } d = definition.wattsperSpaceFloorArea(); if (d){ idfObject.setDouble(GasEquipmentFields::PowerperZoneFloorArea, (*d)*multiplier); } d = definition.wattsperPerson(); if (d){ idfObject.setDouble(GasEquipmentFields::PowerperPerson, (*d)*multiplier); } if (!definition.isFractionLatentDefaulted()){ idfObject.setDouble(GasEquipmentFields::FractionLatent, definition.fractionLatent()); } if (!definition.isFractionRadiantDefaulted()){ idfObject.setDouble(GasEquipmentFields::FractionRadiant, definition.fractionRadiant()); } if (!definition.isFractionLostDefaulted()){ idfObject.setDouble(GasEquipmentFields::FractionLost, definition.fractionLost()); } if (!definition.isCarbonDioxideGenerationRateDefaulted()){ idfObject.setDouble(GasEquipmentFields::CarbonDioxideGenerationRate, definition.carbonDioxideGenerationRate()); } if (!modelObject.isEndUseSubcategoryDefaulted()){ idfObject.setString(GasEquipmentFields::EndUseSubcategory, modelObject.endUseSubcategory()); } return idfObject; } } // energyplus } // openstudio
35.756098
116
0.702592
[ "model" ]
7435b0419b48ca0f1893a4dd8f6de4b9067ba8c9
614
cpp
C++
liquid.cpp
fransvanbuul/the_cube
eb2790340a84a4d95b3554c647c3f48dc9394de0
[ "Unlicense" ]
null
null
null
liquid.cpp
fransvanbuul/the_cube
eb2790340a84a4d95b3554c647c3f48dc9394de0
[ "Unlicense" ]
null
null
null
liquid.cpp
fransvanbuul/the_cube
eb2790340a84a4d95b3554c647c3f48dc9394de0
[ "Unlicense" ]
null
null
null
#include "cube_shared.h" void liquid_loop() { int analog_in = analogRead(7); mpu6050.update(); Vector acc = Vector(0x40*mpu6050.getAccX(), -0x40*mpu6050.getAccY(), 0x40*mpu6050.getAccZ()); int16_t c = Vector(1, 1, 1) * acc + ((analog_in - 512)/5); for(int8_t z = 0; z < 3; z++) { for(int8_t y = 0; y < 3; y++) { for(int8_t x = 0; x < 3; x++) { Vector p = Vector(x, y, z); int16_t d = p * acc - c; if(d < -32) { p.pset(0xFF); } else if(d >= 32) { p.pset(0); } else { p.pset(0xFF - 4*(d + 32)); } } } } }
25.583333
95
0.470684
[ "vector" ]
7436f21f135b76a561fbfd7a9d4fa2b61c271999
36,233
cc
C++
src/ui/scenic/lib/input/input_system.cc
EnderNightLord-ChromeBook/fuchsia-pine64-pinephone
05e2c059b57b6217089090a0315971d1735ecf57
[ "BSD-3-Clause" ]
14
2020-10-25T05:48:36.000Z
2021-09-20T02:46:20.000Z
src/ui/scenic/lib/input/input_system.cc
JokeZhang/fuchsia
d6e9dea8dca7a1c8fa89d03e131367e284b30d23
[ "BSD-3-Clause" ]
null
null
null
src/ui/scenic/lib/input/input_system.cc
JokeZhang/fuchsia
d6e9dea8dca7a1c8fa89d03e131367e284b30d23
[ "BSD-3-Clause" ]
2
2020-10-25T01:13:49.000Z
2020-10-26T02:32:13.000Z
// Copyright 2018 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 "src/ui/scenic/lib/input/input_system.h" #include <fuchsia/ui/input/cpp/fidl.h> #include <fuchsia/ui/scenic/cpp/fidl.h> #include <lib/fostr/fidl/fuchsia/ui/input/formatting.h> #include <lib/syslog/cpp/macros.h> #include <zircon/status.h> #include "src/ui/lib/glm_workaround/glm_workaround.h" #include "src/ui/scenic/lib/gfx/resources/compositor/layer.h" #include "src/ui/scenic/lib/gfx/resources/compositor/layer_stack.h" #include "src/ui/scenic/lib/input/helper.h" #include "src/ui/scenic/lib/input/internal_pointer_event.h" #include "src/ui/scenic/lib/utils/helpers.h" namespace scenic_impl { namespace input { using AccessibilityPointerEvent = fuchsia::ui::input::accessibility::PointerEvent; using FocusChangeStatus = scenic_impl::gfx::ViewTree::FocusChangeStatus; using fuchsia::ui::input::InputEvent; using fuchsia::ui::input::PointerEvent; using fuchsia::ui::input::PointerEventType; namespace { uint64_t NextTraceId() { static uint64_t next_trace_id = 1; return next_trace_id++; } // Creates a hit ray at z = -1000, pointing in the z-direction. escher::ray4 CreateZRay(glm::vec2 coords) { return { // Origin as homogeneous point. .origin = {coords.x, coords.y, -1000, 1}, .direction = {0, 0, 1, 0}, }; } bool IsOutsideViewport(const Viewport& viewport, const glm::vec2& position_in_viewport) { FX_DCHECK(!std::isunordered(position_in_viewport.x, viewport.extents.min.x) && !std::isunordered(position_in_viewport.x, viewport.extents.max.x) && !std::isunordered(position_in_viewport.y, viewport.extents.min.y) && !std::isunordered(position_in_viewport.y, viewport.extents.max.y)); return position_in_viewport.x < viewport.extents.min.x || position_in_viewport.y < viewport.extents.min.y || position_in_viewport.x > viewport.extents.max.x || position_in_viewport.y > viewport.extents.max.y; } // Helper function to build an AccessibilityPointerEvent when there is a // registered accessibility listener. AccessibilityPointerEvent BuildAccessibilityPointerEvent(const InternalPointerEvent& internal_event, const glm::vec2& ndc_point, const glm::vec2& local_point, uint64_t viewref_koid) { AccessibilityPointerEvent event; event.set_event_time(internal_event.timestamp); event.set_device_id(internal_event.device_id); event.set_pointer_id(internal_event.pointer_id); event.set_type(fuchsia::ui::input::PointerEventType::TOUCH); event.set_phase(InternalPhaseToGfxPhase(internal_event.phase)); event.set_ndc_point({ndc_point.x, ndc_point.y}); event.set_viewref_koid(viewref_koid); if (viewref_koid != ZX_KOID_INVALID) { event.set_local_point({local_point.x, local_point.y}); } return event; } bool IsDescendantAndConnected(const gfx::ViewTree& view_tree, zx_koid_t descendant_koid, zx_koid_t ancestor_koid) { if (!view_tree.IsTracked(descendant_koid) || !view_tree.IsTracked(ancestor_koid)) return false; return view_tree.IsDescendant(descendant_koid, ancestor_koid) && view_tree.IsConnectedToScene(ancestor_koid); } std::optional<glm::mat4> GetWorldFromViewTransform(zx_koid_t view_ref_koid, const gfx::ViewTree& view_tree) { return view_tree.GlobalTransformOf(view_ref_koid); } std::optional<glm::mat4> GetViewFromWorldTransform(zx_koid_t view_ref_koid, const gfx::ViewTree& view_tree) { const auto world_from_view_transform = GetWorldFromViewTransform(view_ref_koid, view_tree); if (!world_from_view_transform) return std::nullopt; const glm::mat4 view_from_world_transform = glm::inverse(world_from_view_transform.value()); return view_from_world_transform; } std::optional<glm::mat4> GetDestinationViewFromSourceViewTransform(zx_koid_t source, zx_koid_t destination, const gfx::ViewTree& view_tree) { std::optional<glm::mat4> world_from_source_transform = GetWorldFromViewTransform(source, view_tree); if (!world_from_source_transform) return std::nullopt; std::optional<glm::mat4> destination_from_world_transform = GetViewFromWorldTransform(destination, view_tree); if (!destination_from_world_transform) return std::nullopt; return destination_from_world_transform.value() * world_from_source_transform.value(); } escher::ray4 CreateWorldSpaceRay(const InternalPointerEvent& event, const gfx::ViewTree& view_tree) { const std::optional<glm::mat4> world_from_context_transform = GetWorldFromViewTransform(event.context, view_tree); FX_DCHECK(world_from_context_transform) << "Failed to create world space ray. Either the |event.context| ViewRef is invalid, we're " "out of sync with the ViewTree, or the ViewTree callback returned std::nullopt."; const glm::mat4 world_from_viewport_transform = world_from_context_transform.value() * event.viewport.context_from_viewport_transform; const escher::ray4 viewport_space_ray = CreateZRay(event.position_in_viewport); return world_from_viewport_transform * viewport_space_ray; } // Takes an InternalPointerEvent and returns a point in (Vulkan) Normalized Device Coordinates, // in relation to the viewport. Intended for magnification // TODO(fxbug.dev/50549): Only here to allow the legacy a11y flow. Remove along with the legacy a11y // code. glm::vec2 GetViewportNDCPoint(const InternalPointerEvent& internal_event) { const float width = internal_event.viewport.extents.max.x - internal_event.viewport.extents.min.x; const float height = internal_event.viewport.extents.max.y - internal_event.viewport.extents.min.y; return { width > 0 ? 2.f * internal_event.position_in_viewport.x / width - 1 : 0, height > 0 ? 2.f * internal_event.position_in_viewport.y / height - 1 : 0, }; } } // namespace const char* InputSystem::kName = "InputSystem"; InputSystem::InputSystem(SystemContext context, fxl::WeakPtr<gfx::SceneGraph> scene_graph) : System(std::move(context)), scene_graph_(scene_graph) { FX_CHECK(scene_graph); pointer_event_registry_ = std::make_unique<A11yPointerEventRegistry>( this->context(), /*on_register=*/ [this] { FX_CHECK(!pointer_event_buffer_) << "on_disconnect must be called before registering a new listener"; // In case a11y is turned on mid execution make sure to send active pointer event streams to // their final location and do not send them to the a11y listener. pointer_event_buffer_ = std::make_unique<PointerEventBuffer>( /* DispatchEventFunction */ [this](PointerEventBuffer::DeferredPointerEvent views_and_event) { DispatchDeferredPointerEvent(std::move(views_and_event)); }, /* ReportAccessibilityEventFunction */ [this](fuchsia::ui::input::accessibility::PointerEvent pointer) { accessibility_pointer_event_listener()->OnEvent(std::move(pointer)); }); FX_LOGS(INFO) << "PointerEventBuffer created"; for (const auto& kv : touch_targets_) { // Force a reject in all active pointer IDs. When a new stream arrives, // they will automatically be sent for the a11y listener decide // what to do with them as the status will change to WAITING_RESPONSE. pointer_event_buffer_->SetActiveStreamInfo( /*pointer_id=*/kv.first, PointerEventBuffer::PointerIdStreamStatus::REJECTED); } // Registers an event handler for this listener. This callback captures a pointer to the // event buffer that we own, so we need to clear it before we destroy it (see below). accessibility_pointer_event_listener().events().OnStreamHandled = [buffer = pointer_event_buffer_.get()]( uint32_t device_id, uint32_t pointer_id, fuchsia::ui::input::accessibility::EventHandling handled) { buffer->UpdateStream(pointer_id, handled); }; }, /*on_disconnect=*/ [this] { FX_CHECK(pointer_event_buffer_) << "can not disconnect before registering"; // The listener disconnected. Release held events, delete the buffer. accessibility_pointer_event_listener().events().OnStreamHandled = nullptr; pointer_event_buffer_.reset(); FX_LOGS(INFO) << "PointerEventBuffer destroyed"; }); ime_service_ = this->context()->app_context()->svc()->Connect<fuchsia::ui::input::ImeService>(); ime_service_.set_error_handler( [](zx_status_t status) { FX_LOGS(WARNING) << "Scenic lost connection to TextSync"; }); this->context()->app_context()->outgoing()->AddPublicService(injector_registry_.GetHandler(this)); this->context()->app_context()->outgoing()->AddPublicService( pointer_capture_registry_.GetHandler(this)); FX_LOGS(INFO) << "Scenic input system initialized."; } CommandDispatcherUniquePtr InputSystem::CreateCommandDispatcher( scheduling::SessionId session_id, std::shared_ptr<EventReporter> event_reporter, std::shared_ptr<ErrorReporter> error_reporter) { return CommandDispatcherUniquePtr( new InputCommandDispatcher(session_id, std::move(event_reporter), scene_graph_, this), // Custom deleter. [](CommandDispatcher* cd) { delete cd; }); } A11yPointerEventRegistry::A11yPointerEventRegistry(SystemContext* context, fit::function<void()> on_register, fit::function<void()> on_disconnect) : on_register_(std::move(on_register)), on_disconnect_(std::move(on_disconnect)) { FX_DCHECK(on_register_); FX_DCHECK(on_disconnect_); context->app_context()->outgoing()->AddPublicService( accessibility_pointer_event_registry_.GetHandler(this)); } void A11yPointerEventRegistry::Register( fidl::InterfaceHandle<fuchsia::ui::input::accessibility::PointerEventListener> pointer_event_listener, RegisterCallback callback) { if (!accessibility_pointer_event_listener()) { accessibility_pointer_event_listener_.Bind(std::move(pointer_event_listener)); accessibility_pointer_event_listener_.set_error_handler( [this](zx_status_t) { on_disconnect_(); }); on_register_(); callback(/*success=*/true); } else { // An accessibility listener is already registered. callback(/*success=*/false); } } void InputSystem::Register(fuchsia::ui::pointerinjector::Config config, fidl::InterfaceRequest<fuchsia::ui::pointerinjector::Device> injector, RegisterCallback callback) { if (!Injector::IsValidConfig(config)) { // Errors printed inside IsValidConfig. Just return here. return; } // Check connectivity here, since injector doesn't have access to it. const zx_koid_t context_koid = utils::ExtractKoid(config.context().view()); const zx_koid_t target_koid = utils::ExtractKoid(config.target().view()); if (context_koid == ZX_KOID_INVALID || target_koid == ZX_KOID_INVALID) { FX_LOGS(ERROR) << "InjectorRegistry::Register : Argument |config.context| or |config.target| " "was invalid."; return; } if (!IsDescendantAndConnected(scene_graph_->view_tree(), target_koid, context_koid)) { FX_LOGS(ERROR) << "InjectorRegistry::Register : Argument |config.context| must be connected to " "the Scene, and |config.target| must be a descendant of |config.context|"; return; } // TODO(fxbug.dev/50348): Add a callback to kill the channel immediately if connectivity breaks. const InjectorId id = ++last_injector_id_; InjectorSettings settings{.dispatch_policy = config.dispatch_policy(), .device_id = config.device_id(), .device_type = config.device_type(), .context_koid = context_koid, .target_koid = target_koid}; Viewport viewport{ .extents = {config.viewport().extents()}, .context_from_viewport_transform = ColumnMajorMat3VectorToMat4(config.viewport().viewport_to_context_transform()), }; fit::function<void(const InternalPointerEvent&, StreamId)> inject_func; switch (settings.dispatch_policy) { case fuchsia::ui::pointerinjector::DispatchPolicy::EXCLUSIVE_TARGET: inject_func = [this](const InternalPointerEvent& event, StreamId stream_id) { InjectTouchEventExclusive(event); }; break; case fuchsia::ui::pointerinjector::DispatchPolicy::TOP_HIT_AND_ANCESTORS_IN_TARGET: inject_func = [this](const InternalPointerEvent& event, StreamId stream_id) { InjectTouchEventHitTested(event, stream_id, /*parallel_dispatch*/ false); }; break; default: FX_CHECK(false) << "Should never be reached."; break; } const auto [it, success] = injectors_.try_emplace( id, std::move(settings), std::move(viewport), std::move(injector), /*is_descendant_and_connected*/ [this](zx_koid_t descendant, zx_koid_t ancestor) { return IsDescendantAndConnected(scene_graph_->view_tree(), descendant, ancestor); }, std::move(inject_func)); FX_CHECK(success) << "Injector already exists."; // Remove the injector if the channel has an error. injectors_.at(id).SetErrorHandler([this, id](zx_status_t status) { injectors_.erase(id); }); callback(); } void InputSystem::RegisterListener( fidl::InterfaceHandle<fuchsia::ui::input::PointerCaptureListener> listener_handle, fuchsia::ui::views::ViewRef view_ref, RegisterListenerCallback success_callback) { if (pointer_capture_listener_) { // Already have a listener, decline registration. success_callback(false); return; } fuchsia::ui::input::PointerCaptureListenerPtr new_listener; new_listener.Bind(std::move(listener_handle)); // Remove listener if the interface closes. new_listener.set_error_handler([this](zx_status_t status) { FX_LOGS(ERROR) << "Pointer capture listener interface closed with error: " << zx_status_get_string(status); pointer_capture_listener_ = std::nullopt; }); pointer_capture_listener_ = PointerCaptureListener{.listener_ptr = std::move(new_listener), .view_ref = std::move(view_ref)}; success_callback(true); } void InputSystem::HitTest(const gfx::ViewTree& view_tree, const InternalPointerEvent& event, gfx::HitAccumulator<gfx::ViewHit>& accumulator, bool semantic_hit_test) const { if (IsOutsideViewport(event.viewport, event.position_in_viewport)) { return; } escher::ray4 world_ray = CreateWorldSpaceRay(event, view_tree); view_tree.HitTestFrom(event.target, world_ray, &accumulator, semantic_hit_test); } void InputSystem::DispatchPointerCommand(const fuchsia::ui::input::SendPointerInputCmd& command, scheduling::SessionId session_id, bool parallel_dispatch) { TRACE_DURATION("input", "dispatch_command", "command", "PointerCmd"); if (command.pointer_event.phase == fuchsia::ui::input::PointerEventPhase::HOVER) { FX_LOGS(WARNING) << "Injected pointer event had unexpected HOVER event."; return; } if (!scene_graph_) { FX_LOGS(INFO) << "SceneGraph wasn't set up before injecting legacy input. Dropping event."; return; } // Compositor and layer stack required for dispatch. const GlobalId compositor_id(session_id, command.compositor_id); gfx::CompositorWeakPtr compositor = scene_graph_->GetCompositor(compositor_id); if (!compositor) { FX_LOGS(INFO) << "Compositor wasn't set up before injecting legacy input. Dropping event."; return; // It's legal to race against GFX's compositor setup. } gfx::LayerStackPtr layer_stack = compositor->layer_stack(); if (!layer_stack) { FX_LOGS(INFO) << "Layer stack wasn't set up before injecting legacy input. Dropping event."; return; // It's legal to race against GFX's layer stack setup. } const auto layers = layer_stack->layers(); if (layers.empty()) { FX_LOGS(INFO) << "Layer wasn't set up before injecting legacy input. Dropping event."; return; } const gfx::ViewTree& view_tree = scene_graph_->view_tree(); // Assume we only have one layer. const gfx::LayerPtr first_layer = *layers.begin(); const std::optional<glm::mat4> world_from_screen_transform = first_layer->GetWorldFromScreenTransform(); if (!world_from_screen_transform) { FX_LOGS(INFO) << "Wasn't able to get a WorldFromScreenTransform when injecting legacy input. " "Dropping event. Is the camera or renderer uninitialized?"; return; } const zx_koid_t scene_koid = first_layer->scene()->view_ref_koid(); const std::optional<glm::mat4> context_from_world_transform = GetViewFromWorldTransform(scene_koid, view_tree); FX_DCHECK(context_from_world_transform); const uint32_t screen_width = first_layer->width(); const uint32_t screen_height = first_layer->height(); if (screen_width == 0 || screen_height == 0) { FX_LOGS(WARNING) << "Attempted to inject legacy input while Layer had 0 area"; return; } const glm::mat4 context_from_screen_transform = context_from_world_transform.value() * world_from_screen_transform.value(); InternalPointerEvent internal_event = GfxPointerEventToInternalEvent(command.pointer_event, scene_koid, screen_width, screen_height, context_from_screen_transform); switch (command.pointer_event.type) { case PointerEventType::TOUCH: { // Get stream id. Create one if this is a new stream. const uint64_t stream_key = ((uint64_t)internal_event.device_id << 32) | (uint64_t)internal_event.pointer_id; if (!gfx_legacy_streams_.count(stream_key)) { if (internal_event.phase != Phase::ADD) { FX_LOGS(WARNING) << "Attempted to start a stream without an initial ADD."; return; } gfx_legacy_streams_.emplace(stream_key, NewStreamId()); } else if (internal_event.phase == Phase::ADD) { FX_LOGS(WARNING) << "Attempted to ADD twice for the same stream."; return; } const auto stream_id = gfx_legacy_streams_[stream_key]; // Remove from ongoing streams on stream end. if (internal_event.phase == Phase::REMOVE || internal_event.phase == Phase::CANCEL) { gfx_legacy_streams_.erase(stream_key); } TRACE_DURATION("input", "dispatch_command", "command", "TouchCmd"); TRACE_FLOW_END( "input", "dispatch_event_to_scenic", PointerTraceHACK(command.pointer_event.radius_major, command.pointer_event.radius_minor)); InjectTouchEventHitTested(internal_event, stream_id, parallel_dispatch); break; } case PointerEventType::MOUSE: { TRACE_DURATION("input", "dispatch_command", "command", "MouseCmd"); if (internal_event.phase == Phase::ADD || internal_event.phase == Phase::REMOVE) { FX_LOGS(WARNING) << "Oops, mouse device (id=" << internal_event.device_id << ") had an unexpected event: " << internal_event.phase; return; } InjectMouseEventHitTested(internal_event); break; } default: FX_LOGS(INFO) << "Stylus not supported by legacy input injection API."; break; } } void InputSystem::InjectTouchEventExclusive(const InternalPointerEvent& event) { if (!scene_graph_) return; ReportPointerEventToView(event, event.target, fuchsia::ui::input::PointerEventType::TOUCH, scene_graph_->view_tree()); } // The touch state machine comprises ADD/DOWN/MOVE*/UP/REMOVE. Some notes: // - We assume one touchscreen device, and use the device-assigned finger ID. // - Touch ADD associates the following ADD/DOWN/MOVE*/UP/REMOVE event sequence // with the set of clients available at that time. To enable gesture // disambiguation, we perform parallel dispatch to all clients. // - Touch DOWN triggers a focus change, honoring the "may receive focus" property. // - Touch REMOVE drops the association between event stream and client. void InputSystem::InjectTouchEventHitTested(const InternalPointerEvent& event, StreamId stream_id, bool parallel_dispatch) { FX_DCHECK(scene_graph_); const gfx::ViewTree& view_tree = scene_graph_->view_tree(); const uint32_t pointer_id = event.pointer_id; const Phase pointer_phase = event.phase; // The a11y listener is only enabled if the root view is the context. This will later be handled // implicitly by scene graph structure when gesture disambiguation is implemented. // TODO(fxbug.dev/52134): Remove when gesture disambiguation makes it obsolete. const bool a11y_enabled = IsA11yListenerEnabled() && IsOwnedByRootSession(view_tree, event.context); if (pointer_phase == Phase::ADD) { gfx::ViewHitAccumulator accumulator; HitTest(view_tree, event, accumulator, /*semantic_hit_test*/ false); const auto& hits = accumulator.hits(); // Find input targets. Honor the "input masking" view property. std::vector<zx_koid_t> hit_views; for (const gfx::ViewHit& hit : hits) { hit_views.push_back(hit.view_ref_koid); } FX_VLOGS(1) << "View hits: "; for (auto view_ref_koid : hit_views) { FX_VLOGS(1) << "[ViewRefKoid=" << view_ref_koid << "]"; } // Save targets for consistent delivery of touch events. touch_targets_[pointer_id] = hit_views; // If there is an accessibility pointer event listener enabled, an ADD event means that a new // pointer id stream started. Perform it unconditionally, even if the view stack is empty. if (a11y_enabled) { pointer_event_buffer_->AddStream(pointer_id); } } else if (pointer_phase == Phase::DOWN) { // If accessibility listener is on, focus change events must be sent only if // the stream is rejected. This way, this operation is deferred. if (!a11y_enabled) { if (!touch_targets_[pointer_id].empty()) { // Request that focus be transferred to the top view. RequestFocusChange(touch_targets_[pointer_id].front()); } else if (focus_chain_root() != ZX_KOID_INVALID) { // The touch event stream has no designated receiver. // Request that focus be transferred to the root view, so that (1) the currently focused // view becomes unfocused, and (2) the focus chain remains under control of the root view. RequestFocusChange(focus_chain_root()); } } } // Input delivery must be parallel; needed for gesture disambiguation. std::vector<zx_koid_t> deferred_event_receivers; for (zx_koid_t view_ref_koid : touch_targets_[pointer_id]) { if (a11y_enabled) { deferred_event_receivers.emplace_back(view_ref_koid); } else { ReportPointerEventToView(event, view_ref_koid, fuchsia::ui::input::PointerEventType::TOUCH, view_tree); } if (!parallel_dispatch) { break; // TODO(fxbug.dev/24258): Remove when gesture disambiguation is ready. } } FX_DCHECK(a11y_enabled || deferred_event_receivers.empty()) << "When a11y pointer forwarding is off, never defer events."; if (a11y_enabled) { // We handle both latched (!deferred_event_receivers.empty()) and unlatched // (deferred_event_receivers.empty()) touch events, for two reasons. // // (1) We must notify accessibility about events regardless of latch, so that it has full // information about a gesture stream. E.g., the gesture could start traversal in empty space // before MOVE-ing onto a rect; accessibility needs both the gesture and the rect. // // (2) We must trigger a potential focus change request, even if no view receives the triggering // DOWN event, so that (a) the focused view receives an unfocus event, and (b) the focus chain // gets updated and dispatched accordingly. // // NOTE: Do not rely on the latched view stack for "top hit" information; elevation can change // dynamically (it's only guaranteed correct for DOWN). Instead, perform an independent query // for "top hit". zx_koid_t view_ref_koid = ZX_KOID_INVALID; { // Find top-hit target and send it to accessibility. gfx::TopHitAccumulator top_hit; HitTest(view_tree, event, top_hit, /*semantic_hit_test*/ true); if (top_hit.hit()) { view_ref_koid = top_hit.hit()->view_ref_koid; } } glm::vec2 top_hit_view_local; if (view_ref_koid != ZX_KOID_INVALID) { std::optional<glm::mat4> view_from_context = GetDestinationViewFromSourceViewTransform( /*source*/ event.context, /*destination*/ view_ref_koid, view_tree); FX_DCHECK(view_from_context) << "Failed to create world space ray. Either the |event.context| ViewRef is invalid, " "we're out of sync with the ViewTree, or the ViewTree callback returned std::nullopt."; const glm::mat4 view_from_viewport = view_from_context.value() * event.viewport.context_from_viewport_transform; top_hit_view_local = TransformPointerCoords(event.position_in_viewport, view_from_viewport); } const glm::vec2 ndc = GetViewportNDCPoint(event); AccessibilityPointerEvent packet = BuildAccessibilityPointerEvent(event, ndc, top_hit_view_local, view_ref_koid); pointer_event_buffer_->AddEvent( pointer_id, {.event = std::move(event), .parallel_event_receivers = std::move(deferred_event_receivers)}, std::move(packet)); } else { // TODO(fxbug.dev/48150): Delete when we delete the PointerCapture functionality. ReportPointerEventToPointerCaptureListener(event, view_tree); } if (pointer_phase == Phase::REMOVE || pointer_phase == Phase::CANCEL) { touch_targets_.erase(pointer_id); } } // The mouse state machine is simpler, comprising MOVE*-DOWN/MOVE*/UP-MOVE*. Its // behavior is similar to touch events, but with some differences. // - There can be multiple mouse devices, so we track each device individually. // - Mouse DOWN associates the following DOWN/MOVE*/UP event sequence with one // particular client: the top-hit View. Mouse events aren't associated with // gestures, so there is no parallel dispatch. // - Mouse DOWN triggers a focus change, honoring the "may receive focus" property. // - Mouse UP drops the association between event stream and client. // - For an unlatched MOVE event, we perform a hit test, and send the // top-most client this MOVE event. Focus does not change for unlatched // MOVEs. // - The hit test must account for the mouse cursor itself, which today is // owned by the root presenter. The nodes associated with visible mouse // cursors(!) do not roll up to any View (as expected), but may appear in the // hit test; our dispatch needs to account for such behavior. // TODO(fxbug.dev/24288): Enhance trackpad support. void InputSystem::InjectMouseEventHitTested(const InternalPointerEvent& event) { FX_DCHECK(scene_graph_); const gfx::ViewTree& view_tree = scene_graph_->view_tree(); const uint32_t device_id = event.device_id; const Phase pointer_phase = event.phase; if (pointer_phase == Phase::DOWN) { // Find top-hit target and associated properties. // NOTE: We may hit various mouse cursors (owned by root presenter), but |TopHitAccumulator| // will keep going until we find a hit with a valid owning View. gfx::TopHitAccumulator top_hit; HitTest(view_tree, event, top_hit, /*semantic_hit_test*/ false); std::vector</*view_ref_koids*/ zx_koid_t> hit_views; if (top_hit.hit()) { hit_views.push_back(top_hit.hit()->view_ref_koid); } FX_VLOGS(1) << "View hits: "; for (auto view_ref_koid : hit_views) { FX_VLOGS(1) << "[ViewRefKoid=" << view_ref_koid << "]"; } if (!hit_views.empty()) { // Request that focus be transferred to the top view. RequestFocusChange(hit_views.front()); } else if (focus_chain_root() != ZX_KOID_INVALID) { // The mouse event stream has no designated receiver. // Request that focus be transferred to the root view, so that (1) the currently focused // view becomes unfocused, and (2) the focus chain remains under control of the root view. RequestFocusChange(focus_chain_root()); } // Save target for consistent delivery of mouse events. mouse_targets_[device_id] = hit_views; } if (mouse_targets_.count(device_id) > 0 && // Tracking this device, and mouse_targets_[device_id].size() > 0) { // target view exists. const zx_koid_t top_view_koid = mouse_targets_[device_id].front(); ReportPointerEventToView(event, top_view_koid, fuchsia::ui::input::PointerEventType::MOUSE, view_tree); } if (pointer_phase == Phase::UP || pointer_phase == Phase::CANCEL) { mouse_targets_.erase(device_id); } // Deal with unlatched MOVE events. if (pointer_phase == Phase::CHANGE && mouse_targets_.count(device_id) == 0) { // Find top-hit target and send it this move event. // NOTE: We may hit various mouse cursors (owned by root presenter), but |TopHitAccumulator| // will keep going until we find a hit with a valid owning View. gfx::TopHitAccumulator top_hit; HitTest(view_tree, event, top_hit, /*semantic_hit_test*/ false); if (top_hit.hit()) { const zx_koid_t top_view_koid = top_hit.hit()->view_ref_koid; ReportPointerEventToView(event, top_view_koid, fuchsia::ui::input::PointerEventType::MOUSE, view_tree); } } } void InputSystem::DispatchDeferredPointerEvent( PointerEventBuffer::DeferredPointerEvent views_and_event) { if (!scene_graph_) return; // If this parallel dispatch of events corresponds to a DOWN event, this // triggers a possible deferred focus change event. if (views_and_event.event.phase == Phase::DOWN) { if (!views_and_event.parallel_event_receivers.empty()) { // Request that focus be transferred to the top view. const zx_koid_t view_koid = views_and_event.parallel_event_receivers.front(); FX_DCHECK(view_koid != ZX_KOID_INVALID) << "invariant"; RequestFocusChange(view_koid); } else if (focus_chain_root() != ZX_KOID_INVALID) { // The touch event stream has no designated receiver. // Request that focus be transferred to the root view, so that (1) the currently focused // view becomes unfocused, and (2) the focus chain remains under control of the root view. RequestFocusChange(focus_chain_root()); } } const gfx::ViewTree& view_tree = scene_graph_->view_tree(); for (zx_koid_t view_ref_koid : views_and_event.parallel_event_receivers) { ReportPointerEventToView(views_and_event.event, view_ref_koid, fuchsia::ui::input::PointerEventType::TOUCH, view_tree); } { // TODO(fxbug.dev/48150): Delete when we delete the PointerCapture functionality. ReportPointerEventToPointerCaptureListener(views_and_event.event, view_tree); } } zx_koid_t InputSystem::focus() const { if (!scene_graph_) return ZX_KOID_INVALID; // No scene graph, no view tree, no focus chain. const auto& chain = scene_graph_->view_tree().focus_chain(); if (chain.empty()) return ZX_KOID_INVALID; // Scene not present, or scene not connected to compositor. const zx_koid_t focused_view = chain.back(); FX_DCHECK(focused_view != ZX_KOID_INVALID) << "invariant"; return focused_view; } zx_koid_t InputSystem::focus_chain_root() const { if (!scene_graph_) return ZX_KOID_INVALID; // No scene graph, no view tree, no focus chain. const auto& chain = scene_graph_->view_tree().focus_chain(); if (chain.empty()) return ZX_KOID_INVALID; // Scene not present, or scene not connected to compositor. const zx_koid_t root_view = chain.front(); FX_DCHECK(root_view != ZX_KOID_INVALID) << "invariant"; return root_view; } void InputSystem::RequestFocusChange(zx_koid_t view) { FX_DCHECK(view != ZX_KOID_INVALID) << "precondition"; if (!scene_graph_) return; // No scene graph, no view tree, no focus chain. if (scene_graph_->view_tree().focus_chain().empty()) return; // Scene not present, or scene not connected to compositor. // Input system acts on authority of top-most view. const zx_koid_t requestor = scene_graph_->view_tree().focus_chain().front(); auto status = scene_graph_->RequestFocusChange(requestor, view); FX_VLOGS(1) << "Scenic RequestFocusChange. Authority: " << requestor << ", request: " << view << ", status: " << static_cast<int>(status); FX_DCHECK(status == FocusChangeStatus::kAccept || status == FocusChangeStatus::kErrorRequestCannotReceiveFocus) << "User has authority to request focus change, but the only valid rejection is when the " "requested view may not receive focus. Error code: " << static_cast<int>(status); } bool InputSystem::IsOwnedByRootSession(const gfx::ViewTree& view_tree, zx_koid_t koid) const { const zx_koid_t root_koid = focus_chain_root(); return root_koid != ZX_KOID_INVALID && view_tree.SessionIdOf(koid) == view_tree.SessionIdOf(root_koid); } // TODO(fxbug.dev/48150): Delete when we delete the PointerCapture functionality. void InputSystem::ReportPointerEventToPointerCaptureListener(const InternalPointerEvent& event, const gfx::ViewTree& view_tree) const { if (!pointer_capture_listener_) return; const PointerCaptureListener& listener = pointer_capture_listener_.value(); const zx_koid_t view_ref_koid = utils::ExtractKoid(listener.view_ref); std::optional<glm::mat4> view_from_context_transform = GetDestinationViewFromSourceViewTransform( /*source*/ event.context, /*destination*/ view_ref_koid, view_tree); if (!view_from_context_transform) return; fuchsia::ui::input::PointerEvent gfx_event = InternalPointerEventToGfxPointerEvent( event, view_from_context_transform.value(), fuchsia::ui::input::PointerEventType::TOUCH, /*trace_id*/ 0); // TODO(fxbug.dev/42145): Implement flow control. listener.listener_ptr->OnPointerEvent(gfx_event, [] {}); } void InputSystem::ReportPointerEventToView(const InternalPointerEvent& event, zx_koid_t view_ref_koid, fuchsia::ui::input::PointerEventType type, const gfx::ViewTree& view_tree) const { TRACE_DURATION("input", "dispatch_event_to_client", "event_type", "pointer"); EventReporterWeakPtr event_reporter = view_tree.EventReporterOf(view_ref_koid); if (!event_reporter) return; std::optional<glm::mat4> view_from_context_transform = GetDestinationViewFromSourceViewTransform( /*source*/ event.context, /*destination*/ view_ref_koid, view_tree); if (!view_from_context_transform) return; const uint64_t trace_id = NextTraceId(); TRACE_FLOW_BEGIN("input", "dispatch_event_to_client", trace_id); InputEvent input_event; input_event.set_pointer(InternalPointerEventToGfxPointerEvent( event, view_from_context_transform.value(), type, trace_id)); FX_VLOGS(1) << "Event dispatch to view=" << view_ref_koid << ": " << input_event; event_reporter->EnqueueEvent(std::move(input_event)); } } // namespace input } // namespace scenic_impl
44.567036
100
0.697651
[ "vector" ]
2935c21a2033515e94f301c057b57713393729bc
8,392
cc
C++
tensorflow/lite/delegates/gpu/metal/kernels/elementwise.cc
deerluffy/tensorflow
73e9dc4e1eae1589c8ea4a7cf1e8398c1eff3ab1
[ "Apache-2.0" ]
1
2020-09-30T07:40:55.000Z
2020-09-30T07:40:55.000Z
tensorflow/lite/delegates/gpu/metal/kernels/elementwise.cc
deerluffy/tensorflow
73e9dc4e1eae1589c8ea4a7cf1e8398c1eff3ab1
[ "Apache-2.0" ]
null
null
null
tensorflow/lite/delegates/gpu/metal/kernels/elementwise.cc
deerluffy/tensorflow
73e9dc4e1eae1589c8ea4a7cf1e8398c1eff3ab1
[ "Apache-2.0" ]
1
2021-03-28T10:02:51.000Z
2021-03-28T10:02:51.000Z
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/delegates/gpu/metal/kernels/elementwise.h" #include <cstddef> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/strings/substitute.h" #include "tensorflow/lite/delegates/gpu/common/convert.h" #include "tensorflow/lite/delegates/gpu/common/operations.h" #include "tensorflow/lite/delegates/gpu/common/util.h" #include "tensorflow/lite/delegates/gpu/metal/compute_task_descriptor.h" namespace tflite { namespace gpu { namespace metal { namespace { std::string OneInputFunctor(OperationType op_type, const std::string& value) { const absl::flat_hash_map<OperationType, std::string> functors{ {OperationType::ABS, "abs($0)"}, {OperationType::SIN, "sin($0)"}, {OperationType::HARD_SWISH, "$0 * clamp($0 / 6.0f + FLT4(0.5f), FLT4(0.0f), FLT4(1.0f))"}, {OperationType::COS, "cos($0)"}, {OperationType::ELU, "FLT4($0.x < FLT(0.0f) ? exp($0.x) - FLT(1.0f) : $0.x," "$0.y < FLT(0.0f) ? exp($0.y) - FLT(1.0f) : $0.y," "$0.z < FLT(0.0f) ? exp($0.z) - FLT(1.0f) : $0.z," "$0.w < FLT(0.0f) ? exp($0.w) - FLT(1.0f) : $0.w)"}, {OperationType::EXP, "exp($0)"}, {OperationType::LOG, "log($0)"}, {OperationType::NEG, "-($0)"}, {OperationType::SQRT, "sqrt($0)"}, {OperationType::RSQRT, "1.0 / sqrt($0)"}, {OperationType::SQUARE, "$0 * $0"}, {OperationType::SIGMOID, "1.0 / (1.0 + exp(-1.0 * $0))"}, {OperationType::TANH, "tanh($0)"}, {OperationType::COPY, "$0"}, }; if (functors.find(op_type) == functors.end()) { return "Error, unknown op"; } return absl::Substitute(functors.at(op_type), value); } std::string TwoInputFunctor(OperationType op_type, const std::string& value0, const std::string& value1) { const absl::flat_hash_map<OperationType, std::string> functors{ {OperationType::ADD, "$0 + $1"}, {OperationType::DIV, "$0 / $1"}, {OperationType::MAXIMUM, "max($0, $1)"}, {OperationType::MINIMUM, "min($0, $1)"}, {OperationType::MUL, "$0 * $1"}, {OperationType::POW, "pow($0, $1)"}, {OperationType::SQUARED_DIFF, "($0 - $1) * ($0 - $1)"}, {OperationType::SUB, "$0 - $1"}, }; if (functors.find(op_type) == functors.end()) { return "Error, unknown op"; } return absl::Substitute(functors.at(op_type), value0, value1); } } // namespace ComputeTaskDescriptor ElementwiseWithTwoInputs(int id, std::vector<ValueId> input_ids, ValueId output_id, const BHWC& second_shape, OperationType op_type) { ComputeTaskDescriptor desc; desc.id = id; desc.is_linkable = true; const std::string x_coord = second_shape.w == 1 ? "0" : "int(gid.x)"; const std::string y_coord = second_shape.h == 1 ? "0" : "int(gid.y)"; const std::string s_coord = second_shape.c == 1 ? "0" : "int(gid.z)"; std::string code = "FLT4 linkable$0(FLT4 value, int linear_index, uint3 gid, device FLT4* " "const second_tensor, int2 second_size) {\n"; code += " int second_index = (" + s_coord + " * second_size.y + " + y_coord + ") * second_size.x + " + x_coord + ";\n"; code += " FLT4 src_1 = second_tensor[second_index];\n"; if (second_shape.c == 1) { code += " src_1.y = src_1.x;\n"; code += " src_1.z = src_1.x;\n"; code += " src_1.w = src_1.x;\n"; } code += " return " + TwoInputFunctor(op_type, "value", "src_1") + ";\n"; code += "}\n"; desc.shader_source = code; desc.input_buffers = { {input_ids[0], "device FLT4* const"}, {input_ids[1], "device FLT4* const"}, }; desc.output_buffer = {output_id}; desc.uniform_buffers = { {"constant int2&", [input_ids](const std::map<ValueId, BHWC>& buffers) { const auto& input_dim_1 = buffers.find(input_ids[1])->second; std::vector<int> uniform_params{ input_dim_1.w, input_dim_1.h, }; return GetByteBuffer(uniform_params); }}, }; return desc; } ComputeTaskDescriptor ElementwiseWithOneInput(int id, ValueId input_id, ValueId output_id, OperationType op_type) { ComputeTaskDescriptor desc; desc.id = id; desc.is_linkable = true; desc.shader_source = "FLT4 linkable$0(FLT4 value, int linear_index, uint3 gid) {\n"; desc.shader_source += " return " + OneInputFunctor(op_type, "value") + ";\n"; desc.shader_source += " }"; desc.input_buffers = {{input_id}}; desc.output_buffer = {output_id}; return desc; } ComputeTaskDescriptor ElementwiseWithOneInputAndConstantArguent( int id, ValueId input_id, ValueId output_id, const RuntimeOptions& options, OperationType op_type, const TensorOrScalar& attr) { ComputeTaskDescriptor desc; desc.id = id; desc.is_linkable = true; auto scalar = absl::get_if<float>(&attr); auto linear_buf = absl::get_if<Tensor<Linear, DataType::FLOAT32>>(&attr); auto hwc_buf = absl::get_if<Tensor<HWC, DataType::FLOAT32>>(&attr); std::string param_desc; if (scalar) { param_desc += ", float scalar_val"; } if (linear_buf) { param_desc += ", device FLT4* const linear_buf"; } if (hwc_buf) { param_desc += ", device FLT4* const hwc_buf, int2 hwc_size"; } desc.shader_source = "FLT4 linkable$0(FLT4 value, int linear_index, uint3 gid" + param_desc + ") {\n"; if (scalar) { desc.shader_source += " FLT4 second_arg = FLT4(scalar_val);\n"; } else if (linear_buf) { desc.shader_source += " FLT4 second_arg = linear_buf[gid.z];\n"; } else if (hwc_buf) { const std::string x_coord = hwc_buf->shape.w == 1 ? "0" : "int(gid.x)"; const std::string y_coord = hwc_buf->shape.h == 1 ? "0" : "int(gid.y)"; const std::string s_coord = hwc_buf->shape.c == 1 ? "0" : "int(gid.z)"; std::string index = "(" + s_coord + " * hwc_size.y + " + y_coord + ") * hwc_size.x + " + x_coord; desc.shader_source += " FLT4 second_arg = hwc_buf[" + index + "];\n"; if (hwc_buf->shape.c == 1) { desc.shader_source += " second_arg.y = second_arg.x;\n"; desc.shader_source += " second_arg.z = second_arg.x;\n"; desc.shader_source += " second_arg.w = second_arg.x;\n"; } } desc.shader_source += " return " + TwoInputFunctor(op_type, "value", "second_arg") + ";\n"; desc.shader_source += " }"; desc.input_buffers = {{input_id}}; desc.output_buffer = {output_id}; if (scalar) { std::vector<uint8_t> scalar_bits = GetByteBuffer(std::vector<float>{*scalar}); desc.uniform_buffers = { {"constant float&", [scalar_bits](const std::map<ValueId, BHWC>& buffers) { return scalar_bits; }}, }; } else if (linear_buf) { desc.immutable_buffers = { {"device FLT4* const", GetByteBufferConverted(linear_buf->data, options.storage_precision)}, }; } else if (hwc_buf) { std::vector<uint8_t> size_bits = GetByteBuffer(std::vector<int>{hwc_buf->shape.w, hwc_buf->shape.h}); desc.uniform_buffers = { {"constant int2&", [size_bits](const std::map<ValueId, BHWC>& buffers) { return size_bits; }}, }; desc.immutable_buffers = { {"device FLT4* const", GetByteBufferConverted(ConvertToPHWC4(*hwc_buf), options.storage_precision)}, }; } return desc; } } // namespace metal } // namespace gpu } // namespace tflite
36.486957
80
0.595806
[ "shape", "vector" ]
2938d1a2d005ff06d58a36bb2a4d8de03ce9ec78
1,804
cpp
C++
Codechef/CHEFCRUN.cpp
jceplaras/competitiveprogramming
d92cbedd31d9aa812a6084aea50e573886e5e6e4
[ "MIT" ]
null
null
null
Codechef/CHEFCRUN.cpp
jceplaras/competitiveprogramming
d92cbedd31d9aa812a6084aea50e573886e5e6e4
[ "MIT" ]
null
null
null
Codechef/CHEFCRUN.cpp
jceplaras/competitiveprogramming
d92cbedd31d9aa812a6084aea50e573886e5e6e4
[ "MIT" ]
null
null
null
#include <algorithm> #include <cmath> #include <cctype> #include <climits> #include <cstdio> #include <cstring> #include <iostream> #include <map> #include <queue> #include <set> #include <string> #include <vector> #define FOR(i,a,b) for (int i = a; i <= b; i++) #define FORN(i,N) for (int i = 0; i < N; i++) #define FORD(i,a,b) for (int i = a; i >= b; i--) #define MOD(a,b) (a%b+b)%b using namespace std; typedef long long ll; typedef unsigned long long ull; typedef vector<int> vi; typedef pair<int,int> pii; typedef vector<pii> vpii; int main() { int T; scanf("%d",&T); ll R[200005]; ll F[200005]; ll B[200005]; while(T--) { int N; int start, end; scanf("%d",&N); memset(R, 0, sizeof R); memset(F, 0, sizeof R); memset(B, 0, sizeof R); FOR(i,1,N) scanf("%lld",&R[i]); scanf("%d %d",&start,&end); start--; end--; FOR(i,1,N) { R[i] = R[i] + R[i-1]; } ll costDirect = R[end] - R[start]; ll costIndirect = R[start] + (R[N] - R[end]); ll minVal = min(costDirect,costIndirect); ll minVal = min(minval, minVal+R[N]); ll minSERcost = 0; int minSERend = start; ll minESRcost = 0; int minESRend = end; for(int x = start+1; x < end; x++) { ll costFromStart = R[x] - R[start]; ll costFromEnd = R[end] - R[x]; if(costFromStart < minSERcost) { minSERend = x; minSERight = costFromStart; } if(costFromEnd < minESRcost) { minESRend = x; minESRcost = costFromEnd; } } if(minSERend > minESRend) { ll startToESR = 0; } else { minVal = min(minVal, costIndirect + 2*minESRcost + 2*minSERcost); } printf("%lld\n",costDirect); printf("%lld\n",costIndirect); } return 0; }
18.597938
71
0.553769
[ "vector" ]
2938fcee8135ce16a73a8a557176c782d4f10947
24,136
cpp
C++
lib/wx/c_src/wxe_impl.cpp
jjhoo/otp
808eccc796a05caf2f2a244db385df83c2680b9f
[ "Apache-2.0" ]
8,238
2015-01-02T01:05:29.000Z
2022-03-30T04:09:46.000Z
lib/wx/c_src/wxe_impl.cpp
jjhoo/otp
808eccc796a05caf2f2a244db385df83c2680b9f
[ "Apache-2.0" ]
2,988
2015-01-02T11:40:59.000Z
2022-03-31T18:29:54.000Z
lib/wx/c_src/wxe_impl.cpp
jjhoo/otp
808eccc796a05caf2f2a244db385df83c2680b9f
[ "Apache-2.0" ]
2,459
2015-01-01T18:54:55.000Z
2022-03-31T08:58:25.000Z
/* * %CopyrightBegin% * * Copyright Ericsson AB 2008-2017. 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. * * %CopyrightEnd% */ #include <stdio.h> #include <signal.h> #include <wx/wx.h> // Avoid including these in dcbuffer below #include "wx/dcmemory.h" #include "wx/dcclient.h" #include "wx/window.h" // Ok ugly but needed for wxBufferedDC crash workaround #define private public #include <wx/dcbuffer.h> #undef private #include "wxe_impl.h" #include "wxe_events.h" #include "wxe_return.h" #include "wxe_gl.h" IMPLEMENT_APP_NO_MAIN(WxeApp) DECLARE_APP(WxeApp) DEFINE_EVENT_TYPE(wxeEVT_META_COMMAND) #define WXE_NORMAL 0 #define WXE_CALLBACK 1 #define WXE_STORED 2 // Globals initiated in wxe_init.cpp extern ErlNifMutex *wxe_status_m; extern ErlNifCond *wxe_status_c; extern ErlNifMutex * wxe_batch_locker_m; extern ErlNifCond * wxe_batch_locker_c; extern ErlNifPid init_caller; extern int wxe_status; wxeFifo * wxe_queue = NULL; unsigned int wxe_idle_processed = 0; unsigned int wxe_needs_signal = 0; // inside batch if larger than 0 unsigned int wxe_needs_wakeup = 0; // inside batch if larger than 0 /* ************************************************************ * Commands from erlang * Called by emulator thread * ************************************************************/ void push_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[], int op, wxe_me_ref *mp) { ErlNifPid caller; if(!enif_self(env, &caller)) { caller = ((wxeMemEnv *) mp->memenv)->owner; } enif_mutex_lock(wxe_batch_locker_m); int n = wxe_queue->Add(argc, argv, op, mp, caller); if(wxe_needs_signal) { enif_cond_signal(wxe_batch_locker_c); enif_mutex_unlock(wxe_batch_locker_m); } else { // wx-thread is waiting gui-events int wakeup = wxe_needs_wakeup; wxe_needs_wakeup = 0; enif_mutex_unlock(wxe_batch_locker_m); if(n < 2 || wakeup || WXE_DEBUG_PING) { wxWakeUpIdle(); } } } void meta_command(ErlNifEnv *env, int what, wxe_me_ref *mp) { int status; enif_mutex_lock(wxe_status_m); status = wxe_status; enif_cond_signal(wxe_status_c); enif_mutex_unlock(wxe_status_m); if(status == WXE_INITIATED) { ErlNifPid self; enif_self(env, &self); wxeMetaCommand Cmd(self, what, mp); wxTheApp->AddPendingEvent(Cmd); } } void send_msg(const char * type, const wxString * msg) { WxeApp * app = (WxeApp *) wxTheApp; wxeReturn rt = wxeReturn(app->global_me, init_caller); ERL_NIF_TERM emsg = enif_make_tuple3(rt.env, rt.make_atom((char *) "wxe_driver"), rt.make_atom((char *) type), rt.make(msg)); rt.send(emsg); } void print_cmd(wxeCommand& event) { int i; wxe_fns_t *func = &wxe_fns[event.op]; enif_fprintf(stderr, " %T %d %s::%s(", event.caller, event.op, func->cname, func->fname); for(i=0; i < event.argc-1; i++) { enif_fprintf(stderr, "%T,", event.args[i]); } if(i > 0) { enif_fprintf(stderr, "%T)\r\n", event.args[i]); } else { enif_fprintf(stderr, ")\r\n"); } } /* ************************************************************ * Init WxeApp the application emulator * ************************************************************/ bool WxeApp::OnInit() { global_me = new wxeMemEnv(); wxe_queue = new wxeFifo(2000); cb_return = NULL; recurse_level = 0; delayed_delete = new wxeFifo(100); delayed_cleanup = new wxList; wxe_ps_init2(); wxIdleEvent::SetMode(wxIDLE_PROCESS_SPECIFIED); Connect(wxID_ANY, wxEVT_IDLE, (wxObjectEventFunction) (wxEventFunction) &WxeApp::idle); Connect(WXE_GET_CONSTS, wxeEVT_META_COMMAND,(wxObjectEventFunction) (wxEventFunction) &WxeApp::init_consts); Connect(WXE_DELETE_ENV, wxeEVT_META_COMMAND,(wxObjectEventFunction) (wxEventFunction) &WxeApp::destroyMemEnv); Connect(WXE_SHUTDOWN, wxeEVT_META_COMMAND,(wxObjectEventFunction) (wxEventFunction) &WxeApp::shutdown); // fprintf(stderr, "Size void* %d: long %d long long %d int64 %d \r\n", // sizeof(void *), sizeof(long), sizeof(long long), sizeof(wxInt64)); initEventTable(); wxInitAllImageHandlers(); #ifdef _MACOSX /* Create a default MenuBar so that we can intercept the quit command */ wxMenuBar *macMB = new wxMenuBar; wxMenuBar::MacSetCommonMenuBar(macMB); macMB->MacInstallMenuBar(); macMB->Connect(wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction) (wxEventFunction) &WxeApp::dummy_close); #endif SetExitOnFrameDelete(false); enif_mutex_lock(wxe_status_m); wxe_status = WXE_INITIATED; enif_cond_signal(wxe_status_c); enif_mutex_unlock(wxe_status_m); return TRUE; } #ifdef _MACOSX void WxeApp::MacPrintFile(const wxString &filename) { send_msg("print_file", &filename); } void WxeApp::MacOpenFile(const wxString &filename) { send_msg("open_file", &filename); } void WxeApp::MacOpenURL(const wxString &url) { send_msg("open_url", &url); } void WxeApp::MacNewFile() { wxString empty; send_msg("new_file", &empty); } void WxeApp::MacReopenApp() { wxString empty; send_msg("reopen_app", &empty); } #endif void WxeApp::shutdown(wxeMetaCommand& Ecmd) { wxe_status = WXE_EXITING; ExitMainLoop(); delete wxe_queue; } void WxeApp::dummy_close(wxEvent& Ev) { // fprintf(stderr, "Dummy Close invoked\r\n"); // wxMac really wants a top level window which command-q quits if there are no // windows open, and this will kill the erlang, override default handling } void WxeApp::OnAssertFailure(const wxChar *file, int line, const wxChar *cfunc, const wxChar *cond, const wxChar *cmsgUser) { wxString msg; wxString func(cfunc); wxString msgUser(cmsgUser); msg.Printf(wxT("wxWidgets Assert failure: %s(%d): \"%s\""), file, line, cond); if ( !func.empty() ) { msg << wxT(" in ") << func << wxT("()"); } // and the message itself if ( !msgUser.empty() ) { msg << wxT(" : ") << msgUser; } send_msg("error", &msg); } // Called by wx thread void WxeApp::idle(wxIdleEvent& event) { event.Skip(true); if(dispatch_cmds()) event.RequestMore(); } /* ************************************************************ * Erlang Command execution * * ************************************************************/ /* Callback from printer and event callbacks */ void pre_callback() { // no-op } void handle_event_callback(wxe_me_ref *mr, ErlNifPid process) { WxeApp * app = (WxeApp *) wxTheApp; ErlNifMonitor monitor; if(wxe_status != WXE_INITIATED) return; // enif_fprintf(stderr, "CB EV start %T \r\n", process); // Is thread safe if pdl have been incremented if(mr->memenv && enif_monitor_process(NULL, mr, &process, &monitor) == 0) { // Should we be able to handle commands when recursing? probably app->cb_return = NULL; app->recurse_level++; app->dispatch_cb(wxe_queue, (wxeMemEnv *) mr->memenv, process); app->recurse_level--; enif_demonitor_process(NULL, mr, &monitor); } else { // enif_fprintf(stderr, "CB %T is not alive ignoring\r\n", process); app->cb_return = NULL; } // enif_fprintf(stderr, "CB EV done %T \r\n", process); } int WxeApp::dispatch_cmds() { int more = 0; if(wxe_status != WXE_INITIATED) return more; recurse_level++; // fprintf(stderr, "\r\ndispatch_normal %d\r\n", recurse_level);fflush(stderr); more = dispatch(wxe_queue); // fprintf(stderr, "\r\ndispatch_done %d\r\n", recurse_level);fflush(stderr); recurse_level--; // Cleanup old memenv's and deleted objects if(recurse_level == 0) { wxeCommand *curr; while((curr = delayed_delete->Get()) != NULL) { wxe_dispatch(*curr); delayed_delete->DeleteCmd(curr); } // delayed_delete->Cleanup(); if(delayed_cleanup->size() > 0) for( wxList::compatibility_iterator node = delayed_cleanup->GetFirst(); node; node = delayed_cleanup->GetFirst()) { wxeMetaCommand *event = (wxeMetaCommand *)node->GetData(); delayed_cleanup->Erase(node); destroyMemEnv(*event); delete event; } } return more; } #define CHECK_EVENTS 10000 int WxeApp::dispatch(wxeFifo * batch) { int ping = 0; int blevel = 0; int wait = 0; // Let event handling generate events sometime wxeCommand *event; enif_mutex_lock(wxe_batch_locker_m); wxe_idle_processed = 1; while(true) { while((event = batch->Get()) != NULL) { wait += 1; switch(event->op) { case WXE_BATCH_END: if(blevel>0) { blevel--; if(blevel==0) wait += CHECK_EVENTS/4; } break; case WXE_BATCH_BEGIN: blevel++; break; case WXE_DEBUG_PING: // When in debugger we don't want to hang waiting for a BATCH_END // that never comes, because a breakpoint have hit. ping++; if(ping > 2) blevel = 0; break; case WXE_CB_START: // CB process died just ignore this break; case WXE_CB_RETURN: if(enif_is_identical(event->args[0], WXE_ATOM_ok)) { batch->DeleteCmd(event); } else { cb_return = event; // must be deleted after taken care of } enif_mutex_unlock(wxe_batch_locker_m); return 1; default: enif_mutex_unlock(wxe_batch_locker_m); if(event->op < OPENGL_START) { // fprintf(stderr, " c %d (%d) \r\n", event->op, blevel); wxe_dispatch(*event); } else { gl_dispatch(event); } enif_mutex_lock(wxe_batch_locker_m); break; } if(wait > CHECK_EVENTS) { enif_mutex_unlock(wxe_batch_locker_m); return 1; // Let wx check for events } batch->DeleteCmd(event); } if(blevel <= 0) { enif_mutex_unlock(wxe_batch_locker_m); return 0; } // sleep until something happens // fprintf(stderr, "%s:%d sleep %d %d %d\r\n", __FILE__, __LINE__, batch->m_n, blevel, wait);fflush(stderr); wxe_needs_signal = 1; while(batch->m_q.empty()) { enif_cond_wait(wxe_batch_locker_c, wxe_batch_locker_m); } wxe_needs_signal = 0; } } void WxeApp::dispatch_cb(wxeFifo * batch, wxeMemEnv * memenv, ErlNifPid process) { wxeCommand *event; unsigned int peek = 0; enif_mutex_lock(wxe_batch_locker_m); unsigned int i = 0; unsigned int last = batch->m_q.size(); wxe_idle_processed = 0; while(true) { while (i < last ) { event = batch->m_q[i]; // enif_fprintf(stderr, "%d: CB %T owner %T it %d %d (%d) \r\n", // recurse_level, event ? event->caller : process, process, // i, batch->Size(), batch->m_q.size()); if(event && (event->op == WXE_CB_START || // Event callback start change process event->op == WXE_CB_DIED || // Event callback process died event->op == WXE_DEBUG_PING || enif_compare_pids(&event->caller, &process) == 0 || // Callbacks from CB process only // Allow connect_cb during CB i.e. msg from wxe_server. (memenv && enif_compare_pids(&event->caller,&memenv->owner) == 0) )) { // enif_fprintf(stderr, "Exec:"); print_cmd(*event); batch->DelQueue(i); switch(event->op) { case WXE_BATCH_END: case WXE_BATCH_BEGIN: case WXE_DEBUG_PING: break; case WXE_CB_RETURN: if(enif_is_identical(event->args[0], WXE_ATOM_ok)) { batch->DeleteCmd(event); } else { cb_return = event; // must be deleted after taken care of } wxe_needs_wakeup = 1; enif_mutex_unlock(wxe_batch_locker_m); return; case WXE_CB_DIED: cb_return = NULL; batch->DeleteCmd(event); wxe_needs_wakeup = 1; enif_mutex_unlock(wxe_batch_locker_m); return; case WXE_CB_START: // CB start from now accept message from CB process only process = event->caller; break; default: enif_mutex_unlock(wxe_batch_locker_m); if(event->op < OPENGL_START) { wxe_dispatch(*event); } else { gl_dispatch(event); } enif_mutex_lock(wxe_batch_locker_m); last = batch->m_q.size(); if(wxe_idle_processed) { // We have processed cmds inside dispatch() // so the iterator may be wrong, restart from // beginning of the queue i = 0; } break; } batch->DeleteCmd(event); } else { // enif_fprintf(stderr, "Ignore:"); event ? print_cmd(*event) : fprintf(stderr, "NULL\r\n"); } i++; } // sleep until something happens // enif_fprintf(stderr, "\r\n%s:%d: %d: sleep sz %d (%d) it pos: %d\r\n", __FILE__, __LINE__, recurse_level, // batch->Size(), batch->m_q.size(), i); fflush(stderr); wxe_needs_signal = 1; peek = batch->Size(); while(peek >= batch->Size()) { enif_cond_wait(wxe_batch_locker_c, wxe_batch_locker_m); } wxe_needs_signal = 0; last = batch->m_q.size(); } } void WxeApp::wxe_dispatch(wxeCommand& event) { int op = event.op; wxe_fns_t *func = &wxe_fns[op]; void (*nif_cb) (WxeApp *, wxeMemEnv *, wxeCommand& ) = func->nif_cb; wxeMemEnv * memenv = (wxeMemEnv *) event.me_ref->memenv; if(wxe_debug) { print_cmd(event); } if (event.me_ref->memenv) { if(nif_cb) { try { nif_cb(this, memenv, event); } catch (wxe_badarg badarg) { wxeReturn rt = wxeReturn(memenv, event.caller, false); ERL_NIF_TERM ba = enif_make_tuple2(rt.env, WXE_ATOM_badarg, enif_make_string(rt.env, badarg.var, ERL_NIF_LATIN1)); ERL_NIF_TERM mfa = enif_make_tuple3(rt.env, enif_make_atom(rt.env, func->cname), enif_make_atom(rt.env, func->fname), rt.make_int(func->n)); rt.send(enif_make_tuple4(rt.env, WXE_ATOM_error, rt.make_int(op), mfa, ba)); } } else { wxeReturn rt = wxeReturn(memenv, event.caller, false); ERL_NIF_TERM undef = enif_make_atom(rt.env, "undefined_function"); ERL_NIF_TERM mfa = enif_make_tuple3(rt.env, enif_make_atom(rt.env, func->cname), enif_make_atom(rt.env, func->fname), rt.make_int(func->n)); rt.send(enif_make_tuple4(rt.env, WXE_ATOM_error, rt.make_int(op), mfa, undef)); } } else { wxeReturn rt = wxeReturn(global_me, event.caller); ERL_NIF_TERM unknown_env = enif_make_atom(rt.env, "unknown_env"); ERL_NIF_TERM mfa = enif_make_tuple3(rt.env, enif_make_atom(rt.env, func->cname), enif_make_atom(rt.env, func->fname), rt.make_int(func->n)); rt.send(enif_make_tuple4(rt.env, WXE_ATOM_error, rt.make_int(op), mfa, unknown_env)); } } /* Memory handling */ void * newMemEnv(ErlNifEnv* env, wxe_me_ref *mr) { WxeApp * app = (WxeApp *) wxTheApp; wxeMemEnv* global_me = app->global_me; wxeMemEnv* memenv = new wxeMemEnv(); memenv->create(); for(int i = 0; i < global_me->next; i++) { memenv->ref2ptr[i] = global_me->ref2ptr[i]; } memenv->next = global_me->next; enif_self(env, &memenv->owner); memenv->me_ref = mr; return memenv; } void WxeApp::destroyMemEnv(wxeMetaCommand &Ecmd) { // Clear incoming cmd queue first dispatch_cmds(); enif_mutex_lock(wxe_batch_locker_m); wxe_needs_wakeup = 1; enif_mutex_unlock(wxe_batch_locker_m); wxWindow *parent = NULL; if(!Ecmd.me_ref || !Ecmd.me_ref->memenv) { wxString msg; msg.Printf(wxT("MemEnv already deleted")); send_msg("debug", &msg); return; } wxeMemEnv *memenv = (wxeMemEnv *) Ecmd.me_ref->memenv; if(wxe_debug) { wxString msg; msg.Printf(wxT("Destroying all memory ")); send_msg("debug", &msg); } // pre-pass delete all dialogs first since they might crash erlang otherwise for(int i=1; i < memenv->next; i++) { wxObject * ptr = (wxObject *) memenv->ref2ptr[i]; if(ptr) { ptrMap::iterator it = ptr2ref.find(ptr); if(it != ptr2ref.end()) { wxeRefData *refd = it->second; if(refd->alloc_in_erl && refd->type == 2) { wxDialog *win = (wxDialog *) ptr; if(win->IsModal()) { win->EndModal(-1); } parent = win->GetParent(); if(parent) { ptrMap::iterator parentRef = ptr2ref.find(parent); if(parentRef == ptr2ref.end()) { // The parent is already dead delete the parent ref win->SetParent(NULL); } } if(recurse_level > 0) { // Delay delete until we are out of dispatch* } else { delete win; } } } } } if(recurse_level > 0) { delayed_cleanup->Append(Ecmd.Clone()); return; } // First pass, delete all top parents/windows of all linked objects // fprintf(stderr, "close port %x\r\n", Ecmd.port);fflush(stderr); for(int i=1; i < memenv->next; i++) { void * ptr = memenv->ref2ptr[i]; if(ptr) { ptrMap::iterator it = ptr2ref.find(ptr); if(it != ptr2ref.end()) { wxeRefData *refd = it->second; if(refd->alloc_in_erl && refd->type == 0) { parent = (wxWindow *) ptr; // fprintf(stderr, "window %x %d\r\n", (int) parent, refd->ref); while(parent->GetParent()) { parent = parent->GetParent(); // fprintf(stderr, " parent %x \r\n", (int) parent); } ptrMap::iterator pdata = ptr2ref.find(parent); if(pdata != ptr2ref.end()) { delete parent; } // else parent is already deleted } } else { // fprintf(stderr, "Error found no ref in %d => %x\r\n", i, ptr); } } } // Second pass delete everything else allocated // everything linked from windows should now be deleted for(int i=1; i < memenv->next; i++) { void * ptr = memenv->ref2ptr[i]; if(ptr) { ptrMap::iterator it = ptr2ref.find(ptr); if(it != ptr2ref.end()) { wxeRefData *refd = it->second; if(refd->alloc_in_erl) { if((refd->type == 8) && ((wxObject *)ptr)->IsKindOf(CLASSINFO(wxBufferedDC))) { ((wxBufferedDC *)ptr)->m_dc = NULL; // Workaround } wxString msg; bool cleanup_ref=true; if(refd->type == 0) { // Maybe also class 1 wxClassInfo *cinfo = ((wxObject *)ptr)->GetClassInfo(); msg.Printf(wxT("Memory leak: {wx_ref, %d, %s}"), refd->ref, cinfo->GetClassName()); send_msg("error", &msg); } else if(refd->type != 4) { cleanup_ref = delete_object(ptr, refd); } if(cleanup_ref) { // Delete refs for leaks and non overridden allocs delete refd; ptr2ref.erase(it); } // overridden allocs deletes meta-data in clearPtr } else { // Not alloced in erl just delete references if(refd->ref >= global_me->next) { // if it is not part of global ptrs delete refd; ptr2ref.erase(it); } } } } } // // Assert ? // for(ptrMap::iterator it = ptr2ref.begin(); it != ptr2ref.end(); it++) { // wxeRefData *refd = it->second; // if(refd->ref >= global_me->next) // fprintf(stderr, "L %d %d %d\r\n", refd->ref, refd->type, refd->alloc_in_erl); // } // fflush(stderr); enif_free(memenv->ref2ptr); enif_free_env(memenv->tmp_env); if(wxe_debug) enif_fprintf(stderr, "Deleting memenv %d\r\n", memenv); Ecmd.me_ref->memenv = NULL; enif_release_resource(Ecmd.me_ref); } wxeRefData * WxeApp::getRefData(void *ptr) { ptrMap::iterator it = ptr2ref.find(ptr); if(it != ptr2ref.end()) { wxeRefData *refd = it->second; return refd; } return NULL; } // wxeMemEnv * WxeApp::getMemEnv(ErlDrvTermData port) { // return refmap[port]; // } int WxeApp::newPtr(void * ptr, int type, wxeMemEnv *memenv) { int ref; intList free = memenv->free; if(free.IsEmpty()) { ref = memenv->next++; } else { ref = free.Pop(); }; if(ref >= memenv->max) { memenv->max *= 2; memenv->ref2ptr = (void **) enif_realloc(memenv->ref2ptr,memenv->max * sizeof(void*)); } memenv->ref2ptr[ref] = ptr; if(wxe_debug) { wxString msg; const wxChar *class_info = wxT("unknown"); if(type < 10) { wxClassInfo *cinfo = ((wxObject *)ptr)->GetClassInfo(); class_info = cinfo->GetClassName(); } msg.Printf(wxT("Creating {wx_ref, %d, %s} at %p "), ref, class_info, ptr); send_msg("debug", &msg); } ptr2ref[ptr] = new wxeRefData(ref, type, true, memenv); // fprintf(stderr, "ptr %x id %d\r\n", (int) ptr,ref); return ref; } int WxeApp::getRef(void * ptr, wxeMemEnv *memenv, int type) { if(!ptr) return 0; // NULL and zero is the same ptrMap::iterator it = ptr2ref.find(ptr); if(it != ptr2ref.end()) { wxeRefData *refd = it->second; if(refd->memenv == memenv || refd->memenv == global_me) { // Found it return return refd->ref; } // else // Old reference to deleted object, release old and recreate in current memenv. ptr2ref.erase(it); } int ref; intList free = memenv->free; if(free.IsEmpty()) { ref = memenv->next++; } else { ref = free.Pop(); }; if(ref >= memenv->max) { memenv->max *= 2; memenv->ref2ptr = (void **) enif_realloc(memenv->ref2ptr,memenv->max * sizeof(void*)); } memenv->ref2ptr[ref] = ptr; ptr2ref[ptr] = new wxeRefData(ref, type, false, memenv); return ref; } void WxeApp::clearPtr(void * ptr) { ptrMap::iterator it; it = ptr2ref.find(ptr); if(it != ptr2ref.end()) { wxeRefData *refd = it->second; intList free = refd->memenv->free; int ref = refd->ref; refd->memenv->ref2ptr[ref] = NULL; free.Append(ref); if(!enif_is_pid_undefined(&(refd->pid))) { // Send terminate pid to owner wxeReturn rt = wxeReturn(refd->memenv,refd->pid, false); rt.send(enif_make_tuple2(rt.env, rt.make_atom("_wxe_destroy_"), enif_make_pid(rt.env, &refd->pid))); enif_set_pid_undefined(&(refd->pid)); }; if(refd->type == 1 && ((wxObject*)ptr)->IsKindOf(CLASSINFO(wxSizer))) { wxSizerItemList list = ((wxSizer*)ptr)->GetChildren(); for(wxSizerItemList::compatibility_iterator node = list.GetFirst(); node; node = node->GetNext()) { wxSizerItem *item = node->GetData(); wxObject *content=NULL; if((content = item->GetWindow())) if(ptr2ref.end() == ptr2ref.find(content)) { wxString msg; wxClassInfo *cinfo = ((wxObject *)ptr)->GetClassInfo(); msg.Printf(wxT("Double usage detected of window at %p in sizer {wx_ref, %d, %s}"), content, ref, cinfo->GetClassName()); send_msg("error", &msg); ((wxSizer*)ptr)->Detach((wxWindow*)content); } if((content = item->GetSizer())) if(ptr2ref.end() == ptr2ref.find(content)) { wxString msg; wxClassInfo *cinfo = ((wxObject *)ptr)->GetClassInfo(); msg.Printf(wxT("Double usage detected of sizer at %p in sizer {wx_ref, %d, %s}"), content, ref, cinfo->GetClassName()); send_msg("error", &msg); ((wxSizer*)ptr)->Detach((wxSizer*)content); } } } delete refd; ptr2ref.erase(it); } } int WxeApp::registerPid(int index, ErlNifPid pid, wxeMemEnv * memenv) { void * temp = memenv->ref2ptr[index]; if((index < memenv->next) && ((index == 0) || (temp != (void *) NULL))) { ptrMap::iterator it; it = ptr2ref.find(temp); if(it != ptr2ref.end()) { wxeRefData *refd = it->second; refd->pid = pid; return 1; } }; return 0; }
30.132335
112
0.613399
[ "object" ]
29404843c8e0bdc3cbefd31622f85fcacf6ac3d8
11,513
cc
C++
extensions/browser/verified_contents.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
extensions/browser/verified_contents.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
extensions/browser/verified_contents.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// 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 "extensions/browser/verified_contents.h" #include <stddef.h> #include "base/base64url.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/strings/string_util.h" #include "base/values.h" #include "components/crx_file/id_util.h" #include "crypto/signature_verifier.h" #include "extensions/common/extension.h" using base::DictionaryValue; using base::ListValue; using base::Value; namespace { const char kBlockSizeKey[] = "block_size"; const char kContentHashesKey[] = "content_hashes"; const char kDescriptionKey[] = "description"; const char kFilesKey[] = "files"; const char kFormatKey[] = "format"; const char kHashBlockSizeKey[] = "hash_block_size"; const char kHeaderKidKey[] = "header.kid"; const char kItemIdKey[] = "item_id"; const char kItemVersionKey[] = "item_version"; const char kPathKey[] = "path"; const char kPayloadKey[] = "payload"; const char kProtectedKey[] = "protected"; const char kRootHashKey[] = "root_hash"; const char kSignatureKey[] = "signature"; const char kSignaturesKey[] = "signatures"; const char kSignedContentKey[] = "signed_content"; const char kTreeHashPerFile[] = "treehash per file"; const char kTreeHash[] = "treehash"; const char kWebstoreKId[] = "webstore"; // Helper function to iterate over a list of dictionaries, returning the // dictionary that has |key| -> |value| in it, if any, or NULL. DictionaryValue* FindDictionaryWithValue(const ListValue* list, const std::string& key, const std::string& value) { for (const auto& i : *list) { DictionaryValue* dictionary; if (!i->GetAsDictionary(&dictionary)) continue; std::string found_value; if (dictionary->GetString(key, &found_value) && found_value == value) return dictionary; } return NULL; } } // namespace namespace extensions { VerifiedContents::VerifiedContents(const uint8_t* public_key, int public_key_size) : public_key_(public_key), public_key_size_(public_key_size), valid_signature_(false), // Guilty until proven innocent. block_size_(0) {} VerifiedContents::~VerifiedContents() { } // The format of the payload json is: // { // "item_id": "<extension id>", // "item_version": "<extension version>", // "content_hashes": [ // { // "block_size": 4096, // "hash_block_size": 4096, // "format": "treehash", // "files": [ // { // "path": "foo/bar", // "root_hash": "<base64url encoded bytes>" // }, // ... // ] // } // ] // } bool VerifiedContents::InitFrom(const base::FilePath& path, bool ignore_invalid_signature) { std::string payload; if (!GetPayload(path, &payload, ignore_invalid_signature)) return false; std::unique_ptr<base::Value> value(base::JSONReader::Read(payload)); if (!value.get() || !value->IsType(Value::Type::DICTIONARY)) return false; DictionaryValue* dictionary = static_cast<DictionaryValue*>(value.get()); std::string item_id; if (!dictionary->GetString(kItemIdKey, &item_id) || !crx_file::id_util::IdIsValid(item_id)) return false; extension_id_ = item_id; std::string version_string; if (!dictionary->GetString(kItemVersionKey, &version_string)) return false; version_ = base::Version(version_string); if (!version_.IsValid()) return false; ListValue* hashes_list = NULL; if (!dictionary->GetList(kContentHashesKey, &hashes_list)) return false; for (size_t i = 0; i < hashes_list->GetSize(); i++) { DictionaryValue* hashes = NULL; if (!hashes_list->GetDictionary(i, &hashes)) return false; std::string format; if (!hashes->GetString(kFormatKey, &format) || format != kTreeHash) continue; int block_size = 0; int hash_block_size = 0; if (!hashes->GetInteger(kBlockSizeKey, &block_size) || !hashes->GetInteger(kHashBlockSizeKey, &hash_block_size)) return false; block_size_ = block_size; // We don't support using a different block_size and hash_block_size at // the moment. if (block_size_ != hash_block_size) return false; ListValue* files = NULL; if (!hashes->GetList(kFilesKey, &files)) return false; for (size_t j = 0; j < files->GetSize(); j++) { DictionaryValue* data = NULL; if (!files->GetDictionary(j, &data)) return false; std::string file_path_string; std::string encoded_root_hash; std::string root_hash; if (!data->GetString(kPathKey, &file_path_string) || !base::IsStringUTF8(file_path_string) || !data->GetString(kRootHashKey, &encoded_root_hash) || !base::Base64UrlDecode(encoded_root_hash, base::Base64UrlDecodePolicy::IGNORE_PADDING, &root_hash)) return false; base::FilePath file_path = base::FilePath::FromUTF8Unsafe(file_path_string); RootHashes::iterator i = root_hashes_.insert(std::make_pair( base::ToLowerASCII(file_path.value()), std::string())); i->second.swap(root_hash); } break; } return true; } bool VerifiedContents::HasTreeHashRoot( const base::FilePath& relative_path) const { base::FilePath::StringType path = base::ToLowerASCII( relative_path.NormalizePathSeparatorsTo('/').value()); return root_hashes_.find(path) != root_hashes_.end(); } bool VerifiedContents::TreeHashRootEquals(const base::FilePath& relative_path, const std::string& expected) const { base::FilePath::StringType path = base::ToLowerASCII( relative_path.NormalizePathSeparatorsTo('/').value()); for (RootHashes::const_iterator i = root_hashes_.find(path); i != root_hashes_.end(); ++i) { if (expected == i->second) return true; } return false; } // We're loosely following the "JSON Web Signature" draft spec for signing // a JSON payload: // // http://tools.ietf.org/html/draft-ietf-jose-json-web-signature-26 // // The idea is that you have some JSON that you want to sign, so you // base64-encode that and put it as the "payload" field in a containing // dictionary. There might be signatures of it done with multiple // algorithms/parameters, so the payload is followed by a list of one or more // signature sections. Each signature section specifies the // algorithm/parameters in a JSON object which is base64url encoded into one // string and put into a "protected" field in the signature. Then the encoded // "payload" and "protected" strings are concatenated with a "." in between // them and those bytes are signed and the resulting signature is base64url // encoded and placed in the "signature" field. To allow for extensibility, we // wrap this, so we can include additional kinds of payloads in the future. E.g. // [ // { // "description": "treehash per file", // "signed_content": { // "payload": "<base64url encoded JSON to sign>", // "signatures": [ // { // "protected": "<base64url encoded JSON with algorithm/parameters>", // "header": { // <object with metadata about this signature, eg a key identifier> // } // "signature": // "<base64url encoded signature over payload || . || protected>" // }, // ... <zero or more additional signatures> ... // ] // } // } // ] // There might be both a signature generated with a webstore private key and a // signature generated with the extension's private key - for now we only // verify the webstore one (since the id is in the payload, so we can trust // that it is for a given extension), but in the future we may validate using // the extension's key too (eg for non-webstore hosted extensions such as // enterprise installs). bool VerifiedContents::GetPayload(const base::FilePath& path, std::string* payload, bool ignore_invalid_signature) { std::string contents; if (!base::ReadFileToString(path, &contents)) return false; std::unique_ptr<base::Value> value(base::JSONReader::Read(contents)); if (!value.get() || !value->IsType(Value::Type::LIST)) return false; ListValue* top_list = static_cast<ListValue*>(value.get()); // Find the "treehash per file" signed content, e.g. // [ // { // "description": "treehash per file", // "signed_content": { // "signatures": [ ... ], // "payload": "..." // } // } // ] DictionaryValue* dictionary = FindDictionaryWithValue(top_list, kDescriptionKey, kTreeHashPerFile); DictionaryValue* signed_content = NULL; if (!dictionary || !dictionary->GetDictionaryWithoutPathExpansion(kSignedContentKey, &signed_content)) { return false; } ListValue* signatures = NULL; if (!signed_content->GetList(kSignaturesKey, &signatures)) return false; DictionaryValue* signature_dict = FindDictionaryWithValue(signatures, kHeaderKidKey, kWebstoreKId); if (!signature_dict) return false; std::string protected_value; std::string encoded_signature; std::string decoded_signature; if (!signature_dict->GetString(kProtectedKey, &protected_value) || !signature_dict->GetString(kSignatureKey, &encoded_signature) || !base::Base64UrlDecode(encoded_signature, base::Base64UrlDecodePolicy::IGNORE_PADDING, &decoded_signature)) return false; std::string encoded_payload; if (!signed_content->GetString(kPayloadKey, &encoded_payload)) return false; valid_signature_ = VerifySignature(protected_value, encoded_payload, decoded_signature); if (!valid_signature_ && !ignore_invalid_signature) return false; if (!base::Base64UrlDecode(encoded_payload, base::Base64UrlDecodePolicy::IGNORE_PADDING, payload)) return false; return true; } bool VerifiedContents::VerifySignature(const std::string& protected_value, const std::string& payload, const std::string& signature_bytes) { crypto::SignatureVerifier signature_verifier; if (!signature_verifier.VerifyInit( crypto::SignatureVerifier::RSA_PKCS1_SHA256, reinterpret_cast<const uint8_t*>(signature_bytes.data()), signature_bytes.size(), public_key_, public_key_size_)) { VLOG(1) << "Could not verify signature - VerifyInit failure"; return false; } signature_verifier.VerifyUpdate( reinterpret_cast<const uint8_t*>(protected_value.data()), protected_value.size()); std::string dot("."); signature_verifier.VerifyUpdate(reinterpret_cast<const uint8_t*>(dot.data()), dot.size()); signature_verifier.VerifyUpdate( reinterpret_cast<const uint8_t*>(payload.data()), payload.size()); if (!signature_verifier.VerifyFinal()) { VLOG(1) << "Could not verify signature - VerifyFinal failure"; return false; } return true; } } // namespace extensions
34.993921
80
0.652219
[ "object" ]
29414fae7a380b6e3f074bb2cac5c0ce5ea076ac
1,047
hpp
C++
src/reyes/Torus.hpp
cwbaker/sweet_render
259830adba09fabe4de2eef3537f4a95828965d3
[ "MIT" ]
null
null
null
src/reyes/Torus.hpp
cwbaker/sweet_render
259830adba09fabe4de2eef3537f4a95828965d3
[ "MIT" ]
null
null
null
src/reyes/Torus.hpp
cwbaker/sweet_render
259830adba09fabe4de2eef3537f4a95828965d3
[ "MIT" ]
null
null
null
#pragma once #include "Geometry.hpp" #include <math/vec2.hpp> #include <math/vec3.hpp> #include <math/mat4x4.hpp> #include <list> namespace reyes { class Grid; class Torus : public Geometry { float rmajor_; float rminor_; float phimin_; float phimax_; float thetamax_; public: Torus( float rmajor, float rminor, float phimin, float phimax, float thetamax ); Torus( const Torus& torus, const math::vec2& u_range, const math::vec2& v_range ); bool boundable() const override; void bound( const math::mat4x4& transform, math::vec3* minimum, math::vec3* maximum, Grid* grid ) const override; bool splittable() const override; void split( std::list<std::shared_ptr<Geometry>>* primitives ) const override; bool diceable() const override; void dice( const math::mat4x4& transform, int width, int height, Grid* grid ) const override; private: math::vec3 position( float u, float v ) const; math::vec3 normal( float u, float v ) const; }; }
26.846154
118
0.663801
[ "geometry", "transform" ]
294282eccfe44080b0ceaaebeae60c3359027165
2,976
cpp
C++
A3/polynomial.cpp
anish-sk/CS2810
982259146b210c201ea94ce5068c05c8471cbf30
[ "MIT" ]
null
null
null
A3/polynomial.cpp
anish-sk/CS2810
982259146b210c201ea94ce5068c05c8471cbf30
[ "MIT" ]
null
null
null
A3/polynomial.cpp
anish-sk/CS2810
982259146b210c201ea94ce5068c05c8471cbf30
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int maximum_degree = 22; class polynomial{ public: vector<double> coefficents; polynomial(){ coefficents = vector<double>(maximum_degree,0); } polynomial(int n){ coefficents = vector<double>(maximum_degree,0); for(int i=0;i<n;i++){ int x;double y; cin>>x>>y; //cout<<x<<" "<<y<<"\n"; coefficents[x]=y; //cout<<flush; } } void operator+(polynomial b){ for(int i=0;i<maximum_degree;i++){ coefficents[i]+=b.coefficents[i]; } print(); } void operator-(polynomial b){ for(int i=0;i<maximum_degree;i++){ coefficents[i]-=b.coefficents[i]; } print(); } void operator*(polynomial b){ polynomial p; for(int i=0;i<maximum_degree;i++){ for(int j=0;j<=i;j++){ p.coefficents[i]+=coefficents[j]*b.coefficents[i-j]; } } for(int i=0;i<maximum_degree;i++){ coefficents[i]=p.coefficents[i]; } print(); } double evaluate(double x){ double ans = 0; for(int i=maximum_degree-1;i>=0;i--){ ans = ans*x + coefficents[i]; } return ans; } void print(){ int f =1; for(int i=0;i<maximum_degree;i++){ if(coefficents[i]!=0){ if(f==1){ cout<<coefficents[i]<<"x^"<<i<<" "; f=0; } else{ if(coefficents[i]>0){ cout<<"+ "; } else{ cout<<"- "; } cout<<abs(coefficents[i])<<"x^"<<i<<" "; } } } cout<<"\n"; } }; int main(){ cout.precision(3); cout<<std::fixed; int n; cin>>n; while(n--){ char op; cin>>op; if(op=='a'){ int a,b; cin>>a; polynomial p1 = polynomial(a); cin>>b; polynomial p2 = polynomial(b); p1+p2; } else if(op=='s'){ int a,b; cin>>a; polynomial p1 = polynomial(a); cin>>b; polynomial p2 = polynomial(b); p1-p2; } else if(op=='m'){ int a,b; cin>>a; polynomial p1 = polynomial(a); cin>>b; polynomial p2 = polynomial(b); p1*p2; } else if(op=='e'){ double a; cin>>a; polynomial p1 = polynomial(a); cin>>a; //p1.print(); cout<<p1.evaluate(a)<<"\n"; } } return 0; }
25.878261
80
0.382392
[ "vector" ]
29431bce0bfeef599fa3b5e58c71b7a035019c9c
10,030
cpp
C++
TopGraph/extendedpersistence/extended_pers_11-28-2021ORIGINAL.cpp
mityanony404/TopGraph
23595ca5d3dfcd5bc5ebb771800e3fbe9a0d5eed
[ "MIT" ]
null
null
null
TopGraph/extendedpersistence/extended_pers_11-28-2021ORIGINAL.cpp
mityanony404/TopGraph
23595ca5d3dfcd5bc5ebb771800e3fbe9a0d5eed
[ "MIT" ]
null
null
null
TopGraph/extendedpersistence/extended_pers_11-28-2021ORIGINAL.cpp
mityanony404/TopGraph
23595ca5d3dfcd5bc5ebb771800e3fbe9a0d5eed
[ "MIT" ]
null
null
null
#include <iostream> #include <utility> #include <algorithm> #include <vector> #include <boost/graph/adjacency_list.hpp> #include <boost/graph/graph_traits.hpp> #include <boost/property_map/transform_value_property_map.hpp> #include <boost/property_map/function_property_map.hpp> #include <boost/graph/dijkstra_shortest_paths.hpp> #include <future> #include <torch/extension.h> #define EPS 1e-20 class union_find{ public: union_find(int n){ this->count = n; for(auto i=0; i<n; i++){ parent[i] = i; } } void make_set(int x){ this->parent[x] = x; count++; } int find(int x){ int tmp = x; while(parent[tmp] != tmp){ parent[tmp] = parent[parent[tmp]]; tmp = parent[tmp]; } return tmp; } // For now set parent[y] = x. Union by rank may come later. In that case we need to make sure the root is // always lower f value void link(int x, int y){ parent[y] = x; count--; } int num_connected_component() const{ return this->count; } private: std::map<int, int> parent; int count; }; using std::vector; using torch::Tensor; typedef std::pair<long, long> Edge; typedef std::pair<int, Edge> Pers; typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, boost::no_property, boost::property<boost::edge_weight_t, int>> Graph; typedef boost::graph_traits<Graph>::vertex_descriptor VertexDesc; typedef boost::graph_traits<Graph>::edge_descriptor EdgeDesc; typedef boost::graph_traits<Graph>::vertex_iterator VertexIter; typedef boost::graph_traits<Graph>::edge_iterator EdgeIter; using PathType = vector<vector<VertexDesc>>; using namespace torch::indexing; PathType find_path(int start, VertexDesc goal, const Graph& _graph) { vector<VertexDesc> p(num_vertices(_graph)); vector<int> d(num_vertices(_graph)); VertexDesc s = vertex(start, _graph); //auto idmap = boost::get(boost::vertex_index, _graph); //vector<VertexDesc> predecessors(boost::num_vertices(_graph), Graph::null_vertex()); //vector<int> distances(boost::num_vertices(_graph)); //boost::property_map<Graph, boost::edge_weight_t>::type weightmap = boost::get(boost::edge_weight, _graph); dijkstra_shortest_paths(_graph, s, boost::predecessor_map(&p[0]).distance_map(&d[0])); // extract path VertexDesc current = goal; PathType path { }; //PathType edge_path; do { auto const pred = p.at(current); //std::cout << "extract path: " << current << " " << _graph[current].coord << " <- " << pred << std::endl; if(current == pred) break; path.push_back({current, pred}); current = pred; } while(current != start); //std::reverse(path.begin(), path.end()); return path; } bool mycmp(Edge a, Edge b){ float a_val = std::max(a.first, a.second); float b_val = std::max(b.first, b.second); if (a_val < b_val) return true; else if(std::abs(a_val - b_val) < EPS) return a.second - b.second; return false; } bool vcmp(const vector<VertexDesc>& a, const vector<VertexDesc>& b){ float a_val = std::max(a[0], a[1]); float b_val = std::max(b[0], b[1]); if (a_val < b_val) return true; else if(std::abs(a_val - b_val) < EPS) return a[1] - b[1]; return false; } void print_pairs(vector<Pers> &ed) { for (auto e: ed) { std::cout << e.first << " (" << e.second.first << "," << e.second.second << ")" << std::endl; } } void print_path(const PathType& p){ for(auto v : p){ std::cout << "(" << v[0] << "," << v[1] << ")" << std::endl; } } struct CustomEdgeCompare { Tensor vert_fil; CustomEdgeCompare(const Tensor &vertex_filtration){ this->vert_fil = vertex_filtration; } bool operator()(const vector<VertexDesc>& a, const vector<VertexDesc>& b) const { double a_val = std::max(vert_fil[a[0]].item<double>(), vert_fil[a[1]].item<double>()); double b_val = std::max(vert_fil[b[0]].item<double>(), vert_fil[b[1]].item<double>()); if (a_val < b_val) return true; else if(std::abs(a_val - b_val) < EPS) return (vert_fil[a[1]] - vert_fil[b[1]]).item<int>(); return false; } }; vector<Tensor> compute_pd0(const Tensor & vertex_filtration, const vector<Tensor> & boundary_info){ auto num_nodes = vertex_filtration.size(0); union_find uf = union_find(num_nodes); Tensor tensor_edges = boundary_info[0]; Tensor edge_val = std::get<0>(torch::max(vertex_filtration.index({tensor_edges}), 1)); Tensor sorted_edge_indices = edge_val.argsort(-1,false); const Tensor sorted_edges = tensor_edges.index({sorted_edge_indices}); edge_val = edge_val.index({sorted_edge_indices}); auto num_edges = sorted_edges.size(0); vector<Tensor> pd_0; for(auto i = 0; i < num_edges; i++){ auto e = sorted_edges[i]; auto e_val = edge_val[i]; int u = e[0].item<int>(); int v = e[1].item<int>(); int root_u = uf.find(u); int root_v = uf.find(v); if(root_u == root_v){ continue; } int root = root_u; int merged = root_v; if (vertex_filtration[root].item<double>() > vertex_filtration[merged].item<double>()) std::swap(root, merged); else if (std::abs(vertex_filtration[root].item<double>() - vertex_filtration[merged].item<double>()) < EPS) { if (root > merged) std::swap(root, merged); } auto merged_val = vertex_filtration[merged]; //std::cout << "M: " << merged_val.item<double>() << " E: " << e_val.item<double>()<< std::endl; Tensor pd_pair = torch::stack({merged_val, e_val}); pd_0.emplace_back(pd_pair); uf.link(root, merged); } return pd_0; } vector<vector<Tensor>> extended_filt_persistence_single(const Tensor & vertex_filtration, const vector<Tensor> & boundary_info){ vector<vector<Tensor>> pd; auto num_nodes = vertex_filtration.size(0); union_find uf = union_find(num_nodes); Graph g; vector<size_t> pos_edge_index; vector<Tensor> pd_0_up = compute_pd0(vertex_filtration, boundary_info); vector<Tensor> pd_0_down, pd_1_rel, pd_1_ext; Tensor tensor_edges = boundary_info[0]; Tensor edge_val = std::get<0>(torch::min(vertex_filtration.index({tensor_edges}), 1)); Tensor sorted_edge_indices = edge_val.argsort(-1, true); const Tensor sorted_edges = tensor_edges.index({sorted_edge_indices}); edge_val = edge_val.index({sorted_edge_indices}); auto num_edges = sorted_edges.size(0); for(auto i = 0; i < num_edges; i++){ auto e = sorted_edges[i]; auto e_val = edge_val[i]; int u = e[0].item<int>(); int v = e[1].item<int>(); int root_u = uf.find(u); int root_v = uf.find(v); if(root_u == root_v){ pos_edge_index.push_back(i); continue; } boost::add_edge(u, v, 1, g); int root = root_u; int merged = root_v; if (vertex_filtration[root].item<double>() < vertex_filtration[merged].item<double>()) std::swap(root, merged); else if (std::abs(vertex_filtration[root].item<double>() - vertex_filtration[merged].item<double>()) < EPS) { if (root < merged) std::swap(root, merged); } auto merged_val = vertex_filtration[merged]; Tensor pd_pair = torch::stack({merged_val, e_val}); pd_0_down.emplace_back(pd_pair); uf.link(root, merged); } //pd.push_back(pd_0); Tensor min_max = torch::stack({vertex_filtration.min(), vertex_filtration.max()}); pd_1_rel.push_back(min_max); CustomEdgeCompare cmp = CustomEdgeCompare(vertex_filtration); for(auto ii : pos_edge_index){ auto pos_edge = sorted_edges[ii]; auto pos_edge_val = edge_val[ii]; int u = pos_edge[0].item<int>(); int v = pos_edge[1].item<int>(); PathType p = find_path(u, v, g); //std::cout << "Edge: " << u << " " << v << std::endl; //print_path(p); auto result = *std::max_element(p.begin(), p.end(), cmp); boost::remove_edge(result[0], result[1], g); //std::cout << "Removed edge: " << result[0] << " " << result[1] << std::endl; boost::add_edge(u, v, 1, g); auto cut_edge_tensor = torch::from_blob(result.data(), {2}, torch::TensorOptions().dtype(at::kLong)); auto cut_edge_val = vertex_filtration.index({cut_edge_tensor}).max(); //std::cout << "CE " << cut_edge_val.item<double>() << " AE " << pos_edge_val.item<double>() << std::endl; auto pers_pair = torch::stack({cut_edge_val, pos_edge_val}); pd_1_ext.push_back(pers_pair); } //pd.push_back(pd_1); pd.push_back(pd_0_up); pd.push_back(pd_0_down); pd.push_back(pd_1_rel); pd.push_back(pd_1_ext); return pd; } vector<vector<vector<Tensor>>> extended_filt_persistence_batch(const vector<std::tuple<Tensor, vector<Tensor>>> & batch){ auto futures = vector<std::future<vector<vector<Tensor>>>>(); for (auto & arg: batch){ futures.push_back( async(std::launch::async,[=]{ return extended_filt_persistence_single( std::get<0>(arg), std::get<1>(arg) ); } ) ); } auto ret = vector<vector<vector<Tensor>>>(); for (auto & fut: futures){ ret.push_back( fut.get() ); } return ret; } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("extended_persistence_batch", &extended_filt_persistence_batch, "A function to compute extended_persistence in batches as C-hofer"); m.def("extended_persistence_single", &extended_filt_persistence_single, "A function to compute extended_persistence with (v, [e]) format"); }
35.192982
146
0.613759
[ "vector" ]
2944feb0a107290aa1c3d5933df1bd78ca30abff
1,087
cpp
C++
UFO Shooter/EnemyController.cpp
MylerRL661/2D-Shooter-UFO-Game
f335cfb8f4dcc515de1d6227b624dc447bda28bb
[ "MIT" ]
1
2021-03-14T14:50:16.000Z
2021-03-14T14:50:16.000Z
UFO Shooter/EnemyController.cpp
MylerRL661/2D-Shooter-UFO-Game
f335cfb8f4dcc515de1d6227b624dc447bda28bb
[ "MIT" ]
null
null
null
UFO Shooter/EnemyController.cpp
MylerRL661/2D-Shooter-UFO-Game
f335cfb8f4dcc515de1d6227b624dc447bda28bb
[ "MIT" ]
null
null
null
#include "EnemyController.h" //constructor EnemyController::EnemyController() {} //deconstructor EnemyController::~EnemyController() {} void EnemyController::Init() {} void EnemyController::Add(int X, int Y, SDL_Renderer *arenderer) { //fast spawning if (c % 5000 == 0) { EnemyObj* TempBlock = new EnemyObj(); TempBlock->setColour(0, 204, 204); TempBlock->Init(X, Y, 25, 25, 1, arenderer); this->ListofEnemies.push_back(TempBlock); } } void EnemyController::Render(SDL_Renderer * aRenderer) { //render enemies for (auto& element : ListofEnemies) { //if alive render if (element->isDead != true) { element->Render(aRenderer); } } } void EnemyController::Update(double deltaTime) { c++; //add emeny to enemy list for (auto& element : ListofEnemies) { if (element->isDead != true) { element->Update(deltaTime); } } } void EnemyController::WindowSize(int Ht, int Wh) { //restarints of the window for (auto& element : ListofEnemies) { element->WindowSize(Ht, Wh); } }
17.253968
65
0.638454
[ "render" ]
2949884ac7fbe4e4a09c2b95c81888cad3608e15
44,158
cpp
C++
taichi/backends/opengl/codegen_opengl.cpp
yihong0618/taichi
1ff57c080edd0366a3cfb5174af131b6d94a2adc
[ "MIT" ]
2
2022-03-20T19:30:29.000Z
2022-03-20T19:30:34.000Z
taichi/backends/opengl/codegen_opengl.cpp
frostming/taichi
a866aad0835b4149a1a2328880f41adfc6646dae
[ "MIT" ]
null
null
null
taichi/backends/opengl/codegen_opengl.cpp
frostming/taichi
a866aad0835b4149a1a2328880f41adfc6646dae
[ "MIT" ]
null
null
null
//#define _GLSL_DEBUG 1 #include "codegen_opengl.h" #include <string> #include "taichi/backends/opengl/opengl_api.h" #include "taichi/backends/opengl/opengl_data_types.h" #include "taichi/backends/opengl/opengl_kernel_util.h" #include "taichi/ir/ir.h" #include "taichi/ir/statements.h" #include "taichi/ir/transforms.h" #include "taichi/util/file_sequence_writer.h" #include "taichi/util/line_appender.h" #include "taichi/util/macros.h" TLANG_NAMESPACE_BEGIN namespace opengl { namespace { namespace shaders { #define TI_INSIDE_OPENGL_CODEGEN #include "taichi/backends/opengl/shaders/atomics_macro_f32.glsl.h" #include "taichi/backends/opengl/shaders/runtime.h" #include "taichi/backends/opengl/shaders/listman.h" #include "taichi/backends/opengl/shaders/random.glsl.h" #include "taichi/backends/opengl/shaders/fast_pow.glsl.h" #include "taichi/backends/opengl/shaders/print.glsl.h" #include "taichi/backends/opengl/shaders/reduction.glsl.h" #undef TI_INSIDE_OPENGL_CODEGEN } // namespace shaders using irpass::ExternalPtrAccess; int find_children_id(const SNode *snode) { auto parent = snode->parent; for (int i = 0; i < parent->ch.size(); i++) { if (parent->ch[i].get() == snode) return i; } TI_ERROR("Child not found in parent!"); } std::string opengl_atomic_op_type_cap_name(AtomicOpType type) { static std::map<AtomicOpType, std::string> type_names; if (type_names.empty()) { #define REGISTER_TYPE(i, s) type_names[AtomicOpType::i] = "atomic" #s; REGISTER_TYPE(add, Add); REGISTER_TYPE(sub, Sub); // REGISTER_TYPE(mul, Mul); // REGISTER_TYPE(div, Div); REGISTER_TYPE(max, Max); REGISTER_TYPE(min, Min); REGISTER_TYPE(bit_and, And); REGISTER_TYPE(bit_or, Or); REGISTER_TYPE(bit_xor, Xor); #undef REGISTER_TYPE } return type_names[type]; } class KernelGen : public IRVisitor { public: KernelGen(Kernel *kernel, const StructCompiledResult *struct_compiled, const std::string &kernel_name) : kernel_(kernel), kernel_name_(kernel_name), struct_compiled_(struct_compiled), root_snode_type_name_(struct_compiled->root_snode_type_name), glsl_kernel_prefix_(kernel_name) { compiled_program_.init_args(kernel); allow_undefined_visitor = true; invoke_default_visitor = true; } private: const Kernel *kernel_; const StructCompiledResult *struct_compiled_; std::string kernel_name_; std::string root_snode_type_name_; std::string glsl_kernel_prefix_; GetRootStmt *root_stmt_; int glsl_kernel_count_{0}; bool is_top_level_{true}; CompiledProgram compiled_program_; UsedFeature used; // TODO: is this actually per-offload? // per-offload variables: LineAppender line_appender_; LineAppender line_appender_header_; std::string glsl_kernel_name_; int num_workgroups_{1}; int workgroup_size_{1}; bool used_tls; // TODO: move into UsedFeature? std::unordered_map<int, irpass::ExternalPtrAccess> extptr_access; template <typename... Args> void emit(std::string f, Args &&... args) { line_appender_.append(std::move(f), std::move(args)...); } void generate_header() { emit("const float inf = 1.0f / 0.0f;"); emit("const float nan = 0.0f / 0.0f;"); } // Note that the following two functions not only returns the corresponding // data type, but also **records** the usage of data types to UsedFeatures. std::string opengl_data_type_short_name(DataType dt) { if (dt->is_primitive(PrimitiveTypeID::i64) || dt->is_primitive(PrimitiveTypeID::u64)) { if (!TI_OPENGL_REQUIRE(used, GL_ARB_gpu_shader_int64)) { TI_ERROR( "Extension GL_ARB_gpu_shader_int64 not supported on your OpenGL"); } } if (dt->is_primitive(PrimitiveTypeID::f32)) used.float32 = true; if (dt->is_primitive(PrimitiveTypeID::f64)) used.float64 = true; if (dt->is_primitive(PrimitiveTypeID::i32)) used.int32 = true; if (dt->is_primitive(PrimitiveTypeID::i64)) used.int64 = true; if (dt->is_primitive(PrimitiveTypeID::u32)) used.uint32 = true; if (dt->is_primitive(PrimitiveTypeID::u64)) used.uint64 = true; return data_type_name(dt); } std::string opengl_data_type_name(DataType dt) { return opengl::opengl_data_type_name(dt); } void generate_bottom() { // TODO(archibate): <kernel_name>() really necessary? How about just main()? emit("void main()"); emit("{{"); if (used.random) emit(" _init_rand();"); if (glsl_kernel_name_.size()) emit(" {}();", glsl_kernel_name_); emit("}}"); // clang-format off if (used.print) // the runtime buffer is only used for print now.. line_appender_header_.append_raw(shaders::kOpenGlRuntimeSourceCode); if (used.listman) line_appender_header_.append_raw(shaders::kOpenGLListmanSourceCode); std::string kernel_header; #define DEFINE_LAYOUT(layout, restype, name, id, dt, dtype) \ kernel_header += "layout("#layout", binding = " + fmt::format("{}", id) \ + ") " #restype " " #name "_" #dt " { " #dtype " _" \ #name "_" #dt "_[]; };\n" #define REGISTER_BUFFER(layout, restype, name, id) do { \ if (used.int32) DEFINE_LAYOUT(layout, restype, name, id, i32, int); \ if (used.int64) DEFINE_LAYOUT(layout, restype, name, id, i64, int64_t); \ if (used.uint32) DEFINE_LAYOUT(layout, restype, name, id, u32, uint); \ if (used.uint64) DEFINE_LAYOUT(layout, restype, name, id, u64, uint64_t); \ if (used.float32) DEFINE_LAYOUT(layout, restype, name, id, f32, float); \ if (used.float64) DEFINE_LAYOUT(layout, restype, name, id, f64, double); \ } while (0) REGISTER_BUFFER(std430, buffer, data, GLBufId::Root); if (used.buf_gtmp) REGISTER_BUFFER(std430, buffer, gtmp, GLBufId::Gtmp); if (used.buf_args) REGISTER_BUFFER(std430, readonly buffer, args, GLBufId::Args); if (used.buf_retr) REGISTER_BUFFER(std430, writeonly buffer, retr, GLBufId::Retr); if (used.buf_extr) { bool write = false; bool read = false; for (auto pair : this->extptr_access) { write |= (pair.second & irpass::ExternalPtrAccess::WRITE) != irpass::ExternalPtrAccess::NONE; read |= (pair.second & irpass::ExternalPtrAccess::WRITE) != irpass::ExternalPtrAccess::NONE; } if (write && !read) { REGISTER_BUFFER(std430, writeonly buffer, extr, GLBufId::Extr); } else if (!write && read) { REGISTER_BUFFER(std430, readonly buffer, extr, GLBufId::Extr); } else { REGISTER_BUFFER(std430, buffer, extr, GLBufId::Extr); } } #undef REGISTER_BUFFER #undef DEFINE_LAYOUT // clang-format on if (used.simulated_atomic_float) { line_appender_header_.append_raw(shaders::kOpenGLAtomicF32SourceCode); kernel_header += ("DEFINE_ATOMIC_F32_FUNCTIONS(data);\n"); if (used.buf_gtmp) { kernel_header += ("DEFINE_ATOMIC_F32_FUNCTIONS(gtmp);\n"); } if (used.buf_extr) { kernel_header += ("DEFINE_ATOMIC_F32_FUNCTIONS(extr);\n"); } } if (used.reduction) { line_appender_header_.append_raw(shaders::kOpenGLReductionCommon); line_appender_header_.append_raw(shaders::kOpenGLReductionSourceCode); kernel_header += ("DEFINE_REDUCTION_FUNCTIONS(add, float);\n"); kernel_header += ("DEFINE_REDUCTION_FUNCTIONS(max, float);\n"); kernel_header += ("DEFINE_REDUCTION_FUNCTIONS(min, float);\n"); kernel_header += ("DEFINE_REDUCTION_FUNCTIONS(add, int);\n"); kernel_header += ("DEFINE_REDUCTION_FUNCTIONS(max, int);\n"); kernel_header += ("DEFINE_REDUCTION_FUNCTIONS(min, int);\n"); kernel_header += ("DEFINE_REDUCTION_FUNCTIONS(add, uint);\n"); kernel_header += ("DEFINE_REDUCTION_FUNCTIONS(max, uint);\n"); kernel_header += ("DEFINE_REDUCTION_FUNCTIONS(min, uint);\n"); } line_appender_header_.append_raw(kernel_header); if (used.random) { line_appender_header_.append_raw(shaders::kOpenGLRandomSourceCode); } if (used.fast_pow) { line_appender_header_.append_raw(shaders::kOpenGLFastPowSourceCode); } if (used.print) { line_appender_header_.append_raw(shaders::kOpenGLPrintSourceCode); } std::string extensions = ""; #define PER_OPENGL_EXTENSION(x) \ if (used.extension_##x) \ extensions += "#extension " #x ": enable\n"; #include "taichi/inc/opengl_extension.inc.h" #undef PER_OPENGL_EXTENSION auto kernel_src_code = "#version 430 core\n" + extensions + "precision highp float;\n" + line_appender_header_.lines() + line_appender_.lines(); compiled_program_.add(std::move(glsl_kernel_name_), kernel_src_code, num_workgroups_, workgroup_size_, &this->extptr_access); auto &config = kernel_->program->config; if (config.print_kernel_llvm_ir) { static FileSequenceWriter writer("shader{:04d}.comp", "OpenGL compute shader"); writer.write(kernel_src_code); } line_appender_header_.clear_all(); line_appender_.clear_all(); num_workgroups_ = 1; num_workgroups_ = 1; } void visit(Block *stmt) override { if (!is_top_level_) line_appender_.push_indent(); for (auto &s : stmt->statements) { s->accept(this); } if (!is_top_level_) line_appender_.pop_indent(); } virtual void visit(Stmt *stmt) override { TI_ERROR("[glsl] unsupported statement type {}", typeid(*stmt).name()); } void visit(PrintStmt *stmt) override { used.print = true; int size = stmt->contents.size(); if (size > MAX_CONTENTS_PER_MSG) { TI_WARN("[glsl] printing too much contents: {} > {}, clipping", size, MAX_CONTENTS_PER_MSG); } auto msgid_name = fmt::format("_mi_{}", stmt->short_name()); emit("int {} = atomicAdd(_msg_count_, 1);", msgid_name); emit("{} %= {};", msgid_name, MAX_MESSAGES); for (int i = 0; i < size; i++) { auto const &content = stmt->contents[i]; if (std::holds_alternative<Stmt *>(content)) { auto arg_stmt = std::get<Stmt *>(content); emit("_msg_set_{}({}, {}, {});", opengl_data_type_short_name(arg_stmt->ret_type), msgid_name, i, arg_stmt->short_name()); } else { auto str = std::get<std::string>(content); int stridx = compiled_program_.lookup_or_add_string(str); emit("_msg_set_str({}, {}, {});", msgid_name, i, stridx); } } emit("_msg_set_end({}, {});", msgid_name, size); } void visit(RandStmt *stmt) override { used.random = true; // since random generator uses _gtmp_i32_ as rand state: used.buf_gtmp = true; used.int32 = true; emit("{} {} = _rand_{}();", opengl_data_type_name(stmt->ret_type), stmt->short_name(), opengl_data_type_short_name(stmt->ret_type)); } void visit(LinearizeStmt *stmt) override { std::string val = "0"; for (int i = 0; i < (int)stmt->inputs.size(); i++) { val = fmt::format("({} * {} + {})", val, stmt->strides[i], stmt->inputs[i]->short_name()); } emit("int {} = {};", stmt->short_name(), val); } void visit(BitExtractStmt *stmt) override { TI_WARN( "BitExtractStmt visited. It should have been taken care of by the " "demote_operations pass."); emit("int {} = (({} >> {}) & ((1 << {}) - 1));", stmt->short_name(), stmt->input->short_name(), stmt->bit_begin, stmt->bit_end - stmt->bit_begin); } void visit(GetRootStmt *stmt) override { // Should we assert |root_stmt_| is assigned only once? root_stmt_ = stmt; emit("int {} = 0;", stmt->short_name()); } void visit(SNodeLookupStmt *stmt) override { Stmt *parent; std::string parent_type; if (stmt->input_snode) { parent = stmt->input_snode; parent_type = stmt->snode->node_type_name; } else { TI_ASSERT(root_stmt_ != nullptr); parent = root_stmt_; parent_type = root_snode_type_name_; } emit("int {} = {} + {} * {}; // {}", stmt->short_name(), parent->short_name(), struct_compiled_->snode_map.at(parent_type).elem_stride, stmt->input_index->short_name(), stmt->snode->node_type_name); if (stmt->activate) { if (stmt->snode->type == SNodeType::dense) { // do nothing } else if (stmt->snode->type == SNodeType::dynamic) { used.int32 = true; emit("atomicMax(_data_i32_[{} >> 2], {} + 1); // dynamic activate", get_snode_meta_address(stmt->snode), stmt->input_index->short_name()); } else { TI_NOT_IMPLEMENTED } } } void visit(SNodeOpStmt *stmt) override { // IAPR? if (stmt->op_type == SNodeOpType::activate) { if (stmt->snode->type == SNodeType::dense || stmt->snode->type == SNodeType::root) { // do nothing } else if (stmt->snode->type == SNodeType::dynamic) { used.int32 = true; emit("atomicMax(_data_i32_[{} >> 2], {} + 1); // dynamic activate", get_snode_meta_address(stmt->snode), stmt->val->short_name()); } else { TI_NOT_IMPLEMENTED } } else if (stmt->op_type == SNodeOpType::deactivate) { if (stmt->snode->type == SNodeType::dense || stmt->snode->type == SNodeType::root) { // do nothing } else if (stmt->snode->type == SNodeType::dynamic) { used.int32 = true; emit("_data_i32_[{} >> 2] = 0; // dynamic deactivate", get_snode_meta_address(stmt->snode), stmt->val->short_name()); } else { TI_NOT_IMPLEMENTED } } else if (stmt->op_type == SNodeOpType::is_active) { TI_ASSERT(stmt->ret_type->is_primitive(PrimitiveTypeID::i32)); if (stmt->snode->type == SNodeType::dense || stmt->snode->type == SNodeType::root) { emit("int {} = 1;", stmt->short_name()); } else if (stmt->snode->type == SNodeType::dynamic) { used.int32 = true; emit("int {} = int({} < _data_i32_[{} >> 2]);", stmt->short_name(), stmt->val->short_name(), get_snode_meta_address(stmt->snode)); } else { TI_NOT_IMPLEMENTED } } else if (stmt->op_type == SNodeOpType::append) { TI_ASSERT(stmt->snode->type == SNodeType::dynamic); TI_ASSERT(stmt->ret_type->is_primitive(PrimitiveTypeID::i32)); used.int32 = true; emit("int {} = atomicAdd(_data_i32_[{} >> 2], 1);", stmt->short_name(), get_snode_meta_address(stmt->snode)); auto dt = stmt->val->element_type(); emit("int _ad_{} = {} + {} * {};", stmt->short_name(), get_snode_base_address(stmt->snode), stmt->short_name(), struct_compiled_->snode_map.at(stmt->snode->node_type_name) .elem_stride); emit("_data_{}_[_ad_{} >> {}] = {};", opengl_data_type_short_name(dt), stmt->short_name(), opengl_data_address_shifter(dt), stmt->val->short_name()); } else if (stmt->op_type == SNodeOpType::length) { TI_ASSERT(stmt->snode->type == SNodeType::dynamic); TI_ASSERT(stmt->ret_type->is_primitive(PrimitiveTypeID::i32)); used.int32 = true; emit("int {} = _data_i32_[{} >> 2];", stmt->short_name(), get_snode_meta_address(stmt->snode)); } else { TI_NOT_IMPLEMENTED } } std::map<int, std::string> ptr_signats; void visit(GetChStmt *stmt) override { emit("int {} = {} + {}; // {}", stmt->short_name(), stmt->input_ptr->short_name(), struct_compiled_->snode_map.at(stmt->input_snode->node_type_name) .children_offsets[stmt->chid], stmt->output_snode->node_type_name); if (stmt->output_snode->is_place()) ptr_signats[stmt->id] = "data"; } void visit(GlobalStoreStmt *stmt) override { TI_ASSERT(stmt->width() == 1); auto dt = stmt->val->element_type(); emit("_{}_{}_[{} >> {}] = {};", ptr_signats.at(stmt->dest->id), // throw out_of_range if not a pointer opengl_data_type_short_name(dt), stmt->dest->short_name(), opengl_data_address_shifter(dt), stmt->val->short_name()); } void visit(GlobalLoadStmt *stmt) override { TI_ASSERT(stmt->width() == 1); auto dt = stmt->element_type(); emit("{} {} = _{}_{}_[{} >> {}];", opengl_data_type_name(stmt->element_type()), stmt->short_name(), ptr_signats.at(stmt->src->id), opengl_data_type_short_name(dt), stmt->src->short_name(), opengl_data_address_shifter(dt)); } void visit(ExternalPtrStmt *stmt) override { TI_ASSERT(stmt->width() == 1); const auto linear_index_name = fmt::format("_li_{}", stmt->short_name()); emit("int {} = 0;", linear_index_name); emit("{{ // linear seek"); { ScopedIndent _s(line_appender_); const auto *argload = stmt->base_ptrs[0]->as<ArgLoadStmt>(); const int arg_id = argload->arg_id; const int num_indices = stmt->indices.size(); std::vector<std::string> size_var_names; for (int i = 0; i < num_indices; i++) { used.buf_args = true; used.int32 = true; std::string var_name = fmt::format("_s{}_{}", i, stmt->short_name()); emit("int {} = _args_i32_[{} + {} * {} + {}];", var_name, taichi_opengl_earg_base / sizeof(int), arg_id, taichi_max_num_indices, i); size_var_names.push_back(std::move(var_name)); } for (int i = 0; i < num_indices; i++) { emit("{} *= {};", linear_index_name, size_var_names[i]); emit("{} += {};", linear_index_name, stmt->indices[i]->short_name()); } } emit("}}"); emit("int {} = {} + ({} << {});", stmt->short_name(), stmt->base_ptrs[0]->short_name(), linear_index_name, opengl_data_address_shifter(stmt->base_ptrs[0]->element_type())); used.buf_extr = true; ptr_signats[stmt->id] = "extr"; } void visit(UnaryOpStmt *stmt) override { auto dt_name = opengl_data_type_name(stmt->element_type()); if (stmt->op_type == UnaryOpType::logic_not) { emit("{} {} = {}({} == 0);", dt_name, stmt->short_name(), dt_name, stmt->operand->short_name()); } else if (stmt->op_type == UnaryOpType::neg) { emit("{} {} = {}(-{});", dt_name, stmt->short_name(), dt_name, stmt->operand->short_name()); } else if (stmt->op_type == UnaryOpType::rsqrt) { emit("{} {} = {}(inversesqrt({}));", dt_name, stmt->short_name(), dt_name, stmt->operand->short_name()); } else if (stmt->op_type == UnaryOpType::sgn) { emit("{} {} = {}(sign({}));", dt_name, stmt->short_name(), dt_name, stmt->operand->short_name()); } else if (stmt->op_type == UnaryOpType::bit_not) { emit("{} {} = {}(~{});", dt_name, stmt->short_name(), dt_name, stmt->operand->short_name()); } else if (stmt->op_type == UnaryOpType::cast_value) { emit("{} {} = {}({});", dt_name, stmt->short_name(), opengl_data_type_name(stmt->cast_type), stmt->operand->short_name()); } else if (stmt->op_type == UnaryOpType::cast_bits) { constexpr int FLOATING_POINT = 0; constexpr int SIGNED_INTEGER = 1; constexpr int UNSIGNED_INTEGER = 2; auto dst_type = stmt->cast_type; auto src_type = stmt->operand->element_type(); auto dst_type_id = FLOATING_POINT; if (is_integral(dst_type)) dst_type_id = is_unsigned(dst_type) ? UNSIGNED_INTEGER : SIGNED_INTEGER; auto src_type_id = FLOATING_POINT; if (is_integral(src_type)) src_type_id = is_unsigned(src_type) ? UNSIGNED_INTEGER : SIGNED_INTEGER; TI_ASSERT_INFO( data_type_size(dst_type) == data_type_size(src_type), "bit_cast is only supported between data type with same size"); if (dst_type_id != FLOATING_POINT && src_type_id != FLOATING_POINT) { emit("{} {} = {}({});", dt_name, stmt->short_name(), dt_name, stmt->operand->short_name()); } else if (dst_type_id == FLOATING_POINT && src_type_id == SIGNED_INTEGER) { emit("{} {} = intBitsToFloat({});", dt_name, stmt->short_name(), stmt->operand->short_name()); } else if (dst_type_id == SIGNED_INTEGER && src_type_id == FLOATING_POINT) { emit("{} {} = floatBitsToInt({});", dt_name, stmt->short_name(), stmt->operand->short_name()); } else if (dst_type_id == FLOATING_POINT && src_type_id == UNSIGNED_INTEGER) { emit("{} {} = uintBitsToFloat({});", dt_name, stmt->short_name(), stmt->operand->short_name()); } else if (dst_type_id == UNSIGNED_INTEGER && src_type_id == FLOATING_POINT) { emit("{} {} = floatBitsToUint({});", dt_name, stmt->short_name(), stmt->operand->short_name()); } else { TI_ERROR("[glsl] unsupported bit cast from {} to {}", data_type_name(src_type), data_type_name(dst_type)); } } else { emit("{} {} = {}({}({}));", dt_name, stmt->short_name(), dt_name, unary_op_type_name(stmt->op_type), stmt->operand->short_name()); } } void visit(BinaryOpStmt *bin) override { const auto dt_name = opengl_data_type_name(bin->element_type()); const auto lhs_name = bin->lhs->short_name(); const auto rhs_name = bin->rhs->short_name(); const auto bin_name = bin->short_name(); if (bin->op_type == BinaryOpType::floordiv) { TI_WARN("floordiv called! It should be taken care by demote_operations"); if (is_integral(bin->lhs->element_type()) && is_integral(bin->rhs->element_type())) { emit( "{} {} = {}(sign({}) * {} >= 0 ? abs({}) / abs({}) : sign({}) * " "(abs({}) + abs({}) - 1) / {});", dt_name, bin_name, dt_name, lhs_name, rhs_name, lhs_name, rhs_name, lhs_name, lhs_name, rhs_name, rhs_name); return; } // NOTE: the 1e-6 here is for precision reason, or `7 // 7` will obtain 0 // instead of 1 emit( "{} {} = {}(floor((float({}) * (1 + sign({} * {}) * 1e-6)) / " "float({})));", dt_name, bin_name, dt_name, lhs_name, lhs_name, rhs_name, rhs_name); return; } else if (bin->op_type == BinaryOpType::mod) { // NOTE: the GLSL built-in function `mod()` is a pythonic mod: x - y * // floor(x / y) emit("{} {} = {} - {} * int({} / {});", dt_name, bin_name, lhs_name, rhs_name, lhs_name, rhs_name); return; } else if (bin->op_type == BinaryOpType::atan2) { if (bin->element_type() == PrimitiveType::f64) { // don't know why no atan(double, double) emit("{} {} = {}(atan(float({}), float({})));", dt_name, bin_name, dt_name, lhs_name, rhs_name); } else { emit("{} {} = atan({}, {});", dt_name, bin_name, lhs_name, rhs_name); } return; } else if (bin->op_type == BinaryOpType::pow && is_integral(bin->rhs->element_type())) { // The GLSL `pow` is not so percise for `int`... e.g.: `pow(5, 3)` obtains // 124 So that we have to use some hack to make it percise. Discussion: // https://github.com/taichi-dev/taichi/pull/943#issuecomment-626354902 emit("{} {} = {}(fast_pow_{}({}, {}));", dt_name, bin_name, dt_name, opengl_data_type_short_name(bin->lhs->element_type()), lhs_name, rhs_name); used.fast_pow = true; return; } const auto binop = binary_op_type_symbol(bin->op_type); if (is_opengl_binary_op_infix(bin->op_type)) { if (is_opengl_binary_op_different_return_type(bin->op_type) || bin->element_type() != bin->lhs->element_type() || bin->element_type() != bin->rhs->element_type()) { if (is_comparison(bin->op_type)) { // TODO(#577): Taichi uses -1 as true due to LLVM i1... See // https://github.com/taichi-dev/taichi/blob/6989c0e21d437a9ffdc0151cee9d3aa2aaa2241d/taichi/codegen/codegen_llvm.cpp#L564 // This is a workaround to make OpenGL compatible with the behavior. emit("{} {} = -{}({} {} {});", dt_name, bin_name, dt_name, lhs_name, binop, rhs_name); } else { emit("{} {} = {}({} {} {});", dt_name, bin_name, dt_name, lhs_name, binop, rhs_name); } } else { emit("{} {} = {} {} {};", dt_name, bin_name, lhs_name, binop, rhs_name); } } else { // This is a function call emit("{} {} = {}({}({}, {}));", dt_name, bin_name, dt_name, binop, lhs_name, rhs_name); } } void visit(AtomicOpStmt *stmt) override { TI_ASSERT(stmt->width() == 1); auto dt = stmt->dest->element_type().ptr_removed(); auto val_name = stmt->val->short_name(); emit("{} {};", opengl_data_type_name(stmt->val->element_type()), stmt->short_name()); if (stmt->is_reduction && (dt->is_primitive(PrimitiveTypeID::f32) || dt->is_primitive(PrimitiveTypeID::i32) || dt->is_primitive(PrimitiveTypeID::u32)) && (stmt->op_type == AtomicOpType::add || stmt->op_type == AtomicOpType::sub || stmt->op_type == AtomicOpType::min || stmt->op_type == AtomicOpType::max)) { used.reduction = true; val_name = stmt->short_name() + "_reduction"; auto op_name = ""; if (stmt->op_type == AtomicOpType::sub || stmt->op_type == AtomicOpType::add) { op_name = "add"; } else if (stmt->op_type == AtomicOpType::max) { op_name = "max"; } else if (stmt->op_type == AtomicOpType::min) { op_name = "min"; } emit("{} {} = reduction_workgroup_{}_{}({});", opengl_data_type_name(stmt->val->element_type()), val_name, op_name, opengl_data_type_name(stmt->val->element_type()), stmt->val->short_name()); emit("if (gl_LocalInvocationIndex == 0)"); } emit("{{ // Begin Atomic Op"); if (dt->is_primitive(PrimitiveTypeID::i32) || (TI_OPENGL_REQUIRE(used, GL_NV_shader_atomic_int64) && dt->is_primitive(PrimitiveTypeID::i64)) || ((stmt->op_type == AtomicOpType::add || stmt->op_type == AtomicOpType::sub) && ((TI_OPENGL_REQUIRE(used, GL_NV_shader_atomic_float) && dt->is_primitive(PrimitiveTypeID::f32)) || (TI_OPENGL_REQUIRE(used, GL_NV_shader_atomic_float64) && dt->is_primitive(PrimitiveTypeID::f64))))) { emit("{} = {}(_{}_{}_[{} >> {}], {});", stmt->short_name(), opengl_atomic_op_type_cap_name(stmt->op_type), ptr_signats.at(stmt->dest->id), opengl_data_type_short_name(dt), stmt->dest->short_name(), opengl_data_address_shifter(dt), val_name); } else { if (dt != PrimitiveType::f32) { TI_ERROR( "unsupported atomic operation for PrimitiveType::{}, " "this may because your OpenGL is missing that extension, " "see `glewinfo` for more details", opengl_data_type_short_name(dt)); } used.simulated_atomic_float = true; used.int32 = true; // since simulated atomics are based on _data_i32_ emit("{} = {}_{}_{}({} >> {}, {});", stmt->short_name(), opengl_atomic_op_type_cap_name(stmt->op_type), ptr_signats.at(stmt->dest->id), opengl_data_type_short_name(dt), stmt->dest->short_name(), opengl_data_address_shifter(dt), val_name); } emit("}} // End Atomic Op"); } void visit(TernaryOpStmt *tri) override { TI_ASSERT(tri->op_type == TernaryOpType::select); emit("{} {} = {} != 0 ? {} : {};", opengl_data_type_name(tri->element_type()), tri->short_name(), tri->op1->short_name(), tri->op2->short_name(), tri->op3->short_name()); } void visit(LocalLoadStmt *stmt) override { bool linear_index = true; for (int i = 0; i < (int)stmt->src.size(); i++) { if (stmt->src[i].offset != i) { linear_index = false; } } if (stmt->same_source() && linear_index && stmt->width() == stmt->src[0].var->width()) { auto src = stmt->src[0].var; emit("{} {} = {};", opengl_data_type_name(stmt->element_type()), stmt->short_name(), src->short_name()); } else { TI_NOT_IMPLEMENTED; } } void visit(LocalStoreStmt *stmt) override { emit("{} = {};", stmt->dest->short_name(), stmt->val->short_name()); } void visit(AllocaStmt *alloca) override { auto dt_name = opengl_data_type_name(alloca->element_type()); emit("{} {} = {}(0);", dt_name, alloca->short_name(), dt_name); } void visit(ConstStmt *const_stmt) override { TI_ASSERT(const_stmt->width() == 1); auto dt_name = opengl_data_type_name(const_stmt->element_type()); emit("{} {} = {}({});", dt_name, const_stmt->short_name(), dt_name, const_stmt->val[0].stringify()); } void visit(ReturnStmt *stmt) override { used.buf_retr = true; // TODO: use stmt->ret_id instead of 0 as index emit("_retr_{}_[0] = {};", opengl_data_type_short_name(stmt->element_type()), stmt->value->short_name()); } void visit(ArgLoadStmt *stmt) override { const auto dt = opengl_data_type_name(stmt->element_type()); used.buf_args = true; if (stmt->is_ptr) { used.int32 = true; emit("int {} = _args_i32_[{} << 1]; // is ext pointer {}", stmt->short_name(), stmt->arg_id, dt); } else { emit("{} {} = _args_{}_[{} << {}];", dt, stmt->short_name(), opengl_data_type_short_name(stmt->element_type()), stmt->arg_id, opengl_argument_address_shifter(stmt->element_type())); } } void visit(ExternalFuncCallStmt *stmt) override { TI_ASSERT(!stmt->func); auto format = stmt->source; std::string source; for (int i = 0; i < format.size(); i++) { char c = format[i]; if (c == '%' || c == '$') { // '$' for output, '%' for input int num = 0; while (i < format.size()) { i += 1; if (!::isdigit(format[i])) { i -= 1; break; } num *= 10; num += format[i] - '0'; } auto args = (c == '%') ? stmt->arg_stmts : stmt->output_stmts; TI_ASSERT_INFO(num < args.size(), "{}{} out of {} argument range {}", c, num, ((c == '%') ? "input" : "output"), args.size()); source += args[num]->short_name(); } else { source.push_back(c); } } emit("{};", source); } void visit(ExternalTensorShapeAlongAxisStmt *stmt) override { const auto name = stmt->short_name(); const auto arg_id = stmt->arg_id; const auto axis = stmt->axis; used.buf_args = true; used.int32 = true; emit("int {} = _args_i32_[{} + {} * {} + {}];", name, taichi_opengl_earg_base / sizeof(int), arg_id, taichi_max_num_indices, axis); } std::string make_kernel_name() { return fmt::format("{}{}", glsl_kernel_prefix_, glsl_kernel_count_++); } void generate_serial_kernel(OffloadedStmt *stmt) { TI_ASSERT(stmt->task_type == OffloadedStmt::TaskType::serial); const std::string glsl_kernel_name = make_kernel_name(); this->glsl_kernel_name_ = glsl_kernel_name; emit("void {}()", glsl_kernel_name); emit("{{ // serial"); stmt->body->accept(this); emit("}}\n"); } void generate_grid_stride_loop_header() { ScopedIndent _s(line_appender_); } struct ScopedGridStrideLoop { KernelGen *gen; std::unique_ptr<ScopedIndent> s; ScopedGridStrideLoop(KernelGen *gen, int const_iterations) : ScopedGridStrideLoop(gen, fmt::format("{}", const_iterations), const_iterations) { } ScopedGridStrideLoop(KernelGen *gen, std::string iterations, int const_iterations = -1) : gen(gen) { gen->emit("int _sid0 = int(gl_GlobalInvocationID.x);"); gen->emit("for (int _sid = _sid0; _sid < ({}); _sid += {}) {{", iterations, "int(gl_WorkGroupSize.x * gl_NumWorkGroups.x)"); s = std::make_unique<ScopedIndent>(gen->line_appender_); if (gen->num_workgroups_ == 0) { // if not specified, guess an optimal grid_dim for different situations // Refs: // https://stackoverflow.com/questions/36374652/compute-shaders-optimal-data-division-on-invocations-threads-and-workgroups if (const_iterations > 0) { if (gen->used_tls) { // const range with TLS reduction gen->num_workgroups_ = std::max( const_iterations / std::max(gen->workgroup_size_, 1) / 32, 1); gen->workgroup_size_ = std::max(gen->workgroup_size_ / 4, 1); } else { // const range gen->num_workgroups_ = std::max((const_iterations + gen->workgroup_size_ - 1) / gen->workgroup_size_, 1); } } else { // dynamic range // TODO(archibate): think for a better value for SM utilization: gen->num_workgroups_ = 256; } } } ~ScopedGridStrideLoop() { s = nullptr; gen->emit("}}"); } }; void generate_range_for_kernel(OffloadedStmt *stmt) { TI_ASSERT(stmt->task_type == OffloadedStmt::TaskType::range_for); const std::string glsl_kernel_name = make_kernel_name(); emit("void {}()", glsl_kernel_name); this->glsl_kernel_name_ = glsl_kernel_name; emit("{{ // range for"); used_tls = (stmt->tls_prologue != nullptr); if (used_tls) { auto tls_size = stmt->tls_size; // TODO(k-ye): support 'cursor' in LineAppender: emit("int _tls_i32_[{}];", (tls_size + 3) / 4); if (used.int64) emit("int64_t _tls_i64_[{}];", (tls_size + 7) / 8); if (used.uint32) emit("int _tls_u32_[{}];", (tls_size + 3) / 4); if (used.uint64) emit("int64_t _tls_u64_[{}];", (tls_size + 7) / 8); emit("float _tls_f32_[{}];", (tls_size + 3) / 4); if (used.float64) emit("double _tls_f64_[{}];", (tls_size + 7) / 8); emit("{{ // TLS prologue"); stmt->tls_prologue->accept(this); emit("}}"); } if (stmt->const_begin && stmt->const_end) { ScopedIndent _s(line_appender_); emit("// range known at compile time"); auto begin_value = stmt->begin_value; auto end_value = stmt->end_value; if (end_value < begin_value) end_value = begin_value; workgroup_size_ = stmt->block_dim; num_workgroups_ = stmt->grid_dim; ScopedGridStrideLoop _gsl(this, end_value - begin_value); emit("int _itv = {} + _sid;", begin_value); stmt->body->accept(this); } else { ScopedIndent _s(line_appender_); emit("// range known at runtime"); auto begin_expr = stmt->const_begin ? std::to_string(stmt->begin_value) : fmt::format("_gtmp_i32_[{} >> 2]", stmt->begin_offset); auto end_expr = stmt->const_end ? std::to_string(stmt->end_value) : fmt::format("_gtmp_i32_[{} >> 2]", stmt->end_offset); workgroup_size_ = stmt->block_dim; num_workgroups_ = stmt->grid_dim; emit("int _beg = {}, _end = {};", begin_expr, end_expr); ScopedGridStrideLoop _gsl(this, "_end - _beg"); emit("int _itv = _beg + _sid;"); stmt->body->accept(this); } if (used_tls) { TI_ASSERT(stmt->tls_epilogue != nullptr); emit("{{ // TLS epilogue"); stmt->tls_epilogue->accept(this); emit("}}"); } used_tls = false; emit("}}\n"); } void generate_struct_for_kernel(OffloadedStmt *stmt) { TI_ASSERT(stmt->task_type == OffloadedStmt::TaskType::struct_for); used.listman = true; const std::string glsl_kernel_name = make_kernel_name(); emit("void {}()", glsl_kernel_name); this->glsl_kernel_name_ = glsl_kernel_name; emit("{{ // struct for {}", stmt->snode->node_type_name); { ScopedIndent _s(line_appender_); workgroup_size_ = stmt->block_dim; num_workgroups_ = stmt->grid_dim; ScopedGridStrideLoop _gsl(this, "_list_len_"); emit("int _itv = _list_[_sid];"); stmt->body->accept(this); } emit("}}\n"); } size_t get_snode_base_address(const SNode *snode) { if (snode->type == SNodeType::root) return 0; int chid = find_children_id(snode); const auto &parent_meta = struct_compiled_->snode_map.at(snode->parent->node_type_name); auto choff = parent_meta.children_offsets[chid]; return choff + get_snode_base_address(snode->parent); } size_t get_snode_meta_address(const SNode *snode) { auto addr = get_snode_base_address(snode); addr += struct_compiled_->snode_map.at(snode->node_type_name).stride; addr -= opengl_get_snode_meta_size(*snode); return addr; } void generate_listgen_for_dynamic(const SNode *snode) { TI_ASSERT(snode->type == SNodeType::dynamic); // the `length` field of a dynamic SNode is at it's end: // | x[0] | x[1] | x[2] | x[3] | ... | len | TI_ASSERT_INFO(snode->parent->type == SNodeType::root, "Non-top-level dynamic not supported yet on OpenGL"); size_t addr = get_snode_meta_address(snode); used.int32 = true; emit("_list_len_ = _data_i32_[{} >> 2];", addr); emit("for (int i = 0; i < _list_len_; i++) {{"); { ScopedIndent _s(line_appender_); emit("_list_[i] = i;"); } emit("}}"); } void generate_listgen_for_dense(const SNode *snode) { TI_ASSERT(snode->type == SNodeType::dense); // the `length` field of a dynamic SNode is at it's end: // | x[0] | x[1] | x[2] | x[3] | ... | len | emit("_list_len_ = {};", struct_compiled_->snode_map.at(snode->node_type_name).length); emit("for (int i = 0; i < _list_len_; i++) {{"); { ScopedIndent _s(line_appender_); emit("_list_[i] = i;"); } emit("}}"); } void generate_listgen_kernel(OffloadedStmt *stmt) { TI_ASSERT(stmt->task_type == OffloadedStmt::TaskType::listgen); const std::string glsl_kernel_name = make_kernel_name(); emit("void {}()", glsl_kernel_name); this->glsl_kernel_name_ = glsl_kernel_name; used.listman = true; emit("{{ // listgen {}", stmt->snode->node_type_name); { ScopedIndent _s(line_appender_); if (stmt->snode->type == SNodeType::dense) { generate_listgen_for_dense(stmt->snode); } else if (stmt->snode->type == SNodeType::dynamic) { generate_listgen_for_dynamic(stmt->snode); } else { TI_NOT_IMPLEMENTED } } emit("}}\n"); } void visit(GlobalTemporaryStmt *stmt) override { TI_ASSERT(stmt->width() == 1); used.buf_gtmp = true; emit("int {} = {};", stmt->short_name(), stmt->offset); ptr_signats[stmt->id] = "gtmp"; } void visit(ThreadLocalPtrStmt *stmt) override { TI_ASSERT(stmt->width() == 1); emit("int {} = {};", stmt->short_name(), stmt->offset); ptr_signats[stmt->id] = "tls"; } void visit(LoopIndexStmt *stmt) override { TI_ASSERT(stmt->index == 0); // TODO: multiple indices if (stmt->loop->is<OffloadedStmt>()) { auto type = stmt->loop->as<OffloadedStmt>()->task_type; if (type == OffloadedStmt::TaskType::range_for) { emit("int {} = _itv;", stmt->short_name()); } else if (type == OffloadedStmt::TaskType::struct_for) { emit("int {} = _itv; // struct for", stmt->short_name()); } else { TI_NOT_IMPLEMENTED } } else if (stmt->loop->is<RangeForStmt>()) { emit("int {} = {};", stmt->short_name(), stmt->loop->short_name()); } else { TI_NOT_IMPLEMENTED } } void visit(RangeForStmt *for_stmt) override { TI_ASSERT(for_stmt->width() == 1); auto loop_var_name = for_stmt->short_name(); if (!for_stmt->reversed) { emit("for (int {}_ = {}; {}_ < {}; {}_ += {}) {{", loop_var_name, for_stmt->begin->short_name(), loop_var_name, for_stmt->end->short_name(), loop_var_name, 1); emit(" int {} = {}_;", loop_var_name, loop_var_name); } else { // reversed for loop emit("for (int {}_ = {} - {}; {}_ >= {}; {}_ -= {}) {{", loop_var_name, for_stmt->end->short_name(), 1, loop_var_name, for_stmt->begin->short_name(), loop_var_name, 1); emit(" int {} = {}_;", loop_var_name, loop_var_name); } for_stmt->body->accept(this); emit("}}"); } void visit(WhileControlStmt *stmt) override { emit("if ({} == 0) break;", stmt->cond->short_name()); } void visit(ContinueStmt *stmt) override { // stmt->as_return() is unused when embraced with a grid-stride-loop emit("continue;"); } void visit(WhileStmt *stmt) override { emit("while (true) {{"); stmt->body->accept(this); emit("}}"); } void visit(OffloadedStmt *stmt) override { auto map = irpass::detect_external_ptr_access_in_task(stmt); this->extptr_access = std::move(map); generate_header(); TI_ASSERT(is_top_level_); is_top_level_ = false; using Type = OffloadedStmt::TaskType; if (stmt->task_type == Type::serial) { generate_serial_kernel(stmt); } else if (stmt->task_type == Type::range_for) { generate_range_for_kernel(stmt); } else if (stmt->task_type == Type::struct_for) { generate_struct_for_kernel(stmt); } else if (stmt->task_type == Type::listgen) { generate_listgen_kernel(stmt); } else { // struct_for is automatically lowered to ranged_for for dense snodes // (#378). So we only need to support serial and range_for tasks. TI_ERROR("[glsl] Unsupported offload type={} on OpenGL arch", stmt->task_name()); } is_top_level_ = true; generate_bottom(); } void visit(StructForStmt *) override { TI_ERROR("[glsl] Struct for cannot be nested under OpenGL for now"); } void visit(ClearListStmt *stmt) override { used.listman = true; emit("// clear list {}", stmt->snode->node_type_name); emit("_list_len_ = 0;"); } void visit(IfStmt *if_stmt) override { emit("if ({} != 0) {{", if_stmt->cond->short_name()); if (if_stmt->true_statements) { if_stmt->true_statements->accept(this); } if (if_stmt->false_statements) { emit("}} else {{"); if_stmt->false_statements->accept(this); } emit("}}"); } public: CompiledProgram get_compiled_program() { // We have to set it at the last moment, to get all used feature. compiled_program_.set_used(used); return std::move(compiled_program_); } void run() { kernel_->ir->accept(this); } }; } // namespace CompiledProgram OpenglCodeGen::gen(void) { #if defined(TI_WITH_OPENGL) KernelGen codegen(kernel_, struct_compiled_, kernel_name_); codegen.run(); return codegen.get_compiled_program(); #else TI_NOT_IMPLEMENTED #endif } void OpenglCodeGen::lower() { auto ir = kernel_->ir.get(); auto &config = kernel_->program->config; config.demote_dense_struct_fors = true; irpass::compile_to_executable(ir, config, kernel_, /*vectorize=*/false, kernel_->grad, /*ad_use_stack=*/false, config.print_ir, /*lower_global_access=*/true, /*make_thread_local=*/config.make_thread_local); #ifdef _GLSL_DEBUG irpass::print(ir); #endif } CompiledProgram OpenglCodeGen::compile(Kernel &kernel) { this->kernel_ = &kernel; this->lower(); return this->gen(); } } // namespace opengl TLANG_NAMESPACE_END
36.829024
132
0.601205
[ "vector" ]
294ee3d885d51a22e0f1438fd0d646a90700cdc0
19,201
cc
C++
chrome/browser/chromeos/policy/cloud_external_data_manager_base.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/chromeos/policy/cloud_external_data_manager_base.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/chromeos/policy/cloud_external_data_manager_base.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/policy/cloud_external_data_manager_base.h" #include <stddef.h> #include <stdint.h> #include <map> #include <string> #include <utility> #include "base/bind.h" #include "base/callback.h" #include "base/callback_helpers.h" #include "base/callback_list.h" #include "base/check_op.h" #include "base/containers/contains.h" #include "base/files/file_path.h" #include "base/location.h" #include "base/macros.h" #include "base/notreached.h" #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/chromeos/policy/cloud_external_data_store.h" #include "components/policy/core/common/cloud/cloud_policy_store.h" #include "components/policy/core/common/cloud/external_policy_data_fetcher.h" #include "components/policy/core/common/cloud/external_policy_data_updater.h" #include "components/policy/core/common/external_data_fetcher.h" #include "components/policy/core/common/policy_map.h" #include "services/network/public/cpp/shared_url_loader_factory.h" namespace policy { namespace { // Fetch data for at most two external data references at the same time. const int kMaxParallelFetches = 2; // Allows policies to reference |g_max_external_data_size_for_testing| bytes of // external data even if no |max_size| was specified in policy_templates.json. int g_max_external_data_size_for_testing = 0; } // namespace // Backend for the CloudExternalDataManagerBase that handles all data download, // verification, caching and retrieval. class CloudExternalDataManagerBase::Backend { public: // |get_policy_details| is used to determine the maximum size that the // data referenced by each policy can have. This class can be instantiated on // any thread but from then on, may be accessed via the |task_runner_| only. // All FetchCallbacks will be invoked via |callback_task_runner|. Backend(const GetChromePolicyDetailsCallback& get_policy_details, scoped_refptr<base::SequencedTaskRunner> task_runner, scoped_refptr<base::SequencedTaskRunner> callback_task_runner); // Allows downloaded external data to be cached in |external_data_store|. // Ownership of the store is taken. The store can be destroyed by calling // SetExternalDataStore(std::unique_ptr<CloudExternalDataStore>()). void SetExternalDataStore( std::unique_ptr<CloudExternalDataStore> external_data_store); // Allows downloading of external data via the |external_policy_data_fetcher|. void Connect( std::unique_ptr<ExternalPolicyDataFetcher> external_policy_data_fetcher); // Prevents further external data downloads and aborts any downloads currently // in progress void Disconnect(); // Called when the external data references that this backend is responsible // for change. |metadata| maps from policy names to the metadata specifying // the external data that each of the policies references. void OnMetadataUpdated(std::unique_ptr<Metadata> metadata); // Called by the |updater_| when the external |data| referenced by |policy| // has been successfully downloaded and verified to match |hash|. bool OnDownloadSuccess(const std::string& policy, const std::string& hash, const std::string& data); // Retrieves the external data referenced by |policy| and invokes |callback| // with the result. If |policy| does not reference any external data, the // |callback| is invoked with a NULL pointer. Otherwise, the |callback| is // invoked with the referenced data once it has been successfully retrieved. // If retrieval is temporarily impossible (e.g. the data is not cached yet and // there is no network connectivity), the |callback| will be invoked when the // temporary hindrance is resolved. If retrieval is permanently impossible // (e.g. |policy| references data that does not exist on the server), the // |callback| will never be invoked. // If the data for |policy| is not cached yet, only one download is started, // even if this method is invoked multiple times. The |callback|s passed are // enqueued and all invoked once the data has been successfully retrieved. void Fetch(const std::string& policy, ExternalDataFetcher::FetchCallback callback); // Try to download and cache all external data referenced by |metadata_|. void FetchAll(); private: // List of callbacks to invoke when the attempt to retrieve external data // referenced by a policy completes successfully or fails permanently. using FetchCallbackList = base::OnceCallbackList<void(const std::string*, const base::FilePath&)>; // Map from policy names to the lists of callbacks defined above. using FetchCallbackMap = std::map<std::string, FetchCallbackList>; // Looks up the maximum size that the data referenced by |policy| can have. size_t GetMaxExternalDataSize(const std::string& policy) const; // Invokes |callback| via the |callback_task_runner_|, passing |data| and // |file_path| as parameters. void RunCallback(ExternalDataFetcher::FetchCallback callback, std::unique_ptr<std::string> data, const base::FilePath& file_path) const; // Tells the |updater_| to download the external data referenced by |policy|. // If Connect() was not called yet and no |updater_| exists, does nothing. void StartDownload(const std::string& policy); // Used to determine the maximum size that the data referenced by each policy // can have. GetChromePolicyDetailsCallback get_policy_details_; scoped_refptr<base::SequencedTaskRunner> task_runner_; scoped_refptr<base::SequencedTaskRunner> callback_task_runner_; // Contains the policies for which a download of the referenced external data // has been requested. Each policy is mapped to a list of callbacks to invoke // when the download completes successfully or fails permanently. If no // callback needs to be invoked (because the download was requested via // FetchAll()), a map entry will still exist but the list of callbacks it maps // to will be empty. FetchCallbackMap pending_downloads_; // Indicates that OnMetadataUpdated() has been called at least once and the // contents of |metadata_| is initialized. bool metadata_set_; // Maps from policy names to the metadata specifying the external data that // each of the policies references. Metadata metadata_; // Used to cache external data referenced by policies. std::unique_ptr<CloudExternalDataStore> external_data_store_; // Used to download external data referenced by policies. std::unique_ptr<ExternalPolicyDataUpdater> updater_; SEQUENCE_CHECKER(sequence_checker_); DISALLOW_COPY_AND_ASSIGN(Backend); }; CloudExternalDataManagerBase::Backend::Backend( const GetChromePolicyDetailsCallback& get_policy_details, scoped_refptr<base::SequencedTaskRunner> task_runner, scoped_refptr<base::SequencedTaskRunner> callback_task_runner) : get_policy_details_(get_policy_details), task_runner_(task_runner), callback_task_runner_(callback_task_runner), metadata_set_(false) { // This class is allowed to be instantiated on any thread. DETACH_FROM_SEQUENCE(sequence_checker_); } void CloudExternalDataManagerBase::Backend::SetExternalDataStore( std::unique_ptr<CloudExternalDataStore> external_data_store) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); external_data_store_ = std::move(external_data_store); if (metadata_set_ && external_data_store_) external_data_store_->Prune(metadata_); } void CloudExternalDataManagerBase::Backend::Connect( std::unique_ptr<ExternalPolicyDataFetcher> external_policy_data_fetcher) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(!updater_); updater_.reset(new ExternalPolicyDataUpdater( task_runner_, std::move(external_policy_data_fetcher), kMaxParallelFetches)); for (const auto& it : pending_downloads_) StartDownload(it.first); } void CloudExternalDataManagerBase::Backend::Disconnect() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); updater_.reset(); } void CloudExternalDataManagerBase::Backend::OnMetadataUpdated( std::unique_ptr<Metadata> metadata) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); metadata_set_ = true; Metadata old_metadata; metadata_.swap(old_metadata); if (metadata) metadata_.swap(*metadata); if (external_data_store_) external_data_store_->Prune(metadata_); for (FetchCallbackMap::iterator it = pending_downloads_.begin(); it != pending_downloads_.end(); ) { const std::string policy = it->first; Metadata::const_iterator metadata = metadata_.find(policy); if (metadata == metadata_.end()) { // |policy| no longer references external data. if (updater_) { // Cancel the external data download. updater_->CancelExternalDataFetch(policy); } // Invoke all callbacks for |policy|, indicating permanent failure. it->second.Notify(nullptr, base::FilePath()); pending_downloads_.erase(it++); continue; } if (updater_ && metadata->second != old_metadata[policy]) { // |policy| still references external data but the reference has changed. // Cancel the external data download and start a new one. updater_->CancelExternalDataFetch(policy); StartDownload(policy); } ++it; } } bool CloudExternalDataManagerBase::Backend::OnDownloadSuccess( const std::string& policy, const std::string& hash, const std::string& data) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(metadata_.find(policy) != metadata_.end()); DCHECK_EQ(hash, metadata_[policy].hash); base::FilePath file_path; if (external_data_store_) file_path = external_data_store_->Store(policy, hash, data); pending_downloads_[policy].Notify(&data, file_path); pending_downloads_.erase(policy); return true; } void CloudExternalDataManagerBase::Backend::Fetch( const std::string& policy, ExternalDataFetcher::FetchCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); Metadata::const_iterator metadata = metadata_.find(policy); if (metadata == metadata_.end()) { // If |policy| does not reference any external data, indicate permanent // failure. RunCallback(std::move(callback), nullptr, base::FilePath()); return; } const bool has_pending_download = base::Contains(pending_downloads_, policy); if (!has_pending_download && external_data_store_) { auto data = std::make_unique<std::string>(); const base::FilePath file_path = external_data_store_->Load(policy, metadata->second.hash, GetMaxExternalDataSize(policy), data.get()); if (!file_path.empty()) { // If the external data referenced by |policy| exists in the cache and // matches the expected hash, pass it to the callback. RunCallback(std::move(callback), std::move(data), file_path); return; } } // Callback lists cannot hold callbacks that take move-only args, since // Notify()ing such a list would move the arg into the first callback, leaving // it null or unspecified for remaining callbacks. Instead, adapt the // provided callbacks to accept a raw pointer, which can be copied, and then // wrap in a separate scoping object for each callback. pending_downloads_[policy].AddUnsafe(base::BindOnce( [](const CloudExternalDataManagerBase::Backend* backend, ExternalDataFetcher::FetchCallback callback, const std::string* data, const base::FilePath& file_path) { backend->RunCallback( std::move(callback), data ? std::make_unique<std::string>(*data) : nullptr, file_path); }, base::Unretained(this), std::move(callback))); if (!has_pending_download) StartDownload(policy); } void CloudExternalDataManagerBase::Backend::FetchAll() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // Loop through all external data references. for (const auto& it : metadata_) { const std::string& policy = it.first; std::unique_ptr<std::string> data(new std::string); if (base::Contains(pending_downloads_, policy) || (external_data_store_ && !external_data_store_ ->Load(policy, it.second.hash, GetMaxExternalDataSize(policy), data.get()) .empty())) { // If a download of the external data referenced by |policy| has already // been requested or the data exists in the cache and matches the expected // hash, there is nothing to be done. continue; } // Request a download of the the external data referenced by |policy| and // initialize the list of callbacks to an empty list. pending_downloads_[policy]; StartDownload(policy); } } size_t CloudExternalDataManagerBase::Backend::GetMaxExternalDataSize( const std::string& policy) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (g_max_external_data_size_for_testing) return g_max_external_data_size_for_testing; // Look up the maximum size that the data referenced by |policy| can have in // get_policy_details, which is constructed from the information in // policy_templates.json, allowing the maximum data size to be specified as // part of the policy definition. const PolicyDetails* details = get_policy_details_.Run(policy); if (details) return details->max_external_data_size; NOTREACHED(); return 0; } void CloudExternalDataManagerBase::Backend::RunCallback( ExternalDataFetcher::FetchCallback callback, std::unique_ptr<std::string> data, const base::FilePath& file_path) const { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); callback_task_runner_->PostTask( FROM_HERE, base::BindOnce(std::move(callback), std::move(data), file_path)); } void CloudExternalDataManagerBase::Backend::StartDownload( const std::string& policy) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); DCHECK(base::Contains(pending_downloads_, policy)); if (!updater_) return; const MetadataEntry& metadata = metadata_[policy]; updater_->FetchExternalData( policy, ExternalPolicyDataUpdater::Request(metadata.url, metadata.hash, GetMaxExternalDataSize(policy)), base::BindRepeating( &CloudExternalDataManagerBase::Backend::OnDownloadSuccess, base::Unretained(this), policy, metadata.hash)); } CloudExternalDataManagerBase::CloudExternalDataManagerBase( const GetChromePolicyDetailsCallback& get_policy_details, scoped_refptr<base::SequencedTaskRunner> backend_task_runner) : backend_task_runner_(std::move(backend_task_runner)), backend_(new Backend(get_policy_details, backend_task_runner_, base::ThreadTaskRunnerHandle::Get())) {} CloudExternalDataManagerBase::~CloudExternalDataManagerBase() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); Backend* backend_to_delete = backend_.release(); if (!backend_task_runner_->DeleteSoon(FROM_HERE, backend_to_delete)) { // If the task runner is no longer running, it's safe to just delete the // object, since no further events will be delivered by external data // manager. delete backend_to_delete; } } void CloudExternalDataManagerBase::SetExternalDataStore( std::unique_ptr<CloudExternalDataStore> external_data_store) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); backend_task_runner_->PostTask( FROM_HERE, base::BindOnce(&Backend::SetExternalDataStore, base::Unretained(backend_.get()), std::move(external_data_store))); } void CloudExternalDataManagerBase::SetPolicyStore( CloudPolicyStore* policy_store) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); CloudExternalDataManager::SetPolicyStore(policy_store); if (policy_store_ && policy_store_->is_initialized()) OnPolicyStoreLoaded(); } void CloudExternalDataManagerBase::OnPolicyStoreLoaded() { // Collect all external data references made by policies in |policy_store_| // and pass them to the |backend_|. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); std::unique_ptr<Metadata> metadata(new Metadata); const PolicyMap& policy_map = policy_store_->policy_map(); for (const auto& it : policy_map) { if (!it.second.external_data_fetcher) { // Skip policies that do not reference external data. continue; } const base::DictionaryValue* dict = NULL; std::string url; std::string hex_hash; std::string hash; if (it.second.value() && it.second.value()->GetAsDictionary(&dict) && dict->GetStringWithoutPathExpansion("url", &url) && dict->GetStringWithoutPathExpansion("hash", &hex_hash) && !url.empty() && !hex_hash.empty() && base::HexStringToString(hex_hash, &hash)) { // Add the external data reference to |metadata| if it is valid (URL and // hash are not empty, hash can be decoded as a hex string). (*metadata)[it.first] = MetadataEntry(url, hash); } } backend_task_runner_->PostTask( FROM_HERE, base::BindOnce(&Backend::OnMetadataUpdated, base::Unretained(backend_.get()), std::move(metadata))); } void CloudExternalDataManagerBase::Connect( scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); backend_task_runner_->PostTask( FROM_HERE, base::BindOnce(&Backend::Connect, base::Unretained(backend_.get()), std::make_unique<ExternalPolicyDataFetcher>( std::move(url_loader_factory), backend_task_runner_))); } void CloudExternalDataManagerBase::Disconnect() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); backend_task_runner_->PostTask( FROM_HERE, base::BindOnce(&Backend::Disconnect, base::Unretained(backend_.get()))); } void CloudExternalDataManagerBase::Fetch( const std::string& policy, ExternalDataFetcher::FetchCallback callback) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); backend_task_runner_->PostTask( FROM_HERE, base::BindOnce(&Backend::Fetch, base::Unretained(backend_.get()), policy, std::move(callback))); } // static void CloudExternalDataManagerBase::SetMaxExternalDataSizeForTesting( int max_size) { g_max_external_data_size_for_testing = max_size; } void CloudExternalDataManagerBase::FetchAll() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); backend_task_runner_->PostTask( FROM_HERE, base::BindOnce(&Backend::FetchAll, base::Unretained(backend_.get()))); } } // namespace policy
40.338235
80
0.735222
[ "object" ]
294f367e8f121270bbe3fdbe9386efd888c8142d
18,683
cpp
C++
cocos2d/cocos/platform/linux/CCDevice-linux.cpp
IoriKobayashi/BluetoothChecker
fb0127d756a2794be89e5a98b031109cdabfc977
[ "MIT" ]
null
null
null
cocos2d/cocos/platform/linux/CCDevice-linux.cpp
IoriKobayashi/BluetoothChecker
fb0127d756a2794be89e5a98b031109cdabfc977
[ "MIT" ]
null
null
null
cocos2d/cocos/platform/linux/CCDevice-linux.cpp
IoriKobayashi/BluetoothChecker
fb0127d756a2794be89e5a98b031109cdabfc977
[ "MIT" ]
null
null
null
/**************************************************************************** Copyright (c) 2011 Laschweinski Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos2d-x.org 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 "platform/CCPlatformConfig.h" #if CC_TARGET_PLATFORM == CC_PLATFORM_LINUX #include "platform/CCDevice.h" #include "platform/CCFileUtils.h" #include <X11/Xlib.h> #include <stdio.h> #include <algorithm> #include <vector> #include <map> #include <string> #include <sstream> #include <fontconfig/fontconfig.h> #include "ft2build.h" #include FT_FREETYPE_H using namespace std; // as FcFontMatch is quite an expensive call, cache the results of getFontFile static std::map<std::string, std::string> fontCache; struct LineBreakGlyph { FT_UInt glyphIndex; int paintPosition; int glyphWidth; int bearingX; int kerning; int horizAdvance; }; struct LineBreakLine { LineBreakLine() : lineWidth(0) {} std::vector<LineBreakGlyph> glyphs; int lineWidth; void reset() { glyphs.clear(); lineWidth = 0; } void calculateWidth() { lineWidth = 0; if ( glyphs.empty() == false ) { LineBreakGlyph& glyph = glyphs.at(glyphs.size() - 1); lineWidth = glyph.paintPosition + max(glyph.glyphWidth, glyph.horizAdvance - glyph.bearingX); } } }; NS_CC_BEGIN int Device::getDPI() { static int dpi = -1; if (dpi == -1) { Display *dpy; char *displayname = NULL; int scr = 0; /* Screen number */ dpy = XOpenDisplay (displayname); /* * there are 2.54 centimeters to an inch; so there are 25.4 millimeters. * * dpi = N pixels / (M millimeters / (25.4 millimeters / 1 inch)) * = N pixels / (M inch / 25.4) * = N * 25.4 pixels / M inch */ double xres = ((((double) DisplayWidth(dpy,scr)) * 25.4) / ((double) DisplayWidthMM(dpy,scr))); dpi = (int) (xres + 0.5); //printf("dpi = %d\n", dpi); XCloseDisplay (dpy); } return dpi; } void Device::setAccelerometerEnabled(bool isEnabled) { } void Device::setAccelerometerInterval(float interval) { } class BitmapDC { public: BitmapDC() { libError = FT_Init_FreeType( &library ); FcInit(); _data = NULL; reset(); } ~BitmapDC() { FT_Done_FreeType(library); FcFini(); reset(); } void reset() { iMaxLineWidth = 0; iMaxLineHeight = 0; textLines.clear(); } int utf8(char **p) { if ((**p & 0x80) == 0x00) { int a = *((*p)++); return a; } if ((**p & 0xE0) == 0xC0) { int a = *((*p)++) & 0x1F; int b = *((*p)++) & 0x3F; return (a << 6) | b; } if ((**p & 0xF0) == 0xE0) { int a = *((*p)++) & 0x0F; int b = *((*p)++) & 0x3F; int c = *((*p)++) & 0x3F; return (a << 12) | (b << 6) | c; } if ((**p & 0xF8) == 0xF0) { int a = *((*p)++) & 0x07; int b = *((*p)++) & 0x3F; int c = *((*p)++) & 0x3F; int d = *((*p)++) & 0x3F; return (a << 18) | (b << 12) | (c << 8) | d; } return 0; } bool isBreakPoint(FT_UInt currentCharacter, FT_UInt previousCharacter) { if ( previousCharacter == '-' || previousCharacter == '/' || previousCharacter == '\\' ) { // we can insert a line break after one of these characters return true; } return false; } bool divideString(FT_Face face, const char* sText, int iMaxWidth, int iMaxHeight) { const char* pText = sText; textLines.clear(); iMaxLineWidth = 0; FT_UInt unicode; FT_UInt prevCharacter = 0; FT_UInt glyphIndex = 0; FT_UInt prevGlyphIndex = 0; FT_Vector delta; LineBreakLine currentLine; int currentPaintPosition = 0; int firstBreakIndex = -1; int lastBreakIndex = -1; bool hasKerning = FT_HAS_KERNING( face ); while ((unicode=utf8((char**)&pText))) { if (unicode == '\n') { currentLine.calculateWidth(); iMaxLineWidth = max(iMaxLineWidth, currentLine.lineWidth); textLines.push_back(currentLine); currentLine.reset(); prevGlyphIndex = 0; prevCharacter = 0; firstBreakIndex = -1; lastBreakIndex = -1; currentPaintPosition = 0; continue; } if ( isBreakPoint(unicode, prevCharacter) ) { lastBreakIndex = currentLine.glyphs.size() - 1; } glyphIndex = FT_Get_Char_Index(face, unicode); if (FT_Load_Glyph(face, glyphIndex, FT_LOAD_DEFAULT)) { return false; } LineBreakGlyph glyph; glyph.glyphIndex = glyphIndex; glyph.glyphWidth = face->glyph->metrics.width >> 6; glyph.bearingX = face->glyph->metrics.horiBearingX >> 6; glyph.horizAdvance = face->glyph->metrics.horiAdvance >> 6; glyph.kerning = 0; if (prevGlyphIndex != 0 && hasKerning) { FT_Get_Kerning(face, prevGlyphIndex, glyphIndex, FT_KERNING_DEFAULT, &delta); glyph.kerning = delta.x >> 6; } if (iswspace(unicode)) { prevGlyphIndex = glyphIndex; prevCharacter = unicode; lastBreakIndex = currentLine.glyphs.size(); if (firstBreakIndex == -1) firstBreakIndex = lastBreakIndex; } else { if (iswspace(prevCharacter)) lastBreakIndex = currentLine.glyphs.size(); if (iMaxWidth > 0 && currentPaintPosition + glyph.bearingX + glyph.kerning + glyph.glyphWidth > iMaxWidth) { int glyphCount = currentLine.glyphs.size(); if ( lastBreakIndex >= 0 && lastBreakIndex < glyphCount && currentPaintPosition + glyph.bearingX + glyph.kerning + glyph.glyphWidth - currentLine.glyphs.at(lastBreakIndex).paintPosition < iMaxWidth ) { // we insert a line break at our last break opportunity std::vector<LineBreakGlyph> tempGlyphs; std::vector<LineBreakGlyph>::iterator it = currentLine.glyphs.begin(); std::advance(it, lastBreakIndex); tempGlyphs.insert(tempGlyphs.begin(), it, currentLine.glyphs.end()); if (firstBreakIndex == -1) { currentLine.glyphs.erase(it, currentLine.glyphs.end()); } else { it = currentLine.glyphs.begin(); std::advance(it, firstBreakIndex); currentLine.glyphs.erase(it, currentLine.glyphs.end()); } currentLine.calculateWidth(); iMaxLineWidth = max(iMaxLineWidth, currentLine.lineWidth); textLines.push_back(currentLine); currentLine.reset(); currentPaintPosition = 0; for ( auto& glyph : tempGlyphs ) { if ( currentLine.glyphs.empty() ) { currentPaintPosition = -glyph.bearingX; glyph.kerning = 0; } glyph.paintPosition = currentPaintPosition + glyph.bearingX + glyph.kerning; currentLine.glyphs.push_back(glyph); currentPaintPosition += glyph.kerning + glyph.horizAdvance; } } else { // the current word is too big to fit into one line, insert line break right here currentPaintPosition = 0; glyph.kerning = 0; currentLine.calculateWidth(); iMaxLineWidth = max(iMaxLineWidth, currentLine.lineWidth); textLines.push_back(currentLine); currentLine.reset(); } prevGlyphIndex = 0; prevCharacter = 0; firstBreakIndex = -1; lastBreakIndex = -1; } else { prevGlyphIndex = glyphIndex; prevCharacter = unicode; } } if ( currentLine.glyphs.empty() ) { currentPaintPosition = -glyph.bearingX; } glyph.paintPosition = currentPaintPosition + glyph.bearingX + glyph.kerning; currentLine.glyphs.push_back(glyph); currentPaintPosition += glyph.kerning + glyph.horizAdvance; } if ( currentLine.glyphs.empty() == false ) { currentLine.calculateWidth(); iMaxLineWidth = max(iMaxLineWidth, currentLine.lineWidth); textLines.push_back(currentLine); } return true; } /** * compute the start pos of every line */ int computeLineStart(FT_Face face, Device::TextAlign eAlignMask, int line) { int lineWidth = textLines.at(line).lineWidth; if (eAlignMask == Device::TextAlign::CENTER || eAlignMask == Device::TextAlign::TOP || eAlignMask == Device::TextAlign::BOTTOM) { return (iMaxLineWidth - lineWidth) / 2; } else if (eAlignMask == Device::TextAlign::RIGHT || eAlignMask == Device::TextAlign::TOP_RIGHT || eAlignMask == Device::TextAlign::BOTTOM_RIGHT) { return (iMaxLineWidth - lineWidth); } // left or other situation return 0; } int computeLineStartY( FT_Face face, Device::TextAlign eAlignMask, int txtHeight, int borderHeight ){ int baseLinePos = ceilf(face->size->metrics.ascender/64.0f); if (eAlignMask == Device::TextAlign::CENTER || eAlignMask == Device::TextAlign::LEFT || eAlignMask == Device::TextAlign::RIGHT) { //vertical center return (borderHeight - txtHeight) / 2 + baseLinePos; } else if (eAlignMask == Device::TextAlign::BOTTOM_RIGHT || eAlignMask == Device::TextAlign::BOTTOM || eAlignMask == Device::TextAlign::BOTTOM_LEFT) { //vertical bottom return borderHeight - txtHeight + baseLinePos; } // top alignment return baseLinePos; } std::string getFontFile(const char* family_name) { std::string fontPath = family_name; std::map<std::string, std::string>::iterator it = fontCache.find(family_name); if ( it != fontCache.end() ) { return it->second; } // check if the parameter is a font file shipped with the application std::string lowerCasePath = fontPath; std::transform(lowerCasePath.begin(), lowerCasePath.end(), lowerCasePath.begin(), ::tolower); if ( lowerCasePath.find(".ttf") != std::string::npos ) { fontPath = cocos2d::FileUtils::getInstance()->fullPathForFilename(fontPath.c_str()); FILE *f = fopen(fontPath.c_str(), "r"); if ( f ) { fclose(f); fontCache.insert(std::pair<std::string, std::string>(family_name, fontPath)); return fontPath; } } // use fontconfig to match the parameter against the fonts installed on the system FcPattern *pattern = FcPatternBuild (0, FC_FAMILY, FcTypeString, family_name, (char *) 0); FcConfigSubstitute(0, pattern, FcMatchPattern); FcDefaultSubstitute(pattern); FcResult result; FcPattern *font = FcFontMatch(0, pattern, &result); if ( font ) { FcChar8 *s = NULL; if ( FcPatternGetString(font, FC_FILE, 0, &s) == FcResultMatch ) { fontPath = (const char*)s; FcPatternDestroy(font); FcPatternDestroy(pattern); fontCache.insert(std::pair<std::string, std::string>(family_name, fontPath)); return fontPath; } FcPatternDestroy(font); } FcPatternDestroy(pattern); return family_name; } bool getBitmap(const char *text, const FontDefinition& textDefinition, Device::TextAlign eAlignMask) { if (libError) { return false; } FT_Face face; std::string fontfile = getFontFile(textDefinition._fontName.c_str()); if ( FT_New_Face(library, fontfile.c_str(), 0, &face) ) { //no valid font found use default if ( FT_New_Face(library, "/usr/share/fonts/truetype/freefont/FreeSerif.ttf", 0, &face) ) { return false; } } //select utf8 charmap if ( FT_Select_Charmap(face, FT_ENCODING_UNICODE) ) { FT_Done_Face(face); return false; } if ( FT_Set_Pixel_Sizes(face, textDefinition._fontSize, textDefinition._fontSize) ) { FT_Done_Face(face); return false; } if ( divideString(face, text, textDefinition._dimensions.width, textDefinition._dimensions.height) == false ) { FT_Done_Face(face); return false; } //compute the final line width iMaxLineWidth = MAX(iMaxLineWidth, textDefinition._dimensions.width); //compute the final line height int lineHeight = face->size->metrics.height>>6; int txtHeight = (lineHeight * textLines.size()); iMaxLineHeight = MAX(txtHeight, textDefinition._dimensions.height); _data = (unsigned char*)malloc(sizeof(unsigned char) * (iMaxLineWidth * iMaxLineHeight * 4)); memset(_data,0, iMaxLineWidth * iMaxLineHeight*4); int iCurYCursor = computeLineStartY(face, eAlignMask, txtHeight, iMaxLineHeight); int lineCount = textLines.size(); for (int line = 0; line < lineCount; line++) { int iCurXCursor = computeLineStart(face, eAlignMask, line); int glyphCount = textLines.at(line).glyphs.size(); for (int i = 0; i < glyphCount; i++) { LineBreakGlyph glyph = textLines.at(line).glyphs.at(i); if (FT_Load_Glyph(face, glyph.glyphIndex, FT_LOAD_RENDER)) { continue; } FT_Bitmap& bitmap = face->glyph->bitmap; int yoffset = iCurYCursor - (face->glyph->metrics.horiBearingY >> 6); int xoffset = iCurXCursor + glyph.paintPosition; for (int y = 0; y < bitmap.rows; ++y) { int iY = yoffset + y; if (iY>=iMaxLineHeight) { //exceed the height truncate break; } iY *= iMaxLineWidth; int bitmap_y = y * bitmap.width; for (int x = 0; x < bitmap.width; ++x) { unsigned char cTemp = bitmap.buffer[bitmap_y + x]; if (cTemp == 0) { continue; } int iX = xoffset + x; //FIXME:wrong text color int iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp; *(int*) &_data[(iY + iX) * 4 + 0] = iTemp; } } } // step to next line iCurYCursor += lineHeight; } // free face FT_Done_Face(face); return true; } public: FT_Library library; unsigned char *_data; int libError; std::vector<LineBreakLine> textLines; int iMaxLineWidth; int iMaxLineHeight; }; static BitmapDC& sharedBitmapDC() { static BitmapDC s_BmpDC; return s_BmpDC; } Data Device::getTextureDataForText(const char * text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha) { Data ret; do { BitmapDC &dc = sharedBitmapDC(); CC_BREAK_IF(! dc.getBitmap(text, textDefinition, align)); CC_BREAK_IF(! dc._data); width = dc.iMaxLineWidth; height = dc.iMaxLineHeight; dc.reset(); ret.fastSet(dc._data,width * height * 4); hasPremultipliedAlpha = true; } while (0); return ret; } void Device::setKeepScreenOn(bool /*value*/) { } void Device::vibrate(float /*duration*/) { } NS_CC_END #endif // CC_TARGET_PLATFORM == CC_PLATFORM_LINUX
35.65458
222
0.530803
[ "vector", "transform" ]
2951da12abea2e1415dc45e923fe553e60cd00d2
21,542
cpp
C++
ExternalCode/copasi/model/CChemEqInterface.cpp
dhlee4/Tinkercell_new
c4d1848bbb905f0e1f9e011837268ac80aff8711
[ "BSD-3-Clause" ]
1
2021-01-07T13:12:51.000Z
2021-01-07T13:12:51.000Z
ExternalCode/copasi/model/CChemEqInterface.cpp
dhlee4/Tinkercell_new
c4d1848bbb905f0e1f9e011837268ac80aff8711
[ "BSD-3-Clause" ]
7
2020-04-12T22:25:46.000Z
2020-04-13T07:50:40.000Z
ExternalCode/copasi/model/CChemEqInterface.cpp
daniel-anavaino/tinkercell
7896a7f809a0373ab3c848d25e3691d10a648437
[ "BSD-3-Clause" ]
2
2020-04-12T21:57:01.000Z
2020-04-12T21:59:29.000Z
// Begin CVS Header // $Source: /fs/turing/cvs/copasi_dev/copasi/model/CChemEqInterface.cpp,v $ // $Revision: 1.42 $ // $Name: Build-33 $ // $Author: shoops $ // $Date: 2010/07/16 19:00:59 $ // End CVS Header // Copyright (C) 2010 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "mathematics.h" #include "copasi.h" #include "CChemEqInterface.h" #include "CMetabNameInterface.h" #include "CChemEq.h" #include "CChemEqParser.h" #include "CReaction.h" #include "CModel.h" #include "utilities/CCopasiVector.h" #include "utilities/utility.h" CChemEqInterface::CChemEqInterface(): mpModel(NULL) {} CChemEqInterface::CChemEqInterface(CModel * pModel): mpModel(pModel) {} CChemEqInterface::~CChemEqInterface() {} std::string CChemEqInterface::getChemEqString(bool expanded) const { std::string ChemicalEquation; unsigned C_INT32 j; if ((mSubstrateNames.size() == 0) && (mProductNames.size() == 0) && (mModifierNames.size() == 0)) return ""; for (j = 0; j < mSubstrateNames.size(); j++) { if (j) ChemicalEquation += " + "; ChemicalEquation += writeElement(mSubstrateDisplayNames[j], mSubstrateMult[j], expanded); } if (mReversibility) ChemicalEquation += " = "; else ChemicalEquation += " -> "; for (j = 0; j < mProductNames.size(); j++) { if (j) ChemicalEquation += " + "; ChemicalEquation += writeElement(mProductDisplayNames[j], mProductMult[j], expanded); } if (mModifierNames.size()) { ChemicalEquation += "; "; for (j = 0; j < mModifierNames.size(); j++) { ChemicalEquation += " "; ChemicalEquation += mModifierDisplayNames[j]; } } return ChemicalEquation; } bool CChemEqInterface::setChemEqString(const std::string & ces) { // parse the description into a linked node tree std::istringstream buffer(ces); CChemEqParser Parser(&buffer); bool success = (Parser.yyparse() == 0); if (success) { mReversibility = Parser.isReversible(); mSubstrateNames = Parser.getSubstrateNames(); mSubstrateMult = Parser.getSubstrateMulitplicities(); mSubstrateCompartments = Parser.getSubstrateCompartments(); mProductNames = Parser.getProductNames(); mProductMult = Parser.getProductMulitplicities(); mProductCompartments = Parser.getProductCompartments(); mModifierNames = Parser.getModifierNames(); mModifierMult = Parser.getModifierMulitplicities(); mModifierCompartments = Parser.getModifierCompartments(); } completeCompartments(); buildDisplayNames(); return success; } void CChemEqInterface::completeCompartments() { std::string DefaultCompartment; if (mpModel->getCompartments().size() == 0) DefaultCompartment = "compartment"; else DefaultCompartment = mpModel->getCompartments()[0]->getObjectName(); // We try to find a reaction compartment. Note, it is not possible to use // getCompartment as writeToChemEq may fail; std::string ReactionCompartment = ""; bool first = true; bool HaveReactionCompartment = true; std::vector< std::string >::iterator itCompartment, endCompartment; itCompartment = mSubstrateCompartments.begin(); endCompartment = mSubstrateCompartments.end(); for (; itCompartment != endCompartment && HaveReactionCompartment; ++itCompartment) { if (*itCompartment == "") continue; if (first) { ReactionCompartment = *itCompartment; first = false; } else if (ReactionCompartment != *itCompartment) HaveReactionCompartment = false; } itCompartment = mProductCompartments.begin(); endCompartment = mProductCompartments.end(); for (; itCompartment != endCompartment && HaveReactionCompartment; ++itCompartment) { if (*itCompartment == "") continue; if (first) { ReactionCompartment = *itCompartment; first = false; } else if (ReactionCompartment != *itCompartment) HaveReactionCompartment = false; } itCompartment = mModifierCompartments.begin(); endCompartment = mModifierCompartments.end(); for (; itCompartment != endCompartment && HaveReactionCompartment; ++itCompartment) { if (*itCompartment == "") continue; if (first) { ReactionCompartment = *itCompartment; first = false; } else if (ReactionCompartment != *itCompartment) HaveReactionCompartment = false; } if (first) ReactionCompartment = DefaultCompartment; CMetab * pMetab; std::vector< std::string >::iterator itMetab; itMetab = mSubstrateNames.begin(); itCompartment = mSubstrateCompartments.begin(); endCompartment = mSubstrateCompartments.end(); for (; itCompartment != endCompartment; ++itCompartment, ++itMetab) if (*itCompartment == "") { pMetab = CMetabNameInterface::getMetabolite(mpModel, *itMetab, ""); if (pMetab == NULL) *itCompartment = ReactionCompartment; else if (CMetabNameInterface::isUnique(mpModel, *itMetab)) *itCompartment = pMetab->getCompartment()->getObjectName(); else // Multiple metabolites with the given name exist. { // 1. Metabolite in the reaction compartment pMetab = CMetabNameInterface::getMetabolite(mpModel, *itMetab, ReactionCompartment); // 2. Metabolite in the default compartment if different from reaction compartment if (pMetab == NULL && ReactionCompartment != DefaultCompartment) pMetab = CMetabNameInterface::getMetabolite(mpModel, *itMetab, DefaultCompartment); // 3. The first metabolite found if (pMetab == NULL) pMetab = CMetabNameInterface::getMetabolite(mpModel, *itMetab, ""); *itCompartment = pMetab->getCompartment()->getObjectName(); } } itMetab = mProductNames.begin(); itCompartment = mProductCompartments.begin(); endCompartment = mProductCompartments.end(); for (; itCompartment != endCompartment; ++itCompartment, ++itMetab) if (*itCompartment == "") { pMetab = CMetabNameInterface::getMetabolite(mpModel, *itMetab, ""); if (pMetab == NULL) *itCompartment = ReactionCompartment; else if (CMetabNameInterface::isUnique(mpModel, *itMetab)) *itCompartment = pMetab->getCompartment()->getObjectName(); else // Multiple metabolites with the given name exist. { // 1. Metabolite in the reaction compartment pMetab = CMetabNameInterface::getMetabolite(mpModel, *itMetab, ReactionCompartment); // 2. Metabolite in the default compartment if different from reaction compartment if (pMetab == NULL && ReactionCompartment != DefaultCompartment) pMetab = CMetabNameInterface::getMetabolite(mpModel, *itMetab, DefaultCompartment); // 3. The first metabolite found if (pMetab == NULL) pMetab = CMetabNameInterface::getMetabolite(mpModel, *itMetab, ""); *itCompartment = pMetab->getCompartment()->getObjectName(); } } itMetab = mModifierNames.begin(); itCompartment = mModifierCompartments.begin(); endCompartment = mModifierCompartments.end(); for (; itCompartment != endCompartment; ++itCompartment, ++itMetab) if (*itCompartment == "") { pMetab = CMetabNameInterface::getMetabolite(mpModel, *itMetab, ""); if (pMetab == NULL) *itCompartment = ReactionCompartment; else if (CMetabNameInterface::isUnique(mpModel, *itMetab)) *itCompartment = pMetab->getCompartment()->getObjectName(); else // Multiple metabolites with the given name exist. { // 1. Metabolite in the reaction compartment pMetab = CMetabNameInterface::getMetabolite(mpModel, *itMetab, ReactionCompartment); // 2. Metabolite in the default compartment if different from reaction compartment if (pMetab == NULL && ReactionCompartment != DefaultCompartment) pMetab = CMetabNameInterface::getMetabolite(mpModel, *itMetab, DefaultCompartment); // 3. The first metabolite found if (pMetab == NULL) pMetab = CMetabNameInterface::getMetabolite(mpModel, *itMetab, ""); *itCompartment = pMetab->getCompartment()->getObjectName(); } } } bool CChemEqInterface::loadFromChemEq(const CChemEq & ce) { bool ret = true; const CCopasiVector<CChemEqElement> * elements; C_INT32 i, imax; elements = &ce.getSubstrates(); imax = elements->size(); mSubstrateNames.resize(imax); mSubstrateMult.resize(imax); mSubstrateCompartments.resize(imax); for (i = 0; i < imax; ++i) { mSubstrateNames[i] = (*elements)[i]->getMetabolite()->getObjectName(); mSubstrateMult[i] = (*elements)[i]->getMultiplicity(); mSubstrateCompartments[i] = (*elements)[i]->getMetabolite()->getCompartment()->getObjectName(); } elements = &ce.getProducts(); imax = elements->size(); mProductNames.resize(imax); mProductMult.resize(imax); mProductCompartments.resize(imax); for (i = 0; i < imax; ++i) { mProductNames[i] = (*elements)[i]->getMetabolite()->getObjectName(); mProductMult[i] = (*elements)[i]->getMultiplicity(); mProductCompartments[i] = (*elements)[i]->getMetabolite()->getCompartment()->getObjectName(); } elements = &ce.getModifiers(); imax = elements->size(); mModifierNames.resize(imax); mModifierMult.resize(imax); mModifierCompartments.resize(imax); for (i = 0; i < imax; ++i) { mModifierNames[i] = (*elements)[i]->getMetabolite()->getObjectName(); mModifierMult[i] = (*elements)[i]->getMultiplicity(); mModifierCompartments[i] = (*elements)[i]->getMetabolite()->getCompartment()->getObjectName(); } mReversibility = ce.getReversibility(); buildDisplayNames(); return ret; } void CChemEqInterface::buildDisplayNames() { std::vector< std::string >::const_iterator itName, itCompartment; std::vector< std::string >::iterator it, end; // We need to build the list of display names for the substrates; mSubstrateDisplayNames.resize(mSubstrateNames.size()); for (itName = mSubstrateNames.begin(), itCompartment = mSubstrateCompartments.begin(), it = mSubstrateDisplayNames.begin(), end = mSubstrateDisplayNames.end(); it != end; ++itName, ++itCompartment, ++it) *it = CMetabNameInterface::getDisplayName(mpModel, *itName, *itCompartment); // We need to build the list of display names for the products; mProductDisplayNames.resize(mProductNames.size()); for (itName = mProductNames.begin(), itCompartment = mProductCompartments.begin(), it = mProductDisplayNames.begin(), end = mProductDisplayNames.end(); it != end; ++itName, ++itCompartment, ++it) *it = CMetabNameInterface::getDisplayName(mpModel, *itName, *itCompartment); // We need to build the list of display names for the modifiers; mModifierDisplayNames.resize(mModifierNames.size()); for (itName = mModifierNames.begin(), itCompartment = mModifierCompartments.begin(), it = mModifierDisplayNames.begin(), end = mModifierDisplayNames.end(); it != end; ++itName, ++itCompartment, ++it) *it = CMetabNameInterface::getDisplayName(mpModel, *itName, *itCompartment); return; } bool CChemEqInterface::writeToChemEq(CChemEq & ce) const { bool ret = true; std::string metabkey; C_INT32 i, imax; ce.cleanup(); imax = mSubstrateNames.size(); for (i = 0; i < imax; ++i) { metabkey = CMetabNameInterface::getMetaboliteKey(mpModel, mSubstrateNames[i], mSubstrateCompartments[i]); if (metabkey.empty()) ret = false; else ce.addMetabolite(metabkey, mSubstrateMult[i], CChemEq::SUBSTRATE); } imax = mProductNames.size(); for (i = 0; i < imax; ++i) { metabkey = CMetabNameInterface::getMetaboliteKey(mpModel, mProductNames[i], mProductCompartments[i]); if (metabkey.empty()) ret = false; else ce.addMetabolite(metabkey, mProductMult[i], CChemEq::PRODUCT); } imax = mModifierNames.size(); for (i = 0; i < imax; ++i) { metabkey = CMetabNameInterface::getMetaboliteKey(mpModel, mModifierNames[i], mModifierCompartments[i]); if (metabkey.empty()) ret = false; else ce.addMetabolite(metabkey, mModifierMult[i], CChemEq::MODIFIER); } ce.setReversibility(mReversibility); return ret; //TODO: really check } const std::vector<C_FLOAT64> & CChemEqInterface::getListOfMultiplicities(CFunctionParameter::Role role) const { if (role == CFunctionParameter::SUBSTRATE) return mSubstrateMult; else if (role == CFunctionParameter::PRODUCT) return mProductMult; else if (role == CFunctionParameter::MODIFIER) return mModifierMult; else fatalError(); return mSubstrateMult; //never reached } const std::vector<std::string> & CChemEqInterface::getListOfDisplayNames(CFunctionParameter::Role role) const { if (role == CFunctionParameter::SUBSTRATE) return mSubstrateDisplayNames; else if (role == CFunctionParameter::PRODUCT) return mProductDisplayNames; else if (role == CFunctionParameter::MODIFIER) return mModifierDisplayNames; else fatalError(); return mSubstrateDisplayNames; //never reached } void CChemEqInterface::addModifier(const std::string & name) { std::pair< std::string, std::string > Modifier = CMetabNameInterface::splitDisplayName(name); //is the name already in the list std::vector< std::string >::const_iterator it, itEnd = mModifierNames.end(); std::vector< std::string >::const_iterator itComp = mModifierCompartments.begin(); for (it = mModifierNames.begin(); it != itEnd; ++it, ++itComp) if (Modifier.first == *it && Modifier.second == *itComp) break; if (it == itEnd) { mModifierNames.push_back(Modifier.first); mModifierMult.push_back(1.0); mModifierCompartments.push_back(Modifier.second); mModifierDisplayNames.push_back(name); } } void CChemEqInterface::clearModifiers() { mModifierNames.clear(); mModifierMult.clear(); mModifierCompartments.clear(); mModifierDisplayNames.clear(); } std::string CChemEqInterface::writeElement(const std::string & name, C_FLOAT64 mult, bool expanded) { std::string Metabolite = name; // The last character must not be a ';' in a reaction. if (Metabolite[Metabolite.length() - 1] == ';') Metabolite = "\"" + Metabolite + "\""; if (isNumber(Metabolite)) Metabolite = "\"" + Metabolite + "\""; if (expanded) { std::string ces; C_INT32 i, imax = (C_INT32) mult; for (i = 0; i < imax; ++i) { if (i) ces += " + "; ces += Metabolite; } return ces; } else { if (mult == 1.0) return Metabolite; else return StringPrint("%g * %s", mult, Metabolite.c_str()); } } unsigned C_INT32 CChemEqInterface::getMolecularity(CFunctionParameter::Role role) const { const std::vector<C_FLOAT64> * tmpVector = NULL; if (role == CFunctionParameter::SUBSTRATE) tmpVector = &mSubstrateMult; else if (role == CFunctionParameter::PRODUCT) tmpVector = &mProductMult; else if (role == CFunctionParameter::MODIFIER) tmpVector = &mModifierMult; else fatalError(); C_INT32 ccc, i, imax = tmpVector->size(); ccc = 0; for (i = 0; i < imax; ++i) { if ((*tmpVector)[i] != (C_FLOAT64)(C_INT32)(*tmpVector)[i]) return C_INVALID_INDEX; ccc += (C_INT32)floor((*tmpVector)[i]); } return ccc; } void CChemEqInterface::reverse() { std::vector<std::string> dummyNames; std::vector<C_FLOAT64> dummyMults; std::vector<std::string> dummyCompartments; dummyNames = mSubstrateNames; dummyMults = mSubstrateMult; dummyCompartments = mSubstrateCompartments; mSubstrateNames = mProductNames; mSubstrateMult = mProductMult; mSubstrateCompartments = mProductCompartments; mProductNames = dummyNames; mProductMult = dummyMults; mProductCompartments = dummyCompartments; } std::set<std::string> CChemEqInterface::listOfNonUniqueMetabNames() const { std::set<std::string> ret; std::vector<std::string>::const_iterator it, itEnd; itEnd = mSubstrateNames.end(); for (it = mSubstrateNames.begin(); it != itEnd; ++it) if (!CMetabNameInterface::isUnique(mpModel, *it)) ret.insert(*it); itEnd = mProductNames.end(); for (it = mProductNames.begin(); it != itEnd; ++it) if (!CMetabNameInterface::isUnique(mpModel, *it)) ret.insert(*it); itEnd = mModifierNames.end(); for (it = mModifierNames.begin(); it != itEnd; ++it) if (!CMetabNameInterface::isUnique(mpModel, *it)) ret.insert(*it); return ret; } std::set< std::pair< std::string, std::string > > CChemEqInterface::listOfNonExistingMetabNames() const { std::set< std::pair< std::string, std::string > > ret; std::pair< std::string, std::string > Insert; std::vector<std::string>::const_iterator it, itComp, itEnd; itEnd = mSubstrateNames.end(); for (it = mSubstrateNames.begin(), itComp = mSubstrateCompartments.begin(); it != itEnd; ++it, ++itComp) if (!CMetabNameInterface::doesExist(mpModel, *it, *itComp)) { Insert.first = *it; Insert.second = *itComp; ret.insert(Insert); } itEnd = mProductNames.end(); for (it = mProductNames.begin(), itComp = mProductCompartments.begin(); it != itEnd; ++it, ++itComp) if (!CMetabNameInterface::doesExist(mpModel, *it, *itComp)) { Insert.first = *it; Insert.second = *itComp; ret.insert(Insert); } itEnd = mModifierNames.end(); for (it = mModifierNames.begin(), itComp = mModifierCompartments.begin(); it != itEnd; ++it, ++itComp) if (!CMetabNameInterface::doesExist(mpModel, *it, *itComp)) { Insert.first = *it; Insert.second = *itComp; ret.insert(Insert); } return ret; } bool CChemEqInterface::createNonExistingMetabs() { std::set< std::pair< std::string, std::string > > metabs = listOfNonExistingMetabNames(); bool ret; if (metabs.size() == 0) ret = false; else ret = true; std::set< std::pair< std::string, std::string > >::const_iterator it, itEnd; itEnd = metabs.end(); for (it = metabs.begin(); it != itEnd; ++it) { if (mpModel->getCompartments().getIndex(it->second) == C_INVALID_INDEX) mpModel->createCompartment(it->second, 1); mpModel->createMetabolite(it->first, it->second, 1.0, CModelEntity::REACTIONS); } // Due to the creation of metabolites the display names may have changed. buildDisplayNames(); return ret; } bool CChemEqInterface::isMulticompartment() const { bool Initialize = true; std::string Compartment = ""; std::vector< std::string >::const_iterator it; std::vector< std::string >::const_iterator end; for (it = mSubstrateCompartments.begin(), end = mSubstrateCompartments.end(); it != end; ++it) if (Initialize) { Compartment = *it; Initialize = false; } else if (Compartment != *it) return true; for (it = mProductCompartments.begin(), end = mProductCompartments.end(); it != end; ++it) if (Initialize) { Compartment = *it; Initialize = false; } else if (Compartment != *it) return true; for (it = mModifierCompartments.begin(), end = mModifierCompartments.end(); it != end; ++it) if (Initialize) { Compartment = *it; Initialize = false; } else if (Compartment != *it) return true; return false; } const CCompartment * CChemEqInterface::getCompartment() const { CChemEq ce; writeToChemEq(ce); if (ce.getCompartmentNumber() > 1) return NULL; else { const CMetab * metab = NULL; if (ce.getSubstrates().size()) metab = ce.getSubstrates()[0]->getMetabolite(); else if (ce.getProducts().size()) metab = ce.getProducts()[0]->getMetabolite(); if (metab) return metab->getCompartment(); else return NULL; } } /*static*/ std::string CChemEqInterface::getChemEqString(CModel * model, const CReaction & rea, bool expanded) { CChemEqInterface cei(model); cei.loadFromChemEq(rea.getChemEq()); return cei.getChemEqString(expanded); } /*static*/ void CChemEqInterface::setChemEqFromString(CModel * model, CReaction & rea, const std::string & ces) { CChemEqInterface cei(model); cei.setChemEqString(ces); cei.writeToChemEq(rea.getChemEq()); } /*static*/ bool CChemEqInterface::isValidEq(const std::string & eq) { // parse the description into a linked node tree std::istringstream buffer(eq); CChemEqParser Parser(&buffer); return (Parser.yyparse() == 0); }
29.150203
111
0.657181
[ "vector", "model" ]
29557ade669636738008024c6fe1177883b1976e
24,893
cpp
C++
src/base/attitude/SpiceAttitude.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
1
2020-05-16T16:58:21.000Z
2020-05-16T16:58:21.000Z
src/base/attitude/SpiceAttitude.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
null
null
null
src/base/attitude/SpiceAttitude.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
null
null
null
//$Id:$ //------------------------------------------------------------------------------ // SpiceAttitude //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002-2011 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under // FDSS Task order 28. // // Author: Wendy C. Shoan/GSFC // Created: 2010.04.16 // /** * Class implementation for the SpiceAttitude class. */ //------------------------------------------------------------------------------ #include <iostream> #include <sstream> #include <iomanip> #include "Attitude.hpp" #include "AttitudeException.hpp" #include "SpiceAttitude.hpp" #include "MessageInterface.hpp" //#define DEBUG_SPICE_ATTITUDE //#define DEBUG_SPICE_ATTITUDE_GET_SET //------------------------------------------------------------------------------ // static data //------------------------------------------------------------------------------ const std::string SpiceAttitude::PARAMETER_TEXT[SpiceAttitudeParamCount - AttitudeParamCount] = { "AttitudeKernelName", "SCClockKernelName", "FrameKernelName", }; const Gmat::ParameterType SpiceAttitude::PARAMETER_TYPE[SpiceAttitudeParamCount - AttitudeParamCount] = { Gmat::STRINGARRAY_TYPE, Gmat::STRINGARRAY_TYPE, Gmat::STRINGARRAY_TYPE, }; const Integer SpiceAttitude::UNDEFINED_NAIF_ID = -123456789; const Integer SpiceAttitude::UNDEFINED_NAIF_ID_REF_FRAME = -123456789; //------------------------------------------------------------------------------ // public methods //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // SpiceAttitude(const std::string &itsName) //------------------------------------------------------------------------------ /** * This method creates an object of the SpiceAttitude class * (default Constructor). */ //------------------------------------------------------------------------------ SpiceAttitude::SpiceAttitude(const std::string &attName) : Attitude("SpiceAttitude",attName), scName (""), naifId (UNDEFINED_NAIF_ID), refFrameNaifId (UNDEFINED_NAIF_ID_REF_FRAME) { parameterCount = SpiceAttitudeParamCount; objectTypeNames.push_back("SpiceAttitude"); attitudeModelName = "SpiceAttitude"; modifyCoordSysAllowed = false; setInitialAttitudeAllowed = false; #ifdef __USE_SPICE__ reader = new SpiceAttitudeKernelReader(); #endif ck.clear(); sclk.clear(); fk.clear(); } //------------------------------------------------------------------------------ // SpiceAttitude(const SpiceAttitude &att) //------------------------------------------------------------------------------ /** * This method creates an object of the SpiceAttitude class as a copy of the * specified SpiceAttitude class. * (copy constructor) * * @param <att> SpiceAttitude object to copy. */ //------------------------------------------------------------------------------ SpiceAttitude::SpiceAttitude(const SpiceAttitude& att) : Attitude(att), scName (att.scName), naifId (att.naifId), refFrameNaifId (att.refFrameNaifId) { ck.clear(); sclk.clear(); fk.clear(); ck = att.ck; sclk = att.sclk; fk = att.fk; #ifdef __USE_SPICE__ reader = (att.reader)->Clone(); #endif } //------------------------------------------------------------------------------ // SpiceAttitude& operator= (const SpiceAttitude& att) //------------------------------------------------------------------------------ /** * Assignment operator for the SpiceAttitude class. * * @param att the SpiceAttitude object whose data to assign to "this" * SpiceAttitude. * * @return "this" SpiceAttitude with data of input SpiceAttitude att. */ //------------------------------------------------------------------------------ SpiceAttitude& SpiceAttitude::operator=(const SpiceAttitude& att) { if (&att == this) return *this; Attitude::operator=(att); ck.clear(); sclk.clear(); fk.clear(); scName = att.scName; naifId = att.naifId; refFrameNaifId = att.refFrameNaifId; ck = att.ck; sclk = att.sclk; fk = att.fk; #ifdef __USE_SPICE__ if (reader) delete reader; reader = (att.reader)->Clone(); #endif return *this; } //------------------------------------------------------------------------------ // ~SpiceAttitude() //------------------------------------------------------------------------------ /** * Destroys the SpiceAttitude class (destructor). */ //------------------------------------------------------------------------------ SpiceAttitude::~SpiceAttitude() { #ifdef __USE_SPICE__ if (reader) delete reader; #endif ck.clear(); sclk.clear(); fk.clear(); } //--------------------------------------------------------------------------- // bool Initialize() //--------------------------------------------------------------------------- /** * Initializes the SpiceAttitude. * * @return Success flag. * */ //--------------------------------------------------------------------------- bool SpiceAttitude::Initialize() { #ifdef DEBUG_SPICE_ATTITUDE MessageInterface::ShowMessage("Entering SpiceAttitude::Initialize\n"); #endif bool isOK = Attitude::Initialize(); if (!isOK) return false; if (scName == "") { std::string errmsg = "Error - object name not set on SpiceAttitude object.\n"; throw AttitudeException(errmsg); } if (ck.empty()) { std::string errmsg = "Error - no CK pointing kernel(s) set on SpiceAttitude for object "; errmsg += scName + "\n"; throw AttitudeException(errmsg); } if (sclk.empty()) { std::string errmsg = "Error - no SCLK clock kernel(s) set on SpiceAttitude for object "; errmsg += scName + "\n"; throw AttitudeException(errmsg); } if (fk.empty()) { std::string warnmsg = "Warning - no FK frame kernel(s) set on SpiceAttitude for object "; warnmsg += scName + ". A Frame Kernel may be necessary.\n"; MessageInterface::ShowMessage(warnmsg.c_str()); } #ifdef __USE_SPICE__ // Load the CK kernel(s) for (StringArray::iterator j = ck.begin(); j != ck.end(); ++j) { reader->LoadKernel(*j); } // Load the SCLK kernel(s) for (StringArray::iterator j = sclk.begin(); j != sclk.end(); ++j) { reader->LoadKernel(*j); } // Load the FK kernel(s), if any for (StringArray::iterator j = fk.begin(); j != fk.end(); ++j) { reader->LoadKernel(*j); } #endif if (naifId == UNDEFINED_NAIF_ID) { #ifdef __USE_SPICE__ naifId = reader->GetNaifID(scName); #ifdef DEBUG_SPICE_ATTITUDE MessageInterface::ShowMessage( "Retrieved NAIF ID for %s -> %d\n", scName.c_str(), naifId); #endif if (naifId == 0) { std::string errmsg = "Error - NAIF ID not available for object \n"; errmsg += scName + "\n"; throw AttitudeException(errmsg); } #else std::string errmsg = "Error - NAIF ID not set on SpiceAttitude object.\n"; throw AttitudeException(errmsg); #endif } if (refFrameNaifId == UNDEFINED_NAIF_ID_REF_FRAME) { std::string errmsg = "Error - NAIF ID for object reference frame not set on SpiceAttitude object.\n"; throw AttitudeException(errmsg); } return true; } //------------------------------------------------------------------------------ // GmatBase* Clone() const //------------------------------------------------------------------------------ /** * This method returns a clone of the SpiceAttitude. * * @return clone of the SpiceAttitude. * */ //------------------------------------------------------------------------------ GmatBase* SpiceAttitude::Clone() const { return (new SpiceAttitude(*this)); } //------------------------------------------------------------------------------ // void SetObjectID(const std::string &objName, Integer objNaifId, // Integer objRefFrameNaifId) //------------------------------------------------------------------------------ /** * This method sets the object ID information (name, NAIF ID, reference frame * NAIF ID). * * @param objName name of the object for which to set the object ids * @param objNaifId NAIF ID of the object * @param objRefFrameNaifId reference frame NAIF ID * */ //------------------------------------------------------------------------------ void SpiceAttitude::SetObjectID(const std::string &objName, Integer objNaifId, Integer objRefFrameNaifId) { scName = objName; naifId = objNaifId; refFrameNaifId = objRefFrameNaifId; } //--------------------------------------------------------------------------- // const Rvector& GetQuaternion(Real atTime) //--------------------------------------------------------------------------- /** * Returns the attitude at time atTime as a quaternion. * * @param atTime time at which to compute the attitude. * * @return the quaternion representation of the attitude, computed at * time atTime. */ //--------------------------------------------------------------------------- const Rvector& SpiceAttitude::GetQuaternion(Real atTime) { ComputeCosineMatrixAndAngularVelocity(atTime); attitudeTime = atTime; quaternion = Attitude::ToQuaternion(dcm); return quaternion; } //--------------------------------------------------------------------------- // const Rvector3& GetEulerAngles(Real tTime) //--------------------------------------------------------------------------- /** * Returns the attitude at time atTime as an array of Euler angles. This * method assumes the previously set Euler sequence. * * @param atTime time at which to compute the attitude. * * @return the euler angle representation of the attitude, computed at * time atTime (radians). */ //--------------------------------------------------------------------------- const Rvector3& SpiceAttitude::GetEulerAngles(Real atTime) { ComputeCosineMatrixAndAngularVelocity(atTime); attitudeTime = atTime; eulerAngles = Attitude::ToEulerAngles(dcm, (Integer) eulerSequenceArray.at(0), (Integer) eulerSequenceArray.at(1), (Integer) eulerSequenceArray.at(2)); return eulerAngles; } //--------------------------------------------------------------------------- // const Rvector3& GetEulerAngles(Real atTime, // Integer seq1, Integer seq2, // Integer seq3) //--------------------------------------------------------------------------- /** * Returns the attitude at time atTime as an array of Euler angles. This * method uses the Euler sequence passed in here. * * @param atTime time at which to compute the attitude. * @param seq1 euler Sequence 1 * @param seq2 euler sequence 2 * @param seq3 euler sequence 3 * * @return the euler angle representation of the attitude, computed at * time atTime (radians). * @todo - figure out what to do if the time is the same, but the * Euler sequence is different that the last time it was computed. */ //--------------------------------------------------------------------------- const Rvector3& SpiceAttitude::GetEulerAngles(Real atTime, Integer seq1, Integer seq2, Integer seq3) { ComputeCosineMatrixAndAngularVelocity(atTime); attitudeTime = atTime; eulerAngles = Attitude::ToEulerAngles(dcm, seq1, seq2, seq3); return eulerAngles; } //--------------------------------------------------------------------------- // const Rmatrix33& GetCosineMatrix(Real atTime) //--------------------------------------------------------------------------- /** * Returns the attitude at time atTime as direction cosine matrix. * * @param atTime time at which to compute the attitude. * * @return the direction cosine matrix representation of the attitude, * computed at time atTime. */ //--------------------------------------------------------------------------- const Rmatrix33& SpiceAttitude::GetCosineMatrix(Real atTime) { ComputeCosineMatrixAndAngularVelocity(atTime); attitudeTime = atTime; return dcm; } //--------------------------------------------------------------------------- // const Rvector3& GetAngularVelocity(Real atTime) //--------------------------------------------------------------------------- /** * Returns the attitude rates at time atTime as an angular velocity. * * @param atTime time at which to compute the attitude. * * @return the angular velocity representation of the attitude rates, * computed at time atTime (radians/second). */ //--------------------------------------------------------------------------- const Rvector3& SpiceAttitude::GetAngularVelocity(Real atTime) { ComputeCosineMatrixAndAngularVelocity(atTime); attitudeTime = atTime; return angVel; } //--------------------------------------------------------------------------- // const Rvector3& GetEulerAngleRates(Real atTime) //--------------------------------------------------------------------------- /** * Returns the attitude rates at time atTime as an array of euler * angle rates. * * @param atTime time at which to compute the attitude. * * @return the euler angle rates representation of the attitude rates, * computed at time atTime (radians/second). */ //--------------------------------------------------------------------------- const Rvector3& SpiceAttitude::GetEulerAngleRates(Real atTime) { ComputeCosineMatrixAndAngularVelocity(atTime); attitudeTime = atTime; eulerAngles = GetEulerAngles(atTime); eulerAngleRates = Attitude::ToEulerAngleRates(angVel, eulerAngles, (Integer) eulerSequenceArray.at(0), (Integer) eulerSequenceArray.at(1), (Integer) eulerSequenceArray.at(2)); return eulerAngleRates; } //------------------------------------------------------------------------------ // std::string GetParameterText(const Integer id) const //------------------------------------------------------------------------------ /** * This method returns the parameter text, given the input parameter ID. * * @param <id> Id for the requested parameter text. * * @return parameter text for the requested parameter. * */ //------------------------------------------------------------------------------ std::string SpiceAttitude::GetParameterText(const Integer id) const { if (id >= AttitudeParamCount && id < SpiceAttitudeParamCount) return PARAMETER_TEXT[id - AttitudeParamCount]; return Attitude::GetParameterText(id); } //------------------------------------------------------------------------------ // Integer GetParameterID(const std::string &str) const //------------------------------------------------------------------------------ /** * This method returns the parameter ID, given the input parameter string. * * @param <str> string for the requested parameter. * * @return ID for the requested parameter. * */ //------------------------------------------------------------------------------ Integer SpiceAttitude::GetParameterID(const std::string &str) const { for (Integer i = AttitudeParamCount; i < SpiceAttitudeParamCount; i++) { if (str == PARAMETER_TEXT[i - AttitudeParamCount]) return i; } return Attitude::GetParameterID(str); } //------------------------------------------------------------------------------ // Gmat::ParameterType GetParameterType(const Integer id) const //------------------------------------------------------------------------------ /** * This method returns the parameter type, given the input parameter ID. * * @param <id> ID for the requested parameter. * * @return parameter type of the requested parameter. * */ //------------------------------------------------------------------------------ Gmat::ParameterType SpiceAttitude::GetParameterType(const Integer id) const { if (id >= AttitudeParamCount && id < SpiceAttitudeParamCount) return PARAMETER_TYPE[id - AttitudeParamCount]; return Attitude::GetParameterType(id); } //------------------------------------------------------------------------------ // std::string GetParameterTypeString(const Integer id) const //------------------------------------------------------------------------------ /** * This method returns the parameter type string, given the input parameter ID. * * @param <id> ID for the requested parameter. * * @return parameter type string of the requested parameter. * */ //------------------------------------------------------------------------------ std::string SpiceAttitude::GetParameterTypeString(const Integer id) const { return Attitude::PARAM_TYPE_STRING[GetParameterType(id)]; } //------------------------------------------------------------------------------ // std::string GetStringParameter(const Integer id, const Integer index) const //------------------------------------------------------------------------------ /** * This method returns the string parameter value, given the input * parameter ID. * * @param id ID for the requested parameter * @param index index into the array of strings * * @return string value of the requested parameter. * */ //------------------------------------------------------------------------------ std::string SpiceAttitude::GetStringParameter(const Integer id, const Integer index) const { if (id == ATTITUDE_KERNEL_NAME) { if ((index < 0) || (index >= (Integer) ck.size())) { std::string errmsg = "Error attempting to retrieve CK kernel name for object "; errmsg += scName + " - index out-of-bounds.\n"; throw AttitudeException(errmsg); } return ck.at(index); } if (id == SC_CLOCK_KERNEL_NAME) { if ((index < 0) || (index >= (Integer) sclk.size())) { std::string errmsg = "Error attempting to retrieve SCLK kernel name for object "; errmsg += scName + " - index out-of-bounds.\n"; throw AttitudeException(errmsg); } return sclk.at(index); } if (id == FRAME_KERNEL_NAME) { if ((index < 0) || (index >= (Integer) fk.size())) { std::string errmsg = "Error attempting to retrieve FK kernel name for object "; errmsg += scName + " - index out-of-bounds.\n"; throw AttitudeException(errmsg); } return fk.at(index); } return Attitude::GetStringParameter(id, index); } //------------------------------------------------------------------------------ // bool SetStringParameter(const Integer id, const std::string value, // const Integer index) //------------------------------------------------------------------------------ /** * This method sets the string parameter value, given the input * parameter ID. * * @param id ID for the requested parameter. * @param value string value for the requested parameter. * @param index index into the string array * * @exception <AttitudeException> thrown if value is out of range * * @return success flag. * */ //------------------------------------------------------------------------------ bool SpiceAttitude::SetStringParameter(const Integer id, const std::string &value, const Integer index) { #ifdef DEBUG_SPICE_ATTITUDE_GET_SET MessageInterface::ShowMessage( "Entering SetStringParameter with id = %d, value = \"%s\", index = %d\n", id, value.c_str(), index); #endif if (id == ATTITUDE_KERNEL_NAME) { if ((index < 0) || (index > (Integer) ck.size())) { std::string errmsg = "Error attempting to set CK kernel name for object "; errmsg += scName + " - index out-of-bounds.\n"; throw AttitudeException(errmsg); } if (index == (Integer) ck.size()) ck.push_back(value); else ck.at(index) = value; return true; } if (id == SC_CLOCK_KERNEL_NAME) { if ((index < 0) || (index > (Integer) sclk.size())) { std::string errmsg = "Error attempting to set SCLK kernel name for object "; errmsg += scName + " - index out-of-bounds.\n"; throw AttitudeException(errmsg); } if (index == (Integer) sclk.size()) sclk.push_back(value); else sclk.at(index) = value; return true; } if (id == FRAME_KERNEL_NAME) { if ((index < 0) || (index > (Integer) fk.size())) { std::string errmsg = "Error attempting to set FK kernel name for object "; errmsg += scName + " - index out-of-bounds.\n"; throw AttitudeException(errmsg); } if (index == (Integer) fk.size()) fk.push_back(value); else fk.at(index) = value; return true; } return Attitude::SetStringParameter(id, value, index); } //------------------------------------------------------------------------------ // bool SetStringParameter(const std::string label, const std::string value, // const Integer index) //------------------------------------------------------------------------------ /** * This method sets the string parameter value, given the input * parameter label. * * @param label string label for the requested parameter. * @param value string value for the requested parameter. * @param index index into the string array * * @exception <AttitudeException> thrown if value is out of range * * @return success flag. * */ //------------------------------------------------------------------------------ bool SpiceAttitude::SetStringParameter(const std::string label, const std::string &value, const Integer index) { return SetStringParameter(GetParameterID(label), value, index); } //------------------------------------------------------------------------------ // const StringArray& GetStringArrayParameter(const Integer id) const //------------------------------------------------------------------------------ /** * Gets the requested string array. * * @param id The integer ID for the parameter. * * @return The requested StringArray */ //------------------------------------------------------------------------------ const StringArray& SpiceAttitude::GetStringArrayParameter(const Integer id) const { if (id == ATTITUDE_KERNEL_NAME) return ck; else if (id == SC_CLOCK_KERNEL_NAME) return sclk; else if (id == FRAME_KERNEL_NAME) return fk; return Attitude::GetStringArrayParameter(id); } //------------------------------------------------------------------------------ // protected methods //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // virtual void ComputeCosineMatrixAndAngularVelocity(Real atTime) //------------------------------------------------------------------------------ /** * This method computes the current CosineMatrix at the input time atTime. * * @param atTime the A1Mjd time at which to compute the attitude. * */ //------------------------------------------------------------------------------ void SpiceAttitude::ComputeCosineMatrixAndAngularVelocity(Real atTime) { if (!isInitialized || needsReinit) Initialize(); #ifdef __USE_SPICE__ reader->GetTargetOrientation(scName, naifId, refFrameNaifId, atTime, dcm, angVel); #else std::string errmsg = "Error - attempting to use SpiceAttitude when "; errmsg += "SPICE is not included in the GMAT build.\n"; throw AttitudeException(errmsg); #endif } //------------------------------------------------------------------------------ // private methods //------------------------------------------------------------------------------ // none
35.060563
107
0.484674
[ "object" ]
2956e3a9161ea42b31ea7f8ea53d7d9ffc2236e6
2,777
cpp
C++
src/Tools/Algo/Matrix/Matrix.cpp
bonben/aff3ct
8e78123bfc0a377947ecb690ce1e0d70c0dc0a68
[ "MIT" ]
null
null
null
src/Tools/Algo/Matrix/Matrix.cpp
bonben/aff3ct
8e78123bfc0a377947ecb690ce1e0d70c0dc0a68
[ "MIT" ]
4
2018-09-27T16:46:31.000Z
2018-11-22T11:10:41.000Z
src/Tools/Algo/Matrix/Matrix.cpp
bonben/aff3ct
8e78123bfc0a377947ecb690ce1e0d70c0dc0a68
[ "MIT" ]
null
null
null
#include <string> #include <sstream> #include <vector> #include "Tools/Exception/exception.hpp" #include "Matrix.hpp" using namespace aff3ct; using namespace aff3ct::tools; Matrix ::Matrix(const size_t n_rows, const size_t n_cols) : n_rows (n_rows), n_cols (n_cols), rows_max_degree(0 ), cols_max_degree(0 ), n_connections (0 ) { } void Matrix ::self_transpose() { std::swap(n_rows, n_cols ); std::swap(rows_max_degree, cols_max_degree); } void Matrix ::self_turn(Way w) { if (w == Way::VERTICAL) { if (get_n_cols() > get_n_rows()) this->self_transpose(); } else if (w == Way::HORIZONTAL) { if (get_n_cols() < get_n_rows()) this->self_transpose(); } } Matrix::Way Matrix ::get_way() const { return (get_n_cols() >= get_n_rows()) ? Way::HORIZONTAL : Way::VERTICAL; } float Matrix ::compute_density() const { return ((float)n_connections / (float)(n_rows * n_cols)); } void Matrix ::check_indexes(const size_t row_index, const size_t col_index) const { if (col_index >= get_n_cols()) { std::stringstream message; message << "'col_index' has to be smaller than 'n_cols' ('col_index' = " << col_index << ", 'n_cols' = " << get_n_cols() << ")."; throw invalid_argument(__FILE__, __LINE__, __func__, message.str()); } if (row_index >= get_n_rows()) { std::stringstream message; message << "'row_index' has to be smaller than 'n_rows' ('row_index' = " << row_index << ", 'n_rows' = " << get_n_rows() << ")."; throw invalid_argument(__FILE__, __LINE__, __func__, message.str()); } } void Matrix ::self_resize(const size_t _n_rows, const size_t _n_cols) { n_rows = _n_rows; n_cols = _n_cols; } bool Matrix ::is_of_way(Way w) const noexcept { return get_way() == w; } void Matrix ::is_of_way_throw(Way w) const { if (!is_of_way(w)) { std::stringstream message; message << "This matrix way ('" << way_to_str(get_way()) << "') is not same as the given checked one ('" << way_to_str(w) << "')."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } } std::string Matrix ::way_to_str(Way w) { std::string str; switch(w) { case Way::HORIZONTAL: str = "HORIZONTAL"; break; case Way::VERTICAL: str = "VERTICAL"; break; } if (str.empty()) // this 'if' is a test outside the switch case (instead of default) to keep the compiler check that all // cases of 'Way' are well represented. { std::stringstream message; message << "The way 'w' does not represent a matrix way ('w' = " << (short)w << ")."; throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str()); } return str; } std::ostream& operator<<(std::ostream& os, const Matrix& sm) { sm.print(0, os); return os; }
19.978417
121
0.646381
[ "vector" ]
295771468296e7f0ef8c8e070d914d395774f20f
447
cpp
C++
src/BeginTranOperation.cpp
robin-karlsson/node-sqlserver-v8
60bea3e077d7b50f2fe6280337bf793704a2244e
[ "Apache-2.0" ]
124
2015-09-25T06:56:10.000Z
2022-03-18T23:14:11.000Z
src/BeginTranOperation.cpp
robin-karlsson/node-sqlserver-v8
60bea3e077d7b50f2fe6280337bf793704a2244e
[ "Apache-2.0" ]
222
2015-09-17T23:37:17.000Z
2022-03-28T18:32:53.000Z
expressjs/node_modules/msnodesqlv8/src/BeginTranOperation.cpp
spaykee/AlternativeMethodologies
aaf100dc298045422931b9c8caf135a9597d9cf2
[ "MIT" ]
66
2015-12-28T10:14:26.000Z
2022-03-02T15:48:43.000Z
#include "OdbcConnection.h" #include <BeginTranOperation.h> namespace mssql { BeginTranOperation::BeginTranOperation(const shared_ptr<OdbcConnection> &connection, const Local<Object> callback) : OdbcOperation(connection, callback) { } bool BeginTranOperation::TryInvokeOdbc() { return _connection->try_begin_tran(); } Local<Value> BeginTranOperation::CreateCompletionArg() { const nodeTypeFactory fact; return fact.null(); } }
20.318182
115
0.767338
[ "object" ]
295beb6621d7ad2c6d5202023143d605fca31359
921
cpp
C++
libs/random/test/test_random_number_generator.cpp
jmuskaan72/Boost
047e36c01841a8cd6a5c74d4e3034da46e327bc1
[ "BSL-1.0" ]
198
2015-01-13T05:47:18.000Z
2022-03-09T04:46:46.000Z
libs/random/test/test_random_number_generator.cpp
xiaoliang2121/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
[ "BSL-1.0" ]
4
2015-03-19T08:23:23.000Z
2019-06-24T07:48:47.000Z
libs/random/test/test_random_number_generator.cpp
xiaoliang2121/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
[ "BSL-1.0" ]
139
2015-01-15T20:09:31.000Z
2022-01-31T15:21:16.000Z
/* boost test_random_number_generator.cpp * * Copyright Jens Maurer 2000 * Copyright Steven Watanabe 2011 * Distributed under the Boost Software License, Version 1.0. (See * accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * $Id: test_random_number_generator.cpp 71018 2011-04-05 21:27:52Z steven_watanabe $ */ #include <boost/random/random_number_generator.hpp> #include <boost/random/mersenne_twister.hpp> #include <algorithm> #include <vector> #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(test_random_shuffle) { boost::mt19937 engine(1234); boost::random::random_number_generator<boost::mt19937> generator(engine); std::vector<int> testVec; for (int i = 0; i < 200; ++i) { testVec.push_back(i); } std::random_shuffle(testVec.begin(), testVec.end(), generator); }
27.088235
86
0.705755
[ "vector" ]
295db70a9eb7c10a98bd3e92757b2fa7c838e1b1
26,180
cc
C++
media/capture/video/file_video_capture_device.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
media/capture/video/file_video_capture_device.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
media/capture/video/file_video_capture_device.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/capture/video/file_video_capture_device.h" #include <stddef.h> #include <memory> #include <utility> #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/macros.h" #include "base/numerics/ranges.h" #include "base/single_thread_task_runner.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/threading/thread_task_runner_handle.h" #include "media/base/video_frame.h" #include "media/capture/mojom/image_capture_types.h" #include "media/capture/video/blob_utils.h" #include "media/capture/video/gpu_memory_buffer_utils.h" #include "media/capture/video_capture_types.h" #include "media/parsers/jpeg_parser.h" #include "third_party/libyuv/include/libyuv.h" namespace media { namespace { int gcd(int a, int b) { int c; c = a % b; while (c != 0) { a = b; b = c; c = a % b; } return (b); } } // namespace static const int kY4MHeaderMaxSize = 200; static const char kY4MSimpleFrameDelimiter[] = "FRAME"; static const int kY4MSimpleFrameDelimiterSize = 6; static const float kMJpegFrameRate = 30.0f; int ParseY4MInt(const base::StringPiece& token) { int temp_int; CHECK(base::StringToInt(token, &temp_int)) << token; return temp_int; } // Extract numerator and denominator out of a token that must have the aspect // numerator:denominator, both integer numbers. void ParseY4MRational(const base::StringPiece& token, int* numerator, int* denominator) { size_t index_divider = token.find(':'); CHECK_NE(index_divider, token.npos); *numerator = ParseY4MInt(token.substr(0, index_divider)); *denominator = ParseY4MInt(token.substr(index_divider + 1, token.length())); CHECK(*denominator); } // This function parses the ASCII string in |header| as belonging to a Y4M file, // returning the collected format in |video_format|. For a non authoritative // explanation of the header format, check // http://wiki.multimedia.cx/index.php?title=YUV4MPEG2 // Restrictions: Only interlaced I420 pixel format is supported, and pixel // aspect ratio is ignored. // Implementation notes: Y4M header should end with an ASCII 0x20 (whitespace) // character, however all examples mentioned in the Y4M header description end // with a newline character instead. Also, some headers do _not_ specify pixel // format, in this case it means I420. // This code was inspired by third_party/libvpx/.../y4minput.* . void ParseY4MTags(const std::string& file_header, VideoCaptureFormat* video_format) { VideoCaptureFormat format; format.pixel_format = PIXEL_FORMAT_I420; size_t index = 0; size_t blank_position = 0; base::StringPiece token; while ((blank_position = file_header.find_first_of("\n ", index)) != std::string::npos) { // Every token is supposed to have an identifier letter and a bunch of // information immediately after, which we extract into a |token| here. token = base::StringPiece(&file_header[index + 1], blank_position - index - 1); CHECK(!token.empty()); switch (file_header[index]) { case 'W': format.frame_size.set_width(ParseY4MInt(token)); break; case 'H': format.frame_size.set_height(ParseY4MInt(token)); break; case 'F': { // If the token is "FRAME", it means we have finished with the header. if (token[0] == 'R') break; int fps_numerator, fps_denominator; ParseY4MRational(token, &fps_numerator, &fps_denominator); format.frame_rate = fps_numerator / fps_denominator; break; } case 'I': // Interlacing is ignored, but we don't like mixed modes. CHECK_NE(token[0], 'm'); break; case 'A': // Pixel aspect ratio ignored. break; case 'C': CHECK(token == "420" || token == "420jpeg" || token == "420mpeg2" || token == "420paldv") << token; // Only I420 is supported, and we fudge the variants. break; default: break; } // We're done if we have found a newline character right after the token. if (file_header[blank_position] == '\n') break; index = blank_position + 1; } // Last video format semantic correctness check before sending it back. CHECK(format.IsValid()); *video_format = format; } class VideoFileParser { public: explicit VideoFileParser(const base::FilePath& file_path); virtual ~VideoFileParser(); // Parses file header and collects format information in |capture_format|. virtual bool Initialize(VideoCaptureFormat* capture_format) = 0; // Gets the start pointer of next frame and stores current frame size in // |frame_size|. virtual const uint8_t* GetNextFrame(int* frame_size) = 0; protected: const base::FilePath file_path_; int frame_size_; size_t current_byte_index_; size_t first_frame_byte_index_; }; class Y4mFileParser final : public VideoFileParser { public: explicit Y4mFileParser(const base::FilePath& file_path); // VideoFileParser implementation, class methods. ~Y4mFileParser() override; bool Initialize(VideoCaptureFormat* capture_format) override; const uint8_t* GetNextFrame(int* frame_size) override; private: std::unique_ptr<base::File> file_; std::unique_ptr<uint8_t[]> video_frame_; DISALLOW_COPY_AND_ASSIGN(Y4mFileParser); }; class MjpegFileParser final : public VideoFileParser { public: explicit MjpegFileParser(const base::FilePath& file_path); // VideoFileParser implementation, class methods. ~MjpegFileParser() override; bool Initialize(VideoCaptureFormat* capture_format) override; const uint8_t* GetNextFrame(int* frame_size) override; private: std::unique_ptr<base::MemoryMappedFile> mapped_file_; DISALLOW_COPY_AND_ASSIGN(MjpegFileParser); }; VideoFileParser::VideoFileParser(const base::FilePath& file_path) : file_path_(file_path), frame_size_(0), current_byte_index_(0), first_frame_byte_index_(0) {} VideoFileParser::~VideoFileParser() = default; Y4mFileParser::Y4mFileParser(const base::FilePath& file_path) : VideoFileParser(file_path) {} Y4mFileParser::~Y4mFileParser() = default; bool Y4mFileParser::Initialize(VideoCaptureFormat* capture_format) { file_ = std::make_unique<base::File>( file_path_, base::File::FLAG_OPEN | base::File::FLAG_READ); if (!file_->IsValid()) { DLOG(ERROR) << file_path_.value() << ", error: " << base::File::ErrorToString(file_->error_details()); return false; } std::string header(kY4MHeaderMaxSize, '\0'); file_->Read(0, &header[0], header.size()); const size_t header_end = header.find(kY4MSimpleFrameDelimiter); CHECK_NE(header_end, header.npos); ParseY4MTags(header, capture_format); first_frame_byte_index_ = header_end + kY4MSimpleFrameDelimiterSize; current_byte_index_ = first_frame_byte_index_; frame_size_ = VideoFrame::AllocationSize(capture_format->pixel_format, capture_format->frame_size); return true; } const uint8_t* Y4mFileParser::GetNextFrame(int* frame_size) { if (!video_frame_) video_frame_.reset(new uint8_t[frame_size_]); int result = file_->Read(current_byte_index_, reinterpret_cast<char*>(video_frame_.get()), frame_size_); // If we passed EOF to base::File, it will return 0 read characters. In that // case, reset the pointer and read again. if (result != frame_size_) { CHECK_EQ(result, 0); current_byte_index_ = first_frame_byte_index_; CHECK_EQ( file_->Read(current_byte_index_, reinterpret_cast<char*>(video_frame_.get()), frame_size_), frame_size_); } else { current_byte_index_ += frame_size_ + kY4MSimpleFrameDelimiterSize; } *frame_size = frame_size_; return video_frame_.get(); } MjpegFileParser::MjpegFileParser(const base::FilePath& file_path) : VideoFileParser(file_path) {} MjpegFileParser::~MjpegFileParser() = default; bool MjpegFileParser::Initialize(VideoCaptureFormat* capture_format) { mapped_file_ = std::make_unique<base::MemoryMappedFile>(); if (!mapped_file_->Initialize(file_path_) || !mapped_file_->IsValid()) { LOG(ERROR) << "File memory map error: " << file_path_.value(); return false; } JpegParseResult result; if (!ParseJpegStream(mapped_file_->data(), mapped_file_->length(), &result)) return false; frame_size_ = result.image_size; if (frame_size_ > static_cast<int>(mapped_file_->length())) { LOG(ERROR) << "File is incomplete"; return false; } VideoCaptureFormat format; format.pixel_format = PIXEL_FORMAT_MJPEG; format.frame_size.set_width(result.frame_header.visible_width); format.frame_size.set_height(result.frame_header.visible_height); format.frame_rate = kMJpegFrameRate; if (!format.IsValid()) return false; *capture_format = format; return true; } const uint8_t* MjpegFileParser::GetNextFrame(int* frame_size) { const uint8_t* buf_ptr = mapped_file_->data() + current_byte_index_; JpegParseResult result; if (!ParseJpegStream(buf_ptr, mapped_file_->length() - current_byte_index_, &result)) { return nullptr; } *frame_size = frame_size_ = result.image_size; current_byte_index_ += frame_size_; // Reset the pointer to play repeatedly. if (current_byte_index_ >= mapped_file_->length()) current_byte_index_ = first_frame_byte_index_; return buf_ptr; } // static bool FileVideoCaptureDevice::GetVideoCaptureFormat( const base::FilePath& file_path, VideoCaptureFormat* video_format) { std::unique_ptr<VideoFileParser> file_parser = GetVideoFileParser(file_path, video_format); return file_parser != nullptr; } // static std::unique_ptr<VideoFileParser> FileVideoCaptureDevice::GetVideoFileParser( const base::FilePath& file_path, VideoCaptureFormat* video_format) { std::unique_ptr<VideoFileParser> file_parser; std::string file_name(file_path.value().begin(), file_path.value().end()); if (base::EndsWith(file_name, "y4m", base::CompareCase::INSENSITIVE_ASCII)) { file_parser = std::make_unique<Y4mFileParser>(file_path); } else if (base::EndsWith(file_name, "mjpeg", base::CompareCase::INSENSITIVE_ASCII)) { file_parser = std::make_unique<MjpegFileParser>(file_path); } else { LOG(ERROR) << "Unsupported file format."; return file_parser; } if (!file_parser->Initialize(video_format)) { file_parser.reset(); } return file_parser; } std::unique_ptr<uint8_t[]> FileVideoCaptureDevice::CropPTZRegion( const uint8_t* frame, size_t frame_buffer_size) { CHECK(frame); const gfx::Size& frame_size = capture_format_.frame_size; uint32_t fourcc; std::unique_ptr<uint8_t[]> jpeg_to_i420_buffer_; switch (capture_format_.pixel_format) { case PIXEL_FORMAT_MJPEG: // |libyuv::ConvertToI420| don't support cropping MJPG into different // width and thus require transform to i420 first. if ([&frame, &frame_buffer_size, &frame_size, &jpeg_to_i420_buffer_]() { const size_t i420_buffer_size = VideoFrame::AllocationSize(PIXEL_FORMAT_I420, frame_size); jpeg_to_i420_buffer_.reset(new uint8_t[i420_buffer_size]); uint8_t* dst_yp = jpeg_to_i420_buffer_.get(); uint8_t* dst_up = dst_yp + VideoFrame::PlaneSize(PIXEL_FORMAT_I420, 0, frame_size) .GetArea(); uint8_t* dst_vp = dst_up + VideoFrame::PlaneSize(PIXEL_FORMAT_I420, 1, frame_size) .GetArea(); int dst_yp_stride = frame_size.width(); int dst_up_stride = dst_yp_stride / 2; int dst_vp_stride = dst_yp_stride / 2; return libyuv::ConvertToI420( frame, frame_buffer_size, dst_yp, dst_yp_stride, dst_up, dst_up_stride, dst_vp, dst_vp_stride, /* crop_x */ 0, /* crop_y */ 0, /* src_width */ frame_size.width(), /* src_height */ frame_size.height(), /* crop_width */ frame_size.width(), /* crop_height */ frame_size.height(), libyuv::RotationMode::kRotate0, libyuv::FOURCC_MJPG); }()) { LOG(ERROR) << "Failed to convert MJPEG to i420 for ptz transform"; } frame = jpeg_to_i420_buffer_.get(); frame_buffer_size = VideoFrame::AllocationSize(PIXEL_FORMAT_I420, frame_size); ABSL_FALLTHROUGH_INTENDED; case PIXEL_FORMAT_I420: fourcc = libyuv::FOURCC_I420; break; default: LOG(ERROR) << "Unsupported file format for ptz transform."; return {}; } // Crop zoomed region. const int crop_width = (zoom_max_levels_ - zoom_) * aspect_ratio_numerator_; const int crop_height = (zoom_max_levels_ - zoom_) * aspect_ratio_denominator_; const gfx::Size crop_size(crop_width, crop_height); const int crop_x = std::min(pan_ * aspect_ratio_numerator_, frame_size.width() - crop_width); const int crop_y = std::min((zoom_max_levels_ - 1 - tilt_) * aspect_ratio_denominator_, frame_size.height() - crop_height); const size_t crop_buffer_size = VideoFrame::AllocationSize(PIXEL_FORMAT_I420, crop_size); std::unique_ptr<uint8_t[]> crop_frame(new uint8_t[crop_buffer_size]); uint8_t* crop_yp = crop_frame.get(); uint8_t* crop_up = crop_yp + VideoFrame::PlaneSize(PIXEL_FORMAT_I420, 0, crop_size).GetArea(); uint8_t* crop_vp = crop_up + VideoFrame::PlaneSize(PIXEL_FORMAT_I420, 1, crop_size).GetArea(); int crop_yp_stride = crop_width; int crop_up_stride = crop_yp_stride / 2; int crop_vp_stride = crop_yp_stride / 2; if (libyuv::ConvertToI420(frame, frame_buffer_size, crop_yp, crop_yp_stride, crop_up, crop_up_stride, crop_vp, crop_vp_stride, crop_x, crop_y, frame_size.width(), frame_size.height(), crop_width, crop_height, libyuv::RotationMode::kRotate0, fourcc)) { LOG(ERROR) << "Failed to crop image for ptz transform."; return {}; } if (crop_size == frame_size) return crop_frame; // Scale cropped region to original size. const auto& scale_size = frame_size; const size_t scale_buffer_size = VideoFrame::AllocationSize(PIXEL_FORMAT_I420, scale_size); std::unique_ptr<uint8_t[]> scale_frame(new uint8_t[scale_buffer_size]); uint8_t* scale_yp = scale_frame.get(); uint8_t* scale_up = scale_yp + VideoFrame::PlaneSize(PIXEL_FORMAT_I420, 0, scale_size).GetArea(); uint8_t* scale_vp = scale_up + VideoFrame::PlaneSize(PIXEL_FORMAT_I420, 1, scale_size).GetArea(); int scale_yp_stride = scale_size.width(); int scale_up_stride = scale_yp_stride / 2; int scale_vp_stride = scale_yp_stride / 2; if (libyuv::I420Scale(crop_yp, crop_yp_stride, crop_up, crop_up_stride, crop_vp, crop_vp_stride, crop_width, crop_height, scale_yp, scale_yp_stride, scale_up, scale_up_stride, scale_vp, scale_vp_stride, scale_size.width(), scale_size.height(), libyuv::FilterMode::kFilterBilinear)) { LOG(ERROR) << "Failed to scale image for ptz transform."; return {}; } return scale_frame; } FileVideoCaptureDevice::FileVideoCaptureDevice( const base::FilePath& file_path, std::unique_ptr<gpu::GpuMemoryBufferSupport> gmb_support) : capture_thread_("CaptureThread"), file_path_(file_path), gmb_support_(gmb_support ? std::move(gmb_support) : std::make_unique<gpu::GpuMemoryBufferSupport>()) {} FileVideoCaptureDevice::~FileVideoCaptureDevice() { DCHECK(thread_checker_.CalledOnValidThread()); // Check if the thread is running. // This means that the device have not been DeAllocated properly. CHECK(!capture_thread_.IsRunning()); } void FileVideoCaptureDevice::AllocateAndStart( const VideoCaptureParams& params, std::unique_ptr<VideoCaptureDevice::Client> client) { DCHECK(thread_checker_.CalledOnValidThread()); CHECK(!capture_thread_.IsRunning()); capture_thread_.Start(); capture_thread_.task_runner()->PostTask( FROM_HERE, base::BindOnce(&FileVideoCaptureDevice::OnAllocateAndStart, base::Unretained(this), params, std::move(client))); } void FileVideoCaptureDevice::StopAndDeAllocate() { DCHECK(thread_checker_.CalledOnValidThread()); CHECK(capture_thread_.IsRunning()); capture_thread_.task_runner()->PostTask( FROM_HERE, base::BindOnce(&FileVideoCaptureDevice::OnStopAndDeAllocate, base::Unretained(this))); capture_thread_.Stop(); } void FileVideoCaptureDevice::GetPhotoState(GetPhotoStateCallback callback) { DCHECK(thread_checker_.CalledOnValidThread()); CHECK(capture_thread_.IsRunning()); capture_thread_.task_runner()->PostTask( FROM_HERE, base::BindOnce(&FileVideoCaptureDevice::OnGetPhotoState, base::Unretained(this), std::move(callback))); } void FileVideoCaptureDevice::OnGetPhotoState(GetPhotoStateCallback callback) { DCHECK(capture_thread_.task_runner()->BelongsToCurrentThread()); auto photo_capabilities = mojo::CreateEmptyPhotoState(); int height = capture_format_.frame_size.height(); photo_capabilities->height = mojom::Range::New(height, height, height, 0); int width = capture_format_.frame_size.width(); photo_capabilities->width = mojom::Range::New(width, width, width, 0); if (zoom_max_levels_ > 0) { photo_capabilities->pan = mojom::Range::New(); photo_capabilities->pan->current = pan_; photo_capabilities->pan->max = zoom_max_levels_ - 1; photo_capabilities->pan->min = 0; photo_capabilities->pan->step = 1; photo_capabilities->tilt = mojom::Range::New(); photo_capabilities->tilt->current = tilt_; photo_capabilities->tilt->max = zoom_max_levels_ - 1; photo_capabilities->tilt->min = 0; photo_capabilities->tilt->step = 1; photo_capabilities->zoom = mojom::Range::New(); photo_capabilities->zoom->current = zoom_; photo_capabilities->zoom->max = zoom_max_levels_ - 1; photo_capabilities->zoom->min = 0; photo_capabilities->zoom->step = 1; } std::move(callback).Run(std::move(photo_capabilities)); } void FileVideoCaptureDevice::SetPhotoOptions(mojom::PhotoSettingsPtr settings, SetPhotoOptionsCallback callback) { DCHECK(thread_checker_.CalledOnValidThread()); CHECK(capture_thread_.IsRunning()); capture_thread_.task_runner()->PostTask( FROM_HERE, base::BindOnce(&FileVideoCaptureDevice::OnSetPhotoOptions, base::Unretained(this), std::move(settings), std::move(callback))); } void FileVideoCaptureDevice::OnSetPhotoOptions( mojom::PhotoSettingsPtr settings, SetPhotoOptionsCallback callback) { DCHECK(capture_thread_.task_runner()->BelongsToCurrentThread()); if (settings->has_height && settings->height != capture_format_.frame_size.height()) { return; } if (settings->has_width && settings->width != capture_format_.frame_size.width()) { return; } if (settings->has_torch && settings->torch) return; if (settings->has_red_eye_reduction && settings->red_eye_reduction) return; if (settings->has_exposure_compensation || settings->has_exposure_time || settings->has_color_temperature || settings->has_iso || settings->has_brightness || settings->has_contrast || settings->has_saturation || settings->has_sharpness || settings->has_focus_distance || settings->has_fill_light_mode) { return; } if (settings->has_pan) { pan_ = base::ClampToRange(int(settings->pan), 0, zoom_max_levels_); } if (settings->has_tilt) { tilt_ = base::ClampToRange(int(settings->tilt), 0, zoom_max_levels_); } if (settings->has_zoom) { zoom_ = base::ClampToRange(int(settings->zoom), 0, zoom_max_levels_); } std::move(callback).Run(true); } void FileVideoCaptureDevice::TakePhoto(TakePhotoCallback callback) { DCHECK(thread_checker_.CalledOnValidThread()); base::AutoLock lock(lock_); take_photo_callbacks_.push(std::move(callback)); } void FileVideoCaptureDevice::OnAllocateAndStart( const VideoCaptureParams& params, std::unique_ptr<VideoCaptureDevice::Client> client) { DCHECK(capture_thread_.task_runner()->BelongsToCurrentThread()); client_ = std::move(client); if (params.buffer_type == VideoCaptureBufferType::kGpuMemoryBuffer) video_capture_use_gmb_ = true; DCHECK(!file_parser_); file_parser_ = GetVideoFileParser(file_path_, &capture_format_); if (!file_parser_) { client_->OnError( VideoCaptureError::kFileVideoCaptureDeviceCouldNotOpenVideoFile, FROM_HERE, "Could not open Video file"); return; } zoom_max_levels_ = gcd(capture_format_.frame_size.width(), capture_format_.frame_size.height()); aspect_ratio_numerator_ = capture_format_.frame_size.width() / zoom_max_levels_; aspect_ratio_denominator_ = capture_format_.frame_size.height() / zoom_max_levels_; zoom_ = 0; pan_ = 0; tilt_ = zoom_max_levels_ - 1; DVLOG(1) << "Opened video file " << capture_format_.frame_size.ToString() << ", fps: " << capture_format_.frame_rate; client_->OnStarted(); capture_thread_.task_runner()->PostTask( FROM_HERE, base::BindOnce(&FileVideoCaptureDevice::OnCaptureTask, base::Unretained(this))); } void FileVideoCaptureDevice::OnStopAndDeAllocate() { DCHECK(capture_thread_.task_runner()->BelongsToCurrentThread()); file_parser_.reset(); client_.reset(); next_frame_time_ = base::TimeTicks(); } void FileVideoCaptureDevice::OnCaptureTask() { DCHECK(capture_thread_.task_runner()->BelongsToCurrentThread()); if (!client_) return; base::AutoLock lock(lock_); // Give the captured frame to the client. int frame_size = 0; const uint8_t* frame_ptr = file_parser_->GetNextFrame(&frame_size); CHECK(frame_ptr); auto ptz_frame = CropPTZRegion(frame_ptr, frame_size); CHECK(ptz_frame); const base::TimeTicks current_time = base::TimeTicks::Now(); if (first_ref_time_.is_null()) first_ref_time_ = current_time; if (video_capture_use_gmb_) { const gfx::Size& buffer_size = capture_format_.frame_size; std::unique_ptr<gfx::GpuMemoryBuffer> gmb; VideoCaptureDevice::Client::Buffer capture_buffer; auto reserve_result = AllocateNV12GpuMemoryBuffer( client_.get(), buffer_size, gmb_support_.get(), &gmb, &capture_buffer); if (reserve_result != VideoCaptureDevice::Client::ReserveResult::kSucceeded) { client_->OnFrameDropped( ConvertReservationFailureToFrameDropReason(reserve_result)); DVLOG(2) << __func__ << " frame was dropped."; return; } ScopedNV12GpuMemoryBufferMapping scoped_mapping(std::move(gmb)); const uint8_t* src_y_plane = ptz_frame.get(); const uint8_t* src_u_plane = ptz_frame.get() + VideoFrame::PlaneSize(PIXEL_FORMAT_I420, 0, buffer_size).GetArea(); const uint8_t* src_v_plane = ptz_frame.get() + VideoFrame::PlaneSize(PIXEL_FORMAT_I420, 0, buffer_size).GetArea() + VideoFrame::PlaneSize(PIXEL_FORMAT_I420, 1, buffer_size).GetArea(); libyuv::I420ToNV12( src_y_plane, buffer_size.width(), src_u_plane, buffer_size.width() / 2, src_v_plane, buffer_size.width() / 2, scoped_mapping.y_plane(), scoped_mapping.y_stride(), scoped_mapping.uv_plane(), scoped_mapping.uv_stride(), buffer_size.width(), buffer_size.height()); VideoCaptureFormat modified_format = capture_format_; // When GpuMemoryBuffer is used, the frame data is opaque to the CPU for // most of the time. Currently the only supported underlying format is // NV12. modified_format.pixel_format = PIXEL_FORMAT_NV12; client_->OnIncomingCapturedBuffer(std::move(capture_buffer), modified_format, current_time, current_time - first_ref_time_); } else { // Leave the color space unset for compatibility purposes but this // information should be retrieved from the container when possible. client_->OnIncomingCapturedData( ptz_frame.get(), frame_size, capture_format_, gfx::ColorSpace(), 0 /* clockwise_rotation */, false /* flip_y */, current_time, current_time - first_ref_time_); } // Process waiting photo callbacks while (!take_photo_callbacks_.empty()) { auto cb = std::move(take_photo_callbacks_.front()); take_photo_callbacks_.pop(); mojom::BlobPtr blob = RotateAndBlobify(ptz_frame.get(), frame_size, capture_format_, 0); if (!blob) continue; std::move(cb).Run(std::move(blob)); } // Reschedule next CaptureTask. const base::TimeDelta frame_interval = base::TimeDelta::FromMicroseconds(1E6 / capture_format_.frame_rate); if (next_frame_time_.is_null()) { next_frame_time_ = current_time + frame_interval; } else { next_frame_time_ += frame_interval; // Don't accumulate any debt if we are lagging behind - just post next frame // immediately and continue as normal. if (next_frame_time_ < current_time) next_frame_time_ = current_time; } base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&FileVideoCaptureDevice::OnCaptureTask, base::Unretained(this)), next_frame_time_ - current_time); } } // namespace media
35.961538
80
0.693239
[ "transform" ]
295e046aefe96833f76fbc82417480c0bb84f7e9
1,527
cpp
C++
regression/esbmc-cpp11/cpp/ch4_12/main.cpp
correcthorsebatterystaple/esbmc
1fc1aed3b7a4aa3a16c3fcd4a4f67f477da0c4cc
[ "BSD-3-Clause" ]
null
null
null
regression/esbmc-cpp11/cpp/ch4_12/main.cpp
correcthorsebatterystaple/esbmc
1fc1aed3b7a4aa3a16c3fcd4a4f67f477da0c4cc
[ "BSD-3-Clause" ]
null
null
null
regression/esbmc-cpp11/cpp/ch4_12/main.cpp
correcthorsebatterystaple/esbmc
1fc1aed3b7a4aa3a16c3fcd4a4f67f477da0c4cc
[ "BSD-3-Clause" ]
null
null
null
// Fig. 4.14: fig04_14.cpp // Create GradeBook object and invoke its determineClassAverage function. #include "GradeBook.h" // include definition of class GradeBook int main() { // create GradeBook object myGradeBook and // pass course name to constructor GradeBook myGradeBook( "CS101 C++ Programming" ); myGradeBook.displayMessage(); // display welcome message myGradeBook.determineClassAverage(); // find average of 10 grades } // end main /************************************************************************** * (C) Copyright 1992-2014 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * **************************************************************************/
52.655172
76
0.584807
[ "object" ]
296315686fae0ed28f53f1c3b358a36620e4e1c5
19,905
cpp
C++
frame/file/src/filestore.cpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
frame/file/src/filestore.cpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
frame/file/src/filestore.cpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
// frame/file/src/filestore.cpp // // Copyright (c) 2014 Valentin Palade (vipalade @ gmail . com) // // This file is part of SolidFrame framework. // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt. // #include "frame/file/filestore.hpp" #ifdef HAS_CPP11 #define HASH_NS std #include <functional> #else #include "boost/functional/hash.hpp" #define HASH_NS boost #endif #include "system/atomic.hpp" #include "system/directory.hpp" #include "system/debug.hpp" #include "utility/binaryseeker.hpp" #include "utility/stack.hpp" #include "utility/sharedmutex.hpp" #include "filetemp.hpp" #include <algorithm> #include <unordered_set> #include <cstdio> namespace solid{ namespace frame{ namespace file{ uint32 dbgid(){ static uint32 id = Debug::the().registerModule("frame_file"); return id; } //--------------------------------------------------------------------------- // Utf8Controller::Data //--------------------------------------------------------------------------- typedef ATOMIC_NS::atomic<size_t> AtomicSizeT; typedef std::pair<size_t, size_t> SizePairT; typedef std::vector<SizePairT> SizePairVectorT; typedef std::vector<size_t> SizeVectorT; typedef Stack<size_t> SizeStackT; typedef std::deque<Utf8PathStub> PathDequeT; struct TempWaitStub{ TempWaitStub( UidT const &_uid = frame::invalid_uid(), File *_pfile = NULL, uint64 _size = 0, size_t _value = 0 ):objuid(_uid), pfile(_pfile), size(_size), value(_value){} void clear(){ pfile = NULL; } bool empty()const{ return pfile == NULL; } UidT objuid; File *pfile; uint64 size; size_t value; }; typedef std::deque<TempWaitStub> TempWaitDequeT; typedef std::vector<TempWaitStub> TempWaitVectorT; HASH_NS::hash<std::string> stringhasher; struct PathEqual{ bool operator()(const Utf8PathStub* _req1, const Utf8PathStub* _req2)const{ return _req1->storeidx == _req2->storeidx && _req1->path == _req2->path; } }; struct PathHash{ size_t operator()(const Utf8PathStub* _req1)const{ return _req1->storeidx ^ stringhasher(_req1->path); } }; struct IndexEqual{ bool operator()(const Utf8PathStub* _req1, const Utf8PathStub* _req2)const{ return _req1->idx == _req2->idx; } }; struct IndexHash{ size_t operator()(const Utf8PathStub* _req1)const{ return _req1->idx; } }; typedef std::unordered_set<const Utf8PathStub*, PathHash, PathEqual> PathSetT; typedef std::unordered_set<const Utf8PathStub*, IndexHash, IndexEqual> IndexSetT; typedef Stack<Utf8PathStub*> PathStubStackT; struct SizePairCompare { bool operator() (SizePairT const& _a, SizePairT const& _b)const{ return (_a.first < _b.first); } bool operator() (SizePairT const& _a, size_t _b)const{ if(_a.first < _b) return -1; if(_b < _a.first) return 1; return 0; } } szcmp; BinarySeeker<SizePairCompare> sizeseeker; struct Utf8ConfigurationImpl{ struct Storage{ Storage(){} Storage(Utf8Configuration::Storage const &_rstrg):globalprefix(_rstrg.globalprefix), localprefix(_rstrg.localprefix){ } std::string globalprefix; std::string localprefix; size_t globalsize; }; Utf8ConfigurationImpl(){} Utf8ConfigurationImpl(Utf8Configuration const &_cfg){ storagevec.reserve(_cfg.storagevec.size()); for( Utf8Configuration::StorageVectorT::const_iterator it = _cfg.storagevec.begin(); it != _cfg.storagevec.end(); ++it ){ storagevec.push_back(Storage(*it)); } } typedef std::vector<Storage> StorageVectorT; StorageVectorT storagevec; }; struct TempConfigurationImpl{ struct Storage{ Storage( ): level(0), capacity(0), minsize(0), maxsize(0), waitcount(0), waitsizefirst(0), waitidxfirst(-1), usedsize(0), currentid(0), enqued(false), removemode(RemoveAfterCreateE){} Storage( TempConfiguration::Storage const &_cfg ): path(_cfg.path), level(_cfg.level), capacity(_cfg.capacity), minsize(_cfg.minsize), maxsize(_cfg.maxsize), waitcount(0), waitsizefirst(0), waitidxfirst(-1), usedsize(0), currentid(0), enqued(false), removemode(_cfg.removemode) { if(maxsize > capacity || maxsize == 0){ maxsize = capacity; } } bool canUse(const uint64 _sz, const size_t _flags)const{ return _flags & level && _sz <= maxsize && _sz >= minsize; } bool shouldUse(const uint64 _sz)const{ return waitcount == 0 && ((capacity - usedsize) >= _sz); } bool canDeliver()const{ return waitcount && ((capacity - usedsize) >= waitsizefirst) ; } std::string path; uint32 level; uint64 capacity; uint64 minsize; uint64 maxsize; size_t waitcount; uint64 waitsizefirst; size_t waitidxfirst; uint64 usedsize; size_t currentid; SizeStackT idcache; bool enqued; TempRemoveMode removemode; }; TempConfigurationImpl(){} TempConfigurationImpl(TempConfiguration const &_cfg){ storagevec.reserve(_cfg.storagevec.size()); for( TempConfiguration::StorageVectorT::const_iterator it = _cfg.storagevec.begin(); it != _cfg.storagevec.end(); ++it ){ storagevec.push_back(Storage(*it)); } } typedef std::vector<Storage> StorageVectorT; StorageVectorT storagevec; }; struct Utf8Controller::Data{ Utf8ConfigurationImpl filecfg;//NOTE: it is accessed without lock in openFile TempConfigurationImpl tempcfg; size_t minglobalprefixsz; size_t maxglobalprefixsz; SizePairVectorT hashvec; std::string tmp; PathDequeT pathdq; PathSetT pathset; IndexSetT indexset; PathStubStackT pathcache; SizeVectorT tempidxvec; TempWaitDequeT tempwaitdq; TempWaitVectorT tempwaitvec[2]; TempWaitVectorT *pfilltempwaitvec; TempWaitVectorT *pconstempwaitvec; Data( const Utf8Configuration &_rfilecfg, const TempConfiguration &_rtempcfg ):filecfg(_rfilecfg), tempcfg(_rtempcfg){ pfilltempwaitvec = &tempwaitvec[0]; pconstempwaitvec = &tempwaitvec[1]; } void prepareFile(); void prepareTemp(); size_t findFileStorage(std::string const&_path); }; //--------------------------------------------------------------------------- void Utf8Controller::Data::prepareFile(){ minglobalprefixsz = -1; maxglobalprefixsz = 0; for( Utf8ConfigurationImpl::StorageVectorT::const_iterator it = filecfg.storagevec.begin(); it != filecfg.storagevec.end(); ++it ){ if(it->globalprefix.size() < minglobalprefixsz){ minglobalprefixsz = it->globalprefix.size(); } if(it->globalprefix.size() > maxglobalprefixsz){ maxglobalprefixsz = it->globalprefix.size(); } } for( Utf8ConfigurationImpl::StorageVectorT::iterator it = filecfg.storagevec.begin(); it != filecfg.storagevec.end(); ++it ){ const size_t idx = it - filecfg.storagevec.begin(); it->globalsize = it->globalprefix.size(); it->globalprefix.resize(maxglobalprefixsz, '\0'); hashvec.push_back(SizePairT(stringhasher(it->globalprefix), idx)); } std::sort(hashvec.begin(), hashvec.end(), szcmp); } void Utf8Controller::Data::prepareTemp(){ } size_t Utf8Controller::Data::findFileStorage(std::string const&_path){ tmp.assign(_path, 0, _path.size() < maxglobalprefixsz ? _path.size() : maxglobalprefixsz); tmp.resize(maxglobalprefixsz, '\0'); HASH_NS::hash<std::string> sh; size_t h = sh(tmp); BinarySeekerResultT r = sizeseeker.first(hashvec.begin(), hashvec.end(), h); if(r.first){ while(hashvec[r.second].first == h){ const size_t strgidx = hashvec[r.second].second; Utf8ConfigurationImpl::Storage const &rstrg = filecfg.storagevec[strgidx]; if(_path.compare(0, rstrg.globalsize, rstrg.globalprefix) == 0){ return strgidx; } ++r.second; } } return -1; } //--------------------------------------------------------------------------- // Utf8Controller //--------------------------------------------------------------------------- Utf8Controller::Utf8Controller( const Utf8Configuration &_rfilecfg, const TempConfiguration &_rtempcfg ):d(*(new Data(_rfilecfg, _rtempcfg))){ d.prepareFile(); d.prepareTemp(); } Utf8Controller::~Utf8Controller(){ delete &d; } bool Utf8Controller::prepareIndex( shared::StoreBase::Accessor &/*_rsbacc*/, Utf8OpenCommandBase &_rcmd, size_t &_ridx, size_t &_rflags, ERROR_NS::error_code &_rerr ){ //find _rcmd.inpath file and set _rcmd.outpath //if found set _ridx and return true //else return false const size_t storeidx = d.findFileStorage(_rcmd.inpath); _rcmd.outpath.storeidx = storeidx; if(storeidx == static_cast<size_t>(-1)){ _rerr.assign(1, _rerr.category()); return true; } Utf8ConfigurationImpl::Storage const &rstrg = d.filecfg.storagevec[storeidx]; _rcmd.outpath.path.assign(_rcmd.inpath.c_str() + rstrg.globalsize); PathSetT::const_iterator it = d.pathset.find(&_rcmd.outpath); if(it != d.pathset.end()){ _ridx = (*it)->idx; return true; } return false; } bool Utf8Controller::preparePointer( shared::StoreBase::Accessor &/*_rsbacc*/, Utf8OpenCommandBase &_rcmd, FilePointerT &_rptr, size_t &_rflags, ERROR_NS::error_code &_rerr ){ //just do map[_rcmd.outpath] = _rptr.uid().first Utf8PathStub *ppath; if(d.pathcache.size()){ ppath = d.pathcache.top(); *ppath = _rcmd.outpath; d.pathcache.pop(); }else{ d.pathdq.push_back(_rcmd.outpath); ppath = &d.pathdq.back(); } ppath->idx = _rptr.id().first; d.pathset.insert(ppath); d.indexset.insert(ppath); return true;//we don't store _runiptr for later use } void Utf8Controller::openFile(Utf8OpenCommandBase &_rcmd, FilePointerT &_rptr, ERROR_NS::error_code &_rerr){ Utf8ConfigurationImpl::Storage const &rstrg = d.filecfg.storagevec[_rcmd.outpath.storeidx]; std::string path; path.reserve(rstrg.localprefix.size() + _rcmd.outpath.path.size()); path.assign(rstrg.localprefix); path.append(_rcmd.outpath.path); if(!_rptr->open(path.c_str(), _rcmd.openflags)){ _rerr = last_system_error(); } } bool Utf8Controller::prepareIndex( shared::StoreBase::Accessor &_rsbacc, CreateTempCommandBase &_rcmd, size_t &_ridx, size_t &_rflags, ERROR_NS::error_code &_rerr ){ //nothing to do return false;//no stored index } bool Utf8Controller::preparePointer( shared::StoreBase::Accessor &_rsbacc, CreateTempCommandBase &_rcmd, FilePointerT &_rptr, size_t &_rflags, ERROR_NS::error_code &_rerr ){ //We're under Store's mutex lock UidT uid = _rptr.id(); File *pf = _rptr.release(); d.pfilltempwaitvec->push_back(TempWaitStub(uid, pf, _rcmd.size, _rcmd.openflags)); if(d.pfilltempwaitvec->size() == 1){ //notify the shared store object _rsbacc.notify(frame::S_SIG | frame::S_RAISE); } return false;//will always store _rptr } void Utf8Controller::executeOnSignal(shared::StoreBase::Accessor &_rsbacc, ulong _sm){ //We're under Store's mutex lock solid::exchange(d.pfilltempwaitvec, d.pconstempwaitvec); d.pfilltempwaitvec->clear(); } bool Utf8Controller::executeBeforeErase(shared::StoreBase::Accessor &_rsbacc){ //We're NOT under Store's mutex lock if(d.pconstempwaitvec->size()){ for( TempWaitVectorT::const_iterator waitit = d.pconstempwaitvec->begin(); waitit != d.pconstempwaitvec->end(); ++waitit ){ const size_t tempwaitdqsize = d.tempwaitdq.size(); bool canuse = false; for( TempConfigurationImpl::StorageVectorT::iterator it(d.tempcfg.storagevec.begin()); it != d.tempcfg.storagevec.end(); ++it ){ if(it->canUse(waitit->size, waitit->value)){ const size_t strgidx = it - d.tempcfg.storagevec.begin(); TempConfigurationImpl::Storage &rstrg(*it); if(it->shouldUse(waitit->size)){ d.tempwaitdq.resize(tempwaitdqsize); doPrepareOpenTemp(*waitit->pfile, waitit->size, strgidx); //we schedule for erase the waitit pointer _rsbacc.consumeEraseVector().push_back(waitit->objuid); }else{ d.tempwaitdq.push_back(*waitit); // we dont need the openflags any more - we know which // storages apply d.tempwaitdq.back().value = strgidx; ++rstrg.waitcount; if(rstrg.waitcount == 1){ rstrg.waitsizefirst = waitit->size; } } canuse = true; } } if(!canuse){ //a temp file with uninitialized tempbase means an error _rsbacc.consumeEraseVector().push_back(waitit->objuid); } } } if(d.tempidxvec.size()){ for(SizeVectorT::const_iterator it = d.tempidxvec.begin(); it != d.tempidxvec.begin(); ++it){ doDeliverTemp(_rsbacc, *it); } d.tempidxvec.clear(); } return false; } bool Utf8Controller::clear(shared::StoreBase::Accessor &_rsbacc, File &_rf, const size_t _idx){ //We're under Store's mutex lock //We're under File's mutex lock if(!_rf.isTemp()){ _rf.clear(); Utf8PathStub path; path.idx = _idx; IndexSetT::iterator it = d.indexset.find(&path); if(it != d.indexset.end()){ Utf8PathStub *ps = const_cast<Utf8PathStub *>(*it); d.pathset.erase(ps); d.indexset.erase(it); d.pathcache.push(ps); } }else{ TempBase &temp = *_rf.temp(); const size_t strgidx = temp.tempstorageid; TempConfigurationImpl::Storage &rstrg(d.tempcfg.storagevec[strgidx]); doCloseTemp(temp); _rf.clear(); if(rstrg.canDeliver() && !rstrg.enqued){ d.tempidxvec.push_back(strgidx); rstrg.enqued = true; } } return !d.tempidxvec.empty(); } void Utf8Controller::doPrepareOpenTemp(File &_rf, uint64 _sz, const size_t _storeid){ TempConfigurationImpl::Storage &rstrg(d.tempcfg.storagevec[_storeid]); size_t fileid; if(rstrg.idcache.size()){ fileid = rstrg.idcache.top(); rstrg.idcache.pop(); }else{ fileid = rstrg.currentid; ++rstrg.currentid; } rstrg.usedsize += _sz; //only creates the file backend - does not open it: if((rstrg.level & MemoryLevelFlag) && rstrg.path.empty()){ _rf.ptmp = new TempMemory(_storeid, fileid, _sz); }else{ _rf.ptmp = new TempFile(_storeid, fileid, _sz); } } void Utf8Controller::openTemp(CreateTempCommandBase &_rcmd, FilePointerT &_rptr, ERROR_NS::error_code &_rerr){ if(_rptr->isTemp()){ TempConfigurationImpl::Storage &rstrg(d.tempcfg.storagevec[_rptr->temp()->tempstorageid]); _rptr->temp()->open(rstrg.path.c_str(), _rcmd.openflags, rstrg.removemode == RemoveAfterCreateE, _rerr); }else{ _rerr.assign(1, _rerr.category()); } } void Utf8Controller::doCloseTemp(TempBase &_rtemp){ //erase the temp file for on-disk temps TempConfigurationImpl::Storage &rstrg(d.tempcfg.storagevec[_rtemp.tempstorageid]); rstrg.usedsize -= _rtemp.tempsize; rstrg.idcache.push(_rtemp.tempid); _rtemp.close(rstrg.path.c_str(), rstrg.removemode == RemoveAfterCloseE); } void Utf8Controller::doDeliverTemp(shared::StoreBase::Accessor &_rsbacc, const size_t _storeid){ TempConfigurationImpl::Storage &rstrg(d.tempcfg.storagevec[_storeid]); TempWaitDequeT::iterator it = d.tempwaitdq.begin(); rstrg.enqued = false; while(it != d.tempwaitdq.end()){ //first we find the first item waiting on storage TempWaitDequeT::iterator waitit = it; for(; it != d.tempwaitdq.end(); ++it){ if(it->objuid.first != waitit->objuid.first){ waitit = it; } if(it->value == _storeid){ break; } } cassert(it != d.tempwaitdq.end()); if(rstrg.waitsizefirst == 0){ rstrg.waitsizefirst = it->size; } if(!rstrg.canDeliver()){ break; } cassert(rstrg.waitsizefirst == it->size); --rstrg.waitcount; rstrg.waitsizefirst = 0; doPrepareOpenTemp(*it->pfile, it->size, _storeid); //we schedule for erase the waitit pointer _rsbacc.consumeEraseVector().push_back(it->objuid); //delete the whole range [waitit, itend] const size_t objidx = it->objuid.first; if(waitit == d.tempwaitdq.begin()){ while(waitit != d.tempwaitdq.end() && (waitit->objuid.first == objidx || waitit->pfile == NULL)){ waitit = d.tempwaitdq.erase(waitit); } }else{ while(waitit != d.tempwaitdq.end() && (waitit->objuid.first == objidx || waitit->pfile == NULL)){ waitit->pfile = NULL; ++waitit; } } it = waitit; if(!rstrg.waitcount){ break; } } } //-------------------------------------------------------------------------- // TempBase //-------------------------------------------------------------------------- /*virtual*/ TempBase::~TempBase(){ } /*virtual*/ void TempBase::flush(){ } //-------------------------------------------------------------------------- // TempFile //-------------------------------------------------------------------------- TempFile::TempFile( size_t _storageid, size_t _id, uint64 _size ):TempBase(_storageid, _id, _size){} /*virtual*/ TempFile::~TempFile(){ fd.close(); } namespace{ bool prepare_temp_file_path(std::string &_rpath, const char *_prefix, size_t _id){ _rpath.assign(_prefix); if(_rpath.empty()) return false; if(_rpath.back() != '/'){ _rpath += '/'; } char fldrbuf[128]; char filebuf[128]; if(sizeof(_id) == sizeof(uint64)){ size_t fldrid = _id >> 32; size_t fileid = _id & 0xffffffffUL; std::sprintf(fldrbuf, "%8.8X", fldrid); std::sprintf(filebuf, "/%8.8x.tmp", fileid); }else{ const size_t fldrid = _id >> 16; const size_t fileid = _id & 0xffffUL; std::sprintf(fldrbuf, "%4.4X", fldrid); std::sprintf(filebuf, "/%4.4x.tmp", fileid); } _rpath.append(fldrbuf); Directory::create(_rpath.c_str()); _rpath.append(filebuf); return true; } }//namespace /*virtual*/ bool TempFile::open(const char *_path, const size_t _openflags, bool _remove, ERROR_NS::error_code &_rerr){ std::string path; prepare_temp_file_path(path, _path, tempid); bool rv = fd.open(path.c_str(), FileDevice::CreateE | FileDevice::TruncateE | FileDevice::ReadWriteE); if(!rv){ _rerr = last_system_error(); }else{ if(_remove){ Directory::eraseFile(path.c_str()); } } return rv; } /*virtual*/ void TempFile::close(const char *_path, bool _remove){ fd.close(); if(_remove){ std::string path; prepare_temp_file_path(path, _path, tempid); Directory::eraseFile(path.c_str()); } } /*virtual*/ int TempFile::read(char *_pb, uint32 _bl, int64 _off){ const int64 endoff = _off + _bl; if(endoff > tempsize){ if((endoff - tempsize) <= _bl){ _bl = static_cast<uint32>(endoff - tempsize); }else{ return -1; } } return fd.read(_pb, _bl, _off); } /*virtual*/ int TempFile::write(const char *_pb, uint32 _bl, int64 _off){ const int64 endoff = _off + _bl; if(endoff > tempsize){ if((endoff - tempsize) <= _bl){ _bl = static_cast<uint32>(endoff - tempsize); }else{ errno = ENOSPC; return -1; } } return fd.write(_pb, _bl, _off); } /*virtual*/ int64 TempFile::size()const{ return fd.size(); } /*virtual*/ bool TempFile::truncate(int64 _len){ return fd.truncate(_len); } /*virtual*/ void TempFile::flush(){ fd.flush(); } //-------------------------------------------------------------------------- // TempMemory //-------------------------------------------------------------------------- TempMemory::TempMemory( size_t _storageid, size_t _id, uint64 _size ):TempBase(_storageid, _id, _size), mf(_size) { shared_mutex_safe(this); } /*virtual*/ TempMemory::~TempMemory(){ } /*virtual*/ bool TempMemory::open(const char *_path, const size_t _openflags, bool /*_remove*/, ERROR_NS::error_code &_rerr){ Locker<Mutex> lock(shared_mutex(this)); mf.truncate(0); return true; } /*virtual*/ void TempMemory::close(const char */*_path*/, bool /*_remove*/){ } /*virtual*/ int TempMemory::read(char *_pb, uint32 _bl, int64 _off){ Locker<Mutex> lock(shared_mutex(this)); return mf.read(_pb, _bl, _off); } /*virtual*/ int TempMemory::write(const char *_pb, uint32 _bl, int64 _off){ Locker<Mutex> lock(shared_mutex(this)); return mf.write(_pb, _bl, _off); } /*virtual*/ int64 TempMemory::size()const{ Locker<Mutex> lock(shared_mutex(this)); return mf.size(); } /*virtual*/ bool TempMemory::truncate(int64 _len){ Locker<Mutex> lock(shared_mutex(this)); return mf.truncate(_len) == 0; } }//namespace file }//namespace frame }//namespace solid
27.008141
125
0.669932
[ "object", "vector", "solid" ]
29631fb6ab251f461195535f8918d9db0e65b0e5
16,317
cpp
C++
osdep/LinuxEthernetTap.cpp
ElTopo/ZeroTierOne
db1cd255616bc72221e345508f25109642f74ae4
[ "RSA-MD" ]
null
null
null
osdep/LinuxEthernetTap.cpp
ElTopo/ZeroTierOne
db1cd255616bc72221e345508f25109642f74ae4
[ "RSA-MD" ]
null
null
null
osdep/LinuxEthernetTap.cpp
ElTopo/ZeroTierOne
db1cd255616bc72221e345508f25109642f74ae4
[ "RSA-MD" ]
null
null
null
/* * Copyright (c)2019 ZeroTier, Inc. * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file in the project's root directory. * * Change Date: 2025-01-01 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2.0 of the Apache License. */ /****/ #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wrestrict" #endif #include "../node/Constants.hpp" #ifdef __LINUX__ #include "../node/Utils.hpp" #include "../node/Mutex.hpp" #include "../node/Dictionary.hpp" #include "OSUtils.hpp" #include "LinuxEthernetTap.hpp" #include "LinuxNetLink.hpp" #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <signal.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/ioctl.h> #include <sys/wait.h> #include <sys/select.h> #include <netinet/in.h> #include <net/if_arp.h> #include <arpa/inet.h> #include <linux/if.h> #include <linux/if_tun.h> #include <linux/if_addr.h> #include <linux/if_ether.h> #include <ifaddrs.h> #include <algorithm> #include <utility> #include <string> #ifndef IFNAMSIZ #define IFNAMSIZ 16 #endif #define ZT_TAP_BUF_SIZE 16384 // ff:ff:ff:ff:ff:ff with no ADI static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0); namespace ZeroTier { static const char _base32_chars[32] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','2','3','4','5','6','7' }; static void _base32_5_to_8(const uint8_t *in,char *out) { out[0] = _base32_chars[(in[0]) >> 3]; out[1] = _base32_chars[(in[0] & 0x07) << 2 | (in[1] & 0xc0) >> 6]; out[2] = _base32_chars[(in[1] & 0x3e) >> 1]; out[3] = _base32_chars[(in[1] & 0x01) << 4 | (in[2] & 0xf0) >> 4]; out[4] = _base32_chars[(in[2] & 0x0f) << 1 | (in[3] & 0x80) >> 7]; out[5] = _base32_chars[(in[3] & 0x7c) >> 2]; out[6] = _base32_chars[(in[3] & 0x03) << 3 | (in[4] & 0xe0) >> 5]; out[7] = _base32_chars[(in[4] & 0x1f)]; } LinuxEthernetTap::LinuxEthernetTap( const char *homePath, const MAC &mac, unsigned int mtu, unsigned int metric, uint64_t nwid, const char *friendlyName, void (*handler)(void *,void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int), void *arg) : _handler(handler), _arg(arg), _nwid(nwid), _mac(mac), _homePath(homePath), _mtu(mtu), _fd(0), _enabled(true), _run(true) { static std::mutex s_tapCreateLock; char procpath[128],nwids[32]; struct stat sbuf; // Create only one tap at a time globally. std::lock_guard<std::mutex> tapCreateLock(s_tapCreateLock); // Make sure Linux netlink is initialized. (void)LinuxNetLink::getInstance(); OSUtils::ztsnprintf(nwids,sizeof(nwids),"%.16llx",nwid); _fd = ::open("/dev/net/tun",O_RDWR); if (_fd <= 0) { _fd = ::open("/dev/tun",O_RDWR); if (_fd <= 0) throw std::runtime_error(std::string("could not open TUN/TAP device: ") + strerror(errno)); } struct ifreq ifr; memset(&ifr,0,sizeof(ifr)); // Restore device names from legacy devicemap, but for new devices we use a base32-based // canonical device name. std::map<std::string,std::string> globalDeviceMap; FILE *devmapf = fopen((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),"r"); if (devmapf) { char buf[256]; while (fgets(buf,sizeof(buf),devmapf)) { char *x = (char *)0; char *y = (char *)0; char *saveptr = (char *)0; for(char *f=Utils::stok(buf,"\r\n=",&saveptr);(f);f=Utils::stok((char *)0,"\r\n=",&saveptr)) { if (!x) x = f; else if (!y) y = f; else break; } if ((x)&&(y)&&(x[0])&&(y[0])) globalDeviceMap[x] = y; } fclose(devmapf); } bool recalledDevice = false; std::map<std::string,std::string>::const_iterator gdmEntry = globalDeviceMap.find(nwids); if (gdmEntry != globalDeviceMap.end()) { Utils::scopy(ifr.ifr_name,sizeof(ifr.ifr_name),gdmEntry->second.c_str()); OSUtils::ztsnprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name); recalledDevice = (stat(procpath,&sbuf) != 0); } if (!recalledDevice) { #ifdef __SYNOLOGY__ int devno = 50; do { OSUtils::ztsnprintf(ifr.ifr_name,sizeof(ifr.ifr_name),"eth%d",devno++); OSUtils::ztsnprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name); } while (stat(procpath,&sbuf) == 0); // try zt#++ until we find one that does not exist #else uint64_t trial = 0; // incremented in the very unlikely event of a name collision with another network do { const uint64_t nwid40 = (nwid ^ (nwid >> 24)) + trial++; uint8_t tmp2[5]; char tmp3[11]; tmp2[0] = (uint8_t)((nwid40 >> 32) & 0xff); tmp2[1] = (uint8_t)((nwid40 >> 24) & 0xff); tmp2[2] = (uint8_t)((nwid40 >> 16) & 0xff); tmp2[3] = (uint8_t)((nwid40 >> 8) & 0xff); tmp2[4] = (uint8_t)(nwid40 & 0xff); tmp3[0] = 'z'; tmp3[1] = 't'; _base32_5_to_8(tmp2,tmp3 + 2); tmp3[10] = (char)0; memcpy(ifr.ifr_name,tmp3,11); OSUtils::ztsnprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name); } while (stat(procpath,&sbuf) == 0); #endif } ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (ioctl(_fd,TUNSETIFF,(void *)&ifr) < 0) { ::close(_fd); throw std::runtime_error("unable to configure TUN/TAP device for TAP operation"); } ::ioctl(_fd,TUNSETPERSIST,0); // valgrind may generate a false alarm here _dev = ifr.ifr_name; ::fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC); (void)::pipe(_shutdownSignalPipe); #if 0 //lxl _thread_init_l.lock(); for(unsigned int t=0;t<2;++t) { _tapReaderThread[t] = std::thread([this, t]{ fd_set readfds,nullfds; int n,nfds,r; void *buf = nullptr; std::vector<void *> buffers; if (t == 0) { struct ifreq ifr; memset(&ifr,0,sizeof(ifr)); strcpy(ifr.ifr_name,_dev.c_str()); const int sock = socket(AF_INET,SOCK_DGRAM,0); if (sock <= 0) return; if (ioctl(sock,SIOCGIFFLAGS,(void *)&ifr) < 0) { ::close(sock); printf("WARNING: ioctl() failed setting up Linux tap device (bring interface up)\n"); return; } ifr.ifr_flags |= IFF_UP; if (ioctl(sock,SIOCSIFFLAGS,(void *)&ifr) < 0) { ::close(sock); printf("WARNING: ioctl() failed setting up Linux tap device (bring interface up)\n"); return; } // Some kernel versions seem to require you to yield while the device comes up // before they will accept MTU and MAC. For others it doesn't matter, but is // harmless. This was moved to the worker thread though so as not to block the // main ZeroTier loop. usleep(500000); ifr.ifr_ifru.ifru_hwaddr.sa_family = ARPHRD_ETHER; _mac.copyTo(ifr.ifr_ifru.ifru_hwaddr.sa_data,6); if (ioctl(sock,SIOCSIFHWADDR,(void *)&ifr) < 0) { ::close(sock); printf("WARNING: ioctl() failed setting up Linux tap device (set MAC)\n"); // lxl // return; } ifr.ifr_ifru.ifru_mtu = (int)_mtu; if (ioctl(sock,SIOCSIFMTU,(void *)&ifr) < 0) { ::close(sock); printf("WARNING: ioctl() failed setting up Linux tap device (set MTU)\n"); // lxl // return; } fcntl(_fd,F_SETFL,O_NONBLOCK); #endif // lxl _tapReaderThread = std::thread([this]{ uint8_t b[ZT_TAP_BUF_SIZE]; fd_set readfds,nullfds; int n,nfds,r; std::vector<void *> buffers; struct ifreq ifr; memset(&ifr,0,sizeof(ifr)); strcpy(ifr.ifr_name,_dev.c_str()); const int sock = socket(AF_INET,SOCK_DGRAM,0); if (sock <= 0) return; if (ioctl(sock,SIOCGIFFLAGS,(void *)&ifr) < 0) { ::close(sock); printf("WARNING: ioctl() failed setting up Linux tap device (bring interface up)\n"); return; } ifr.ifr_ifru.ifru_hwaddr.sa_family = ARPHRD_ETHER; _mac.copyTo(ifr.ifr_ifru.ifru_hwaddr.sa_data,6); if (ioctl(sock,SIOCSIFHWADDR,(void *)&ifr) < 0) { ::close(sock); printf("WARNING: ioctl() failed setting up Linux tap device (set MAC)\n"); return; } usleep(100000); ifr.ifr_flags |= IFF_MULTICAST; ifr.ifr_flags |= IFF_UP; if (ioctl(sock,SIOCSIFFLAGS,(void *)&ifr) < 0) { ::close(sock); printf("WARNING: ioctl() failed setting up Linux tap device (bring interface up)\n"); return; } usleep(100000); ifr.ifr_ifru.ifru_hwaddr.sa_family = ARPHRD_ETHER; _mac.copyTo(ifr.ifr_ifru.ifru_hwaddr.sa_data,6); if (ioctl(sock,SIOCSIFHWADDR,(void *)&ifr) < 0) { ::close(sock); printf("WARNING: ioctl() failed setting up Linux tap device (set MAC)\n"); return; } ifr.ifr_ifru.ifru_mtu = (int)_mtu; if (ioctl(sock,SIOCSIFMTU,(void *)&ifr) < 0) { ::close(sock); printf("WARNING: ioctl() failed setting up Linux tap device (set MTU)\n"); return; } fcntl(_fd,F_SETFL,O_NONBLOCK); ::close(sock); if (!_run) return; FD_ZERO(&readfds); FD_ZERO(&nullfds); nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1; r = 0; for(;;) { FD_SET(_shutdownSignalPipe[0],&readfds); FD_SET(_fd,&readfds); select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0); if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) break; if (FD_ISSET(_fd,&readfds)) { for(;;) { // read until there are no more packets, then return to outer select() loop n = (int)::read(_fd,b + r,ZT_TAP_BUF_SIZE - r); if (n > 0) { // Some tap drivers like to send the ethernet frame and the // payload in two chunks, so handle that by accumulating // data until we have at least a frame. r += n; if (r > 14) { if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms r = _mtu + 14; if (_enabled) { //_tapq.post(std::pair<void *,int>(buf,r)); //buf = nullptr; MAC to(b, 6),from(b + 6, 6); unsigned int etherType = Utils::ntoh(((const uint16_t *)b)[6]); _handler(_arg, nullptr, _nwid, from, to, etherType, 0, (const void *)(b + 14),(unsigned int)(r - 14)); } r = 0; } } else { r = 0; break; } } } } }); } LinuxEthernetTap::~LinuxEthernetTap() { _run = false; (void)::write(_shutdownSignalPipe[1],"\0",1); _tapReaderThread.join(); ::close(_fd); ::close(_shutdownSignalPipe[0]); ::close(_shutdownSignalPipe[1]); } void LinuxEthernetTap::setEnabled(bool en) { _enabled = en; } bool LinuxEthernetTap::enabled() const { return _enabled; } static bool ___removeIp(const std::string &_dev,const InetAddress &ip) { LinuxNetLink::getInstance().removeAddress(ip, _dev.c_str()); return true; } bool LinuxEthernetTap::addIps(std::vector<InetAddress> ips) { #ifdef __SYNOLOGY__ std::string filepath = "/etc/sysconfig/network-scripts/ifcfg-"+_dev; std::string cfg_contents = "DEVICE="+_dev+"\nBOOTPROTO=static"; int ip4=0,ip6=0,ip4_tot=0,ip6_tot=0; for(int i=0; i<(int)ips.size(); i++) { if (ips[i].isV4()) ip4_tot++; else ip6_tot++; } // Assemble and write contents of ifcfg-dev file for(int i=0; i<(int)ips.size(); i++) { if (ips[i].isV4()) { char iptmp[64],iptmp2[64]; std::string numstr4 = ip4_tot > 1 ? std::to_string(ip4) : ""; cfg_contents += "\nIPADDR"+numstr4+"="+ips[i].toIpString(iptmp) + "\nNETMASK"+numstr4+"="+ips[i].netmask().toIpString(iptmp2)+"\n"; ip4++; } else { char iptmp[64],iptmp2[64]; std::string numstr6 = ip6_tot > 1 ? std::to_string(ip6) : ""; cfg_contents += "\nIPV6ADDR"+numstr6+"="+ips[i].toIpString(iptmp) + "\nNETMASK"+numstr6+"="+ips[i].netmask().toIpString(iptmp2)+"\n"; ip6++; } } OSUtils::writeFile(filepath.c_str(), cfg_contents.c_str(), cfg_contents.length()); // Finally, add IPs for(int i=0; i<(int)ips.size(); i++){ LinuxNetLink::getInstance().addAddress(ips[i], _dev.c_str()); } return true; #endif // __SYNOLOGY__ return false; } bool LinuxEthernetTap::addIp(const InetAddress &ip) { if (!ip) return false; std::vector<InetAddress> allIps(ips()); if (std::binary_search(allIps.begin(),allIps.end(),ip)) return true; // Remove and reconfigure if address is the same but netmask is different for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) { if (i->ipsEqual(ip)) ___removeIp(_dev,*i); } LinuxNetLink::getInstance().addAddress(ip, _dev.c_str()); return true; } bool LinuxEthernetTap::removeIp(const InetAddress &ip) { if (!ip) return true; std::vector<InetAddress> allIps(ips()); if (std::find(allIps.begin(),allIps.end(),ip) != allIps.end()) { if (___removeIp(_dev,ip)) return true; } return false; } std::vector<InetAddress> LinuxEthernetTap::ips() const { struct ifaddrs *ifa = (struct ifaddrs *)0; if (getifaddrs(&ifa)) return std::vector<InetAddress>(); std::vector<InetAddress> r; struct ifaddrs *p = ifa; while (p) { if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) { switch(p->ifa_addr->sa_family) { case AF_INET: { struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr; struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask; r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr))); } break; case AF_INET6: { struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr; struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask; uint32_t b[4]; memcpy(b,nm->sin6_addr.s6_addr,sizeof(b)); r.push_back(InetAddress(sin->sin6_addr.s6_addr,16,Utils::countBits(b[0]) + Utils::countBits(b[1]) + Utils::countBits(b[2]) + Utils::countBits(b[3]))); } break; } } p = p->ifa_next; } if (ifa) freeifaddrs(ifa); std::sort(r.begin(),r.end()); r.erase(std::unique(r.begin(),r.end()),r.end()); return r; } void LinuxEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len) { char putBuf[ZT_MAX_MTU + 64]; if ((_fd > 0)&&(len <= _mtu)&&(_enabled)) { to.copyTo(putBuf,6); from.copyTo(putBuf + 6,6); *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType); memcpy(putBuf + 14,data,len); len += 14; (void)::write(_fd,putBuf,len); } } std::string LinuxEthernetTap::deviceName() const { return _dev; } void LinuxEthernetTap::setFriendlyName(const char *friendlyName) { } void LinuxEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed) { char *ptr,*ptr2; unsigned char mac[6]; std::vector<MulticastGroup> newGroups; int fd = ::open("/proc/net/dev_mcast",O_RDONLY); if (fd > 0) { char buf[131072]; int n = (int)::read(fd,buf,sizeof(buf)); if ((n > 0)&&(n < (int)sizeof(buf))) { buf[n] = (char)0; for(char *l=strtok_r(buf,"\r\n",&ptr);(l);l=strtok_r((char *)0,"\r\n",&ptr)) { int fno = 0; char *devname = (char *)0; char *mcastmac = (char *)0; for(char *f=strtok_r(l," \t",&ptr2);(f);f=strtok_r((char *)0," \t",&ptr2)) { if (fno == 1) devname = f; else if (fno == 4) mcastmac = f; ++fno; } if ((devname)&&(!strcmp(devname,_dev.c_str()))&&(mcastmac)&&(Utils::unhex(mcastmac,mac,6) == 6)) newGroups.push_back(MulticastGroup(MAC(mac,6),0)); } } ::close(fd); } std::vector<InetAddress> allIps(ips()); for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip) newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip)); std::sort(newGroups.begin(),newGroups.end()); newGroups.erase(std::unique(newGroups.begin(),newGroups.end()),newGroups.end()); for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) { if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m)) added.push_back(*m); } for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) { if (!std::binary_search(newGroups.begin(),newGroups.end(),*m)) removed.push_back(*m); } _multicastGroups.swap(newGroups); } void LinuxEthernetTap::setMtu(unsigned int mtu) { if (_mtu != mtu) { _mtu = mtu; int sock = socket(AF_INET,SOCK_DGRAM,0); if (sock > 0) { struct ifreq ifr; memset(&ifr,0,sizeof(ifr)); ifr.ifr_ifru.ifru_mtu = (int)mtu; ioctl(sock,SIOCSIFMTU,(void *)&ifr); close(sock); } } } } // namespace ZeroTier #endif // __LINUX__
28.426829
170
0.645155
[ "vector" ]
29645512bbf2f6f8dbc104adeb57bee3767b4a42
16,445
cpp
C++
module-bluetooth/Bluetooth/interface/profiles/GAP/GAP.cpp
mudita/MuditaOS
fc05d5e6188630518f4456b25968ee8ccd618ba7
[ "BSL-1.0" ]
369
2021-11-10T09:20:29.000Z
2022-03-30T06:36:58.000Z
module-bluetooth/Bluetooth/interface/profiles/GAP/GAP.cpp
mudita/MuditaOS
fc05d5e6188630518f4456b25968ee8ccd618ba7
[ "BSL-1.0" ]
149
2021-11-10T08:38:35.000Z
2022-03-31T23:01:52.000Z
module-bluetooth/Bluetooth/interface/profiles/GAP/GAP.cpp
mudita/MuditaOS
fc05d5e6188630518f4456b25968ee8ccd618ba7
[ "BSL-1.0" ]
41
2021-11-10T08:30:37.000Z
2022-03-29T08:12:46.000Z
// Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved. // For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md #include "GAP.hpp" #include "Devices.hpp" #include "GAP/used_events.hpp" #include <Bluetooth/error_bluetooth.hpp> #include <service-bluetooth/BluetoothMessage.hpp> #include <service-bluetooth/messages/ResponseVisibleDevices.hpp> #include <service-bluetooth/messages/Unpair.hpp> #include <service-bluetooth/messages/Authenticate.hpp> #include <service-bluetooth/Constants.hpp> #include <log/log.hpp> #include <memory> extern "C" { #include "btstack.h" #include "hci.h" }; namespace bluetooth { sys::Service *GAP::ownerService = nullptr; btstack_packet_callback_registration_t GAP::cb_handler; stack::state GAP::state; namespace gap { enum class state { scan_off = 0, scan_on, } static state; } static gap::Devices &devices() { static std::unique_ptr<gap::Devices> dev; if (not dev) { dev = std::make_unique<gap::Devices>(); } return *dev; }; auto GAP::registerScan() -> Error { LOG_INFO("GAP register scan!"); /// -> this have to be called prior to power on! hci_set_inquiry_mode(INQUIRY_MODE_RSSI_AND_EIR); cb_handler.callback = &packetHandler; hci_add_event_handler(&cb_handler); return Error(); } auto GAP::scan() -> Error { if (hci_get_state() == HCI_STATE_WORKING) { if (gap::state == gap::state::scan_on) { stopScan(); } devices().clear(); if (auto ret = startScan(); ret != 0) { LOG_ERROR("Start scan error!: 0x%02X - %s", ret, error_cstr(ret)); return Error(Error::LibraryError, ret); } gap::state = gap::state::scan_on; } else { return Error(Error::NotReady); } return Error(); } void GAP::stopScan() { gap::state = gap::state::scan_off; gap_inquiry_force_stop(); LOG_INFO("Scan stopped!"); } void GAP::setVisibility(bool visibility) { gap_discoverable_control(static_cast<std::uint8_t>(visibility)); LOG_INFO("Visibility: %s", visibility ? "true" : "false"); } auto GAP::pair(Devicei device, std::uint8_t protectionLevel) -> bool { if (hci_get_state() == HCI_STATE_WORKING) { auto it = devices().find(device.address); if (it == devices().end()) { LOG_ERROR("device not found: %s", device.address_str()); return false; } return gap_dedicated_bonding(device.address, protectionLevel) == 0; } return false; } void GAP::sendDevices() { auto msg = std::make_shared<message::bluetooth::ResponseVisibleDevices>(devices().getList()); ownerService->bus.sendMulticast(std::move(msg), sys::BusChannel::BluetoothNotifications); } auto GAP::startScan() -> int { LOG_INFO("Starting inquiry scan.."); return gap_inquiry_start(inquiryIntervalSeconds); } void GAP::continueScanning() { if (const auto &it = devices().find(REMOTE_NAME_REQUEST); it != devices().end()) { LOG_INFO("Get remote name for %s", it->name.data()); it->state = REMOTE_NAME_INQUIRED; gap_remote_name_request(it->address, it->pageScanRepetitionMode, it->clockOffset | 0x8000); return; } if (gap::state == gap::state::scan_on) { startScan(); } } auto GAP::updateDeviceName(std::uint8_t *packet, bd_addr_t &addr) -> bool { reverse_bd_addr(&packet[3], addr); if (auto it = devices().find(addr); it != devices().end()) { it->state = packet[2] ? REMOTE_NAME_FAILURE : REMOTE_NAME_FETCHED; if (it->state != REMOTE_NAME_FAILURE) { strcpy(it->name.data(), reinterpret_cast<const char *>(&packet[9])); } return it->state == REMOTE_NAME_FETCHED; } return false; } void GAP::addNewDevice(std::uint8_t *packet, bd_addr_t &addr) { Devicei device; device.setAddress(&addr); device.pageScanRepetitionMode = gap_event_inquiry_result_get_page_scan_repetition_mode(packet); device.clockOffset = gap_event_inquiry_result_get_clock_offset(packet); device.classOfDevice = gap_event_inquiry_result_get_class_of_device(packet); LOG_INFO("Device found "); LOG_INFO("with address: %s, ", device.address_str()); LOG_INFO("with COD: 0x%06x, ", static_cast<unsigned int>(device.classOfDevice)); LOG_INFO("pageScan %d, ", device.pageScanRepetitionMode); LOG_INFO("clock offset 0x%04x", device.clockOffset); if (gap_event_inquiry_result_get_rssi_available(packet) != 0u) { LOG_INFO(", rssi %d dBm", static_cast<int8_t>(gap_event_inquiry_result_get_rssi(packet))); } if (gap_event_inquiry_result_get_name_available(packet) != 0u) { if (const auto nameLen = gap_event_inquiry_result_get_name_len(packet); nameLen > Device::NameBufferSize) { LOG_ERROR("Can't add new device - name length is too large."); return; } auto name = gap_event_inquiry_result_get_name(packet); strcpy(device.name.data(), reinterpret_cast<const char *>(name)); device.state = REMOTE_NAME_FETCHED; } else { bd_addr_t devAddr; gap_event_inquiry_result_get_bd_addr(packet, devAddr); device.state = REMOTE_NAME_REQUEST; strcpy(device.name.data(), bd_addr_to_str(devAddr)); } devices().put(std::move(device)); } void GAP::processInquiryResult(std::uint8_t *packet) { bd_addr_t addr; gap_event_inquiry_result_get_bd_addr(packet, addr); auto it = devices().find(addr); if (it != devices().end()) { return; // already in our list } uint32_t classOfDevice = gap_event_inquiry_result_get_class_of_device(packet); LOG_INFO("Device CoD: %" PRIx32 "", classOfDevice); ///> Device has to support services: AUDIO for HFP and HSP profiles, and RENDERING for SNK of A2DP profile if (!(classOfDevice & TYPE_OF_SERVICE::REMOTE_SUPPORTED_SERVICES)) { LOG_INFO("Ignoring device with incompatible services: %s, ", getListOfSupportedServicesInString(classOfDevice).c_str()); return; } addNewDevice(packet, addr); sendDevices(); } void GAP::processInquiryComplete() { devices().for_each([](Devicei &d) { if (d.state == REMOTE_NAME_INQUIRED) { d.state = REMOTE_NAME_REQUEST; } }); continueScanning(); } void GAP::processNameRequestComplete(std::uint8_t *packet, bd_addr_t &addr) { if (updateDeviceName(packet, addr)) { sendDevices(); } continueScanning(); } void GAP::processDedicatedBondingCompleted(std::uint8_t *packet, bd_addr_t &addr) { auto result = packet[2]; auto it = devices().find(addr); auto msg = std::make_shared<BluetoothPairResultMessage>(it != devices().end() ? *it : Devicei(), result == 0u); ownerService->bus.sendUnicast(std::move(msg), service::name::bluetooth); } /* @text In ACTIVE, the following events are processed: * - GAP Inquiry result event: BTstack provides a unified inquiry result that contain * Class of Device (CoD), page scan mode, clock offset. RSSI and name (from EIR) are optional. * - Inquiry complete event: the remote name is requested for devices without a fetched * name. The state of a remote name can be one of the following: * REMOTE_NAME_REQUEST, REMOTE_NAME_INQUIRED, or REMOTE_NAME_FETCHED. * - Remote name request complete event: the remote name is stored in the table and the * state is updated to REMOTE_NAME_FETCHED. The query of remote names is continued. */ void GAP::activeStateHandler(std::uint8_t eventType, std::uint8_t *packet, std::uint16_t size) { if (not(eventType == HCI_EVENT_TRANSPORT_PACKET_SENT || eventType == HCI_EVENT_COMMAND_STATUS || eventType == HCI_EVENT_INQUIRY_COMPLETE || eventType == HCI_EVENT_COMMAND_COMPLETE || eventType == HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS)) { LOG_DEBUG("event: 0x%02X - %s - size: %" PRIu16, eventType, evt_cstr(eventType), size); } switch (eventType) { case HCI_EVENT_TRANSPORT_PACKET_SENT: break; case HCI_EVENT_EXTENDED_INQUIRY_RESPONSE: break; case GAP_EVENT_PAIRING_STARTED: break; case HCI_EVENT_READ_REMOTE_SUPPORTED_FEATURES_COMPLETE: break; case HCI_EVENT_USER_CONFIRMATION_REQUEST: { bd_addr_t addr; hci_event_user_confirmation_request_get_bd_addr(packet, addr); auto conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_ACL); if (conn == nullptr) { break; } auto it = devices().find(addr); if (it == devices().end()) { gap_remote_name_request(addr, PAGE_SCAN_MODE_STANDARD, 0); it = devices().put(addr); } it->isPairingSSP = true; if (conn->io_cap_response_io == SSP_IO_CAPABILITY_NO_INPUT_NO_OUTPUT) { gap_ssp_confirmation_response(addr); break; } auto code = hci_event_user_passkey_notification_get_numeric_value(packet); auto msg = std::make_shared<::message::bluetooth::RequestAuthenticate>( *it, bluetooth::AuthenticateType::PairCancel, (code != 0) ? static_cast<std::optional<unsigned long>>(code) : std::nullopt); ownerService->bus.sendMulticast(std::move(msg), sys::BusChannel::BluetoothNotifications); } break; case HCI_EVENT_PIN_CODE_REQUEST: { bd_addr_t addr; hci_event_pin_code_request_get_bd_addr(packet, addr); auto it = devices().find(addr); if (it == devices().end()) { gap_remote_name_request(addr, PAGE_SCAN_MODE_STANDARD, 0); it = devices().put(addr); } it->isPairingSSP = false; auto msg = std::make_shared<::message::bluetooth::RequestAuthenticate>(*it, bluetooth::AuthenticateType::Passkey); ownerService->bus.sendMulticast(std::move(msg), sys::BusChannel::BluetoothNotifications); } break; case HCI_EVENT_READ_REMOTE_EXTENDED_FEATURES_COMPLETE: { uint16_t handle = little_endian_read_16(packet, 3); hci_connection_t *conn = hci_connection_for_handle(handle); auto yes = gap_ssp_supported_on_both_sides(conn->con_handle); auto it = devices().find(conn->address); if (it == devices().end()) { return; } it->isPairingSSP = yes; } break; case GAP_EVENT_INQUIRY_RESULT: processInquiryResult(packet); break; case GAP_EVENT_INQUIRY_COMPLETE: processInquiryComplete(); break; case HCI_EVENT_USER_PASSKEY_REQUEST: { bd_addr_t addr; hci_event_user_passkey_request_get_bd_addr(packet, addr); auto it = devices().find(addr); if (it == devices().end()) { gap_remote_name_request(addr, PAGE_SCAN_MODE_STANDARD, 0); it = devices().put(addr); } it->isPairingSSP = true; ownerService->bus.sendMulticast( std::make_shared<::message::bluetooth::RequestAuthenticate>(*it, bluetooth::AuthenticateType::Passkey), sys::BusChannel::BluetoothNotifications); } break; case HCI_EVENT_REMOTE_NAME_REQUEST_COMPLETE: { bd_addr_t addr; hci_event_remote_name_request_complete_get_bd_addr(packet, addr); processNameRequestComplete(packet, addr); } break; case GAP_EVENT_DEDICATED_BONDING_COMPLETED: bd_addr_t addr; reverse_bd_addr(&packet[3], addr); processDedicatedBondingCompleted(packet, addr); break; case HCI_EVENT_SIMPLE_PAIRING_COMPLETE: { bd_addr_t addr; hci_event_simple_pairing_complete_get_bd_addr(packet, addr); processSimplePairingCompleted(packet, addr); } break; case GAP_EVENT_PAIRING_COMPLETE: LOG_DEBUG("status: 0x%02X", packet[10]); break; default: break; } } void GAP::initStateHandler(std::uint8_t eventType, std::uint8_t *packet) { if (eventType == BTSTACK_EVENT_STATE) { if (btstack_event_state_get_state(packet) == HCI_STATE_WORKING) { state = stack::state::working; } } } void GAP::packetHandler(std::uint8_t packet_type, std::uint16_t channel, std::uint8_t *packet, std::uint16_t size) { if (packet_type != HCI_EVENT_PACKET) { return; } const auto eventType = hci_event_packet_get_type(packet); switch (state) { case stack::state::init: initStateHandler(eventType, packet); break; case stack::state::working: activeStateHandler(eventType, packet, size); break; default: break; } } GAP::GAP(sys::Service *owner) { ownerService = owner; state = stack::state::init; } auto GAP::getDevicesList() -> std::vector<Devicei> { return devices().getList(); } auto GAP::unpair(Devicei device) -> bool { LOG_INFO("Unpairing device"); gap_drop_link_key_for_bd_addr(device.address); LOG_INFO("Device unpaired"); ownerService->bus.sendMulticast(std::make_shared<message::bluetooth::UnpairResult>(device, true), sys::BusChannel::BluetoothNotifications); return true; } void GAP::respondPinCode(const std::string &pin, Devicei d) { LOG_DEBUG("pairing response for device: %s pin: %s is SSP? %s", d.address_str(), pin.c_str(), d.isPairingSSP ? "yes" : "no"); if (!d.isPairingSSP) { gap_pin_code_response(d.address, pin.c_str()); return; } unsigned int passkey = 0; try { passkey = stoi(pin); LOG_DEBUG("Sending %06u as a passkey", passkey); } catch (const std::invalid_argument &e) { LOG_ERROR("STOI error: %s", e.what()); } gap_ssp_passkey_response(d.address, passkey); } void GAP::processSimplePairingCompleted(std::uint8_t *packet, bd_addr_t &addr) { auto status = hci_event_simple_pairing_complete_get_status(packet); auto it = devices().find(addr); LOG_INFO("HCI_EVENT_SIMPLE_PAIRING_COMPLETE: 0x%02X - %s - device found: %s : address: %s", status, error_cstr(status), it != devices().end() ? "found" : "fail", bd_addr_to_str(addr)); if (it == devices().end()) { auto msg = std::make_shared<BluetoothPairResultMessage>(Devicei(), false); ownerService->bus.sendUnicast(std::move(msg), service::name::bluetooth); return; } auto msg = std::make_shared<BluetoothPairResultMessage>(*it, status == ERROR_CODE_SUCCESS); ownerService->bus.sendUnicast(std::move(msg), service::name::bluetooth); } void GAP::finishCodeComparison(bool accepted, Devicei d) { if (accepted) { gap_ssp_confirmation_response(d.address); } else { gap_ssp_confirmation_negative(d.address); } } } // namespace bluetooth
37.205882
119
0.595439
[ "vector" ]
296596ccf947e3e92eb5890c5b40e86db76941f6
6,281
cpp
C++
GraphicsTraining/GraphicsTraining/Editor_MaterialPanel.cpp
Josef212/ShadowMappingTest
f49451bce46d8030f887766be462ab6e43a26d03
[ "MIT" ]
null
null
null
GraphicsTraining/GraphicsTraining/Editor_MaterialPanel.cpp
Josef212/ShadowMappingTest
f49451bce46d8030f887766be462ab6e43a26d03
[ "MIT" ]
null
null
null
GraphicsTraining/GraphicsTraining/Editor_MaterialPanel.cpp
Josef212/ShadowMappingTest
f49451bce46d8030f887766be462ab6e43a26d03
[ "MIT" ]
null
null
null
#include "Editor_MaterialPanel.h" #include "ImGui/imgui.h" #include "ResourceManager.h" #include "Resource.h" #include "Material.h" #include "ComplexMaterial.h" #include "PhongMaterial.h" #include "PBRMaterial.h" #include "Shader.h" #include "Texture.h" #include "ImGui/imgui.h" Editor_MaterialPanel::Editor_MaterialPanel(const char* name, bool startEnabled) : EditorPanel(name, startEnabled) { } Editor_MaterialPanel::~Editor_MaterialPanel() { } void Editor_MaterialPanel::OnInit() { } void Editor_MaterialPanel::Display() { ImGui::Begin(name.c_str(), &show); std::vector<Resource*> mats; resourceManager->GatherResourceOfType(ResourceType::RES_MATERIAL, mats); static int mI = -1; int i = 0; for (auto it : mats) { ImGuiTreeNodeFlags flags = 0; // ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick; //if (gI == i) flags |= ImGuiTreeNodeFlags_Selected; //else flags |= ImGuiTreeNodeFlags_Leaf; Material* mat = static_cast<Material*>(it); if (mat) { if (ImGui::TreeNodeEx(mat->GetNameCStr(), flags)) { if (ImGui::IsItemClicked()) mI = i; //if (gI == i) MaterialInfo(mat); ImGui::TreePop(); } if (it != mats[mats.size() - 1]) ImGui::Separator(); } ++i; } ImGui::End(); if (editingMat) EditMaterialWindow(); } void Editor_MaterialPanel::MaterialInfo(Material * mat) { ImGui::Text("Shader: "); ImGui::SameLine(); ImGui::TextColored(ImVec4(1, 1, 0, 1), mat->GetShader() ? mat->GetShader()->GetNameCStr() : "none"); ComplexMaterial* cm = dynamic_cast<ComplexMaterial*>(mat); if(cm) { CMaterialInfo(cm); } PhongMaterial* pm = dynamic_cast<PhongMaterial*>(mat); if(pm) { PhongMaterialInfo(pm); } PBRMaterial* pbr = dynamic_cast<PBRMaterial*>(mat); if(pbr) { PBRMaterialInfo(pbr); } } void Editor_MaterialPanel::CMaterialInfo(ComplexMaterial* cmat) { ImGui::Text("Num properties: "); ImGui::SameLine(); ImGui::TextColored(ImVec4(1, 1, 0, 1), "%d", cmat->properties.size()); for(auto it : cmat->properties) { if(it) { ImGui::Text(("\t" + it->propertyName).c_str()); } } if (ImGui::Button("Edit")) { editingMat = true; editingMaterial = cmat; } } void Editor_MaterialPanel::PhongMaterialInfo(PhongMaterial * phong) { ImGui::Separator(); ImGui::ColorEdit3("Object color", &phong->color.r); ImGui::Checkbox("Blinn", &phong->blinn); ImGui::SameLine(); ImGui::Checkbox("Use texture", &phong->useTexture); ImGui::SameLine(); ImGui::Checkbox("Use normal map", &phong->useNormalMap); if(phong->colorTexture) { if (ImGui::ImageButton((ImTextureID*)phong->colorTexture->TextureID(), ImVec2(64, 64))) { ImGui::OpenPopup("Select color texture"); } ImGui::SameLine(); ImGui::Text("Color"); } if(phong->normalMap) { if (ImGui::ImageButton((ImTextureID*)phong->normalMap->TextureID(), ImVec2(64, 64))) { ImGui::OpenPopup("Select normal map texture"); } ImGui::SameLine(); ImGui::Text("Normal map"); } if(ImGui::BeginPopup("Select color texture")) { std::vector<Resource*> textures; resourceManager->GatherResourceOfType(RES_TEXTURE, textures); for(auto tex : textures) { Texture* t = static_cast<Texture*>(tex); ImGui::Image((ImTextureID*)t->TextureID(), ImVec2(16, 16)); ImGui::SameLine(); if (ImGui::Selectable(tex->GetNameCStr())) phong->colorTexture = t; } ImGui::EndPopup(); } if (ImGui::BeginPopup("Select normal map texture")) { std::vector<Resource*> textures; resourceManager->GatherResourceOfType(RES_TEXTURE, textures); for (auto tex : textures) { Texture* t = static_cast<Texture*>(tex); ImGui::Image((ImTextureID*)t->TextureID(), ImVec2(16, 16)); ImGui::SameLine(); if (ImGui::Selectable(tex->GetNameCStr())) phong->normalMap = t; } ImGui::EndPopup(); } ImGui::Separator(); } void Editor_MaterialPanel::PBRMaterialInfo(PBRMaterial * pbr) { ImGui::Separator(); ImGui::ColorEdit3("Albedo color", &pbr->albedoColor.r); ImGui::DragFloat("Metallic", &pbr->metallicValue, 0.01f, 0.f, 1.f); ImGui::DragFloat("Roughness", &pbr->roughnessValue, 0.01f, 0.f, 1.f); ImGui::DragFloat("AO", &pbr->aoValue, 0.01f, 0.f, 1.f); ImGui::Separator(); } void Editor_MaterialPanel::EditMaterialWindow() { ImGui::Begin("Material editor", &editingMat); if(editingMaterial) { std::vector<MatProperty*> propertiesToRemove; for (auto it : editingMaterial->properties) { if (it) { ImGui::Text(it->propertyName.c_str()); ImGui::SameLine(); ImGui::TextColored(ImVec4(0.7, 0.7, 0, 1), GetMatPropertyValueTypeStr(it->propertyType)); ImGui::SameLine(); if(ImGui::Button(("Remove " + it->propertyName).c_str())) { propertiesToRemove.push_back(it); } // Edit the property switch (it->propertyType) { case MAT_BOOL: ImGui::Checkbox(it->propertyName.c_str(), &it->propertyValue._bool); break; case MAT_INT: ImGui::DragInt(it->propertyName.c_str(), &it->propertyValue._int); break; case MAT_FLOAT: ImGui::DragFloat(it->propertyName.c_str(), &it->propertyValue._float); break; case MAT_VEC2: ImGui::DragFloat2(it->propertyName.c_str(), it->propertyValue._floatPtr); break; case MAT_VEC3: ImGui::DragFloat3(it->propertyName.c_str(), it->propertyValue._floatPtr); break; case MAT_VEC4: ImGui::DragFloat4(it->propertyName.c_str(), it->propertyValue._floatPtr); break; // TODO: Matrices & texture } if (it != (*(editingMaterial->properties.end() - 1))) ImGui::Separator(); } } // TODO: Add properties /*static int selected = -1; const char* types[] = { "INT", "FLOAT", "VEC2", "VEC3", "VEC4", "MAT2", "MAT3", "MAT4", "TEXTURE", "BOOL" }; ImGui::TextColored(ImVec4(1, 0, 0, 1), selected == -1 ? "none" : types[selected]); if(ImGui::Button("Add property")) { selected = -1; ImGui::OpenPopup("prop type"); } if(ImGui::BeginPopup("prop type")) { for(int i = 0; i < IM_ARRAYSIZE(types); ++i) { if(ImGui::Selectable(types[i])) { selected = i; editingMaterial->AddProperty(new MatProperty()) } } ImGui::EndPopup(); }*/ for(auto it : propertiesToRemove) { editingMaterial->RemoveProperty(it); } } ImGui::End(); }
22.27305
113
0.656424
[ "object", "vector" ]
296b6ff3a8dd3ed13c9d464e9876af68779dcb08
8,234
hpp
C++
tables.hpp
FreeosDAO/votemvp
33aeffa148d0f3110c2b8b933e12c1f4161d9bdc
[ "MIT" ]
null
null
null
tables.hpp
FreeosDAO/votemvp
33aeffa148d0f3110c2b8b933e12c1f4161d9bdc
[ "MIT" ]
2
2022-03-21T23:21:36.000Z
2022-03-29T21:19:47.000Z
tables.hpp
FreeosDAO/votemvp
33aeffa148d0f3110c2b8b933e12c1f4161d9bdc
[ "MIT" ]
null
null
null
#pragma once #include <eosio/eosio.hpp> #include "eosio.proton.hpp" using namespace eosio; using namespace std; namespace freedao { // SYSTEM // system table struct[[ eosio::table("system"), eosio::contract("votemvp") ]] system { time_point init; uint32_t iteration; uint32_t usercount; uint64_t claimevents; uint32_t participants; asset cls; uint64_t primary_key() const { return 0; } // return a constant to ensure a single-row table }; using system_index = eosio::multi_index<"system"_n, system>; // POINTS ACCOUNTS struct[[ eosio::table("accounts"), eosio::contract("freeosgov") ]] account { asset balance; uint64_t primary_key() const { return balance.symbol.code().raw(); } }; typedef eosio::multi_index<"accounts"_n, account> accounts; typedef eosio::multi_index<"mintfeefree"_n, account> mintfeefree_index; // currency stats struct[[ eosio::table("stat"), eosio::contract("freeosgov") ]] currency_stats { asset supply; asset max_supply; asset conditional_supply; // not used. maintained for backwards compatibility with AirClaim POINTs token name issuer; uint64_t primary_key() const { return supply.symbol.code().raw(); } }; typedef eosio::multi_index<"stat"_n, currency_stats> stats; // transferers table - a whitelist of who can call the transfer function struct[[ eosio::table("transferers"), eosio::contract("freeosgov") ]] transfer_whitelist { name account; uint64_t primary_key() const { return account.value; } }; using transferers_index = eosio::multi_index<"transferers"_n, transfer_whitelist>; // minters table - a whitelist of who can call the issue function struct[[ eosio::table("minters"), eosio::contract("freeosgov") ]] minter_whitelist { name account; uint64_t primary_key() const { return account.value; } }; using minters_index = eosio::multi_index<"minters"_n, minter_whitelist>; // burners table - a whitelist of who can call the retire function struct[[ eosio::table("burners"), eosio::contract("freeosgov") ]] burner_whitelist { name account; uint64_t primary_key() const { return account.value; } }; using burners_index = eosio::multi_index<"burners"_n, burner_whitelist>; // AirClaim iterations table // iteration calendar table struct[[ eosio::table("iterations"), eosio::contract("freeosconfig") ]] iteration { uint32_t iteration_number; time_point start; time_point end; uint16_t claim_amount; uint16_t tokens_required; uint64_t primary_key() const { return iteration_number; } uint64_t get_secondary() const { return start.time_since_epoch()._count; } }; using iterations_index = eosio::multi_index< "iterations"_n, iteration, indexed_by<"start"_n, const_mem_fun<iteration, uint64_t, &iteration::get_secondary>>>; // new statistics table - to replace counters struct[[ eosio::table("statistics"), eosio::contract("freeos") ]] statistic { uint32_t usercount; uint32_t claimevents; uint32_t unvestpercent; uint32_t unvestpercentiteration; uint32_t iteration; uint32_t failsafecounter; uint64_t primary_key() const { return 0; } // return a constant (0 in this case) to ensure a single-row table }; using statistic_index = eosio::multi_index<"statistics"_n, statistic>; // PARAMETERS // parameters table struct[[ eosio::table("parameters"), eosio::contract("votemvp") ]] parameter { name paramname; string value; uint64_t primary_key() const { return paramname.value; } }; using parameters_index = eosio::multi_index<"parameters"_n, parameter>; // DPARAMETERS // double parameters table struct[[ eosio::table("dparameters"), eosio::contract("votemvp") ]] dparameter { name paramname; double value; uint64_t primary_key() const { return paramname.value; } }; using dparameters_index = eosio::multi_index<"dparameters"_n, dparameter>; // USERS // the registered user table struct[[ eosio::table("users"), eosio::contract("freeosgov") ]] user { asset stake; // how many tokens staked string account_type; // user's verification level uint32_t registered_iteration; // when the user was registered uint32_t staked_iteration; // the iteration in which the user staked their tokens uint32_t votes; // how many votes the user has made uint32_t issuances; // total number of times the user has been issued with OPTIONs uint32_t last_issuance; // the last iteration in which the user was issued with OPTIONs asset total_issuance_amount; // accrued POINTs uint64_t primary_key() const { return 0; } // return a constant to ensure a single-row table }; using users_index = eosio::multi_index<"users"_n, user>; // AIRCLAIM_USERS // the airclaim registered user table struct[[ eosio::table("users"), eosio::contract("freeos") ]] airclaim_user { asset stake; // how many XPR tokens staked char account_type; // user's verification level uint32_t registered_iteration; // when the user was registered uint32_t staked_iteration; // the iteration in which the user staked their tokens uint32_t votes; // how many votes the user has made uint32_t issuances; // total number of times the user has been issued with // OPTIONs uint32_t last_issuance; // the last iteration in which the user was issued // with OPTIONs uint64_t primary_key() const { return stake.symbol.code().raw(); } }; using airclaim_users_index = eosio::multi_index<"users"_n, airclaim_user>; // USERSINFO // Verification table - a mockup of the verification table on eosio.proton which is not available on the testnet // This allows us to test in development. // Used to determine a user's account_type. Taken from // https://github.com/ProtonProtocol/proton.contracts/blob/master/contracts/eosio.proton/include/eosio.proton/eosio.proton.hpp struct[[ eosio::table("usersinfo"), eosio::contract("eosio.proton") ]] userinfo { name acc; std::string name; std::string avatar; bool verified; uint64_t date; uint64_t verifiedon; eosio::name verifier; std::vector<eosio::name> raccs; std::vector<std::tuple<eosio::name, eosio::name>> aacts; std::vector<std::tuple<eosio::name, std::string>> ac; std::vector<kyc_prov> kyc; uint64_t primary_key() const { return acc.value; } }; typedef eosio::multi_index<"usersinfo"_n, userinfo> usersinfo; // PARTICIPATION // survey, vote and ratification participation table struct[[ eosio::table("svrs"), eosio::contract("votemvp") ]] svr { uint32_t survey0; uint32_t survey1; uint32_t survey2; uint32_t survey3; uint32_t survey4; uint32_t vote0; uint32_t vote1; uint32_t vote2; uint32_t vote3; uint32_t vote4; uint32_t ratify0; uint32_t ratify1; uint32_t ratify2; uint32_t ratify3; uint32_t ratify4; uint64_t primary_key() const { return 0; } // return a constant to ensure a single-row table }; using svr_index = eosio::multi_index<"svrs"_n, svr>; // VOTE // Running processing of vote responses struct[[ eosio::table("voterecord"), eosio::contract("votemvp") ]] vote_record { uint32_t iteration; uint32_t participants; double q1average; // issuance rate (0 - 100) double q2average; // mint fee percent (6 - 30) double q3average; // locking threshold - expressed as asset price uint32_t q4choice1; // POOL uint32_t q4choice2; // BURN double q5average; // Reserve pool % to be released uint32_t q6choice1; // partner 1 uint32_t q6choice2; // partner 2 uint32_t q6choice3; // partner 3 uint32_t q6choice4; // partner 4 uint32_t q6choice5; // partner 5 uint32_t q6choice6; // partner 6 uint64_t primary_key() const { return 0; } // return a constant to ensure a single-row table }; using vote_index = eosio::multi_index<"voterecord"_n, vote_record>; // EXCHANGERATE // exchangerate table struct[[ eosio::table("exchangerate"), eosio::contract("freeosgov") ]] price { double currentprice; double targetprice; uint64_t primary_key() const { return 0; } // return a constant (0 in this case) to ensure a single-row table }; using exchange_index = eosio::multi_index<"exchangerate"_n, price>; } // end of namespace freedao
33.745902
126
0.71642
[ "vector" ]
296d30f0c7e4c60c90c79aef163495a4aff3602e
167,704
hh
C++
lib/include/filesystem.hh
aqk/chiapos
1f82a109af0bfbfc1a1b703c23ef89fdd2392e1b
[ "Apache-2.0" ]
null
null
null
lib/include/filesystem.hh
aqk/chiapos
1f82a109af0bfbfc1a1b703c23ef89fdd2392e1b
[ "Apache-2.0" ]
null
null
null
lib/include/filesystem.hh
aqk/chiapos
1f82a109af0bfbfc1a1b703c23ef89fdd2392e1b
[ "Apache-2.0" ]
null
null
null
//--------------------------------------------------------------------------------------- // // ghc::filesystem - A C++17-like filesystem implementation for C++11/C++14/C++17 // //--------------------------------------------------------------------------------------- // // Copyright (c) 2018, Steffen Schümann <s.schuemann@pobox.com> // // 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. // //--------------------------------------------------------------------------------------- // // To dynamically select std::filesystem where available, you could use: // // #if defined(__cplusplus) && __cplusplus >= 201703L && defined(__has_include) && __has_include(<filesystem>) // #include <filesystem> // namespace fs = std::filesystem; // #else // #include <ghc/filesystem.hpp> // namespace fs = ghc::filesystem; // #endif // //--------------------------------------------------------------------------------------- #ifndef GHC_FILESYSTEM_H #define GHC_FILESYSTEM_H // #define BSD manifest constant only in // sys/param.h #ifndef _WIN32 #include <sys/param.h> #endif #ifndef GHC_OS_DETECTED #if defined(__APPLE__) && defined(__MACH__) #define GHC_OS_MACOS #elif defined(__linux__) #define GHC_OS_LINUX #if defined(__ANDROID__) #define GHC_OS_ANDROID #endif #elif defined(_WIN64) #define GHC_OS_WINDOWS #define GHC_OS_WIN64 #elif defined(_WIN32) #define GHC_OS_WINDOWS #define GHC_OS_WIN32 #elif defined(__svr4__) #define GHC_OS_SYS5R4 #elif defined(BSD) #define GHC_OS_BSD #elif defined(__EMSCRIPTEN__) #define GHC_OS_WEB #include <wasi/api.h> #else #error "Operating system currently not supported!" #endif #define GHC_OS_DETECTED #endif #if defined(GHC_FILESYSTEM_IMPLEMENTATION) #define GHC_EXPAND_IMPL #define GHC_INLINE #ifdef GHC_OS_WINDOWS #define GHC_FS_API #define GHC_FS_API_CLASS #else #define GHC_FS_API __attribute__((visibility("default"))) #define GHC_FS_API_CLASS __attribute__((visibility("default"))) #endif #elif defined(GHC_FILESYSTEM_FWD) #define GHC_INLINE #ifdef GHC_OS_WINDOWS #define GHC_FS_API extern #define GHC_FS_API_CLASS #else #define GHC_FS_API extern #define GHC_FS_API_CLASS #endif #else #define GHC_EXPAND_IMPL #define GHC_INLINE inline #define GHC_FS_API #define GHC_FS_API_CLASS #endif #ifdef GHC_EXPAND_IMPL #ifdef GHC_OS_WINDOWS #include <windows.h> // additional includes #include <shellapi.h> #include <sys/stat.h> #include <sys/types.h> #include <wchar.h> #include <winioctl.h> #else #include <dirent.h> #include <fcntl.h> #include <sys/param.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <limits.h> #ifdef GHC_OS_ANDROID #include <android/api-level.h> #if __ANDROID_API__ < 12 #include <sys/syscall.h> #endif #include <sys/vfs.h> #define statvfs statfs #else #include <sys/statvfs.h> #endif #if !defined(__ANDROID__) || __ANDROID_API__ >= 26 #include <langinfo.h> #endif #endif #ifdef GHC_OS_MACOS #include <Availability.h> #endif #include <algorithm> #include <cctype> #include <chrono> #include <clocale> #include <cstdlib> #include <cstring> #include <fstream> #include <functional> #include <memory> #include <stack> #include <stdexcept> #include <string> #include <system_error> #include <type_traits> #include <utility> #include <vector> #else // GHC_EXPAND_IMPL #include <chrono> #include <fstream> #include <memory> #include <stack> #include <stdexcept> #include <string> #include <system_error> #ifdef GHC_OS_WINDOWS #include <vector> #endif #endif // GHC_EXPAND_IMPL //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Behaviour Switches (see README.md, should match the config in test/filesystem_test.cpp): //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // LWG #2682 disables the since then invalid use of the copy option create_symlinks on directories // configure LWG conformance () #define LWG_2682_BEHAVIOUR //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // LWG #2395 makes crate_directory/create_directories not emit an error if there is a regular // file with that name, it is superceded by P1164R1, so only activate if really needed // #define LWG_2935_BEHAVIOUR //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // LWG #2937 enforces that fs::equivalent emits an error, if !fs::exists(p1)||!exists(p2) #define LWG_2937_BEHAVIOUR //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // UTF8-Everywhere is the original behaviour of ghc::filesystem. With this define you can // enable the more standard conforming implementation option that uses wstring on Windows // as ghc::filesystem::string_type. // #define GHC_WIN_WSTRING_STRING_TYPE //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Raise errors/exceptions when invalid unicode codepoints or UTF-8 sequences are found, // instead of replacing them with the unicode replacement character (U+FFFD). // #define GHC_RAISE_UNICODE_ERRORS //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // ghc::filesystem version in decimal (major * 10000 + minor * 100 + patch) #define GHC_FILESYSTEM_VERSION 10304L #if !defined(GHC_WITH_EXCEPTIONS) && (defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)) #define GHC_WITH_EXCEPTIONS #endif #if !defined(GHC_WITH_EXCEPTIONS) && defined(GHC_RAISE_UNICODE_ERRORS) #error "Can't raise unicode errors whith exception support disabled" #endif namespace ghc { namespace filesystem { // temporary existing exception type for yet unimplemented parts class GHC_FS_API_CLASS not_implemented_exception : public std::logic_error { public: not_implemented_exception() : std::logic_error("function not implemented yet.") { } }; template<typename char_type> class path_helper_base { public: using value_type = char_type; #ifdef GHC_OS_WINDOWS static constexpr value_type preferred_separator = '\\'; #else static constexpr value_type preferred_separator = '/'; #endif }; #if __cplusplus < 201703L template <typename char_type> constexpr char_type path_helper_base<char_type>::preferred_separator; #endif // 30.10.8 class path class GHC_FS_API_CLASS path #if defined(GHC_OS_WINDOWS) && defined(GHC_WIN_WSTRING_STRING_TYPE) #define GHC_USE_WCHAR_T : private path_helper_base<std::wstring::value_type> { public: using path_helper_base<std::wstring::value_type>::value_type; #else : private path_helper_base<std::string::value_type> { public: using path_helper_base<std::string::value_type>::value_type; #endif using string_type = std::basic_string<value_type>; using path_helper_base<value_type>::preferred_separator; // 30.10.10.1 enumeration format /// The path format in wich the constructor argument is given. enum format { generic_format, ///< The generic format, internally used by ///< ghc::filesystem::path with slashes native_format, ///< The format native to the current platform this code ///< is build for auto_format, ///< Try to auto-detect the format, fallback to native }; template <class T> struct _is_basic_string : std::false_type { }; template <class CharT, class Traits, class Alloc> struct _is_basic_string<std::basic_string<CharT, Traits, Alloc>> : std::true_type { }; #ifdef __cpp_lib_string_view template <class CharT> struct _is_basic_string<std::basic_string_view<CharT>> : std::true_type { }; #endif template <typename T1, typename T2 = void> using path_type = typename std::enable_if<!std::is_same<path, T1>::value, path>::type; #ifdef GHC_USE_WCHAR_T template <typename T> using path_from_string = typename std::enable_if<_is_basic_string<T>::value || std::is_same<char const*, typename std::decay<T>::type>::value || std::is_same<char*, typename std::decay<T>::type>::value || std::is_same<wchar_t const*, typename std::decay<T>::type>::value || std::is_same<wchar_t*, typename std::decay<T>::type>::value, path>::type; template <typename T> using path_type_EcharT = typename std::enable_if<std::is_same<T, char>::value || std::is_same<T, char16_t>::value || std::is_same<T, char32_t>::value, path>::type; #else template <typename T> using path_from_string = typename std::enable_if<_is_basic_string<T>::value || std::is_same<char const*, typename std::decay<T>::type>::value || std::is_same<char*, typename std::decay<T>::type>::value, path>::type; template <typename T> using path_type_EcharT = typename std::enable_if<std::is_same<T, char>::value || std::is_same<T, char16_t>::value || std::is_same<T, char32_t>::value || std::is_same<T, wchar_t>::value, path>::type; #endif // 30.10.8.4.1 constructors and destructor path() noexcept; path(const path& p); path(path&& p) noexcept; path(string_type&& source, format fmt = auto_format); template <class Source, typename = path_from_string<Source>> path(const Source& source, format fmt = auto_format); template <class InputIterator> path(InputIterator first, InputIterator last, format fmt = auto_format); #ifdef GHC_WITH_EXCEPTIONS template <class Source, typename = path_from_string<Source>> path(const Source& source, const std::locale& loc, format fmt = auto_format); template <class InputIterator> path(InputIterator first, InputIterator last, const std::locale& loc, format fmt = auto_format); #endif ~path(); // 30.10.8.4.2 assignments path& operator=(const path& p); path& operator=(path&& p) noexcept; path& operator=(string_type&& source); path& assign(string_type&& source); template <class Source> path& operator=(const Source& source); template <class Source> path& assign(const Source& source); template <class InputIterator> path& assign(InputIterator first, InputIterator last); // 30.10.8.4.3 appends path& operator/=(const path& p); template <class Source> path& operator/=(const Source& source); template <class Source> path& append(const Source& source); template <class InputIterator> path& append(InputIterator first, InputIterator last); // 30.10.8.4.4 concatenation path& operator+=(const path& x); path& operator+=(const string_type& x); #ifdef __cpp_lib_string_view path& operator+=(std::basic_string_view<value_type> x); #endif path& operator+=(const value_type* x); path& operator+=(value_type x); template <class Source> path_from_string<Source>& operator+=(const Source& x); template <class EcharT> path_type_EcharT<EcharT>& operator+=(EcharT x); template <class Source> path& concat(const Source& x); template <class InputIterator> path& concat(InputIterator first, InputIterator last); // 30.10.8.4.5 modifiers void clear() noexcept; path& make_preferred(); path& remove_filename(); path& replace_filename(const path& replacement); path& replace_extension(const path& replacement = path()); void swap(path& rhs) noexcept; // 30.10.8.4.6 native format observers const string_type& native() const; // this implementation doesn't support noexcept for native() const value_type* c_str() const; // this implementation doesn't support noexcept for c_str() operator string_type() const; template <class EcharT, class traits = std::char_traits<EcharT>, class Allocator = std::allocator<EcharT>> std::basic_string<EcharT, traits, Allocator> string(const Allocator& a = Allocator()) const; std::string string() const; std::wstring wstring() const; std::string u8string() const; std::u16string u16string() const; std::u32string u32string() const; // 30.10.8.4.7 generic format observers template <class EcharT, class traits = std::char_traits<EcharT>, class Allocator = std::allocator<EcharT>> std::basic_string<EcharT, traits, Allocator> generic_string(const Allocator& a = Allocator()) const; const std::string& generic_string() const; // this is different from the standard, that returns by value std::wstring generic_wstring() const; std::string generic_u8string() const; std::u16string generic_u16string() const; std::u32string generic_u32string() const; // 30.10.8.4.8 compare int compare(const path& p) const noexcept; int compare(const string_type& s) const; #ifdef __cpp_lib_string_view int compare(std::basic_string_view<value_type> s) const; #endif int compare(const value_type* s) const; // 30.10.8.4.9 decomposition path root_name() const; path root_directory() const; path root_path() const; path relative_path() const; path parent_path() const; path filename() const; path stem() const; path extension() const; // 30.10.8.4.10 query bool empty() const noexcept; bool has_root_name() const; bool has_root_directory() const; bool has_root_path() const; bool has_relative_path() const; bool has_parent_path() const; bool has_filename() const; bool has_stem() const; bool has_extension() const; bool is_absolute() const; bool is_relative() const; // 30.10.8.4.11 generation path lexically_normal() const; path lexically_relative(const path& base) const; path lexically_proximate(const path& base) const; // 30.10.8.5 iterators class iterator; using const_iterator = iterator; iterator begin() const; iterator end() const; private: using impl_value_type = std::string::value_type; using impl_string_type = std::basic_string<impl_value_type>; friend class directory_iterator; void append_name(const char* name); static constexpr impl_value_type generic_separator = '/'; template <typename InputIterator> class input_iterator_range { public: typedef InputIterator iterator; typedef InputIterator const_iterator; typedef typename InputIterator::difference_type difference_type; input_iterator_range(const InputIterator& first, const InputIterator& last) : _first(first) , _last(last) { } InputIterator begin() const { return _first; } InputIterator end() const { return _last; } private: InputIterator _first; InputIterator _last; }; friend void swap(path& lhs, path& rhs) noexcept; friend size_t hash_value(const path& p) noexcept; static void postprocess_path_with_format(impl_string_type& p, format fmt); impl_string_type _path; #ifdef GHC_OS_WINDOWS impl_string_type native_impl() const; mutable string_type _native_cache; #else const impl_string_type& native_impl() const; #endif }; // 30.10.8.6 path non-member functions GHC_FS_API void swap(path& lhs, path& rhs) noexcept; GHC_FS_API size_t hash_value(const path& p) noexcept; GHC_FS_API bool operator==(const path& lhs, const path& rhs) noexcept; GHC_FS_API bool operator!=(const path& lhs, const path& rhs) noexcept; GHC_FS_API bool operator<(const path& lhs, const path& rhs) noexcept; GHC_FS_API bool operator<=(const path& lhs, const path& rhs) noexcept; GHC_FS_API bool operator>(const path& lhs, const path& rhs) noexcept; GHC_FS_API bool operator>=(const path& lhs, const path& rhs) noexcept; GHC_FS_API path operator/(const path& lhs, const path& rhs); // 30.10.8.6.1 path inserter and extractor template <class charT, class traits> std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, const path& p); template <class charT, class traits> std::basic_istream<charT, traits>& operator>>(std::basic_istream<charT, traits>& is, path& p); // 30.10.8.6.2 path factory functions template <class Source, typename = path::path_from_string<Source>> path u8path(const Source& source); template <class InputIterator> path u8path(InputIterator first, InputIterator last); // 30.10.9 class filesystem_error class GHC_FS_API_CLASS filesystem_error : public std::system_error { public: filesystem_error(const std::string& what_arg, std::error_code ec); filesystem_error(const std::string& what_arg, const path& p1, std::error_code ec); filesystem_error(const std::string& what_arg, const path& p1, const path& p2, std::error_code ec); const path& path1() const noexcept; const path& path2() const noexcept; const char* what() const noexcept override; private: std::string _what_arg; std::error_code _ec; path _p1, _p2; }; class GHC_FS_API_CLASS path::iterator { public: using value_type = const path; using difference_type = std::ptrdiff_t; using pointer = const path*; using reference = const path&; using iterator_category = std::bidirectional_iterator_tag; iterator(); iterator(const impl_string_type::const_iterator& first, const impl_string_type::const_iterator& last, const impl_string_type::const_iterator& pos); iterator& operator++(); iterator operator++(int); iterator& operator--(); iterator operator--(int); bool operator==(const iterator& other) const; bool operator!=(const iterator& other) const; reference operator*() const; pointer operator->() const; private: impl_string_type::const_iterator increment(const std::string::const_iterator& pos) const; impl_string_type::const_iterator decrement(const std::string::const_iterator& pos) const; void updateCurrent(); impl_string_type::const_iterator _first; impl_string_type::const_iterator _last; impl_string_type::const_iterator _root; impl_string_type::const_iterator _iter; path _current; }; struct space_info { uintmax_t capacity; uintmax_t free; uintmax_t available; }; // 30.10.10, enumerations enum class file_type { none, not_found, regular, directory, symlink, block, character, fifo, socket, unknown, }; enum class perms : uint16_t { none = 0, owner_read = 0400, owner_write = 0200, owner_exec = 0100, owner_all = 0700, group_read = 040, group_write = 020, group_exec = 010, group_all = 070, others_read = 04, others_write = 02, others_exec = 01, others_all = 07, all = 0777, set_uid = 04000, set_gid = 02000, sticky_bit = 01000, mask = 07777, unknown = 0xffff }; enum class perm_options : uint16_t { replace = 3, add = 1, remove = 2, nofollow = 4, }; enum class copy_options : uint16_t { none = 0, skip_existing = 1, overwrite_existing = 2, update_existing = 4, recursive = 8, copy_symlinks = 0x10, skip_symlinks = 0x20, directories_only = 0x40, create_symlinks = 0x80, #ifndef GHC_OS_WEB create_hard_links = 0x100 #endif }; enum class directory_options : uint16_t { none = 0, follow_directory_symlink = 1, skip_permission_denied = 2, }; // 30.10.11 class file_status class GHC_FS_API_CLASS file_status { public: // 30.10.11.1 constructors and destructor file_status() noexcept; explicit file_status(file_type ft, perms prms = perms::unknown) noexcept; file_status(const file_status&) noexcept; file_status(file_status&&) noexcept; ~file_status(); // assignments: file_status& operator=(const file_status&) noexcept; file_status& operator=(file_status&&) noexcept; // 30.10.11.3 modifiers void type(file_type ft) noexcept; void permissions(perms prms) noexcept; // 30.10.11.2 observers file_type type() const noexcept; perms permissions() const noexcept; private: file_type _type; perms _perms; }; using file_time_type = std::chrono::time_point<std::chrono::system_clock>; // 30.10.12 Class directory_entry class GHC_FS_API_CLASS directory_entry { public: // 30.10.12.1 constructors and destructor directory_entry() noexcept = default; directory_entry(const directory_entry&) = default; directory_entry(directory_entry&&) noexcept = default; #ifdef GHC_WITH_EXCEPTIONS explicit directory_entry(const path& p); #endif directory_entry(const path& p, std::error_code& ec); ~directory_entry(); // assignments: directory_entry& operator=(const directory_entry&) = default; directory_entry& operator=(directory_entry&&) noexcept = default; // 30.10.12.2 modifiers #ifdef GHC_WITH_EXCEPTIONS void assign(const path& p); #endif void assign(const path& p, std::error_code& ec); #ifdef GHC_WITH_EXCEPTIONS void replace_filename(const path& p); #endif void replace_filename(const path& p, std::error_code& ec); #ifdef GHC_WITH_EXCEPTIONS void refresh(); #endif void refresh(std::error_code& ec) noexcept; // 30.10.12.3 observers const filesystem::path& path() const noexcept; operator const filesystem::path&() const noexcept; #ifdef GHC_WITH_EXCEPTIONS bool exists() const; #endif bool exists(std::error_code& ec) const noexcept; #ifdef GHC_WITH_EXCEPTIONS bool is_block_file() const; #endif bool is_block_file(std::error_code& ec) const noexcept; #ifdef GHC_WITH_EXCEPTIONS bool is_character_file() const; #endif bool is_character_file(std::error_code& ec) const noexcept; #ifdef GHC_WITH_EXCEPTIONS bool is_directory() const; #endif bool is_directory(std::error_code& ec) const noexcept; #ifdef GHC_WITH_EXCEPTIONS bool is_fifo() const; #endif bool is_fifo(std::error_code& ec) const noexcept; #ifdef GHC_WITH_EXCEPTIONS bool is_other() const; #endif bool is_other(std::error_code& ec) const noexcept; #ifdef GHC_WITH_EXCEPTIONS bool is_regular_file() const; #endif bool is_regular_file(std::error_code& ec) const noexcept; #ifdef GHC_WITH_EXCEPTIONS bool is_socket() const; #endif bool is_socket(std::error_code& ec) const noexcept; #ifdef GHC_WITH_EXCEPTIONS bool is_symlink() const; #endif bool is_symlink(std::error_code& ec) const noexcept; #ifdef GHC_WITH_EXCEPTIONS uintmax_t file_size() const; #endif uintmax_t file_size(std::error_code& ec) const noexcept; #ifndef GHC_OS_WEB #ifdef GHC_WITH_EXCEPTIONS uintmax_t hard_link_count() const; #endif uintmax_t hard_link_count(std::error_code& ec) const noexcept; #endif #ifdef GHC_WITH_EXCEPTIONS file_time_type last_write_time() const; #endif file_time_type last_write_time(std::error_code& ec) const noexcept; #ifdef GHC_WITH_EXCEPTIONS file_status status() const; #endif file_status status(std::error_code& ec) const noexcept; #ifdef GHC_WITH_EXCEPTIONS file_status symlink_status() const; #endif file_status symlink_status(std::error_code& ec) const noexcept; bool operator<(const directory_entry& rhs) const noexcept; bool operator==(const directory_entry& rhs) const noexcept; bool operator!=(const directory_entry& rhs) const noexcept; bool operator<=(const directory_entry& rhs) const noexcept; bool operator>(const directory_entry& rhs) const noexcept; bool operator>=(const directory_entry& rhs) const noexcept; private: friend class directory_iterator; filesystem::path _path; file_status _status; file_status _symlink_status; uintmax_t _file_size = 0; #ifndef GHC_OS_WINDOWS uintmax_t _hard_link_count = 0; #endif time_t _last_write_time = 0; }; // 30.10.13 Class directory_iterator class GHC_FS_API_CLASS directory_iterator { public: class GHC_FS_API_CLASS proxy { public: const directory_entry& operator*() const& noexcept { return _dir_entry; } directory_entry operator*() && noexcept { return std::move(_dir_entry); } private: explicit proxy(const directory_entry& dir_entry) : _dir_entry(dir_entry) { } friend class directory_iterator; friend class recursive_directory_iterator; directory_entry _dir_entry; }; using iterator_category = std::input_iterator_tag; using value_type = directory_entry; using difference_type = std::ptrdiff_t; using pointer = const directory_entry*; using reference = const directory_entry&; // 30.10.13.1 member functions directory_iterator() noexcept; #ifdef GHC_WITH_EXCEPTIONS explicit directory_iterator(const path& p); directory_iterator(const path& p, directory_options options); #endif directory_iterator(const path& p, std::error_code& ec) noexcept; directory_iterator(const path& p, directory_options options, std::error_code& ec) noexcept; directory_iterator(const directory_iterator& rhs); directory_iterator(directory_iterator&& rhs) noexcept; ~directory_iterator(); directory_iterator& operator=(const directory_iterator& rhs); directory_iterator& operator=(directory_iterator&& rhs) noexcept; const directory_entry& operator*() const; const directory_entry* operator->() const; #ifdef GHC_WITH_EXCEPTIONS directory_iterator& operator++(); #endif directory_iterator& increment(std::error_code& ec) noexcept; // other members as required by 27.2.3, input iterators #ifdef GHC_WITH_EXCEPTIONS proxy operator++(int) { proxy p{**this}; ++*this; return p; } #endif bool operator==(const directory_iterator& rhs) const; bool operator!=(const directory_iterator& rhs) const; private: friend class recursive_directory_iterator; class impl; std::shared_ptr<impl> _impl; }; // 30.10.13.2 directory_iterator non-member functions GHC_FS_API directory_iterator begin(directory_iterator iter) noexcept; GHC_FS_API directory_iterator end(const directory_iterator&) noexcept; // 30.10.14 class recursive_directory_iterator class GHC_FS_API_CLASS recursive_directory_iterator { public: using iterator_category = std::input_iterator_tag; using value_type = directory_entry; using difference_type = std::ptrdiff_t; using pointer = const directory_entry*; using reference = const directory_entry&; // 30.10.14.1 constructors and destructor recursive_directory_iterator() noexcept; #ifdef GHC_WITH_EXCEPTIONS explicit recursive_directory_iterator(const path& p); recursive_directory_iterator(const path& p, directory_options options); #endif recursive_directory_iterator(const path& p, directory_options options, std::error_code& ec) noexcept; recursive_directory_iterator(const path& p, std::error_code& ec) noexcept; recursive_directory_iterator(const recursive_directory_iterator& rhs); recursive_directory_iterator(recursive_directory_iterator&& rhs) noexcept; ~recursive_directory_iterator(); // 30.10.14.1 observers directory_options options() const; int depth() const; bool recursion_pending() const; const directory_entry& operator*() const; const directory_entry* operator->() const; // 30.10.14.1 modifiers recursive_directory_iterator& recursive_directory_iterator& operator=(const recursive_directory_iterator& rhs); recursive_directory_iterator& operator=(recursive_directory_iterator&& rhs) noexcept; #ifdef GHC_WITH_EXCEPTIONS recursive_directory_iterator& operator++(); #endif recursive_directory_iterator& increment(std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS void pop(); #endif void pop(std::error_code& ec); void disable_recursion_pending(); // other members as required by 27.2.3, input iterators #ifdef GHC_WITH_EXCEPTIONS directory_iterator::proxy operator++(int) { directory_iterator::proxy proxy{**this}; ++*this; return proxy; } #endif bool operator==(const recursive_directory_iterator& rhs) const; bool operator!=(const recursive_directory_iterator& rhs) const; private: struct recursive_directory_iterator_impl { directory_options _options; bool _recursion_pending; std::stack<directory_iterator> _dir_iter_stack; recursive_directory_iterator_impl(directory_options options, bool recursion_pending) : _options(options) , _recursion_pending(recursion_pending) { } }; std::shared_ptr<recursive_directory_iterator_impl> _impl; }; // 30.10.14.2 directory_iterator non-member functions GHC_FS_API recursive_directory_iterator begin(recursive_directory_iterator iter) noexcept; GHC_FS_API recursive_directory_iterator end(const recursive_directory_iterator&) noexcept; // 30.10.15 filesystem operations #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API path absolute(const path& p); #endif GHC_FS_API path absolute(const path& p, std::error_code& ec); #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API path canonical(const path& p); #endif GHC_FS_API path canonical(const path& p, std::error_code& ec); #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API void copy(const path& from, const path& to); #endif GHC_FS_API void copy(const path& from, const path& to, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API void copy(const path& from, const path& to, copy_options options); #endif GHC_FS_API void copy(const path& from, const path& to, copy_options options, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool copy_file(const path& from, const path& to); #endif GHC_FS_API bool copy_file(const path& from, const path& to, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool copy_file(const path& from, const path& to, copy_options option); #endif GHC_FS_API bool copy_file(const path& from, const path& to, copy_options option, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API void copy_symlink(const path& existing_symlink, const path& new_symlink); #endif GHC_FS_API void copy_symlink(const path& existing_symlink, const path& new_symlink, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool create_directories(const path& p); #endif GHC_FS_API bool create_directories(const path& p, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool create_directory(const path& p); #endif GHC_FS_API bool create_directory(const path& p, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool create_directory(const path& p, const path& attributes); #endif GHC_FS_API bool create_directory(const path& p, const path& attributes, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API void create_directory_symlink(const path& to, const path& new_symlink); #endif GHC_FS_API void create_directory_symlink(const path& to, const path& new_symlink, std::error_code& ec) noexcept; #ifndef GHC_OS_WEB #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API void create_hard_link(const path& to, const path& new_hard_link); #endif GHC_FS_API void create_hard_link(const path& to, const path& new_hard_link, std::error_code& ec) noexcept; #endif #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API void create_symlink(const path& to, const path& new_symlink); #endif GHC_FS_API void create_symlink(const path& to, const path& new_symlink, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API path current_path(); #endif GHC_FS_API path current_path(std::error_code& ec); #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API void current_path(const path& p); #endif GHC_FS_API void current_path(const path& p, std::error_code& ec) noexcept; GHC_FS_API bool exists(file_status s) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool exists(const path& p); #endif GHC_FS_API bool exists(const path& p, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool equivalent(const path& p1, const path& p2); #endif GHC_FS_API bool equivalent(const path& p1, const path& p2, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API uintmax_t file_size(const path& p); #endif GHC_FS_API uintmax_t file_size(const path& p, std::error_code& ec) noexcept; #ifndef GHC_OS_WEB #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API uintmax_t hard_link_count(const path& p); #endif GHC_FS_API uintmax_t hard_link_count(const path& p, std::error_code& ec) noexcept; #endif GHC_FS_API bool is_block_file(file_status s) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool is_block_file(const path& p); #endif GHC_FS_API bool is_block_file(const path& p, std::error_code& ec) noexcept; GHC_FS_API bool is_character_file(file_status s) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool is_character_file(const path& p); #endif GHC_FS_API bool is_character_file(const path& p, std::error_code& ec) noexcept; GHC_FS_API bool is_directory(file_status s) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool is_directory(const path& p); #endif GHC_FS_API bool is_directory(const path& p, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool is_empty(const path& p); #endif GHC_FS_API bool is_empty(const path& p, std::error_code& ec) noexcept; GHC_FS_API bool is_fifo(file_status s) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool is_fifo(const path& p); #endif GHC_FS_API bool is_fifo(const path& p, std::error_code& ec) noexcept; GHC_FS_API bool is_other(file_status s) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool is_other(const path& p); #endif GHC_FS_API bool is_other(const path& p, std::error_code& ec) noexcept; GHC_FS_API bool is_regular_file(file_status s) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool is_regular_file(const path& p); #endif GHC_FS_API bool is_regular_file(const path& p, std::error_code& ec) noexcept; GHC_FS_API bool is_socket(file_status s) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool is_socket(const path& p); #endif GHC_FS_API bool is_socket(const path& p, std::error_code& ec) noexcept; GHC_FS_API bool is_symlink(file_status s) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool is_symlink(const path& p); #endif GHC_FS_API bool is_symlink(const path& p, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API file_time_type last_write_time(const path& p); #endif GHC_FS_API file_time_type last_write_time(const path& p, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API void last_write_time(const path& p, file_time_type new_time); #endif GHC_FS_API void last_write_time(const path& p, file_time_type new_time, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API void permissions(const path& p, perms prms, perm_options opts = perm_options::replace); #endif GHC_FS_API void permissions(const path& p, perms prms, std::error_code& ec) noexcept; GHC_FS_API void permissions(const path& p, perms prms, perm_options opts, std::error_code& ec); #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API path proximate(const path& p, std::error_code& ec); GHC_FS_API path proximate(const path& p, const path& base = current_path()); #endif GHC_FS_API path proximate(const path& p, const path& base, std::error_code& ec); #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API path read_symlink(const path& p); #endif GHC_FS_API path read_symlink(const path& p, std::error_code& ec); GHC_FS_API path relative(const path& p, std::error_code& ec); #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API path relative(const path& p, const path& base = current_path()); #endif GHC_FS_API path relative(const path& p, const path& base, std::error_code& ec); #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API bool remove(const path& p); #endif GHC_FS_API bool remove(const path& p, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API uintmax_t remove_all(const path& p); #endif GHC_FS_API uintmax_t remove_all(const path& p, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API void rename(const path& from, const path& to); #endif GHC_FS_API void rename(const path& from, const path& to, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API void resize_file(const path& p, uintmax_t size); #endif GHC_FS_API void resize_file(const path& p, uintmax_t size, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API space_info space(const path& p); #endif GHC_FS_API space_info space(const path& p, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API file_status status(const path& p); #endif GHC_FS_API file_status status(const path& p, std::error_code& ec) noexcept; GHC_FS_API bool status_known(file_status s) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API file_status symlink_status(const path& p); #endif GHC_FS_API file_status symlink_status(const path& p, std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API path temp_directory_path(); #endif GHC_FS_API path temp_directory_path(std::error_code& ec) noexcept; #ifdef GHC_WITH_EXCEPTIONS GHC_FS_API path weakly_canonical(const path& p); #endif GHC_FS_API path weakly_canonical(const path& p, std::error_code& ec) noexcept; // Non-C++17 add-on std::fstream wrappers with path template <class charT, class traits = std::char_traits<charT>> class basic_filebuf : public std::basic_filebuf<charT, traits> { public: basic_filebuf() {} ~basic_filebuf() override {} basic_filebuf(const basic_filebuf&) = delete; const basic_filebuf& operator=(const basic_filebuf&) = delete; basic_filebuf<charT, traits>* open(const path& p, std::ios_base::openmode mode) { #if defined(GHC_OS_WINDOWS) && !defined(__GLIBCXX__) return std::basic_filebuf<charT, traits>::open(p.wstring().c_str(), mode) ? this : 0; #else return std::basic_filebuf<charT, traits>::open(p.string().c_str(), mode) ? this : 0; #endif } }; template <class charT, class traits = std::char_traits<charT>> class basic_ifstream : public std::basic_ifstream<charT, traits> { public: basic_ifstream() {} #if defined(GHC_OS_WINDOWS) && !defined(__GLIBCXX__) explicit basic_ifstream(const path& p, std::ios_base::openmode mode = std::ios_base::in) : std::basic_ifstream<charT, traits>(p.wstring().c_str(), mode) { } void open(const path& p, std::ios_base::openmode mode = std::ios_base::in) { std::basic_ifstream<charT, traits>::open(p.wstring().c_str(), mode); } #else explicit basic_ifstream(const path& p, std::ios_base::openmode mode = std::ios_base::in) : std::basic_ifstream<charT, traits>(p.string().c_str(), mode) { } void open(const path& p, std::ios_base::openmode mode = std::ios_base::in) { std::basic_ifstream<charT, traits>::open(p.string().c_str(), mode); } #endif basic_ifstream(const basic_ifstream&) = delete; const basic_ifstream& operator=(const basic_ifstream&) = delete; ~basic_ifstream() override {} }; template <class charT, class traits = std::char_traits<charT>> class basic_ofstream : public std::basic_ofstream<charT, traits> { public: basic_ofstream() {} #if defined(GHC_OS_WINDOWS) && !defined(__GLIBCXX__) explicit basic_ofstream(const path& p, std::ios_base::openmode mode = std::ios_base::out) : std::basic_ofstream<charT, traits>(p.wstring().c_str(), mode) { } void open(const path& p, std::ios_base::openmode mode = std::ios_base::out) { std::basic_ofstream<charT, traits>::open(p.wstring().c_str(), mode); } #else explicit basic_ofstream(const path& p, std::ios_base::openmode mode = std::ios_base::out) : std::basic_ofstream<charT, traits>(p.string().c_str(), mode) { } void open(const path& p, std::ios_base::openmode mode = std::ios_base::out) { std::basic_ofstream<charT, traits>::open(p.string().c_str(), mode); } #endif basic_ofstream(const basic_ofstream&) = delete; const basic_ofstream& operator=(const basic_ofstream&) = delete; ~basic_ofstream() override {} }; template <class charT, class traits = std::char_traits<charT>> class basic_fstream : public std::basic_fstream<charT, traits> { public: basic_fstream() {} #if defined(GHC_OS_WINDOWS) && !defined(__GLIBCXX__) explicit basic_fstream(const path& p, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out) : std::basic_fstream<charT, traits>(p.wstring().c_str(), mode) { } void open(const path& p, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out) { std::basic_fstream<charT, traits>::open(p.wstring().c_str(), mode); } #else explicit basic_fstream(const path& p, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out) : std::basic_fstream<charT, traits>(p.string().c_str(), mode) { } void open(const path& p, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out) { std::basic_fstream<charT, traits>::open(p.string().c_str(), mode); } #endif basic_fstream(const basic_fstream&) = delete; const basic_fstream& operator=(const basic_fstream&) = delete; ~basic_fstream() override {} }; typedef basic_filebuf<char> filebuf; typedef basic_filebuf<wchar_t> wfilebuf; typedef basic_ifstream<char> ifstream; typedef basic_ifstream<wchar_t> wifstream; typedef basic_ofstream<char> ofstream; typedef basic_ofstream<wchar_t> wofstream; typedef basic_fstream<char> fstream; typedef basic_fstream<wchar_t> wfstream; class GHC_FS_API_CLASS u8arguments { public: u8arguments(int& argc, char**& argv); ~u8arguments() { _refargc = _argc; _refargv = _argv; } bool valid() const { return _isvalid; } private: int _argc; char** _argv; int& _refargc; char**& _refargv; bool _isvalid; #ifdef GHC_OS_WINDOWS std::vector<std::string> _args; std::vector<char*> _argp; #endif }; //------------------------------------------------------------------------------------------------- // Implementation //------------------------------------------------------------------------------------------------- namespace detail { // GHC_FS_API void postprocess_path_with_format(path::impl_string_type& p, path::format fmt); enum utf8_states_t { S_STRT = 0, S_RJCT = 8 }; GHC_FS_API void appendUTF8(std::string& str, uint32_t unicode); GHC_FS_API bool is_surrogate(uint32_t c); GHC_FS_API bool is_high_surrogate(uint32_t c); GHC_FS_API bool is_low_surrogate(uint32_t c); GHC_FS_API unsigned consumeUtf8Fragment(const unsigned state, const uint8_t fragment, uint32_t& codepoint); enum class portable_error { none = 0, exists, not_found, not_supported, not_implemented, invalid_argument, is_a_directory, }; GHC_FS_API std::error_code make_error_code(portable_error err); #ifdef GHC_OS_WINDOWS GHC_FS_API std::error_code make_system_error(uint32_t err = 0); #else GHC_FS_API std::error_code make_system_error(int err = 0); #endif } // namespace detail namespace detail { #ifdef GHC_EXPAND_IMPL GHC_INLINE std::error_code make_error_code(portable_error err) { #ifdef GHC_OS_WINDOWS switch (err) { case portable_error::none: return std::error_code(); case portable_error::exists: return std::error_code(ERROR_ALREADY_EXISTS, std::system_category()); case portable_error::not_found: return std::error_code(ERROR_PATH_NOT_FOUND, std::system_category()); case portable_error::not_supported: return std::error_code(ERROR_NOT_SUPPORTED, std::system_category()); case portable_error::not_implemented: return std::error_code(ERROR_CALL_NOT_IMPLEMENTED, std::system_category()); case portable_error::invalid_argument: return std::error_code(ERROR_INVALID_PARAMETER, std::system_category()); case portable_error::is_a_directory: #ifdef ERROR_DIRECTORY_NOT_SUPPORTED return std::error_code(ERROR_DIRECTORY_NOT_SUPPORTED, std::system_category()); #else return std::error_code(ERROR_NOT_SUPPORTED, std::system_category()); #endif } #else switch (err) { case portable_error::none: return std::error_code(); case portable_error::exists: return std::error_code(EEXIST, std::system_category()); case portable_error::not_found: return std::error_code(ENOENT, std::system_category()); case portable_error::not_supported: return std::error_code(ENOTSUP, std::system_category()); case portable_error::not_implemented: return std::error_code(ENOSYS, std::system_category()); case portable_error::invalid_argument: return std::error_code(EINVAL, std::system_category()); case portable_error::is_a_directory: return std::error_code(EISDIR, std::system_category()); } #endif return std::error_code(); } #ifdef GHC_OS_WINDOWS GHC_INLINE std::error_code make_system_error(uint32_t err) { return std::error_code(err ? static_cast<int>(err) : static_cast<int>(::GetLastError()), std::system_category()); } #else GHC_INLINE std::error_code make_system_error(int err) { return std::error_code(err ? err : errno, std::system_category()); } #endif #endif // GHC_EXPAND_IMPL template <typename Enum> using EnableBitmask = typename std::enable_if<std::is_same<Enum, perms>::value || std::is_same<Enum, perm_options>::value || std::is_same<Enum, copy_options>::value || std::is_same<Enum, directory_options>::value, Enum>::type; } // namespace detail template <typename Enum> detail::EnableBitmask<Enum> operator&(Enum X, Enum Y) { using underlying = typename std::underlying_type<Enum>::type; return static_cast<Enum>(static_cast<underlying>(X) & static_cast<underlying>(Y)); } template <typename Enum> detail::EnableBitmask<Enum> operator|(Enum X, Enum Y) { using underlying = typename std::underlying_type<Enum>::type; return static_cast<Enum>(static_cast<underlying>(X) | static_cast<underlying>(Y)); } template <typename Enum> detail::EnableBitmask<Enum> operator^(Enum X, Enum Y) { using underlying = typename std::underlying_type<Enum>::type; return static_cast<Enum>(static_cast<underlying>(X) ^ static_cast<underlying>(Y)); } template <typename Enum> detail::EnableBitmask<Enum> operator~(Enum X) { using underlying = typename std::underlying_type<Enum>::type; return static_cast<Enum>(~static_cast<underlying>(X)); } template <typename Enum> detail::EnableBitmask<Enum>& operator&=(Enum& X, Enum Y) { X = X & Y; return X; } template <typename Enum> detail::EnableBitmask<Enum>& operator|=(Enum& X, Enum Y) { X = X | Y; return X; } template <typename Enum> detail::EnableBitmask<Enum>& operator^=(Enum& X, Enum Y) { X = X ^ Y; return X; } #ifdef GHC_EXPAND_IMPL namespace detail { GHC_INLINE bool in_range(uint32_t c, uint32_t lo, uint32_t hi) { return (static_cast<uint32_t>(c - lo) < (hi - lo + 1)); } GHC_INLINE bool is_surrogate(uint32_t c) { return in_range(c, 0xd800, 0xdfff); } GHC_INLINE bool is_high_surrogate(uint32_t c) { return (c & 0xfffffc00) == 0xd800; } GHC_INLINE bool is_low_surrogate(uint32_t c) { return (c & 0xfffffc00) == 0xdc00; } GHC_INLINE void appendUTF8(std::string& str, uint32_t unicode) { if (unicode <= 0x7f) { str.push_back(static_cast<char>(unicode)); } else if (unicode >= 0x80 && unicode <= 0x7ff) { str.push_back(static_cast<char>((unicode >> 6) + 192)); str.push_back(static_cast<char>((unicode & 0x3f) + 128)); } else if ((unicode >= 0x800 && unicode <= 0xd7ff) || (unicode >= 0xe000 && unicode <= 0xffff)) { str.push_back(static_cast<char>((unicode >> 12) + 224)); str.push_back(static_cast<char>(((unicode & 0xfff) >> 6) + 128)); str.push_back(static_cast<char>((unicode & 0x3f) + 128)); } else if (unicode >= 0x10000 && unicode <= 0x10ffff) { str.push_back(static_cast<char>((unicode >> 18) + 240)); str.push_back(static_cast<char>(((unicode & 0x3ffff) >> 12) + 128)); str.push_back(static_cast<char>(((unicode & 0xfff) >> 6) + 128)); str.push_back(static_cast<char>((unicode & 0x3f) + 128)); } else { #ifdef GHC_RAISE_UNICODE_ERRORS throw filesystem_error("Illegal code point for unicode character.", str, std::make_error_code(std::errc::illegal_byte_sequence)); #else appendUTF8(str, 0xfffd); #endif } } // Thanks to Bjoern Hoehrmann (https://bjoern.hoehrmann.de/utf-8/decoder/dfa/) // and Taylor R Campbell for the ideas to this DFA approach of UTF-8 decoding; // Generating debugging and shrinking my own DFA from scratch was a day of fun! GHC_INLINE unsigned consumeUtf8Fragment(const unsigned state, const uint8_t fragment, uint32_t& codepoint) { static const uint32_t utf8_state_info[] = { // encoded states 0x11111111u, 0x11111111u, 0x77777777u, 0x77777777u, 0x88888888u, 0x88888888u, 0x88888888u, 0x88888888u, 0x22222299u, 0x22222222u, 0x22222222u, 0x22222222u, 0x3333333au, 0x33433333u, 0x9995666bu, 0x99999999u, 0x88888880u, 0x22818108u, 0x88888881u, 0x88888882u, 0x88888884u, 0x88888887u, 0x88888886u, 0x82218108u, 0x82281108u, 0x88888888u, 0x88888883u, 0x88888885u, 0u, 0u, 0u, 0u, }; uint8_t category = fragment < 128 ? 0 : (utf8_state_info[(fragment >> 3) & 0xf] >> ((fragment & 7) << 2)) & 0xf; codepoint = (state ? (codepoint << 6) | (fragment & 0x3fu) : (0xffu >> category) & fragment); return state == S_RJCT ? static_cast<unsigned>(S_RJCT) : static_cast<unsigned>((utf8_state_info[category + 16] >> (state << 2)) & 0xf); } GHC_INLINE bool validUtf8(const std::string& utf8String) { std::string::const_iterator iter = utf8String.begin(); unsigned utf8_state = S_STRT; std::uint32_t codepoint = 0; while (iter < utf8String.end()) { if ((utf8_state = consumeUtf8Fragment(utf8_state, static_cast<uint8_t>(*iter++), codepoint)) == S_RJCT) { return false; } } if (utf8_state) { return false; } return true; } } // namespace detail #endif namespace detail { template <class StringType, typename std::enable_if<(sizeof(typename StringType::value_type) == 1)>::type* = nullptr> inline StringType fromUtf8(const std::string& utf8String, const typename StringType::allocator_type& alloc = typename StringType::allocator_type()) { return StringType(utf8String.begin(), utf8String.end(), alloc); } template <class StringType, typename std::enable_if<(sizeof(typename StringType::value_type) == 2)>::type* = nullptr> inline StringType fromUtf8(const std::string& utf8String, const typename StringType::allocator_type& alloc = typename StringType::allocator_type()) { StringType result(alloc); result.reserve(utf8String.length()); std::string::const_iterator iter = utf8String.begin(); unsigned utf8_state = S_STRT; std::uint32_t codepoint = 0; while (iter < utf8String.end()) { if ((utf8_state = consumeUtf8Fragment(utf8_state, static_cast<uint8_t>(*iter++), codepoint)) == S_STRT) { if (codepoint <= 0xffff) { result += static_cast<typename StringType::value_type>(codepoint); } else { codepoint -= 0x10000; result += static_cast<typename StringType::value_type>((codepoint >> 10) + 0xd800); result += static_cast<typename StringType::value_type>((codepoint & 0x3ff) + 0xdc00); } codepoint = 0; } else if (utf8_state == S_RJCT) { #ifdef GHC_RAISE_UNICODE_ERRORS throw filesystem_error("Illegal byte sequence for unicode character.", utf8String, std::make_error_code(std::errc::illegal_byte_sequence)); #else result += static_cast<typename StringType::value_type>(0xfffd); utf8_state = S_STRT; codepoint = 0; #endif } } if (utf8_state) { #ifdef GHC_RAISE_UNICODE_ERRORS throw filesystem_error("Illegal byte sequence for unicode character.", utf8String, std::make_error_code(std::errc::illegal_byte_sequence)); #else result += static_cast<typename StringType::value_type>(0xfffd); #endif } return result; } template <class StringType, typename std::enable_if<(sizeof(typename StringType::value_type) == 4)>::type* = nullptr> inline StringType fromUtf8(const std::string& utf8String, const typename StringType::allocator_type& alloc = typename StringType::allocator_type()) { StringType result(alloc); result.reserve(utf8String.length()); std::string::const_iterator iter = utf8String.begin(); unsigned utf8_state = S_STRT; std::uint32_t codepoint = 0; while (iter < utf8String.end()) { if ((utf8_state = consumeUtf8Fragment(utf8_state, static_cast<uint8_t>(*iter++), codepoint)) == S_STRT) { result += static_cast<typename StringType::value_type>(codepoint); codepoint = 0; } else if (utf8_state == S_RJCT) { #ifdef GHC_RAISE_UNICODE_ERRORS throw filesystem_error("Illegal byte sequence for unicode character.", utf8String, std::make_error_code(std::errc::illegal_byte_sequence)); #else result += static_cast<typename StringType::value_type>(0xfffd); utf8_state = S_STRT; codepoint = 0; #endif } } if (utf8_state) { #ifdef GHC_RAISE_UNICODE_ERRORS throw filesystem_error("Illegal byte sequence for unicode character.", utf8String, std::make_error_code(std::errc::illegal_byte_sequence)); #else result += static_cast<typename StringType::value_type>(0xfffd); #endif } return result; } template <typename charT, typename traits, typename Alloc, typename std::enable_if<(sizeof(charT) == 1), int>::type size = 1> inline std::string toUtf8(const std::basic_string<charT, traits, Alloc>& unicodeString) { return std::string(unicodeString.begin(), unicodeString.end()); } template <typename charT, typename traits, typename Alloc, typename std::enable_if<(sizeof(charT) == 2), int>::type size = 2> inline std::string toUtf8(const std::basic_string<charT, traits, Alloc>& unicodeString) { std::string result; for (auto iter = unicodeString.begin(); iter != unicodeString.end(); ++iter) { char32_t c = *iter; if (is_surrogate(c)) { ++iter; if (iter != unicodeString.end() && is_high_surrogate(c) && is_low_surrogate(*iter)) { appendUTF8(result, (char32_t(c) << 10) + *iter - 0x35fdc00); } else { #ifdef GHC_RAISE_UNICODE_ERRORS throw filesystem_error("Illegal code point for unicode character.", result, std::make_error_code(std::errc::illegal_byte_sequence)); #else appendUTF8(result, 0xfffd); if(iter == unicodeString.end()) { break; } #endif } } else { appendUTF8(result, c); } } return result; } template <typename charT, typename traits, typename Alloc, typename std::enable_if<(sizeof(charT) == 4), int>::type size = 4> inline std::string toUtf8(const std::basic_string<charT, traits, Alloc>& unicodeString) { std::string result; for (auto c : unicodeString) { appendUTF8(result, static_cast<uint32_t>(c)); } return result; } template <typename charT> inline std::string toUtf8(const charT* unicodeString) { return toUtf8(std::basic_string<charT, std::char_traits<charT>>(unicodeString)); } } // namespace detail #ifdef GHC_EXPAND_IMPL namespace detail { GHC_INLINE bool startsWith(const std::string& what, const std::string& with) { return with.length() <= what.length() && equal(with.begin(), with.end(), what.begin()); } } // namespace detail GHC_INLINE void path::postprocess_path_with_format(path::impl_string_type& p, path::format fmt) { #ifdef GHC_RAISE_UNICODE_ERRORS if(!detail::validUtf8(p)) { path t; t._path = p; throw filesystem_error("Illegal byte sequence for unicode character.", t, std::make_error_code(std::errc::illegal_byte_sequence)); } #endif switch (fmt) { #ifndef GHC_OS_WINDOWS case path::auto_format: case path::native_format: #endif case path::generic_format: // nothing to do break; #ifdef GHC_OS_WINDOWS case path::auto_format: case path::native_format: if (detail::startsWith(p, std::string("\\\\?\\"))) { // remove Windows long filename marker p.erase(0, 4); if (detail::startsWith(p, std::string("UNC\\"))) { p.erase(0, 2); p[0] = '\\'; } } for (auto& c : p) { if (c == '\\') { c = '/'; } } break; #endif } if (p.length() > 2 && p[0] == '/' && p[1] == '/' && p[2] != '/') { std::string::iterator new_end = std::unique(p.begin() + 2, p.end(), [](path::value_type lhs, path::value_type rhs) { return lhs == rhs && lhs == '/'; }); p.erase(new_end, p.end()); } else { std::string::iterator new_end = std::unique(p.begin(), p.end(), [](path::value_type lhs, path::value_type rhs) { return lhs == rhs && lhs == '/'; }); p.erase(new_end, p.end()); } } #endif // GHC_EXPAND_IMPL template <class Source, typename> inline path::path(const Source& source, format fmt) : _path(detail::toUtf8(source)) { postprocess_path_with_format(_path, fmt); } template <> inline path::path(const std::wstring& source, format fmt) { _path = detail::toUtf8(source); postprocess_path_with_format(_path, fmt); } template <> inline path::path(const std::u16string& source, format fmt) { _path = detail::toUtf8(source); postprocess_path_with_format(_path, fmt); } template <> inline path::path(const std::u32string& source, format fmt) { _path = detail::toUtf8(source); postprocess_path_with_format(_path, fmt); } #ifdef __cpp_lib_string_view template <> inline path::path(const std::string_view& source, format fmt) { _path = detail::toUtf8(std::string(source)); postprocess_path_with_format(_path, fmt); } #ifdef GHC_USE_WCHAR_T template <> inline path::path(const std::wstring_view& source, format fmt) { _path = detail::toUtf8(std::wstring(source).c_str()); postprocess_path_with_format(_path, fmt); } #endif #endif template <class Source, typename> inline path u8path(const Source& source) { return path(source); } template <class InputIterator> inline path u8path(InputIterator first, InputIterator last) { return path(first, last); } template <class InputIterator> inline path::path(InputIterator first, InputIterator last, format fmt) : path(std::basic_string<typename std::iterator_traits<InputIterator>::value_type>(first, last), fmt) { // delegated } #ifdef GHC_EXPAND_IMPL namespace detail { GHC_INLINE bool equals_simple_insensitive(const char* str1, const char* str2) { #ifdef GHC_OS_WINDOWS #ifdef __GNUC__ while (::tolower((unsigned char)*str1) == ::tolower((unsigned char)*str2++)) { if (*str1++ == 0) return true; } return false; #else return 0 == ::_stricmp(str1, str2); #endif #else return 0 == ::strcasecmp(str1, str2); #endif } GHC_INLINE const char* strerror_adapter(char* gnu, char*) { return gnu; } GHC_INLINE const char* strerror_adapter(int posix, char* buffer) { if(posix) { return "Error in strerror_r!"; } return buffer; } template <typename ErrorNumber> GHC_INLINE std::string systemErrorText(ErrorNumber code = 0) { #if defined(GHC_OS_WINDOWS) LPVOID msgBuf; DWORD dw = code ? static_cast<DWORD>(code) : ::GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&msgBuf, 0, NULL); std::string msg = toUtf8(std::wstring((LPWSTR)msgBuf)); LocalFree(msgBuf); return msg; #else char buffer[512]; return strerror_adapter(strerror_r(code ? code : errno, buffer, sizeof(buffer)), buffer); #endif } #ifdef GHC_OS_WINDOWS using CreateSymbolicLinkW_fp = BOOLEAN(WINAPI*)(LPCWSTR, LPCWSTR, DWORD); using CreateHardLinkW_fp = BOOLEAN(WINAPI*)(LPCWSTR, LPCWSTR, LPSECURITY_ATTRIBUTES); GHC_INLINE void create_symlink(const path& target_name, const path& new_symlink, bool to_directory, std::error_code& ec) { std::error_code tec; auto fs = status(target_name, tec); if ((fs.type() == file_type::directory && !to_directory) || (fs.type() == file_type::regular && to_directory)) { ec = detail::make_error_code(detail::portable_error::not_supported); return; } #if defined(__GNUC__) && __GNUC__ >= 8 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-function-type" #endif static CreateSymbolicLinkW_fp api_call = reinterpret_cast<CreateSymbolicLinkW_fp>(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "CreateSymbolicLinkW")); #if defined(__GNUC__) && __GNUC__ >= 8 #pragma GCC diagnostic pop #endif if (api_call) { if (api_call(detail::fromUtf8<std::wstring>(new_symlink.u8string()).c_str(), detail::fromUtf8<std::wstring>(target_name.u8string()).c_str(), to_directory ? 1 : 0) == 0) { auto result = ::GetLastError(); if (result == ERROR_PRIVILEGE_NOT_HELD && api_call(detail::fromUtf8<std::wstring>(new_symlink.u8string()).c_str(), detail::fromUtf8<std::wstring>(target_name.u8string()).c_str(), to_directory ? 3 : 2) != 0) { return; } ec = detail::make_system_error(result); } } else { ec = detail::make_system_error(ERROR_NOT_SUPPORTED); } } GHC_INLINE void create_hardlink(const path& target_name, const path& new_hardlink, std::error_code& ec) { #if defined(__GNUC__) && __GNUC__ >= 8 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-function-type" #endif static CreateHardLinkW_fp api_call = reinterpret_cast<CreateHardLinkW_fp>(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "CreateHardLinkW")); #if defined(__GNUC__) && __GNUC__ >= 8 #pragma GCC diagnostic pop #endif if (api_call) { if (api_call(detail::fromUtf8<std::wstring>(new_hardlink.u8string()).c_str(), detail::fromUtf8<std::wstring>(target_name.u8string()).c_str(), NULL) == 0) { ec = detail::make_system_error(); } } else { ec = detail::make_system_error(ERROR_NOT_SUPPORTED); } } #else GHC_INLINE void create_symlink(const path& target_name, const path& new_symlink, bool, std::error_code& ec) { if (::symlink(target_name.c_str(), new_symlink.c_str()) != 0) { ec = detail::make_system_error(); } } #ifndef GHC_OS_WEB GHC_INLINE void create_hardlink(const path& target_name, const path& new_hardlink, std::error_code& ec) { if (::link(target_name.c_str(), new_hardlink.c_str()) != 0) { ec = detail::make_system_error(); } } #endif #endif template <typename T> GHC_INLINE file_status file_status_from_st_mode(T mode) { #ifdef GHC_OS_WINDOWS file_type ft = file_type::unknown; if ((mode & _S_IFDIR) == _S_IFDIR) { ft = file_type::directory; } else if ((mode & _S_IFREG) == _S_IFREG) { ft = file_type::regular; } else if ((mode & _S_IFCHR) == _S_IFCHR) { ft = file_type::character; } perms prms = static_cast<perms>(mode & 0xfff); return file_status(ft, prms); #else file_type ft = file_type::unknown; if (S_ISDIR(mode)) { ft = file_type::directory; } else if (S_ISREG(mode)) { ft = file_type::regular; } else if (S_ISCHR(mode)) { ft = file_type::character; } else if (S_ISBLK(mode)) { ft = file_type::block; } else if (S_ISFIFO(mode)) { ft = file_type::fifo; } else if (S_ISLNK(mode)) { ft = file_type::symlink; } else if (S_ISSOCK(mode)) { ft = file_type::socket; } perms prms = static_cast<perms>(mode & 0xfff); return file_status(ft, prms); #endif } GHC_INLINE path resolveSymlink(const path& p, std::error_code& ec) { #ifdef GHC_OS_WINDOWS #ifndef REPARSE_DATA_BUFFER_HEADER_SIZE typedef struct _REPARSE_DATA_BUFFER { ULONG ReparseTag; USHORT ReparseDataLength; USHORT Reserved; union { struct { USHORT SubstituteNameOffset; USHORT SubstituteNameLength; USHORT PrintNameOffset; USHORT PrintNameLength; ULONG Flags; WCHAR PathBuffer[1]; } SymbolicLinkReparseBuffer; struct { USHORT SubstituteNameOffset; USHORT SubstituteNameLength; USHORT PrintNameOffset; USHORT PrintNameLength; WCHAR PathBuffer[1]; } MountPointReparseBuffer; struct { UCHAR DataBuffer[1]; } GenericReparseBuffer; } DUMMYUNIONNAME; } REPARSE_DATA_BUFFER; #ifndef MAXIMUM_REPARSE_DATA_BUFFER_SIZE #define MAXIMUM_REPARSE_DATA_BUFFER_SIZE (16 * 1024) #endif #endif std::shared_ptr<void> file(CreateFileW(p.wstring().c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, 0), CloseHandle); if (file.get() == INVALID_HANDLE_VALUE) { ec = detail::make_system_error(); return path(); } std::shared_ptr<REPARSE_DATA_BUFFER> reparseData((REPARSE_DATA_BUFFER*)std::calloc(1, MAXIMUM_REPARSE_DATA_BUFFER_SIZE), std::free); ULONG bufferUsed; path result; if (DeviceIoControl(file.get(), FSCTL_GET_REPARSE_POINT, 0, 0, reparseData.get(), MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &bufferUsed, 0)) { if (IsReparseTagMicrosoft(reparseData->ReparseTag)) { switch (reparseData->ReparseTag) { case IO_REPARSE_TAG_SYMLINK: result = std::wstring(&reparseData->SymbolicLinkReparseBuffer.PathBuffer[reparseData->SymbolicLinkReparseBuffer.PrintNameOffset / sizeof(WCHAR)], reparseData->SymbolicLinkReparseBuffer.PrintNameLength / sizeof(WCHAR)); break; case IO_REPARSE_TAG_MOUNT_POINT: result = std::wstring(&reparseData->MountPointReparseBuffer.PathBuffer[reparseData->MountPointReparseBuffer.PrintNameOffset / sizeof(WCHAR)], reparseData->MountPointReparseBuffer.PrintNameLength / sizeof(WCHAR)); break; default: break; } } } else { ec = detail::make_system_error(); } return result; #else size_t bufferSize = 256; while (true) { std::vector<char> buffer(bufferSize, static_cast<char>(0)); auto rc = ::readlink(p.c_str(), buffer.data(), buffer.size()); if (rc < 0) { ec = detail::make_system_error(); return path(); } else if (rc < static_cast<int>(bufferSize)) { return path(std::string(buffer.data(), static_cast<std::string::size_type>(rc))); } bufferSize *= 2; } return path(); #endif } #ifdef GHC_OS_WINDOWS GHC_INLINE time_t timeFromFILETIME(const FILETIME& ft) { ULARGE_INTEGER ull; ull.LowPart = ft.dwLowDateTime; ull.HighPart = ft.dwHighDateTime; return static_cast<time_t>(ull.QuadPart / 10000000ULL - 11644473600ULL); } GHC_INLINE void timeToFILETIME(time_t t, FILETIME& ft) { LONGLONG ll; ll = Int32x32To64(t, 10000000) + 116444736000000000; ft.dwLowDateTime = static_cast<DWORD>(ll); ft.dwHighDateTime = static_cast<DWORD>(ll >> 32); } template <typename INFO> GHC_INLINE uintmax_t hard_links_from_INFO(const INFO* info) { return static_cast<uintmax_t>(-1); } template <> GHC_INLINE uintmax_t hard_links_from_INFO<BY_HANDLE_FILE_INFORMATION>(const BY_HANDLE_FILE_INFORMATION* info) { return info->nNumberOfLinks; } template <typename INFO> GHC_INLINE file_status status_from_INFO(const path& p, const INFO* info, std::error_code&, uintmax_t* sz = nullptr, time_t* lwt = nullptr) noexcept { file_type ft = file_type::unknown; if ((info->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) { ft = file_type::symlink; } else { if ((info->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { ft = file_type::directory; } else { ft = file_type::regular; } } perms prms = perms::owner_read | perms::group_read | perms::others_read; if (!(info->dwFileAttributes & FILE_ATTRIBUTE_READONLY)) { prms = prms | perms::owner_write | perms::group_write | perms::others_write; } std::string ext = p.extension().generic_string(); if (equals_simple_insensitive(ext.c_str(), ".exe") || equals_simple_insensitive(ext.c_str(), ".cmd") || equals_simple_insensitive(ext.c_str(), ".bat") || equals_simple_insensitive(ext.c_str(), ".com")) { prms = prms | perms::owner_exec | perms::group_exec | perms::others_exec; } if (sz) { *sz = static_cast<uintmax_t>(info->nFileSizeHigh) << (sizeof(info->nFileSizeHigh) * 8) | info->nFileSizeLow; } if (lwt) { *lwt = detail::timeFromFILETIME(info->ftLastWriteTime); } return file_status(ft, prms); } #endif GHC_INLINE bool is_not_found_error(std::error_code& ec) { #ifdef GHC_OS_WINDOWS return ec.value() == ERROR_FILE_NOT_FOUND || ec.value() == ERROR_PATH_NOT_FOUND || ec.value() == ERROR_INVALID_NAME; #else return ec.value() == ENOENT || ec.value() == ENOTDIR; #endif } GHC_INLINE file_status symlink_status_ex(const path& p, std::error_code& ec, uintmax_t* sz = nullptr, uintmax_t* nhl = nullptr, time_t* lwt = nullptr) noexcept { #ifdef GHC_OS_WINDOWS file_status fs; WIN32_FILE_ATTRIBUTE_DATA attr; if (!GetFileAttributesExW(detail::fromUtf8<std::wstring>(p.u8string()).c_str(), GetFileExInfoStandard, &attr)) { ec = detail::make_system_error(); } else { ec.clear(); fs = detail::status_from_INFO(p, &attr, ec, sz, lwt); if (nhl) { *nhl = 0; } if (attr.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { fs.type(file_type::symlink); } } if (detail::is_not_found_error(ec)) { return file_status(file_type::not_found); } return ec ? file_status(file_type::none) : fs; #else (void)sz; (void)nhl; (void)lwt; struct ::stat fs; auto result = ::lstat(p.c_str(), &fs); if (result == 0) { ec.clear(); file_status f_s = detail::file_status_from_st_mode(fs.st_mode); return f_s; } ec = detail::make_system_error(); if (detail::is_not_found_error(ec)) { return file_status(file_type::not_found, perms::unknown); } return file_status(file_type::none); #endif } GHC_INLINE file_status status_ex(const path& p, std::error_code& ec, file_status* sls = nullptr, uintmax_t* sz = nullptr, uintmax_t* nhl = nullptr, time_t* lwt = nullptr, int recurse_count = 0) noexcept { ec.clear(); #ifdef GHC_OS_WINDOWS if (recurse_count > 16) { ec = detail::make_system_error(0x2A9 /*ERROR_STOPPED_ON_SYMLINK*/); return file_status(file_type::unknown); } WIN32_FILE_ATTRIBUTE_DATA attr; if (!::GetFileAttributesExW(p.wstring().c_str(), GetFileExInfoStandard, &attr)) { ec = detail::make_system_error(); } else if (attr.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { path target = resolveSymlink(p, ec); file_status result; if (!ec && !target.empty()) { if (sls) { *sls = status_from_INFO(p, &attr, ec); } return detail::status_ex(target, ec, nullptr, sz, nhl, lwt, recurse_count + 1); } return file_status(file_type::unknown); } if (ec) { if (detail::is_not_found_error(ec)) { return file_status(file_type::not_found); } return file_status(file_type::none); } if (nhl) { *nhl = 0; } return detail::status_from_INFO(p, &attr, ec, sz, lwt); #else (void)recurse_count; struct ::stat st; auto result = ::lstat(p.c_str(), &st); if (result == 0) { ec.clear(); file_status fs = detail::file_status_from_st_mode(st.st_mode); if (fs.type() == file_type::symlink) { result = ::stat(p.c_str(), &st); if (result == 0) { if (sls) { *sls = fs; } fs = detail::file_status_from_st_mode(st.st_mode); } } if (sz) { *sz = static_cast<uintmax_t>(st.st_size); } if (nhl) { *nhl = st.st_nlink; } if (lwt) { *lwt = st.st_mtime; } return fs; } else { ec = detail::make_system_error(); if (detail::is_not_found_error(ec)) { return file_status(file_type::not_found, perms::unknown); } return file_status(file_type::none); } #endif } } // namespace detail GHC_INLINE u8arguments::u8arguments(int& argc, char**& argv) : _argc(argc) , _argv(argv) , _refargc(argc) , _refargv(argv) , _isvalid(false) { #ifdef GHC_OS_WINDOWS LPWSTR* p; p = ::CommandLineToArgvW(::GetCommandLineW(), &argc); _args.reserve(static_cast<size_t>(argc)); _argp.reserve(static_cast<size_t>(argc)); for (size_t i = 0; i < static_cast<size_t>(argc); ++i) { _args.push_back(detail::toUtf8(std::wstring(p[i]))); _argp.push_back((char*)_args[i].data()); } argv = _argp.data(); ::LocalFree(p); _isvalid = true; #else std::setlocale(LC_ALL, ""); #if defined(__ANDROID__) && __ANDROID_API__ < 26 _isvalid = true; #else if (detail::equals_simple_insensitive(::nl_langinfo(CODESET), "UTF-8")) { _isvalid = true; } #endif #endif } //----------------------------------------------------------------------------- // 30.10.8.4.1 constructors and destructor GHC_INLINE path::path() noexcept {} GHC_INLINE path::path(const path& p) : _path(p._path) { } GHC_INLINE path::path(path&& p) noexcept : _path(std::move(p._path)) { } GHC_INLINE path::path(string_type&& source, format fmt) #ifdef GHC_USE_WCHAR_T : _path(detail::toUtf8(source)) #else : _path(std::move(source)) #endif { postprocess_path_with_format(_path, fmt); } #endif // GHC_EXPAND_IMPL #ifdef GHC_WITH_EXCEPTIONS template <class Source, typename> inline path::path(const Source& source, const std::locale& loc, format fmt) : path(source, fmt) { std::string locName = loc.name(); if (!(locName.length() >= 5 && (locName.substr(locName.length() - 5) == "UTF-8" || locName.substr(locName.length() - 5) == "utf-8"))) { throw filesystem_error("This implementation only supports UTF-8 locales!", path(_path), detail::make_error_code(detail::portable_error::not_supported)); } } template <class InputIterator> inline path::path(InputIterator first, InputIterator last, const std::locale& loc, format fmt) : path(std::basic_string<typename std::iterator_traits<InputIterator>::value_type>(first, last), fmt) { std::string locName = loc.name(); if (!(locName.length() >= 5 && (locName.substr(locName.length() - 5) == "UTF-8" || locName.substr(locName.length() - 5) == "utf-8"))) { throw filesystem_error("This implementation only supports UTF-8 locales!", path(_path), detail::make_error_code(detail::portable_error::not_supported)); } } #endif #ifdef GHC_EXPAND_IMPL GHC_INLINE path::~path() {} //----------------------------------------------------------------------------- // 30.10.8.4.2 assignments GHC_INLINE path& path::operator=(const path& p) { _path = p._path; return *this; } GHC_INLINE path& path::operator=(path&& p) noexcept { _path = std::move(p._path); return *this; } GHC_INLINE path& path::operator=(path::string_type&& source) { return assign(source); } GHC_INLINE path& path::assign(path::string_type&& source) { #ifdef GHC_USE_WCHAR_T _path = detail::toUtf8(source); #else _path = std::move(source); #endif postprocess_path_with_format(_path, native_format); return *this; } #endif // GHC_EXPAND_IMPL template <class Source> inline path& path::operator=(const Source& source) { return assign(source); } template <class Source> inline path& path::assign(const Source& source) { _path.assign(detail::toUtf8(source)); postprocess_path_with_format(_path, native_format); return *this; } template <> inline path& path::assign<path>(const path& source) { _path = source._path; return *this; } template <class InputIterator> inline path& path::assign(InputIterator first, InputIterator last) { _path.assign(first, last); postprocess_path_with_format(_path, native_format); return *this; } #ifdef GHC_EXPAND_IMPL //----------------------------------------------------------------------------- // 30.10.8.4.3 appends GHC_INLINE path& path::operator/=(const path& p) { if (p.empty()) { // was: if ((!has_root_directory() && is_absolute()) || has_filename()) if (!_path.empty() && _path[_path.length() - 1] != '/' && _path[_path.length() - 1] != ':') { _path += '/'; } return *this; } if ((p.is_absolute() && (_path != root_name() || p._path != "/")) || (p.has_root_name() && p.root_name() != root_name())) { assign(p); return *this; } if (p.has_root_directory()) { assign(root_name()); } else if ((!has_root_directory() && is_absolute()) || has_filename()) { _path += '/'; } auto iter = p.begin(); bool first = true; if (p.has_root_name()) { ++iter; } while (iter != p.end()) { if (!first && !(!_path.empty() && _path[_path.length() - 1] == '/')) { _path += '/'; } first = false; _path += (*iter++).generic_string(); } return *this; } GHC_INLINE void path::append_name(const char* name) { if (_path.empty()) { this->operator/=(path(name)); } else { if (_path.back() != path::generic_separator) { _path.push_back(path::generic_separator); } _path += name; } } #endif // GHC_EXPAND_IMPL template <class Source> inline path& path::operator/=(const Source& source) { return append(source); } template <class Source> inline path& path::append(const Source& source) { return this->operator/=(path(detail::toUtf8(source))); } template <> inline path& path::append<path>(const path& p) { return this->operator/=(p); } template <class InputIterator> inline path& path::append(InputIterator first, InputIterator last) { std::basic_string<typename std::iterator_traits<InputIterator>::value_type> part(first, last); return append(part); } #ifdef GHC_EXPAND_IMPL //----------------------------------------------------------------------------- // 30.10.8.4.4 concatenation GHC_INLINE path& path::operator+=(const path& x) { return concat(x._path); } GHC_INLINE path& path::operator+=(const string_type& x) { return concat(x); } #ifdef __cpp_lib_string_view GHC_INLINE path& path::operator+=(std::basic_string_view<value_type> x) { return concat(x); } #endif GHC_INLINE path& path::operator+=(const value_type* x) { return concat(string_type(x)); } GHC_INLINE path& path::operator+=(value_type x) { #ifdef GHC_OS_WINDOWS if (x == '\\') { x = generic_separator; } #endif if (_path.empty() || _path.back() != generic_separator) { #ifdef GHC_USE_WCHAR_T _path += detail::toUtf8(string_type(1, x)); #else _path += x; #endif } return *this; } #endif // GHC_EXPAND_IMPL template <class Source> inline path::path_from_string<Source>& path::operator+=(const Source& x) { return concat(x); } template <class EcharT> inline path::path_type_EcharT<EcharT>& path::operator+=(EcharT x) { std::basic_string<EcharT> part(1, x); concat(detail::toUtf8(part)); return *this; } template <class Source> inline path& path::concat(const Source& x) { path p(x); postprocess_path_with_format(p._path, native_format); _path += p._path; return *this; } template <class InputIterator> inline path& path::concat(InputIterator first, InputIterator last) { _path.append(first, last); postprocess_path_with_format(_path, native_format); return *this; } #ifdef GHC_EXPAND_IMPL //----------------------------------------------------------------------------- // 30.10.8.4.5 modifiers GHC_INLINE void path::clear() noexcept { _path.clear(); } GHC_INLINE path& path::make_preferred() { // as this filesystem implementation only uses generic_format // internally, this must be a no-op return *this; } GHC_INLINE path& path::remove_filename() { if (has_filename()) { _path.erase(_path.size() - filename()._path.size()); } return *this; } GHC_INLINE path& path::replace_filename(const path& replacement) { remove_filename(); return append(replacement); } GHC_INLINE path& path::replace_extension(const path& replacement) { if (has_extension()) { _path.erase(_path.size() - extension()._path.size()); } if (!replacement.empty() && replacement._path[0] != '.') { _path += '.'; } return concat(replacement); } GHC_INLINE void path::swap(path& rhs) noexcept { _path.swap(rhs._path); } //----------------------------------------------------------------------------- // 30.10.8.4.6, native format observers #ifdef GHC_OS_WINDOWS GHC_INLINE path::impl_string_type path::native_impl() const { impl_string_type result; if (is_absolute() && _path.length() > MAX_PATH - 10) { // expand long Windows filenames with marker if (has_root_name() && _path[0] == '/') { result = "\\\\?\\UNC" + _path.substr(1); } else { result = "\\\\?\\" + _path; } } else { result = _path; } /*if (has_root_name() && root_name()._path[0] == '/') { return _path; }*/ for (auto& c : result) { if (c == '/') { c = '\\'; } } return result; } #else GHC_INLINE const path::impl_string_type& path::native_impl() const { return _path; } #endif GHC_INLINE const path::string_type& path::native() const { #ifdef GHC_OS_WINDOWS #ifdef GHC_USE_WCHAR_T _native_cache = detail::fromUtf8<string_type>(native_impl()); #else _native_cache = native_impl(); #endif return _native_cache; #else return _path; #endif } GHC_INLINE const path::value_type* path::c_str() const { return native().c_str(); } GHC_INLINE path::operator path::string_type() const { return native(); } #endif // GHC_EXPAND_IMPL template <class EcharT, class traits, class Allocator> inline std::basic_string<EcharT, traits, Allocator> path::string(const Allocator& a) const { return detail::fromUtf8<std::basic_string<EcharT, traits, Allocator>>(native_impl(), a); } #ifdef GHC_EXPAND_IMPL GHC_INLINE std::string path::string() const { return native_impl(); } GHC_INLINE std::wstring path::wstring() const { #ifdef GHC_USE_WCHAR_T return native(); #else return detail::fromUtf8<std::wstring>(native()); #endif } GHC_INLINE std::string path::u8string() const { return native_impl(); } GHC_INLINE std::u16string path::u16string() const { return detail::fromUtf8<std::u16string>(native_impl()); } GHC_INLINE std::u32string path::u32string() const { return detail::fromUtf8<std::u32string>(native_impl()); } #endif // GHC_EXPAND_IMPL //----------------------------------------------------------------------------- // 30.10.8.4.7, generic format observers template <class EcharT, class traits, class Allocator> inline std::basic_string<EcharT, traits, Allocator> path::generic_string(const Allocator& a) const { return detail::fromUtf8<std::basic_string<EcharT, traits, Allocator>>(_path, a); } #ifdef GHC_EXPAND_IMPL GHC_INLINE const std::string& path::generic_string() const { return _path; } GHC_INLINE std::wstring path::generic_wstring() const { return detail::fromUtf8<std::wstring>(_path); } GHC_INLINE std::string path::generic_u8string() const { return _path; } GHC_INLINE std::u16string path::generic_u16string() const { return detail::fromUtf8<std::u16string>(_path); } GHC_INLINE std::u32string path::generic_u32string() const { return detail::fromUtf8<std::u32string>(_path); } //----------------------------------------------------------------------------- // 30.10.8.4.8, compare GHC_INLINE int path::compare(const path& p) const noexcept { return native().compare(p.native()); } GHC_INLINE int path::compare(const string_type& s) const { return native().compare(path(s).native()); } #ifdef __cpp_lib_string_view GHC_INLINE int path::compare(std::basic_string_view<value_type> s) const { return native().compare(path(s).native()); } #endif GHC_INLINE int path::compare(const value_type* s) const { return native().compare(path(s).native()); } //----------------------------------------------------------------------------- // 30.10.8.4.9, decomposition GHC_INLINE path path::root_name() const { #ifdef GHC_OS_WINDOWS if (_path.length() >= 2 && std::toupper(static_cast<unsigned char>(_path[0])) >= 'A' && std::toupper(static_cast<unsigned char>(_path[0])) <= 'Z' && _path[1] == ':') { return path(_path.substr(0, 2)); } #endif if (_path.length() > 2 && _path[0] == '/' && _path[1] == '/' && _path[2] != '/' && std::isprint(_path[2])) { impl_string_type::size_type pos = _path.find_first_of("/\\", 3); if (pos == impl_string_type::npos) { return path(_path); } else { return path(_path.substr(0, pos)); } } return path(); } GHC_INLINE path path::root_directory() const { path root = root_name(); if (_path.length() > root._path.length() && _path[root._path.length()] == '/') { return path("/"); } return path(); } GHC_INLINE path path::root_path() const { return root_name().generic_string() + root_directory().generic_string(); } GHC_INLINE path path::relative_path() const { std::string root = root_path()._path; return path(_path.substr((std::min)(root.length(), _path.length())), generic_format); } GHC_INLINE path path::parent_path() const { if (has_relative_path()) { if (empty() || begin() == --end()) { return path(); } else { path pp; for (string_type s : input_iterator_range<iterator>(begin(), --end())) { if (s == "/") { // don't use append to join a path- pp += s; } else { pp /= s; } } return pp; } } else { return *this; } } GHC_INLINE path path::filename() const { return relative_path().empty() ? path() : path(*--end()); } GHC_INLINE path path::stem() const { impl_string_type fn = filename().string(); if (fn != "." && fn != "..") { impl_string_type::size_type n = fn.rfind('.'); if (n != impl_string_type::npos && n != 0) { return path{fn.substr(0, n)}; } } return path{fn}; } GHC_INLINE path path::extension() const { impl_string_type fn = filename().string(); impl_string_type::size_type pos = fn.find_last_of('.'); if (pos == std::string::npos || pos == 0) { return ""; } return fn.substr(pos); } //----------------------------------------------------------------------------- // 30.10.8.4.10, query GHC_INLINE bool path::empty() const noexcept { return _path.empty(); } GHC_INLINE bool path::has_root_name() const { return !root_name().empty(); } GHC_INLINE bool path::has_root_directory() const { return !root_directory().empty(); } GHC_INLINE bool path::has_root_path() const { return !root_path().empty(); } GHC_INLINE bool path::has_relative_path() const { return !relative_path().empty(); } GHC_INLINE bool path::has_parent_path() const { return !parent_path().empty(); } GHC_INLINE bool path::has_filename() const { return !filename().empty(); } GHC_INLINE bool path::has_stem() const { return !stem().empty(); } GHC_INLINE bool path::has_extension() const { return !extension().empty(); } GHC_INLINE bool path::is_absolute() const { #ifdef GHC_OS_WINDOWS return has_root_name() && has_root_directory(); #else return has_root_directory(); #endif } GHC_INLINE bool path::is_relative() const { return !is_absolute(); } //----------------------------------------------------------------------------- // 30.10.8.4.11, generation GHC_INLINE path path::lexically_normal() const { path dest; bool lastDotDot = false; for (string_type s : *this) { if (s == ".") { dest /= ""; continue; } else if (s == ".." && !dest.empty()) { auto root = root_path(); if (dest == root) { continue; } else if (*(--dest.end()) != "..") { if (dest._path.back() == generic_separator) { dest._path.pop_back(); } dest.remove_filename(); continue; } } if (!(s.empty() && lastDotDot)) { dest /= s; } lastDotDot = s == ".."; } if (dest.empty()) { dest = "."; } return dest; } GHC_INLINE path path::lexically_relative(const path& base) const { if (root_name() != base.root_name() || is_absolute() != base.is_absolute() || (!has_root_directory() && base.has_root_directory())) { return path(); } const_iterator a = begin(), b = base.begin(); while (a != end() && b != base.end() && *a == *b) { ++a; ++b; } if (a == end() && b == base.end()) { return path("."); } int count = 0; for (const auto& element : input_iterator_range<const_iterator>(b, base.end())) { if (element != "." && element != "" && element != "..") { ++count; } else if (element == "..") { --count; } } if (count < 0) { return path(); } path result; for (int i = 0; i < count; ++i) { result /= ".."; } for (const auto& element : input_iterator_range<const_iterator>(a, end())) { result /= element; } return result; } GHC_INLINE path path::lexically_proximate(const path& base) const { path result = lexically_relative(base); return result.empty() ? *this : result; } //----------------------------------------------------------------------------- // 30.10.8.5, iterators GHC_INLINE path::iterator::iterator() {} GHC_INLINE path::iterator::iterator(const path::impl_string_type::const_iterator& first, const path::impl_string_type::const_iterator& last, const path::impl_string_type::const_iterator& pos) : _first(first) , _last(last) , _iter(pos) { updateCurrent(); // find the position of a potential root directory slash #ifdef GHC_OS_WINDOWS if (_last - _first >= 3 && std::toupper(static_cast<unsigned char>(*first)) >= 'A' && std::toupper(static_cast<unsigned char>(*first)) <= 'Z' && *(first + 1) == ':' && *(first + 2) == '/') { _root = _first + 2; } else #endif { if (_first != _last && *_first == '/') { if (_last - _first >= 2 && *(_first + 1) == '/' && !(_last - _first >= 3 && *(_first + 2) == '/')) { _root = increment(_first); } else { _root = _first; } } else { _root = _last; } } } GHC_INLINE path::impl_string_type::const_iterator path::iterator::increment(const path::impl_string_type::const_iterator& pos) const { path::impl_string_type::const_iterator i = pos; bool fromStart = i == _first; if (i != _last) { // we can only sit on a slash if it is a network name or a root if (*i++ == '/') { if (i != _last && *i == '/') { if (fromStart && !(i + 1 != _last && *(i + 1) == '/')) { // leadind double slashes detected, treat this and the // following until a slash as one unit i = std::find(++i, _last, '/'); } else { // skip redundant slashes while (i != _last && *i == '/') { ++i; } } } } else { if (fromStart && i != _last && *i == ':') { ++i; } else { i = std::find(i, _last, '/'); } } } return i; } GHC_INLINE path::impl_string_type::const_iterator path::iterator::decrement(const path::impl_string_type::const_iterator& pos) const { path::impl_string_type::const_iterator i = pos; if (i != _first) { --i; // if this is now the root slash or the trailing slash, we are done, // else check for network name if (i != _root && (pos != _last || *i != '/')) { #ifdef GHC_OS_WINDOWS static const std::string seps = "/:"; i = std::find_first_of(std::reverse_iterator<path::impl_string_type::const_iterator>(i), std::reverse_iterator<path::impl_string_type::const_iterator>(_first), seps.begin(), seps.end()).base(); if (i > _first && *i == ':') { i++; } #else i = std::find(std::reverse_iterator<path::impl_string_type::const_iterator>(i), std::reverse_iterator<path::impl_string_type::const_iterator>(_first), '/').base(); #endif // Now we have to check if this is a network name if (i - _first == 2 && *_first == '/' && *(_first + 1) == '/') { i -= 2; } } } return i; } GHC_INLINE void path::iterator::updateCurrent() { if (_iter != _first && _iter != _last && (*_iter == '/' && _iter != _root) && (_iter + 1 == _last)) { _current = ""; } else { _current.assign(_iter, increment(_iter)); if (_current.generic_string().size() > 1 && _current.generic_string()[0] == '/' && _current.generic_string()[_current.generic_string().size() - 1] == '/') { // shrink successive slashes to one _current = "/"; } } } GHC_INLINE path::iterator& path::iterator::operator++() { _iter = increment(_iter); while (_iter != _last && // we didn't reach the end _iter != _root && // this is not a root position *_iter == '/' && // we are on a slash (_iter + 1) != _last // the slash is not the last char ) { ++_iter; } updateCurrent(); return *this; } GHC_INLINE path::iterator path::iterator::operator++(int) { path::iterator i{*this}; ++(*this); return i; } GHC_INLINE path::iterator& path::iterator::operator--() { _iter = decrement(_iter); updateCurrent(); return *this; } GHC_INLINE path::iterator path::iterator::operator--(int) { auto i = *this; --(*this); return i; } GHC_INLINE bool path::iterator::operator==(const path::iterator& other) const { return _iter == other._iter; } GHC_INLINE bool path::iterator::operator!=(const path::iterator& other) const { return _iter != other._iter; } GHC_INLINE path::iterator::reference path::iterator::operator*() const { return _current; } GHC_INLINE path::iterator::pointer path::iterator::operator->() const { return &_current; } GHC_INLINE path::iterator path::begin() const { return iterator(_path.begin(), _path.end(), _path.begin()); } GHC_INLINE path::iterator path::end() const { return iterator(_path.begin(), _path.end(), _path.end()); } //----------------------------------------------------------------------------- // 30.10.8.6, path non-member functions GHC_INLINE void swap(path& lhs, path& rhs) noexcept { swap(lhs._path, rhs._path); } GHC_INLINE size_t hash_value(const path& p) noexcept { return std::hash<std::string>()(p.generic_string()); } GHC_INLINE bool operator==(const path& lhs, const path& rhs) noexcept { return lhs.generic_string() == rhs.generic_string(); } GHC_INLINE bool operator!=(const path& lhs, const path& rhs) noexcept { return lhs.generic_string() != rhs.generic_string(); } GHC_INLINE bool operator<(const path& lhs, const path& rhs) noexcept { return lhs.generic_string() < rhs.generic_string(); } GHC_INLINE bool operator<=(const path& lhs, const path& rhs) noexcept { return lhs.generic_string() <= rhs.generic_string(); } GHC_INLINE bool operator>(const path& lhs, const path& rhs) noexcept { return lhs.generic_string() > rhs.generic_string(); } GHC_INLINE bool operator>=(const path& lhs, const path& rhs) noexcept { return lhs.generic_string() >= rhs.generic_string(); } GHC_INLINE path operator/(const path& lhs, const path& rhs) { path result(lhs); result /= rhs; return result; } #endif // GHC_EXPAND_IMPL //----------------------------------------------------------------------------- // 30.10.8.6.1 path inserter and extractor template <class charT, class traits> inline std::basic_ostream<charT, traits>& operator<<(std::basic_ostream<charT, traits>& os, const path& p) { os << "\""; auto ps = p.string<charT, traits>(); for (auto c : ps) { if (c == '"' || c == '\\') { os << '\\'; } os << c; } os << "\""; return os; } template <class charT, class traits> inline std::basic_istream<charT, traits>& operator>>(std::basic_istream<charT, traits>& is, path& p) { std::basic_string<charT, traits> tmp; charT c; is >> c; if (c == '"') { auto sf = is.flags(); is >> std::noskipws; while (is) { auto c2 = is.get(); if (is) { if (c2 == '\\') { c2 = is.get(); if (is) { tmp += static_cast<charT>(c2); } } else if (c2 == '"') { break; } else { tmp += static_cast<charT>(c2); } } } if ((sf & std::ios_base::skipws) == std::ios_base::skipws) { is >> std::skipws; } p = path(tmp); } else { is >> tmp; p = path(static_cast<charT>(c) + tmp); } return is; } #ifdef GHC_EXPAND_IMPL //----------------------------------------------------------------------------- // 30.10.9 Class filesystem_error GHC_INLINE filesystem_error::filesystem_error(const std::string& what_arg, std::error_code ec) : std::system_error(ec, what_arg) , _what_arg(what_arg) , _ec(ec) { } GHC_INLINE filesystem_error::filesystem_error(const std::string& what_arg, const path& p1, std::error_code ec) : std::system_error(ec, what_arg) , _what_arg(what_arg) , _ec(ec) , _p1(p1) { if (!_p1.empty()) { _what_arg += ": '" + _p1.u8string() + "'"; } } GHC_INLINE filesystem_error::filesystem_error(const std::string& what_arg, const path& p1, const path& p2, std::error_code ec) : std::system_error(ec, what_arg) , _what_arg(what_arg) , _ec(ec) , _p1(p1) , _p2(p2) { if (!_p1.empty()) { _what_arg += ": '" + _p1.u8string() + "'"; } if (!_p2.empty()) { _what_arg += ", '" + _p2.u8string() + "'"; } } GHC_INLINE const path& filesystem_error::path1() const noexcept { return _p1; } GHC_INLINE const path& filesystem_error::path2() const noexcept { return _p2; } GHC_INLINE const char* filesystem_error::what() const noexcept { return _what_arg.c_str(); } //----------------------------------------------------------------------------- // 30.10.15, filesystem operations #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE path absolute(const path& p) { std::error_code ec; path result = absolute(p, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } return result; } #endif GHC_INLINE path absolute(const path& p, std::error_code& ec) { ec.clear(); #ifdef GHC_OS_WINDOWS if (p.empty()) { return absolute(current_path(ec), ec) / ""; } ULONG size = ::GetFullPathNameW(p.wstring().c_str(), 0, 0, 0); if (size) { std::vector<wchar_t> buf(size, 0); ULONG s2 = GetFullPathNameW(p.wstring().c_str(), size, buf.data(), nullptr); if (s2 && s2 < size) { path result = path(std::wstring(buf.data(), s2)); if (p.filename() == ".") { result /= "."; } return result; } } ec = detail::make_system_error(); return path(); #else path base = current_path(ec); if (!ec) { if (p.empty()) { return base / p; } if (p.has_root_name()) { if (p.has_root_directory()) { return p; } else { return p.root_name() / base.root_directory() / base.relative_path() / p.relative_path(); } } else { if (p.has_root_directory()) { return base.root_name() / p; } else { return base / p; } } } ec = detail::make_system_error(); return path(); #endif } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE path canonical(const path& p) { std::error_code ec; auto result = canonical(p, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } return result; } #endif GHC_INLINE path canonical(const path& p, std::error_code& ec) { if (p.empty()) { ec = detail::make_error_code(detail::portable_error::not_found); return path(); } path work = p.is_absolute() ? p : absolute(p, ec); path root = work.root_path(); path result; auto fs = status(work, ec); if (ec) { return path(); } if (fs.type() == file_type::not_found) { ec = detail::make_error_code(detail::portable_error::not_found); return path(); } bool redo; do { redo = false; result.clear(); for (auto pe : work) { if (pe.empty() || pe == ".") { continue; } else if (pe == "..") { result = result.parent_path(); continue; } else if ((result / pe).string().length() <= root.string().length()) { result /= pe; continue; } auto sls = symlink_status(result / pe, ec); if (ec) { return path(); } if (is_symlink(sls)) { redo = true; auto target = read_symlink(result / pe, ec); if (ec) { return path(); } if (target.is_absolute()) { result = target; continue; } else { result /= target; continue; } } else { result /= pe; } } work = result; } while (redo); ec.clear(); return result; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void copy(const path& from, const path& to) { copy(from, to, copy_options::none); } #endif GHC_INLINE void copy(const path& from, const path& to, std::error_code& ec) noexcept { copy(from, to, copy_options::none, ec); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void copy(const path& from, const path& to, copy_options options) { std::error_code ec; copy(from, to, options, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), from, to, ec); } } #endif GHC_INLINE void copy(const path& from, const path& to, copy_options options, std::error_code& ec) noexcept { std::error_code tec; file_status fs_from, fs_to; ec.clear(); if ((options & (copy_options::skip_symlinks | copy_options::copy_symlinks | copy_options::create_symlinks)) != copy_options::none) { fs_from = symlink_status(from, ec); } else { fs_from = status(from, ec); } if (!exists(fs_from)) { if (!ec) { ec = detail::make_error_code(detail::portable_error::not_found); } return; } if ((options & (copy_options::skip_symlinks | copy_options::create_symlinks)) != copy_options::none) { fs_to = symlink_status(to, tec); } else { fs_to = status(to, tec); } if (is_other(fs_from) || is_other(fs_to) || (is_directory(fs_from) && is_regular_file(fs_to)) || (exists(fs_to) && equivalent(from, to, ec))) { ec = detail::make_error_code(detail::portable_error::invalid_argument); } else if (is_symlink(fs_from)) { if ((options & copy_options::skip_symlinks) == copy_options::none) { if (!exists(fs_to) && (options & copy_options::copy_symlinks) != copy_options::none) { copy_symlink(from, to, ec); } else { ec = detail::make_error_code(detail::portable_error::invalid_argument); } } } else if (is_regular_file(fs_from)) { if ((options & copy_options::directories_only) == copy_options::none) { if ((options & copy_options::create_symlinks) != copy_options::none) { create_symlink(from.is_absolute() ? from : canonical(from, ec), to, ec); } #ifndef GHC_OS_WEB else if ((options & copy_options::create_hard_links) != copy_options::none) { create_hard_link(from, to, ec); } #endif else if (is_directory(fs_to)) { copy_file(from, to / from.filename(), options, ec); } else { copy_file(from, to, options, ec); } } } #ifdef LWG_2682_BEHAVIOUR else if (is_directory(fs_from) && (options & copy_options::create_symlinks) != copy_options::none) { ec = detail::make_error_code(detail::portable_error::is_a_directory); } #endif else if (is_directory(fs_from) && (options == copy_options::none || (options & copy_options::recursive) != copy_options::none)) { if (!exists(fs_to)) { create_directory(to, from, ec); if (ec) { return; } } for (auto iter = directory_iterator(from, ec); iter != directory_iterator(); iter.increment(ec)) { if (!ec) { copy(iter->path(), to / iter->path().filename(), options | static_cast<copy_options>(0x8000), ec); } if (ec) { return; } } } return; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool copy_file(const path& from, const path& to) { return copy_file(from, to, copy_options::none); } #endif GHC_INLINE bool copy_file(const path& from, const path& to, std::error_code& ec) noexcept { return copy_file(from, to, copy_options::none, ec); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool copy_file(const path& from, const path& to, copy_options option) { std::error_code ec; auto result = copy_file(from, to, option, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), from, to, ec); } return result; } #endif GHC_INLINE bool copy_file(const path& from, const path& to, copy_options options, std::error_code& ec) noexcept { std::error_code tecf, tect; auto sf = status(from, tecf); auto st = status(to, tect); bool overwrite = false; ec.clear(); if (!is_regular_file(sf)) { ec = tecf; return false; } if (exists(st) && (!is_regular_file(st) || equivalent(from, to, ec) || (options & (copy_options::skip_existing | copy_options::overwrite_existing | copy_options::update_existing)) == copy_options::none)) { ec = tect ? tect : detail::make_error_code(detail::portable_error::exists); return false; } if (exists(st)) { if ((options & copy_options::update_existing) == copy_options::update_existing) { auto from_time = last_write_time(from, ec); if (ec) { ec = detail::make_system_error(); return false; } auto to_time = last_write_time(to, ec); if (ec) { ec = detail::make_system_error(); return false; } if (from_time <= to_time) { return false; } } overwrite = true; } #ifdef GHC_OS_WINDOWS if (!::CopyFileW(detail::fromUtf8<std::wstring>(from.u8string()).c_str(), detail::fromUtf8<std::wstring>(to.u8string()).c_str(), !overwrite)) { ec = detail::make_system_error(); return false; } return true; #else std::vector<char> buffer(16384, '\0'); int in = -1, out = -1; if ((in = ::open(from.c_str(), O_RDONLY)) < 0) { ec = detail::make_system_error(); return false; } int mode = O_CREAT | O_WRONLY | O_TRUNC; if (!overwrite) { mode |= O_EXCL; } if ((out = ::open(to.c_str(), mode, static_cast<int>(sf.permissions() & perms::all))) < 0) { ec = detail::make_system_error(); ::close(in); return false; } ssize_t br, bw; while ((br = ::read(in, buffer.data(), buffer.size())) > 0) { ssize_t offset = 0; do { if ((bw = ::write(out, buffer.data() + offset, static_cast<size_t>(br))) > 0) { br -= bw; offset += bw; } else if (bw < 0) { ec = detail::make_system_error(); ::close(in); ::close(out); return false; } } while (br); } ::close(in); ::close(out); return true; #endif } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void copy_symlink(const path& existing_symlink, const path& new_symlink) { std::error_code ec; copy_symlink(existing_symlink, new_symlink, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), existing_symlink, new_symlink, ec); } } #endif GHC_INLINE void copy_symlink(const path& existing_symlink, const path& new_symlink, std::error_code& ec) noexcept { ec.clear(); auto to = read_symlink(existing_symlink, ec); if (!ec) { if (exists(to, ec) && is_directory(to, ec)) { create_directory_symlink(to, new_symlink, ec); } else { create_symlink(to, new_symlink, ec); } } } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool create_directories(const path& p) { std::error_code ec; auto result = create_directories(p, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } return result; } #endif GHC_INLINE bool create_directories(const path& p, std::error_code& ec) noexcept { path current; ec.clear(); bool didCreate = false; for (path::string_type part : p) { current /= part; if (current != p.root_name() && current != p.root_path()) { std::error_code tec; auto fs = status(current, tec); if (tec && fs.type() != file_type::not_found) { ec = tec; return false; } if (!exists(fs)) { create_directory(current, ec); if (ec) { std::error_code tmp_ec; if (is_directory(current, tmp_ec)) { ec.clear(); } else { return false; } } didCreate = true; } #ifndef LWG_2935_BEHAVIOUR else if (!is_directory(fs)) { ec = detail::make_error_code(detail::portable_error::exists); return false; } #endif } } return didCreate; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool create_directory(const path& p) { std::error_code ec; auto result = create_directory(p, path(), ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } return result; } #endif GHC_INLINE bool create_directory(const path& p, std::error_code& ec) noexcept { return create_directory(p, path(), ec); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool create_directory(const path& p, const path& attributes) { std::error_code ec; auto result = create_directory(p, attributes, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } return result; } #endif GHC_INLINE bool create_directory(const path& p, const path& attributes, std::error_code& ec) noexcept { std::error_code tec; ec.clear(); auto fs = status(p, tec); #ifdef LWG_2935_BEHAVIOUR if (status_known(fs) && exists(fs)) { return false; } #else if (status_known(fs) && exists(fs) && is_directory(fs)) { return false; } #endif #ifdef GHC_OS_WINDOWS if (!attributes.empty()) { if (!::CreateDirectoryExW(detail::fromUtf8<std::wstring>(attributes.u8string()).c_str(), detail::fromUtf8<std::wstring>(p.u8string()).c_str(), NULL)) { ec = detail::make_system_error(); return false; } } else if (!::CreateDirectoryW(detail::fromUtf8<std::wstring>(p.u8string()).c_str(), NULL)) { ec = detail::make_system_error(); return false; } #else ::mode_t attribs = static_cast<mode_t>(perms::all); if (!attributes.empty()) { struct ::stat fileStat; if (::stat(attributes.c_str(), &fileStat) != 0) { ec = detail::make_system_error(); return false; } attribs = fileStat.st_mode; } if (::mkdir(p.c_str(), attribs) != 0) { ec = detail::make_system_error(); return false; } #endif return true; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void create_directory_symlink(const path& to, const path& new_symlink) { std::error_code ec; create_directory_symlink(to, new_symlink, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), to, new_symlink, ec); } } #endif GHC_INLINE void create_directory_symlink(const path& to, const path& new_symlink, std::error_code& ec) noexcept { detail::create_symlink(to, new_symlink, true, ec); } #ifndef GHC_OS_WEB #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void create_hard_link(const path& to, const path& new_hard_link) { std::error_code ec; create_hard_link(to, new_hard_link, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), to, new_hard_link, ec); } } #endif GHC_INLINE void create_hard_link(const path& to, const path& new_hard_link, std::error_code& ec) noexcept { detail::create_hardlink(to, new_hard_link, ec); } #endif #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void create_symlink(const path& to, const path& new_symlink) { std::error_code ec; create_symlink(to, new_symlink, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), to, new_symlink, ec); } } #endif GHC_INLINE void create_symlink(const path& to, const path& new_symlink, std::error_code& ec) noexcept { detail::create_symlink(to, new_symlink, false, ec); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE path current_path() { std::error_code ec; auto result = current_path(ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), ec); } return result; } #endif GHC_INLINE path current_path(std::error_code& ec) { ec.clear(); #ifdef GHC_OS_WINDOWS DWORD pathlen = ::GetCurrentDirectoryW(0, 0); std::unique_ptr<wchar_t[]> buffer(new wchar_t[size_t(pathlen) + 1]); if (::GetCurrentDirectoryW(pathlen, buffer.get()) == 0) { ec = detail::make_system_error(); return path(); } return path(std::wstring(buffer.get()), path::native_format); #else size_t pathlen = static_cast<size_t>(std::max(int(::pathconf(".", _PC_PATH_MAX)), int(PATH_MAX))); std::unique_ptr<char[]> buffer(new char[pathlen + 1]); if (::getcwd(buffer.get(), pathlen) == nullptr) { ec = detail::make_system_error(); return path(); } return path(buffer.get()); #endif } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void current_path(const path& p) { std::error_code ec; current_path(p, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } } #endif GHC_INLINE void current_path(const path& p, std::error_code& ec) noexcept { ec.clear(); #ifdef GHC_OS_WINDOWS if (!::SetCurrentDirectoryW(detail::fromUtf8<std::wstring>(p.u8string()).c_str())) { ec = detail::make_system_error(); } #else if (::chdir(p.string().c_str()) == -1) { ec = detail::make_system_error(); } #endif } GHC_INLINE bool exists(file_status s) noexcept { return status_known(s) && s.type() != file_type::not_found; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool exists(const path& p) { return exists(status(p)); } #endif GHC_INLINE bool exists(const path& p, std::error_code& ec) noexcept { file_status s = status(p, ec); if (status_known(s)) { ec.clear(); } return exists(s); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool equivalent(const path& p1, const path& p2) { std::error_code ec; bool result = equivalent(p1, p2, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p1, p2, ec); } return result; } #endif GHC_INLINE bool equivalent(const path& p1, const path& p2, std::error_code& ec) noexcept { ec.clear(); #ifdef GHC_OS_WINDOWS std::shared_ptr<void> file1(::CreateFileW(p1.wstring().c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0), CloseHandle); auto e1 = ::GetLastError(); std::shared_ptr<void> file2(::CreateFileW(p2.wstring().c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0), CloseHandle); if (file1.get() == INVALID_HANDLE_VALUE || file2.get() == INVALID_HANDLE_VALUE) { #ifdef LWG_2937_BEHAVIOUR ec = detail::make_system_error(e1 ? e1 : ::GetLastError()); #else if (file1 == file2) { ec = detail::make_system_error(e1 ? e1 : ::GetLastError()); } #endif return false; } BY_HANDLE_FILE_INFORMATION inf1, inf2; if (!::GetFileInformationByHandle(file1.get(), &inf1)) { ec = detail::make_system_error(); return false; } if (!::GetFileInformationByHandle(file2.get(), &inf2)) { ec = detail::make_system_error(); return false; } return inf1.ftLastWriteTime.dwLowDateTime == inf2.ftLastWriteTime.dwLowDateTime && inf1.ftLastWriteTime.dwHighDateTime == inf2.ftLastWriteTime.dwHighDateTime && inf1.nFileIndexHigh == inf2.nFileIndexHigh && inf1.nFileIndexLow == inf2.nFileIndexLow && inf1.nFileSizeHigh == inf2.nFileSizeHigh && inf1.nFileSizeLow == inf2.nFileSizeLow && inf1.dwVolumeSerialNumber == inf2.dwVolumeSerialNumber; #else struct ::stat s1, s2; auto rc1 = ::stat(p1.c_str(), &s1); auto e1 = errno; auto rc2 = ::stat(p2.c_str(), &s2); if (rc1 || rc2) { #ifdef LWG_2937_BEHAVIOUR ec = detail::make_system_error(e1 ? e1 : errno); #else if (rc1 && rc2) { ec = detail::make_system_error(e1 ? e1 : errno); } #endif return false; } return s1.st_dev == s2.st_dev && s1.st_ino == s2.st_ino && s1.st_size == s2.st_size && s1.st_mtime == s2.st_mtime; #endif } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE uintmax_t file_size(const path& p) { std::error_code ec; auto result = file_size(p, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } return result; } #endif GHC_INLINE uintmax_t file_size(const path& p, std::error_code& ec) noexcept { ec.clear(); #ifdef GHC_OS_WINDOWS WIN32_FILE_ATTRIBUTE_DATA attr; if (!GetFileAttributesExW(detail::fromUtf8<std::wstring>(p.u8string()).c_str(), GetFileExInfoStandard, &attr)) { ec = detail::make_system_error(); return static_cast<uintmax_t>(-1); } return static_cast<uintmax_t>(attr.nFileSizeHigh) << (sizeof(attr.nFileSizeHigh) * 8) | attr.nFileSizeLow; #else struct ::stat fileStat; if (::stat(p.c_str(), &fileStat) == -1) { ec = detail::make_system_error(); return static_cast<uintmax_t>(-1); } return static_cast<uintmax_t>(fileStat.st_size); #endif } #ifndef GHC_OS_WEB #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE uintmax_t hard_link_count(const path& p) { std::error_code ec; auto result = hard_link_count(p, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } return result; } #endif GHC_INLINE uintmax_t hard_link_count(const path& p, std::error_code& ec) noexcept { ec.clear(); #ifdef GHC_OS_WINDOWS uintmax_t result = static_cast<uintmax_t>(-1); std::shared_ptr<void> file(::CreateFileW(p.wstring().c_str(), 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0), CloseHandle); BY_HANDLE_FILE_INFORMATION inf; if (file.get() == INVALID_HANDLE_VALUE) { ec = detail::make_system_error(); } else { if (!::GetFileInformationByHandle(file.get(), &inf)) { ec = detail::make_system_error(); } else { result = inf.nNumberOfLinks; } } return result; #else uintmax_t result = 0; file_status fs = detail::status_ex(p, ec, nullptr, nullptr, &result, nullptr); if (fs.type() == file_type::not_found) { ec = detail::make_error_code(detail::portable_error::not_found); } return ec ? static_cast<uintmax_t>(-1) : result; #endif } #endif GHC_INLINE bool is_block_file(file_status s) noexcept { return s.type() == file_type::block; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool is_block_file(const path& p) { return is_block_file(status(p)); } #endif GHC_INLINE bool is_block_file(const path& p, std::error_code& ec) noexcept { return is_block_file(status(p, ec)); } GHC_INLINE bool is_character_file(file_status s) noexcept { return s.type() == file_type::character; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool is_character_file(const path& p) { return is_character_file(status(p)); } #endif GHC_INLINE bool is_character_file(const path& p, std::error_code& ec) noexcept { return is_character_file(status(p, ec)); } GHC_INLINE bool is_directory(file_status s) noexcept { return s.type() == file_type::directory; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool is_directory(const path& p) { return is_directory(status(p)); } #endif GHC_INLINE bool is_directory(const path& p, std::error_code& ec) noexcept { return is_directory(status(p, ec)); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool is_empty(const path& p) { if (is_directory(p)) { return directory_iterator(p) == directory_iterator(); } else { return file_size(p) == 0; } } #endif GHC_INLINE bool is_empty(const path& p, std::error_code& ec) noexcept { auto fs = status(p, ec); if (ec) { return false; } if (is_directory(fs)) { directory_iterator iter(p, ec); if (ec) { return false; } return iter == directory_iterator(); } else { auto sz = file_size(p, ec); if (ec) { return false; } return sz == 0; } } GHC_INLINE bool is_fifo(file_status s) noexcept { return s.type() == file_type::fifo; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool is_fifo(const path& p) { return is_fifo(status(p)); } #endif GHC_INLINE bool is_fifo(const path& p, std::error_code& ec) noexcept { return is_fifo(status(p, ec)); } GHC_INLINE bool is_other(file_status s) noexcept { return exists(s) && !is_regular_file(s) && !is_directory(s) && !is_symlink(s); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool is_other(const path& p) { return is_other(status(p)); } #endif GHC_INLINE bool is_other(const path& p, std::error_code& ec) noexcept { return is_other(status(p, ec)); } GHC_INLINE bool is_regular_file(file_status s) noexcept { return s.type() == file_type::regular; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool is_regular_file(const path& p) { return is_regular_file(status(p)); } #endif GHC_INLINE bool is_regular_file(const path& p, std::error_code& ec) noexcept { return is_regular_file(status(p, ec)); } GHC_INLINE bool is_socket(file_status s) noexcept { return s.type() == file_type::socket; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool is_socket(const path& p) { return is_socket(status(p)); } #endif GHC_INLINE bool is_socket(const path& p, std::error_code& ec) noexcept { return is_socket(status(p, ec)); } GHC_INLINE bool is_symlink(file_status s) noexcept { return s.type() == file_type::symlink; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool is_symlink(const path& p) { return is_symlink(symlink_status(p)); } #endif GHC_INLINE bool is_symlink(const path& p, std::error_code& ec) noexcept { return is_symlink(symlink_status(p, ec)); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE file_time_type last_write_time(const path& p) { std::error_code ec; auto result = last_write_time(p, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } return result; } #endif GHC_INLINE file_time_type last_write_time(const path& p, std::error_code& ec) noexcept { time_t result = 0; ec.clear(); file_status fs = detail::status_ex(p, ec, nullptr, nullptr, nullptr, &result); return ec ? (file_time_type::min)() : std::chrono::system_clock::from_time_t(result); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void last_write_time(const path& p, file_time_type new_time) { std::error_code ec; last_write_time(p, new_time, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } } #endif GHC_INLINE void last_write_time(const path& p, file_time_type new_time, std::error_code& ec) noexcept { ec.clear(); auto d = new_time.time_since_epoch(); #ifdef GHC_OS_WINDOWS std::shared_ptr<void> file(::CreateFileW(p.wstring().c_str(), FILE_WRITE_ATTRIBUTES, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL), ::CloseHandle); FILETIME ft; auto tt = std::chrono::duration_cast<std::chrono::microseconds>(d).count() * 10 + 116444736000000000; ft.dwLowDateTime = static_cast<DWORD>(tt); ft.dwHighDateTime = static_cast<DWORD>(tt >> 32); if (!::SetFileTime(file.get(), 0, 0, &ft)) { ec = detail::make_system_error(); } #elif defined(GHC_OS_MACOS) #ifdef __MAC_OS_X_VERSION_MIN_REQUIRED #if __MAC_OS_X_VERSION_MIN_REQUIRED < 101300 struct ::stat fs; if (::stat(p.c_str(), &fs) == 0) { struct ::timeval tv[2]; tv[0].tv_sec = fs.st_atimespec.tv_sec; tv[0].tv_usec = static_cast<int>(fs.st_atimespec.tv_nsec / 1000); tv[1].tv_sec = std::chrono::duration_cast<std::chrono::seconds>(d).count(); tv[1].tv_usec = static_cast<int>(std::chrono::duration_cast<std::chrono::microseconds>(d).count() % 1000000); if (::utimes(p.c_str(), tv) == 0) { return; } } ec = detail::make_system_error(); return; #else struct ::timespec times[2]; times[0].tv_sec = 0; times[0].tv_nsec = UTIME_OMIT; times[1].tv_sec = std::chrono::duration_cast<std::chrono::seconds>(d).count(); times[1].tv_nsec = 0; //std::chrono::duration_cast<std::chrono::nanoseconds>(d).count() % 1000000000; if (::utimensat(AT_FDCWD, p.c_str(), times, AT_SYMLINK_NOFOLLOW) != 0) { ec = detail::make_system_error(); } return; #endif #endif #else #ifndef UTIME_OMIT #define UTIME_OMIT ((1l << 30) - 2l) #endif struct ::timespec times[2]; times[0].tv_sec = 0; times[0].tv_nsec = UTIME_OMIT; times[1].tv_sec = static_cast<decltype(times[1].tv_sec)>(std::chrono::duration_cast<std::chrono::seconds>(d).count()); times[1].tv_nsec = static_cast<decltype(times[1].tv_nsec)>(std::chrono::duration_cast<std::chrono::nanoseconds>(d).count() % 1000000000); #if defined(__ANDROID_API__) && __ANDROID_API__ < 12 if (syscall(__NR_utimensat, AT_FDCWD, p.c_str(), times, AT_SYMLINK_NOFOLLOW) != 0) { #else if (::utimensat(AT_FDCWD, p.c_str(), times, AT_SYMLINK_NOFOLLOW) != 0) { #endif ec = detail::make_system_error(); } return; #endif } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void permissions(const path& p, perms prms, perm_options opts) { std::error_code ec; permissions(p, prms, opts, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } } #endif GHC_INLINE void permissions(const path& p, perms prms, std::error_code& ec) noexcept { permissions(p, prms, perm_options::replace, ec); } GHC_INLINE void permissions(const path& p, perms prms, perm_options opts, std::error_code& ec) { if (static_cast<int>(opts & (perm_options::replace | perm_options::add | perm_options::remove)) == 0) { ec = detail::make_error_code(detail::portable_error::invalid_argument); return; } auto fs = symlink_status(p, ec); if ((opts & perm_options::replace) != perm_options::replace) { if ((opts & perm_options::add) == perm_options::add) { prms = fs.permissions() | prms; } else { prms = fs.permissions() & ~prms; } } #ifdef GHC_OS_WINDOWS #ifdef __GNUC__ auto oldAttr = GetFileAttributesW(p.wstring().c_str()); if (oldAttr != INVALID_FILE_ATTRIBUTES) { DWORD newAttr = ((prms & perms::owner_write) == perms::owner_write) ? oldAttr & ~(static_cast<DWORD>(FILE_ATTRIBUTE_READONLY)) : oldAttr | FILE_ATTRIBUTE_READONLY; if (oldAttr == newAttr || SetFileAttributesW(p.wstring().c_str(), newAttr)) { return; } } ec = detail::make_system_error(); #else int mode = 0; if ((prms & perms::owner_read) == perms::owner_read) { mode |= _S_IREAD; } if ((prms & perms::owner_write) == perms::owner_write) { mode |= _S_IWRITE; } if (::_wchmod(p.wstring().c_str(), mode) != 0) { ec = detail::make_system_error(); } #endif #else if ((opts & perm_options::nofollow) != perm_options::nofollow) { if (::chmod(p.c_str(), static_cast<mode_t>(prms)) != 0) { ec = detail::make_system_error(); } } #endif } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE path proximate(const path& p, std::error_code& ec) { return proximate(p, current_path(), ec); } #endif #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE path proximate(const path& p, const path& base) { return weakly_canonical(p).lexically_proximate(weakly_canonical(base)); } #endif GHC_INLINE path proximate(const path& p, const path& base, std::error_code& ec) { return weakly_canonical(p, ec).lexically_proximate(weakly_canonical(base, ec)); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE path read_symlink(const path& p) { std::error_code ec; auto result = read_symlink(p, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } return result; } #endif GHC_INLINE path read_symlink(const path& p, std::error_code& ec) { file_status fs = symlink_status(p, ec); if (fs.type() != file_type::symlink) { ec = detail::make_error_code(detail::portable_error::invalid_argument); return path(); } auto result = detail::resolveSymlink(p, ec); return ec ? path() : result; } GHC_INLINE path relative(const path& p, std::error_code& ec) { return relative(p, current_path(ec), ec); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE path relative(const path& p, const path& base) { return weakly_canonical(p).lexically_relative(weakly_canonical(base)); } #endif GHC_INLINE path relative(const path& p, const path& base, std::error_code& ec) { return weakly_canonical(p, ec).lexically_relative(weakly_canonical(base, ec)); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool remove(const path& p) { std::error_code ec; auto result = remove(p, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } return result; } #endif GHC_INLINE bool remove(const path& p, std::error_code& ec) noexcept { ec.clear(); #ifdef GHC_OS_WINDOWS std::wstring np = detail::fromUtf8<std::wstring>(p.u8string()); DWORD attr = GetFileAttributesW(np.c_str()); if (attr == INVALID_FILE_ATTRIBUTES) { auto error = ::GetLastError(); if (error == ERROR_FILE_NOT_FOUND || error == ERROR_PATH_NOT_FOUND) { return false; } ec = detail::make_system_error(error); } if (!ec) { if (attr & FILE_ATTRIBUTE_DIRECTORY) { if (!RemoveDirectoryW(np.c_str())) { ec = detail::make_system_error(); } } else { if (!DeleteFileW(np.c_str())) { ec = detail::make_system_error(); } } } #else if (::remove(p.c_str()) == -1) { auto error = errno; if (error == ENOENT) { return false; } ec = detail::make_system_error(); } #endif return ec ? false : true; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE uintmax_t remove_all(const path& p) { std::error_code ec; auto result = remove_all(p, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } return result; } #endif GHC_INLINE uintmax_t remove_all(const path& p, std::error_code& ec) noexcept { ec.clear(); uintmax_t count = 0; if (p == "/") { ec = detail::make_error_code(detail::portable_error::not_supported); return static_cast<uintmax_t>(-1); } std::error_code tec; auto fs = status(p, tec); if (exists(fs) && is_directory(fs)) { for (auto iter = directory_iterator(p, ec); iter != directory_iterator(); iter.increment(ec)) { if (ec) { break; } bool is_symlink_result = iter->is_symlink(ec); if (ec) return static_cast<uintmax_t>(-1); bool is_directory_result = iter->is_directory(ec); if (ec) return static_cast<uintmax_t>(-1); if (!is_symlink_result && is_directory_result) { count += remove_all(iter->path(), ec); if (ec) { return static_cast<uintmax_t>(-1); } } else { remove(iter->path(), ec); if (ec) { return static_cast<uintmax_t>(-1); } ++count; } } } if (!ec) { if (remove(p, ec)) { ++count; } } if (ec) { return static_cast<uintmax_t>(-1); } return count; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void rename(const path& from, const path& to) { std::error_code ec; rename(from, to, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), from, to, ec); } } #endif GHC_INLINE void rename(const path& from, const path& to, std::error_code& ec) noexcept { ec.clear(); #ifdef GHC_OS_WINDOWS if (from != to) { if (!MoveFileExW(detail::fromUtf8<std::wstring>(from.u8string()).c_str(), detail::fromUtf8<std::wstring>(to.u8string()).c_str(), (DWORD)MOVEFILE_REPLACE_EXISTING)) { ec = detail::make_system_error(); } } #else if (from != to) { if (::rename(from.c_str(), to.c_str()) != 0) { ec = detail::make_system_error(); } } #endif } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void resize_file(const path& p, uintmax_t size) { std::error_code ec; resize_file(p, size, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } } #endif GHC_INLINE void resize_file(const path& p, uintmax_t size, std::error_code& ec) noexcept { ec.clear(); #ifdef GHC_OS_WINDOWS LARGE_INTEGER lisize; lisize.QuadPart = static_cast<LONGLONG>(size); if(lisize.QuadPart < 0) { #ifdef ERROR_FILE_TOO_LARGE ec = detail::make_system_error(ERROR_FILE_TOO_LARGE); #else ec = detail::make_system_error(223); #endif return; } std::shared_ptr<void> file(CreateFileW(detail::fromUtf8<std::wstring>(p.u8string()).c_str(), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL), CloseHandle); if (file.get() == INVALID_HANDLE_VALUE) { ec = detail::make_system_error(); } else if (SetFilePointerEx(file.get(), lisize, NULL, FILE_BEGIN) == 0 || SetEndOfFile(file.get()) == 0) { ec = detail::make_system_error(); } #else if (::truncate(p.c_str(), static_cast<off_t>(size)) != 0) { ec = detail::make_system_error(); } #endif } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE space_info space(const path& p) { std::error_code ec; auto result = space(p, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } return result; } #endif GHC_INLINE space_info space(const path& p, std::error_code& ec) noexcept { ec.clear(); #ifdef GHC_OS_WINDOWS ULARGE_INTEGER freeBytesAvailableToCaller = {{0, 0}}; ULARGE_INTEGER totalNumberOfBytes = {{0, 0}}; ULARGE_INTEGER totalNumberOfFreeBytes = {{0, 0}}; if (!GetDiskFreeSpaceExW(detail::fromUtf8<std::wstring>(p.u8string()).c_str(), &freeBytesAvailableToCaller, &totalNumberOfBytes, &totalNumberOfFreeBytes)) { ec = detail::make_system_error(); return {static_cast<uintmax_t>(-1), static_cast<uintmax_t>(-1), static_cast<uintmax_t>(-1)}; } return {static_cast<uintmax_t>(totalNumberOfBytes.QuadPart), static_cast<uintmax_t>(totalNumberOfFreeBytes.QuadPart), static_cast<uintmax_t>(freeBytesAvailableToCaller.QuadPart)}; #else struct ::statvfs sfs; if (::statvfs(p.c_str(), &sfs) != 0) { ec = detail::make_system_error(); return {static_cast<uintmax_t>(-1), static_cast<uintmax_t>(-1), static_cast<uintmax_t>(-1)}; } return {static_cast<uintmax_t>(sfs.f_blocks * sfs.f_frsize), static_cast<uintmax_t>(sfs.f_bfree * sfs.f_frsize), static_cast<uintmax_t>(sfs.f_bavail * sfs.f_frsize)}; #endif } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE file_status status(const path& p) { std::error_code ec; auto result = status(p, ec); if (result.type() == file_type::none) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } return result; } #endif GHC_INLINE file_status status(const path& p, std::error_code& ec) noexcept { return detail::status_ex(p, ec); } GHC_INLINE bool status_known(file_status s) noexcept { return s.type() != file_type::none; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE file_status symlink_status(const path& p) { std::error_code ec; auto result = symlink_status(p, ec); if (result.type() == file_type::none) { throw filesystem_error(detail::systemErrorText(ec.value()), ec); } return result; } #endif GHC_INLINE file_status symlink_status(const path& p, std::error_code& ec) noexcept { return detail::symlink_status_ex(p, ec); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE path temp_directory_path() { std::error_code ec; path result = temp_directory_path(ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), ec); } return result; } #endif GHC_INLINE path temp_directory_path(std::error_code& ec) noexcept { ec.clear(); #ifdef GHC_OS_WINDOWS wchar_t buffer[512]; auto rc = GetTempPathW(511, buffer); if (!rc || rc > 511) { ec = detail::make_system_error(); return path(); } return path(std::wstring(buffer)); #else static const char* temp_vars[] = {"TMPDIR", "TMP", "TEMP", "TEMPDIR", nullptr}; const char* temp_path = nullptr; for (auto temp_name = temp_vars; *temp_name != nullptr; ++temp_name) { temp_path = std::getenv(*temp_name); if (temp_path) { return path(temp_path); } } return path("/tmp"); #endif } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE path weakly_canonical(const path& p) { std::error_code ec; auto result = weakly_canonical(p, ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), p, ec); } return result; } #endif GHC_INLINE path weakly_canonical(const path& p, std::error_code& ec) noexcept { path result; ec.clear(); bool scan = true; for (auto pe : p) { if (scan) { std::error_code tec; if (exists(result / pe, tec)) { result /= pe; } else { if (ec) { return path(); } scan = false; if (!result.empty()) { result = canonical(result, ec) / pe; if (ec) { break; } } else { result /= pe; } } } else { result /= pe; } } if (scan) { if (!result.empty()) { result = canonical(result, ec); } } return ec ? path() : result.lexically_normal(); } //----------------------------------------------------------------------------- // 30.10.11 class file_status // 30.10.11.1 constructors and destructor GHC_INLINE file_status::file_status() noexcept : file_status(file_type::none) { } GHC_INLINE file_status::file_status(file_type ft, perms prms) noexcept : _type(ft) , _perms(prms) { } GHC_INLINE file_status::file_status(const file_status& other) noexcept : _type(other._type) , _perms(other._perms) { } GHC_INLINE file_status::file_status(file_status&& other) noexcept : _type(other._type) , _perms(other._perms) { } GHC_INLINE file_status::~file_status() {} // assignments: GHC_INLINE file_status& file_status::operator=(const file_status& rhs) noexcept { _type = rhs._type; _perms = rhs._perms; return *this; } GHC_INLINE file_status& file_status::operator=(file_status&& rhs) noexcept { _type = rhs._type; _perms = rhs._perms; return *this; } // 30.10.11.3 modifiers GHC_INLINE void file_status::type(file_type ft) noexcept { _type = ft; } GHC_INLINE void file_status::permissions(perms prms) noexcept { _perms = prms; } // 30.10.11.2 observers GHC_INLINE file_type file_status::type() const noexcept { return _type; } GHC_INLINE perms file_status::permissions() const noexcept { return _perms; } //----------------------------------------------------------------------------- // 30.10.12 class directory_entry // 30.10.12.1 constructors and destructor // directory_entry::directory_entry() noexcept = default; // directory_entry::directory_entry(const directory_entry&) = default; // directory_entry::directory_entry(directory_entry&&) noexcept = default; #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE directory_entry::directory_entry(const filesystem::path& p) : _path(p) , _file_size(0) #ifndef GHC_OS_WINDOWS , _hard_link_count(0) #endif , _last_write_time(0) { refresh(); } #endif GHC_INLINE directory_entry::directory_entry(const filesystem::path& p, std::error_code& ec) : _path(p) , _file_size(0) #ifndef GHC_OS_WINDOWS , _hard_link_count(0) #endif , _last_write_time(0) { refresh(ec); } GHC_INLINE directory_entry::~directory_entry() {} // assignments: // directory_entry& directory_entry::operator=(const directory_entry&) = default; // directory_entry& directory_entry::operator=(directory_entry&&) noexcept = default; // 30.10.12.2 directory_entry modifiers #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void directory_entry::assign(const filesystem::path& p) { _path = p; refresh(); } #endif GHC_INLINE void directory_entry::assign(const filesystem::path& p, std::error_code& ec) { _path = p; refresh(ec); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void directory_entry::replace_filename(const filesystem::path& p) { _path.replace_filename(p); refresh(); } #endif GHC_INLINE void directory_entry::replace_filename(const filesystem::path& p, std::error_code& ec) { _path.replace_filename(p); refresh(ec); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void directory_entry::refresh() { std::error_code ec; refresh(ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), _path, ec); } } #endif GHC_INLINE void directory_entry::refresh(std::error_code& ec) noexcept { #ifdef GHC_OS_WINDOWS _status = detail::status_ex(_path, ec, &_symlink_status, &_file_size, nullptr, &_last_write_time); #else _status = detail::status_ex(_path, ec, &_symlink_status, &_file_size, &_hard_link_count, &_last_write_time); #endif } // 30.10.12.3 directory_entry observers GHC_INLINE const filesystem::path& directory_entry::path() const noexcept { return _path; } GHC_INLINE directory_entry::operator const filesystem::path&() const noexcept { return _path; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool directory_entry::exists() const { return filesystem::exists(status()); } #endif GHC_INLINE bool directory_entry::exists(std::error_code& ec) const noexcept { return filesystem::exists(status(ec)); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool directory_entry::is_block_file() const { return filesystem::is_block_file(status()); } #endif GHC_INLINE bool directory_entry::is_block_file(std::error_code& ec) const noexcept { return filesystem::is_block_file(status(ec)); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool directory_entry::is_character_file() const { return filesystem::is_character_file(status()); } #endif GHC_INLINE bool directory_entry::is_character_file(std::error_code& ec) const noexcept { return filesystem::is_character_file(status(ec)); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool directory_entry::is_directory() const { return filesystem::is_directory(status()); } #endif GHC_INLINE bool directory_entry::is_directory(std::error_code& ec) const noexcept { return filesystem::is_directory(status(ec)); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool directory_entry::is_fifo() const { return filesystem::is_fifo(status()); } #endif GHC_INLINE bool directory_entry::is_fifo(std::error_code& ec) const noexcept { return filesystem::is_fifo(status(ec)); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool directory_entry::is_other() const { return filesystem::is_other(status()); } #endif GHC_INLINE bool directory_entry::is_other(std::error_code& ec) const noexcept { return filesystem::is_other(status(ec)); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool directory_entry::is_regular_file() const { return filesystem::is_regular_file(status()); } #endif GHC_INLINE bool directory_entry::is_regular_file(std::error_code& ec) const noexcept { return filesystem::is_regular_file(status(ec)); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool directory_entry::is_socket() const { return filesystem::is_socket(status()); } #endif GHC_INLINE bool directory_entry::is_socket(std::error_code& ec) const noexcept { return filesystem::is_socket(status(ec)); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE bool directory_entry::is_symlink() const { return filesystem::is_symlink(symlink_status()); } #endif GHC_INLINE bool directory_entry::is_symlink(std::error_code& ec) const noexcept { return filesystem::is_symlink(symlink_status(ec)); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE uintmax_t directory_entry::file_size() const { if (_status.type() != file_type::none) { return _file_size; } return filesystem::file_size(path()); } #endif GHC_INLINE uintmax_t directory_entry::file_size(std::error_code& ec) const noexcept { if (_status.type() != file_type::none) { ec.clear(); return _file_size; } return filesystem::file_size(path(), ec); } #ifndef GHC_OS_WEB #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE uintmax_t directory_entry::hard_link_count() const { #ifndef GHC_OS_WINDOWS if (_status.type() != file_type::none) { return _hard_link_count; } #endif return filesystem::hard_link_count(path()); } #endif GHC_INLINE uintmax_t directory_entry::hard_link_count(std::error_code& ec) const noexcept { #ifndef GHC_OS_WINDOWS if (_status.type() != file_type::none) { ec.clear(); return _hard_link_count; } #endif return filesystem::hard_link_count(path(), ec); } #endif #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE file_time_type directory_entry::last_write_time() const { if (_status.type() != file_type::none) { return std::chrono::system_clock::from_time_t(_last_write_time); } return filesystem::last_write_time(path()); } #endif GHC_INLINE file_time_type directory_entry::last_write_time(std::error_code& ec) const noexcept { if (_status.type() != file_type::none) { ec.clear(); return std::chrono::system_clock::from_time_t(_last_write_time); } return filesystem::last_write_time(path(), ec); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE file_status directory_entry::status() const { if (_status.type() != file_type::none) { return _status; } return filesystem::status(path()); } #endif GHC_INLINE file_status directory_entry::status(std::error_code& ec) const noexcept { if (_status.type() != file_type::none) { ec.clear(); return _status; } return filesystem::status(path(), ec); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE file_status directory_entry::symlink_status() const { if (_symlink_status.type() != file_type::none) { return _symlink_status; } return filesystem::symlink_status(path()); } #endif GHC_INLINE file_status directory_entry::symlink_status(std::error_code& ec) const noexcept { if (_symlink_status.type() != file_type::none) { ec.clear(); return _symlink_status; } return filesystem::symlink_status(path(), ec); } GHC_INLINE bool directory_entry::operator<(const directory_entry& rhs) const noexcept { return _path < rhs._path; } GHC_INLINE bool directory_entry::operator==(const directory_entry& rhs) const noexcept { return _path == rhs._path; } GHC_INLINE bool directory_entry::operator!=(const directory_entry& rhs) const noexcept { return _path != rhs._path; } GHC_INLINE bool directory_entry::operator<=(const directory_entry& rhs) const noexcept { return _path <= rhs._path; } GHC_INLINE bool directory_entry::operator>(const directory_entry& rhs) const noexcept { return _path > rhs._path; } GHC_INLINE bool directory_entry::operator>=(const directory_entry& rhs) const noexcept { return _path >= rhs._path; } //----------------------------------------------------------------------------- // 30.10.13 class directory_iterator #ifdef GHC_OS_WINDOWS class directory_iterator::impl { public: impl(const path& p, directory_options options) : _base(p) , _options(options) , _dirHandle(INVALID_HANDLE_VALUE) { if (!_base.empty()) { ZeroMemory(&_findData, sizeof(WIN32_FIND_DATAW)); if ((_dirHandle = FindFirstFileW(detail::fromUtf8<std::wstring>((_base / "*").u8string()).c_str(), &_findData)) != INVALID_HANDLE_VALUE) { if (std::wstring(_findData.cFileName) == L"." || std::wstring(_findData.cFileName) == L"..") { increment(_ec); } else { _current = _base / std::wstring(_findData.cFileName); copyToDirEntry(_ec); } } else { auto error = ::GetLastError(); _base = filesystem::path(); if (error != ERROR_ACCESS_DENIED || (options & directory_options::skip_permission_denied) == directory_options::none) { _ec = detail::make_system_error(); } } } } impl(const impl& other) = delete; ~impl() { if (_dirHandle != INVALID_HANDLE_VALUE) { FindClose(_dirHandle); _dirHandle = INVALID_HANDLE_VALUE; } } void increment(std::error_code& ec) { if (_dirHandle != INVALID_HANDLE_VALUE) { do { if (FindNextFileW(_dirHandle, &_findData)) { _current = _base; #ifdef GHC_RAISE_UNICODE_ERRORS try { _current.append_name(detail::toUtf8(_findData.cFileName).c_str()); } catch(filesystem_error& fe) { ec = fe.code(); return; } #else _current.append_name(detail::toUtf8(_findData.cFileName).c_str()); #endif copyToDirEntry(ec); } else { auto err = ::GetLastError(); if(err != ERROR_NO_MORE_FILES) { _ec = ec = detail::make_system_error(err); } FindClose(_dirHandle); _dirHandle = INVALID_HANDLE_VALUE; _current = filesystem::path(); break; } } while (std::wstring(_findData.cFileName) == L"." || std::wstring(_findData.cFileName) == L".."); } else { ec = _ec; } } void copyToDirEntry(std::error_code& ec) { _dir_entry._path = _current; if (_findData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) { _dir_entry._status = detail::status_ex(_current, ec, &_dir_entry._symlink_status, &_dir_entry._file_size, nullptr, &_dir_entry._last_write_time); } else { _dir_entry._status = detail::status_from_INFO(_current, &_findData, ec, &_dir_entry._file_size, &_dir_entry._last_write_time); _dir_entry._symlink_status = _dir_entry._status; } if (ec) { if (_dir_entry._status.type() != file_type::none && _dir_entry._symlink_status.type() != file_type::none) { ec.clear(); } else { _dir_entry._file_size = static_cast<uintmax_t>(-1); _dir_entry._last_write_time = 0; } } } path _base; directory_options _options; WIN32_FIND_DATAW _findData; HANDLE _dirHandle; path _current; directory_entry _dir_entry; std::error_code _ec; }; #else // POSIX implementation class directory_iterator::impl { public: impl(const path& path, directory_options options) : _base(path) , _options(options) , _dir(nullptr) , _entry(nullptr) { if (!path.empty()) { _dir = ::opendir(path.native().c_str()); } if (!path.empty()) { if (!_dir) { auto error = errno; _base = filesystem::path(); if (error != EACCES || (options & directory_options::skip_permission_denied) == directory_options::none) { _ec = detail::make_system_error(); } } else { increment(_ec); } } } impl(const impl& other) = delete; ~impl() { if (_dir) { ::closedir(_dir); } } void increment(std::error_code& ec) { if (_dir) { bool skip; do { skip = false; errno = 0; _entry = ::readdir(_dir); if (_entry) { _current = _base; _current.append_name(_entry->d_name); _dir_entry = directory_entry(_current, ec); if(ec && (ec.value() == EACCES || ec.value() == EPERM) && (_options & directory_options::skip_permission_denied) == directory_options::skip_permission_denied) { ec.clear(); skip = true; } } else { ::closedir(_dir); _dir = nullptr; _current = path(); if (errno) { ec = detail::make_system_error(); } break; } } while (skip || std::strcmp(_entry->d_name, ".") == 0 || std::strcmp(_entry->d_name, "..") == 0); } } path _base; directory_options _options; path _current; DIR* _dir; struct ::dirent* _entry; directory_entry _dir_entry; std::error_code _ec; }; #endif // 30.10.13.1 member functions GHC_INLINE directory_iterator::directory_iterator() noexcept : _impl(new impl(path(), directory_options::none)) { } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE directory_iterator::directory_iterator(const path& p) : _impl(new impl(p, directory_options::none)) { if (_impl->_ec) { throw filesystem_error(detail::systemErrorText(_impl->_ec.value()), p, _impl->_ec); } _impl->_ec.clear(); } GHC_INLINE directory_iterator::directory_iterator(const path& p, directory_options options) : _impl(new impl(p, options)) { if (_impl->_ec) { throw filesystem_error(detail::systemErrorText(_impl->_ec.value()), p, _impl->_ec); } } #endif GHC_INLINE directory_iterator::directory_iterator(const path& p, std::error_code& ec) noexcept : _impl(new impl(p, directory_options::none)) { if (_impl->_ec) { ec = _impl->_ec; } } GHC_INLINE directory_iterator::directory_iterator(const path& p, directory_options options, std::error_code& ec) noexcept : _impl(new impl(p, options)) { if (_impl->_ec) { ec = _impl->_ec; } } GHC_INLINE directory_iterator::directory_iterator(const directory_iterator& rhs) : _impl(rhs._impl) { } GHC_INLINE directory_iterator::directory_iterator(directory_iterator&& rhs) noexcept : _impl(std::move(rhs._impl)) { } GHC_INLINE directory_iterator::~directory_iterator() {} GHC_INLINE directory_iterator& directory_iterator::operator=(const directory_iterator& rhs) { _impl = rhs._impl; return *this; } GHC_INLINE directory_iterator& directory_iterator::operator=(directory_iterator&& rhs) noexcept { _impl = std::move(rhs._impl); return *this; } GHC_INLINE const directory_entry& directory_iterator::operator*() const { return _impl->_dir_entry; } GHC_INLINE const directory_entry* directory_iterator::operator->() const { return &_impl->_dir_entry; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE directory_iterator& directory_iterator::operator++() { std::error_code ec; _impl->increment(ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), _impl->_current, ec); } return *this; } #endif GHC_INLINE directory_iterator& directory_iterator::increment(std::error_code& ec) noexcept { _impl->increment(ec); return *this; } GHC_INLINE bool directory_iterator::operator==(const directory_iterator& rhs) const { return _impl->_current == rhs._impl->_current; } GHC_INLINE bool directory_iterator::operator!=(const directory_iterator& rhs) const { return _impl->_current != rhs._impl->_current; } // 30.10.13.2 directory_iterator non-member functions GHC_INLINE directory_iterator begin(directory_iterator iter) noexcept { return iter; } GHC_INLINE directory_iterator end(const directory_iterator&) noexcept { return directory_iterator(); } //----------------------------------------------------------------------------- // 30.10.14 class recursive_directory_iterator GHC_INLINE recursive_directory_iterator::recursive_directory_iterator() noexcept : _impl(new recursive_directory_iterator_impl(directory_options::none, true)) { _impl->_dir_iter_stack.push(directory_iterator()); } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE recursive_directory_iterator::recursive_directory_iterator(const path& p) : _impl(new recursive_directory_iterator_impl(directory_options::none, true)) { _impl->_dir_iter_stack.push(directory_iterator(p)); } GHC_INLINE recursive_directory_iterator::recursive_directory_iterator(const path& p, directory_options options) : _impl(new recursive_directory_iterator_impl(options, true)) { _impl->_dir_iter_stack.push(directory_iterator(p, options)); } #endif GHC_INLINE recursive_directory_iterator::recursive_directory_iterator(const path& p, directory_options options, std::error_code& ec) noexcept : _impl(new recursive_directory_iterator_impl(options, true)) { _impl->_dir_iter_stack.push(directory_iterator(p, options, ec)); } GHC_INLINE recursive_directory_iterator::recursive_directory_iterator(const path& p, std::error_code& ec) noexcept : _impl(new recursive_directory_iterator_impl(directory_options::none, true)) { _impl->_dir_iter_stack.push(directory_iterator(p, ec)); } GHC_INLINE recursive_directory_iterator::recursive_directory_iterator(const recursive_directory_iterator& rhs) : _impl(rhs._impl) { } GHC_INLINE recursive_directory_iterator::recursive_directory_iterator(recursive_directory_iterator&& rhs) noexcept : _impl(std::move(rhs._impl)) { } GHC_INLINE recursive_directory_iterator::~recursive_directory_iterator() {} // 30.10.14.1 observers GHC_INLINE directory_options recursive_directory_iterator::options() const { return _impl->_options; } GHC_INLINE int recursive_directory_iterator::depth() const { return static_cast<int>(_impl->_dir_iter_stack.size() - 1); } GHC_INLINE bool recursive_directory_iterator::recursion_pending() const { return _impl->_recursion_pending; } GHC_INLINE const directory_entry& recursive_directory_iterator::operator*() const { return *(_impl->_dir_iter_stack.top()); } GHC_INLINE const directory_entry* recursive_directory_iterator::operator->() const { return &(*(_impl->_dir_iter_stack.top())); } // 30.10.14.1 modifiers recursive_directory_iterator& GHC_INLINE recursive_directory_iterator& recursive_directory_iterator::operator=(const recursive_directory_iterator& rhs) { _impl = rhs._impl; return *this; } GHC_INLINE recursive_directory_iterator& recursive_directory_iterator::operator=(recursive_directory_iterator&& rhs) noexcept { _impl = std::move(rhs._impl); return *this; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE recursive_directory_iterator& recursive_directory_iterator::operator++() { std::error_code ec; increment(ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), _impl->_dir_iter_stack.empty() ? path() : _impl->_dir_iter_stack.top()->path(), ec); } return *this; } #endif GHC_INLINE recursive_directory_iterator& recursive_directory_iterator::increment(std::error_code& ec) noexcept { auto status = (*this)->status(ec); if (ec) return *this; auto symlink_status = (*this)->symlink_status(ec); if (ec) return *this; if (recursion_pending() && is_directory(status) && (!is_symlink(symlink_status) || (options() & directory_options::follow_directory_symlink) != directory_options::none)) { _impl->_dir_iter_stack.push(directory_iterator((*this)->path(), _impl->_options, ec)); } else { _impl->_dir_iter_stack.top().increment(ec); } if (!ec) { while (depth() && _impl->_dir_iter_stack.top() == directory_iterator()) { _impl->_dir_iter_stack.pop(); _impl->_dir_iter_stack.top().increment(ec); } } else if (!_impl->_dir_iter_stack.empty()) { _impl->_dir_iter_stack.pop(); } _impl->_recursion_pending = true; return *this; } #ifdef GHC_WITH_EXCEPTIONS GHC_INLINE void recursive_directory_iterator::pop() { std::error_code ec; pop(ec); if (ec) { throw filesystem_error(detail::systemErrorText(ec.value()), _impl->_dir_iter_stack.empty() ? path() : _impl->_dir_iter_stack.top()->path(), ec); } } #endif GHC_INLINE void recursive_directory_iterator::pop(std::error_code& ec) { if (depth() == 0) { *this = recursive_directory_iterator(); } else { do { _impl->_dir_iter_stack.pop(); _impl->_dir_iter_stack.top().increment(ec); } while (depth() && _impl->_dir_iter_stack.top() == directory_iterator()); } } GHC_INLINE void recursive_directory_iterator::disable_recursion_pending() { _impl->_recursion_pending = false; } // other members as required by 27.2.3, input iterators GHC_INLINE bool recursive_directory_iterator::operator==(const recursive_directory_iterator& rhs) const { return _impl->_dir_iter_stack.top() == rhs._impl->_dir_iter_stack.top(); } GHC_INLINE bool recursive_directory_iterator::operator!=(const recursive_directory_iterator& rhs) const { return _impl->_dir_iter_stack.top() != rhs._impl->_dir_iter_stack.top(); } // 30.10.14.2 directory_iterator non-member functions GHC_INLINE recursive_directory_iterator begin(recursive_directory_iterator iter) noexcept { return iter; } GHC_INLINE recursive_directory_iterator end(const recursive_directory_iterator&) noexcept { return recursive_directory_iterator(); } #endif // GHC_EXPAND_IMPL } // namespace filesystem } // namespace ghc // cleanup some macros #undef GHC_INLINE #undef GHC_EXPAND_IMPL #endif // GHC_FILESYSTEM_H
30.168016
254
0.645638
[ "vector" ]
2970a038a4524703d8ae22e16f5bffb55cd7e054
5,137
cc
C++
runtime/vm/type_testing_stubs_test_arm.cc
wennyyustalim/sdk
e6ffc0b285fb393ba04c4afa35f9a7eae0e05793
[ "BSD-3-Clause" ]
3
2020-04-20T00:11:34.000Z
2022-01-24T20:43:43.000Z
runtime/vm/type_testing_stubs_test_arm.cc
wennyyustalim/sdk
e6ffc0b285fb393ba04c4afa35f9a7eae0e05793
[ "BSD-3-Clause" ]
4
2020-04-20T11:16:42.000Z
2020-04-20T11:18:30.000Z
runtime/vm/type_testing_stubs_test_arm.cc
wennyyustalim/sdk
e6ffc0b285fb393ba04c4afa35f9a7eae0e05793
[ "BSD-3-Clause" ]
9
2021-03-16T09:29:26.000Z
2022-01-06T08:38:10.000Z
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "platform/globals.h" #if defined(TARGET_ARCH_ARM) #include "vm/compiler/assembler/assembler.h" #include "vm/compiler/runtime_api.h" #include "vm/constants.h" #include "vm/object.h" #include "vm/stack_frame.h" #include "vm/symbols.h" #define __ assembler-> namespace dart { void GenerateInvokeTTSStub(compiler::Assembler* assembler) { __ EnterDartFrame(0); intptr_t sum = 0; for (intptr_t i = 0; i < kNumberOfCpuRegisters; ++i) { if (((1 << i) & kDartAvailableCpuRegs) == 0) continue; if (((1 << i) & TypeTestABI::kAbiRegisters) != 0) continue; if (((1 << i) & TTSInternalRegs::kInternalRegisters) != 0) continue; __ LoadImmediate(static_cast<Register>(i), 0x10 + 2 * i); sum += 0x10 + 2 * i; } // Load the arguments into the right TTS calling convention registers. __ ldr(TypeTestABI::kInstanceReg, compiler::Address( FP, (kCallerSpSlotFromFp + 3) * compiler::target::kWordSize)); __ ldr(TypeTestABI::kInstantiatorTypeArgumentsReg, compiler::Address( FP, (kCallerSpSlotFromFp + 2) * compiler::target::kWordSize)); __ ldr(TypeTestABI::kFunctionTypeArgumentsReg, compiler::Address( FP, (kCallerSpSlotFromFp + 1) * compiler::target::kWordSize)); __ ldr(TypeTestABI::kDstTypeReg, compiler::Address( FP, (kCallerSpSlotFromFp + 0) * compiler::target::kWordSize)); const intptr_t sub_type_cache_index = __ object_pool_builder().AddObject( Object::null_object(), compiler::ObjectPoolBuilderEntry::kPatchable); const intptr_t sub_type_cache_offset = ObjectPool::element_offset(sub_type_cache_index) - kHeapObjectTag; const intptr_t dst_name_index = __ object_pool_builder().AddObject( Symbols::OptimizedOut(), compiler::ObjectPoolBuilderEntry::kPatchable); ASSERT((sub_type_cache_index + 1) == dst_name_index); ASSERT(__ constant_pool_allowed()); // Call the TTS. __ ldr(R9, compiler::FieldAddress( TypeTestABI::kDstTypeReg, AbstractType::type_test_stub_entry_point_offset())); __ ldr(TypeTestABI::kSubtypeTestCacheReg, compiler::Address(PP, sub_type_cache_offset)); __ blx(R9); // We have the guarantee that TTS preserve all registers except for one // scratch register atm (if the TTS handles the type test successfully). // // Let the test know whether TTS abi registers were preserved. compiler::Label abi_regs_modified, store_abi_regs_modified_bool; __ CompareWithMemoryValue( TypeTestABI::kInstanceReg, compiler::Address( FP, (kCallerSpSlotFromFp + 3) * compiler::target::kWordSize)); __ BranchIf(NOT_EQUAL, &abi_regs_modified); __ CompareWithMemoryValue( TypeTestABI::kInstantiatorTypeArgumentsReg, compiler::Address( FP, (kCallerSpSlotFromFp + 2) * compiler::target::kWordSize)); __ BranchIf(NOT_EQUAL, &abi_regs_modified); __ CompareWithMemoryValue( TypeTestABI::kFunctionTypeArgumentsReg, compiler::Address( FP, (kCallerSpSlotFromFp + 1) * compiler::target::kWordSize)); __ BranchIf(NOT_EQUAL, &abi_regs_modified); __ CompareWithMemoryValue( TypeTestABI::kDstTypeReg, compiler::Address( FP, (kCallerSpSlotFromFp + 0) * compiler::target::kWordSize)); __ BranchIf(NOT_EQUAL, &abi_regs_modified); __ ldr(R0, compiler::Address(THR, Thread::bool_false_offset())); __ b(&store_abi_regs_modified_bool); __ Bind(&abi_regs_modified); __ ldr(R0, compiler::Address(THR, Thread::bool_true_offset())); __ Bind(&store_abi_regs_modified_bool); __ ldr(TMP, compiler::Address( FP, (kCallerSpSlotFromFp + 5) * compiler::target::kWordSize)); __ str(R0, compiler::FieldAddress(TMP, Array::element_offset(0))); // Let the test know whether the non-TTS abi registers were preserved. compiler::Label rest_regs_modified, store_rest_regs_modified_bool; __ mov(TMP, compiler::Operand(0)); for (intptr_t i = 0; i < kNumberOfCpuRegisters; ++i) { if (((1 << i) & kDartAvailableCpuRegs) == 0) continue; if (((1 << i) & TypeTestABI::kAbiRegisters) != 0) continue; if (((1 << i) & TTSInternalRegs::kInternalRegisters) != 0) continue; __ add(TMP, TMP, compiler::Operand(static_cast<Register>(i))); } __ cmp(TMP, compiler::Operand(sum)); __ BranchIf(NOT_EQUAL, &rest_regs_modified); __ ldr(R0, compiler::Address(THR, Thread::bool_false_offset())); __ b(&store_rest_regs_modified_bool); __ Bind(&rest_regs_modified); __ ldr(R0, compiler::Address(THR, Thread::bool_true_offset())); __ Bind(&store_rest_regs_modified_bool); __ ldr(TMP, compiler::Address( FP, (kCallerSpSlotFromFp + 4) * compiler::target::kWordSize)); __ str(R0, compiler::FieldAddress(TMP, Array::element_offset(0))); __ LoadObject(R0, Object::null_object()); __ LeaveDartFrameAndReturn(); } } // namespace dart #endif // defined(TARGET_ARCH_ARM)
41.427419
80
0.701577
[ "object" ]
2972f55ac2f7fd7b17823d68000acf11f838384f
2,230
cpp
C++
Gems/RecastNavigation/Code/Source/Components/RecastNavigationMeshComponent.cpp
prophetl33t/o3de
eaeeb883eee1594b1b93327f6909eebd1a826caf
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/RecastNavigation/Code/Source/Components/RecastNavigationMeshComponent.cpp
prophetl33t/o3de
eaeeb883eee1594b1b93327f6909eebd1a826caf
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/RecastNavigation/Code/Source/Components/RecastNavigationMeshComponent.cpp
prophetl33t/o3de
eaeeb883eee1594b1b93327f6909eebd1a826caf
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "RecastNavigationMeshComponent.h" #include <AzCore/Preprocessor/CodeGen.h> #include <AzCore/Serialization/SerializeContext.h> namespace RecastNavigation { RecastNavigationMeshComponent::RecastNavigationMeshComponent(const RecastNavigationMeshConfig& config) : BaseClass(config) { } void RecastNavigationMeshComponent::Reflect(AZ::ReflectContext* context) { BaseClass::Reflect(context); if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context)) { serializeContext->Class<RecastNavigationMeshComponent, BaseClass>() ->Version(1); } if (auto behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context)) { behaviorContext->ConstantProperty("RecastNavigationMeshComponentTypeId", BehaviorConstant(AZ::Uuid(RecastNavigationMeshComponentTypeId))) ->Attribute(AZ::Script::Attributes::Module, "navigation") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common); behaviorContext->EBus<RecastNavigationMeshRequestBus>("RecastNavigationMeshRequestBus") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Module, "navigation") ->Attribute(AZ::Script::Attributes::Category, "Recast Navigation") ->Event("UpdateNavigationMesh", &RecastNavigationMeshRequests::UpdateNavigationMeshBlockUntilCompleted) ->Event("UpdateNavigationMeshAsync", &RecastNavigationMeshRequests::UpdateNavigationMeshAsync); behaviorContext->Class<RecastNavigationMeshComponentController>()->RequestBus("RecastNavigationMeshRequestBus"); behaviorContext->EBus<RecastNavigationMeshNotificationBus>("RecastNavigationMeshNotificationBus") ->Handler<RecastNavigationNotificationHandler>(); } } } // namespace RecastNavigation
43.72549
149
0.707175
[ "3d" ]
297324bd2fa8da7886f3ea1e8575d98fd5c9aaec
2,895
cpp
C++
rw_utils/rwde_shader.cpp
mrqo/rw_parse
cc1c079ba61dca36b799b1761a3bab87f84f33bb
[ "MIT" ]
3
2020-10-22T05:58:05.000Z
2021-11-18T17:40:07.000Z
rw_utils/rwde_shader.cpp
mrqo/rw_parse
cc1c079ba61dca36b799b1761a3bab87f84f33bb
[ "MIT" ]
null
null
null
rw_utils/rwde_shader.cpp
mrqo/rw_parse
cc1c079ba61dca36b799b1761a3bab87f84f33bb
[ "MIT" ]
null
null
null
// REWRITE IT! #include "stdafx.h" #include "rwde_shader.h" #include <iostream> #include <fstream> Shader::Shader(const std::string& fileName) { m_program = glCreateProgram(); m_shaders[0] = CreateShader(LoadShader(fileName + ".vs"), GL_VERTEX_SHADER); m_shaders[1] = CreateShader(LoadShader(fileName + ".fs"), GL_FRAGMENT_SHADER); for (unsigned int i = 0; i < NUM_SHADERS; i++) glAttachShader(m_program, m_shaders[i]); glBindAttribLocation(m_program, 0, "position"); glBindAttribLocation(m_program, 1, "texCoord"); glBindAttribLocation(m_program, 2, "normal"); glLinkProgram(m_program); CheckShaderError(m_program, GL_LINK_STATUS, true, "Error linking shader program"); glValidateProgram(m_program); CheckShaderError(m_program, GL_LINK_STATUS, true, "Invalid shader program"); m_uniforms[0] = glGetUniformLocation(m_program, "MVP"); m_uniforms[1] = glGetUniformLocation(m_program, "Normal"); m_uniforms[2] = glGetUniformLocation(m_program, "lightDirection"); } Shader::~Shader() { for (unsigned int i = 0; i < NUM_SHADERS; i++) { glDetachShader(m_program, m_shaders[i]); glDeleteShader(m_shaders[i]); } glDeleteProgram(m_program); } void Shader::Bind() { glUseProgram(m_program); } void Shader::Update(const Transform& transform, const RWDE::Camera& camera) { glm::mat4 MVP = transform.GetMVP(camera); glm::mat4 Normal = transform.GetModel(); glUniformMatrix4fv(m_uniforms[0], 1, GL_FALSE, &MVP[0][0]); glUniformMatrix4fv(m_uniforms[1], 1, GL_FALSE, &Normal[0][0]); glUniform3f(m_uniforms[2], 0.0f, 0.0f, 1.0f); } std::string Shader::LoadShader(const std::string& fileName) { std::ifstream file; file.open((fileName).c_str()); std::string output; std::string line; if (file.is_open()) { while (file.good()) { getline(file, line); output.append(line + "\n"); } } else { std::cerr << "Unable to load shader: " << fileName << std::endl; } return output; } void Shader::CheckShaderError(GLuint shader, GLuint flag, bool isProgram, const std::string& errorMessage) { GLint success = 0; GLchar error[1024] = { 0 }; if (isProgram) glGetProgramiv(shader, flag, &success); else glGetShaderiv(shader, flag, &success); if (success == GL_FALSE) { if (isProgram) glGetProgramInfoLog(shader, sizeof(error), NULL, error); else glGetShaderInfoLog(shader, sizeof(error), NULL, error); std::cerr << errorMessage << ": '" << error << "'" << std::endl; } } GLuint Shader::CreateShader(const std::string& text, unsigned int type) { GLuint shader = glCreateShader(type); if (shader == 0) std::cerr << "Error compiling shader type " << type << std::endl; const GLchar* p[1]; p[0] = text.c_str(); GLint lengths[1]; lengths[0] = text.length(); glShaderSource(shader, 1, p, lengths); glCompileShader(shader); CheckShaderError(shader, GL_COMPILE_STATUS, false, "Error compiling shader!"); return shader; }
23.92562
106
0.700864
[ "transform" ]
29745beb68289bc4cb8357540f535917ec5c608b
10,171
cpp
C++
Gems/EMotionFX/Code/Source/Editor/Plugins/Ragdoll/RagdollNodeWidget.cpp
pollend/o3de
02b6b1dbf4d9889b55d4c11e049aa5b1804c9897
[ "Apache-2.0", "MIT" ]
8
2021-08-31T02:14:19.000Z
2021-12-28T19:20:59.000Z
Gems/EMotionFX/Code/Source/Editor/Plugins/Ragdoll/RagdollNodeWidget.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
8
2021-07-12T13:55:00.000Z
2021-10-04T14:53:21.000Z
Gems/EMotionFX/Code/Source/Editor/Plugins/Ragdoll/RagdollNodeWidget.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
1
2021-07-09T06:02:14.000Z
2021-07-09T06:02:14.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/Component/ComponentApplicationBus.h> #include <AzCore/Serialization/SerializeContext.h> #include <AzFramework/Physics/Ragdoll.h> #include <EMotionFX/Source/Actor.h> #include <EMotionFX/Source/Node.h> #include <EMotionFX/CommandSystem/Source/ColliderCommands.h> #include <Editor/ColliderContainerWidget.h> #include <Editor/ColliderHelpers.h> #include <Editor/ObjectEditor.h> #include <Editor/SkeletonModel.h> #include <Editor/Plugins/Ragdoll/RagdollJointLimitWidget.h> #include <Editor/Plugins/Ragdoll/RagdollNodeInspectorPlugin.h> #include <Editor/Plugins/Ragdoll/RagdollNodeWidget.h> #include <Editor/Plugins/SkeletonOutliner/SkeletonOutlinerBus.h> #include <QLabel> #include <QMessageBox> #include <QHBoxLayout> #include <QVBoxLayout> namespace EMotionFX { RagdollCardHeader::RagdollCardHeader(QWidget* parent) : AzQtComponents::CardHeader(parent) { m_backgroundFrame->setObjectName(""); } RagdollCard::RagdollCard(QWidget* parent) : AzQtComponents::Card(new RagdollCardHeader(), parent) { hideFrame(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// RagdollNodeWidget::RagdollNodeWidget(QWidget* parent) : SkeletonModelJointWidget(parent) , m_ragdollNodeCard(nullptr) , m_ragdollNodeEditor(nullptr) , m_addRemoveButton(nullptr) , m_jointLimitWidget(nullptr) , m_addColliderButton(nullptr) , m_collidersWidget(nullptr) { } QWidget* RagdollNodeWidget::CreateContentWidget(QWidget* parent) { QWidget* result = new QWidget(parent); QVBoxLayout* layout = new QVBoxLayout(); layout->setMargin(0); layout->setSpacing(ColliderContainerWidget::s_layoutSpacing); result->setLayout(layout); // Ragdoll node widget AZ::SerializeContext* serializeContext = nullptr; AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); AZ_Error("EMotionFX", serializeContext, "Can't get serialize context from component application."); m_ragdollNodeEditor = new EMotionFX::ObjectEditor(serializeContext, result); m_ragdollNodeCard = new RagdollCard(result); m_ragdollNodeCard->setTitle("Ragdoll properties"); m_ragdollNodeCard->setContentWidget(m_ragdollNodeEditor); m_ragdollNodeCard->setExpanded(true); AzQtComponents::CardHeader* cardHeader = m_ragdollNodeCard->header(); cardHeader->setHasContextMenu(false); layout->addWidget(m_ragdollNodeCard); // Buttons QVBoxLayout* buttonLayout = new QVBoxLayout(); layout->addLayout(buttonLayout); m_addColliderButton = new AddColliderButton("Add ragdoll collider", result, PhysicsSetup::ColliderConfigType::Ragdoll); connect(m_addColliderButton, &AddColliderButton::AddCollider, this, &RagdollNodeWidget::OnAddCollider); buttonLayout->addWidget(m_addColliderButton); m_addRemoveButton = new QPushButton(result); m_addRemoveButton->setObjectName("EMFX.RagdollNodeWidget.PushButton.RagdollAddRemoveButton"); connect(m_addRemoveButton, &QPushButton::clicked, this, &RagdollNodeWidget::OnAddRemoveRagdollNode); buttonLayout->addWidget(m_addRemoveButton); // Joint limit m_jointLimitWidget = new RagdollJointLimitWidget(m_copiedJointLimit, result); connect(m_jointLimitWidget, &RagdollJointLimitWidget::JointLimitCopied, [this](const AZStd::string& serializedJointLimits) { m_copiedJointLimit = serializedJointLimits; }); layout->addWidget(m_jointLimitWidget); // Colliders m_collidersWidget = new ColliderContainerWidget(QIcon(SkeletonModel::s_ragdollColliderIconPath), result); connect(m_collidersWidget, &ColliderContainerWidget::CopyCollider, this, &RagdollNodeWidget::OnCopyCollider); connect(m_collidersWidget, &ColliderContainerWidget::PasteCollider, this, &RagdollNodeWidget::OnPasteCollider); connect(m_collidersWidget, &ColliderContainerWidget::RemoveCollider, this, &RagdollNodeWidget::OnRemoveCollider); layout->addWidget(m_collidersWidget); return result; } QWidget* RagdollNodeWidget::CreateNoSelectionWidget(QWidget* parent) { QLabel* noSelectionLabel = new QLabel("Select joints from the Skeleton Outliner and add it to the ragdoll using the right-click menu", parent); noSelectionLabel->setWordWrap(true); return noSelectionLabel; } void RagdollNodeWidget::InternalReinit() { const QModelIndexList& selectedModelIndices = GetSelectedModelIndices(); if (selectedModelIndices.size() == 1) { m_ragdollNodeEditor->ClearInstances(false); Physics::CharacterColliderNodeConfiguration* colliderNodeConfig = GetRagdollColliderNodeConfig(); Physics::RagdollNodeConfiguration* ragdollNodeConfig = GetRagdollNodeConfig(); if (ragdollNodeConfig) { m_addColliderButton->show(); m_addRemoveButton->setText("Remove from ragdoll"); m_ragdollNodeEditor->AddInstance(ragdollNodeConfig, azrtti_typeid(ragdollNodeConfig)); AZ::SerializeContext* serializeContext = nullptr; AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); AZ_Error("EMotionFX", serializeContext, "Can't get serialize context from component application."); if (colliderNodeConfig) { m_collidersWidget->Update(GetActor(), GetNode(), PhysicsSetup::ColliderConfigType::Ragdoll, colliderNodeConfig->m_shapes, serializeContext); } else { m_collidersWidget->Reset(); } m_jointLimitWidget->Update(selectedModelIndices[0]); m_ragdollNodeCard->setExpanded(true); m_ragdollNodeCard->show(); m_jointLimitWidget->show(); m_collidersWidget->show(); } else { m_addColliderButton->hide(); m_addRemoveButton->setText("Add to ragdoll"); m_collidersWidget->Reset(); m_ragdollNodeCard->hide(); m_jointLimitWidget->Update(QModelIndex()); m_jointLimitWidget->hide(); m_collidersWidget->hide(); } } else { m_ragdollNodeEditor->ClearInstances(true); m_jointLimitWidget->Update(QModelIndex()); m_collidersWidget->Reset(); } } void RagdollNodeWidget::OnAddRemoveRagdollNode() { const QModelIndexList& selectedModelIndices = GetSelectedModelIndices(); if (GetRagdollNodeConfig()) { // The node is present in the ragdoll, remove it. RagdollNodeInspectorPlugin::RemoveFromRagdoll(selectedModelIndices); } else { // The node is not part of the ragdoll, add it. RagdollNodeInspectorPlugin::AddToRagdoll(selectedModelIndices); } } void RagdollNodeWidget::OnAddCollider(const AZ::TypeId& colliderType) { ColliderHelpers::AddCollider(GetSelectedModelIndices(), PhysicsSetup::Ragdoll, colliderType); } void RagdollNodeWidget::OnCopyCollider(size_t colliderIndex) { ColliderHelpers::CopyColliderToClipboard(GetSelectedModelIndices().first(), colliderIndex, PhysicsSetup::Ragdoll); } void RagdollNodeWidget::OnPasteCollider(size_t colliderIndex, bool replace) { ColliderHelpers::PasteColliderFromClipboard(GetSelectedModelIndices().first(), colliderIndex, PhysicsSetup::Ragdoll, replace); } void RagdollNodeWidget::OnRemoveCollider(size_t colliderIndex) { CommandColliderHelpers::RemoveCollider(GetActor()->GetID(), GetNode()->GetNameString(), PhysicsSetup::Ragdoll, colliderIndex); } Physics::RagdollConfiguration* RagdollNodeWidget::GetRagdollConfig() const { Actor* actor = GetActor(); Node* node = GetNode(); if (actor && node) { const AZStd::shared_ptr<EMotionFX::PhysicsSetup>& physicsSetup = actor->GetPhysicsSetup(); if (physicsSetup) { return &physicsSetup->GetRagdollConfig(); } } return nullptr; } Physics::CharacterColliderNodeConfiguration* RagdollNodeWidget::GetRagdollColliderNodeConfig() const { Actor* actor = GetActor(); Node* node = GetNode(); if (actor && node) { const AZStd::shared_ptr<EMotionFX::PhysicsSetup>& physicsSetup = actor->GetPhysicsSetup(); if (physicsSetup) { const Physics::CharacterColliderConfiguration& colliderConfig = physicsSetup->GetRagdollConfig().m_colliders; return colliderConfig.FindNodeConfigByName(node->GetNameString()); } } return nullptr; } Physics::RagdollNodeConfiguration* RagdollNodeWidget::GetRagdollNodeConfig() const { Actor* actor = GetActor(); Node* node = GetNode(); if (actor && node) { const AZStd::shared_ptr<EMotionFX::PhysicsSetup>& physicsSetup = actor->GetPhysicsSetup(); if (physicsSetup) { const Physics::RagdollConfiguration& ragdollConfig = physicsSetup->GetRagdollConfig(); return ragdollConfig.FindNodeConfigByName(node->GetNameString()); } } return nullptr; } } // namespace EMotionFX
39.730469
160
0.659424
[ "3d" ]
29808019f9982a416949b11d42dac2bbe7c4e85c
5,551
cc
C++
RecoVertex/KinematicFit/src/VertexKinematicConstraint.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
RecoVertex/KinematicFit/src/VertexKinematicConstraint.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
RecoVertex/KinematicFit/src/VertexKinematicConstraint.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "RecoVertex/KinematicFit/interface/VertexKinematicConstraint.h" #include "RecoVertex/VertexPrimitives/interface/VertexException.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" VertexKinematicConstraint::VertexKinematicConstraint() {} VertexKinematicConstraint::~VertexKinematicConstraint() {} AlgebraicVector VertexKinematicConstraint::value(const std::vector<KinematicState> &states, const GlobalPoint& point) const { int num = states.size(); if(num<2) throw VertexException("VertexKinematicConstraint::<2 states passed"); //it is 2 equations per track AlgebraicVector vl(2*num,0); int num_r = 0; for(std::vector<KinematicState>::const_iterator i = states.begin(); i != states.end(); i++) { TrackCharge ch = i->particleCharge(); GlobalVector mom = i->globalMomentum(); GlobalPoint pos = i->globalPosition(); double d_x = point.x() - pos.x(); double d_y = point.y() - pos.y(); double d_z = point.z() - pos.z(); double pt = mom.transverse(); if(ch !=0) { //charged particle double a_i = - ch * i->magneticField()->inInverseGeV(pos).z(); double pvx = mom.x() - a_i*d_y; double pvy = mom.y() + a_i*d_x; double n = a_i*(d_x * mom.x() + d_y * mom.y()); double m = (pvx*mom.x() + pvy*mom.y()); double delta = atan2(n,m); //vector of values vl(num_r*2 +1) = d_y*mom.x() - d_x*mom.y() -a_i*(d_x*d_x + d_y*d_y)/2; vl(num_r*2 +2) = d_z - mom.z()*delta/a_i; }else{ //neutral particle vl(num_r*2 +1) = d_y*mom.x() - d_x*mom.y(); vl(num_r*2 +2) = d_z - mom.z()*(d_x * mom.x() + d_y * mom.y())/(pt*pt); } num_r++; } return vl; } AlgebraicMatrix VertexKinematicConstraint::parametersDerivative(const std::vector<KinematicState> &states, const GlobalPoint& point) const { int num = states.size(); if(num<2) throw VertexException("VertexKinematicConstraint::<2 states passed"); AlgebraicMatrix jac_d(2*num,7*num); int num_r = 0; for(std::vector<KinematicState>::const_iterator i = states.begin(); i != states.end(); i++) { AlgebraicMatrix el_part_d(2,7,0); TrackCharge ch = i->particleCharge(); GlobalVector mom = i->globalMomentum(); GlobalPoint pos = i->globalPosition(); double d_x = point.x() - pos.x(); double d_y = point.y() - pos.y(); double pt = mom.transverse(); if(ch !=0){ //charged particle double a_i = - ch * i->magneticField()->inInverseGeV(pos).z(); double pvx = mom.x() - a_i*d_y; double pvy = mom.y() + a_i*d_x; double pvt = sqrt(pvx*pvx+pvy*pvy); double novera = (d_x * mom.x() + d_y * mom.y()); double n = a_i*novera; double m = (pvx*mom.x() + pvy*mom.y()); double k = -mom.z()/(pvt*pvt*pt*pt); double delta = atan2(n,m); //D Jacobian matrix el_part_d(1,1) = mom.y() + a_i*d_x; el_part_d(1,2) = -mom.x() + a_i*d_y; el_part_d(2,1) = -k*(m*mom.x() - n*mom.y()); el_part_d(2,2) = -k*(m*mom.y() + n*mom.x()); el_part_d(2,3) = -1.; el_part_d(1,4) = d_y; el_part_d(1,5) = -d_x; el_part_d(2,4) = k*(m*d_x - novera*(2*mom.x() - a_i*d_y)); el_part_d(2,5) = k*(m*d_y - novera*(2*mom.y() + a_i*d_x)); el_part_d(2,6) = -delta /a_i; jac_d.sub(num_r*2+1, num_r*7+1, el_part_d); }else{ //neutral particle el_part_d(1,1) = mom.y(); el_part_d(1,2) = -mom.x(); el_part_d(2,1) = mom.x() * mom.z()/(pt*pt); el_part_d(2,2) = mom.y() * mom.z()/(pt*pt); el_part_d(2,3) = -1.; el_part_d(1,4) = d_y; el_part_d(1,5) = -d_x; el_part_d(2,4) = 2*(d_x*mom.x()+d_y*mom.y())*mom.x()*mom.z()/(pt*pt*pt*pt) - mom.z()*d_x/(pt*pt); el_part_d(2,5) = 2*(d_x*mom.x()+d_y*mom.y())*mom.y()*mom.z()/(pt*pt*pt*pt) - mom.z()*d_y/(pt*pt); el_part_d(2,6) =-(d_x * mom.x() + d_y * mom.y())/(pt*pt); jac_d.sub(num_r*2+1, num_r*7+1, el_part_d); } num_r++; } return jac_d; } AlgebraicMatrix VertexKinematicConstraint::positionDerivative(const std::vector<KinematicState> &states, const GlobalPoint& point) const { int num = states.size(); if(num<2) throw VertexException("VertexKinematicConstraint::<2 states passed"); AlgebraicMatrix jac_e(2*num,3); int num_r = 0; for(std::vector<KinematicState>::const_iterator i = states.begin(); i != states.end(); i++) { AlgebraicMatrix el_part_e(2,3,0); TrackCharge ch = i->particleCharge(); GlobalVector mom = i->globalMomentum(); GlobalPoint pos = i->globalPosition(); double d_x = point.x() - pos.x(); double d_y = point.y() - pos.y(); double pt = mom.transverse(); if(ch !=0 ) { //charged particle double a_i = - ch * i->magneticField()->inInverseGeV(pos).z(); double pvx = mom.x() - a_i*d_y; double pvy = mom.y() + a_i*d_x; double pvt = sqrt(pvx*pvx+pvy*pvy); double n = a_i*(d_x * mom.x() + d_y * mom.y()); double m = (pvx*mom.x() + pvy*mom.y()); double k = -mom.z()/(pvt*pvt*pt*pt); //E jacobian matrix el_part_e(1,1) = -(mom.y() + a_i*d_x); el_part_e(1,2) = mom.x() - a_i*d_y; el_part_e(2,1) = k*(m*mom.x() - n*mom.y()); el_part_e(2,2) = k*(m*mom.y() + n*mom.x()); el_part_e(2,3) = 1; jac_e.sub(2*num_r+1,1,el_part_e); }else{ //neutral particle el_part_e(1,1) = - mom.y(); el_part_e(1,2) = mom.x(); el_part_e(2,1) = -mom.x()*mom.z()/(pt*pt); el_part_e(2,2) = -mom.y()*mom.z()/(pt*pt); el_part_e(2,3) = 1; jac_e.sub(2*num_r+1,1,el_part_e); } num_r++; } return jac_e; } int VertexKinematicConstraint::numberOfEquations() const {return 2;}
32.273256
106
0.601513
[ "vector" ]
298971283c242e1fa06b0e259f9336b62104dd8c
2,819
cpp
C++
tcss/src/v20201101/model/ModifyAssetImageScanStopRequest.cpp
milezhang/tencentcloud-sdk-cpp
cbe6b13912dd1582bf7a95cfc9c6303bdc874e1d
[ "Apache-2.0" ]
null
null
null
tcss/src/v20201101/model/ModifyAssetImageScanStopRequest.cpp
milezhang/tencentcloud-sdk-cpp
cbe6b13912dd1582bf7a95cfc9c6303bdc874e1d
[ "Apache-2.0" ]
null
null
null
tcss/src/v20201101/model/ModifyAssetImageScanStopRequest.cpp
milezhang/tencentcloud-sdk-cpp
cbe6b13912dd1582bf7a95cfc9c6303bdc874e1d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/tcss/v20201101/model/ModifyAssetImageScanStopRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Tcss::V20201101::Model; using namespace std; ModifyAssetImageScanStopRequest::ModifyAssetImageScanStopRequest() : m_taskIDHasBeenSet(false), m_imagesHasBeenSet(false) { } string ModifyAssetImageScanStopRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_taskIDHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TaskID"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_taskID.c_str(), allocator).Move(), allocator); } if (m_imagesHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Images"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_images.begin(); itr != m_images.end(); ++itr) { d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string ModifyAssetImageScanStopRequest::GetTaskID() const { return m_taskID; } void ModifyAssetImageScanStopRequest::SetTaskID(const string& _taskID) { m_taskID = _taskID; m_taskIDHasBeenSet = true; } bool ModifyAssetImageScanStopRequest::TaskIDHasBeenSet() const { return m_taskIDHasBeenSet; } vector<string> ModifyAssetImageScanStopRequest::GetImages() const { return m_images; } void ModifyAssetImageScanStopRequest::SetImages(const vector<string>& _images) { m_images = _images; m_imagesHasBeenSet = true; } bool ModifyAssetImageScanStopRequest::ImagesHasBeenSet() const { return m_imagesHasBeenSet; }
28.19
104
0.721887
[ "vector", "model" ]
2989a857128971e405b987d4ceaea78ffe4bd775
8,660
cc
C++
source/common/json/json_loader.cc
rojkov/envoy
23474d712358e6681a7fe0f839c6546c9ff2193f
[ "Apache-2.0" ]
null
null
null
source/common/json/json_loader.cc
rojkov/envoy
23474d712358e6681a7fe0f839c6546c9ff2193f
[ "Apache-2.0" ]
33
2020-12-04T15:48:38.000Z
2021-08-12T12:06:48.000Z
source/common/json/json_loader.cc
rojkov/envoy
23474d712358e6681a7fe0f839c6546c9ff2193f
[ "Apache-2.0" ]
null
null
null
#include "json_loader.h" // Do not let RapidJson leak outside of this file. #include "rapidjson/document.h" #include "rapidjson/error/en.h" #include "rapidjson/istreamwrapper.h" #include "rapidjson/schema.h" #include "rapidjson/stringbuffer.h" #include "rapidjson/writer.h" namespace Json { /** * Implementation of Object. */ class ObjectImplBase : public Object { public: ObjectImplBase(const rapidjson::Value& value, const std::string& name) : name_(name), value_(value) {} std::vector<ObjectPtr> asObjectArray() const override { if (!value_.IsArray()) { throw Exception(fmt::format("'{}' is not an array", name_)); } std::vector<ObjectPtr> object_array; object_array.reserve(value_.Size()); for (auto& array_value : value_.GetArray()) { object_array.emplace_back(new ObjectImplBase(array_value, name_ + " (array item)")); } return object_array; } bool getBoolean(const std::string& name) const override { rapidjson::Value::ConstMemberIterator member_itr = value_.FindMember(name.c_str()); if (member_itr == value_.MemberEnd() || !member_itr->value.IsBool()) { throw Exception(fmt::format("key '{}' missing or not a boolean in '{}'", name, name_)); } return member_itr->value.GetBool(); } bool getBoolean(const std::string& name, bool default_value) const override { if (!value_.HasMember(name.c_str())) { return default_value; } else { return getBoolean(name); } } int64_t getInteger(const std::string& name) const override { rapidjson::Value::ConstMemberIterator member_itr = value_.FindMember(name.c_str()); if (member_itr == value_.MemberEnd() || !member_itr->value.IsInt64()) { throw Exception(fmt::format("key '{}' missing or not an integer in '{}'", name, name_)); } return member_itr->value.GetInt64(); } int64_t getInteger(const std::string& name, int64_t default_value) const override { if (!value_.HasMember(name.c_str())) { return default_value; } else { return getInteger(name); } } ObjectPtr getObject(const std::string& name, bool allow_empty) const override { rapidjson::Value::ConstMemberIterator member_itr = value_.FindMember(name.c_str()); if (member_itr == value_.MemberEnd() && !allow_empty) { throw Exception(fmt::format("key '{}' missing or not an integer in '{}'", name, name_)); } else if (member_itr == value_.MemberEnd()) { return ObjectPtr{new ObjectImplBase(empty_rapid_json_value_, name)}; } return ObjectPtr{new ObjectImplBase(member_itr->value, name)}; } std::vector<ObjectPtr> getObjectArray(const std::string& name) const override { rapidjson::Value::ConstMemberIterator member_itr = value_.FindMember(name.c_str()); if (member_itr == value_.MemberEnd() || !member_itr->value.IsArray()) { throw Exception(fmt::format("key '{}' missing or not a array in '{}'", name, name_)); } std::vector<ObjectPtr> object_array; object_array.reserve(member_itr->value.Size()); for (auto& array_value : member_itr->value.GetArray()) { object_array.emplace_back(new ObjectImplBase(array_value, name + " (array item)")); } return object_array; } std::string getString(const std::string& name) const override { rapidjson::Value::ConstMemberIterator member_itr = value_.FindMember(name.c_str()); if (member_itr == value_.MemberEnd() || !member_itr->value.IsString()) { throw Exception(fmt::format("key '{}' missing or not a string in '{}'", name, name_)); } return member_itr->value.GetString(); } std::string getString(const std::string& name, const std::string& default_value) const override { if (!value_.HasMember(name.c_str())) { return default_value; } else { return getString(name); } } std::vector<std::string> getStringArray(const std::string& name) const override { rapidjson::Value::ConstMemberIterator member_itr = value_.FindMember(name.c_str()); if (member_itr == value_.MemberEnd() || !member_itr->value.IsArray()) { throw Exception(fmt::format("key '{}' missing or not an array in '{}'", name, name_)); } std::vector<std::string> string_array; string_array.reserve(member_itr->value.Size()); for (auto& array_value : member_itr->value.GetArray()) { if (!array_value.IsString()) { throw Exception(fmt::format("array '{}' does not contain all strings", name)); } string_array.push_back(array_value.GetString()); } return string_array; } double getDouble(const std::string& name) const override { rapidjson::Value::ConstMemberIterator member_itr = value_.FindMember(name.c_str()); if (member_itr == value_.MemberEnd() || !member_itr->value.IsDouble()) { throw Exception(fmt::format("key '{}' missing or not a double in '{}'", name, name_)); } return member_itr->value.GetDouble(); } double getDouble(const std::string& name, double default_value) const override { if (!value_.HasMember(name.c_str())) { return default_value; } else { return getDouble(name); } } uint64_t hash() const override { rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); value_.Accept(writer); return std::hash<std::string>{}(buffer.GetString()); } void iterate(const ObjectCallback& callback) const override { for (auto& member : value_.GetObject()) { ObjectImplBase object(member.value, member.name.GetString()); bool need_continue = callback(member.name.GetString(), object); if (!need_continue) { break; } } } bool hasObject(const std::string& name) const override { return value_.HasMember(name.c_str()); } void validateSchema(const std::string& schema) const override { rapidjson::Document document; if (document.Parse<0>(schema.c_str()).HasParseError()) { throw std::invalid_argument(fmt::format("invalid schema \n Effor(offset {}) : {}\n", document.GetErrorOffset(), GetParseError_En(document.GetParseError()))); } rapidjson::SchemaDocument schema_document(document); rapidjson::SchemaValidator schema_validator(schema_document); if (!value_.Accept(schema_validator)) { // TODO(mattklein123): Improve errors by switching to SAX API. rapidjson::StringBuffer schema_string_buffer; rapidjson::StringBuffer document_string_buffer; schema_validator.GetInvalidSchemaPointer().StringifyUriFragment(schema_string_buffer); schema_validator.GetInvalidDocumentPointer().StringifyUriFragment(document_string_buffer); throw Exception(fmt::format( "JSON object doesn't conform to schema.\n Invalid schema: {}.\n Invalid keyword: " "{}.\n Invalid document key: {}", schema_string_buffer.GetString(), schema_validator.GetInvalidSchemaKeyword(), document_string_buffer.GetString())); } } std::string asString() const { if (!value_.IsString()) { throw Exception(fmt::format("'{}' is not a string", name_)); } return value_.GetString(); } bool empty() const override { return value_.IsObject() && value_.ObjectEmpty(); } private: const std::string name_; const rapidjson::Value& value_; static const rapidjson::Value empty_rapid_json_value_; }; const rapidjson::Value ObjectImplBase::empty_rapid_json_value_(rapidjson::kObjectType); /** * Holds the root Object reference. */ class ObjectImplRoot : public ObjectImplBase { public: ObjectImplRoot(rapidjson::Document&& document) : ObjectImplBase(root_, "root"), root_(std::move(document)) {} private: rapidjson::Document root_; }; ObjectPtr Factory::LoadFromFile(const std::string& file_path) { rapidjson::Document document; std::ifstream file_stream(file_path); rapidjson::IStreamWrapper stream_wrapper(file_stream); if (document.ParseStream(stream_wrapper).HasParseError()) { throw Exception(fmt::format("Error(offset {}): {}\n", document.GetErrorOffset(), GetParseError_En(document.GetParseError()))); } return ObjectPtr{new ObjectImplRoot(std::move(document))}; } ObjectPtr Factory::LoadFromString(const std::string& json) { rapidjson::Document document; if (document.Parse<0>(json.c_str()).HasParseError()) { throw Exception(fmt::format("Error(offset {}): {}\n", document.GetErrorOffset(), GetParseError_En(document.GetParseError()))); } return ObjectPtr{new ObjectImplRoot(std::move(document))}; } } // Json
36.694915
99
0.67679
[ "object", "vector" ]
298a8e7829fadf75857efc96a6c270e55cc312cb
185,485
cpp
C++
compiler/codegen/expr.cpp
milisarge/chapel
5a3bb108f1dde56f19ad0811726809566b9e6613
[ "ECL-2.0", "Apache-2.0" ]
3
2020-02-24T13:34:10.000Z
2020-04-17T07:41:55.000Z
compiler/codegen/expr.cpp
milisarge/chapel
5a3bb108f1dde56f19ad0811726809566b9e6613
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
compiler/codegen/expr.cpp
milisarge/chapel
5a3bb108f1dde56f19ad0811726809566b9e6613
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright 2004-2020 Hewlett Packard Enterprise Development LP * Other additional copyright holders may be indicated within. * * The entirety of this work is 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 "expr.h" #include "alist.h" #include "astutil.h" #include "AstVisitor.h" #include "clangUtil.h" #include "codegen.h" #include "driver.h" #include "ForLoop.h" #include "genret.h" #include "insertLineNumbers.h" #include "LayeredValueTable.h" #include "llvmUtil.h" #include "misc.h" #include "passes.h" #include "stmt.h" #include "stringutil.h" #include "type.h" #include "virtualDispatch.h" #include "WhileStmt.h" #include "wellknown.h" #ifdef HAVE_LLVM #include "llvm/IR/Module.h" #endif #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include <inttypes.h> #include <cstdio> #include <cstdlib> #include <cstring> #include <ostream> #include <stack> class FnSymbol; // some prototypes static void codegenAssign(GenRet to_ptr, GenRet from); static GenRet codegenCast(Type* t, GenRet value, bool Cparens = true); static GenRet codegenCastToVoidStar(GenRet value); static GenRet createTempVar(Type* t); static bool codegenIsSpecialPrimitive(BaseAST* target, Expr* e, GenRet& ret); #define createTempRef(t) createTempVar(t) // These functions operate on wide pointers. There are several different // kinds of wide pointers: // 1 wide reference to something // (wide.chplType->symbol->hasFlag(FLAG_WIDE_REF)) // 2 wide class pointer // (wide.chplType->symbol->hasFlag(FLAG_WIDE_CLASS)) // 3 wide result of codegenFieldPtr or codegenElementPtr etc // (wide.isLVPtr == GEN_WIDE_PTR) // These functions need to handle all of these cases, but they // may transform the last case into the 1st. They can't transform // case 2 into case 3 because we wouldn't have a Chapel type for // the body of a class. static GenRet codegenRaddr(GenRet wide); static GenRet codegenRlocale(GenRet wide); static GenRet codegenRnode(GenRet wide); static GenRet codegenAddrOf(GenRet r); /* Note well the difference between codegenCall and codegenCallExpr. * codegenCallExpr always returns the call as an expression in the * returned GenRet. But codegenCall instead adds the call to the * generated statements. If one uses codegenCallExpr instead of codegenCall, * the C backend will never actually emit the call, since it won't * be added to the list of statements. */ static GenRet codegenCallExpr(GenRet function, std::vector<GenRet> & args, FnSymbol* fSym, bool defaultToValues); static GenRet codegenCallExpr(const char* fnName, std::vector<GenRet> & args, bool defaultToValues = true); // some codegenCallExpr are declared in codegen.h static GenRet codegenCallExpr(const char* fnName, GenRet a1, GenRet a2, GenRet a3); static void codegenCall(const char* fnName, std::vector<GenRet> & args, bool defaultToValues = true); static void codegenCall(const char* fnName, GenRet a1); static void codegenCall(const char* fnName, GenRet a1, GenRet a2); static void codegenCall(const char* fnName, GenRet a1, GenRet a2, GenRet a3); //static void codegenCallNotValues(const char* fnName, GenRet a1, GenRet a2, GenRet a3); static void codegenCall(const char* fnName, GenRet a1, GenRet a2, GenRet a3, GenRet a4); static void codegenCall(const char* fnName, GenRet a1, GenRet a2, GenRet a3, GenRet a4, GenRet a5); static void codegenCall(const char* fnName, GenRet a1, GenRet a2, GenRet a3, GenRet a4, GenRet a5, GenRet a6); static GenRet codegenZero(); static GenRet codegenZero32(); static GenRet codegen_prim_get_real(GenRet, Type*, bool real); static int codegen_tmp = 1; /************************************ | ************************************* * * * * ************************************* | ************************************/ /************************************ | ************************************* * * * * ************************************* | ************************************/ #ifdef HAVE_LLVM static void addNoAliasMetadata(GenRet &ret, Symbol* sym) { GenInfo* info = gGenInfo; if (info->cfile == NULL) { // add no-alias information if it's in our map if (info->noAliasScopeLists.count(sym) > 0) ret.aliasScope = info->noAliasScopeLists[sym]; if (info->noAliasLists.count(sym) > 0) ret.noalias = info->noAliasLists[sym]; } } #endif GenRet SymExpr::codegen() { GenInfo* info = gGenInfo; FILE* outfile = info->cfile; GenRet ret; if (id == breakOnCodegenID) gdbShouldBreakHere(); if( outfile ) { if (getStmtExpr() && getStmtExpr() == this) codegenStmt(this); ret = var->codegen(); } else { #ifdef HAVE_LLVM if(isVarSymbol(var)) { ret = toVarSymbol(var)->codegen(); addNoAliasMetadata(ret, var); } else if(isArgSymbol(var)) { ret = info->lvt->getValue(var->cname); addNoAliasMetadata(ret, var); } else if(isTypeSymbol(var)) { ret.type = toTypeSymbol(var)->codegen().type; } else if(isFnSymbol(var) ){ ret = toFnSymbol(var)->codegen(); } else { ret = info->lvt->getValue(var->cname); if( ! ret.val ) { INT_FATAL(this, "!!!!!!! UNHANDLED SYM EXPR !!!!!!!"); } } #endif } ret.canBeMarkedAsConstAfterStore = var->isConstValWillNotChange(); return ret; } /************************************ | ************************************* * * * * ************************************* | ************************************/ GenRet UnresolvedSymExpr::codegen() { GenInfo* info = gGenInfo; FILE* outfile = info->cfile; GenRet ret; INT_FATAL(this, "UnresolvedSymExpr::codegen called"); if( outfile ) fprintf(outfile, "%s /* unresolved symbol */", unresolved); return ret; } /************************************ | ************************************* * * * * ************************************* | ************************************/ GenRet DefExpr::codegen() { GenInfo* info = gGenInfo; GenRet ret; if( info->cfile ) { if (toLabelSymbol(sym)) { std::string str = sym->cname; str += ":;\n"; // ; avoids 'label at end of compound statement' error info->cStatements.push_back(str); } } else { #ifdef HAVE_LLVM if (toLabelSymbol(sym)) { llvm::Function *func = info->irBuilder->GetInsertBlock()->getParent(); llvm::BasicBlock *blockLabel; if(!(blockLabel = info->lvt->getBlock(sym->cname))) { blockLabel = llvm::BasicBlock::Create( info->module->getContext(), sym->cname); info->lvt->addBlock(sym->cname, blockLabel); } info->irBuilder->CreateBr(blockLabel); func->getBasicBlockList().push_back(blockLabel); info->irBuilder->SetInsertPoint(blockLabel); } #endif } return ret; } /************************************ | ************************************* * * * * ************************************* | ************************************/ #ifdef HAVE_LLVM static void codegenLifetimeStart(llvm::Type *valType, llvm::Value *addr) { GenInfo *info = gGenInfo; const llvm::DataLayout& dataLayout = info->module->getDataLayout(); int64_t sizeInBytes = -1; if (valType->isSized()) sizeInBytes = dataLayout.getTypeStoreSize(valType); llvm::ConstantInt *size = llvm::ConstantInt::getSigned( llvm::Type::getInt64Ty(info->llvmContext), sizeInBytes); info->irBuilder->CreateLifetimeStart(addr, size); } llvm::Value* createVarLLVM(llvm::Type* type, const char* name) { GenInfo* info = gGenInfo; llvm::Value* val = createLLVMAlloca(info->irBuilder, type, name); info->currentStackVariables.push_back(std::pair<llvm::Value*, llvm::Type*>(val, type)); codegenLifetimeStart(type, val); return val; } llvm::Value* createVarLLVM(llvm::Type* type) { char name[32]; sprintf(name, "chpl_macro_tmp_%d", codegen_tmp++); return createVarLLVM(type, name); } // Returns n elements in a vector/array or -1 static int64_t arrayVecN(llvm::Type *t) { if( t->isArrayTy() ) { llvm::ArrayType *at = llvm::dyn_cast<llvm::ArrayType>(t); unsigned n = at->getNumElements(); return n; } else if( t->isVectorTy() ) { llvm::VectorType *vt = llvm::dyn_cast<llvm::VectorType>(t); unsigned n = vt->getNumElements(); return n; } else { return -1; } } static llvm::Type* arrayVecEltType(llvm::Type *t) { if( t->isArrayTy() ) { llvm::ArrayType *at = llvm::dyn_cast<llvm::ArrayType>(t); return at->getElementType(); } else if( t->isVectorTy() ) { llvm::VectorType *vt = llvm::dyn_cast<llvm::VectorType>(t); return vt->getElementType(); } else { return NULL; } } static bool isTypeEquivalent(const llvm::DataLayout& layout, llvm::Type* a, llvm::Type* b, bool force) { int64_t aN = arrayVecN(a); int64_t bN = arrayVecN(a); int alignA, alignB; int64_t sizeA, sizeB; if( a == b ) { return true; } else if( a->isStructTy() && b->isStructTy() ) { llvm::StructType *aTy = llvm::dyn_cast<llvm::StructType>(a); llvm::StructType *bTy = llvm::dyn_cast<llvm::StructType>(b); if( aTy->isLayoutIdentical(bTy) ) return true; // handle case like // {float, float, float, float} <=> { <2xfloat>, <2xfloat> } // fall through... } else if( aN >= 0 && aN == bN && arrayVecEltType(a) && arrayVecEltType(a) == arrayVecEltType(b) ) { return true; } alignA = layout.getPrefTypeAlignment(a); alignB = layout.getPrefTypeAlignment(b); sizeA = layout.getTypeStoreSize(a); sizeB = layout.getTypeStoreSize(b); // Are they the same size? if( sizeA == sizeB ) return true; if( !force ) return false; // Are they the same size, within alignment? if( sizeA < sizeB ) { // Try making size A bigger... if( sizeA + alignA >= sizeB ) return true; } else { // A >= B // Try making size B bigger... if( sizeB + alignB >= sizeA ) return true; } return false; } static llvm::Value *convertValueToType(llvm::Value *value, llvm::Type *newType, bool isSigned = false, bool force = false) { llvm::IRBuilder<>* irBuilder = gGenInfo->irBuilder; const llvm::DataLayout& layout = gGenInfo->module->getDataLayout(); llvm::Type *curType = value->getType(); if(curType == newType) { return value; } //Integer values if(newType->isIntegerTy() && curType->isIntegerTy()) { if(newType->getPrimitiveSizeInBits() > curType->getPrimitiveSizeInBits()) { // Sign extend if isSigned, but never sign extend single bits. if(isSigned && ! curType->isIntegerTy(1)) { return irBuilder->CreateSExtOrBitCast(value, newType); } else { return irBuilder->CreateZExtOrBitCast(value, newType); } } else { return irBuilder->CreateTruncOrBitCast(value, newType); } } //Floating point values if(newType->isFloatingPointTy() && curType->isFloatingPointTy()) { if(newType->getPrimitiveSizeInBits() > curType->getPrimitiveSizeInBits()) { return irBuilder->CreateFPExt(value, newType); } else { return irBuilder->CreateFPTrunc(value, newType); } } //Integer value to floating point value if(newType->isFloatingPointTy() && curType->isIntegerTy()) { if(isSigned) { return irBuilder->CreateSIToFP(value, newType); } else { return irBuilder->CreateUIToFP(value, newType); } } //Floating point value to integer value if(newType->isIntegerTy() && curType->isFloatingPointTy()) { return irBuilder->CreateFPToSI(value, newType); } //Integer to pointer if(newType->isPointerTy() && curType->isIntegerTy()) { return irBuilder->CreateIntToPtr(value, newType); } //Pointer to integer if(newType->isIntegerTy() && curType->isPointerTy()) { return irBuilder->CreatePtrToInt(value, newType); } //Pointers if(newType->isPointerTy() && curType->isPointerTy()) { if( newType->getPointerAddressSpace() != curType->getPointerAddressSpace() ) { assert( 0 && "Can't convert pointer to different address space"); } return irBuilder->CreatePointerCast(value, newType); } // Structure types. // This is important in order to handle clang structure expansion // (e.g. calling a function that returns {int64,int64}) if( isArrayVecOrStruct(curType) || isArrayVecOrStruct(newType) ) { if( isTypeEquivalent(layout, curType, newType, force) ) { // We turn it into a store/load to convert the type // since LLVM does not allow bit casts on structure types. llvm::Value* tmp_alloc; if( layout.getTypeStoreSize(newType) >= layout.getTypeStoreSize(curType) ) tmp_alloc = createVarLLVM(newType, ""); else { tmp_alloc = createVarLLVM(curType, ""); } // Now cast the allocation to both fromType and toType. llvm::Type* curPtrType = curType->getPointerTo(); llvm::Type* newPtrType = newType->getPointerTo(); // Now get cast pointers llvm::Value* tmp_cur = irBuilder->CreatePointerCast(tmp_alloc, curPtrType); llvm::Value* tmp_new = irBuilder->CreatePointerCast(tmp_alloc, newPtrType); irBuilder->CreateStore(value, tmp_cur); return irBuilder->CreateLoad(tmp_new); } } return NULL; } static PromotedPair convertValuesToLarger(llvm::Value *value1, llvm::Value *value2, bool isSigned1 = false, bool isSigned2 = false) { GenInfo* info = gGenInfo; return convertValuesToLarger(info->irBuilder, value1, value2, isSigned1, isSigned2); } // Sign or zero extend a value to an integer that is the size of a // pointer in the address space AS. static llvm::Value* extendToPointerSize(GenRet index, unsigned AS) { GenInfo* info = gGenInfo; const llvm::DataLayout& DL = info->module->getDataLayout(); llvm::Type* sizeTy = DL.getIntPtrType(info->module->getContext(), AS); unsigned sizeBits = DL.getTypeSizeInBits(sizeTy); unsigned idxBits = DL.getTypeSizeInBits(index.val->getType()); if (idxBits < sizeBits) { return convertValueToType(index.val, sizeTy, !index.isUnsigned); } return index.val; } static llvm::Value* createInBoundsGEP(llvm::Value* ptr, llvm::ArrayRef<llvm::Value*> idxList) { GenInfo* info = gGenInfo; if (developer || fVerify) { const llvm::DataLayout& DL = info->module->getDataLayout(); unsigned ptrBits = DL.getPointerSizeInBits(0); // Check that each idxList element is at least ptrBits big. // Otherwise, it always does signed extending, but sometimes // we want unsigned. for (auto v : idxList) { unsigned idxSize = DL.getTypeSizeInBits(v->getType()); INT_ASSERT(idxSize >= ptrBits); // consider calling extendToPointerSize at the call site } } return info->irBuilder->CreateInBoundsGEP(ptr, idxList); } #endif enum WideThingField { WIDE_GEP_LOC=0, WIDE_GEP_ADDR=1, }; static const char* wide_fields[] = {"locale", "addr", "size", NULL}; static GenRet genCommID(GenInfo* info) { return baseASTCodegen(new_CommIDSymbol(commIDMap[info->filename]++)); } // Generates code to load the wide version of an address and returns an // expression that evaluates to this address. // // The wide address is generated by a call to the runtime support // function chpl_build_wide_ptr_loc. // // The type can be passed here in case the raddr does not have a Chapel type // or in case it would be difficult to compute it. It used to be the case that // it was sometimes impossible to reference types for some arguments but // getOrMakeRefTypeDuringCodegen/getOrMakeWideTypeDuringCodegen may cover // all the cases. static GenRet codegenWideAddr(GenRet locale, GenRet raddr, Type* wideType = NULL) { GenRet ret; GenInfo* info = gGenInfo; Type* wideRefType = NULL; // either a wide class or a wide ref if( locale.chplType ) INT_ASSERT(locale.chplType == dtLocaleID->typeInfo()); if( raddr.chplType && !wideType ) { INT_ASSERT(raddr.isLVPtr != GEN_WIDE_PTR); Type* refType = NULL; if( raddr.isLVPtr == GEN_VAL ) { // Then we should have a ref or a class. INT_ASSERT(raddr.chplType == dtNil || isClass(raddr.chplType) || raddr.chplType->symbol->hasFlag(FLAG_REF)); refType = raddr.chplType; } else { // GEN_REF refType = getOrMakeRefTypeDuringCodegen(raddr.chplType); } wideRefType = getOrMakeWideTypeDuringCodegen(refType); INT_ASSERT(wideRefType); } else { wideRefType = wideType; } INT_ASSERT(wideRefType); locale = codegenValue(locale); if( !fLLVMWideOpt ) { // Create a stack-local stored wide pointer // of the appropriate type. ret = createTempVar(wideRefType); if( info->cfile ) { std::string localeAssign; std::string addrAssign; ret = codegenValue(ret); // remove the & part. localeAssign = ret.c + ".locale = " + locale.c + ";\n"; info->cStatements.push_back(localeAssign); addrAssign = ret.c + ".addr = " + raddr.c + ";\n"; info->cStatements.push_back(addrAssign); } else { #ifdef HAVE_LLVM llvm::Value* adr = info->irBuilder->CreateStructGEP( NULL, ret.val, WIDE_GEP_ADDR); llvm::Value* loc = info->irBuilder->CreateStructGEP( NULL, ret.val, WIDE_GEP_LOC); // cast address if needed. This is necessary for building a wide // NULL pointer since NULL is actually an i8*. llvm::Type* addrType = adr->getType()->getPointerElementType(); llvm::Value* addrVal = raddr.val; if (raddr.val->getType() != addrType){ addrVal = convertValueToType(addrVal, addrType); } INT_ASSERT(addrVal); info->irBuilder->CreateStore(addrVal, adr); info->irBuilder->CreateStore(locale.val, loc); #endif } // Load whatever we stored... ret = codegenValue(ret); } else { #ifdef HAVE_LLVM GenRet wideTy = wideRefType; // get the LLVM type for the wide ref. llvm::PointerType *addrType = llvm::cast<llvm::PointerType>(wideTy.type); // call GLOBAL_FN_GLOBAL_MAKE dummy function llvm::Function* fn = getMakeFn(info->module, &info->globalToWideInfo, addrType); INT_ASSERT(fn); llvm::Type* eltType = addrType->getElementType(); llvm::Type* locAddrType = llvm::PointerType::getUnqual(eltType); // Null pointers require us to possibly cast to the pointer type // we are supposed to have since null has type void*. llvm::Value* locAddr = raddr.val; locAddr = info->irBuilder->CreatePointerCast(locAddr, locAddrType); ret.val = info->irBuilder->CreateCall(fn, {locale.val, locAddr}); #endif } ret.chplType = wideRefType->getValType(); // Class pointers are "values" as far as the code generator // is concerned, unlike wide references. if (wideRefType->symbol->hasFlag(FLAG_WIDE_CLASS)) ret.isLVPtr = GEN_VAL; else ret.isLVPtr = GEN_WIDE_PTR; return ret; } // Generates a new version of a wide address which has a different // .addr part, leaving the locale part alone. static GenRet codegenWideAddrWithAddr(GenRet base, GenRet newAddr, Type* wideType = NULL) { // NOTE - if computing the entire localeID becomes one day // expensive, and it can be inferred from the pointer part, // update this to just use the node part. return codegenWideAddr(codegenRlocale(base), newAddr, wideType); } #ifdef HAVE_LLVM // Set USE_TBAA to 0 to disable the emission of Type Based Alias Analysis // metadata when generating LLVM loads or stores. // Set USE_TBAA to 1 to emit TBAA metadata with loads and stores. #define USE_TBAA 1 static void codegenInvariantStart(llvm::Type *valType, llvm::Value *addr) { GenInfo *info = gGenInfo; const llvm::DataLayout& dataLayout = info->module->getDataLayout(); uint64_t sizeInBytes; if (valType->isSized()) sizeInBytes = dataLayout.getTypeSizeInBits(valType)/8; else return; llvm::ConstantInt *size = llvm::ConstantInt::getSigned( llvm::Type::getInt64Ty(info->llvmContext), sizeInBytes); info->irBuilder->CreateInvariantStart(addr, size); } // Create an LLVM store instruction possibly adding // appropriate metadata based upon the Chapel type of val. // static llvm::StoreInst* codegenStoreLLVM(llvm::Value* val, llvm::Value* ptr, Type* valType = NULL, Type* surroundingStruct = NULL, uint64_t fieldOffset = 0, llvm::MDNode* fieldTbaaTypeDescriptor = NULL, llvm::MDNode* aliasScope = NULL, llvm::MDNode* noalias = NULL, bool addInvariantStart = false) { GenInfo *info = gGenInfo; llvm::StoreInst* ret = info->irBuilder->CreateStore(val, ptr); llvm::MDNode* tbaa = NULL; if (USE_TBAA && valType && (isClass(valType) || !valType->symbol->llvmTbaaStructCopyNode)) { if (surroundingStruct) { INT_ASSERT(fieldTbaaTypeDescriptor != info->tbaaRootNode); tbaa = info->mdBuilder->createTBAAStructTagNode( surroundingStruct->symbol->llvmTbaaAggTypeDescriptor, fieldTbaaTypeDescriptor, fieldOffset); } else { tbaa = valType->symbol->llvmTbaaAccessTag; } } if( tbaa ) ret->setMetadata(llvm::LLVMContext::MD_tbaa, tbaa); if( aliasScope ) ret->setMetadata(llvm::LLVMContext::MD_alias_scope, aliasScope); if( noalias ) ret->setMetadata(llvm::LLVMContext::MD_noalias, noalias); if(!info->loopStack.empty()) { const auto &loopData = info->loopStack.top(); // Currently, the parallel_loop_access metadata refers to the // innermost loop the instruction is in, while for some cases // this could refer to the group of loops it is in. if(loopData.parallel) ret->setMetadata("llvm.mem.parallel_loop_access", loopData.loopMetadata); } if(addInvariantStart) codegenInvariantStart(val->getType(), ptr); return ret; } static llvm::StoreInst* codegenStoreLLVM(GenRet val, GenRet ptr, Type* valType = NULL) { if( val.chplType && !valType ) valType = val.chplType; if( ptr.chplType && !valType ) { if( ptr.isLVPtr ) valType = ptr.chplType; else valType = ptr.chplType->getValType(); } llvm::Type* ptrValType = llvm::cast<llvm::PointerType>( ptr.val->getType())->getElementType(); // implicit cast in C, needs to be made explicit in LLVM // e.g. T3 = alloca i8; // T3 = (T == T2); // not actual LLVM syntax // in LLVM, boolean type is i1 if (val.val->getType() != ptrValType){ llvm::Value* v = convertValueToType(val.val, ptrValType, !val.isUnsigned); INT_ASSERT(v); val.val = v; } INT_ASSERT(!(ptr.alreadyStored && ptr.canBeMarkedAsConstAfterStore)); ptr.alreadyStored = true; return codegenStoreLLVM(val.val, ptr.val, valType, ptr.surroundingStruct, ptr.fieldOffset, ptr.fieldTbaaTypeDescriptor, ptr.aliasScope, ptr.noalias, ptr.canBeMarkedAsConstAfterStore); } // Create an LLVM load instruction possibly adding // appropriate metadata based upon the Chapel type of ptr. static llvm::LoadInst* codegenLoadLLVM(llvm::Value* ptr, Type* valType = NULL, Type* surroundingStruct = NULL, uint64_t fieldOffset = 0, llvm::MDNode* fieldTbaaTypeDescriptor = NULL, llvm::MDNode* aliasScope = NULL, llvm::MDNode* noalias = NULL, bool isConst = false) { GenInfo* info = gGenInfo; llvm::LoadInst* ret = info->irBuilder->CreateLoad(ptr); llvm::MDNode* tbaa = NULL; if (USE_TBAA && valType && (isClass(valType) || !valType->symbol->llvmTbaaStructCopyNode)) { if (surroundingStruct) { INT_ASSERT(fieldTbaaTypeDescriptor != info->tbaaRootNode); tbaa = info->mdBuilder->createTBAAStructTagNode( surroundingStruct->symbol->llvmTbaaAggTypeDescriptor, fieldTbaaTypeDescriptor, fieldOffset, isConst); } else { if( isConst ) tbaa = valType->symbol->llvmConstTbaaAccessTag; else tbaa = valType->symbol->llvmTbaaAccessTag; } } if(!info->loopStack.empty()) { const auto &loopData = info->loopStack.top(); if(loopData.parallel) ret->setMetadata(llvm::StringRef("llvm.mem.parallel_loop_access"), loopData.loopMetadata); } if( tbaa ) ret->setMetadata(llvm::LLVMContext::MD_tbaa, tbaa); if( aliasScope ) ret->setMetadata(llvm::LLVMContext::MD_alias_scope, aliasScope); if( noalias ) ret->setMetadata(llvm::LLVMContext::MD_noalias, noalias); return ret; } static llvm::LoadInst* codegenLoadLLVM(GenRet ptr, Type* valType = NULL, bool isConst = false) { if( ptr.chplType && !valType ) { if( ptr.isLVPtr ) valType = ptr.chplType; else valType = ptr.chplType->getValType(); } return codegenLoadLLVM(ptr.val, valType, ptr.surroundingStruct, ptr.fieldOffset, ptr.fieldTbaaTypeDescriptor, ptr.aliasScope, ptr.noalias, isConst); } #endif static GenRet codegenUseGlobal(const char* global) { GenInfo* info = gGenInfo; GenRet ret; if( info->cfile ) { ret.c = global; } else { #ifdef HAVE_LLVM ret = info->lvt->getValue(global); if( ! ret.val ) INT_FATAL("Could not find global %s, " "perhaps it is missing or is complicated macro?", global); assert( ret.isLVPtr != GEN_WIDE_PTR ); if( ret.isLVPtr == GEN_PTR ) { ret.val = codegenLoadLLVM(ret); } INT_ASSERT(ret.val); #endif } ret.isLVPtr = GEN_VAL; return ret; } static GenRet codegenLocaleForNode(GenRet node) { Type* localeType = LOCALE_ID_TYPE; GenRet ret; ret.chplType = localeType; node = codegenValue(node); GenRet tmp = createTempVar(localeType); GenRet anySublocale = codegenUseGlobal("c_sublocid_any"); codegenCall("chpl_buildLocaleID", node, anySublocale, codegenAddrOf(tmp), /*ln*/codegenZero(), /*fn*/ codegenZero32()); return tmp; } static GenRet codegenUseCid(Type* classType) { std::string varname; varname = varname + "chpl__cid_" + classType->symbol->cname; GenRet ret = codegenUseGlobal(varname.c_str()); ret.chplType = CLASS_ID_TYPE; return ret; } // A construct which gives the current node ID (int32_t). static GenRet codegenGetNodeID(void) { GenRet ret = codegenUseGlobal("chpl_nodeID"); ret.chplType = NODE_ID_TYPE; return ret; } // A construct which gives the current locale ID. static GenRet codegenGetLocaleID(void) { GenRet ret = codegenCallExpr("chpl_gen_getLocaleID"); ret.chplType = LOCALE_ID_TYPE; #ifdef HAVE_LLVM GenInfo* info = gGenInfo; if (!info->cfile ) { // Make sure that the result of gen_getLocaleID is // the right type (since clang likes to fold int32/int32 into int32). GenRet expectType = LOCALE_ID_TYPE; ret.val = convertValueToType(ret.val, expectType.type, false, true); assert(ret.val); } #endif return ret; } static GenRet codegenUseGlobal(std::string str) { return codegenUseGlobal(str.c_str()); } static GenRet codegenWideHere(GenRet addr, Type* wideType = NULL) { GenRet locale = codegenGetLocaleID(); GenRet addrVal = codegenValue(addr); GenRet ret = codegenWideAddr(locale, addrVal, wideType); return ret; } static bool isWide(GenRet x) { if( x.isLVPtr == GEN_WIDE_PTR ) return true; if( x.chplType && x.chplType->isWidePtrType() ) return true; return false; } // This function takes in something already code-generated that should be some // sort of wide thing (isLVPtr == GEN_WIDE_PTR, or wide ref or wide class). // It returns the local reference type and sets *wideRefTypeOut // to the wide reference type. static Type* getRefTypesForWideThing(GenRet wide, Type** wideRefTypeOut) { Type* ret = NULL; Type* wideRefType = NULL; if( wide.chplType ) { // Set the resulting Chapel type. if( wide.isLVPtr == GEN_WIDE_PTR ) { // wide lv-pointer, e.g. to int, // so we return a reference to int. ret = getOrMakeRefTypeDuringCodegen(wide.chplType); wideRefType = getOrMakeWideTypeDuringCodegen(ret); } else { // local lv-pointer or value; in such cases they are wide // only if they are a wide reference or a wide class. // Then the wide type is the current Chapel type. if( wide.chplType->symbol->hasEitherFlag(FLAG_WIDE_REF,FLAG_WIDE_CLASS) ) { ret = wide.chplType->getField("addr")->typeInfo(); wideRefType = wide.chplType; } else { INT_ASSERT(0); // Not a wide thing. } } } if( wideRefTypeOut ) *wideRefTypeOut = wideRefType; return ret; } // This function casts a wide pointer to a void* wide pointer (ie wide_ptr_t) // for use with packed wide pointers. /* static GenRet codegenCastWideToVoid(GenRet wide) { INT_ASSERT(wide.isLVPtr == GEN_WIDE_PTR || (wide.chplType && wide.chplType->symbol->hasEitherFlag(FLAG_WIDE_REF,FLAG_WIDE_CLASS))); // If we have a local pointer to a wide reference, // codegen value it. if( wide.isLVPtr == GEN_PTR ) { wide = codegenValue(wide); } // If we don't already have a wide reference - that is, if // wide.isLVPtr == GEN_WIDE_PTR - convert it to a Chapel reference in order // to create a temporary variable and have fewer cases below. if( wide.isLVPtr == GEN_WIDE_PTR ) { wide = codegenAddrOf(wide); // The result is wide.isLVPtr == GEN_VAL but wide.chplType is a wide ref } return codegenCast("wide_ptr_t", wide); } */ // Extract a field of a wide string/ptr, returning an lvalue-pointer to the that // field if we have a pointer to the wide string/ptr. We need this function // because codegenRaddr and friends now work with void wide pointer data-types // (and wide strings are not the same as other wide types), and because // codegenFieldPtr doesn't work to extract wide string fields (since it thinks // it's supposed to be extracting fields from the class rather than from the // wide ptr). // // Works for wide strings or wide pointers. // // field is WIDE_GEP_LOC, WIDE_GEP_ADDR static GenRet codegenWideThingField(GenRet ws, WideThingField field) { GenRet ret; GenInfo* info = gGenInfo; INT_ASSERT(field == WIDE_GEP_LOC || field == WIDE_GEP_ADDR); if( field == WIDE_GEP_LOC ) { ret.chplType = LOCALE_ID_TYPE; } else if( field == WIDE_GEP_ADDR ) { // get the local reference type // this will probably be overwritten by the caller, // but it is used below in the LLVM code. ret.chplType = getRefTypesForWideThing(ws, NULL); } const char* fname = wide_fields[field]; if( info->cfile ) { if (ws.isLVPtr == GEN_PTR) { ret.isLVPtr = GEN_PTR; ret.c += "&((" + ws.c + ")->" + fname + ")"; } else { // This case handles GEN_WIDE_PTR or GEN_VAL // we don't have an l-value for this one. // Could be wide lv-ptr or GEN_VAL wide ref. ret.isLVPtr = GEN_PTR; ret.c += "&((" + ws.c + ")." + fname + ")"; } } else { #ifdef HAVE_LLVM if ( !fLLVMWideOpt ) { if (ws.val->getType()->isPointerTy()){ ret.isLVPtr = GEN_PTR; ret.val = info->irBuilder->CreateConstInBoundsGEP2_32( NULL, ws.val, 0, field); } else { ret.isLVPtr = GEN_VAL; ret.val = info->irBuilder->CreateExtractValue(ws.val, field); } assert(ret.val); } else { // Workaround: for LLVMWideOpt, get pointers to parts // of addresses, but only support that when they are rvalues. // TODO: replace this code with an assert. // It would probably be better to fix InsertWideReferences. // The problematic pattern comes up when the optimization // local _array -> local _array._instance fires in the // array's deinit/_do_destroy code. if( field == WIDE_GEP_LOC ) { ret = createTempVarWith(codegenRlocale(ws)); } else if( field == WIDE_GEP_ADDR ) { ret = createTempVarWith(codegenRaddr(ws)); } } #endif } return ret; } // Generates code to load the remote address from a wide address. // Always returns the address portion of the wide pointer as a value. // The .chplType of the result will be a reference or class type. GenRet codegenRaddr(GenRet wide) { GenRet ret; Type* wideRefType = NULL; Type* type = NULL; type = getRefTypesForWideThing(wide, &wideRefType); if( !fLLVMWideOpt ) { ret = codegenValue(codegenWideThingField(wide, WIDE_GEP_ADDR)); } else { #ifdef HAVE_LLVM GenInfo* info = gGenInfo; if (wide.isLVPtr == GEN_PTR) wide = codegenValue(wide); GenRet wideTy = wideRefType; // get the LLVM type for the wide ref. llvm::PointerType *addrType = llvm::cast<llvm::PointerType>(wideTy.type); // call GLOBAL_FN_GLOBAL_ADDR dummy function llvm::Function* fn = getAddrFn(info->module, &info->globalToWideInfo, addrType); INT_ASSERT(fn); ret.val = info->irBuilder->CreateCall(fn, wide.val); #endif ret = codegenCast(type, ret); } ret.chplType = type; return ret; } // Generates code to load the remote locale from a wide address static GenRet codegenRlocale(GenRet wide) { GenRet ret; Type* type = LOCALE_ID_TYPE; if( !fLLVMWideOpt ) { ret = codegenWideThingField(wide, WIDE_GEP_LOC); } else { #ifdef HAVE_LLVM Type* wideRefType = NULL; GenInfo* info = gGenInfo; getRefTypesForWideThing(wide, &wideRefType); if (wide.isLVPtr == GEN_PTR) wide = codegenValue(wide); GenRet wideTy = wideRefType; // get the LLVM type for the wide ref. llvm::PointerType *addrType = llvm::cast<llvm::PointerType>(wideTy.type); // call GLOBAL_FN_GLOBAL_LOCID dummy function llvm::Function* fn = getLocFn(info->module, &info->globalToWideInfo, addrType); INT_ASSERT(fn); ret.val = info->irBuilder->CreateCall(fn, wide.val); #endif } ret.chplType = type; return ret; } static GenRet codegenRnode(GenRet wide){ GenRet ret; Type* type = NODE_ID_TYPE; if( !fLLVMWideOpt ) { ret = codegenCallExpr("chpl_nodeFromLocaleID", codegenAddrOf(codegenValuePtr( codegenWideThingField(wide, WIDE_GEP_LOC))), /*ln*/codegenZero(), /*fn*/codegenZero32()); } else { #ifdef HAVE_LLVM Type* wideRefType = NULL; GenInfo* info = gGenInfo; getRefTypesForWideThing(wide, &wideRefType); if (wide.isLVPtr == GEN_PTR) wide = codegenValue(wide); GenRet wideTy = wideRefType; // get the LLVM type for the wide ref. llvm::PointerType *addrType = llvm::cast<llvm::PointerType>(wideTy.type); // call GLOBAL_FN_GLOBAL_NODEID dummy function llvm::Function* fn = getNodeFn(info->module, &info->globalToWideInfo, addrType); INT_ASSERT(fn); ret.val = info->irBuilder->CreateCall(fn, wide.val); #endif } ret.chplType = type; return ret; } static const int field_normal = 0; static const int field_cid = 1; static const int field_uid = 2; static const int field_other = 3; // Generates code to produce a pointer to the member (ie a field). // Does not normally do any loads,stores,puts,or gets; // just does address arithmetic. The exception is if it has // to read an lvalue or when we have a reference to a class. // // This function handles the following cases: // 1 base.chplType is a Chapel class // 2 base.chplType is a Chapel wide class // 3 base.chplType is a Chapel record and base.isLVPtr is set // 4 base.chplType is a Chapel union and base.isLVPtr is set // 5 base.chplType is a Chapel reference or wide reference type to a record // 6 base.chplType is a Chapel reference or wide reference type to a union // 7 base.chplType is a Chapel reference or wide reference to // a class or wide class (* causes a load) // // In addition, it handles some special cases which are not reflected // in the Chapel type system, like getting the class ID or union ID // fields. // // In any case, returns a GEN_PTR or GEN_WIDE_PTR to the field. // // This is equivalent to C (assuming x has ptr type e.g. struct mystruct*) // & x->myfield // static GenRet doCodegenFieldPtr( GenRet base, const char *c_field_name, const char* chpl_field_name, int special /* field_normal,field_cid, or field_uid */ ) { GenInfo* info = gGenInfo; GenRet ret; Type* baseType = base.chplType; AggregateType* ct = NULL; Type* castType = NULL; if( special == field_normal ) { INT_ASSERT(baseType); } if( baseType ) { // Reduce the Chapel reference or wide reference cases // to GEN_PTR or GEN_WIDE_PTR cases. if (baseType->symbol->hasEitherFlag(FLAG_REF,FLAG_WIDE_REF)) { base = codegenDeref(base); return doCodegenFieldPtr(base, c_field_name, chpl_field_name, special); } } if( ! fLLVMWideOpt ) { // Reduce GEN_WIDE_PTR or FLAG_WIDE_CLASS cases to local versions // and rebuild addresses. if( base.isLVPtr == GEN_WIDE_PTR || (baseType && baseType->symbol->hasFlag(FLAG_WIDE_CLASS)) ) { GenRet addr; addr = codegenRaddr(base); addr = doCodegenFieldPtr(addr, c_field_name, chpl_field_name, special); ret = codegenWideAddrWithAddr(base, addr); return ret; } } if( baseType ) { // At this point, baseType should be a record, union, class, or wide class // All of these types are in the AggregateType AST node. ct = toAggregateType(baseType); INT_ASSERT(ct); if ( isClass(ct) ) { // ok, we have a class type. We should codegenValue // to make sure we have no extra indirection. base = codegenValue(base); } else if ( baseType->symbol->hasFlag(FLAG_WIDE_CLASS)) { // Get the local version of the class (because it has the fields) base = codegenValue(base); baseType = baseType->getField("addr")->typeInfo(); ct = toAggregateType(baseType); } else { // Must be a record or union type, and we must have an // lvalue-ptr to one of them. INT_ASSERT(isRecord(ct) || isUnion(ct)); INT_ASSERT( base.isLVPtr != GEN_VAL ); } } // No Chapel field name? it must be special. if( !chpl_field_name && !special ) special = field_other; if( special ) { if( special == field_cid ) { INT_ASSERT( ct && isClass(ct) ); ret.chplType = CLASS_ID_TYPE; castType = dtObject; } else if( special == field_uid ) { ret.chplType = UNION_ID_TYPE; } else { ret.chplType = NULL; } } else if( ct ) { // The field might be in a base class, so we // cast to the right base class type. If the field // is in the class, there is no need to cast. Symbol* fieldSymbol = ct->getField(chpl_field_name); if( isClass(ct) ) { castType = fieldSymbol->defPoint->parentSymbol->typeInfo(); if( castType == ct ) castType = NULL; } ret.chplType = fieldSymbol->type; } ret.isLVPtr = GEN_PTR; if (isClass(ct) ) { base = codegenValue(base); } else { // not a class. base is a lvalue pointer. if( !fLLVMWideOpt ) INT_ASSERT(base.isLVPtr == GEN_PTR); else INT_ASSERT(base.isLVPtr != GEN_VAL); } if( info->cfile ) { ret.c = '&'; ret.c += "("; if( castType ) ret.c += codegenCast(castType,base).c; else ret.c += "(" + base.c + ")"; ret.c += "->"; if (isUnion(ct) && !special) ret.c += "_u."; ret.c += c_field_name; ret.c += ")"; } else { #ifdef HAVE_LLVM // LLVM codegen llvm::Value* baseValue = base.val; // with LLVMWideOpt, we might return a wide ptr. if( fLLVMWideOpt && isWide(base) ) ret.isLVPtr = GEN_WIDE_PTR; // cast if needed if (castType) { Type* useCastType = castType; if (fLLVMWideOpt && isWide(base)) useCastType = getOrMakeWideTypeDuringCodegen(castType); llvm::Type* castTypeLLVM = useCastType->codegen().type; baseValue = convertValueToType(base.val, castTypeLLVM, !base.isUnsigned); INT_ASSERT(baseValue); } AggregateType *cBaseType = castType ? toAggregateType(castType) : ct; // We need the LLVM type of the field we're getting INT_ASSERT(ret.chplType); GenRet retType = ret.chplType; if( isUnion(ct) && !special ) { // Get a pointer to the union data then cast it to the right type bool unused; ret.val = info->irBuilder->CreateStructGEP( NULL, baseValue, cBaseType->getMemberGEP("_u", unused)); llvm::PointerType* ty = llvm::PointerType::get(retType.type, baseValue->getType()->getPointerAddressSpace()); // Now cast it to the right type. ret.val = convertValueToType(ret.val, ty, false); INT_ASSERT(ret.val); } else { // Normally, we just use a GEP. bool isCArrayField = false; int fieldno = cBaseType->getMemberGEP(c_field_name, isCArrayField); if (isCArrayField && ret.chplType->getValType()->symbol->hasFlag(FLAG_C_PTR_CLASS)) { // Accessing field that is a C array declared with c_ptr(eltType) // should result in a pointer to the first element. ret.val = info->irBuilder->CreateStructGEP(NULL, baseValue, fieldno); ret.val = info->irBuilder->CreateStructGEP(NULL, ret.val, 0); ret.isLVPtr = GEN_VAL; } else { ret.val = info->irBuilder->CreateStructGEP(NULL, baseValue, fieldno); if ((isClass(ct) || isRecord(ct)) && cBaseType->symbol->llvmTbaaAggTypeDescriptor && ret.chplType->symbol->llvmTbaaTypeDescriptor != info->tbaaRootNode) { llvm::StructType *structType = llvm::cast<llvm::StructType> (llvm::cast<llvm::PointerType> (baseValue->getType())->getElementType()); ret.surroundingStruct = cBaseType; ret.fieldOffset = info->module->getDataLayout(). getStructLayout(structType)->getElementOffset(fieldno); ret.fieldTbaaTypeDescriptor = ret.chplType->symbol->llvmTbaaTypeDescriptor; } } } // Propagate noalias scopes if (base.aliasScope) ret.aliasScope = base.aliasScope; if (base.noalias) ret.noalias = base.noalias; #endif } return ret; } static GenRet codegenFieldPtr(GenRet base, Expr* field) { const char* cname = NULL; const char* name = NULL; GenRet genBase = base; if(DefExpr *de = toDefExpr(field)) { cname = de->sym->cname; name = de->sym->name; } else if(SymExpr *se = toSymExpr(field)) { cname = se->symbol()->cname; name = se->symbol()->name; } else if(NamedExpr *ne = toNamedExpr(field)) { cname = name = ne->name; } else { INT_FATAL("Unknown field in codegenFieldPtr"); } return doCodegenFieldPtr(genBase, cname, name, field_normal); } static GenRet codegenFieldCidPtr(GenRet base) { GenRet ret = doCodegenFieldPtr(base, "chpl__cid", NULL, field_cid); //if( ! ret.chplType ) ret.chplType = CLASS_ID_TYPE; return ret; } static GenRet codegenFieldUidPtr(GenRet base) { GenRet ret = doCodegenFieldPtr(base, "_uid", NULL, field_uid); //if( ! ret.chplType ) ret.chplType = UNION_ID_TYPE; return ret; } // Generates code to produce a pointer an array element. // // Handles the following cases: // 1 base.chplType is a data class (ie _ddata) // 2 base.chplType is a wide data class // 3 base.chplType is a homogeneous tuple (aka star tuple) and isLVPtr != 0 // 4 base.chplType is a Chapel reference or wide reference // to a data class, wide data class, or homogeneous tuple. // // In any case, returns a GEN_PTR or GEN_WIDE_PTR to the element. // // This is equivalent to C (assuming ptr is a pointer type) // ptr + i // If ddataPtr is true, we return a pointer to the element. This is // currently only used for the PRIM_ARRAY_SHIFT_BASE_POINTER case. // static GenRet codegenElementPtr(GenRet base, GenRet index, bool ddataPtr=false) { GenRet ret; GenInfo* info = gGenInfo; Type* baseType = NULL; Type* eltType = NULL; std::string addr; bool isStarTuple = false; INT_ASSERT(base.chplType); // Handle references to arrays or star tuples // by converting them to isLVPtr != GEN_VAL if( base.chplType->symbol->hasEitherFlag(FLAG_REF,FLAG_WIDE_REF) ) { base = codegenDeref(base); } baseType = base.chplType; // Now we should either have: // - wide data class // - data class // - star tuple with isLVPtr != 0 if( ! fLLVMWideOpt ) { // Convert wide pointer operations to the local counterparts. if( base.isLVPtr == GEN_WIDE_PTR || baseType->symbol->hasFlag(FLAG_WIDE_CLASS) ) { GenRet newAddr = codegenElementPtr(codegenRaddr(base), index, ddataPtr); if (ddataPtr) { GenRet ret = codegenWideAddrWithAddr(base, newAddr, baseType); // Tell the compiler this is a ddata pointer not a ref to an element ret.isLVPtr = GEN_PTR; ret.chplType = base.chplType; ret.isUnsigned = true; return ret; } else { return codegenWideAddrWithAddr(base, newAddr); } } } ret.isLVPtr = GEN_PTR; if( fLLVMWideOpt && isWide(base) ) ret.isLVPtr = GEN_WIDE_PTR; if( baseType->symbol->hasFlag(FLAG_STAR_TUPLE) ) { eltType = baseType->getField("x1")->typeInfo(); isStarTuple = true; // Star tuples should only be passed by reference here... INT_ASSERT(base.isLVPtr != GEN_VAL); } else if (baseType->symbol->hasFlag(FLAG_C_ARRAY)) { eltType = toAggregateType(baseType)->cArrayElementType(); isStarTuple = true; } else if( baseType->symbol->hasFlag(FLAG_DATA_CLASS) ) { eltType = getDataClassType(baseType->symbol)->typeInfo(); isStarTuple = false; } if (ddataPtr) { // Tell the compiler this is a ddata pointer not a ref to an element ret.chplType = baseType; ret.isUnsigned = true; } else { ret.chplType = eltType; } index = codegenValue(index); if( !isStarTuple ) base = codegenValue(base); if( info->cfile ) { base = codegenValue(base); // even for tuple, for style. ret.c = "(" + base.c + " + " + index.c + ")"; } else { #ifdef HAVE_LLVM unsigned AS = base.val->getType()->getPointerAddressSpace(); // in LLVM, arrays are not pointers and cannot be used in // calls to CreateGEP, CreateCall, CreateStore, etc. // so references to arrays must be used instead // (i.e. if it is a reference to an array, do not deref) std::vector<llvm::Value *> GEPLocs; // add zero as first index if tuple if (isStarTuple){ GEPLocs.push_back( llvm::Constant::getNullValue( llvm::IntegerType::getInt64Ty(info->module->getContext()))); } GEPLocs.push_back(extendToPointerSize(index, AS)); ret.val = createInBoundsGEP(base.val, GEPLocs); // Propagate noalias scopes if (base.aliasScope) ret.aliasScope = base.aliasScope; if (base.noalias) ret.noalias = base.noalias; #endif } return ret; } static GenRet createTempVar(const char* ctype) { GenInfo* info = gGenInfo; GenRet ret; char name[32]; sprintf(name, "chpl_macro_tmp_%d", codegen_tmp++); ret.isLVPtr = GEN_PTR; if( info->cfile ) { // Add a temporary variable info->cLocalDecls.push_back(std::string(ctype) + " " + name); ret.c = std::string("&") + name; } else { #ifdef HAVE_LLVM llvm::Type* llTy = info->lvt->getType(ctype); INT_ASSERT(llTy); ret.val = createVarLLVM(llTy, name); #endif } return ret; } // use this function for chplTypes static GenRet createTempVar(Type* t) { GenInfo* info = gGenInfo; GenRet ret; if( info->cfile ) { // Just use the C-name. ret = createTempVar(t->symbol->cname); } else { #ifdef HAVE_LLVM // We need to code-generate the type in the event // that it does not exist. That happens for some // types that are constructed during code generation // (to do with references and references pointers) // It's not a problem for C since the type will // be added to the header before the C compiler runs. GenRet tmp = t; llvm::Type* llTy = tmp.type; INT_ASSERT(llTy); ret.isLVPtr = GEN_PTR; ret.val = createVarLLVM(llTy); #endif } ret.chplType = t; return ret; } GenRet createTempVarWith(GenRet v) { GenInfo* info = gGenInfo; Type* t = v.chplType; INT_ASSERT(t); GenRet ret = createTempRef(t); ret.isUnsigned = v.isUnsigned; // now store into the temp var the value we have. if( info->cfile ) { std::string stmt = codegenValue(ret).c + " = " + codegenValue(v).c + ";\n"; info->cStatements.push_back(stmt); } else { #ifdef HAVE_LLVM codegenStoreLLVM(codegenValue(v), ret); #endif } return ret; } // For C code generation // Codegen *(ptr), but we optimize away // & or &(something) // if GenRet is a wide pointer, we will emit a 'get'. // For a star tuple, if we have a reference to a star tuple, // returns the base address. GenRet codegenValue(GenRet r) { GenInfo* info = gGenInfo; GenRet ret = r; ret.isLVPtr = GEN_VAL; if( r.isLVPtr == GEN_VAL ) return ret; if( r.isLVPtr == GEN_WIDE_PTR && !fLLVMWideOpt) { // with fLLVMWideOpt, we can just load directly below. assert(r.chplType); // Emit a temporary. // Assign from wide pointer value into temporary // Return local pointer to temporary ret = createTempRef(r.chplType); codegenAssign(ret, r); return codegenValue(ret); } // At this point r.isPtr == GEN_PTR. if( r.chplType ) { // If we have a Chapel type, propagate it. ret.chplType = r.chplType; // NOT value type if it's a reference, since // codegenValue on a Chapel reference just returns the pointer! } if( info->cfile ) { INT_ASSERT(r.c.length() > 0); if( r.c[0] == '&' ) { if( r.c[1] == '(' && r.c[r.c.length()-1] == ')' ) { // we have &(something) ret.c = r.c.substr(2, r.c.length()-3); } else { // we have &something ret.c = r.c.substr(1, r.c.length()-1); } } else if( r.c[0] == '(' && r.c[r.c.length()-1] == ')') { // we have (something) ret.c = "*" + r.c; } else { ret.c = "*(" + r.c + ")"; } } else { #ifdef HAVE_LLVM if (r.isLVPtr) { // But don't dereference star tuples (since C views these as arrays) if( r.chplType && r.chplType->symbol->hasFlag(FLAG_STAR_TUPLE) ) { ret.val = r.val; ret.isLVPtr = r.isLVPtr; } else ret.val = codegenLoadLLVM(r); // TODO - is r pointer to const? } else { ret.val = r.val; } #endif } return ret; } // Create a temporary value holding r and return a pointer to it. // If r is already a pointer, do nothing. // Does not handle homogeneous tuples. // Does not handle wide pointers. GenRet codegenValuePtr(GenRet r) { GenRet ret = r; // In codegen, 'nil' has to be treated like literal value. Specifically, // in remote puts, it has to be copied into a temporary first, and the address // of the temporary used as the local buffer address in chpl_gen_comm_put(). if( ret.isLVPtr == GEN_PTR && r.chplType != dtNil) return ret; if( r.chplType ) { bool isStarTuple = r.chplType->symbol->hasFlag(FLAG_STAR_TUPLE); INT_ASSERT(!isStarTuple); } INT_ASSERT(r.isLVPtr != GEN_WIDE_PTR); ret = createTempVarWith(r); return ret; } // Converts an L-value pointer into a // pointer value, so that it can for example // be stored in another pointer. static GenRet codegenAddrOf(GenRet r) { GenRet ret = r; if (r.isLVPtr == GEN_WIDE_PTR) { if(r.chplType) { Type* refType = getOrMakeRefTypeDuringCodegen(r.chplType); ret.chplType = getOrMakeWideTypeDuringCodegen(refType); } ret.isLVPtr = GEN_VAL; return ret; } else if( r.isLVPtr == GEN_PTR ) { if(r.chplType) ret.chplType = getOrMakeRefTypeDuringCodegen(r.chplType); ret.isLVPtr = GEN_VAL; } else { INT_FATAL("misuse of codegenAddrOf"); } return ret; } // Converts an L-value pointer into a // pointer value, so that it can for example // be stored in another pointer. // If we start with a wide pointer, we just discard // the locale portion (ie assume it is local). static GenRet codegenLocalAddrOf(GenRet r) { if (r.isLVPtr == GEN_WIDE_PTR) { return codegenRaddr(r); } return codegenAddrOf(r); } GenRet codegenLocalDeref(GenRet r) { GenRet ret; // LocalDeref on a wide pointer should just give // the address field as a reference. if( r.chplType && r.chplType->symbol->hasFlag(FLAG_WIDE_REF) ) { ret = codegenRaddr(r); return ret; } // For some reason, ArgSymbol might not have a real Chapel // reference type, so we have this function as a workaround // (instead of running codegenDeref with chplType=type->refType ) ret = codegenValue(r); ret.isLVPtr = GEN_PTR; if( r.chplType ) ret.chplType = r.chplType->getValType(); return ret; } // codegenValue(r) to remove & or add * (if & already removed) and sets isLVPtr GenRet codegenDeref(GenRet r) { GenRet ret; INT_ASSERT(r.chplType); if (r.chplType->symbol->hasEitherFlag(FLAG_WIDE_REF, FLAG_WIDE_CLASS)) { ret = codegenValue(r); ret.isLVPtr = GEN_WIDE_PTR; ret.chplType = r.chplType->getValType(); } else if ( r.chplType->symbol->hasFlag(FLAG_REF) ){ return codegenLocalDeref(r); } else { //when an svec member value is returned and it is actually an address INT_ASSERT(0); // not a reference. } return ret; } static GenRet codegenEquals(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); ret.chplType = dtBool; if( info->cfile ) ret.c = "(" + av.c + " == " + bv.c + ")"; else { #ifdef HAVE_LLVM // if type mismatch, create cast on RHS if (av.val->getType() != bv.val->getType()){ bv.val = convertValueToType(bv.val, av.val->getType(), !bv.isUnsigned); INT_ASSERT(bv.val); } if( av.val->getType()->isFPOrFPVectorTy() ) { ret.val = info->irBuilder->CreateFCmpOEQ(av.val, bv.val); } else { ret.val = info->irBuilder->CreateICmpEQ(av.val, bv.val); } #endif } return ret; } static GenRet codegenNotEquals(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); ret.chplType = dtBool; if( info->cfile ) ret.c = "(" + av.c + " != " + bv.c + ")"; else { #ifdef HAVE_LLVM // if type mismatch, create cast on RHS if (av.val->getType() != bv.val->getType()){ bv.val = convertValueToType(bv.val, av.val->getType(), !bv.isUnsigned); INT_ASSERT(bv.val); } if( av.val->getType()->isFPOrFPVectorTy() ) { ret.val = info->irBuilder->CreateFCmpUNE(av.val, bv.val); } else { ret.val = info->irBuilder->CreateICmpNE(av.val, bv.val); } #endif } return ret; } static GenRet codegenLessEquals(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); ret.chplType = dtBool; if( info->cfile ) ret.c = "(" + av.c + " <= " + bv.c + ")"; else { #ifdef HAVE_LLVM PromotedPair values = convertValuesToLarger( av.val, bv.val, is_signed(av.chplType), is_signed(bv.chplType)); if (values.a->getType()->isFPOrFPVectorTy()) { ret.val = gGenInfo->irBuilder->CreateFCmpOLE(values.a, values.b); } else if (!values.isSigned) { ret.val = gGenInfo->irBuilder->CreateICmpULE(values.a, values.b); } else { ret.val = gGenInfo->irBuilder->CreateICmpSLE(values.a, values.b); } #endif } return ret; } static GenRet codegenLogicalOr(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); ret.chplType = dtBool; if( info->cfile ) ret.c = "(" + av.c + " || " + bv.c + ")"; else { #ifdef HAVE_LLVM ret.val = info->irBuilder->CreateOr(info->irBuilder->CreateIsNotNull(av.val), info->irBuilder->CreateIsNotNull(bv.val)); #endif } return ret; } static GenRet codegenLogicalAnd(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); ret.chplType = dtBool; if( info->cfile ) ret.c = "(" + av.c + " && " + bv.c + ")"; else { #ifdef HAVE_LLVM ret.val = info->irBuilder->CreateAnd(info->irBuilder->CreateIsNotNull(av.val), info->irBuilder->CreateIsNotNull(bv.val)); #endif } return ret; } static GenRet codegenAdd(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); if( info->cfile ) ret.c = "(" + av.c + " + " + bv.c + ")"; else { #ifdef HAVE_LLVM bool a_signed = false; bool b_signed = false; if( av.chplType ) a_signed = is_signed(av.chplType); if( bv.chplType ) b_signed = is_signed(bv.chplType); if (av.chplType == dtComplex[COMPLEX_SIZE_64]) { ret = codegenCallExpr("complexAdd64", av, bv); } else if (av.chplType == dtComplex[COMPLEX_SIZE_128]) { ret = codegenCallExpr("complexAdd128", av, bv); } else if(av.val->getType()->isPointerTy() || bv.val->getType()->isPointerTy()) { // Handle pointer arithmetic ( e.g. int8* + int64) // We must have one integer and one pointer, not two pointers. GenRet *ptr = NULL; GenRet *i = NULL; if(av.val->getType()->isPointerTy()) ptr = &av; else i = &av; if(bv.val->getType()->isPointerTy()) ptr = &bv; else i = &bv; // We must have a pointer and an integer. INT_ASSERT(ptr && i); unsigned AS = ptr->val->getType()->getPointerAddressSpace(); // Emit a GEP instruction to do the addition. ret.isUnsigned = true; // returning a pointer, consider them unsigned ret.val = createInBoundsGEP(ptr->val, extendToPointerSize(*i, AS)); } else { PromotedPair values = convertValuesToLarger(av.val, bv.val, a_signed, b_signed); if(values.a->getType()->isFPOrFPVectorTy()) { ret.val = info->irBuilder->CreateFAdd(values.a, values.b); } else { // Purpose of adding values.isSigned is to generate 'nsw' argument // to add instruction if addition happens to be between signed integers. // This causes overflowing on adding to be undefined behaviour as in C. ret.val = info->irBuilder->CreateAdd(values.a, values.b, "", false, values.isSigned); } ret.isUnsigned = !values.isSigned; } #endif } return ret; } static GenRet codegenSub(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); if( info->cfile ) ret.c = "(" + av.c + " - " + bv.c + ")"; else { #ifdef HAVE_LLVM bool a_signed = false; bool b_signed = false; if( av.chplType ) a_signed = is_signed(av.chplType); if( bv.chplType ) b_signed = is_signed(bv.chplType); if (av.chplType == dtComplex[COMPLEX_SIZE_64]) { ret = codegenCallExpr("complexSubtract64", av, bv); } else if (av.chplType == dtComplex[COMPLEX_SIZE_128]) { ret = codegenCallExpr("complexSubtract128", av, bv); } else if(av.val->getType()->isPointerTy()) { // Handle pointer arithmetic by calling codegenAdd // with a negative value. INT_ASSERT(bv.val->getType()->isIntegerTy()); GenRet negbv; negbv.val = info->irBuilder->CreateNSWNeg(bv.val); negbv.isUnsigned = false; ret = codegenAdd(av, negbv); } else { PromotedPair values = convertValuesToLarger(av.val, bv.val, a_signed, b_signed); if(values.a->getType()->isFPOrFPVectorTy()) { ret.val = info->irBuilder->CreateFSub(values.a, values.b); } else { ret.val = info->irBuilder->CreateSub(values.a, values.b, "", false, values.isSigned); } ret.isUnsigned = !values.isSigned; } #endif } return ret; } static GenRet codegenNeg(GenRet a) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); GenRet av = codegenValue(a); if( info->cfile ) ret.c = "(-" + av.c + ")"; else { #ifdef HAVE_LLVM llvm::Value *value = av.val; if (av.chplType == dtComplex[COMPLEX_SIZE_64]) { ret = codegenCallExpr("complexUnaryMinus64", av); } else if (av.chplType == dtComplex[COMPLEX_SIZE_128]) { ret = codegenCallExpr("complexUnaryMinus128", av); } else if(value->getType()->isFPOrFPVectorTy()) { ret.val = info->irBuilder->CreateFNeg(value); } else { bool av_signed = false; if(av.chplType) av_signed = is_signed(av.chplType); ret.val = info->irBuilder->CreateNeg(value, "", false, av_signed); } ret.isUnsigned = false; #endif } return ret; } static GenRet codegenMul(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); if( info->cfile ) ret.c = "(" + av.c + " * " + bv.c + ")"; else { #ifdef HAVE_LLVM bool a_signed = false; bool b_signed = false; if( av.chplType ) a_signed = is_signed(av.chplType); if( bv.chplType ) b_signed = is_signed(bv.chplType); if (av.chplType == dtComplex[COMPLEX_SIZE_64]) { ret = codegenCallExpr("complexMultiply64", av, bv); } else if (av.chplType == dtComplex[COMPLEX_SIZE_128]) { ret = codegenCallExpr("complexMultiply128", av, bv); } else { PromotedPair values = convertValuesToLarger(av.val, bv.val, a_signed, b_signed); if(values.a->getType()->isFPOrFPVectorTy()) { ret.val = info->irBuilder->CreateFMul(values.a, values.b); } else { ret.val = info->irBuilder->CreateMul(values.a, values.b, "", false, values.isSigned); } ret.isUnsigned = !values.isSigned; } #endif } return ret; } static GenRet codegenDiv(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); if( info->cfile ) ret.c = "(" + av.c + " / " + bv.c + ")"; else { #ifdef HAVE_LLVM if (av.chplType == dtComplex[COMPLEX_SIZE_64]) { ret = codegenCallExpr("complexDivide64", av, bv); } else if (av.chplType == dtComplex[COMPLEX_SIZE_128]) { ret = codegenCallExpr("complexDivide128", av, bv); } else { PromotedPair values = convertValuesToLarger(av.val, bv.val, is_signed(av.chplType), is_signed(bv.chplType)); if(values.a->getType()->isFPOrFPVectorTy()) { ret.val = info->irBuilder->CreateFDiv(values.a, values.b); } else { if(!values.isSigned) { ret.val = info->irBuilder->CreateUDiv(values.a, values.b); } else { ret.val = info->irBuilder->CreateSDiv(values.a, values.b); } } } #endif } return ret; } static GenRet codegenMod(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); if( info->cfile ) ret.c = "(" + av.c + " % " + bv.c + ")"; else { #ifdef HAVE_LLVM PromotedPair values = convertValuesToLarger(av.val, bv.val, is_signed(av.chplType), is_signed(bv.chplType)); if(values.a->getType()->isFPOrFPVectorTy()) { ret.val = info->irBuilder->CreateFRem(values.a, values.b); } else { if(!values.isSigned) { ret.val = info->irBuilder->CreateURem(values.a, values.b); } else { ret.val = info->irBuilder->CreateSRem(values.a, values.b); } } #endif } return ret; } static GenRet codegenLsh(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); if( info->cfile ) ret.c = "(" + av.c + " << " + bv.c + ")"; else { #ifdef HAVE_LLVM llvm::Value* amt = convertValueToType(bv.val, av.val->getType(), is_signed(bv.chplType)); bool av_signed = false; if(av.chplType) av_signed = is_signed(av.chplType); ret.val = info->irBuilder->CreateShl(av.val, amt, "", false, av_signed); #endif } return ret; } static GenRet codegenRsh(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); if( info->cfile ) ret.c = "(" + av.c + " >> " + bv.c + ")"; else { #ifdef HAVE_LLVM llvm::Value* amt = convertValueToType(bv.val, av.val->getType(), is_signed(bv.chplType)); if(!is_signed(a.chplType)) { ret.val = info->irBuilder->CreateLShr(av.val, amt); } else { ret.val = info->irBuilder->CreateAShr(av.val, amt); } #endif } return ret; } static GenRet codegenAnd(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); if( info->cfile ) ret.c = "(" + av.c + " & " + bv.c + ")"; else { #ifdef HAVE_LLVM PromotedPair values = convertValuesToLarger(av.val, bv.val, is_signed(av.chplType), is_signed(bv.chplType)); ret.val = info->irBuilder->CreateAnd(values.a, values.b); #endif } return ret; } static GenRet codegenOr(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); if( info->cfile ) ret.c = "(" + av.c + " | " + bv.c + ")"; else { #ifdef HAVE_LLVM PromotedPair values = convertValuesToLarger(av.val, bv.val, is_signed(av.chplType), is_signed(bv.chplType)); ret.val = info->irBuilder->CreateOr(values.a, values.b); #endif } return ret; } static GenRet codegenXor(GenRet a, GenRet b) { GenInfo* info = gGenInfo; GenRet ret; if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); if( info->cfile ) ret.c = "(" + av.c + " ^ " + bv.c + ")"; else { #ifdef HAVE_LLVM PromotedPair values = convertValuesToLarger(av.val, bv.val, is_signed(av.chplType), is_signed(bv.chplType)); ret.val = info->irBuilder->CreateXor(values.a, values.b); #endif } return ret; } static GenRet codegenTernary(GenRet cond, GenRet ifTrue, GenRet ifFalse) { GenInfo* info = gGenInfo; GenRet ret; Type* type = ifTrue.chplType; if( ! type ) type = ifFalse.chplType; ret.chplType = type; #ifdef HAVE_LLVM bool ifTrueSigned = !ifTrue.isUnsigned; bool ifFalseSigned = !ifFalse.isUnsigned; if( ifTrue.chplType ) ifTrueSigned = is_signed(ifTrue.chplType); if( ifFalse.chplType ) ifFalseSigned = is_signed(ifFalse.chplType); #endif if( info->cfile ) { ret.c = "( (" + cond.c + ")?(" + ifTrue.c + "):(" + ifFalse.c + ") )"; } else { #ifdef HAVE_LLVM llvm::Function *func = info->irBuilder->GetInsertBlock()->getParent(); llvm::BasicBlock *blockIfTrue =llvm::BasicBlock::Create( info->module->getContext(), "ternaryBlockIfTrue"); llvm::BasicBlock *blockIfFalse = llvm::BasicBlock::Create( info->module->getContext(), "ternaryBlockIfFalse"); llvm::BasicBlock *blockEnd = llvm::BasicBlock::Create( info->module->getContext(), "ternaryBlockEnd"); GenRet ifTrueVal = codegenValue(ifTrue); GenRet ifFalseVal = codegenValue(ifFalse); PromotedPair values = convertValuesToLarger( ifTrueVal.val, ifFalseVal.val, ifTrueSigned, ifFalseSigned); char name[32]; sprintf(name, "chpl_macro_tmp_tv_%d", codegen_tmp++); llvm::Value* tmp = createVarLLVM(values.a->getType(), name); info->irBuilder->CreateCondBr( codegenValue(cond).val, blockIfTrue, blockIfFalse); func->getBasicBlockList().push_back(blockIfTrue); info->irBuilder->SetInsertPoint(blockIfTrue); info->irBuilder->CreateStore(values.a, tmp); info->irBuilder->CreateBr(blockEnd); func->getBasicBlockList().push_back(blockIfFalse); info->irBuilder->SetInsertPoint(blockIfFalse); info->irBuilder->CreateStore(values.b, tmp); info->irBuilder->CreateBr(blockEnd); func->getBasicBlockList().push_back(blockEnd); info->irBuilder->SetInsertPoint(blockEnd); ret.val = info->irBuilder->CreateLoad(tmp); ret.isUnsigned = !values.isSigned; #endif } return ret; } // AKA == null static GenRet codegenIsZero(GenRet x) { GenInfo* info = gGenInfo; GenRet ret; if (x.chplType->symbol->hasEitherFlag(FLAG_WIDE_REF,FLAG_WIDE_CLASS) ) { x = codegenRaddr(x); if (info->cfile) { ret.c = x.c; ret.c += " == nil"; } else { #ifdef HAVE_LLVM ret.val = info->irBuilder->CreateIsNull(x.val); #endif } } else { GenRet xv = codegenValue(x); if( info->cfile ) ret.c = "(! " + xv.c + ")"; else { #ifdef HAVE_LLVM ret.val = info->irBuilder->CreateIsNull(xv.val); #endif } } return ret; } // AKA != null static GenRet codegenIsNotZero(GenRet x) { GenInfo* info = gGenInfo; GenRet ret; if (x.chplType->symbol->hasEitherFlag(FLAG_WIDE_REF,FLAG_WIDE_CLASS) ) { x = codegenRaddr(x); if (info->cfile) { ret.c = x.c; ret.c += " != nil"; } else { #ifdef HAVE_LLVM ret.val = info->irBuilder->CreateIsNotNull(x.val); #endif } } else { GenRet xv = codegenValue(x); if( info->cfile ) ret.c = "(!(! " + xv.c + "))"; else { #ifdef HAVE_LLVM ret.val = info->irBuilder->CreateIsNotNull(xv.val); #endif } } return ret; } static GenRet codegenGlobalArrayElement(const char* table_name, GenRet elt) { GenInfo* info = gGenInfo; GenRet ret; if (info->cfile) { ret.c = table_name; ret.c += "["; ret.c += elt.c; ret.c += "]"; } else { #ifdef HAVE_LLVM GenRet table = info->lvt->getValue(table_name); INT_ASSERT(table.val); INT_ASSERT(elt.val);; llvm::Value* GEPLocs[2]; GEPLocs[0] = llvm::Constant::getNullValue( llvm::IntegerType::getInt64Ty(info->module->getContext())); GEPLocs[1] = extendToPointerSize(elt, 0); llvm::Value* elementPtr; elementPtr = createInBoundsGEP(table.val, GEPLocs); llvm::Instruction* element = info->irBuilder->CreateLoad(elementPtr); // I don't think it matters, but we could provide TBAA metadata // here to indicate global constant variable loads are constant... // I'd expect LLVM to figure that out because the table loaded is // constant. ret.val = element; #endif } return ret; } // cid_Td is the class-id field value of the dynamic type // Type* C is the type to downcast to static GenRet codegenDynamicCastCheck(GenRet cid_Td, Type* C) { // see genSubclassArrays in codegen.cpp // currently using Schubert Numbering method // // Td is a subclass of C (or a C) iff // n1(C) <= n1(Td) && n1(Td) <= n2(C) // // but note, we n1(C) *is* C->classId AggregateType* at = toAggregateType(C); INT_ASSERT(at != NULL); GenRet cid_C = codegenUseCid(C); GenRet n1_C = cid_C; // Since we use n1_Td twice, put it into a temp var // other than that, n1_Td is cid_Td. GenRet n1_Td = createTempVarWith(cid_Td); GenRet n2_C = codegenGlobalArrayElement("chpl_subclass_max_id", cid_C); GenRet part1 = codegenLessEquals(n1_C, n1_Td); GenRet part2 = codegenLessEquals(n1_Td, n2_C); GenRet ret = codegenLogicalAnd(part1, part2); return ret; } #ifdef HAVE_LLVM static void convertArgumentForCall(llvm::FunctionType *fnType, GenRet arg, std::vector<llvm::Value*> & outArgs) { GenInfo* info = gGenInfo; llvm::Value* v = arg.val; llvm::Type* t = v->getType(); bool isSigned = false; if( arg.chplType ) isSigned = is_signed(arg.chplType); llvm::Type* targetType = NULL; if( outArgs.size() < fnType->getNumParams() ) { targetType = fnType->getParamType(outArgs.size()); } // Check that we're not casting between global address // space and local address space pointers (since that // would be invalid!) if( targetType ) { llvm::PointerType* tgtPtr = llvm::dyn_cast<llvm::PointerType>(targetType); llvm::PointerType* tPtr = llvm::dyn_cast<llvm::PointerType>(t); if( tgtPtr && tPtr ) { bool tgtGlobal = tgtPtr->getAddressSpace() == info->globalToWideInfo.globalSpace; bool tGlobal = tPtr->getAddressSpace() == info->globalToWideInfo.globalSpace; INT_ASSERT(tgtGlobal == tGlobal); } } llvm::Value* out; if( targetType ) out = convertValueToType(v, targetType, isSigned, false); else out = v; // no target type means we just emit it. if( out ) { // OK, we were able to emit it... outArgs.push_back(out); } else if( t->isEmptyTy() ) { // OK, just don't emit an argument at all. } else if( t->isStructTy() || t->isArrayTy() || t->isVectorTy() ) { // We might need to put the arguments in one-at-a-time, // in order to put up with structure expansion done by clang // (see canExpandIndirectArgument) // TODO - this should actually depend on the clang ABI, // or else we should find a way to disable the optimization in clang. // It should be possible to get the necessary information from clang // with cgModule->getTypes()->arrangeFunctionDeclaration(FunctionDecl) // Work with a prefix of the structure/vector argument. llvm::Type* int8_type; llvm::Type* int8_ptr_type; llvm::Type* dst_ptr_type; llvm::Value* arg_ptr; llvm::Value* arg_i8_ptr; llvm::Value* cur_ptr; llvm::Value* casted_ptr; llvm::Value* cur; int64_t offset = 0; int64_t cur_size = 0; int64_t arg_size = 0; int64_t targ_size = 0; int8_type = llvm::Type::getInt8Ty(info->llvmContext); int8_ptr_type = int8_type->getPointerTo(); arg_size = getTypeSizeInBytes(info->module->getDataLayout(), t); assert(arg_size >= 0); targetType = fnType->getParamType(outArgs.size()); targ_size = getTypeSizeInBytes(info->module->getDataLayout(), targetType); // Allocate space on the stack... // Some ABIs will increase the size of small structs, // e.g. on aarch64, a struct < 128 bits will be rounded // up to a multiple of 64 bits. if (targ_size > arg_size) { arg_ptr = createVarLLVM(targetType, ""); arg_ptr = info->irBuilder->CreatePointerCast(arg_ptr, t->getPointerTo()); } else { arg_ptr = createVarLLVM(t, ""); } arg_i8_ptr = info->irBuilder->CreatePointerCast(arg_ptr, int8_ptr_type, ""); // Copy the value to the stack... info->irBuilder->CreateStore(v, arg_ptr); while(offset < arg_size) { if( outArgs.size() >= fnType->getNumParams() ) { INT_FATAL("Could not convert arguments for call"); } targetType = fnType->getParamType(outArgs.size()); dst_ptr_type = targetType->getPointerTo(); cur_size = getTypeSizeInBytes(info->module->getDataLayout(), targetType); assert(cur_size > 0); if (cur_size <= arg_size && offset + cur_size > arg_size) { INT_FATAL("Could not convert arguments for call"); } // Now load cur_size bytes from pointer into the argument. cur_ptr = info->irBuilder->CreateConstInBoundsGEP1_64(arg_i8_ptr, offset); casted_ptr = info->irBuilder->CreatePointerCast(cur_ptr, dst_ptr_type); cur = info->irBuilder->CreateLoad(casted_ptr); outArgs.push_back(cur); //printf("offset was %i\n", (int) offset); offset = getTypeFieldNext(info->module->getDataLayout(), t, offset + (arg_size < cur_size ? arg_size : cur_size) - 1); //printf("offset now %i\n", (int) offset); } } else { INT_FATAL("Could not convert arguments for call"); } } #endif static GenRet codegenArgForFormal(GenRet arg, ArgSymbol* formal, bool defaultToValues, bool isExtern) { // NOTE -- VMT call had add & if arg isRecord. if( formal ) { bool passRef = false; bool passWideRef = false; // We need to pass a reference in these cases // Don't pass a reference to extern functions // Do if requiresCPtr or the argument is of reference type if (isExtern && (!(formal->intent & INTENT_FLAG_REF) || formal->type->getValType()->symbol->hasFlag(FLAG_TUPLE))) { // Don't pass by reference to extern functions } else if (formal->requiresCPtr() || formal->isRef() || formal->isWideRef()) { // Pass by reference in this case passRef = true; // If it's wide, make a note of it if (formal->isWideRef()) { passWideRef = true; } } // Make sure that the formal type + intent // matches, so we don't get multiple reference levels. // If we need to pass a reference but we already have a reference, // pass the pointer by value. if (arg.chplType && passRef) { if (passWideRef && arg.chplType->symbol->hasFlag(FLAG_WIDE_REF)) { passWideRef = false; passRef = false; } if (passRef && arg.chplType->symbol->hasFlag(FLAG_REF)) { passRef = false; } } if (passWideRef) { if( arg.isLVPtr == GEN_VAL ) { arg = codegenValuePtr(arg); arg = codegenWideHere(codegenAddrOf(arg)); } else if( arg.isLVPtr == GEN_PTR ) { arg = codegenWideHere(codegenAddrOf(arg)); } // otherwise, arg.isLVPtr == GEN_WIDE_PTR, no action necessary } else if(passRef) { if( arg.isLVPtr == GEN_VAL ) { arg = codegenValuePtr(arg); } else if( arg.isLVPtr == GEN_WIDE_PTR ) { arg = codegenValuePtr(codegenRaddr(arg)); } // otherwise, arg.isLVPtr == GEN_PTR, no action necessary } else { if( arg.isLVPtr != GEN_VAL ) { arg = codegenValue(arg); } } } else { if( defaultToValues ) { if( arg.isLVPtr != GEN_VAL ) { arg = codegenValue(arg); } } // otherwise, leave it be. } return arg; } // if fSym is non-NULL, we use that to decide what to dereference. // Otherwise, if defaultToValues=true, we will codegenValue() the arguments, // and if it is false, they will pass by reference if they // are references. static GenRet codegenCallExpr(GenRet function, std::vector<GenRet> & args, FnSymbol* fSym, bool defaultToValues) { GenInfo* info = gGenInfo; GenRet ret; if( info->cfile ) { ret.c = function.c; ret.c += '('; bool first_actual = true; for( size_t i = 0; i < args.size(); i++ ) { { // Convert formals if we have fSym ArgSymbol* formal = NULL; bool isExtern = true; if( fSym ) { Expr* e = fSym->formals.get(i + 1); DefExpr* de = toDefExpr(e); formal = toArgSymbol(de->sym); INT_ASSERT(formal); if (!fSym->hasFlag(FLAG_EXTERN)) isExtern = false; } args[i] = codegenArgForFormal(args[i], formal, defaultToValues, isExtern); } if (first_actual) first_actual = false; else ret.c += ", "; ret.c += args[i].c; } ret.c += ')'; } else { #ifdef HAVE_LLVM INT_ASSERT(function.val); llvm::Value *val = function.val; // Maybe function is bit-cast to a pointer? llvm::Function *func = llvm::dyn_cast<llvm::Function>(val); llvm::FunctionType *fnType; if (func){ fnType = func->getFunctionType(); } else { fnType = llvm::cast<llvm::FunctionType>( val->getType()->getPointerElementType()); } std::vector<llvm::Value *> llArgs; llvm::Value* sret = NULL; // We might be doing 'structure return' if( fnType->getReturnType()->isVoidTy() && fnType->getNumParams() >= 1 && func && func->hasStructRetAttr() ) { // We must allocate a temporary to store the return value llvm::PointerType* ptrToRetTy = llvm::cast<llvm::PointerType>( fnType->getParamType(0)); llvm::Type* retTy = ptrToRetTy->getElementType(); sret = createVarLLVM(retTy); llArgs.push_back(sret); } for( size_t i = 0; i < args.size(); i++ ) { // If we are passing byval, get the pointer to the // argument if( llArgs.size() < fnType->getNumParams() && func && func->getAttributes().hasAttribute(llArgs.size()+1, llvm::Attribute::ByVal) ){ args[i] = codegenAddrOf(codegenValuePtr(args[i])); // TODO -- this is not working! } // Convert formals if we have fSym { ArgSymbol* formal = NULL; bool isExtern = true; if( fSym ) { Expr* e = fSym->formals.get(i + 1); DefExpr* de = toDefExpr(e); formal = toArgSymbol(de->sym); INT_ASSERT(formal); if (!fSym->hasFlag(FLAG_EXTERN)) isExtern = false; } args[i] = codegenArgForFormal(args[i], formal, defaultToValues, isExtern); } // Handle structure expansion done by clang. convertArgumentForCall(fnType, args[i], llArgs); } if (func) { ret.val = info->irBuilder->CreateCall(func, llArgs); } else { ret.val = info->irBuilder->CreateCall(val, llArgs); } if( sret ) { ret.val = codegenLoadLLVM(sret, fSym?(fSym->retType):(NULL)); } #endif } return ret; } static GenRet codegenCallExpr(const char* fnName, std::vector<GenRet> & args, bool defaultToValues) { GenInfo* info = gGenInfo; GenRet fn; if( info->cfile ) fn.c = fnName; else { #ifdef HAVE_LLVM fn.val = getFunctionLLVM(fnName); INT_ASSERT(fn.val); #endif } return codegenCallExpr(fn, args, NULL, defaultToValues); } static void codegenCall(const char* fnName, std::vector<GenRet> & args, bool defaultToValues) { GenInfo* info = gGenInfo; GenRet ret = codegenCallExpr(fnName, args, defaultToValues); if( info->cfile ) { info->cStatements.push_back(ret.c + ";\n"); } } /* These overloads of codegenCall are a bit boring-looking, * but they make it much easier to write the primitive call * generation in Expr::codegen */ GenRet codegenCallExpr(const char* fnName) { std::vector<GenRet> args; return codegenCallExpr(fnName, args); } GenRet codegenCallExpr(const char* fnName, GenRet a1) { std::vector<GenRet> args; args.push_back(a1); return codegenCallExpr(fnName, args); } GenRet codegenCallExpr(const char* fnName, GenRet a1, GenRet a2) { std::vector<GenRet> args; args.push_back(a1); args.push_back(a2); return codegenCallExpr(fnName, args); } static GenRet codegenCallExpr(const char* fnName, GenRet a1, GenRet a2, GenRet a3) { std::vector<GenRet> args; args.push_back(a1); args.push_back(a2); args.push_back(a3); return codegenCallExpr(fnName, args); } /* static void codegenCall(const char* fnName) { std::vector<GenRet> args; codegenCall(fnName, args); }*/ static void codegenCall(const char* fnName, GenRet a1) { std::vector<GenRet> args; args.push_back(a1); codegenCall(fnName, args); } static void codegenCall(const char* fnName, GenRet a1, GenRet a2) { std::vector<GenRet> args; args.push_back(a1); args.push_back(a2); codegenCall(fnName, args); } static void codegenCall(const char* fnName, GenRet a1, GenRet a2, GenRet a3) { std::vector<GenRet> args; args.push_back(a1); args.push_back(a2); args.push_back(a3); codegenCall(fnName, args); } static void codegenCall(const char* fnName, GenRet a1, GenRet a2, GenRet a3, GenRet a4) { std::vector<GenRet> args; args.push_back(a1); args.push_back(a2); args.push_back(a3); args.push_back(a4); codegenCall(fnName, args); } static void codegenCall(const char* fnName, GenRet a1, GenRet a2, GenRet a3, GenRet a4, GenRet a5) { std::vector<GenRet> args; args.push_back(a1); args.push_back(a2); args.push_back(a3); args.push_back(a4); args.push_back(a5); codegenCall(fnName, args); } static void codegenCall(const char* fnName, GenRet a1, GenRet a2, GenRet a3, GenRet a4, GenRet a5, GenRet a6) { std::vector<GenRet> args; args.push_back(a1); args.push_back(a2); args.push_back(a3); args.push_back(a4); args.push_back(a5); args.push_back(a6); codegenCall(fnName, args); } static void codegenCall(const char* fnName, GenRet a1, GenRet a2, GenRet a3, GenRet a4, GenRet a5, GenRet a6, GenRet a7) { std::vector<GenRet> args; args.push_back(a1); args.push_back(a2); args.push_back(a3); args.push_back(a4); args.push_back(a5); args.push_back(a6); args.push_back(a7); codegenCall(fnName, args); } static void codegenCall(const char* fnName, GenRet a1, GenRet a2, GenRet a3, GenRet a4, GenRet a5, GenRet a6, GenRet a7, GenRet a8) { std::vector<GenRet> args; args.push_back(a1); args.push_back(a2); args.push_back(a3); args.push_back(a4); args.push_back(a5); args.push_back(a6); args.push_back(a7); args.push_back(a8); codegenCall(fnName, args); } /* static void codegenCall(const char* fnName, GenRet a1, GenRet a2, GenRet a3, GenRet a4, GenRet a5, GenRet a6, GenRet a7, GenRet a8, GenRet a9) { std::vector<GenRet> args; args.push_back(a1); args.push_back(a2); args.push_back(a3); args.push_back(a4); args.push_back(a5); args.push_back(a6); args.push_back(a7); args.push_back(a8); args.push_back(a9); codegenCall(fnName, args); } */ /*static void codegenCall(const char* fnName, GenRet a1, GenRet a2, GenRet a3, GenRet a4, GenRet a5, GenRet a6, GenRet a7, GenRet a8, GenRet a9, GenRet a10) { std::vector<GenRet> args; args.push_back(a1); args.push_back(a2); args.push_back(a3); args.push_back(a4); args.push_back(a5); args.push_back(a6); args.push_back(a7); args.push_back(a8); args.push_back(a9); args.push_back(a10); codegenCall(fnName, args); }*/ static void codegenCall(const char* fnName, GenRet a1, GenRet a2, GenRet a3, GenRet a4, GenRet a5, GenRet a6, GenRet a7, GenRet a8, GenRet a9, GenRet a10, GenRet a11) { std::vector<GenRet> args; args.push_back(a1); args.push_back(a2); args.push_back(a3); args.push_back(a4); args.push_back(a5); args.push_back(a6); args.push_back(a7); args.push_back(a8); args.push_back(a9); args.push_back(a10); args.push_back(a11); codegenCall(fnName, args); } /* static void codegenCall(const char* fnName, GenRet a1, GenRet a2, GenRet a3, GenRet a4, GenRet a5, GenRet a6, GenRet a7, GenRet a8, GenRet a9, GenRet a10, GenRet a11, GenRet a12) { std::vector<GenRet> args; args.push_back(a1); args.push_back(a2); args.push_back(a3); args.push_back(a4); args.push_back(a5); args.push_back(a6); args.push_back(a7); args.push_back(a8); args.push_back(a9); args.push_back(a10); args.push_back(a11); args.push_back(a12); codegenCall(fnName, args); } */ static GenRet codegenZero() { return new_IntSymbol(0, INT_SIZE_64)->codegen(); } static GenRet codegenZero32() { return new_IntSymbol(0, INT_SIZE_32)->codegen(); } /* static GenRet codegenOne() { return new_IntSymbol(1, INT_SIZE_64)->codegen(); } */ GenRet codegenNullPointer() { GenInfo* info = gGenInfo; GenRet ret; ret.chplType = dtNil; if( info->cfile ) { ret.c = "NULL"; } else { #ifdef HAVE_LLVM ret.val = llvm::Constant::getNullValue(info->irBuilder->getInt8PtrTy()); #endif } return ret; } // Create a memcpy call copying size bytes from src to dest. // If we are copying a single type known to the compiler (e.g. a whole // record), pointedToType can contain the single element type. If we // are copying (or possibly copying) multiple elements, pointedToType // should be NULL. pointedToType is used to emit alias analysis information. static void codegenCallMemcpy(GenRet dest, GenRet src, GenRet size, Type* pointedToType) { GenInfo *info = gGenInfo; // Must call with two real pointer arguments // (and not any lvalues) INT_ASSERT(dest.isLVPtr == GEN_VAL); INT_ASSERT(src.isLVPtr == GEN_VAL); if( info->cfile ) { codegenCall("memcpy", dest, src, size); } else { #ifdef HAVE_LLVM // Caller should use e.g. codegenAddrOf, this function does // not operate on lvalues. dest = codegenValue(dest); src = codegenValue(src); size = codegenValue(size); llvm::Type *int8Ty = llvm::Type::getInt8Ty(info->llvmContext); llvm::Type *types[3]; unsigned addrSpaceDest = llvm::cast<llvm::PointerType>(dest.val->getType())->getAddressSpace(); unsigned addrSpaceSrc = llvm::cast<llvm::PointerType>(src.val->getType())->getAddressSpace(); types[0] = llvm::PointerType::get(int8Ty, addrSpaceDest); types[1] = llvm::PointerType::get(int8Ty, addrSpaceSrc); types[2] = llvm::Type::getInt64Ty(info->llvmContext); //types[3] = llvm::Type::getInt32Ty(info->llvmContext); //types[4] = llvm::Type::getInt1Ty(info->llvmContext); llvm::Function *func = llvm::Intrinsic::getDeclaration(info->module, llvm::Intrinsic::memcpy, types); //llvm::FunctionType *fnType = func->getFunctionType(); #if HAVE_LLVM_VER >= 70 // LLVM 7 and later: memcpy has no alignment argument llvm::Value* llArgs[4]; llArgs[0] = convertValueToType(dest.val, types[0], false); llArgs[1] = convertValueToType(src.val, types[1], false); llArgs[2] = convertValueToType(size.val, types[2], false); // LLVM memcpy intrinsic has additional argument isvolatile // isVolatile? llArgs[3] = llvm::ConstantInt::get(llvm::Type::getInt1Ty(info->module->getContext()), 0, false); #else // LLVM 6 and earlier: memcpy had alignment argument llvm::Value* llArgs[5]; llArgs[0] = convertValueToType(dest.val, types[0], false); llArgs[1] = convertValueToType(src.val, types[1], false); llArgs[2] = convertValueToType(size.val, types[2], false); // LLVM memcpy intrinsic has additional arguments alignment, isvolatile // alignment llArgs[3] = llvm::ConstantInt::get(llvm::Type::getInt32Ty(info->module->getContext()), 0, false); // isVolatile? llArgs[4] = llvm::ConstantInt::get(llvm::Type::getInt1Ty(info->module->getContext()), 0, false); #endif // We can't use IRBuilder::CreateMemCpy because that adds // a cast to i8 (in address space 0). llvm::CallInst* CI = info->irBuilder->CreateCall(func, llArgs); llvm::MDNode* tbaaStructTag = NULL; if( pointedToType ) { tbaaStructTag = pointedToType->symbol->llvmTbaaStructCopyNode; } // LLVM's memcpy only supports tbaa.struct metadata, not scalar tbaa. // The reason is that LLVM is only looking for holes in structs here, // not aliasing. Clang also puts only tbaa.struct on memcpy calls. // Adding scalar tbaa metadata here causes incorrect code to be generated. if( tbaaStructTag ) CI->setMetadata(llvm::LLVMContext::MD_tbaa_struct, tbaaStructTag); #endif } } #ifdef HAVE_LLVM static GenRet codegenSizeof(llvm::Type* type) { GenRet ret; ret.chplType = SIZE_TYPE; ret.val = codegenSizeofLLVM(type); return ret; } #endif static GenRet codegenSizeof(const char* name) { GenInfo* info = gGenInfo; GenRet ret; ret.chplType = SIZE_TYPE; if( info->cfile ) { ret.c = "sizeof("; ret.c += name; ret.c += ')'; } else { #ifdef HAVE_LLVM ret.val = codegenSizeofLLVM(getTypeLLVM(name)); #endif } return ret; } static GenRet codegenSizeof(Type* t) { return codegenSizeof(t->symbol->cname); } // dest dest must have isLVPtr set. This function implements // part of codegenAssign. static void codegenCopy(GenRet dest, GenRet src, Type* chplType=NULL) { assert( dest.isLVPtr ); if( ! chplType ) chplType = src.chplType; if( ! chplType ) chplType = dest.chplType; // This does handle isLVPtr being wide but only // if we're using fLLVMWideOpt. if( ! fLLVMWideOpt ) { assert( dest.isLVPtr != GEN_WIDE_PTR ); assert( src.isLVPtr != GEN_WIDE_PTR ); } #ifdef HAVE_LLVM GenInfo *info = gGenInfo; if( ! info->cfile ) { bool useMemcpy = false; if( chplType && chplType->symbol->llvmTbaaStructCopyNode ) { // Always use memcpy for things for which we've developed LLVM // struct nodes for alias analysis, since as far as we know, we // can't use tbaa.struct for load/store. useMemcpy = true; } else if( src.isLVPtr ) { // Consider using memcpy instead of stack allocating a possibly // large structure. llvm::Type* ptrTy = src.val->getType(); llvm::Type* eltTy = ptrTy->getPointerElementType(); if( chplType && chplType->symbol->hasFlag(FLAG_STAR_TUPLE) ) { // Always use memcpy for star tuples. useMemcpy = true; } else if( isTypeSizeSmallerThan(info->module->getDataLayout(), eltTy, 256 /* max bytes to load/store */)) { // OK } else { useMemcpy = true; } } if( !useMemcpy ) { // Do it with store(load(src_ptr), dst_ptr) src = codegenValue(src); codegenStoreLLVM(src, dest); return; } } #endif // Otherwise call memcpy. dest = codegenAddrOf(dest); if( ! src.isLVPtr ) src = codegenValuePtr(src); src = codegenAddrOf(src); GenRet size = codegenSizeof(chplType); codegenCallMemcpy(dest, src, size, chplType); } static bool isTupleOfTuple(BaseAST *e) { return (e->typeInfo()->symbol->hasFlag(FLAG_STAR_TUPLE) && toDefExpr(toAggregateType(e->typeInfo())->fields.head)->sym-> type->symbol->hasFlag(FLAG_TUPLE)); } // MPF - perhaps this should always call codegenValue // and return isLVPtr = GEN_VAL. GenRet codegenCast(Type* t, GenRet value, bool Cparens) { GenInfo* info = gGenInfo; GenRet ret; ret.chplType = t; ret.isLVPtr = value.isLVPtr; ret.isUnsigned = ! is_signed(t); // If we are casting to bool, set it to != 0. if( is_bool_type(t) ) { // NOTE: We have to limit this special treatment for bool cast to // --no-llvm compilations. LLVM bool operations return single bit // integers whereas bool type is 8-bits. So we still need explicit // cast. Engin if(info->cfile) { return codegenNotEquals(value, codegenZero()); } else { #ifdef HAVE_LLVM GenRet notZero = codegenNotEquals(value, codegenZero()); // convert the i1 result into an i8 (or appropriate bool width) llvm::Type* castType = t->codegen().type; ret.val = convertValueToType(notZero.val, castType, !ret.isUnsigned); INT_ASSERT(ret.val); return ret; #endif } } // if we are casting a C99 wide pointer, parens around the value // will result in an error, hence the Cparens parameter // e.g. ((chpl____wide_DefaultRectangularArr_locale_1_int64_t_F)( // { .locale = chpl_nodeID, .addr = nil })) // won't compile if (info->cfile){ ret.c = "((" + t->codegen().c + ")"; if (Cparens){ ret.c += "("; } ret.c += value.c; if (Cparens){ ret.c += ")"; } ret.c += ")"; } else { #ifdef HAVE_LLVM llvm::Type* castType = t->codegen().type; ret.val = convertValueToType(value.val, castType, !value.isUnsigned); INT_ASSERT(ret.val); #endif } return ret; } GenRet codegenCast(const char* typeName, GenRet value, bool Cparens) { GenInfo* info = gGenInfo; GenRet ret; ret.isLVPtr = value.isLVPtr; ret.chplType = getNamedType(std::string(typeName)); if( info->cfile ) { ret.c = "(("; ret.c += typeName; ret.c += ")"; if (Cparens){ ret.c += "("; } ret.c += value.c; if (Cparens){ ret.c += ")"; } ret.c += ")"; /*ret.c = "(("; ret.c += typeName; ret.c += ")("; ret.c += value.c; ret.c += "))";*/ } else { #ifdef HAVE_LLVM GenRet really = codegenValue(value); llvm::Type* castType = getTypeLLVM(typeName); ret.val = convertValueToType(really.val, castType, !really.isUnsigned); INT_ASSERT(ret.val); #endif } return ret; } static GenRet codegenCastToVoidStar(GenRet value) { GenInfo* info = gGenInfo; GenRet ret; if( info->cfile ) { ret.c = "((void*)("; ret.c += value.c; ret.c += "))"; } else { #ifdef HAVE_LLVM llvm::Type* castType = info->irBuilder->getInt8PtrTy(); ret.val = convertValueToType(value.val, castType, !value.isUnsigned); INT_ASSERT(ret.val); #endif } return ret; } void codegenCallPrintf(const char* arg) { GenInfo* info = gGenInfo; if (info->cfile) { fprintf(info->cfile, "printf(\"%%s\", \"%s\");\n", arg); } else { #ifdef HAVE_LLVM codegenCall("printf", new_CStringSymbol("%s")->codegen(), new_CStringSymbol(arg)->codegen()); #endif } } /* Commented out because it is not currently used. static GenRet codegenCastPtrToInt(Type* toType, GenRet value) { GenInfo* info = gGenInfo; if( info->cfile ) { return codegenCast(toType, value); } else { GenRet ret; #ifdef HAVE_LLVM llvm::Type* castType = toType->codegen().type; ret.val = info->irBuilder->CreatePtrToInt(value.val, castType); ret.isLVPtr = GEN_VAL; ret.chplType = toType; ret.isUnsigned = ! is_signed(toType); #endif return ret; } } */ // Generates code to perform an "assignment" operation, given // a destination pointer and a value. // That's basically // (*)to_ptr = (*)from // but for a homogeneous tuple, we will copy element-by-element // or possibly call memcpy (in order to copy more that the first element). // // If to_ptr or from_ptr is a wide reference type (but not both), // we will generate a PUT or a GET. // // from_type is used (in C) to create a temporary in case that // is needed. // // This function will always copy some value. If that is not // desired, other functions should be used. // // This function should have lvalues according to what should // be copied; that is to_ptr should have isLVPtr set, and from // can optionally have isLVPtr set. static void codegenAssign(GenRet to_ptr, GenRet from) { GenInfo* info = gGenInfo; // To must be a pointer. INT_ASSERT(to_ptr.isLVPtr); Type* type = from.chplType; if( ! type ) type = to_ptr.chplType; INT_ASSERT(type); bool isStarTuple = false; int starTupleLength = 0; if (type->symbol->hasFlag(FLAG_STAR_TUPLE)) { isStarTuple = true; starTupleLength = toAggregateType(type)->fields.length; } else if (type->symbol->hasFlag(FLAG_C_ARRAY)) { isStarTuple = true; int64_t sizeInt = toAggregateType(type)->cArrayLength(); if (sizeInt > INT_MAX) USR_FATAL(type->symbol->instantiationPoint, "c_array is too large"); starTupleLength = (int) sizeInt; } // if from is a wide ptr a ref to dtNil, set from to // a nil pointer of the correct type. if (from.chplType && to_ptr.chplType){ AggregateType* ct = toAggregateType(from.chplType); if (ct && ct->symbol->hasEitherFlag(FLAG_WIDE_REF, FLAG_WIDE_CLASS)) { Symbol* valField = ct->getField("addr"); if (valField && valField->getValType() == dtNil) { from = codegenAddrOf( codegenWideHere(codegenNullPointer(), to_ptr.chplType)); } } if (from.chplType == dtNil) { if (to_ptr.chplType->symbol->hasEitherFlag(FLAG_WIDE_REF, FLAG_WIDE_CLASS)) { from = codegenWideHere(codegenNullPointer(), to_ptr.chplType); type = to_ptr.chplType->getValType(); from.isLVPtr = GEN_VAL; } else { from = codegenNullPointer(); type = to_ptr.chplType->getValType(); from.isLVPtr = GEN_VAL; } } } if( (to_ptr.isLVPtr != GEN_WIDE_PTR && from.isLVPtr != GEN_WIDE_PTR )) { // Neither is wide. if( isStarTuple ) { // Homogeneous tuples are pointers even when GEN_VAL is set. // Homogeneous tuples are copied specially if ( !fNoTupleCopyOpt && starTupleLength <= tuple_copy_limit && !isTupleOfTuple(type) ) { // tuple copy optimization for (int i = 0; i < starTupleLength; i++) { GenRet to_i = codegenElementPtr(to_ptr, new_IntSymbol(i, INT_SIZE_64)); GenRet from_i = codegenElementPtr(from, new_IntSymbol(i, INT_SIZE_64)); codegenAssign(to_i, from_i); } } else { // tuple copy but use memcpy // to is already a pointer. codegenCopy(to_ptr, from, type); } } else { // not a homogeneous tuple copy if( info->cfile ) { GenRet value = codegenValue(from); INT_ASSERT(value.c != ""); std::string stmt = codegenValue(to_ptr).c + " = "; stmt += value.c; stmt += ";\n"; info->cStatements.push_back(stmt); } else { #ifdef HAVE_LLVM // LLVM codegen assignment (non-wide, non-tuple) assert(from.val); GenRet value = codegenValue(from); assert(value.val); codegenStoreLLVM(value, to_ptr, type); #endif } } } else { if (from.isLVPtr == GEN_WIDE_PTR && to_ptr.isLVPtr == GEN_WIDE_PTR){ // Assign two wide pointers through a temporary. // Create a temporary, assign tmp = from, // then assign to = tmp. INT_ASSERT(from.chplType); GenRet tmp = createTempVar(from.chplType); codegenAssign(tmp, from); // Now assign to_ptr = tmp codegenAssign(to_ptr, tmp); return; } // One of the types is a wide pointer type, so we have to // call get or put. if( from.isLVPtr == GEN_WIDE_PTR ) { // GET INT_ASSERT(type); // would also be nice to call createTempVarWith to // store a temporary wide pointer so we don't get // code like: // chpl_comm_get(..., // ((wide type) {.locale = ..., .addr = ...}).locale, // ((wide type) {.locale = ..., .addr = ...}).addr, // ...); // Generate a GET if (forceWidePtrsForLocal()) { // We're actually doing local compilation, so just do a copy codegenCopy(to_ptr, codegenDeref(codegenRaddr(from)), type); } else { if (fLLVMWideOpt) { // LLVM pass will translate it to a get after some opts // We already know to is a pointer (wide or not). // Make sure that from is a pointer codegenCopy(to_ptr, from, type); } else { codegenCall("chpl_gen_comm_get", codegenCastToVoidStar(to_ptr), codegenRnode(from), codegenRaddr(from), codegenSizeof(type), genCommID(info), info->lineno, gFilenameLookupCache[info->filename]); } } } else { // PUT if (forceWidePtrsForLocal()) { // We're actually doing local compilation, so just do a copy codegenCopy(codegenDeref(codegenRaddr(to_ptr)), from, type); } else { // Generate a PUT // to is already a pointer. if (fLLVMWideOpt) { // LLVM pass will translate it to a put after some opts // We already know to is a pointer (wide or not). // Make sure that from is a pointer codegenCopy(to_ptr, from, type); } else { codegenCall("chpl_gen_comm_put", codegenCastToVoidStar(codegenValuePtr(from)), codegenRnode(to_ptr), codegenRaddr(to_ptr), codegenSizeof(type), genCommID(info), info->lineno, gFilenameLookupCache[info->filename]); } } } } } static GenRet codegenExprMinusOne(Expr* expr) { int64_t i; IF1_int_type width = INT_SIZE_64; if( get_width(expr->typeInfo()) <= 8 ) width = INT_SIZE_8; else if( get_width(expr->typeInfo()) <= 16 ) width = INT_SIZE_16; else if( get_width(expr->typeInfo()) <= 32 ) width = INT_SIZE_32; if (get_int(expr, &i)) { return new_IntSymbol(i-1, width)->codegen(); } else { return codegenSub(expr, new_IntSymbol(1, width)); } } /************************************* | ************************************** * * * * ************************************** | *************************************/ // // Codegen assignments like a += b, a -= b, a *= b, etc. // op is the C string for the operator (e.g., " += ") // codegenOp is a function pointer to the codegenAdd()-style // routine that would be used to generate the operator // itself in a normal context (used by LLVM) // static void codegenOpAssign(GenRet a, GenRet b, const char* op, GenRet (*codegenOp)(GenRet a, GenRet b)) { GenInfo* info = gGenInfo; // deref 'a' if it is a 'ref' argument GenRet ap; if (a.chplType->symbol->hasFlag(FLAG_REF) || a.chplType->symbol->hasFlag(FLAG_WIDE_REF) || a.chplType->symbol->hasFlag(FLAG_WIDE_CLASS)) { ap = codegenDeref(a); } else { ap = a; } GenRet bv = codegenValue(b); // get the value of 'b' bool aIsRemote = ap.isLVPtr == GEN_WIDE_PTR; GenRet aLocal; // a guaranteed-local copy of a // For a wide pointer, we copy in and copy out... if( aIsRemote ) { // copy in -- will result in a chpl_comm_get(...) aLocal = createTempVar(ap.chplType); codegenAssign(aLocal, ap); } else { // otherwise, it's already local aLocal = ap; } if( info->cfile ) { // generate the local C statement std::string stmt = codegenValue(aLocal).c + op + bv.c + ";\n"; info->cStatements.push_back(stmt); } else { // LLVM version of a += b is just a = a + b. codegenAssign(aLocal, codegenOp(codegenValue(ap), bv)); } if( aIsRemote ) { // copy out -- will result in a chpl_comm_put(...) codegenAssign(ap, aLocal); } } static GenRet codegen_prim_get_real(GenRet arg, Type* type, bool real) { GenRet ret; const char* realOrImag; char fnName[21]; if (real) { realOrImag = "Real"; } else { realOrImag = "Imag"; } if (type == dtComplex[COMPLEX_SIZE_64]->refType) { snprintf(fnName, 21, "complex64Get%sRef", realOrImag); ret = codegenCallExpr(fnName, arg); } else if (type == dtComplex[COMPLEX_SIZE_128]->refType) { snprintf(fnName, 21, "complex128Get%sRef", realOrImag); ret = codegenCallExpr(fnName, arg); } else if (type == dtComplex[COMPLEX_SIZE_64]) { snprintf(fnName, 21, "complex64Get%sRef", realOrImag); ret = codegenCallExpr(fnName, codegenAddrOf(arg)); } else if (type == dtComplex[COMPLEX_SIZE_128]) { snprintf(fnName, 21, "complex128Get%sRef", realOrImag); ret = codegenCallExpr(fnName, codegenAddrOf(arg)); } else { INT_FATAL("Unsupported type in PRIM_GET_REAL"); } return ret; } /* Notes about code generation: * Intermediate expressions are returned from Expr::codegen * Local variables, array elements, tuple elements, and fields * are always generated as the address of that value (ie lvalues * are pointers) * Expressions may be actual values, not addresses * Chapel includes class instances - which may be remote or local. * Note that the variable in question for a class instance *is* * a wide (or not) reference (to the allocated object), but these * references are considered "values" rather than "lvalue pointers" * by the code generator. Thus a "reference to AGGREGATE_CLASS" is * actually a reference to a reference.. Note also that an "ARRAY" * in the code generator is actually an instance of the e.g. _ddata * class (and so the pointer to the data is again treated as a value). * Lastly, Chapel references are considered "values" rather * than "lvalue pointers", similarly to class instances, so that * the generated code can set what a reference is pointing to * (even though that is not allowed in Chapel). */ GenRet CallExpr::codegen() { SET_LINENO(this); FnSymbol* fn = resolvedFunction(); GenRet ret; // Note (for debugging), function name is in parentSymbol->cname. if (id == breakOnCodegenID) gdbShouldBreakHere(); if (getStmtExpr() && getStmtExpr() == this) codegenStmt(this); if (primitive != NULL) { ret = codegenPrimitive(); } else if (fn->hasFlag(FLAG_ON_BLOCK) == true) { codegenInvokeOnFun(); } else if (fn->hasFlag(FLAG_BEGIN_BLOCK) == true) { codegenInvokeTaskFun("chpl_taskListAddBegin"); } else if (fn->hasFlag(FLAG_COBEGIN_OR_COFORALL_BLOCK) == true) { codegenInvokeTaskFun("chpl_taskListAddCoStmt"); } else if (fn->hasFlag(FLAG_NO_CODEGEN) == false) { std::vector<GenRet> args(numActuals()); GenRet base = baseExpr->codegen(); int i = 0; for_formals_actuals(formal, actual, this) { SymExpr* se = toSymExpr(actual); GenRet arg = actual; if (se && isFnSymbol(se->symbol())) { if(this->theFnSymbol()->hasFlag(FLAG_EXTERN) || formal->type == dtCFnPtr) { arg = codegenCast("c_fn_ptr", arg); } else { arg = codegenCast("chpl_fn_p", arg); } } // If actual is special primitive arg will be modified // Otherwise, arg is untouched codegenIsSpecialPrimitive(formal, actual, arg); // Handle passing strings to externs //should this be else if? if (fn->hasFlag(FLAG_EXTERN)) { if (actual->isWideRef() == true || arg.isLVPtr == GEN_WIDE_PTR) { arg = codegenValue(arg); } else if (isRefExternStarTuple(formal, actual) == true) { // In C, a fixed-size-array lvalue is already a pointer, // so we deref here. But for LLVM, if we deref we will // end up passing the tuple by value, which is not right. if (gGenInfo->cfile != NULL) arg = codegenDeref(arg); } } // TODO: What if the actual is a wide-ref and the formal is a narrow ref? // Should that be handled back in IWR? if (arg.chplType->symbol->isRefOrWideRef() && !formal->isRefOrWideRef()) { arg = codegenValue(codegenDeref(arg)); } args[i] = arg; i = i + 1; } if (gGenInfo->cfile != NULL) { ret = codegenCallExpr(base, args, fn, true); if (getStmtExpr() && getStmtExpr() == this) gGenInfo->cStatements.push_back(ret.c + ";\n"); } else { // handle any special cases for which // bool isBuiltinExternCFunction(const char* cname) returns true. // // special case: for CallExpr sizeof(..) if (fn->hasFlag(FLAG_EXTERN) == true && strcmp(fn->name, "sizeof") == 0) { #ifdef HAVE_LLVM if (args[0].type) return codegenSizeof(args[0].type); else return codegenSizeof(codegenValue(args[0]).val->getType()); #endif } ret = codegenCallExpr(base, args, fn, true); #ifdef HAVE_LLVM // We might have to convert the return from the function // if clang did some structure-expanding. bool returnedValueUsed = false; if (CallExpr* parentCall = toCallExpr(this->parentExpr)) if (parentCall->isPrimitive(PRIM_MOVE)) returnedValueUsed = true; if (returnedValueUsed && this->typeInfo() != dtNothing) { GenRet ty = this->typeInfo(); INT_ASSERT(ty.type); if (ty.type != ret.val->getType()) { llvm::Value* converted = convertValueToType(ret.val, ty.type, false, true); INT_ASSERT(converted); ret.val = converted; } } // Handle setting LLVM invariant on const records after // they are initialized if (fn->isInitializer() || fn->isCopyInit()) { if (typeNeedsCopyInitDeinit(get(1)->typeInfo())) { if (SymExpr* initedSe = toSymExpr(get(1))) { if (initedSe->symbol()->isConstValWillNotChange()) { GenRet genSe = args[0]; llvm::Value* ptr = genSe.val; INT_ASSERT(ptr); llvm::Type* ptrTy = ptr->getType(); INT_ASSERT(ptrTy && ptrTy->isPointerTy()); llvm::Type* eltTy = ptrTy->getPointerElementType(); codegenInvariantStart(eltTy, ptr); } } } } #endif } } // When generating LLVM value, if --gen-ids is on, // add metadata nodes that have the Chapel AST ids #ifdef HAVE_LLVM if (gGenInfo->cfile == NULL && ret.val && fGenIDS) { if (llvm::Instruction* insn = llvm::dyn_cast<llvm::Instruction>(ret.val)) { llvm::LLVMContext& ctx = gGenInfo->llvmContext; llvm::Type *int64Ty = llvm::Type::getInt64Ty(ctx); llvm::Constant* c = llvm::ConstantInt::get(int64Ty, this->id); llvm::ConstantAsMetadata* aid = llvm::ConstantAsMetadata::get(c); llvm::MDNode* node = llvm::MDNode::get(ctx, aid); insn->setMetadata("chpl.ast.id", node); } } #endif return ret; } // to define a primitive's code generation method #define DEFINE_PRIM(NAME) \ void CallExpr::codegen ## NAME (CallExpr* call, GenRet &ret) // to call a primitive's code generation method #define CODEGEN_PRIM(NAME, call, ret) \ codegen ## NAME (call, ret); // to call another primitive's DEFINE_PRIM #define FORWARD_PRIM(NAME) \ CODEGEN_PRIM(NAME, call, ret); DEFINE_PRIM(PRIM_UNKNOWN) { // This is handled separately INT_ASSERT(false); } DEFINE_PRIM(PRIM_ARRAY_SET) { // get(1): (wide?) base pointer // get(2): index // get(3): value // Used to handle FLAG_WIDE_CLASS/FLAG_STAR_TUPLE specially, // but these should be taken care of by codegenElementPtr and // codegenAssign now. GenRet elementPtr = codegenElementPtr(call->get(1), call->get(2)); codegenAssign(elementPtr, call->get(3)); } DEFINE_PRIM(PRIM_ARRAY_SET_FIRST) { FORWARD_PRIM(PRIM_ARRAY_SET); } DEFINE_PRIM(PRIM_ARRAY_SHIFT_BASE_POINTER) { // get(1): local return value // get(2): _ddata instance // get(3): integral amount to shift by GenRet rv = call->get(1); GenRet addr = call->get(2); GenRet shifted = codegenElementPtr(addr, call->get(3), true); if (rv.isLVPtr != GEN_WIDE_PTR) { codegenAssign(rv, codegenAddrOf(shifted)); } else { codegenWideAddrWithAddr(rv, shifted, ret.chplType); } } DEFINE_PRIM(PRIM_NOOP) { } DEFINE_PRIM(PRIM_MOVE) { INT_FATAL("Handled in switch"); } DEFINE_PRIM(PRIM_DEREF) { codegenIsSpecialPrimitive(NULL, call, ret); } DEFINE_PRIM(PRIM_GET_SVEC_MEMBER_VALUE) { codegenIsSpecialPrimitive(NULL, call, ret); } DEFINE_PRIM(PRIM_GET_MEMBER_VALUE) { codegenIsSpecialPrimitive(NULL, call, ret); } DEFINE_PRIM(PRIM_ARRAY_GET) { codegenIsSpecialPrimitive(NULL, call, ret); } DEFINE_PRIM(PRIM_ARRAY_GET_VALUE) { codegenIsSpecialPrimitive(NULL, call, ret); } DEFINE_PRIM(PRIM_ON_LOCALE_NUM) { codegenIsSpecialPrimitive(NULL, call, ret); } DEFINE_PRIM(PRIM_GET_REAL) { codegenIsSpecialPrimitive(NULL, call, ret); } DEFINE_PRIM(PRIM_GET_IMAG) { codegenIsSpecialPrimitive(NULL, call, ret); } DEFINE_PRIM(PRIM_WIDE_MAKE) { // (type, localeID, addr) Type* narrowType = call->get(1)->typeInfo(); if (narrowType->symbol->hasFlag(FLAG_WIDE_CLASS)) { narrowType = narrowType->getField("addr")->typeInfo(); } INT_ASSERT(!narrowType->symbol->hasFlag(FLAG_WIDE_CLASS)); GenRet locale = call->get(2)->codegen(); GenRet raddr = codegenValue(call->get(3)->codegen()); ret = codegenCast(narrowType, raddr, true); if (requireWideReferences()) { ret = codegenWideAddr(locale, ret); } } DEFINE_PRIM(PRIM_WIDE_GET_LOCALE) { if (call->get(1)->isWideRef() || call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) { ret = codegenRlocale(call->get(1)); } else { ret = codegenGetLocaleID(); } } DEFINE_PRIM(PRIM_WIDE_GET_NODE) { if (call->get(1)->isWideRef() || call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) { ret = codegenRnode(call->get(1)); } else { ret = codegenGetNodeID(); } } DEFINE_PRIM(PRIM_WIDE_GET_ADDR) { if (call->get(1)->isWideRef() || call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) { ret = codegenRaddr(call->get(1)); } else { ret = codegenValue(call->get(1)); } // _wide_get_addr promises to return a c void ptr. Hence the cast. ret = codegenCast(dtCVoidPtr, ret); ret.isUnsigned = true; } DEFINE_PRIM(PRIM_SET_REFERENCE) { // Special handling for reference variables // These variables have value type so PRIM_ADDR_OF // should just return the reference. if (call->get(1)->isRefOrWideRef()) { ret = codegenValue(call->get(1)); } else { ret = codegenAddrOf(call->get(1)); } } DEFINE_PRIM(PRIM_ADDR_OF) { FORWARD_PRIM(PRIM_SET_REFERENCE); } DEFINE_PRIM(PRIM_REF_TO_STRING) { if (call->get(1)->isWideRef() || call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) { GenRet wide = call->get(1); ret = codegenCallExpr("chpl_wideRefToString", codegenRnode(wide), codegenRaddr(wide)); } else { ret = codegenCallExpr("chpl_refToString", call->get(1)); } } DEFINE_PRIM(PRIM_CLASS_NAME_BY_ID) { GenRet cid = codegenValue(call->get(1)); ret = codegenGlobalArrayElement("chpl_classNames", cid); } DEFINE_PRIM(PRIM_RETURN) { bool returnVoid = call->typeInfo() == dtVoid || call->typeInfo() == dtNothing; if (!returnVoid) { GenRet retExpr = call->get(1); if (!call->typeInfo()->symbol->isRefOrWideRef() && call->get(1)->isRefOrWideRef()) { retExpr = codegenDeref(retExpr); } ret = codegenValue(retExpr); } if (gGenInfo->cfile) { if (returnVoid) { ret.c = "return"; } else { ret.c = "return " + ret.c; } } else { #ifdef HAVE_LLVM llvm::ReturnInst* returnInst = NULL; if (returnVoid) { returnInst = gGenInfo->irBuilder->CreateRetVoid(); } else { ret = codegenCast(ret.chplType, ret); returnInst = gGenInfo->irBuilder->CreateRet(ret.val); } ret.val = returnInst; if (returnInst) { // Since putting anything after the return statement will make the LLVM // IR invalid, we set the insert point before the return instruction so that // other compilation processes work fine and as expected. gGenInfo->irBuilder->SetInsertPoint(returnInst); } #endif } } DEFINE_PRIM(PRIM_UNARY_MINUS) { ret = codegenNeg(call->get(1)); } DEFINE_PRIM(PRIM_UNARY_PLUS) { GenRet tmp = codegenValue(call->get(1)); if (gGenInfo->cfile) ret.c = "(+ " + tmp.c + ")"; else ret = tmp; // nothing is necessary. } DEFINE_PRIM(PRIM_UNARY_NOT) { GenRet tmp = codegenValue(call->get(1)); if (gGenInfo->cfile) { ret.c = "(~ " + tmp.c + ")"; } else { #ifdef HAVE_LLVM ret.val = gGenInfo->irBuilder->CreateNot(tmp.val); #endif } } DEFINE_PRIM(PRIM_UNARY_LNOT) { ret = codegenIsZero(call->get(1)); } DEFINE_PRIM(PRIM_ADD) { ret = codegenAdd(call->get(1), call->get(2)); } DEFINE_PRIM(PRIM_SUBTRACT) { ret = codegenSub(call->get(1), call->get(2)); } DEFINE_PRIM(PRIM_MULT) { ret = codegenMul(call->get(1), call->get(2)); } DEFINE_PRIM(PRIM_DIV) { ret = codegenDiv(call->get(1), call->get(2)); } DEFINE_PRIM(PRIM_MOD) { ret = codegenMod(call->get(1), call->get(2)); } DEFINE_PRIM(PRIM_LSH) { ret = codegenLsh(call->get(1), call->get(2)); } DEFINE_PRIM(PRIM_RSH) { ret = codegenRsh(call->get(1), call->get(2)); } DEFINE_PRIM(PRIM_PTR_EQUAL) { FORWARD_PRIM(PRIM_EQUAL); } DEFINE_PRIM(PRIM_EQUAL) { if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS) && call->get(2)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) { // TODO: The locale model will eventually have to provide a function // to compare wide addresses. Ditto for the NOTEQUAL case below. GenRet a = call->get(1); GenRet b = call->get(2); GenRet addrNe = codegenNotEquals(codegenRaddr(a), codegenRaddr(b)); GenRet locNe = codegenNotEquals(codegenRnode(a), codegenRnode(b)); GenRet rh = codegenLogicalAnd(codegenIsNotZero(codegenRaddr(a)), locNe); GenRet ne = codegenLogicalOr(addrNe, rh); ret = codegenIsZero(ne); } else if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS) && call->get(2)->typeInfo() == dtNil) { ret = codegenIsZero(call->get(1)); } else if (call->get(2)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS) && call->get(1)->typeInfo() == dtNil) { ret = codegenIsZero(call->get(2)); } else { ret = codegenEquals(call->get(1), call->get(2)); } } DEFINE_PRIM(PRIM_PTR_NOTEQUAL) { FORWARD_PRIM(PRIM_NOTEQUAL); } DEFINE_PRIM(PRIM_NOTEQUAL) { if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS) && call->get(2)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) { // TODO: The locale model will eventually have to provide a function // to compare wide addresses. Ditto for the EQUAL case above. GenRet a = call->get(1); GenRet b = call->get(2); GenRet addrNe = codegenNotEquals(codegenRaddr(a), codegenRaddr(b)); GenRet locNe = codegenNotEquals(codegenRnode(a), codegenRnode(b)); GenRet rh = codegenLogicalAnd(codegenIsNotZero(codegenRaddr(a)), locNe); ret = codegenLogicalOr(addrNe, rh); } else if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS) && call->get(2)->typeInfo() == dtNil) { ret = codegenIsNotZero(call->get(1)); } else if (call->get(2)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS) && call->get(1)->typeInfo() == dtNil) { ret = codegenIsNotZero(call->get(2)); } else { ret = codegenNotEquals(call->get(1), call->get(2)); } } DEFINE_PRIM(PRIM_LESSOREQUAL) { GenRet a = call->get(1); GenRet b = call->get(2); if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); if (gGenInfo->cfile) { ret.c = "(" + av.c + " <= " + bv.c + ")"; } else { #ifdef HAVE_LLVM PromotedPair values = convertValuesToLarger( av.val, bv.val, is_signed(call->get(1)->typeInfo()), is_signed(call->get(2)->typeInfo())); if (values.a->getType()->isFPOrFPVectorTy()) { ret.val = gGenInfo->irBuilder->CreateFCmpOLE(values.a, values.b); } else if (!values.isSigned) { ret.val = gGenInfo->irBuilder->CreateICmpULE(values.a, values.b); } else { ret.val = gGenInfo->irBuilder->CreateICmpSLE(values.a, values.b); } #endif } } DEFINE_PRIM(PRIM_GREATEROREQUAL) { GenRet a = call->get(1); GenRet b = call->get(2); if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); if (gGenInfo->cfile) { ret.c = "(" + av.c + " >= " + bv.c + ")"; } else { #ifdef HAVE_LLVM PromotedPair values = convertValuesToLarger( av.val, bv.val, is_signed(call->get(1)->typeInfo()), is_signed(call->get(2)->typeInfo())); if (values.a->getType()->isFPOrFPVectorTy()) { ret.val = gGenInfo->irBuilder->CreateFCmpOGE(values.a, values.b); } else if (!values.isSigned) { ret.val = gGenInfo->irBuilder->CreateICmpUGE(values.a, values.b); } else { ret.val = gGenInfo->irBuilder->CreateICmpSGE(values.a, values.b); } #endif } } DEFINE_PRIM(PRIM_LESS) { GenRet a = call->get(1); GenRet b = call->get(2); if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); if (gGenInfo->cfile) { ret.c = "(" + av.c + " < " + bv.c + ")"; } else { #ifdef HAVE_LLVM PromotedPair values = convertValuesToLarger( av.val, bv.val, is_signed(call->get(1)->typeInfo()), is_signed(call->get(2)->typeInfo())); if (values.a->getType()->isFPOrFPVectorTy()) { ret.val = gGenInfo->irBuilder->CreateFCmpOLT(values.a, values.b); } else if (!values.isSigned) { ret.val = gGenInfo->irBuilder->CreateICmpULT(values.a, values.b); } else { ret.val = gGenInfo->irBuilder->CreateICmpSLT(values.a, values.b); } #endif } } DEFINE_PRIM(PRIM_GREATER) { GenRet a = call->get(1); GenRet b = call->get(2); if (a.chplType && a.chplType->symbol->isRefOrWideRef()) a = codegenDeref(a); if (b.chplType && b.chplType->symbol->isRefOrWideRef()) b = codegenDeref(b); GenRet av = codegenValue(a); GenRet bv = codegenValue(b); if (gGenInfo->cfile) { ret.c = "(" + av.c + " > " + bv.c + ")"; } else { #ifdef HAVE_LLVM PromotedPair values = convertValuesToLarger( av.val, bv.val, is_signed(call->get(1)->typeInfo()), is_signed(call->get(2)->typeInfo())); if (values.a->getType()->isFPOrFPVectorTy()) { ret.val = gGenInfo->irBuilder->CreateFCmpOGT(values.a, values.b); } else if (!values.isSigned) { ret.val = gGenInfo->irBuilder->CreateICmpUGT(values.a, values.b); } else { ret.val = gGenInfo->irBuilder->CreateICmpSGT(values.a, values.b); } #endif } } DEFINE_PRIM(PRIM_AND) { ret = codegenAnd(call->get(1), call->get(2)); } DEFINE_PRIM(PRIM_OR) { ret = codegenOr(call->get(1), call->get(2)); } DEFINE_PRIM(PRIM_XOR) { ret = codegenXor(call->get(1), call->get(2)); } DEFINE_PRIM(PRIM_ASSIGN) { Expr* lhs = call->get(1); Expr* rhs = call->get(2); TypeSymbol* lhsTypeSym = lhs->typeInfo()->symbol; TypeSymbol* rhsTypeSym = rhs->typeInfo()->symbol; // PRIM_ASSIGN differs from PRIM_MOVE in that PRIM_ASSIGN always copies // objects. PRIM_MOVE can be used to copy a pointer (i.e. reference) // into another pointer, but if you try this with PRIM_ASSIGN, instead // it will overwrite what the LHS points to with what the RHS points to. // TODO: Works but may be slow. // (See the implementation of PRIM_MOVE above for several peephole // optimizations depending on specifics of the RHS expression.) // PRIM_ASSIGN expects either a narrow or wide pointer as its LHS arg. GenRet lg; GenRet rg; if (lhs->isRefOrWideRef()) { lg = codegenDeref(lhs); lhsTypeSym = lhsTypeSym->getValType()->symbol; } else { lg = lhs->codegen(); } if (rhs->isRefOrWideRef()) { rg = codegenDeref(rhs); rhsTypeSym = rhsTypeSym->getValType()->symbol; } else { rg = rhs->codegen(); } if (lhsTypeSym->hasFlag(FLAG_WIDE_CLASS) == false && rhsTypeSym->hasFlag(FLAG_WIDE_CLASS) == true) rg = codegenRaddr(rg); if (lhsTypeSym->hasFlag(FLAG_WIDE_CLASS) == true && rhsTypeSym->hasFlag(FLAG_WIDE_CLASS) == false) rg = codegenWideHere(rg); if (!lg.chplType) lg.chplType = lhsTypeSym->type; if (!rg.chplType) rg.chplType = rhsTypeSym->type; codegenAssign(lg, rg); } DEFINE_PRIM(PRIM_UNORDERED_ASSIGN) { Expr* lhsExpr = call->get(1); Expr* rhsExpr = call->get(2); bool lhsWide = lhsExpr->isWideRef(); bool rhsWide = rhsExpr->isWideRef(); // Both sides are narrow, do a normal assign if (!lhsWide && !rhsWide) { FORWARD_PRIM(PRIM_ASSIGN); return; } GenRet dst = lhsExpr; bool dstRef = lhsExpr->typeInfo()->symbol->hasFlag(FLAG_REF); GenRet src = rhsExpr; bool srcRef = rhsExpr->typeInfo()->symbol->hasFlag(FLAG_REF); GenRet ln = call->get(3); GenRet fn = call->get(4); TypeSymbol* dt = lhsExpr->typeInfo()->getValType()->symbol; GenRet size = codegenSizeof(dt->typeInfo()); if (!lhsWide && rhsWide) { // do an unordered GET // chpl_gen_comm_get_unordered(void *dst, // c_nodeid_t src_locale, void* src_raddr, // size_t size, int32_t commID, // int ln, int32_t fn); dst = codegenValuePtr(dst); if (dstRef) dst = codegenDeref(dst); codegenCall("chpl_gen_comm_get_unordered", codegenCastToVoidStar(codegenAddrOf(dst)), codegenRnode(src), codegenRaddr(src), size, genCommID(gGenInfo), ln, fn); } else if (lhsWide && !rhsWide) { // do an unordered PUT // chpl_gen_comm_put_unordered(void *src, // c_nodeid_t dst_locale, void* dst_raddr, // size_t size, int32_t commID, // int ln, int32_t fn); src = codegenValuePtr(src); if (srcRef) src = codegenDeref(src); codegenCall("chpl_gen_comm_put_unordered", codegenCastToVoidStar(codegenAddrOf(src)), codegenRnode(dst), codegenRaddr(dst), size, genCommID(gGenInfo), ln, fn); } else { // do an unordered GETPUT // chpl_comm_getput_unordered( // c_nodeid_t dst_locale, void* dst_raddr, // c_nodeid_t src_locale, void* src_raddr, // size_t size, int32_t commID, // int ln, int32_t fn); codegenCall("chpl_gen_comm_getput_unordered", codegenRnode(dst), codegenRaddr(dst), codegenRnode(src), codegenRaddr(src), size, genCommID(gGenInfo), ln, fn); } } DEFINE_PRIM(PRIM_ADD_ASSIGN) { codegenOpAssign(call->get(1), call->get(2), " += ", codegenAdd); } DEFINE_PRIM(PRIM_SUBTRACT_ASSIGN) { codegenOpAssign(call->get(1), call->get(2), " -= ", codegenSub); } DEFINE_PRIM(PRIM_MULT_ASSIGN) { codegenOpAssign(call->get(1), call->get(2), " *= ", codegenMul); } DEFINE_PRIM(PRIM_DIV_ASSIGN) { codegenOpAssign(call->get(1), call->get(2), " /= ", codegenDiv); } DEFINE_PRIM(PRIM_MOD_ASSIGN) { codegenOpAssign(call->get(1), call->get(2), " %= ", codegenMod); } DEFINE_PRIM(PRIM_LSH_ASSIGN) { codegenOpAssign(call->get(1), call->get(2), " <<= ", codegenLsh); } DEFINE_PRIM(PRIM_RSH_ASSIGN) { codegenOpAssign(call->get(1), call->get(2), " >>= ", codegenRsh); } DEFINE_PRIM(PRIM_AND_ASSIGN) { codegenOpAssign(call->get(1), call->get(2), " &= ", codegenAnd); } DEFINE_PRIM(PRIM_OR_ASSIGN) { codegenOpAssign(call->get(1), call->get(2), " |= ", codegenOr); } DEFINE_PRIM(PRIM_XOR_ASSIGN) { codegenOpAssign(call->get(1), call->get(2), " ^= ", codegenXor); } DEFINE_PRIM(PRIM_POW) { ret = codegenCallExpr("pow", call->get(1), call->get(2)); } DEFINE_PRIM(PRIM_MIN) { Type* t = call->get(1)->typeInfo(); if (is_arithmetic_type( t)) { if (is_int_type( t)) { ret = codegenUseGlobal("MIN_INT" + numToString(get_width(t))); } else if (is_uint_type( t)) { ret = codegenUseGlobal("MIN_UINT" + numToString(get_width(t))); } else if (is_real_type( t)) { std::string width = numToString(get_width(t)); ret = codegenNeg(codegenUseGlobal("MAX_FLOAT" + width)); } else if (is_imag_type( t)) { std::string width = numToString(get_width(t)); ret = codegenNeg(codegenUseGlobal("MAX_FLOAT" + width)); } else if (is_complex_type( t)) { std::string width = numToString(get_width(t)); std::string halfWidth = numToString(get_width(t) / 2); std::string fname = "_chpl_complex" + width; std::string maxFloat = "MAX_FLOAT" + halfWidth; ret = codegenCallExpr(fname.c_str(), codegenNeg(codegenUseGlobal(maxFloat)), codegenNeg(codegenUseGlobal(maxFloat))); } else { INT_FATAL( t, "cannot do min on supplied type"); } } else { INT_FATAL( t, "not arithmetic type"); } } DEFINE_PRIM(PRIM_MAX) { Type* t = call->get(1)->typeInfo(); if (is_arithmetic_type( t)) { if (is_int_type( t)) { ret = codegenUseGlobal("MAX_INT" + numToString(get_width(t))); } else if (is_uint_type( t)) { ret = codegenUseGlobal("MAX_UINT" + numToString(get_width(t))); } else if (is_real_type( t)) { ret = codegenUseGlobal("MAX_FLOAT" + numToString(get_width(t))); } else if (is_imag_type( t)) { ret = codegenUseGlobal("MAX_FLOAT" + numToString(get_width(t))); } else if (is_complex_type( t)) { std::string width = numToString(get_width(t)); std::string halfWidth = numToString(get_width(t) / 2); std::string fname = "_chpl_complex" + width; std::string maxFloat = "MAX_FLOAT" + halfWidth; ret = codegenCallExpr(fname.c_str(), codegenUseGlobal(maxFloat), codegenUseGlobal(maxFloat)); } else { INT_FATAL( t, "cannot do max on supplied type"); } } else { INT_FATAL( t, "not arithmetic type"); } } DEFINE_PRIM(PRIM_SETCID) { // get(1) is the object // (type=chpl__class_id, // wide=get(1), // local=chpl__cid_<type>, // stype=dtObject->typeInfo(), // sfield=chpl__cid) // if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_NO_OBJECT) == true && call->get(1)->typeInfo()->symbol->hasFlag(FLAG_OBJECT_CLASS) == false) { // Don't set cid for a no-object class. // This should probably be an error in the future. } else { Type* classType; if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) { classType = call->get(1)->typeInfo()->getField("addr")->type; } else { classType = call->get(1)->typeInfo(); } GenRet ref = codegenFieldCidPtr(call->get(1)); codegenAssign(ref, codegenUseCid(classType)); } } DEFINE_PRIM(PRIM_GETCID) { INT_ASSERT(call->get(1)->typeInfo() != dtNil); if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_NO_OBJECT) == true && call->get(1)->typeInfo()->symbol->hasFlag(FLAG_OBJECT_CLASS) == false) { INT_ASSERT(0); } GenRet ref = codegenFieldCidPtr(call->get(1)); ret = codegenValue(ref); } DEFINE_PRIM(PRIM_TESTCID) { // get(1) is an object to test, get(2) we just use the type of it. INT_ASSERT(call->get(1)->typeInfo() != dtNil); if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_NO_OBJECT) == true && call->get(1)->typeInfo()->symbol->hasFlag(FLAG_OBJECT_CLASS) == false) { INT_ASSERT(0); } GenRet ref = codegenFieldCidPtr(call->get(1)); ret = codegenEquals(ref, codegenUseCid(call->get(2)->typeInfo())); } DEFINE_PRIM(PRIM_SET_UNION_ID) { // get(1)->_uid = get(2) GenRet ref = codegenFieldUidPtr(call->get(1)); codegenAssign(ref, call->get(2)); } DEFINE_PRIM(PRIM_GET_UNION_ID) { // returns uid from get(1) GenRet ref = codegenFieldUidPtr(call->get(1)); ret = codegenValue(ref); } DEFINE_PRIM(PRIM_SET_SVEC_MEMBER) { // set tuple base=get(1) at index=get(2) to value=get(3) GenRet ptr = codegenElementPtr(call->get(1), codegenExprMinusOne(call->get(2))); GenRet val = call->get(3); // BHARSH TODO: 'getSvecSymbol' may also be useful here... if (call->get(3)->isRefOrWideRef() && !ptr.chplType->symbol->isRefOrWideRef()) { val = codegenDeref(val); } codegenAssign(ptr, val); } DEFINE_PRIM(PRIM_GET_MEMBER) { // base=get(1), field symbol=get(2) // Invalid AST to use PRIM_GET_MEMBER with a ref field INT_ASSERT(!call->get(2)->isRef()); ret = codegenFieldPtr(call->get(1), call->get(2)); // Used to only do addrOf if // !get(2)->typeInfo()->symbol->hasFlag(FLAG_REF) // but that unnaturally depends on the type of the field. ret = codegenAddrOf(ret); } DEFINE_PRIM(PRIM_GET_SVEC_MEMBER) { // get tuple base=get(1) at index=get(2) Type* tupleType = call->get(1)->getValType(); ret = codegenElementPtr(call->get(1), codegenExprMinusOne(call->get(2))); if (tupleType->getField("x1")->type->symbol->hasFlag(FLAG_REF) == false) ret = codegenAddrOf(ret); } DEFINE_PRIM(PRIM_SET_MEMBER) { // base=get(1), field=get(2), value=get(3) // if the field is a ref, and the value is a not ref, invalid AST if (call->get(2)->isRef() && !call->get(3)->isRef()) INT_FATAL("Invalid PRIM_SET_MEMBER ref field with value"); GenRet ptr = codegenFieldPtr(call->get(1), call->get(2)); GenRet val = call->get(3); if (call->get(3)->isRefOrWideRef() && !call->get(2)->isRefOrWideRef()) { val = codegenDeref(val); } codegenAssign(ptr, val); } DEFINE_PRIM(PRIM_CHECK_NIL) { GenRet ptr = call->get(1); if (ptr.chplType->symbol->hasFlag(FLAG_WIDE_CLASS)) ptr = codegenRaddr(ptr); codegenCall("chpl_check_nil", ptr, call->get(2), call->get(3)); } DEFINE_PRIM(PRIM_LOCAL_CHECK) { // arguments are (wide ptr, error string, line, function/file) GenRet lhs = call->get(1); Symbol* lhsType = lhs.chplType->symbol; const char* error = toVarSymbol(toSymExpr(call->get(2))->symbol())->immediate->v_string; if (lhsType->hasEitherFlag(FLAG_WIDE_REF, FLAG_WIDE_CLASS) == true) { GenRet filename = GenRet(call->get(4)); GenRet lhs = call->get(1); if (call->get(1)->isRef()) { lhs = codegenDeref(lhs); } codegenCall("chpl_check_local", codegenRnode(lhs), call->get(3), filename, error); } } DEFINE_PRIM(PRIM_GET_SERIAL) { ret = codegenCallExpr("chpl_task_getSerial"); } DEFINE_PRIM(PRIM_SET_SERIAL) { codegenCall("chpl_task_setSerial", codegenValue(call->get(1))); } DEFINE_PRIM(PRIM_GET_DYNAMIC_END_COUNT) { CallExpr* rcall = new CallExpr(gGetDynamicEndCount); ret = rcall->codegen(); } DEFINE_PRIM(PRIM_SET_DYNAMIC_END_COUNT) { CallExpr* rcall = new CallExpr(gSetDynamicEndCount, call->get(1)->copy()); ret = rcall->codegen(); } static void codegenPutGet(CallExpr* call, GenRet &ret) { // args are: // localvar, locale, remote addr, get(4)==size, line, file // get(4)==len for array_get/put const char* fn; TypeSymbol* dt; bool isget = true; if (call->primitive->tag == PRIM_CHPL_COMM_GET || call->primitive->tag == PRIM_CHPL_COMM_ARRAY_GET) { fn = "chpl_gen_comm_get"; } else { fn = "chpl_gen_comm_put"; isget = false; } GenRet localAddr = codegenValuePtr(call->get(1)); // destination data array if (call->get(1)->isWideRef()) { Symbol* sym = call->get(1)->typeInfo()->getField("addr", true); INT_ASSERT(sym); dt = sym->typeInfo()->getValType()->symbol; localAddr = codegenRaddr(localAddr); } else { dt = call->get(1)->typeInfo()->getValType()->symbol; if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_REF)) { localAddr = codegenDeref(localAddr); } // c_ptr/ddata are already addresses, so dereference one level. if (dt->hasFlag(FLAG_DATA_CLASS)) { localAddr = codegenValue(localAddr); } } GenRet locale; if (call->get(2)->isRefOrWideRef()) { locale = codegenValue(codegenDeref(call->get(2))); } else { locale = codegenValue(call->get(2)); } // source data array GenRet remoteAddr = call->get(3); TypeSymbol *t = call->get(3)->typeInfo()->symbol; if (call->get(3)->isWideRef() == true) { remoteAddr = codegenRaddr(remoteAddr); } else if (t->hasFlag(FLAG_DATA_CLASS) == true) { remoteAddr = codegenValue(remoteAddr); } else if (call->get(3)->isRef() == false) { remoteAddr = codegenAddrOf(remoteAddr); } GenRet len; GenRet size; if (call->get(4)->isRefOrWideRef()) { len = codegenValue(codegenDeref(call->get(4))); } else { len = codegenValue(call->get(4)); } if (call->primitive->tag == PRIM_CHPL_COMM_ARRAY_PUT || call->primitive->tag == PRIM_CHPL_COMM_ARRAY_GET) { GenRet eltSize = codegenSizeof(dt->typeInfo()); size = codegenMul(eltSize, len); } else { size = len; } if (!fLLVMWideOpt) { codegenCall(fn, codegenCastToVoidStar(localAddr), locale, remoteAddr, size, genCommID(gGenInfo), call->get(5), call->get(6)); } else { // Figure out the locale-struct value to put into the wide address // (instead of just using the node number) GenRet lc = codegenLocaleForNode(locale); remoteAddr = codegenWideAddr(lc, remoteAddr); if (remoteAddr.isLVPtr == GEN_WIDE_PTR) remoteAddr = codegenAddrOf(remoteAddr); if (localAddr.isLVPtr == GEN_PTR) localAddr = codegenAddrOf(localAddr); if (localAddr.isLVPtr == GEN_WIDE_PTR) localAddr = codegenRaddr(localAddr); if (isget) { codegenCallMemcpy(localAddr, remoteAddr, size, NULL); } else { codegenCallMemcpy(remoteAddr, localAddr, size, NULL); } } } DEFINE_PRIM(PRIM_CHPL_COMM_GET) { codegenPutGet(call, ret); } DEFINE_PRIM(PRIM_CHPL_COMM_PUT) { codegenPutGet(call, ret); } DEFINE_PRIM(PRIM_CHPL_COMM_ARRAY_GET) { codegenPutGet(call, ret); } DEFINE_PRIM(PRIM_CHPL_COMM_ARRAY_PUT) { codegenPutGet(call, ret); } DEFINE_PRIM(PRIM_CHPL_COMM_REMOTE_PREFETCH) { // args are: // locale, remote addr, get(3)==size, line, file // Get the locale GenRet locale; if (call->get(1)->isRefOrWideRef()) { locale = codegenValue(codegenDeref(call->get(1))); } else { locale = codegenValue(call->get(1)); } // source data array GenRet remoteAddr = call->get(2); SymExpr* sym = toSymExpr(call->get(2)); INT_ASSERT(sym); if (sym->isWideRef()) { remoteAddr = codegenRaddr(remoteAddr); } else if (sym->isRef() == false) { remoteAddr = codegenAddrOf(remoteAddr); } GenRet len; if (call->get(3)->isRefOrWideRef()) { len = codegenValue(codegenDeref(call->get(3))); } else { len = codegenValue(call->get(3)); } codegenCall("chpl_gen_comm_prefetch", locale, remoteAddr, len, genCommID(gGenInfo), call->get(4), call->get(5)); } // Strided versions of get and put static void codegenPutGetStrd(CallExpr* call, GenRet &ret) { // args are: localvar, dststr addr, locale, remote addr, srcstr addr // count addr, strlevels, elem const char* fn; TypeSymbol* dt; if (call->primitive->tag == PRIM_CHPL_COMM_GET_STRD) { fn = "chpl_gen_comm_get_strd"; } else { fn = "chpl_gen_comm_put_strd"; } GenRet localAddr = codegenValuePtr(call->get(1)); // destination data array if (call->get(1)->isWideRef()) { Symbol* sym = call->get(1)->typeInfo()->getField("addr", true); INT_ASSERT(sym); dt = sym->typeInfo()->getValType()->symbol; localAddr = codegenRaddr(localAddr); } else { dt = call->get(1)->typeInfo()->getValType()->symbol; if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_REF)) { localAddr = codegenDeref(localAddr); } } // destination strides local array GenRet dststr = codegenValuePtr(call->get(2)); if (call->get(2)->isWideRef()) { Symbol* sym = call->get(2)->typeInfo()->getField("addr", true); INT_ASSERT(sym); dststr = codegenRaddr(dststr); } else if (call->get(2)->typeInfo()->symbol->hasFlag(FLAG_REF)) { dststr = codegenDeref(dststr); } // locale id GenRet locale; if (call->get(3)->isRefOrWideRef()) { locale = codegenValue(codegenDeref(call->get(3))); } else { locale = codegenValue(call->get(3)); } // source data array GenRet remoteAddr = call->get(4); if (call->get(4)->isWideRef() == true) { remoteAddr = codegenRaddr(remoteAddr); } else if (call->get(4)->isRef() == false) { remoteAddr = codegenAddrOf(remoteAddr); } // source strides local array GenRet srcstr = codegenValuePtr(call->get(5)); if (call->get(5)->isWideRef()) { Symbol* sym = call->get(5)->typeInfo()->getField("addr", true); INT_ASSERT(sym); srcstr = codegenRaddr(srcstr); } else { if (call->get(5)->typeInfo()->symbol->hasFlag(FLAG_REF)) { srcstr = codegenDeref(srcstr); } } // count local array GenRet count = codegenValuePtr(call->get(6)); if (call->get(6)->isWideRef()) { Symbol* sym = call->get(6)->typeInfo()->getField("addr", true); INT_ASSERT(sym); count = codegenRaddr(count); } else if (call->get(6)->typeInfo()->symbol->hasFlag(FLAG_REF)) { count = codegenDeref(count); } // stridelevels GenRet stridelevels; if (call->get(7)->isRefOrWideRef()) { stridelevels = codegenValue(codegenDeref(call->get(7))); } else { stridelevels = codegenValue(call->get(7)); } // eltSize GenRet eltSize = codegenSizeof(dt->typeInfo()); codegenCall(fn, codegenCastToVoidStar(localAddr), codegenCastToVoidStar(dststr), locale, remoteAddr, codegenCastToVoidStar(srcstr), codegenCastToVoidStar(count), stridelevels, eltSize, genCommID(gGenInfo), call->get(8), call->get(9)); } DEFINE_PRIM(PRIM_CHPL_COMM_PUT_STRD) { codegenPutGetStrd(call, ret); } DEFINE_PRIM(PRIM_CHPL_COMM_GET_STRD) { codegenPutGetStrd(call, ret); } DEFINE_PRIM(PRIM_SIZEOF_BUNDLE) { Type* type = call->get(1)->typeInfo(); GenRet size; // If wide, get the value type. if (type->symbol->hasFlag(FLAG_WIDE_CLASS) || call->get(1)->isWideRef()) type = toAggregateType(type)->getField("addr", true)->typeInfo(); // If Chapel class or record if (AggregateType* ct = toAggregateType(type)) { size = codegenSizeof(ct->classStructName(true)); } else { size = codegenSizeof(type); } ret = size; } DEFINE_PRIM(PRIM_SIZEOF_DDATA_ELEMENT) { Type* type = call->get(1)->typeInfo(); GenRet size; if (type->symbol->hasFlag(FLAG_WIDE_CLASS) == true) { size = codegenSizeof(getDataClassType(type->getField("addr")-> type->symbol)->typeInfo()); } else { size = codegenSizeof(getDataClassType(type->symbol)->typeInfo()); } ret = size; } DEFINE_PRIM(PRIM_CAST) { if (call->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS) || call->isWideRef()) { GenRet tmp = call->get(2); ret = codegenWideAddrWithAddr(tmp, codegenCast(call->get(1)->typeInfo(), codegenRaddr(tmp))); } else { Type* dst = call->get(1)->typeInfo(); Type* src = call->get(2)->typeInfo(); GenRet srcGen = call->get(2); // 2016-12-08 // Denormalize might move the reference in an implicit dereference // (move non-ref, ref) into a PRIM_CAST. This would then be a cast from // a reference type to a non-reference type, which doesn't really make // sense in today's compiler. When we see such a case, assume that we // should deref the 'src'. if (src->symbol->hasFlag(FLAG_REF) && dst->symbol->hasFlag(FLAG_REF) == false) { srcGen = codegenDeref(srcGen); src = src->getValType(); } // C standard promotes small ints to full int when they are involved in // arithmetic operations. When we don't denormalize the AST, small integer // arithmetic is always assigned to a temporary of the suitable size, // which truncates the integer appropriately. OTOH, if we denormalize the // AST then we have to make sure that are cast to appropriate size. // // TODO We use a wide brush by casting all integer operations. It should // be enough to cast integers that are smaller than standard C int for // target architecture. However, there was no easy way of obtaining that // at the time of writing this piece. Engin if (dst == src && !(is_int_type(dst) || is_uint_type(dst) || is_real_type(dst)) ) { ret = srcGen; } else if ((is_int_type(dst) || is_uint_type(dst)) && src == dtTaskID) { GenRet v = codegenValue(srcGen); // cast like this: (type) (intptr_t) v ret = codegenCast(call->typeInfo(), codegenCast("intptr_t", v)); } else if (isRecord(call->typeInfo()) || isUnion(call->typeInfo())) { INT_FATAL("TODO - don't like type-punning record/union"); } else if (src->symbol->hasFlag(FLAG_WIDE_CLASS) && call->typeInfo() == dtCVoidPtr) { // Special case: If we are casting a wide-ptr to a c_void_ptr we need to ensure // that we perform the cast on the actual address portion of the wide-ptr. LouisJenkinsCS ret = codegenCast(call->typeInfo(), codegenRaddr(srcGen)); } else { GenRet v = codegenValue(srcGen); ret = codegenCast(call->typeInfo(), v); } } } DEFINE_PRIM(PRIM_DYNAMIC_CAST) { if (call->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) INT_FATAL(call, "wide class dynamic cast is not normal"); GenRet tmp = codegenFieldCidPtr(call->get(2)); GenRet value = codegenValue(tmp); GenRet ok = codegenDynamicCastCheck(value, call->typeInfo()); GenRet cast = codegenCast(call->typeInfo(), codegenValue(call->get(2))); GenRet nul = codegenCast(call->typeInfo(), codegenNullPointer()); ret = codegenTernary(ok, cast, nul); } DEFINE_PRIM(PRIM_STACK_ALLOCATE_CLASS) { AggregateType* at = toAggregateType(call->get(1)->typeInfo()); const char* struct_name = at->classStructName(true); GenRet tmp = createTempVar(struct_name); ret = codegenCast(at, codegenAddrOf(tmp)); } DEFINE_PRIM(PRIM_REGISTER_GLOBAL_VAR) { GenRet idx = codegenValue(call->get(1)); GenRet var = call->get(2); GenRet ptr_wide_ptr = codegenAddrOf(var); #ifdef HAVE_LLVM if( fLLVMWideOpt ) { // With fLLVMWideOpt, ptr_wide_ptr is actually pointing // to a global pointer at this point, and we can't call // a C function on a global type (since it won't exist // by the time we are linking - it will have been lowered // to a wide type). So add the call to convert it to // wide (which makes the IR type check but will just // get removed in the eventual code). llvm::Type* ptr_wide_ptr_ty = ptr_wide_ptr.val->getType(); // call GLOBAL_FN_GLOBAL_TO_WIDE dummy function llvm::Function* fn = getGlobalToWideFn(gGenInfo->module, &gGenInfo->globalToWideInfo, ptr_wide_ptr_ty); INT_ASSERT(fn); ptr_wide_ptr.val = gGenInfo->irBuilder->CreateCall(fn, ptr_wide_ptr.val); } #endif codegenCall("chpl_comm_register_global_var", idx, codegenCast("ptr_wide_ptr_t", ptr_wide_ptr)); } DEFINE_PRIM(PRIM_BROADCAST_GLOBAL_VARS) { codegenCall("chpl_comm_broadcast_global_vars", call->get(1)); } DEFINE_PRIM(PRIM_PRIVATE_BROADCAST) { codegenCall("chpl_comm_broadcast_private", call->get(1), codegenSizeof(call->get(2)->typeInfo())); } DEFINE_PRIM(PRIM_INT_ERROR) { codegenCall("chpl_internal_error", new_CStringSymbol("compiler generated error")); } DEFINE_PRIM(PRIM_STRING_COPY) { GenRet cpyFrom = call->get(1)->codegen(); if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) { cpyFrom.isLVPtr = GEN_VAL; // Prevent &(char*) syntax. ret = codegenCallExpr("chpl_wide_string_copy", cpyFrom, call->get(2), call->get(3)); } else ret = call->codegenBasicPrimitiveExpr(); } DEFINE_PRIM(PRIM_CAST_TO_VOID_STAR) { GenRet act = call->get(1); GenRet ptr; const bool refToWide = call->get(1)->isRef() && act.chplType->getValType()->symbol->hasFlag(FLAG_WIDE_CLASS); if (act.chplType->symbol->hasEitherFlag(FLAG_WIDE_REF, FLAG_WIDE_CLASS) || refToWide) { // Get the local address. // Assume that we have already tested to ensure that this wide pointer // is local. That is, caller should have called chpl_check_local. if (refToWide) { act = codegenDeref(act); } ptr = codegenRaddr(act); } else ptr = codegenValue(call->get(1)); ret = codegenCastToVoidStar(ptr); } DEFINE_PRIM(PRIM_RT_ERROR) { ret = call->codegenBasicPrimitiveExpr(); } DEFINE_PRIM(PRIM_RT_WARNING) { ret = call->codegenBasicPrimitiveExpr(); } DEFINE_PRIM(PRIM_START_RMEM_FENCE) { ret = call->codegenBasicPrimitiveExpr(); } DEFINE_PRIM(PRIM_FINISH_RMEM_FENCE) { ret = call->codegenBasicPrimitiveExpr(); } DEFINE_PRIM(PRIM_NEW_PRIV_CLASS) { GenRet arg = call->get(1); GenRet pid = codegenValue(call->get(2)); if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) arg = codegenRaddr(arg); codegenCall("chpl_newPrivatizedClass", arg, pid); } DEFINE_PRIM(PRIM_FTABLE_CALL) { // // indirect function call via a function pointer // GenRet index = codegenValue(call->get(1)); GenRet fngen; // Generate a cast based upon the arguments. if (gGenInfo->cfile){ std::string str = "((void(*)("; GenRet arg = call->get(2); str += arg.chplType->symbol->cname; if (argMustUseCPtr(arg.chplType)) str += "*"; str += ","; str += call->get(3)->typeInfo()->symbol->cname; if (argMustUseCPtr(call->get(3)->typeInfo())) str += "*"; str += "))*chpl_ftable[" + index.c + "])"; fngen.c = str; } else { #ifdef HAVE_LLVM GenRet ftable = gGenInfo->lvt->getValue("chpl_ftable"); llvm::Value* fnPtrPtr; llvm::Instruction* fnPtr; llvm::Value* GEPLocs[2]; GEPLocs[0] = llvm::Constant::getNullValue(llvm::IntegerType::getInt64Ty(gGenInfo->module->getContext())); GEPLocs[1] = index.val; fnPtrPtr = createInBoundsGEP(ftable.val, GEPLocs); fnPtr = gGenInfo->irBuilder->CreateLoad(fnPtrPtr); // Generate an LLVM function type based upon the arguments. std::vector<llvm::Type*> argumentTypes; llvm::Type* returnType; returnType = llvm::Type::getVoidTy(gGenInfo->module->getContext()); llvm::Type* argt = NULL; llvm::FunctionType* fnType = NULL; argt = call->get(2)->typeInfo()->codegen().type; if (argMustUseCPtr(call->get(2)->typeInfo())) argt = argt->getPointerTo(); argumentTypes.push_back(argt); argt = call->get(3)->typeInfo()->codegen().type; if (argMustUseCPtr(call->get(3)->typeInfo())) argt = argt->getPointerTo(); argumentTypes.push_back(argt); fnType = llvm::FunctionType::get(returnType, argumentTypes, /* is var arg */ false); // OK, now cast to the fnType. fngen.val = gGenInfo->irBuilder->CreateBitCast(fnPtr, fnType->getPointerTo()); #endif } std::vector<GenRet> args; GenRet arg = call->get(2); if (argMustUseCPtr(arg.chplType) && !call->get(2)->isRef()) arg = codegenLocalAddrOf(arg); args.push_back(arg); arg = call->get(3); if (argMustUseCPtr(call->get(3)->typeInfo())) arg = codegenLocalAddrOf(arg); args.push_back(arg); ret = codegenCallExpr(fngen, args, NULL, true); } DEFINE_PRIM(PRIM_VIRTUAL_METHOD_CALL) { GenRet fnPtr; GenRet index; FnSymbol* fn = NULL; int startArgs = 3; // Where actual arguments begin. SymExpr* se = toSymExpr(call->get(1)); // the function symbol INT_ASSERT(se); fn = toFnSymbol(se->symbol()); INT_ASSERT(fn); { GenRet i = codegenValue(call->get(2)); // the cid int64_t fnId = virtualMethodMap.get(fn); GenRet j = new_IntSymbol(fnId, INT_SIZE_64); GenRet maxVMTConst = new_IntSymbol(gMaxVMT, INT_SIZE_64); INT_ASSERT(gMaxVMT >= 0); // indexExpr = maxVMT * classId + fnId index = codegenAdd(codegenMul(maxVMTConst, i), j); } if (gGenInfo->cfile){ fnPtr.c = std::string("chpl_vmtable") + "[" + index.c + "]"; } else { #ifdef HAVE_LLVM GenRet table = gGenInfo->lvt->getValue("chpl_vmtable"); llvm::Value* fnPtrPtr; llvm::Value* GEPLocs[2]; GEPLocs[0] = llvm::Constant::getNullValue( llvm::IntegerType::getInt64Ty(gGenInfo->module->getContext())); GEPLocs[1] = index.val; fnPtrPtr = createInBoundsGEP(table.val, GEPLocs); llvm::Instruction* fnPtrV = gGenInfo->irBuilder->CreateLoad(fnPtrPtr); fnPtr.val = fnPtrV; #endif } // the function expression to call. std::vector<GenRet> args; GenRet fngen = fn->codegenCast(fnPtr); int i = startArgs; for_formals(arg, fn) { args.push_back(call->get(i++)); } ret = codegenCallExpr(fngen, args, fn, true); } DEFINE_PRIM(PRIM_LOOKUP_FILENAME) { ret = call->codegenBasicPrimitiveExpr(); } DEFINE_PRIM(PRIM_INVARIANT_START) { GenInfo* info = gGenInfo; if (info->cfile) { // do nothing for the C backend } else { #ifdef HAVE_LLVM GenRet ptr = codegenValue(call->get(1)); llvm::Value* val = ptr.val; llvm::Type* ty = val->getType()->getPointerElementType(); codegenInvariantStart(ty, val); #endif } } #ifdef HAVE_LLVM static llvm::MDNode* createMetadataScope(llvm::LLVMContext& ctx, llvm::MDNode* domain, const char* name) { auto scopeName = llvm::MDString::get(ctx, name); auto dummy = llvm::MDNode::getTemporary(ctx, llvm::None); llvm::Metadata* Args[] = {dummy.get(), domain, scopeName}; auto scope = llvm::MDNode::get(ctx, Args); // Remove the dummy and replace it with a self-reference. dummy->replaceAllUsesWith(scope); return scope; } #endif DEFINE_PRIM(PRIM_NO_ALIAS_SET) { GenInfo* info = gGenInfo; if (info->cfile) { // do nothing for the C backend } else { #ifdef HAVE_LLVM Symbol* sym = toSymExpr(call->get(1))->symbol(); llvm::LLVMContext &ctx = info->llvmContext; if (info->noAliasDomain == NULL) { auto domainName = llvm::MDString::get(ctx, "Chapel no-alias"); auto dummy = llvm::MDNode::getTemporary(ctx, llvm::None); llvm::Metadata* Args[] = {dummy.get(), domainName}; info->noAliasDomain = llvm::MDNode::get(ctx, Args); // Remove the dummy and replace it with a self-reference. dummy->replaceAllUsesWith(info->noAliasDomain); } llvm::MDNode *&scope = info->noAliasScopes[sym]; if (scope == NULL) scope = createMetadataScope(ctx, info->noAliasDomain, sym->name); // now create a list storing just the scope llvm::MDNode *&scopeList = info->noAliasScopeLists[sym]; if (scopeList == NULL) scopeList = llvm::MDNode::get(ctx, scope); // now create the no-alias metadata llvm::MDNode *&noAliasList = info->noAliasLists[sym]; if (noAliasList == NULL) { llvm::SmallVector<llvm::Metadata*, 6> Args; bool first = true; for_actuals(actual, call) { if (!first) { Symbol* noAliasSym = toSymExpr(actual)->symbol(); llvm::MDNode *&otherScope = info->noAliasScopes[noAliasSym]; if (otherScope == NULL) otherScope = createMetadataScope(ctx, info->noAliasDomain, noAliasSym->name); Args.push_back(otherScope); } first = false; } noAliasList = llvm::MDNode::get(ctx, Args); } #endif } } DEFINE_PRIM(PRIM_COPIES_NO_ALIAS_SET) { GenInfo* info = gGenInfo; if (info->cfile) { // do nothing for the C backend } else { #ifdef HAVE_LLVM Symbol* sym = toSymExpr(call->get(1))->symbol(); Symbol* otherSym = toSymExpr(call->get(2))->symbol(); if (info->noAliasScopeLists.count(otherSym) > 0) { llvm::MDNode *&scopeList = info->noAliasScopeLists[sym]; scopeList = info->noAliasScopeLists[otherSym]; } llvm::MDNode *&noAliasList = info->noAliasLists[sym]; if (info->noAliasLists.count(otherSym) > 0) { noAliasList = info->noAliasLists[otherSym]; } #endif } } DEFINE_PRIM(PRIM_OPTIMIZATION_INFO) { // No action required here } void CallExpr::registerPrimitivesForCodegen() { // The following macros call registerPrimitiveCodegen for // the DEFINE_PRIM routines above for each primitive labelled // as PRIMITIVE_G (i.e. as needing code generation) #define PRIMITIVE_G(NAME) \ if (NAME!=PRIM_UNKNOWN) registerPrimitiveCodegen(NAME, codegen ## NAME ); #define PRIMITIVE_R(NAME) #include "primitive_list.h" #undef PRIMITIVE_G #undef PRIMITIVE_R } GenRet CallExpr::codegenPrimitive() { SET_LINENO(this); GenRet ret; PrimitiveTag tag = primitive->tag; void (*codegenFn)(CallExpr*, GenRet&); codegenFn = primitive->codegenFn; if (tag == PRIM_MOVE) { // PRIM_MOVE is the most common by far ret = this->codegenPrimMove(); } else if (tag == PRIM_UNKNOWN) { // PRIM_UNKNOWN won't have a codegenFn ret = codegenBasicPrimitiveExpr(); } else if (codegenFn != NULL) { // use a registered DEFINE_PRIM function from above codegenFn(this, ret); } else { // otherwise, error INT_FATAL(this, "primitive codegen fail; should it still be in the AST?"); if (gGenInfo->cfile) { std::string stmt; stmt += "/* ERR "; stmt += primitive->name; stmt += "*/"; gGenInfo->cStatements.push_back(stmt); } } if (gGenInfo->cfile && getStmtExpr() && getStmtExpr() == this && ret.c.length() > 0) gGenInfo->cStatements.push_back(ret.c + ";\n"); return ret; } GenRet CallExpr::codegenPrimMove() { GenRet ret; const bool LHSRef = get(1)->isRef() || get(1)->isWideRef(); const bool RHSRef = get(2)->isRef() || get(2)->isWideRef(); GenRet specRet; if (get(1)->typeInfo() == dtNothing) { ret = get(2)->codegen(); // Is the RHS a primop with special case handling? } else if (codegenIsSpecialPrimitive(get(1), get(2), specRet)) { // TODO The special treatment for PRIM_GET_REAL and PRIM_GET_IMAG can be // removed CallExpr* rhsCe = toCallExpr(get(2)); if(rhsCe->isPrimitive(PRIM_GET_REAL) || rhsCe->isPrimitive(PRIM_GET_IMAG)) { if (gGenInfo->cfile) { std::string stmt = codegenValue(get(1)).c + " = "; stmt += specRet.c; stmt += ";\n"; gGenInfo->cStatements.push_back(stmt); } else { #ifdef HAVE_LLVM codegenStoreLLVM(specRet, get(1)); #endif } } else { codegenAssign(get(1), specRet); } } else if (get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS) == true && get(2)->getValType()->symbol->hasFlag(FLAG_WIDE_CLASS) == false ) { GenRet rhs = get(2); if (get(2)->isRef()) { rhs = codegenDeref(rhs); } // At this point, RHS should be a class type. INT_ASSERT(isClassOrNil(rhs.chplType)); codegenAssign(get(1), codegenWideHere(rhs)); } else if (get(1)->isWideRef() == true && get(2)->isRef() == true) { codegenAssign(get(1), codegenAddrOf(codegenWideHere(get(2)))); } else if (get(1)->isWideRef() == true && get(2)->isWideRef() == false && get(2)->isRef() == false) { GenRet to_ptr = codegenDeref(get(1)); codegenAssign(to_ptr, get(2)); } else if (get(1)->isRef() == true && get(2)->isWideRef() == true) { if (get(1)->getValType() != get(2)->getValType()) { GenRet narrowRef = codegenRaddr(get(2)); GenRet wideThing = codegenDeref(narrowRef); GenRet narrowThing = codegenWideThingField(wideThing, WIDE_GEP_ADDR); codegenAssign(get(1), codegenAddrOf(narrowThing)); } else { GenRet genWide = get(2); codegenAssign(get(1), codegenRaddr(genWide)); } } else if (get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS) == false && get(1)->isRef() == false && get(2)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS) == true) { codegenAssign(get(1), codegenRaddr(get(2))); } else if (get(1)->isRef() == true && get(2)->isRef() == false) { codegenAssign(codegenDeref(get(1)), get(2)); } else if(!LHSRef && RHSRef) { codegenAssign(get(1), codegenDeref(get(2))); } else { codegenAssign(get(1), get(2)); } return ret; } /* * Some primitives require special attention depending on where they are used. * This generally involves casting the result of the primitive to the type of * the target. * * This function is used by codegenPrimMove, CallExpr::codegen(for matching * formal/actual types) and codegenPrimitive * * Returns true if `e` is a special primitive, and sets ret. * Returns false and doesn't change ret, otherwise */ static bool codegenIsSpecialPrimitive(BaseAST* target, Expr* e, GenRet& ret) { bool retval = false; CallExpr* call = toCallExpr(e); if(!call) return false; if (call->id == breakOnCodegenID) gdbShouldBreakHere(); if (call->primitive) { switch (call->primitive->tag) { case PRIM_GET_REAL: case PRIM_GET_IMAG: { bool isReal = call->primitive->tag == PRIM_GET_REAL; if (call->get(1)->isWideRef()) { // move(wide_real, prim_get_real(wide_complex)); // turns into: wide_real.locale = wide_complex.locale; // wide_real.addr = prim_get_real(wide_complex.addr); Type* cplxType = call->get(1)->typeInfo()->getRefType(); GenRet t1 = createTempVar(cplxType); codegenAssign(t1, codegenRaddr(call->get(1))); GenRet t2; if(target) { t2 = createTempVar(target->typeInfo()->getRefType()); } else { t2 = createTempVar(cplxType); } codegenAssign(t2, codegen_prim_get_real(t1, cplxType, isReal)); ret = codegenWideAddr(codegenRlocale(call->get(1)), codegenDeref(t2)); } else { ret = codegen_prim_get_real(call->get(1), call->get(1)->typeInfo(), isReal); } retval = true; break; } case PRIM_DEREF: { // BHARSH TODO: What if get(1) for this first branch is not a ref? if (call->get(1)->isWideRef() || call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) { Type* valueType; // BHARSH TODO: It seems odd to use a PRIM_DEREF on a wide class, why do we? if (call->get(1)->isWideRef()) valueType = call->get(1)->getValType(); else valueType = call->get(1)->typeInfo()->getField("addr")->type; if(target) { INT_ASSERT(valueType == target->typeInfo()); } ret = codegenDeref(call->get(1)); } else if (target && target->typeInfo()->symbol->hasFlag(FLAG_STAR_TUPLE)) { // star tuple retval in codegenAssign ret = codegenDeref(call->get(1)); } else { ret = codegenDeref(call->get(1)); } retval = true; break; } case PRIM_GET_MEMBER_VALUE: { SymExpr* se = toSymExpr(call->get(2)); if (target && call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) { if (se->symbol()->hasFlag(FLAG_SUPER_CLASS)) { // We're getting the super class pointer. GenRet srcwide = call->get(1); Type* addrType = target->typeInfo()->getField("addr")->type; GenRet addr = codegenCast(addrType, codegenRaddr(srcwide)); GenRet ref = codegenWideAddrWithAddr(srcwide, addr); ret = ref; } else { ret = codegenFieldPtr(call->get(1), se); } } else if (call->get(1)->isWideRef()) { ret = codegenFieldPtr(call->get(1), se); } else if (call->get(2)->typeInfo()->symbol->hasFlag(FLAG_STAR_TUPLE)) { ret = codegenFieldPtr(call->get(1), se); } else if (se->symbol()->hasFlag(FLAG_SUPER_CLASS)) { // We're getting the super class pointer. GenRet ref = codegenFieldPtr(call->get(1), se); // Now we have a field pointer to object->super, but // the pointer to super *is* actually the value of // the super class. So we just set isPtr to Value. ref.isLVPtr = GEN_VAL; ret = ref; } else { ret = codegenFieldPtr(call->get(1), se); } retval = true; break; } case PRIM_GET_MEMBER: { /* Get a pointer to a member */ SymExpr* se = toSymExpr(call->get(2)); // Invalid AST to use PRIM_GET_MEMBER with a ref field INT_ASSERT(!call->get(2)->isRefOrWideRef()); if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS) || call->get(1)->isWideRef() || call->typeInfo()->symbol->hasFlag(FLAG_STAR_TUPLE)) { ret = codegenAddrOf(codegenFieldPtr(call->get(1), se)); retval = true; } else if (target && ((target->isRef() && call->get(2)->isRef()) || (target->isWideRef() && call->get(2)->isWideRef()))) { ret = codegenFieldPtr(call->get(1), se); retval = true; } else if (target && (target->getValType() != call->get(2)->typeInfo())) { // get a narrow reference to the actual 'addr' field // of the wide pointer GenRet getField = codegenFieldPtr(call->get(1), se); ret = codegenAddrOf(codegenWideThingField(getField, WIDE_GEP_ADDR)); retval = true; } break; } case PRIM_GET_SVEC_MEMBER: { if (call->get(1)->isWideRef()) { /* Get a pointer to the i'th element of a homogeneous tuple */ GenRet elemPtr = codegenElementPtr(call->get(1), codegenExprMinusOne(call->get(2))); INT_ASSERT( elemPtr.isLVPtr == GEN_WIDE_PTR ); elemPtr = codegenAddrOf(elemPtr); //codegenAssign(get(1), elemPtr); ret = elemPtr; retval = true; } else if (target && (target->getValType() != call->getValType())) { GenRet getElem = codegenElementPtr(call->get(1), codegenExprMinusOne(call->get(2))); ret = codegenAddrOf(codegenWideThingField(getElem, WIDE_GEP_ADDR)); retval = true; } break; } case PRIM_GET_SVEC_MEMBER_VALUE: { /* Get the i'th value from a homogeneous tuple */ //there was an if/else block checking if call->get(1) is wide or narrow, //however if/else blocks were identical. It may not be in the future. ret = codegenElementPtr(call->get(1), codegenExprMinusOne(call->get(2))); retval = true; break; } case PRIM_ARRAY_GET: { /* Get a pointer to the i'th array element */ // ('_array_get' array idx) GenRet elem = codegenElementPtr(call->get(1), call->get(2)); GenRet ref = codegenAddrOf(elem); TypeSymbol* arrTS = call->get(1)->typeInfo()->symbol; // Handle the case that the array is a wide class/reference if (arrTS->hasFlag(FLAG_WIDE_CLASS) || arrTS->hasFlag(FLAG_WIDE_REF)) { ret = ref; // array is not wide, but what if the target is? } else if (target && (target->qualType().isWideRef() || target->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS))) { // resulting reference is wide, but the array is local. // This can happen with c_ptr for extern integration... ret = codegenAddrOf(codegenWideHere(ref)); } else { ret = ref; } retval = true; break; } case PRIM_ARRAY_GET_VALUE: { ret = codegenElementPtr(call->get(1), call->get(2)); retval = true; break; } case PRIM_GET_UNION_ID: { if (call->get(1)->isWideRef()) { ret = codegenFieldUidPtr(call->get(1)); retval = true; } break; } case PRIM_TESTCID: { // set get(1) to // call->get(1)->chpl_class_id == chpl__cid_"rhs->get(2)" if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) { GenRet tmp = codegenFieldCidPtr(call->get(1)); GenRet cid = codegenUseCid(call->get(2)->typeInfo()); ret = codegenEquals(tmp, cid); retval = true; } break; } case PRIM_GETCID: { if (call->get(1)->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) { GenRet tmp = codegenFieldCidPtr(call->get(1)); ret = tmp; retval = true; } break; } case PRIM_CAST: { if (call->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) { GenRet tmp = call->get(2); if (call->get(2)->isRef()) { tmp = codegenDeref(tmp); } ret = codegenWideAddrWithAddr(tmp, codegenCast(call->get(1)->typeInfo(), codegenRaddr(tmp))); retval = true; } else if (call->isWideRef()) { // MPF TODO: Can we remove this case? Why would we cast // a ref? GenRet tmp = call->get(2); // BHARSH TODO: Should we check if we're casting to a ref? if (call->get(2)->isRef()) { tmp = codegenDeref(tmp); } tmp = codegenWideAddrWithAddr(tmp, codegenCast(call->get(1)->typeInfo(), codegenRaddr(tmp))); ret = codegenAddrOf(tmp); retval = true; } // Should this handle target being wide? break; } case PRIM_DYNAMIC_CAST: { if (call->typeInfo()->symbol->hasFlag(FLAG_WIDE_CLASS)) { Type* type = call->typeInfo()->getField("addr")->type; GenRet wideFrom = codegenValue(call->get(2)); GenRet wideFromAddr = codegenRaddr(wideFrom); GenRet value = codegenValue(codegenFieldCidPtr(wideFrom)); GenRet ok = codegenDynamicCastCheck(value, type); GenRet cast = codegenCast(type, wideFromAddr); GenRet nul = codegenCast(type, codegenNullPointer()); GenRet addr = codegenTernary(ok, cast, nul); GenRet wide = codegenWideAddrWithAddr(wideFrom, addr, call->typeInfo()); ret = wide; retval = true; } break; } case PRIM_ON_LOCALE_NUM: { // This primitive expects an argument of type chpl_localeID_t. INT_ASSERT(call->get(1)->typeInfo() == dtLocaleID); ret = call->get(1); retval = true; break; } default: // OK, we did not handle the RHS as a special case. retval = false; break; } } return retval; } void CallExpr::codegenInvokeOnFun() { FnSymbol* fn = resolvedFunction(); GenRet localeId = get(1); const char* fname = NULL; GenRet argBundle; GenRet bundleSize; std::vector<GenRet> args(6); // get(1) is the locale // get(2) is a buffer containing bundled arguments // get(3) is a the size of the buffer // get(4) is a dummy class type for the argument bundle if (fn->hasFlag(FLAG_NON_BLOCKING)) fname = "chpl_executeOnNB"; else if (fn->hasFlag(FLAG_FAST_ON)) fname = "chpl_executeOnFast"; else fname = "chpl_executeOn"; argBundle = codegenValue(get(2)); bundleSize = codegenValue(get(3)); args[0] = codegenLocalAddrOf(localeId); args[1] = new_IntSymbol(ftableMap[fn], INT_SIZE_32); args[2] = codegenCast("chpl_comm_on_bundle_p", argBundle); args[3] = bundleSize; args[4] = fn->linenum(); args[5] = new_IntSymbol(gFilenameLookupCache[fn->fname()], INT_SIZE_32); genComment(fn->cname, true); codegenCall(fname, args); } void CallExpr::codegenInvokeTaskFun(const char* name) { FnSymbol* fn = resolvedFunction(); GenRet taskList = codegenValue(get(1)); GenRet taskListNode; GenRet taskBundle; GenRet bundleSize; std::vector<GenRet> args(8); // get(1) is a ref/wide ref to a task list value // get(2) is the node ID owning the task list // get(3) is a buffer containing bundled arguments // get(4) is the buffer's length // get(5) is a dummy class type for the argument bundle if (get(1)->isWideRef()) { taskList = codegenRaddr(taskList); } taskListNode = codegenValue(get(2)); taskBundle = codegenValue(get(3)); bundleSize = codegenValue(get(4)); args[0] = new_IntSymbol(-2 /* c_sublocid_any */, INT_SIZE_32); args[1] = new_IntSymbol(ftableMap[fn], INT_SIZE_64); args[2] = codegenCast("chpl_task_bundle_p", taskBundle); args[3] = bundleSize; args[4] = taskList; args[5] = codegenValue(taskListNode); args[6] = fn->linenum(); args[7] = new_IntSymbol(gFilenameLookupCache[fn->fname()], INT_SIZE_32); genComment(fn->cname, true); codegenCall(name, args); } GenRet CallExpr::codegenBasicPrimitiveExpr() const { std::vector<GenRet> args; for_alist(actual, argList) { GenRet gen = actual; Symbol* type = actual->typeInfo()->symbol; // Make wide pointers/classes local if (type->hasFlag(FLAG_WIDE_CLASS) || actual->isWideRef()) gen = codegenRaddr(gen); // Dereference reference or now-local wide reference if (actual->isRef() || actual->isWideRef()) gen = codegenDeref(gen); gen = codegenValue(gen); args.push_back(gen); } return codegenCallExpr(primitive->name, args); } /************************************* | ************************************** * * * * ************************************** | *************************************/ GenRet ContextCallExpr::codegen() { GenRet ret; INT_FATAL(this, "ContextCallExpr::codegen called"); return ret; } /************************************ | ************************************* * * * * ************************************* | ************************************/ GenRet NamedExpr::codegen() { GenRet ret; INT_FATAL(this, "NamedExpr::codegen not implemented"); return ret; } /************************************ | ************************************* * * * * ************************************* | ************************************/
31.03832
124
0.614411
[ "object", "vector", "model", "transform" ]
298b6c93b1b21e4a3a014e7d7269bbeb4070778f
24,484
cxx
C++
PWGJE/EMCALJetTasks/AliEmcalJetTaggerTaskFast.cxx
fkellere/AliPhysics
7ebfd87ceb3a02da8b1210ae3242c54ff4dffb98
[ "BSD-3-Clause" ]
null
null
null
PWGJE/EMCALJetTasks/AliEmcalJetTaggerTaskFast.cxx
fkellere/AliPhysics
7ebfd87ceb3a02da8b1210ae3242c54ff4dffb98
[ "BSD-3-Clause" ]
null
null
null
PWGJE/EMCALJetTasks/AliEmcalJetTaggerTaskFast.cxx
fkellere/AliPhysics
7ebfd87ceb3a02da8b1210ae3242c54ff4dffb98
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************************ * Copyright (C) 2017, Copyright Holders of the ALICE Collaboration * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * Neither the name of the <organization> nor the * * names of its contributors may be used to endorse or promote products * * derived from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * * DISCLAIMED. IN NO EVENT SHALL ALICE COLLABORATION 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 <iostream> #include <vector> #include <TH1.h> #include <TH2.h> #include <TH3.h> #include <THnSparse.h> #include <TKDTree.h> #include "AliAnalysisManager.h" #include "AliEmcalJet.h" #include "AliLog.h" #include "AliJetContainer.h" #include "AliParticleContainer.h" #include "AliEmcalJetTaggerTaskFast.h" /// \cond CLASSIMP ClassImp(PWGJE::EMCALJetTasks::AliEmcalJetTaggerTaskFast) /// \endcond namespace PWGJE { namespace EMCALJetTasks{ AliEmcalJetTaggerTaskFast::AliEmcalJetTaggerTaskFast() : AliAnalysisTaskEmcalJet("AliEmcalJetTaggerTaskFast", kTRUE), fJetTaggingType(kTag), fJetTaggingMethod(kGeo), fContainerBase(0), fContainerTag(1), fSpecPartContTag(-1), fMinFractionShared(0), fUseSumw2(0), fMatchingDone(0), fTypeAcc(kLimitBaseTagEtaPhi), fMaxDist(0.3), fInit(kFALSE), fh3PtJet1VsDeltaEtaDeltaPhi(nullptr), fh2PtJet1VsDeltaR(nullptr), fh2PtJet2VsFraction(nullptr), fh2PtJet1VsLeadPtAllSel(nullptr), fh2PtJet1VsLeadPtTagged(nullptr), fh2PtJet1VsPtJet2(nullptr), fh2PtJet2VsRelPt(nullptr), fh3PtJetDEtaDPhiConst(nullptr), fh3PtJetAreaDRConst(nullptr), fNAccJets(nullptr) #ifdef JETTAGGERFAST_TEST , fIndexErrorRateBase(nullptr) , fIndexErrorRateTag(nullptr) , fContainerErrorRateBase(nullptr) , fContainerErrorRateTag(nullptr) #endif { SetMakeGeneralHistograms(kTRUE); } AliEmcalJetTaggerTaskFast::AliEmcalJetTaggerTaskFast(const char *name) : AliAnalysisTaskEmcalJet(name, kTRUE), fJetTaggingType(kTag), fJetTaggingMethod(kGeo), fContainerBase(0), fContainerTag(1), fSpecPartContTag(-1), fMinFractionShared(0), fUseSumw2(0), fMatchingDone(0), fTypeAcc(kLimitBaseTagEtaPhi), fMaxDist(0.3), fInit(kFALSE), fh3PtJet1VsDeltaEtaDeltaPhi(nullptr), fh2PtJet1VsDeltaR(nullptr), fh2PtJet2VsFraction(nullptr), fh2PtJet1VsLeadPtAllSel(nullptr), fh2PtJet1VsLeadPtTagged(nullptr), fh2PtJet1VsPtJet2(nullptr), fh2PtJet2VsRelPt(nullptr), fh3PtJetDEtaDPhiConst(nullptr), fh3PtJetAreaDRConst(nullptr), fNAccJets(nullptr) #ifdef JETTAGGERFAST_TEST , fIndexErrorRateBase(nullptr) , fIndexErrorRateTag(nullptr) , fContainerErrorRateBase(nullptr) , fContainerErrorRateTag(nullptr) #endif { SetMakeGeneralHistograms(kTRUE); } void AliEmcalJetTaggerTaskFast::UserCreateOutputObjects() { AliAnalysisTaskEmcalJet::UserCreateOutputObjects(); // Notify the user to be careful. AliErrorStream() << "This task isn't yet validated. Please use the standard AliAnalysisTaskEmcalJetTagger.\n"; Bool_t oldStatus = TH1::AddDirectoryStatus(); TH1::AddDirectory(kFALSE); const Int_t nBinsPt = 40; const Int_t nBinsDPhi = 72; const Int_t nBinsDEta = 100; const Int_t nBinsDR = 50; const Int_t nBinsFraction = 101; const Double_t minPt = -50.; const Double_t maxPt = 150.; const Double_t minDPhi = -0.5; const Double_t maxDPhi = 0.5; const Double_t minDEta = -0.5; const Double_t maxDEta = 0.5; const Double_t minDR = 0.; const Double_t maxDR = 0.5; const Double_t minFraction = -0.005; const Double_t maxFraction = 1.005; // Prepare histograms fh3PtJet1VsDeltaEtaDeltaPhi = new TH3*[fNcentBins]; fh2PtJet1VsDeltaR = new TH2*[fNcentBins]; fh2PtJet2VsFraction = new TH2*[fNcentBins]; fh2PtJet1VsLeadPtAllSel = new TH2*[fNcentBins]; fh2PtJet1VsLeadPtTagged = new TH2*[fNcentBins]; fh2PtJet1VsPtJet2 = new TH2*[fNcentBins]; fh2PtJet2VsRelPt = new TH2*[fNcentBins]; for (Int_t i = 0; i < fNcentBins; i++) { fh3PtJet1VsDeltaEtaDeltaPhi[i] = 0; fh2PtJet1VsDeltaR[i] = 0; fh2PtJet2VsFraction[i] = 0; fh2PtJet1VsLeadPtAllSel[i] = 0; fh2PtJet1VsLeadPtTagged[i] = 0; fh2PtJet1VsPtJet2[i] = 0; fh2PtJet2VsRelPt[i] = 0; } TString histName = ""; TString histTitle = ""; for (Int_t i = 0; i < fNcentBins; i++) { histName = TString::Format("fh3PtJet1VsDeltaEtaDeltaPhi_%d",i); histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{#Delta#eta};#it{#Delta#varphi}",histName.Data()); fh3PtJet1VsDeltaEtaDeltaPhi[i] = new TH3F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsDEta,minDEta,maxDEta,nBinsDPhi,minDPhi,maxDPhi); fOutput->Add(fh3PtJet1VsDeltaEtaDeltaPhi[i]); histName = TString::Format("fh2PtJet1VsDeltaR_%d",i); histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{#Delta R}",histName.Data()); fh2PtJet1VsDeltaR[i] = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsDR,minDR,maxDR); fOutput->Add(fh2PtJet1VsDeltaR[i]); histName = TString::Format("fh2PtJet2VsFraction_%d",i); histTitle = TString::Format("%s;#it{p}_{T,jet2};#it{f}_{shared}",histName.Data()); fh2PtJet2VsFraction[i] = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsFraction,minFraction,maxFraction); fOutput->Add(fh2PtJet2VsFraction[i]); histName = TString::Format("fh2PtJet1VsLeadPtAllSel_%d",i); histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{p}_{T,lead trk}",histName.Data()); fh2PtJet1VsLeadPtAllSel[i] = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,20,0.,20.); fOutput->Add(fh2PtJet1VsLeadPtAllSel[i]); histName = TString::Format("fh2PtJet1VsLeadPtTagged_%d",i); histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{p}_{T,lead trk}",histName.Data()); fh2PtJet1VsLeadPtTagged[i] = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,20,0.,20.); fOutput->Add(fh2PtJet1VsLeadPtTagged[i]); histName = TString::Format("fh2PtJet1VsPtJet2_%d",i); histTitle = TString::Format("%s;#it{p}_{T,jet1};#it{p}_{T,jet2}",histName.Data()); fh2PtJet1VsPtJet2[i] = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,nBinsPt,minPt,maxPt); fOutput->Add(fh2PtJet1VsPtJet2[i]); histName = TString::Format("fh2PtJet2VsRelPt_%d",i); histTitle = TString::Format("%s;#it{p}_{T,jet2};(#it{p}_{T,jet2}-#it{p}_{T,jet1})/#it{p}_{T,jet1}",histName.Data()); fh2PtJet2VsRelPt[i] = new TH2F(histName.Data(),histTitle.Data(),nBinsPt,minPt,maxPt,241,-2.41,2.41); fOutput->Add(fh2PtJet2VsRelPt[i]); } fh3PtJetDEtaDPhiConst = new TH3F("fh3PtJetDEtaDPhiConst","fh3PtJetDEtaDPhiConst;pT;#Delta #eta;#Delta #varphi",nBinsPt,minPt,maxPt,nBinsDEta,-1.,1.,nBinsDPhi,-1.,1.); fOutput->Add(fh3PtJetDEtaDPhiConst); fh3PtJetAreaDRConst = new TH3F("fh3PtJetAreaDRConst","fh3PtJetAreaDRConst;pT;A;#Delta R",nBinsPt,minPt,maxPt,50,0.,1.,50,0.,1.); fOutput->Add(fh3PtJetAreaDRConst); fNAccJets = new TH1F("fNAccJets","fNAccJets;N/ev",11,-0.5, 9.5); fOutput->Add(fNAccJets); #ifdef JETTAGGERFAST_TEST fIndexErrorRateBase = new TH1F("indexErrorsBase", "Index errors nearest neighbor base jets", 1, 0.5, 1.5); fIndexErrorRateTag = new TH1F("indexErrorsTag", "Index errors nearest neighbors tag jets", 1, 0.5, 1.5); fContainerErrorRateBase = new TH1F("containerErrorsBase", "Matching errors container - kdtree base jets", 1, 0.5, 1.5); fContainerErrorRateTag = new TH1F("containerErrorsTag", "Matching errors container - kdtree tag jets", 1, 0.5, 1.5); fOutput->Add(fIndexErrorRateBase); fOutput->Add(fIndexErrorRateTag); fOutput->Add(fContainerErrorRateBase); fOutput->Add(fContainerErrorRateTag); #endif if(fUseSumw2) { // =========== Switch on Sumw2 for all histos =========== for(auto it : *fOutput){ TH1 *h1 = dynamic_cast<TH1*>(it); if (h1){ h1->Sumw2(); continue; } THnSparse *hn = dynamic_cast<THnSparse*>(it); if(hn)hn->Sumw2(); } } TH1::AddDirectory(oldStatus); PostData(1, fOutput); // Post data for ALL output slots > 0 here. } void AliEmcalJetTaggerTaskFast::Init(){ if(fInit) return; AliJetContainer *cont1 = GetJetContainer(fContainerBase); AliJetContainer *cont2 = GetJetContainer(fContainerTag); if(!cont1 || !cont2) AliError("Missing jet container"); // when full azimuth, don't do anything Double_t phiMin1 = cont1->GetJetPhiMin(), phiMin2 = cont2->GetJetPhiMin(); Bool_t isZeroTwoPi1 = kFALSE; //check only one side of phi, since the upper bound is not well defined if(phiMin1 > -1.e-6 && phiMin1 < 1.e-6) isZeroTwoPi1 = kTRUE; Bool_t isZeroTwoPi2 = kFALSE; if(phiMin2 > -1.e-6 && phiMin2 < 1.e-6) isZeroTwoPi2 = kTRUE; switch(fTypeAcc){ case kNoLimit: break; case kLimitTagEta: cont2->SetJetEtaLimits(cont2->GetJetEtaMin()-0.1,cont2->GetJetEtaMax()+0.1); break; case kLimitTagEtaPhi: cont2->SetJetEtaLimits(cont2->GetJetEtaMin()-0.1,cont2->GetJetEtaMax()+0.1); if(!isZeroTwoPi2) cont2->SetJetPhiLimits(cont2->GetJetPhiMin()-0.1,cont2->GetJetPhiMax()+0.1); break; case kLimitBaseTagEtaPhi: cont1->SetJetEtaLimits(cont1->GetJetEtaMin()-0.1,cont1->GetJetEtaMax()+0.1); if(!isZeroTwoPi1) cont1->SetJetPhiLimits(cont1->GetJetPhiMin()-0.1,cont1->GetJetPhiMax()+0.1); cont2->SetJetEtaLimits(cont2->GetJetEtaMin()-0.1,cont2->GetJetEtaMax()+0.1); if(!isZeroTwoPi2) cont2->SetJetPhiLimits(cont2->GetJetPhiMin()-0.1,cont2->GetJetPhiMax()+0.1); }; fInit = kTRUE; return; } Bool_t AliEmcalJetTaggerTaskFast::Run() { Init(); AliJetContainer *contBase = GetJetContainer(fContainerBase), *contTag = GetJetContainer(fContainerTag); ResetTagging(*contBase); ResetTagging(*contTag); fMatchingDone = MatchJetsGeo(*contBase, *contTag, fMaxDist); return kTRUE; } Bool_t AliEmcalJetTaggerTaskFast::FillHistograms() { // Fill histograms. AliEmcalJet *jet1 = NULL; AliJetContainer *jetCont = GetJetContainer(fContainerBase); if(!jetCont) return kFALSE; jetCont->ResetCurrentID(); Int_t count = 0; while((jet1 = jetCont->GetNextAcceptJet())) { count++; Double_t ptJet1 = jet1->Pt() - jetCont->GetRhoVal()*jet1->Area(); fh2PtJet1VsLeadPtAllSel[fCentBin]->Fill(ptJet1,jet1->MaxTrackPt()); //fill histo with angle between jet axis and constituents for(Int_t icc=0; icc<jet1->GetNumberOfTracks(); icc++) { AliVParticle *vp = static_cast<AliVParticle*>(jet1->Track(icc)); if(!vp) continue; Double_t dEta = jet1->Eta()-vp->Eta(); Double_t dPhi = jet1->Phi()-vp->Phi(); if(dPhi<TMath::Pi()) dPhi+=TMath::TwoPi(); if(dPhi>TMath::Pi()) dPhi-=TMath::TwoPi(); fh3PtJetDEtaDPhiConst->Fill(ptJet1,dEta,dPhi); Double_t dR = TMath::Sqrt(dPhi*dPhi+dEta*dEta); fh3PtJetAreaDRConst->Fill(ptJet1,jet1->Area(),dR); } if(jet1->GetTagStatus()<1 && fJetTaggingType==kTag) continue; AliEmcalJet *jet2 = NULL; if(fJetTaggingType==kTag) jet2 = jet1->GetTaggedJet(); if(fJetTaggingType==kClosest) jet2 = jet1->ClosestJet(); if(!jet2) continue; Double_t ptJet2 = jet2->Pt() - GetRhoVal(fContainerTag)*jet2->Area(); Double_t fraction = -2; if(fSpecPartContTag > -1) fraction = jetCont->GetFractionSharedPt(jet1, GetParticleContainer(fSpecPartContTag)); else fraction = jetCont->GetFractionSharedPt(jet1); fh2PtJet2VsFraction[fCentBin]->Fill(ptJet2,fraction); AliDebug(5, Form("Fraction = %f, minimum = %f", fraction, fMinFractionShared)); //if(fJetTaggingType==kClosest) Printf("Fraction = %f, minimum = %f", fraction, fMinFractionShared); if(fraction<fMinFractionShared && fJetTaggingType==kClosest) continue; fh2PtJet1VsLeadPtTagged[fCentBin]->Fill(ptJet1,jet1->MaxTrackPt()); fh2PtJet1VsPtJet2[fCentBin]->Fill(ptJet1,ptJet2); if(ptJet2>0.) fh2PtJet2VsRelPt[fCentBin]->Fill(ptJet2,(ptJet1-ptJet2)/ptJet2); Double_t dPhi = GetDeltaPhi(jet1->Phi(),jet2->Phi()); if(dPhi>TMath::Pi()) dPhi -= TMath::TwoPi(); if(dPhi<(-1.*TMath::Pi())) dPhi += TMath::TwoPi(); fh3PtJet1VsDeltaEtaDeltaPhi[fCentBin]->Fill(ptJet1,jet1->Eta()-jet2->Eta(),dPhi); fh2PtJet1VsDeltaR[fCentBin]->Fill(ptJet1,jet1->DeltaR(jet2)); } fNAccJets->Fill(count); return kTRUE; } void AliEmcalJetTaggerTaskFast::ResetTagging(const AliJetContainer &c) const { for(auto j : c.all()){ switch(fJetTaggingType){ case kClosest: j->ResetMatching(); break; case kTag: j->SetTaggedJet(nullptr); j->SetTagStatus(-1); }; } } bool AliEmcalJetTaggerTaskFast::MatchJetsGeo(AliJetContainer &contBase, AliJetContainer &contTag, Float_t maxDist) const { const Int_t kNacceptedBase = contBase.GetNAcceptedJets(), kNacceptedTag = contTag.GetNAcceptedJets(); if(!(kNacceptedBase && kNacceptedTag)) return false; // Build kd-trees TArrayD etaBase(kNacceptedBase), phiBase(kNacceptedBase), etaTag(kNacceptedTag), phiTag(kNacceptedTag); std::vector<AliEmcalJet *> jetsBase(kNacceptedBase), jetsTag(kNacceptedTag); // the storages are needed later for applying the tagging, in order to avoid multiple occurrence of jet selection int countBase(0), countTag(0); for(auto jb : contBase.accepted()) { etaBase[countBase] = jb->Eta(); phiBase[countBase] = jb->Phi(); jetsBase[countBase] = jb; countBase++; } for(auto jt : contTag.accepted()) { etaTag[countTag] = jt->Eta(); phiTag[countTag] = jt->Phi(); jetsTag[countTag] = jt; countTag++; } TKDTreeID treeBase(etaBase.GetSize(), 2, 1), treeTag(etaTag.GetSize(), 2, 1); treeBase.SetData(0, etaBase.GetArray()); treeBase.SetData(1, phiBase.GetArray()); treeBase.Build(); treeTag.SetData(0, etaTag.GetArray()); treeTag.SetData(1, phiTag.GetArray()); treeTag.Build(); TArrayI faMatchIndexTag(kNacceptedBase), faMatchIndexBase(kNacceptedTag); faMatchIndexBase.Reset(-1); faMatchIndexTag.Reset(-1); // find the closest distance to the full jet countBase = 0; for(auto j : contBase.accepted()) { Double_t point[2] = {j->Eta(), j->Phi()}; Int_t index(-1); Double_t distance(-1); treeTag.FindNearestNeighbors(point, 1, &index, &distance); // test whether indices are matching: if(index >= 0 && distance < maxDist){ AliDebugStream(1) << "Found closest tag jet for " << countBase << " with match index " << index << " and distance " << distance << std::endl; faMatchIndexTag[countBase]=index; } else { AliDebugStream(1) << "Not found closest tag jet for " << countBase << ", distance to closest " << distance << std::endl; } #ifdef JETTAGGERFAST_TEST if(index>-1){ Double_t distanceTest(-1); distanceTest = TMath::Sqrt(TMath::Power(etaTag[index] - j->Eta(), 2) + TMath::Power(phiTag[index] - j->Phi(), 2)); if(TMath::Abs(distanceTest - distance) > DBL_EPSILON){ AliDebugStream(1) << "Mismatch in distance from tag jet with index from tree: " << distanceTest << ", distance from tree " << distance << std::endl; fIndexErrorRateBase->Fill(1); } } #endif countBase++; } // other way around countTag = 0; for(auto j : contTag.accepted()){ Double_t point[2] = {j->Eta(), j->Phi()}; Int_t index(-1); Double_t distance(-1); treeBase.FindNearestNeighbors(point, 1, &index, &distance); if(index >= 0 && distance < maxDist){ AliDebugStream(1) << "Found closest base jet for " << countBase << " with match index " << index << " and distance " << distance << std::endl; faMatchIndexBase[countTag]=index; } else { AliDebugStream(1) << "Not found closest tag jet for " << countBase << ", distance to closest " << distance << std::endl; } #ifdef JETTAGGERFAST_TEST if(index>-1){ Double_t distanceTest(-1); distanceTest = TMath::Sqrt(TMath::Power(etaBase[index] - j->Eta(), 2) + TMath::Power(phiBase[index] - j->Phi(), 2)); if(TMath::Abs(distanceTest - distance) > DBL_EPSILON){ AliDebugStream(1) << "Mismatch in distance from base jet with index from tree: " << distanceTest << ", distance from tree " << distance << std::endl; fIndexErrorRateTag->Fill(1); } } #endif countTag++; } // check for "true" correlations // these are pairs where the base jet is the closest to the tag jet and vice versa // As the lists are linear a loop over the outer base jet is sufficient. AliDebugStream(1) << "Starting true jet loop: nbase(" << kNacceptedBase << "), ntag(" << kNacceptedTag << ")\n"; for(int ibase = 0; ibase < kNacceptedBase; ibase++) { AliDebugStream(2) << "base jet " << ibase << ": match index in tag jet container " << faMatchIndexTag[ibase] << "\n"; if(faMatchIndexTag[ibase] > -1){ AliDebugStream(2) << "tag jet " << faMatchIndexTag[ibase] << ": matched base jet " << faMatchIndexBase[faMatchIndexTag[ibase]] << "\n"; } if(faMatchIndexTag[ibase] > -1 && faMatchIndexBase[faMatchIndexTag[ibase]] == ibase) { AliDebugStream(2) << "found a true match \n"; AliEmcalJet *jetBase = jetsBase[ibase], *jetTag = jetsTag[faMatchIndexTag[ibase]]; if(jetBase && jetTag) { #ifdef JETTAGGERFAST_TEST if(TMath::Abs(etaBase[ibase] - jetBase->Eta()) > DBL_EPSILON || TMath::Abs(phiBase[ibase] - jetBase->Phi()) > DBL_EPSILON){ AliErrorStream() << "Selected incorrect base jet for tagging : eta test(" << jetBase->Eta() << ")/true(" << etaBase[ibase] << "), phi test(" << jetBase->Phi() << ")/true(" << phiBase[ibase] << ")\n"; fContainerErrorRateBase->Fill(1); } if(TMath::Abs(etaTag[faMatchIndexTag[ibase]] - jetTag->Eta()) > DBL_EPSILON || TMath::Abs(phiTag[faMatchIndexTag[ibase]] - jetTag->Phi()) > DBL_EPSILON){ AliErrorStream() << "Selected incorrect tag jet for tagging : eta test(" << jetTag->Eta() << ")/true(" << etaTag[faMatchIndexTag[ibase]] << "), phi test(" << jetTag->Phi() << ")/true(" << phiTag[faMatchIndexTag[ibase]] << ")\n"; fContainerErrorRateTag->Fill(1); } #endif // Test if the position of the jets correp Double_t dR = jetBase->DeltaR(jetTag); switch(fJetTaggingType){ case kTag: jetBase->SetTaggedJet(jetTag); jetBase->SetTagStatus(1); jetTag->SetTaggedJet(jetBase); jetTag->SetTagStatus(1); break; case kClosest: jetBase->SetClosestJet(jetTag,dR); jetTag->SetClosestJet(jetBase,dR); break; }; } } } return kTRUE; } Double_t AliEmcalJetTaggerTaskFast::GetDeltaPhi(const AliEmcalJet* jet1, const AliEmcalJet* jet2) { return GetDeltaPhi(jet1->Phi(),jet2->Phi()); } Double_t AliEmcalJetTaggerTaskFast::GetDeltaPhi(Double_t phi1,Double_t phi2) { Double_t dPhi = phi1-phi2; if(dPhi <-0.5*TMath::Pi()) dPhi += TMath::TwoPi(); if(dPhi > 1.5*TMath::Pi()) dPhi -= TMath::TwoPi(); return dPhi; } AliEmcalJetTaggerTaskFast *AliEmcalJetTaggerTaskFast::AddTaskJetTaggerFast(const char * njetsBase, const char * njetsTag, const Double_t R, const char * nrhoBase, const char * nrhoTag, const char * ntracks, const char * nclusters, const char * type, const char * CentEst, Int_t pSel, const char * trigClass){ AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { std::cerr << "E-AddEmcalJetTaggerTaskFast: No analysis manager found.\n"; return nullptr; } // Check the analysis type using the event handlers connected to the analysis manager. //============================================================================== if (!mgr->GetInputEventHandler()) { std::cerr << "E-AddEmcalJetTaggerTaskFast: This task requires an input event handler\n"; return NULL; } TString wagonName = Form("JetTagger_%s_%s_TC%s",njetsBase,njetsTag,trigClass); //Configure jet tagger task AliEmcalJetTaggerTaskFast *task = new AliEmcalJetTaggerTaskFast(wagonName); task->SetNCentBins(4); //task->SetVzRange(-10.,10.); AliParticleContainer *trackCont = task->AddParticleContainer(ntracks); AliClusterContainer *clusterCont = task->AddClusterContainer(nclusters); task->SetJetContainerBase(0); task->SetJetContainerTag(1); TString strType(type); AliJetContainer *jetContBase = task->AddJetContainer(njetsBase,strType,R); if(jetContBase) { jetContBase->SetRhoName(nrhoBase); jetContBase->ConnectParticleContainer(trackCont); jetContBase->ConnectClusterContainer(clusterCont); jetContBase->SetMaxTrackPt(10000.); } AliJetContainer *jetContTag = task->AddJetContainer(njetsTag,"TPC",R); if(jetContTag) { jetContTag->SetRhoName(nrhoTag); jetContTag->ConnectParticleContainer(trackCont); jetContTag->ConnectClusterContainer(clusterCont); jetContTag->SetMaxTrackPt(10000.); } for(Int_t i=0; i<2; i++) { task->SetPercAreaCut(0.6, i); //keep? } task->SetCentralityEstimator(CentEst); task->SelectCollisionCandidates(pSel); task->SetUseAliAnaUtils(kFALSE); mgr->AddTask(task); //Connnect input mgr->ConnectInput (task, 0, mgr->GetCommonInputContainer() ); //Connect output TString contName(wagonName); TString outputfile = Form("%s",AliAnalysisManager::GetCommonFileName()); AliAnalysisDataContainer *coutput1 = mgr->CreateContainer(contName.Data(), TList::Class(),AliAnalysisManager::kOutputContainer,outputfile); mgr->ConnectOutput(task,1,coutput1); return task; } } }
41.080537
194
0.638866
[ "vector" ]
298dbab1b823abb90581753175be5f8a190321d8
7,578
cpp
C++
src/Renderer/OpenGL/GraphicsDeviceOpenGL.cpp
foxostro/PinkTopaz
cd8275a93ea34a56f640f915d4b6c769e82e9dc2
[ "MIT" ]
1
2017-10-30T22:49:06.000Z
2017-10-30T22:49:06.000Z
src/Renderer/OpenGL/GraphicsDeviceOpenGL.cpp
foxostro/PinkTopaz
cd8275a93ea34a56f640f915d4b6c769e82e9dc2
[ "MIT" ]
null
null
null
src/Renderer/OpenGL/GraphicsDeviceOpenGL.cpp
foxostro/PinkTopaz
cd8275a93ea34a56f640f915d4b6c769e82e9dc2
[ "MIT" ]
null
null
null
// // GraphicsDeviceOpenGL.cpp // PinkTopaz // // Created by Andrew Fox on 7/8/16. // // #include "Renderer/OpenGL/GraphicsDeviceOpenGL.hpp" #include "Renderer/OpenGL/CommandEncoderOpenGL.hpp" #include "Renderer/OpenGL/ShaderOpenGL.hpp" #include "Renderer/OpenGL/TextureOpenGL.hpp" #include "Renderer/OpenGL/TextureSamplerOpenGL.hpp" #include "Renderer/OpenGL/BufferOpenGL.hpp" #include "Renderer/OpenGL/glUtilities.hpp" #include "Renderer/OpenGL/opengl.hpp" #include "SDLException.hpp" #include "FileUtilities.hpp" #include <vector> static constexpr unsigned FIRST_ID = 2; GraphicsDeviceOpenGL::GraphicsDeviceOpenGL(std::shared_ptr<spdlog::logger> log, SDL_Window &window) : _nextId(FIRST_ID), _window(window), _commandQueue(std::make_shared<CommandQueue>(log)) { // VMWare provides OpenGL 3.3. So, this is our minimum OpenGL version. // The next lowest is macOS, which provides 4.1. constexpr int desiredMajor = 3; constexpr int desiredMinor = 3; if (SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, desiredMajor) != 0) { throw SDLException("SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, desiredMajor={})", desiredMajor); } if (SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, desiredMinor) != 0) { throw SDLException("SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, desiredMinor={})", desiredMinor); } if (SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE) != 0) { throw SDLException("SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, SDL_GL_CONTEXT_PROFILE_CORE)"); } if (SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1) != 0) { throw SDLException("SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1)"); } if (SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1) != 0) { throw SDLException("SDL_GL_SetAttribute(SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, 1)"); } _glContext = SDL_GL_CreateContext(&_window); if (!_glContext) { throw SDLException("SDL_GL_CreateContext failed"); } // Check the OpenGL version and log an error if it's not supported. // But we'll try to run anyway. { int major = 0; int minor = 0; glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MINOR_VERSION, &minor); _log->info("OpenGL version is {}.{}", major, minor); if ((major < desiredMajor) || ((major == desiredMajor) && (minor < desiredMinor))) { _log->error("This application requires at least " "OpenGL {}.{} to run.", desiredMajor, desiredMinor); } } GLenum err = glewInit(); if (GLEW_OK != err) { throw GraphicsDeviceInitFailureOpenGLException("glewInit failed: {}", glewGetErrorString(err)); } if (SDL_GL_SetSwapInterval(1) != 0) { throw SDLException("SDL_GL_SetSwapInterval failed"); } glEnable(GL_FRAMEBUFFER_SRGB); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); glFrontFace(GL_CCW); // Determine the maximum sizes of buffers. int maxUniformBufferSize = 0; glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &maxUniformBufferSize); _maxBufferSizes[UniformBuffer] = (size_t)maxUniformBufferSize; _maxBufferSizes[ArrayBuffer] = std::numeric_limits<std::size_t>::max(); _maxBufferSizes[IndexBuffer] = std::numeric_limits<std::size_t>::max(); CHECK_GL_ERROR(); } GraphicsDeviceOpenGL::~GraphicsDeviceOpenGL() { SDL_GL_DeleteContext(_glContext); } std::shared_ptr<CommandEncoder> GraphicsDeviceOpenGL::encoder(const RenderPassDescriptor &desc) { auto encoder = std::make_shared<CommandEncoderOpenGL>(_log, nextId(), _commandQueue, desc); return std::dynamic_pointer_cast<CommandEncoder>(encoder); } void GraphicsDeviceOpenGL::swapBuffers() { _commandQueue->execute(); SDL_GL_SwapWindow(&_window); } std::shared_ptr<Shader> GraphicsDeviceOpenGL::makeShader(const VertexFormat &vertexFormat, const std::string &vertexProgramName, const std::string &fragmentProgramName, bool blending) { const boost::filesystem::path vertexProgramSourceFileName(vertexProgramName + ".glsl"); std::string vertexShaderSource = stringFromFileContents(vertexProgramSourceFileName); const boost::filesystem::path fragmentProgramSourceFileName(fragmentProgramName + ".glsl"); std::string fragmentShaderSource = stringFromFileContents(fragmentProgramSourceFileName); auto shader = std::make_shared<ShaderOpenGL>(nextId(), _commandQueue, vertexFormat, vertexShaderSource, fragmentShaderSource, blending); return std::dynamic_pointer_cast<Shader>(shader); } std::shared_ptr<Texture> GraphicsDeviceOpenGL::makeTexture(const TextureDescriptor &desc, const void *data) { auto texture = std::make_shared<TextureOpenGL>(nextId(), _commandQueue, desc, data); return std::dynamic_pointer_cast<Texture>(texture); } std::shared_ptr<Texture> GraphicsDeviceOpenGL::makeTexture(const TextureDescriptor &desc, const std::vector<uint8_t> &data) { auto texture = std::make_shared<TextureOpenGL>(nextId(), _commandQueue, desc, data); return std::dynamic_pointer_cast<Texture>(texture); } std::shared_ptr<TextureSampler> GraphicsDeviceOpenGL::makeTextureSampler(const TextureSamplerDescriptor &desc) { auto sampler = std::make_shared<TextureSamplerOpenGL>(nextId(), _commandQueue, desc); return std::dynamic_pointer_cast<TextureSampler>(sampler); } std::shared_ptr<Buffer> GraphicsDeviceOpenGL::makeBuffer(const std::vector<uint8_t> &data, BufferUsage usage, BufferType bufferType) { auto buffer = std::make_shared<BufferOpenGL>(nextId(), _commandQueue, data, usage, bufferType); return std::dynamic_pointer_cast<Buffer>(buffer); } std::shared_ptr<Buffer> GraphicsDeviceOpenGL::makeBuffer(size_t bufferSize, const void *bufferData, BufferUsage usage, BufferType bufferType) { auto buffer = std::make_shared<BufferOpenGL>(nextId(), _commandQueue, bufferSize, bufferData, usage, bufferType); return std::dynamic_pointer_cast<Buffer>(buffer); } std::shared_ptr<Buffer> GraphicsDeviceOpenGL::makeBuffer(size_t bufferSize, BufferUsage usage, BufferType bufferType) { auto buffer = std::make_shared<BufferOpenGL>(nextId(), _commandQueue, bufferSize, usage, bufferType); return std::dynamic_pointer_cast<Buffer>(buffer); } size_t GraphicsDeviceOpenGL::getMaxBufferSize(BufferType bufferType) { return _maxBufferSizes[bufferType]; } void GraphicsDeviceOpenGL::windowSizeChanged() {} const glm::mat4& GraphicsDeviceOpenGL::getProjectionAdjustMatrix() const { static const glm::mat4 identity; return identity; } unsigned GraphicsDeviceOpenGL::nextId() { return _nextId++; }
37.147059
123
0.659409
[ "vector" ]
29926812989f5ce1afe315e427434dd27efaf2cf
29,220
cpp
C++
src/main/cpp/domconfigurator.cpp
Blaxar/log4cxxNG
8dfdfa2ab3d2fe598a41ec95e71ef01e79bac2ae
[ "Apache-2.0" ]
null
null
null
src/main/cpp/domconfigurator.cpp
Blaxar/log4cxxNG
8dfdfa2ab3d2fe598a41ec95e71ef01e79bac2ae
[ "Apache-2.0" ]
null
null
null
src/main/cpp/domconfigurator.cpp
Blaxar/log4cxxNG
8dfdfa2ab3d2fe598a41ec95e71ef01e79bac2ae
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <log4cxxNG/logstring.h> #include <log4cxxNG/xml/domconfigurator.h> #include <log4cxxNG/appender.h> #include <log4cxxNG/layout.h> #include <log4cxxNG/logger.h> #include <log4cxxNG/logmanager.h> #include <log4cxxNG/level.h> #include <log4cxxNG/spi/filter.h> #include <log4cxxNG/helpers/loglog.h> #include <log4cxxNG/helpers/stringhelper.h> #include <log4cxxNG/helpers/loader.h> #include <log4cxxNG/helpers/optionconverter.h> #include <log4cxxNG/config/propertysetter.h> #include <log4cxxNG/spi/errorhandler.h> #include <log4cxxNG/spi/loggerfactory.h> #include <log4cxxNG/defaultloggerfactory.h> #include <log4cxxNG/helpers/filewatchdog.h> #include <log4cxxNG/helpers/synchronized.h> #include <log4cxxNG/spi/loggerrepository.h> #include <log4cxxNG/spi/loggingevent.h> #include <log4cxxNG/helpers/pool.h> #include <sstream> #include <log4cxxNG/helpers/transcoder.h> #include <log4cxxNG/rolling/rollingfileappender.h> #include <log4cxxNG/rolling/filterbasedtriggeringpolicy.h> #include <apr_xml.h> #include <log4cxxNG/helpers/bytebuffer.h> #include <log4cxxNG/helpers/charsetdecoder.h> #include <log4cxxNG/net/smtpappender.h> #include <log4cxxNG/helpers/messagebuffer.h> #define LOG4CXXNG 1 #include <log4cxxNG/helpers/aprinitializer.h> using namespace log4cxxng; using namespace log4cxxng::xml; using namespace log4cxxng::helpers; using namespace log4cxxng::spi; using namespace log4cxxng::config; using namespace log4cxxng::rolling; #if APR_HAS_THREADS namespace log4cxxng { namespace xml { class XMLWatchdog : public FileWatchdog { public: XMLWatchdog(const File& filename) : FileWatchdog(filename) { } /** Call DOMConfigurator#doConfigure with the <code>filename</code> to reconfigure log4cxx. */ void doOnChange() { DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); } }; } } XMLWatchdog* DOMConfigurator::xdog = NULL; #endif IMPLEMENT_LOG4CXXNG_OBJECT(DOMConfigurator) #define CONFIGURATION_TAG "log4j:configuration" #define OLD_CONFIGURATION_TAG "configuration" #define APPENDER_TAG "appender" #define APPENDER_REF_TAG "appender-ref" #define PARAM_TAG "param" #define LAYOUT_TAG "layout" #define ROLLING_POLICY_TAG "rollingPolicy" #define TRIGGERING_POLICY_TAG "triggeringPolicy" #define CATEGORY "category" #define LOGGER "logger" #define LOGGER_REF "logger-ref" #define CATEGORY_FACTORY_TAG "categoryFactory" #define NAME_ATTR "name" #define CLASS_ATTR "class" #define VALUE_ATTR "value" #define ROOT_TAG "root" #define ROOT_REF "root-ref" #define LEVEL_TAG "level" #define PRIORITY_TAG "priority" #define FILTER_TAG "filter" #define ERROR_HANDLER_TAG "errorHandler" #define REF_ATTR "ref" #define ADDITIVITY_ATTR "additivity" #define THRESHOLD_ATTR "threshold" #define STRINGSTREAM_ATTR "stringstream" #define CONFIG_DEBUG_ATTR "configDebug" #define INTERNAL_DEBUG_ATTR "debug" DOMConfigurator::DOMConfigurator() : props(), repository() { } void DOMConfigurator::addRef() const { ObjectImpl::addRef(); } void DOMConfigurator::releaseRef() const { ObjectImpl::releaseRef(); } /** Used internally to parse appenders by IDREF name. */ AppenderPtr DOMConfigurator::findAppenderByName(log4cxxng::helpers::Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, apr_xml_doc* doc, const LogString& appenderName, AppenderMap& appenders) { AppenderPtr appender; std::string tagName(element->name); if (tagName == APPENDER_TAG) { if (appenderName == getAttribute(utf8Decoder, element, NAME_ATTR)) { appender = parseAppender(p, utf8Decoder, element, doc, appenders); } } if (element->first_child && !appender) { appender = findAppenderByName(p, utf8Decoder, element->first_child, doc, appenderName, appenders); } if (element->next && !appender) { appender = findAppenderByName(p, utf8Decoder, element->next, doc, appenderName, appenders); } return appender; } /** Used internally to parse appenders by IDREF element. */ AppenderPtr DOMConfigurator::findAppenderByReference( log4cxxng::helpers::Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* appenderRef, apr_xml_doc* doc, AppenderMap& appenders) { LogString appenderName(subst(getAttribute(utf8Decoder, appenderRef, REF_ATTR))); AppenderMap::const_iterator match = appenders.find(appenderName); AppenderPtr appender; if (match != appenders.end()) { appender = match->second; } else if (doc) { appender = findAppenderByName(p, utf8Decoder, doc->root, doc, appenderName, appenders); if (appender) { appenders.insert(AppenderMap::value_type(appenderName, appender)); } } if (!appender) { LogLog::error(LOG4CXXNG_STR("No appender named [") + appenderName + LOG4CXXNG_STR("] could be found.")); } return appender; } /** Used internally to parse an appender element. */ AppenderPtr DOMConfigurator::parseAppender(Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* appenderElement, apr_xml_doc* doc, AppenderMap& appenders) { LogString className(subst(getAttribute(utf8Decoder, appenderElement, CLASS_ATTR))); LogLog::debug(LOG4CXXNG_STR("Class name: [") + className + LOG4CXXNG_STR("]")); try { ObjectPtr instance = Loader::loadClass(className).newInstance(); AppenderPtr appender = instance; PropertySetter propSetter(appender); appender->setName(subst(getAttribute(utf8Decoder, appenderElement, NAME_ATTR))); for (apr_xml_elem* currentElement = appenderElement->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); // Parse appender parameters if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } // Set appender layout else if (tagName == LAYOUT_TAG) { appender->setLayout(parseLayout(p, utf8Decoder, currentElement)); } // Add filters else if (tagName == FILTER_TAG) { std::vector<log4cxxng::spi::FilterPtr> filters; parseFilters(p, utf8Decoder, currentElement, filters); for (std::vector<log4cxxng::spi::FilterPtr>::iterator iter = filters.begin(); iter != filters.end(); iter++) { appender->addFilter(*iter); } } else if (tagName == ERROR_HANDLER_TAG) { parseErrorHandler(p, utf8Decoder, currentElement, appender, doc, appenders); } else if (tagName == ROLLING_POLICY_TAG) { RollingPolicyPtr rollPolicy(parseRollingPolicy(p, utf8Decoder, currentElement)); RollingFileAppenderPtr rfa(appender); if (rfa != NULL) { rfa->setRollingPolicy(rollPolicy); } } else if (tagName == TRIGGERING_POLICY_TAG) { ObjectPtr policy(parseTriggeringPolicy(p, utf8Decoder, currentElement)); RollingFileAppenderPtr rfa(appender); if (rfa != NULL) { rfa->setTriggeringPolicy(policy); } else { log4cxxng::net::SMTPAppenderPtr smtpa(appender); if (smtpa != NULL) { log4cxxng::spi::TriggeringEventEvaluatorPtr evaluator(policy); smtpa->setEvaluator(evaluator); } } } else if (tagName == APPENDER_REF_TAG) { LogString refName = subst(getAttribute(utf8Decoder, currentElement, REF_ATTR)); if (appender->instanceof(AppenderAttachable::getStaticClass())) { AppenderAttachablePtr aa(appender); LogLog::debug(LOG4CXXNG_STR("Attaching appender named [") + refName + LOG4CXXNG_STR("] to appender named [") + appender->getName() + LOG4CXXNG_STR("].")); aa->addAppender(findAppenderByReference(p, utf8Decoder, currentElement, doc, appenders)); } else { LogLog::error(LOG4CXXNG_STR("Requesting attachment of appender named [") + refName + LOG4CXXNG_STR("] to appender named [") + appender->getName() + LOG4CXXNG_STR("] which does not implement AppenderAttachable.")); } } } propSetter.activate(p); return appender; } /* Yes, it's ugly. But all of these exceptions point to the same problem: we can't create an Appender */ catch (Exception& oops) { LogLog::error(LOG4CXXNG_STR("Could not create an Appender. Reported error follows."), oops); return 0; } } /** Used internally to parse an {@link ErrorHandler} element. */ void DOMConfigurator::parseErrorHandler(Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, AppenderPtr& appender, apr_xml_doc* doc, AppenderMap& appenders) { ErrorHandlerPtr eh = OptionConverter::instantiateByClassName( subst(getAttribute(utf8Decoder, element, CLASS_ATTR)), ErrorHandler::getStaticClass(), 0); if (eh != 0) { eh->setAppender(appender); PropertySetter propSetter(eh); for (apr_xml_elem* currentElement = element->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } else if (tagName == APPENDER_REF_TAG) { eh->setBackupAppender(findAppenderByReference(p, utf8Decoder, currentElement, doc, appenders)); } else if (tagName == LOGGER_REF) { LogString loggerName(getAttribute(utf8Decoder, currentElement, REF_ATTR)); LoggerPtr logger = repository->getLogger(loggerName, loggerFactory); eh->setLogger(logger); } else if (tagName == ROOT_REF) { LoggerPtr root = repository->getRootLogger(); eh->setLogger(root); } } propSetter.activate(p); ObjectPtrT<AppenderSkeleton> appSkeleton(appender); if (appSkeleton != 0) { appSkeleton->setErrorHandler(eh); } } } /** Used internally to parse a filter element. */ void DOMConfigurator::parseFilters(Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, std::vector<log4cxxng::spi::FilterPtr>& filters) { LogString clazz = subst(getAttribute(utf8Decoder, element, CLASS_ATTR)); FilterPtr filter = OptionConverter::instantiateByClassName(clazz, Filter::getStaticClass(), 0); if (filter != 0) { PropertySetter propSetter(filter); for (apr_xml_elem* currentElement = element->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } } propSetter.activate(p); filters.push_back(filter); } } /** Used internally to parse an category or logger element. */ void DOMConfigurator::parseLogger( log4cxxng::helpers::Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* loggerElement, apr_xml_doc* doc, AppenderMap& appenders) { // Create a new Logger object from the <category> element. LogString loggerName = subst(getAttribute(utf8Decoder, loggerElement, NAME_ATTR)); LogLog::debug(LOG4CXXNG_STR("Retreiving an instance of Logger.")); LoggerPtr logger = repository->getLogger(loggerName, loggerFactory); // Setting up a logger needs to be an atomic operation, in order // to protect potential log operations while logger // configuration is in progress. LOCK_W sync(logger->getMutex()); bool additivity = OptionConverter::toBoolean( subst(getAttribute(utf8Decoder, loggerElement, ADDITIVITY_ATTR)), true); LogLog::debug(LOG4CXXNG_STR("Setting [") + logger->getName() + LOG4CXXNG_STR("] additivity to [") + (additivity ? LogString(LOG4CXXNG_STR("true")) : LogString(LOG4CXXNG_STR("false"))) + LOG4CXXNG_STR("].")); logger->setAdditivity(additivity); parseChildrenOfLoggerElement(p, utf8Decoder, loggerElement, logger, false, doc, appenders); } /** Used internally to parse the logger factory element. */ void DOMConfigurator::parseLoggerFactory( log4cxxng::helpers::Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* factoryElement) { LogString className(subst(getAttribute(utf8Decoder, factoryElement, CLASS_ATTR))); if (className.empty()) { LogLog::error(LOG4CXXNG_STR("Logger Factory tag class attribute not found.")); LogLog::debug(LOG4CXXNG_STR("No Logger Factory configured.")); } else { LogLog::debug(LOG4CXXNG_STR("Desired logger factory: [") + className + LOG4CXXNG_STR("]")); loggerFactory = OptionConverter::instantiateByClassName( className, LoggerFactory::getStaticClass(), 0); PropertySetter propSetter(loggerFactory); for (apr_xml_elem* currentElement = factoryElement->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } } } } /** Used internally to parse the root logger element. */ void DOMConfigurator::parseRoot( log4cxxng::helpers::Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* rootElement, apr_xml_doc* doc, AppenderMap& appenders) { LoggerPtr root = repository->getRootLogger(); // logger configuration needs to be atomic LOCK_W sync(root->getMutex()); parseChildrenOfLoggerElement(p, utf8Decoder, rootElement, root, true, doc, appenders); } /** Used internally to parse the children of a logger element. */ void DOMConfigurator::parseChildrenOfLoggerElement( log4cxxng::helpers::Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* loggerElement, LoggerPtr logger, bool isRoot, apr_xml_doc* doc, AppenderMap& appenders) { PropertySetter propSetter(logger); // Remove all existing appenders from logger. They will be // reconstructed if need be. logger->removeAllAppenders(); for (apr_xml_elem* currentElement = loggerElement->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == APPENDER_REF_TAG) { AppenderPtr appender = findAppenderByReference(p, utf8Decoder, currentElement, doc, appenders); LogString refName = subst(getAttribute(utf8Decoder, currentElement, REF_ATTR)); if (appender != 0) { LogLog::debug(LOG4CXXNG_STR("Adding appender named [") + refName + LOG4CXXNG_STR("] to logger [") + logger->getName() + LOG4CXXNG_STR("].")); } else { LogLog::debug(LOG4CXXNG_STR("Appender named [") + refName + LOG4CXXNG_STR("] not found.")); } logger->addAppender(appender); } else if (tagName == LEVEL_TAG) { parseLevel(p, utf8Decoder, currentElement, logger, isRoot); } else if (tagName == PRIORITY_TAG) { parseLevel(p, utf8Decoder, currentElement, logger, isRoot); } else if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } } propSetter.activate(p); } /** Used internally to parse a layout element. */ LayoutPtr DOMConfigurator::parseLayout ( log4cxxng::helpers::Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* layout_element) { LogString className(subst(getAttribute(utf8Decoder, layout_element, CLASS_ATTR))); LogLog::debug(LOG4CXXNG_STR("Parsing layout of class: \"") + className + LOG4CXXNG_STR("\"")); try { ObjectPtr instance = Loader::loadClass(className).newInstance(); LayoutPtr layout = instance; PropertySetter propSetter(layout); for (apr_xml_elem* currentElement = layout_element->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } } propSetter.activate(p); return layout; } catch (Exception& oops) { LogLog::error(LOG4CXXNG_STR("Could not create the Layout. Reported error follows."), oops); return 0; } } /** Used internally to parse a triggering policy */ ObjectPtr DOMConfigurator::parseTriggeringPolicy ( log4cxxng::helpers::Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* layout_element) { LogString className = subst(getAttribute(utf8Decoder, layout_element, CLASS_ATTR)); LogLog::debug(LOG4CXXNG_STR("Parsing triggering policy of class: \"") + className + LOG4CXXNG_STR("\"")); try { ObjectPtr instance = Loader::loadClass(className).newInstance(); PropertySetter propSetter(instance); for (apr_xml_elem* currentElement = layout_element->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } else if (tagName == FILTER_TAG) { std::vector<log4cxxng::spi::FilterPtr> filters; parseFilters(p, utf8Decoder, currentElement, filters); FilterBasedTriggeringPolicyPtr fbtp(instance); if (fbtp != NULL) { for (std::vector<log4cxxng::spi::FilterPtr>::iterator iter = filters.begin(); iter != filters.end(); iter++) { fbtp->addFilter(*iter); } } } } propSetter.activate(p); return instance; } catch (Exception& oops) { LogLog::error(LOG4CXXNG_STR("Could not create the TriggeringPolicy. Reported error follows."), oops); return 0; } } /** Used internally to parse a triggering policy */ RollingPolicyPtr DOMConfigurator::parseRollingPolicy ( log4cxxng::helpers::Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* layout_element) { LogString className = subst(getAttribute(utf8Decoder, layout_element, CLASS_ATTR)); LogLog::debug(LOG4CXXNG_STR("Parsing rolling policy of class: \"") + className + LOG4CXXNG_STR("\"")); try { ObjectPtr instance = Loader::loadClass(className).newInstance(); RollingPolicyPtr layout = instance; PropertySetter propSetter(layout); for (apr_xml_elem* currentElement = layout_element->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == PARAM_TAG) { setParameter(p, utf8Decoder, currentElement, propSetter); } } propSetter.activate(p); return layout; } catch (Exception& oops) { LogLog::error(LOG4CXXNG_STR("Could not create the RollingPolicy. Reported error follows."), oops); return 0; } } /** Used internally to parse a level element. */ void DOMConfigurator::parseLevel( log4cxxng::helpers::Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, LoggerPtr logger, bool isRoot) { LogString loggerName = logger->getName(); if (isRoot) { loggerName = LOG4CXXNG_STR("root"); } LogString levelStr(subst(getAttribute(utf8Decoder, element, VALUE_ATTR))); LogLog::debug(LOG4CXXNG_STR("Level value for ") + loggerName + LOG4CXXNG_STR(" is [") + levelStr + LOG4CXXNG_STR("].")); if (StringHelper::equalsIgnoreCase(levelStr, LOG4CXXNG_STR("INHERITED"), LOG4CXXNG_STR("inherited")) || StringHelper::equalsIgnoreCase(levelStr, LOG4CXXNG_STR("NULL"), LOG4CXXNG_STR("null"))) { if (isRoot) { LogLog::error(LOG4CXXNG_STR("Root level cannot be inherited. Ignoring directive.")); } else { logger->setLevel(0); } } else { LogString className(subst(getAttribute(utf8Decoder, element, CLASS_ATTR))); if (className.empty()) { logger->setLevel(OptionConverter::toLevel(levelStr, Level::getDebug())); } else { LogLog::debug(LOG4CXXNG_STR("Desired Level sub-class: [") + className + LOG4CXXNG_STR("]")); try { Level::LevelClass& levelClass = (Level::LevelClass&)Loader::loadClass(className); LevelPtr level = levelClass.toLevel(levelStr); logger->setLevel(level); } catch (Exception& oops) { LogLog::error( LOG4CXXNG_STR("Could not create level [") + levelStr + LOG4CXXNG_STR("]. Reported error follows."), oops); return; } catch (...) { LogLog::error( LOG4CXXNG_STR("Could not create level [") + levelStr); return; } } } LogLog::debug(loggerName + LOG4CXXNG_STR(" level set to ") + logger->getEffectiveLevel()->toString()); } void DOMConfigurator::setParameter(log4cxxng::helpers::Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* elem, PropertySetter& propSetter) { LogString name(subst(getAttribute(utf8Decoder, elem, NAME_ATTR))); LogString value(subst(getAttribute(utf8Decoder, elem, VALUE_ATTR))); value = subst(value); propSetter.setProperty(name, value, p); } void DOMConfigurator::doConfigure(const File& filename, spi::LoggerRepositoryPtr& repository1) { repository1->setConfigured(true); this->repository = repository1; LogString msg(LOG4CXXNG_STR("DOMConfigurator configuring file ")); msg.append(filename.getPath()); msg.append(LOG4CXXNG_STR("...")); LogLog::debug(msg); loggerFactory = new DefaultLoggerFactory(); Pool p; apr_file_t* fd; log4cxxng_status_t rv = filename.open(&fd, APR_READ, APR_OS_DEFAULT, p); if (rv != APR_SUCCESS) { LogString msg2(LOG4CXXNG_STR("Could not open file [")); msg2.append(filename.getPath()); msg2.append(LOG4CXXNG_STR("].")); LogLog::error(msg2); } else { apr_xml_parser* parser = NULL; apr_xml_doc* doc = NULL; rv = apr_xml_parse_file(p.getAPRPool(), &parser, &doc, fd, 2000); if (rv != APR_SUCCESS) { char errbuf[2000]; char errbufXML[2000]; LogString msg2(LOG4CXXNG_STR("Error parsing file [")); msg2.append(filename.getPath()); msg2.append(LOG4CXXNG_STR("], ")); apr_strerror(rv, errbuf, sizeof(errbuf)); LOG4CXXNG_DECODE_CHAR(lerrbuf, std::string(errbuf)); msg2.append(lerrbuf); if (parser) { apr_xml_parser_geterror(parser, errbufXML, sizeof(errbufXML)); LOG4CXXNG_DECODE_CHAR(lerrbufXML, std::string(errbufXML)); msg2.append(lerrbufXML); } LogLog::error(msg2); } else { AppenderMap appenders; CharsetDecoderPtr utf8Decoder(CharsetDecoder::getUTF8Decoder()); parse(p, utf8Decoder, doc->root, doc, appenders); } } } void DOMConfigurator::configure(const std::string& filename) { File file(filename); DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); } #if LOG4CXXNG_WCHAR_T_API void DOMConfigurator::configure(const std::wstring& filename) { File file(filename); DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); } #endif #if LOG4CXXNG_UNICHAR_API void DOMConfigurator::configure(const std::basic_string<UniChar>& filename) { File file(filename); DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); } #endif #if LOG4CXXNG_CFSTRING_API void DOMConfigurator::configure(const CFStringRef& filename) { File file(filename); DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); } #endif void DOMConfigurator::configureAndWatch(const std::string& filename) { configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY); } #if LOG4CXXNG_WCHAR_T_API void DOMConfigurator::configureAndWatch(const std::wstring& filename) { configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY); } #endif #if LOG4CXXNG_UNICHAR_API void DOMConfigurator::configureAndWatch(const std::basic_string<UniChar>& filename) { configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY); } #endif #if LOG4CXXNG_CFSTRING_API void DOMConfigurator::configureAndWatch(const CFStringRef& filename) { configureAndWatch(filename, FileWatchdog::DEFAULT_DELAY); } #endif void DOMConfigurator::configureAndWatch(const std::string& filename, long delay) { File file(filename); #if APR_HAS_THREADS if ( xdog ) { APRInitializer::unregisterCleanup(xdog); delete xdog; } xdog = new XMLWatchdog(file); APRInitializer::registerCleanup(xdog); xdog->setDelay(delay); xdog->start(); #else DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); #endif } #if LOG4CXXNG_WCHAR_T_API void DOMConfigurator::configureAndWatch(const std::wstring& filename, long delay) { File file(filename); #if APR_HAS_THREADS if ( xdog ) { APRInitializer::unregisterCleanup(xdog); delete xdog; } xdog = new XMLWatchdog(file); APRInitializer::registerCleanup(xdog); xdog->setDelay(delay); xdog->start(); #else DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); #endif } #endif #if LOG4CXXNG_UNICHAR_API void DOMConfigurator::configureAndWatch(const std::basic_string<UniChar>& filename, long delay) { File file(filename); #if APR_HAS_THREADS if ( xdog ) { APRInitializer::unregisterCleanup(xdog); delete xdog; } xdog = new XMLWatchdog(file); APRInitializer::registerCleanup(xdog); xdog->setDelay(delay); xdog->start(); #else DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); #endif } #endif #if LOG4CXXNG_CFSTRING_API void DOMConfigurator::configureAndWatch(const CFStringRef& filename, long delay) { File file(filename); #if APR_HAS_THREADS if ( xdog ) { APRInitializer::unregisterCleanup(xdog); delete xdog; } xdog = new XMLWatchdog(file); APRInitializer::registerCleanup(xdog); xdog->setDelay(delay); xdog->start(); #else DOMConfigurator().doConfigure(file, LogManager::getLoggerRepository()); #endif } #endif void DOMConfigurator::parse( Pool& p, log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, apr_xml_doc* doc, AppenderMap& appenders) { std::string rootElementName(element->name); if (rootElementName != CONFIGURATION_TAG) { if (rootElementName == OLD_CONFIGURATION_TAG) { //LogLog::warn(LOG4CXXNG_STR("The <")+String(OLD_CONFIGURATION_TAG)+ // LOG4CXXNG_STR("> element has been deprecated.")); //LogLog::warn(LOG4CXXNG_STR("Use the <")+String(CONFIGURATION_TAG)+ // LOG4CXXNG_STR("> element instead.")); } else { LogLog::error(LOG4CXXNG_STR("DOM element is - not a <configuration> element.")); return; } } LogString debugAttrib = subst(getAttribute(utf8Decoder, element, INTERNAL_DEBUG_ATTR)); static const LogString NuLL(LOG4CXXNG_STR("NULL")); LogLog::debug(LOG4CXXNG_STR("debug attribute= \"") + debugAttrib + LOG4CXXNG_STR("\".")); // if the log4j.dtd is not specified in the XML file, then the // "debug" attribute is returned as the empty string. if (!debugAttrib.empty() && debugAttrib != NuLL) { LogLog::setInternalDebugging(OptionConverter::toBoolean(debugAttrib, true)); } else { LogLog::debug(LOG4CXXNG_STR("Ignoring internalDebug attribute.")); } LogString confDebug = subst(getAttribute(utf8Decoder, element, CONFIG_DEBUG_ATTR)); if (!confDebug.empty() && confDebug != NuLL) { LogLog::warn(LOG4CXXNG_STR("The \"configDebug\" attribute is deprecated.")); LogLog::warn(LOG4CXXNG_STR("Use the \"internalDebug\" attribute instead.")); LogLog::setInternalDebugging(OptionConverter::toBoolean(confDebug, true)); } LogString thresholdStr = subst(getAttribute(utf8Decoder, element, THRESHOLD_ATTR)); LogLog::debug(LOG4CXXNG_STR("Threshold =\"") + thresholdStr + LOG4CXXNG_STR("\".")); if (!thresholdStr.empty() && thresholdStr != NuLL) { repository->setThreshold(thresholdStr); } LogString strstrValue = subst(getAttribute(utf8Decoder, element, STRINGSTREAM_ATTR)); LogLog::debug(LOG4CXXNG_STR("Stringstream =\"") + strstrValue + LOG4CXXNG_STR("\".")); if (!strstrValue.empty() && strstrValue != NuLL) { MessageBufferUseStaticStream(); } apr_xml_elem* currentElement; for (currentElement = element->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == CATEGORY_FACTORY_TAG) { parseLoggerFactory(p, utf8Decoder, currentElement); } } for (currentElement = element->first_child; currentElement; currentElement = currentElement->next) { std::string tagName(currentElement->name); if (tagName == CATEGORY || tagName == LOGGER) { parseLogger(p, utf8Decoder, currentElement, doc, appenders); } else if (tagName == ROOT_TAG) { parseRoot(p, utf8Decoder, currentElement, doc, appenders); } } } LogString DOMConfigurator::subst(const LogString& value) { try { return OptionConverter::substVars(value, props); } catch (IllegalArgumentException& e) { LogLog::warn(LOG4CXXNG_STR("Could not perform variable substitution."), e); return value; } } LogString DOMConfigurator::getAttribute( log4cxxng::helpers::CharsetDecoderPtr& utf8Decoder, apr_xml_elem* element, const std::string& attrName) { LogString attrValue; for (apr_xml_attr* attr = element->attr; attr; attr = attr->next) { if (attrName == attr->name) { ByteBuffer buf((char*) attr->value, strlen(attr->value)); utf8Decoder->decode(buf, attrValue); } } return attrValue; }
26.276978
121
0.730493
[ "object", "vector" ]
29926a328a8d2fbd583dbf45f4eebcba525716b1
10,708
hpp
C++
src/Gui/BaseApplication.hpp
Yasoo31/Radium-Engine
e22754d0abe192207fd946509cbd63c4f9e52dd4
[ "Apache-2.0" ]
78
2017-12-01T12:23:22.000Z
2022-03-31T05:08:09.000Z
src/Gui/BaseApplication.hpp
Yasoo31/Radium-Engine
e22754d0abe192207fd946509cbd63c4f9e52dd4
[ "Apache-2.0" ]
527
2017-09-25T13:05:32.000Z
2022-03-31T18:47:44.000Z
src/Gui/BaseApplication.hpp
Yasoo31/Radium-Engine
e22754d0abe192207fd946509cbd63c4f9e52dd4
[ "Apache-2.0" ]
48
2018-01-04T22:08:08.000Z
2022-03-03T08:13:41.000Z
#pragma once #include <atomic> #include <chrono> #include <memory> #include <vector> #include <QApplication> #include <Core/Utils/Timer.hpp> #include <Gui/TimerData/FrameTimerData.hpp> #include <PluginBase/RadiumPluginInterface.hpp> class QTimer; class QCommandLineParser; namespace Ra { namespace Engine { class RadiumEngine; namespace Scene { class GeometrySystem; struct ItemEntry; } // namespace Scene } // namespace Engine namespace Gui { class Viewer; class MainWindowInterface; /// This class contains the main application logic. It owns the engine and the GUI. class RA_GUI_API BaseApplication : public QApplication { Q_OBJECT public: class WindowFactory { public: WindowFactory() = default; virtual ~WindowFactory() = default; virtual Ra::Gui::MainWindowInterface* createMainWindow() const = 0; }; /** Setup the application, create main window and main connections. * * \param argc from main() * \param argv from main() * \param applicationName Name of the application (used to store settings) * \param organizationName Name of the organization (used to store settings) * * The arguments managed from the command line are the following : * \snippet Gui/BaseApplication.cpp Command line arguments */ BaseApplication( int& argc, char** argv, QString applicationName = "RadiumEngine", QString organizationName = "STORM-IRIT" ); ~BaseApplication() override; /** Initialize the application, create the Gui and OpenGL environment. * The initialization of an application is made in several steps * 1. Create and initialize the engine and its non-OpenGL services * - Once the engine singleton is instanciated, call the BaseApplication's virtual method * engineBaseInitialization to populate the engine with the base systems * (eg. GeometrySystem) and configure the non-openGL engine services. * 2. Create and initialize the openGL environment * - When the openGL context is ready and bound, call the BaseApplication's virtual method * engineOpenGLInitialize (this method is a virtual slot connected to the event * Gui::Viewer::requestEngineOpenGLInitialization). * - When the application and its opengl window are ready, call the BaseApplication's * virtual method initializeGl (this method is a virtual slot connected to the event * Gui::Viewer::glInitialized). * 3. Create Plugin context, load plugins, configure base Radium::IO services * - The plugins located int the registered plugin paths (into the Radium Engine or * bundled with the installed application, into paths found in the app configuration file) * are loaded automatically. * - The Radium::IO services compiled into the Radium bundle are configured (file loaders) * - After plugins and default services are configured, call the BaseApplication's virtual * method addApplicationExtension. * 4. Manage scene related command-line argument * - loads the given scene, ... * * \param factory : a functor that instanciate the mainWindow * @note The initialize method call virtual methods on the object being initialized to * configure the engine and application services. * When redefining those methods, it is recommended to call the inherited one to have * consistent initialization wrt the BaseApplication ancestor. * The initialize method could be also overloaded by derived classes. In this case, it is * recommended that the overload explicetely call the ancestor method.. * \todo allow the user to ask for some "standard" systems to be added to the initialized * Engine. */ void initialize( const WindowFactory& factory ); /** * This method configure the base, non opengl dependant, scene services. * * It is expected that this method add the Engine's systems required by the application. * and configure the engine time management properties. * The default implementation add the following systems : * - Ra::Engine::GeometrySystem * * The default implementation also configure the time system according to the user requested * frame rate (app command line argument -framerate) or to the default 60fps. */ virtual void engineBaseInitialization(); /** * Allow derived applications to add specific extensions to the engine and the base application. * Such extensions are expected to be : * - specific file loaders * - specific plugins * - specific global resources needed by the application (Textures, shaders, ...) * This method could also be used to populate the engine with systems or with OpenGL related * services if this was not already done in the appropriate methods (engineBaseInitialization, * engineOpenGLInitialize, initializeGl) * - specific renderers (could be added instead when configuring OpenGL) * - */ virtual void addApplicationExtension() {}; /// Advance the engine for one frame. void radiumFrame(); bool isRunning() const { return !m_isAboutToQuit; } const Engine::RadiumEngine* getEngine() const { return m_engine.get(); } uint getFrameCount() const { return m_frameCounter; } const std::string& getExportFolderName() const { return m_exportFoldername; } /// Allow the user to register a specific plugin directory for the application void addPluginDirectory( const std::string& pluginDir ); /// Remove all registered plugin directories (except the default Radium Bundle one) void clearPluginDirectories(); /// Open the QSetting editor for the current application /// \todo implement the editor void editSettings(); /// Get the html formatted help text virtual std::string getHelpText() const; signals: /// Fired when the engine has just started, before the frame timer is set. void starting(); /// Fired when the engine is about to stop. void stopping(); /// Fired when the scene has changed. void sceneChanged( const Core::Aabb& ); void updateFrameStats( const std::vector<FrameTimerData>& ); void loadComplete(); void selectedItem( const Ra::Engine::Scene::ItemEntry& entry ); public slots: /// slot called when the OpenGL need to be initialized virtual void engineOpenGLInitialize(); /// slot called once the application window and its OpenGL services are ready. /// TODO : rename this to be more representative of post opengl & gui operations virtual void initializeGl(); void updateRadiumFrameIfNeeded() { // Main loop if ( m_isUpdateNeeded.load() ) radiumFrame(); if ( m_continuousUpdateRequest <= 0 ) { m_continuousUpdateRequest.store( 0 ); m_isUpdateNeeded.store( false ); } if ( m_isAboutToQuit ) { this->exit(); } } bool loadFile( QString path ); void framesCountForStatsChanged( uint count ); void appNeedsToQuit(); void setRealFrameRate( bool on ); void setRecordFrames( bool on ); void setRecordTimings( bool on ); void setRecordGraph( bool on ); void recordFrame(); void onSelectedItem( const Ra::Engine::Scene::ItemEntry& entry ) { emit selectedItem( entry ); } void setContinuousUpdate( bool b ) { b ? m_continuousUpdateRequest++ : m_continuousUpdateRequest--; // if continuous update is requested, then we need an update, if not, // let update needed stay in the same state. if ( m_continuousUpdateRequest > 0 ) m_isUpdateNeeded.store( true ); } void askForUpdate() { m_isUpdateNeeded.store( true ); } protected: /// Create signal / slots connections void createConnections(); /// Load plugins from the specified folder. /// If loadList is empty, attempts to load all DLLs in the folder (except those on the ignore /// list) If loadList contains names it will only look for DLLs in that folder with the given /// name. bool loadPlugins( const std::string& pluginsPath, const QStringList& loadList, const QStringList& ignoreList ); void setupScene(); /// check wheter someone ask for update bool isUpdateNeeded() { return m_isUpdateNeeded.load(); } /// if b is true, then update anyway. If b is false, update on request only void setIsUpdateNeeded( bool b ) { m_isUpdateNeeded.store( b ); } // Public variables, accessible through the mainApp singleton. public: /// Application main window and GUI root class. std::unique_ptr<Gui::MainWindowInterface> m_mainWindow; /// Instance of the radium engine. std::unique_ptr<Engine::RadiumEngine> m_engine; /// Task queue for processing tasks. std::unique_ptr<Core::TaskQueue> m_taskQueue; /// Number of frames per second to generate. uint m_targetFPS; protected: /// Plugins that need to be initialized once OpenGL is ready std::vector<Ra::Plugins::RadiumPluginInterface*> m_openGLPlugins; /// Pointer to OpenGL Viewer for render call (belongs to MainWindow). Gui::Viewer* m_viewer; /// Timer to wake us up at every frame start. QTimer* m_frameTimer; /// Time since the last frame start. Core::Utils::TimePoint m_lastFrameStart; uint m_frameCounter; uint m_frameCountBeforeUpdate; uint m_numFrames; uint m_maxThreads; std::vector<FrameTimerData> m_timerData; std::string m_pluginPath; /// If true, use the wall clock to advance the engine. If false, use a fixed time step. bool m_realFrameRate; // Options to control monitoring and outputs /// Name of the folder where exported data goes std::string m_exportFoldername; /// If true, dump each frame to a PNG file. bool m_recordFrames; /// If true, print the detailed timings of each frame bool m_recordTimings; /// If true, print the task graph; bool m_recordGraph; /// True if the applicatioon is about to quit. prevent to use resources that are being released. bool m_isAboutToQuit; /// If true update the viewer frame next time std::atomic_bool m_isUpdateNeeded {true}; /// If counter is >= 0, continuously update viewer frame std::atomic<int> m_continuousUpdateRequest {1}; Plugins::Context m_pluginContext; QCommandLineParser* m_parser; }; } // namespace Gui } // namespace Ra
37.837456
100
0.686029
[ "render", "object", "vector" ]
29935033bccaf338bc670fb3c6efe8bf5cdc8e38
3,150
cc
C++
gneis-geant4/test/src/isnp/runner/CommandLineParserTest.cc
andrey-nakin/gneis-geant4
6def0304b5664a5dafdcfd58344ad2006ef44d62
[ "MIT" ]
null
null
null
gneis-geant4/test/src/isnp/runner/CommandLineParserTest.cc
andrey-nakin/gneis-geant4
6def0304b5664a5dafdcfd58344ad2006ef44d62
[ "MIT" ]
null
null
null
gneis-geant4/test/src/isnp/runner/CommandLineParserTest.cc
andrey-nakin/gneis-geant4
6def0304b5664a5dafdcfd58344ad2006ef44d62
[ "MIT" ]
null
null
null
#include <string.h> #include <memory.h> #include <vector> #include <gtest/gtest.h> #include "isnp/runner/CommandLineParser.hh" namespace isnp { namespace runner { class Helper { public: Helper() = delete; static CommandLineParser Instance(const char* const commandLine) { // container for all arguments std::vector<char*> arguments; // first argument is a path to executable arguments.push_back(::strdup("/path/to/executable")); // don't care about memory freeing // split command line by spaces char* const buf = ::strdup(commandLine); // don't care about memory freeing char* p = ::strtok(buf, " "); while (p != nullptr) { arguments.push_back(p); p = strtok(nullptr, " "); } // number of arguments int const argc = arguments.size(); // argument values char** const argv = (char**) ::calloc(argc, sizeof(char*)); // don't care about memory freeing memcpy(argv, &arguments[0], argc * sizeof(char*)); return CommandLineParser(arguments.size(), argv, true); } }; TEST(CommandLineParser, Nothing) { CommandLineParser const parser = Helper::Instance(""); EXPECT_EQ(0, parser.GetReturnCode()); EXPECT_EQ(1, parser.GetArgc()); EXPECT_FALSE(parser.GetVisualMode()); EXPECT_STREQ("/path/to/executable", parser.GetArgv()[0]); } TEST(CommandLineParser, NoOptions) { CommandLineParser const parser = Helper::Instance("filename1 filename2"); EXPECT_EQ(0, parser.GetReturnCode()); EXPECT_EQ(3, parser.GetArgc()); EXPECT_FALSE(parser.GetVisualMode()); EXPECT_STREQ("/path/to/executable", parser.GetArgv()[0]); EXPECT_STREQ("filename1", parser.GetArgv()[1]); EXPECT_STREQ("filename2", parser.GetArgv()[2]); } TEST(CommandLineParser, Help) { { CommandLineParser const parser = Helper::Instance("-h"); EXPECT_EQ(1, parser.GetReturnCode()); EXPECT_EQ(1, parser.GetArgc()); } { CommandLineParser const parser = Helper::Instance("-?"); EXPECT_EQ(1, parser.GetReturnCode()); EXPECT_EQ(1, parser.GetArgc()); } } #ifdef G4MULTITHREADED TEST(CommandLineParser, NumOfThreads) { { CommandLineParser const parser = Helper::Instance("filename1 filename2"); EXPECT_EQ(0, parser.GetReturnCode()); EXPECT_EQ(3, parser.GetArgc()); EXPECT_EQ(0, parser.GetNumOfThreads()); EXPECT_STREQ("filename1", parser.GetArgv()[1]); EXPECT_STREQ("filename2", parser.GetArgv()[2]); } { CommandLineParser const parser = Helper::Instance("-t 4 filename1 filename2"); EXPECT_EQ(0, parser.GetReturnCode()); EXPECT_EQ(3, parser.GetArgc()); EXPECT_EQ(4, parser.GetNumOfThreads()); EXPECT_STREQ("filename1", parser.GetArgv()[1]); EXPECT_STREQ("filename2", parser.GetArgv()[2]); } } #endif TEST(CommandLineParser, AllOptions) { CommandLineParser const parser = Helper::Instance("-v filename1 filename2"); EXPECT_EQ(0, parser.GetReturnCode()); EXPECT_EQ(3, parser.GetArgc()); EXPECT_TRUE(parser.GetVisualMode()); EXPECT_STREQ("filename1", parser.GetArgv()[1]); EXPECT_STREQ("filename2", parser.GetArgv()[2]); } TEST(CommandLineParser, BadOption) { CommandLineParser const parser = Helper::Instance("-Z"); EXPECT_EQ(1, parser.GetReturnCode()); EXPECT_EQ(1, parser.GetArgc()); } } }
27.391304
96
0.710159
[ "vector" ]
29957dba1e9297a5fd81a357953e415ced735122
3,281
hpp
C++
mk-physics/src/physics/fluids/FLIPSolver2D.hpp
mpazoscr/computer-graphics
a6c9bf8700161a4243f753a965dfd5f56b195e36
[ "MIT" ]
3
2017-06-21T13:53:20.000Z
2021-12-01T02:49:06.000Z
mk-physics/src/physics/fluids/FLIPSolver2D.hpp
mpazoscr/computer-graphics
a6c9bf8700161a4243f753a965dfd5f56b195e36
[ "MIT" ]
null
null
null
mk-physics/src/physics/fluids/FLIPSolver2D.hpp
mpazoscr/computer-graphics
a6c9bf8700161a4243f753a965dfd5f56b195e36
[ "MIT" ]
2
2020-03-15T16:14:08.000Z
2021-12-01T02:49:07.000Z
#ifndef SRC_PHYSICS_FLUIDS_FLIPSOLVER2D_H_ #define SRC_PHYSICS_FLUIDS_FLIPSOLVER2D_H_ #include <vector> #include <boost/numeric/ublas/vector.hpp> #include <glm/glm.hpp> namespace mk { namespace physics { enum CellType { kCellTypeAir = 0, kCellTypeFluid, kCellTypeSolid }; class FLIPSolver2D { public: struct Particles { public: Particles(); void addParticle(const glm::fvec2& pos, const glm::fvec2& vel); void clearParticles(); public: std::vector<glm::fvec2> positions; std::vector<glm::fvec2> velocities; int numParticles; }; public: FLIPSolver2D(int grid_width, int grid_height, float dx); float timeStep(); void simulate(float dt); void setBoundaryVel(const glm::fvec2& vel); float getPressure(int i, int j); glm::fvec2 getVelocity(int i, int j); glm::fvec2 getVelocity(float i, float j); CellType getCellType(int i, int j) const; void setCellType(int i, int j, CellType type); void setPicFlipFactor(float factor); float& u(int i, int j); float& v(int i, int j); int ix(int i, int j) const; int ixBig(int i, int j); public: Particles mParticles; private: void applyForce(float dt, float ax, float ay); void setBoundary(); void project(float dt); void checkBoundary(float i_init_, float j_init_, float& i_end_, float& j_end_); void advectParticles(float dt); void particlesToGrid(); void storeVel(); float computePhi(float a, float b, float current); void computeGridPhi(); void sweepU(int i0, int i1, int j0, int j1); void sweepV(int i0, int i1, int j0, int j1); void extrapolateVel(); void subtractVel(); void gridToParticles(); void fillHoles(); void solvePressure(); void calcPrecond(); void applyPrecond(); void applyA(); float uVel(float i, float j); float vVel(float i, float j); int uIndex_x(float x, float& wx); int uIndex_y(float y, float& wy); int vIndex_x(float x, float& wx); int vIndex_y(float y, float& wy); void swapVel(); private: int mGridWidth; int mGridHeight; int mGridSize; float mDx; float mOverDx; glm::fvec2 mBoundaryVelocity; float mPicFlipFactor; std::vector<float> mVelX; std::vector<float> mVelY; std::vector<float> mDeltaVelX; std::vector<float> mDeltaVelY; std::vector<float> mWeightSum; std::vector<float> mPhi; std::vector<CellType> mCellType; std::vector<CellType> mCellTypeAux; boost::numeric::ublas::vector<double> mP; boost::numeric::ublas::vector<double> mR; boost::numeric::ublas::vector<double> mS; boost::numeric::ublas::vector<double> mZ; boost::numeric::ublas::vector<double> mAux; boost::numeric::ublas::vector<double> mRhs; boost::numeric::ublas::vector<double> mPrecond; boost::numeric::ublas::vector<double> mCoefDiag; boost::numeric::ublas::vector<double> mCoefPlusI; boost::numeric::ublas::vector<double> mCoefPlusJ; }; } } #endif // SRC_PHYSICS_FLUIDS_FLIPSOLVER2D_H_
27.115702
85
0.627248
[ "vector" ]
299ac7c0f2422bd87998b7dfe5c7ccc650036cdb
11,096
cpp
C++
src/lolo_sim_msg_bridge.cpp
smarc-project/lolo_stonefish_sim
237935a2a5ac81d45ab46f284f542dca06d0be64
[ "BSD-3-Clause" ]
null
null
null
src/lolo_sim_msg_bridge.cpp
smarc-project/lolo_stonefish_sim
237935a2a5ac81d45ab46f284f542dca06d0be64
[ "BSD-3-Clause" ]
null
null
null
src/lolo_sim_msg_bridge.cpp
smarc-project/lolo_stonefish_sim
237935a2a5ac81d45ab46f284f542dca06d0be64
[ "BSD-3-Clause" ]
null
null
null
#include <ros/ros.h> #include <std_msgs/Float32.h> #include <std_msgs/Float64.h> #include <sensor_msgs/FluidPressure.h> #include <sensor_msgs/BatteryState.h> #include <sensor_msgs/JointState.h> #include <smarc_msgs/ThrusterRPM.h> #include <smarc_msgs/ThrusterFeedback.h> #include <smarc_msgs/DVL.h> #include <smarc_msgs/DVLBeam.h> //#include <sam_msgs/PercentStamped.h> //#include <sam_msgs/ThrusterAngles.h> #include <cola2_msgs/Setpoints.h> #include <cola2_msgs/DVL.h> #include <cola2_msgs/DVLBeam.h> class LoloSimMsgBridge { private: // parameters std::string robot_name; double vbs_vol_min, vbs_vol_max; // messages to publish cola2_msgs::Setpoints last_rudder_msg; cola2_msgs::Setpoints last_thruster_msg; cola2_msgs::Setpoints zero_thruster_msg; ros::Time last_thruster_msg_time; sensor_msgs::BatteryState battery_msg; // sensor outputs from stonefish ros::Subscriber pressure_sub; ros::Subscriber vbs_fb_sub[4]; //ros::Subscriber joint_states_fb_sub; ros::Subscriber dvl_sub; // sensor outputs from bridge ros::Publisher pressure_pub; ros::Publisher battery_pub; ros::Publisher vbs_fb_pub[4]; //ros::Publisher lcg_fb_pub; ros::Publisher thruster1_fb_pub; ros::Publisher thruster2_fb_pub; ros::Publisher dvl_pub; // command inputs to stonefish ros::Publisher thruster_cmd_pub; ros::Publisher rudder_cmd_pub; ros::Publisher vbs_cmd_pub[4]; ros::Publisher joint_states_cmd_pub; // command inputs to bridge ros::Subscriber thruster1_cmd_sub; ros::Subscriber thruster2_cmd_sub; ros::Subscriber vbs_cmd_sub[4]; //ros::Subscriber angles_cmd_sub; ros::Subscriber rudder_cmd_sub; ros::Subscriber elevator_cmd_sub; ros::Subscriber elevon_port_cmd_sub; ros::Subscriber elevon_stbd_cmd_sub; //ros::Subscriber lcg_cmd_sub; // publish timers ros::Timer battery_timer; ros::Timer thruster_timer; public: void dvl_callback(const cola2_msgs::DVL& msg) { smarc_msgs::DVL dvl; dvl.header = msg.header; dvl.velocity = msg.velocity; dvl.velocity_covariance = msg.velocity_covariance; dvl.altitude = msg.altitude; for (const cola2_msgs::DVLBeam& beam : msg.beams) { smarc_msgs::DVLBeam b; b.range = beam.range; b.range_covariance = beam.range_covariance; b.velocity = beam.velocity; b.velocity_covariance = beam.velocity_covariance; b.pose = beam.pose; dvl.beams.push_back(b); } dvl_pub.publish(dvl); } void rudder_cmd_callback(const std_msgs::Float32::ConstPtr& msg, int rudder_ind) { /* sensor_msgs::JointState rudder_angles; rudder_angles.header.stamp = ros::Time::now(); rudder_angles.name.push_back(robot_name + "/rudder_port_joint"); rudder_angles.name.push_back(robot_name + "/rudder_stbd_joint"); rudder_angles.position.push_back(msg.data); rudder_angles.position.push_back(msg.data); joint_states_cmd_pub.publish(rudder_angles); */ last_rudder_msg.header.stamp = ros::Time::now(); last_rudder_msg.setpoints[rudder_ind] = msg->data; if (rudder_ind == 1) { last_rudder_msg.setpoints[2] = msg->data; } rudder_cmd_pub.publish(last_rudder_msg); } /* void elevator_cmd_callback(const std_msgs::Float32& msg) { sensor_msgs::JointState elevator_angle; elevator_angle.header.stamp = ros::Time::now(); elevator_angle.name.push_back(robot_name + "/elevator_joint"); elevator_angle.position.push_back(msg.data); joint_states_cmd_pub.publish(elevator_angle); } */ /* void joint_states_fb_callback(const sensor_msgs::JointState& msg) { if (msg.name[0] == "sam/lcg_joint") { sam_msgs::PercentStamped fb_msg; fb_msg.header.stamp = ros::Time::now(); fb_msg.value = 100./(lcg_joint_max-lcg_joint_min)*(msg.position[0] - lcg_joint_min); lcg_fb_pub.publish(fb_msg); } } */ /* void lcg_cmd_callback(const sam_msgs::PercentStamped& msg) { sensor_msgs::JointState lcg_pos; lcg_pos.header.stamp = ros::Time::now(); lcg_pos.name.push_back(robot_name + "/lcg_joint"); lcg_pos.position.push_back(lcg_joint_min + 0.01*msg.value*(lcg_joint_max-lcg_joint_min)); joint_states_cmd_pub.publish(lcg_pos); } */ void vbs_cmd_callback(const std_msgs::Float32::ConstPtr& msg, int vbs_ind) { std_msgs::Float64 cmd; cmd.data = vbs_vol_min + 0.01*msg->data*(vbs_vol_max - vbs_vol_min); vbs_cmd_pub[vbs_ind].publish(cmd); } void vbs_fb_callback(const std_msgs::Float64::ConstPtr& msg, int vbs_ind) { std_msgs::Float32 fb; fb.data = 100.*(.5+msg->data); vbs_fb_pub[vbs_ind].publish(fb); } void pressure_callback(const sensor_msgs::FluidPressure& msg) { sensor_msgs::FluidPressure new_msg = msg; new_msg.fluid_pressure += 101325.; pressure_pub.publish(new_msg); } void thruster_cmd_callback(const smarc_msgs::ThrusterRPM::ConstPtr& msg, int thruster_ind) { last_thruster_msg_time = ros::Time::now(); last_thruster_msg.header.stamp = last_thruster_msg_time; last_thruster_msg.setpoints[thruster_ind] = msg->rpm; } void thruster_timer_callback(const ros::TimerEvent& event) { ros::Time current_time = ros::Time::now(); cola2_msgs::Setpoints msg; // must publish at 10Hz to get the thrusters going if ((current_time - last_thruster_msg_time).toSec() < 0.1) { msg = last_thruster_msg; msg.header.stamp = current_time; } else { msg = zero_thruster_msg; } thruster_cmd_pub.publish(msg); // publish feedback smarc_msgs::ThrusterFeedback fb; fb.rpm.rpm = msg.setpoints[0]; fb.header.stamp = msg.header.stamp; thruster1_fb_pub.publish(fb); fb.rpm.rpm = msg.setpoints[1]; thruster2_fb_pub.publish(fb); } void battery_timer_callback(const ros::TimerEvent& event) { battery_msg.header.stamp = ros::Time::now(); battery_pub.publish(battery_msg); } void setup_messages() { last_rudder_msg.setpoints.push_back(0.); last_rudder_msg.setpoints.push_back(0.); last_rudder_msg.setpoints.push_back(0.); last_rudder_msg.setpoints.push_back(0.); last_rudder_msg.setpoints.push_back(0.); last_thruster_msg.setpoints.push_back(0.); last_thruster_msg.setpoints.push_back(0.); zero_thruster_msg = last_thruster_msg; last_thruster_msg_time = ros::Time::now(); battery_msg.voltage = 12.5; battery_msg.percentage = 81.; battery_msg.power_supply_health = sensor_msgs::BatteryState::POWER_SUPPLY_HEALTH_GOOD; } LoloSimMsgBridge(ros::NodeHandle& nh) { ros::NodeHandle pn("~"); pn.param<std::string>("robot_name", robot_name, "lolo"); pn.param<double>("vbs_vol_min", vbs_vol_min, -.5); pn.param<double>("vbs_vol_max", vbs_vol_max, .5); setup_messages(); battery_pub = nh.advertise<sensor_msgs::BatteryState>("core/battery", 1000); pressure_pub = nh.advertise<sensor_msgs::FluidPressure>("core/pressure", 1000); pressure_sub = nh.subscribe("sim/pressure", 1000, &LoloSimMsgBridge::pressure_callback, this); dvl_pub = nh.advertise<smarc_msgs::DVL>("core/dvl", 1000); dvl_sub = nh.subscribe("sim/dvl", 1000, &LoloSimMsgBridge::dvl_callback, this); std::vector<std::string> vbs_names = {"vbs_front_stbd", "vbs_front_port", "vbs_back_stbd", "vbs_back_port"}; for (int i = 0; i < vbs_names.size(); ++i) { std::string name = vbs_names[i]; vbs_cmd_sub[i] = nh.subscribe<std_msgs::Float32>(std::string("core/") + name + "_cmd", 1000, boost::bind(&LoloSimMsgBridge::vbs_cmd_callback, this, _1, i)); vbs_fb_sub[i] = nh.subscribe<std_msgs::Float64>(std::string("sim/") + name + "/volume_centered", 1000, boost::bind(&LoloSimMsgBridge::vbs_fb_callback, this, _1, i)); vbs_fb_pub[i] = nh.advertise<std_msgs::Float32>(std::string("core/") + name + "_fb", 1000); vbs_cmd_pub[i] = nh.advertise<std_msgs::Float64>(std::string("sim/") + name + "/setpoint", 1000); } joint_states_cmd_pub = nh.advertise<sensor_msgs::JointState>("desired_joint_states", 1000); /* joint_states_fb_sub = nh.subscribe("joint_states", 1000, &LoloSimMsgBridge::joint_states_fb_callback, this); lcg_fb_pub = nh.advertise<sam_msgs::PercentStamped>("core/lcg_fb", 1000); lcg_cmd_sub = nh.subscribe("core/lcg_cmd", 1000, &LoloSimMsgBridge::lcg_cmd_callback, this); */ //angles_cmd_sub = nh.subscribe("core/thrust_vector_cmd", 1000, &LoloSimMsgBridge::angles_cmd_callback, this); //rudder_cmd_sub = nh.subscribe("core/rudder_cmd", 1000, &LoloSimMsgBridge::rudder_cmd_callback, this); //elevator_cmd_sub = nh.subscribe("core/elevator_cmd", 1000, &LoloSimMsgBridge::elevator_cmd_callback, this); thruster1_cmd_sub = nh.subscribe<smarc_msgs::ThrusterRPM>("core/thruster1_cmd", 1000, boost::bind(&LoloSimMsgBridge::thruster_cmd_callback, this, _1, 0)); thruster2_cmd_sub = nh.subscribe<smarc_msgs::ThrusterRPM>("core/thruster2_cmd", 1000, boost::bind(&LoloSimMsgBridge::thruster_cmd_callback, this, _1, 1)); elevator_cmd_sub = nh.subscribe<std_msgs::Float32>("core/elevator_cmd", 1000, boost::bind(&LoloSimMsgBridge::rudder_cmd_callback, this, _1, 0)); rudder_cmd_sub = nh.subscribe<std_msgs::Float32>("core/rudder_cmd", 1000, boost::bind(&LoloSimMsgBridge::rudder_cmd_callback, this, _1, 1)); elevon_port_cmd_sub = nh.subscribe<std_msgs::Float32>("core/elevon_port_cmd", 1000, boost::bind(&LoloSimMsgBridge::rudder_cmd_callback, this, _1, 3)); elevon_stbd_cmd_sub = nh.subscribe<std_msgs::Float32>("core/elevon_strb_cmd", 1000, boost::bind(&LoloSimMsgBridge::rudder_cmd_callback, this, _1, 4)); thruster_cmd_pub = nh.advertise<cola2_msgs::Setpoints>("sim/thruster_setpoints", 1000); rudder_cmd_pub = nh.advertise<cola2_msgs::Setpoints>("sim/rudder_setpoints", 1000); thruster1_fb_pub = nh.advertise<smarc_msgs::ThrusterFeedback>("core/thruster1_fb", 1000); thruster2_fb_pub = nh.advertise<smarc_msgs::ThrusterFeedback>("core/thruster2_fb", 1000); battery_timer = nh.createTimer(ros::Duration(1), &LoloSimMsgBridge::battery_timer_callback, this); thruster_timer = nh.createTimer(ros::Duration(.1), &LoloSimMsgBridge::thruster_timer_callback, this); } }; int main(int argc, char** argv) { ros::init(argc, argv, "sam_sim_msg_bridge"); ros::NodeHandle nh; LoloSimMsgBridge bridge(nh); ros::spin(); return 0; }
38.933333
177
0.672134
[ "vector" ]
299b6c393bc9ff1ac9ca8c0d709b3f73d7ce9cae
625
cpp
C++
CodeForces/Complete/800-899/847A-UnionOfDoublyLinkedLists.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/800-899/847A-UnionOfDoublyLinkedLists.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/800-899/847A-UnionOfDoublyLinkedLists.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <cstdio> #include <vector> #include <set> int main(){ long n; scanf("%ld", &n); std::vector<long> left(n + 1, 0), right(n + 1, 0); std::set<long> s; for(long p = 1; p <= n; p++){ scanf("%ld %ld", &left[p], &right[p]); if(left[p] == 0){s.insert(p);} } long cur = *s.begin(); s.erase(cur); long node = cur; while(s.size() > 0){ while(right[node] > 0){node = right[node];} cur = *s.begin(); s.erase(cur); left[cur] = node; right[node] = cur; node = cur; } for(long p = 1; p <= n; p++){printf("%ld %ld\n", left[p], right[p]);} return 0; }
24.038462
88
0.4864
[ "vector" ]
299c8eaafb54babcfbfeed46fbc502799af32809
20,949
cpp
C++
Plugins/CurveBuilder/Source/CurveBuilder/RuntimeComponent/RuntimeSplinePrimitiveComponent.cpp
PacosLelouch/CurveBuilderForUE4
d7925784ece55aa94207d3a377eb49746b3af850
[ "MIT" ]
1
2021-11-27T01:36:15.000Z
2021-11-27T01:36:15.000Z
Plugins/CurveBuilder/Source/CurveBuilder/RuntimeComponent/RuntimeSplinePrimitiveComponent.cpp
PacosLelouch/CurveBuilderForUE4
d7925784ece55aa94207d3a377eb49746b3af850
[ "MIT" ]
null
null
null
Plugins/CurveBuilder/Source/CurveBuilder/RuntimeComponent/RuntimeSplinePrimitiveComponent.cpp
PacosLelouch/CurveBuilderForUE4
d7925784ece55aa94207d3a377eb49746b3af850
[ "MIT" ]
null
null
null
// Copyright 2020 PacosLelouch, Inc. All Rights Reserved. // https://github.com/PacosLelouch/ #pragma once #include "RuntimeSplinePrimitiveComponent.h" #include "SceneProxies/RuntimeSplinePrimitiveSceneProxy.h" #include "PhysicsEngine/BodySetup.h" #include "Engine/StaticMesh.h" #include "Engine/Engine.h" #include "Styling/SlateStyle.h" #include "Styling/CoreStyle.h" #include "Widgets/SWidget.h" #include "Widgets/SViewport.h" #include "Framework/Commands/Commands.h" #include "Framework/Commands/UICommandInfo.h" #include "Framework/Multibox/MultiboxBuilder.h" #include "Framework/Application/SlateApplication.h" #define LOCTEXT_NAMESPACE "RuntimeSplineCommandHelper" DEFINE_LOG_CATEGORY_STATIC(LogRuntimeSplinePrimitiveComponent, Warning, All) // Initialize in static scope will crash after packaging. TSharedPtr<ISlateStyle> FRuntimeSplineCommandHelperBase::SlateStyle; ECollisionTraceFlag URuntimeSplinePrimitiveComponent::SpCompCollisionTraceFlag = ECollisionTraceFlag::CTF_UseSimpleAsComplex; URuntimeSplinePrimitiveComponent::URuntimeSplinePrimitiveComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { bUseAttachParentBound = false; bAlwaysCreatePhysicsState = true; CanCharacterStepUpOn = ECanBeCharacterBase::ECB_No; DepthPriorityGroup = ESceneDepthPriorityGroup::SDPG_Foreground; } void URuntimeSplinePrimitiveComponent::BeginPlay() { Super::BeginPlay(); SetCollisionEnabled(ECollisionEnabled::QueryOnly); SetGenerateOverlapEvents(true); SetCollisionResponseToAllChannels(ECollisionResponse::ECR_Overlap); } bool URuntimeSplinePrimitiveComponent::MoveComponentImpl(const FVector& Delta, const FQuat& NewRotation, bool bSweep, FHitResult* Hit, EMoveComponentFlags MoveFlags, ETeleportType Teleport) { bool bReturnValue = Super::MoveComponentImpl(Delta, NewRotation, bSweep, Hit, MoveFlags, Teleport); #if !DISABLE_COPY_IN_SPLINE_SCENE_PROXY MarkRenderStateDirty(); #endif // DISABLE_COPY_IN_SPLINE_SCENE_PROXY return bReturnValue; } FPrimitiveSceneProxy* URuntimeSplinePrimitiveComponent::CreateSceneProxy() { return new FRuntimeSplinePrimitiveSceneProxy(this); } FMatrix URuntimeSplinePrimitiveComponent::GetRenderMatrix() const { return GetSplineLocalToWorldTransform().ToMatrixWithScale(); } void URuntimeSplinePrimitiveComponent::OnCreatePhysicsState() { #if true Super::OnCreatePhysicsState(); #else USceneComponent::OnCreatePhysicsState(); // if we have a scene, we don't want to disable all physics and we have no bodyinstance already //if (true) if (!BodyInstance.IsValidBodyInstance()) { //UE_LOG(LogPrimitiveComponent, Warning, TEXT("Creating Physics State (%s : %s)"), *GetNameSafe(GetOuter()), *GetName()); UBodySetup* UseBodySetup = GetBodySetup(); if (UseBodySetup) { // Create new BodyInstance at given location. FTransform BodyTransform = GetComponentTransform();//GetSplineLocalToWorldTransform(); // Here we make sure we don't have zero scale. This still results in a body being made and placed in // world (very small) but is consistent with a body scaled to zero. const FVector BodyScale = BodyTransform.GetScale3D(); if (BodyScale.IsNearlyZero()) { BodyTransform.SetScale3D(FVector(KINDA_SMALL_NUMBER)); } #if !(UE_BUILD_SHIPPING || UE_BUILD_TEST) if ((BodyInstance.GetCollisionEnabled() != ECollisionEnabled::NoCollision) && (FMath::IsNearlyZero(BodyScale.X) || FMath::IsNearlyZero(BodyScale.Y) || FMath::IsNearlyZero(BodyScale.Z))) { UE_LOG(LogPhysics, Warning, TEXT("Scale for %s has a component set to zero, which will result in a bad body instance. Scale:%s"), *GetPathNameSafe(this), *BodyScale.ToString()); } #endif // Create the body. BodyInstance.InitBody(UseBodySetup, BodyTransform, this, GetWorld()->GetPhysicsScene()); #if !(UE_BUILD_SHIPPING || UE_BUILD_TEST) SendRenderDebugPhysics(); #endif // !(UE_BUILD_SHIPPING || UE_BUILD_TEST) #if WITH_EDITOR // Make sure we have a valid body instance here. As we do not keep BIs with no collision shapes at all, // we don't want to create cloth collision in these cases if (BodyInstance.IsValidBodyInstance()) { const float RealMass = BodyInstance.GetBodyMass(); const float CalcedMass = BodySetup->CalculateMass(this); float MassDifference = RealMass - CalcedMass; if (RealMass > 1.0f && FMath::Abs(MassDifference) > 0.1f) { UE_LOG(LogPhysics, Log, TEXT("Calculated mass differs from real mass for %s:%s. Mass: %f CalculatedMass: %f"), GetOwner() != NULL ? *GetOwner()->GetName() : TEXT("NoActor"), *GetName(), RealMass, CalcedMass); } } #endif // WITH_EDITOR } } #endif } void URuntimeSplinePrimitiveComponent::OnUpdateTransform(EUpdateTransformFlags UpdateTransformFlags, ETeleportType Teleport) { Super::OnUpdateTransform(UpdateTransformFlags, Teleport); UpdateBounds(); UpdateCollision(); MarkRenderStateDirty(); //MarkRenderTransformDirty(); // Need to send new bounds to render thread } FBoxSphereBounds URuntimeSplinePrimitiveComponent::CalcBounds(const FTransform& LocalToWorld) const { UE_LOG(LogRuntimeSplinePrimitiveComponent, Warning, TEXT("CalcBounds not override.")); return Super::CalcBounds(LocalToWorld); } void URuntimeSplinePrimitiveComponent::SetDrawDebugCollision(bool bValue) { if (bDrawDebugCollision != bValue) { bDrawDebugCollision = bValue; MarkRenderStateDirty(); } } void URuntimeSplinePrimitiveComponent::SetDrawInGame(bool bValue) { if (bDrawInGame != bValue) { bDrawInGame = bValue; MarkRenderStateDirty(); } } void URuntimeSplinePrimitiveComponent::InitializeCommandHelper() { } #if WITH_EDITOR void URuntimeSplinePrimitiveComponent::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) { //UE_LOG(LogRuntimeSplinePrimitiveComponent, Warning, TEXT("PostEditChangeProperty not override.")); Super::PostEditChangeProperty(PropertyChangedEvent); const FName PropertyName = PropertyChangedEvent.Property ? PropertyChangedEvent.Property->GetFName() : FName(); const FName MemberPropertyName = PropertyChangedEvent.MemberProperty ? PropertyChangedEvent.MemberProperty->GetFName() : FName(); if (PropertyName == GET_MEMBER_NAME_CHECKED(URuntimeSplinePrimitiveComponent, bDrawInGame) || PropertyName == GET_MEMBER_NAME_CHECKED(URuntimeSplinePrimitiveComponent, bDrawDebugCollision)) { MarkRenderStateDirty(); } } #endif FTransform URuntimeSplinePrimitiveComponent::GetSplineLocalToWorldTransform() const { if (ParentGraph) { return ParentGraph->GetActorTransform(); } USceneComponent* RealParent = GetAttachParent(); if (IsValid(RealParent)) { return RealParent->GetComponentTransform(); } return GetComponentTransform(); } FTransform URuntimeSplinePrimitiveComponent::GetWorldToSplineLocalTransform() const { return GetSplineLocalToWorldTransform().Inverse(); } FTransform URuntimeSplinePrimitiveComponent::GetSplineLocalToComponentLocalTransform() const { return GetSplineLocalToWorldTransform() * GetComponentTransform().Inverse(); } FTransform URuntimeSplinePrimitiveComponent::GetComponentLocalToSplineLocalTransform() const { return GetComponentTransform() * GetSplineLocalToWorldTransform().Inverse(); } FTransform URuntimeSplinePrimitiveComponent::GetWorldToParentComponentTransform() const { return GetParentComponentToWorldTransform().Inverse(); } FTransform URuntimeSplinePrimitiveComponent::GetParentComponentToWorldTransform() const { USceneComponent* RealParent = GetAttachParent(); if (IsValid(RealParent)) { return RealParent->GetComponentTransform(); } return GetComponentTransform(); } FTransform URuntimeSplinePrimitiveComponent::GetSplineLocalToParentComponentTransform() const { USceneComponent* RealParent = GetAttachParent(); if (IsValid(RealParent)) { return GetSplineLocalToWorldTransform() * RealParent->GetComponentTransform().Inverse(); } return GetSplineLocalToWorldTransform(); } FTransform URuntimeSplinePrimitiveComponent::GetParentComponentToSplineLocalTransform() const { USceneComponent* RealParent = GetAttachParent(); if (IsValid(RealParent)) { return RealParent->GetComponentTransform() * GetWorldToSplineLocalTransform(); } return GetWorldToSplineLocalTransform(); } FVector URuntimeSplinePrimitiveComponent::ConvertPosition(const FVector& SourcePosition, ECustomSplineCoordinateType From, ECustomSplineCoordinateType To) const { switch (From) { case ECustomSplineCoordinateType::ComponentLocal: switch (To) { case ECustomSplineCoordinateType::SplineGraphLocal: return GetParentComponentToSplineLocalTransform().TransformPosition(SourcePosition); case ECustomSplineCoordinateType::World: return GetParentComponentToWorldTransform().TransformPosition(SourcePosition); } break; case ECustomSplineCoordinateType::SplineGraphLocal: switch (To) { case ECustomSplineCoordinateType::ComponentLocal: return GetSplineLocalToParentComponentTransform().TransformPosition(SourcePosition); case ECustomSplineCoordinateType::World: return GetSplineLocalToWorldTransform().TransformPosition(SourcePosition); } break; case ECustomSplineCoordinateType::World: switch (To) { case ECustomSplineCoordinateType::SplineGraphLocal: return GetWorldToSplineLocalTransform().TransformPosition(SourcePosition); case ECustomSplineCoordinateType::ComponentLocal: return GetWorldToParentComponentTransform().TransformPosition(SourcePosition); } break; } return SourcePosition; } void URuntimeSplinePrimitiveComponent::CreateBodySetup() { if (!IsValid(BodySetup)) { BodySetup = NewObject<UBodySetup>(this, NAME_None, (IsTemplate() ? RF_Public : RF_NoFlags)); BodySetup->BodySetupGuid = FGuid::NewGuid(); BodySetup->BuildScale3D = FVector::OneVector; BodySetup->bGenerateMirroredCollision = false; BodySetup->bDoubleSidedGeometry = false; BodySetup->CollisionTraceFlag = SpCompCollisionTraceFlag; } } void URuntimeSplinePrimitiveComponent::UpdateCollision() { UE_LOG(LogRuntimeSplinePrimitiveComponent, Warning, TEXT("UpdateCollision not override.")); } void URuntimeSplinePrimitiveComponent::OpenMenu(const FVector& SnappedWorldPosition) { if (CommandHelper.IsValid()) { CloseMenu(); CommandHelper.Get()->CreateMenuBarAt(SnappedWorldPosition, &OpenedMenu); } } void URuntimeSplinePrimitiveComponent::CloseMenu() { if (OpenedMenu.IsValid()) { FSlateApplication::Get().DismissMenu(OpenedMenu); } } FRuntimeSplineCommandsBase::FRuntimeSplineCommandsBase() : TCommands<FRuntimeSplineCommandsBase> ( "RuntimeSplineCommandHelper", // Context name for fast lookup LOCTEXT("RuntimeSplineCommandHelper", "Runtime Spline Command Helper"), // Localized context name for displaying NAME_None, // Parent FRuntimeSplineCommandHelperBase::GetSlateStyle().GetStyleSetName() ) { } void FRuntimeSplineCommandsBase::RegisterCommands() { //UI_COMMAND(DeleteKey, "Delete Spline Point", "Delete the currently selected spline point.", EUserInterfaceActionType::Button, FInputChord(EKeys::Delete)); //UI_COMMAND(DuplicateKey, "Duplicate Spline Point", "Duplicate the currently selected spline point.", EUserInterfaceActionType::Button, FInputChord()); //UI_COMMAND(AddKey, "Add Spline Point Here", "Add a new spline point at the cursor location.", EUserInterfaceActionType::Button, FInputChord()); //UI_COMMAND(SelectAll, "Select All Spline Points", "Select all spline points.", EUserInterfaceActionType::Button, FInputChord()); //UI_COMMAND(ResetToUnclampedTangent, "Unclamped Tangent", "Reset the tangent for this spline point to its default unclamped value.", EUserInterfaceActionType::Button, FInputChord()); //UI_COMMAND(ResetToClampedTangent, "Clamped Tangent", "Reset the tangent for this spline point to its default clamped value.", EUserInterfaceActionType::Button, FInputChord()); //UI_COMMAND(SetKeyToCurve, "Curve", "Set spline point to Curve type", EUserInterfaceActionType::RadioButton, FInputChord()); //UI_COMMAND(SetKeyToLinear, "Linear", "Set spline point to Linear type", EUserInterfaceActionType::RadioButton, FInputChord()); //UI_COMMAND(SetKeyToConstant, "Constant", "Set spline point to Constant type", EUserInterfaceActionType::RadioButton, FInputChord()); //UI_COMMAND(FocusViewportToSelection, "Focus Selected", "Moves the camera in front of the selection", EUserInterfaceActionType::Button, FInputChord(EKeys::F)); //UI_COMMAND(SnapToNearestSplinePoint, "Snap to Nearest Spline Point", "Snap to nearest spline point.", EUserInterfaceActionType::Button, FInputChord()); //UI_COMMAND(AlignToNearestSplinePoint, "Align to Nearest Spline Point", "Align to nearest spline point.", EUserInterfaceActionType::Button, FInputChord()); //UI_COMMAND(AlignPerpendicularToNearestSplinePoint, "Align Perpendicular to Nearest Spline Point", "Align perpendicular to nearest spline point.", EUserInterfaceActionType::Button, FInputChord()); //UI_COMMAND(SnapAllToSelectedX, "Snap All To Selected X", "Snap all spline points to selected spline point X.", EUserInterfaceActionType::Button, FInputChord()); //UI_COMMAND(SnapAllToSelectedY, "Snap All To Selected Y", "Snap all spline points to selected spline point Y.", EUserInterfaceActionType::Button, FInputChord()); //UI_COMMAND(SnapAllToSelectedZ, "Snap All To Selected Z", "Snap all spline points to selected spline point Z.", EUserInterfaceActionType::Button, FInputChord()); //UI_COMMAND(SetLockedAxisNone, "None", "New spline point axis is not fixed.", EUserInterfaceActionType::RadioButton, FInputChord()); //UI_COMMAND(SetLockedAxisX, "X", "Fix X axis when adding new spline points.", EUserInterfaceActionType::RadioButton, FInputChord()); //UI_COMMAND(SetLockedAxisY, "Y", "Fix Y axis when adding new spline points.", EUserInterfaceActionType::RadioButton, FInputChord()); //UI_COMMAND(SetLockedAxisZ, "Z", "Fix Z axis when adding new spline points.", EUserInterfaceActionType::RadioButton, FInputChord()); //UI_COMMAND(VisualizeRollAndScale, "Visualize Roll and Scale", "Whether the visualization should show roll and scale on this spline.", EUserInterfaceActionType::ToggleButton, FInputChord()); //UI_COMMAND(DiscontinuousSpline, "Allow Discontinuous Splines", "Whether the visualization allows Arrive and Leave tangents to be set separately.", EUserInterfaceActionType::ToggleButton, FInputChord()); //UI_COMMAND(ResetToDefault, "Reset to Default", "Reset this spline to its archetype default.", EUserInterfaceActionType::Button, FInputChord()); } void FRuntimeSplineCommandHelperBase::MapActions() { } TSharedPtr<SWidget> FRuntimeSplineCommandHelperBase::GenerateContextMenu() { if (!CommandList.IsValid()) { //FRuntimeSplineCommandsBase::Register(); //MapActions(); return nullptr; } FMenuBuilder MenuBuilder(true, CommandList, TSharedPtr<FExtender>(), false, &GetSlateStyle()); GenerateContextMenuSections(MenuBuilder); TSharedPtr<SWidget> MenuWidget = MenuBuilder.MakeWidget(); return MenuWidget; } void FRuntimeSplineCommandHelperBase::GenerateContextMenuSections(FMenuBuilder& InMenuBuilder) const { //InMenuBuilder.BeginSection("SplinePointEdit", LOCTEXT("SplinePoint", "Spline Point")); //{ // if (SelectedSegmentIndex != INDEX_NONE) // { // InMenuBuilder.AddMenuEntry(FSplineComponentVisualizerCommands::Get().AddKey); // } // else if (LastKeyIndexSelected != INDEX_NONE) // { // InMenuBuilder.AddMenuEntry(FSplineComponentVisualizerCommands::Get().DeleteKey); // InMenuBuilder.AddMenuEntry(FSplineComponentVisualizerCommands::Get().DuplicateKey); // InMenuBuilder.AddMenuEntry(FSplineComponentVisualizerCommands::Get().SelectAll); // InMenuBuilder.AddSubMenu( // LOCTEXT("SplinePointType", "Spline Point Type"), // LOCTEXT("SplinePointTypeTooltip", "Define the type of the spline point."), // FNewMenuDelegate::CreateSP(this, &FSplineComponentVisualizer::GenerateSplinePointTypeSubMenu)); // // Only add the Automatic Tangents submenu if any of the keys is a curve type // USplineComponent* SplineComp = GetEditedSplineComponent(); // if (SplineComp != nullptr) // { // for (int32 SelectedKeyIndex : SelectedKeys) // { // check(SelectedKeyIndex >= 0); // check(SelectedKeyIndex < SplineComp->GetNumberOfSplinePoints()); // const auto& Point = SplineComp->SplineCurves.Position.Points[SelectedKeyIndex]; // if (Point.IsCurveKey()) // { // InMenuBuilder.AddSubMenu( // LOCTEXT("ResetToAutomaticTangent", "Reset to Automatic Tangent"), // LOCTEXT("ResetToAutomaticTangentTooltip", "Reset the spline point tangent to an automatically generated value."), // FNewMenuDelegate::CreateSP(this, &FSplineComponentVisualizer::GenerateTangentTypeSubMenu)); // break; // } // } // } // InMenuBuilder.AddMenuEntry( // LOCTEXT("SplineGenerate", "Spline Generation Panel"), // LOCTEXT("SplineGenerateTooltip", "Opens up a spline generation panel to easily create basic shapes with splines"), // FSlateIcon(), // FUIAction( // FExecuteAction::CreateSP(const_cast<FSplineComponentVisualizer*>(this), &FSplineComponentVisualizer::CreateSplineGeneratorPanel), // FCanExecuteAction::CreateLambda([] { return true; }) // ) // ); // } //} //InMenuBuilder.EndSection(); //InMenuBuilder.BeginSection("Transform"); //{ // InMenuBuilder.AddMenuEntry(FSplineComponentVisualizerCommands::Get().FocusViewportToSelection); // InMenuBuilder.AddSubMenu( // LOCTEXT("SnapAlign", "Snap/Align"), // LOCTEXT("SnapAlignTooltip", "Snap align options."), // FNewMenuDelegate::CreateSP(this, &FSplineComponentVisualizer::GenerateSnapAlignSubMenu)); // /* temporarily disabled // InMenuBuilder.AddSubMenu( // LOCTEXT("LockAxis", "Lock Axis"), // LOCTEXT("LockAxisTooltip", "Axis to lock when adding new spline points."), // FNewMenuDelegate::CreateSP(this, &FSplineComponentVisualizer::GenerateLockAxisSubMenu)); // */ //} //InMenuBuilder.EndSection(); //InMenuBuilder.BeginSection("Spline", LOCTEXT("Spline", "Spline")); //{ // InMenuBuilder.AddMenuEntry(FSplineComponentVisualizerCommands::Get().ResetToDefault); //} //InMenuBuilder.EndSection(); //InMenuBuilder.BeginSection("Visualization", LOCTEXT("Visualization", "Visualization")); //{ // InMenuBuilder.AddMenuEntry(FSplineComponentVisualizerCommands::Get().VisualizeRollAndScale); // InMenuBuilder.AddMenuEntry(FSplineComponentVisualizerCommands::Get().DiscontinuousSpline); //} //InMenuBuilder.EndSection(); } //void FSplineComponentVisualizer::GenerateSplinePointTypeSubMenu(FMenuBuilder& MenuBuilder) const //{ // MenuBuilder.AddMenuEntry(FSplineComponentVisualizerCommands::Get().SetKeyToCurve); // MenuBuilder.AddMenuEntry(FSplineComponentVisualizerCommands::Get().SetKeyToLinear); // MenuBuilder.AddMenuEntry(FSplineComponentVisualizerCommands::Get().SetKeyToConstant); //} void FRuntimeSplineCommandHelperBase::CapturedMouseMove(FViewport* InViewport, int32 InMouseX, int32 InMouseY) { UE_LOG(LogRuntimeSplinePrimitiveComponent, Log, TEXT("FRuntimeSplineCommandHelperBase::CapturedMouseMove: <%d, %d>"), InMouseX, InMouseY); } bool FRuntimeSplineCommandHelperBase::InputKey(FViewport* Viewport, int32 ControllerId, FKey Key, EInputEvent Event, float AmountDepressed, bool bGamepad) { UE_LOG(LogRuntimeSplinePrimitiveComponent, Log, TEXT("FRuntimeSplineCommandHelperBase::InputKey: CtrlId: %d, Key: %s, Event: %d, AmountDepressed: %f, Gamepad: %d"), ControllerId, *Key.ToString(), Event, AmountDepressed, bGamepad); return false; } bool FRuntimeSplineCommandHelperBase::InputAxis(FViewport* Viewport, int32 ControllerId, FKey Key, float Delta, float DeltaTime, int32 NumSamples, bool bGamepad) { UE_LOG(LogRuntimeSplinePrimitiveComponent, Log, TEXT("FRuntimeSplineCommandHelperBase::InputAxis: CtrlId: %d, Key: %s, Delta: %f, DeltaTime: %f, NumSamples: %d, Gamepad: %d"), ControllerId, *Key.ToString(), Delta, DeltaTime, NumSamples, bGamepad); return false; } bool FRuntimeSplineCommandHelperBase::CreateMenuBarAt(const FVector& SnappedWorldPosition, TSharedPtr<IMenu>* OpenedMenuPtr) { TSharedPtr<SWidget> MenuWidget = GenerateContextMenu(); if (!MenuWidget.IsValid()) { return false; } if (!IsValid(GEngine) || !IsValid(GEngine->GameViewport)) { return false; } TSharedPtr<SViewport> GameViewportWidget = GEngine->GameViewport->GetGameViewportWidget(); if (!GameViewportWidget.IsValid()) { return false; } TSharedPtr<IMenu> OpenedMenu = FSlateApplication::Get().PushMenu( GameViewportWidget.ToSharedRef(), FWidgetPath(), MenuWidget.ToSharedRef(), FSlateApplication::Get().GetCursorPos(), FPopupTransitionEffect(FPopupTransitionEffect::ContextMenu)); LastSnappedWorldPosition = SnappedWorldPosition; if (OpenedMenuPtr) { *OpenedMenuPtr = OpenedMenu; } return true; } ISlateStyle& FRuntimeSplineCommandHelperBase::GetSlateStyle() { if (!SlateStyle.IsValid()) { SlateStyle = TSharedPtr<ISlateStyle>(FCoreStyle::Create()); } return *SlateStyle.Get(); } #undef LOCTEXT_NAMESPACE
39.676136
205
0.782472
[ "render", "transform" ]
299d3f89d1a9f2676a145494c29819e5ddc12c40
1,079
cpp
C++
Sample/JapaneseFlag/Application.cpp
EPAC-Saxon/advance-obj-JuliePreperier
5adc1a308c8ad6bed9555dc507f83437a5b5208c
[ "MIT" ]
1
2021-05-27T08:17:57.000Z
2021-05-27T08:17:57.000Z
Sample/JapaneseFlag/Application.cpp
EPAC-Saxon/advance-obj-JuliePreperier
5adc1a308c8ad6bed9555dc507f83437a5b5208c
[ "MIT" ]
null
null
null
Sample/JapaneseFlag/Application.cpp
EPAC-Saxon/advance-obj-JuliePreperier
5adc1a308c8ad6bed9555dc507f83437a5b5208c
[ "MIT" ]
null
null
null
#include "Application.h" #include <glm/gtc/matrix_transform.hpp> Application::Application(const std::shared_ptr<sgl::WindowInterface>& window) : window_(window) {} void Application::Startup() { auto device = window_->GetUniqueDevice(); device->Startup(); auto billboard_mesh = CreateBillboardMesh(); auto billboard_program = billboard_mesh->GetProgram(); // Pack it into a Scene object. sgl::SceneTree scene_tree{}; auto root = std::make_shared<sgl::SceneMatrix>( [billboard_program](const double dt) -> glm::mat4 { billboard_program->UniformFloat("Time", static_cast<float>(dt)); return glm::mat4(1.0); }); scene_tree.AddNode(root); scene_tree.AddNode(std::make_shared<sgl::SceneMesh>(billboard_mesh), root); device->SetSceneTree(scene_tree); } void Application::Run() { window_->Run(); } std::shared_ptr<sgl::Mesh> Application::CreateBillboardMesh() const { // Create the ray marching program. auto ray_marshing_program = sgl::CreateProgram("JapaneseFlag"); auto billboard_mesh = sgl::CreateQuadMesh(ray_marshing_program); return billboard_mesh; }
27.666667
79
0.747915
[ "mesh", "object" ]
299e0190b4b1aeec5c9753d5dad1452b449bc5b8
39,137
cpp
C++
admin/wmi/wbem/winmgmt/wmiexts/dumpwc.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/wmi/wbem/winmgmt/wmiexts/dumpwc.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/wmi/wbem/winmgmt/wmiexts/dumpwc.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include <wmiexts.h> #include <oleauto.h> #include <wbemutil.h> #ifndef COREPROX_POLARITY #define COREPROX_POLARITY #endif #include <arena.h> #include <faster.h> #include <faststr.h> #include <wbemint.h> #include <fastcls.h> #include <var.h> #include <fastinst.h> #include <wbemdatapacket.h> //#include <smartnextpacket.h> #pragma pack( push ) #pragma pack( 1 ) // IWbemWCOSmartEnum::Next() Header. Changing this will // cause the main version to change typedef struct tagWBEM_DATAPACKET_SMARTENUM_NEXT { DWORD dwSizeOfHeader; // Size of the header struct. Data immediately follows header. DWORD dwDataSize; // Size of Data following header. } WBEM_DATAPACKET_SMARTENUM_NEXT; typedef WBEM_DATAPACKET_SMARTENUM_NEXT* PWBEM_DATAPACKET_SMARTENUM_NEXT; // restore packing #pragma pack( pop ) //#include <objarraypacket.h> #pragma pack( push ) #pragma pack( 1 ) // IWbemClassObject Array Header. Changing this will // cause the main version to change typedef struct tagWBEM_DATAPACKET_OBJECT_ARRAY { DWORD dwSizeOfHeader; // Size of the header struct. Data immediately follows header. DWORD dwDataSize; // Size of Data following header. DWORD dwNumObjects; // Number of objects in the array } WBEM_DATAPACKET_OBJECT_ARRAY; typedef WBEM_DATAPACKET_OBJECT_ARRAY* PWBEM_DATAPACKET_OBJECT_ARRAY; // restore packing #pragma pack( pop ) #pragma pack( push ) #pragma pack( 1 ) // IWbemObjectSink::Indicate() Header. Changing this will // cause the main version to change typedef struct tagWBEM_DATAPACKET_OBJECTSINK_INDICATE { DWORD dwSizeOfHeader; // Size of the header struct. Data immediately follows header. DWORD dwDataSize; // Size of Data following header. } WBEM_DATAPACKET_OBJECTSINK_INDICATE; typedef WBEM_DATAPACKET_OBJECTSINK_INDICATE* PWBEM_DATAPACKET_OBJECTSINK_INDICATE; // restore packing #pragma pack( pop ) #pragma pack( push ) #pragma pack( 1 ) // IWbemObjectSink::Indicate() Header. Changing this will // cause the main version to change typedef struct tagWBEM_DATAPACKET_UNBOUNDSINK_INDICATE { DWORD dwSizeOfHeader; // Size of the header struct. Data immediately follows header. DWORD dwDataSize; // Size of Data following header. DWORD dwLogicalConsumerSize; // Size of Logical Consumer Object } WBEM_DATAPACKET_UNBOUNDSINK_INDICATE; #ifdef _WIN64 typedef UNALIGNED WBEM_DATAPACKET_UNBOUNDSINK_INDICATE * PWBEM_DATAPACKET_UNBOUNDSINK_INDICATE; #else typedef WBEM_DATAPACKET_UNBOUNDSINK_INDICATE * PWBEM_DATAPACKET_UNBOUNDSINK_INDICATE; #endif // restore packing #pragma pack( pop ) #pragma pack( push ) #pragma pack( 1 ) // IWbemMultiTarget::DeliverEvent() Header. Changing this will // cause the main version to change typedef struct tagWBEM_DATAPACKET_MULTITARGET_DELIVEREVENT { DWORD dwSizeOfHeader; // Size of the header struct. Data immediately follows header. DWORD dwDataSize; // Size of Data following header. } WBEM_DATAPACKET_MULTITARGET_DELIVEREVENT; typedef WBEM_DATAPACKET_MULTITARGET_DELIVEREVENT* PWBEM_DATAPACKET_MULTITARGET_DELIVEREVENT; // restore packing #pragma pack( pop ) #include <wbemobjpacket.h> #include <malloc.h> #ifndef HEAP_ENTRY typedef struct _HEAP_ENTRY { USHORT Size; USHORT PreviousSize; UCHAR SmallTagIndex; UCHAR Flags; UCHAR UnusedBytes; UCHAR SegmentIndex; #if defined(_WIN64) ULONGLONG Reserved1; #endif } HEAP_ENTRY, *PHEAP_ENTRY; #endif void GetCompressedString(ULONG_PTR pRemoteAddr, BYTE * pBuff, DWORD Size){ if (pRemoteAddr) { CCompressedString * pCS = (CCompressedString *)_alloca(Size*2); ReadMemory(pRemoteAddr,pCS,Size*2,0); pBuff[Size-2]=0; pBuff[Size-1]=0; if (pCS->m_fFlags == STRING_FLAG_UNICODE){ WideCharToMultiByte(CP_ACP,0,(WCHAR *)&(pCS->m_cFirstByte),-1,(LPSTR)pBuff,Size-2,NULL,NULL); } else { memcpy(pBuff,&(pCS->m_cFirstByte),Size-2); } } else { lstrcpyA((LPSTR)pBuff,"<NULL>"); } } /* protected: length_t m_nTotalLength; //CDecorationPart m_DecorationPart; CClassAndMethods m_ParentPart; CClassAndMethods m_CombinedPart; int m_nCurrentMethod; CLimitationMapping* m_pLimitMapping; friend class CWbemInstance; */ /* CClassPart m_ClassPart; CMethodPart m_MethodPart; CWbemClass* m_pClass; */ void DumpClass(CClassPart * pCls){ BYTE pBuff[256]; dprintf(" m_pContainer %p m_pParent %p m_pHeader %p\n",pCls->m_pContainer,pCls->m_pParent,pCls->m_pHeader); DEFINE_CPP_VAR(CClassPart::CClassPartHeader,varHeader); CClassPart::CClassPartHeader * pHeader = GET_CPP_VAR_PTR( CClassPart::CClassPartHeader , varHeader ); if (pCls->m_pHeader){ ReadMemory((ULONG_PTR)pCls->m_pHeader,pHeader,sizeof(CClassPart::CClassPartHeader),0); dprintf(" nLength %x fFlags %02x ptrClassName %08x nDataLength %x\n",pHeader->nLength,pHeader->fFlags,pHeader->ptrClassName,pHeader->nDataLength); } dprintf(" DL m_nNumStrings %x %08x\n",pCls->m_Derivation.m_nNumStrings,pCls->m_Derivation.m_pnLength); dprintf(" QS m_nLength %x m_pOthers %08x m_pHeap %08x\n",pCls->m_Qualifiers.m_nLength,pCls->m_Qualifiers.m_pOthers,pCls->m_Qualifiers.m_pHeap); DEFINE_CPP_VAR(CFastHeap,varCFastHeap); CFastHeap * pFHeap = GET_CPP_VAR_PTR( CFastHeap , varCFastHeap ); ReadMemory((ULONG_PTR)pCls->m_Qualifiers.m_pHeap,pFHeap,sizeof(CFastHeap),0); dprintf(" FH m_pHeapData %08x m_pHeapHeader %08x m_pContainer %08x\n",pFHeap->m_pHeapData,pFHeap->m_pHeapHeader,pFHeap->m_pContainer); dprintf(" m_nPropagationFlag %x m_nRef %x\n",pCls->m_Qualifiers.m_nPropagationFlag,pCls->m_Qualifiers.m_nRef); dprintf(" m_pControl %08x m_pContainer %08x m_pSecondarySet %08x\n",pCls->m_Qualifiers.m_pControl,pCls->m_Qualifiers.m_pContainer,pCls->m_Qualifiers.m_pSecondarySet); dprintf(" BA m_nSize %x m_astrStrings %08x\n",pCls->m_Qualifiers.m_astrCurrentNames.m_nSize,pCls->m_Qualifiers.m_astrCurrentNames.m_astrStrings); int nProp; if (pCls->m_Properties.m_pnProps) { ReadMemory((ULONG_PTR)pCls->m_Properties.m_pnProps,&nProp,sizeof(int),0); dprintf(" PR m_pnProps %08x %x m_pContainer %08x\n",pCls->m_Properties.m_pnProps,nProp,pCls->m_Properties.m_pContainer); CPropertyLookup * pPropLook = (CPropertyLookup *)_alloca(nProp*sizeof(CPropertyLookup)); ReadMemory((ULONG_PTR)pCls->m_Properties.m_pnProps+sizeof(int),pPropLook,nProp*sizeof(CPropertyLookup),0); DWORD i; for (i=0;i<nProp;i++){ pBuff[0]=0; if ((ULONG_PTR)(pCls->m_Heap.m_pHeapData+pPropLook[i].ptrName) != 0xffffffff){ GetCompressedString((ULONG_PTR)(pCls->m_Heap.m_pHeapData+pPropLook[i].ptrName),pBuff,sizeof(pBuff)); } DEFINE_CPP_VAR(CPropertyInformation,varCPropertyInformation); CPropertyInformation * pPropInfo = GET_CPP_VAR_PTR( CPropertyInformation , varCPropertyInformation ); ReadMemory((ULONG_PTR)pCls->m_Heap.m_pHeapData+pPropLook[i].ptrInformation,pPropInfo ,sizeof(CPropertyInformation),0); dprintf(" prop %d %s Type %08x DataIdx %04x DataOff %08x Origin %08x\n",i, pBuff, pPropInfo->nType, pPropInfo->nDataIndex, pPropInfo->nDataOffset, pPropInfo->nOrigin); if (CheckControlC()) break; } } else { dprintf(" PR m_pnProps %08x m_pContainer %08x\n",pCls->m_Properties.m_pnProps,pCls->m_Properties.m_pContainer); } CDataTable * pCData = &pCls->m_Defaults; dprintf(" DT m_pNullness %08x m_pData %08x m_nLength %x m_nProps %x m_pContainer %08x\n",pCData->m_pNullness,pCData->m_pData,pCData->m_nLength,pCData->m_nProps,pCData->m_pContainer); dprintf(" FH m_pHeapData %08x m_pHeapHeader %08x m_pContainer %08x\n",pCls->m_Heap.m_pHeapData,pCls->m_Heap.m_pHeapHeader,pCls->m_Heap.m_pContainer); //CHeapHeader m_LocalHeapHeader; BYTE * pHeap = pCls->m_Heap.m_pHeapData; pBuff[0]=0; if ((DWORD)(pHeader->ptrClassName) != 0xffffffff){ GetCompressedString((ULONG_PTR)(pHeap+pHeader->ptrClassName),pBuff,sizeof(pBuff)); } dprintf(" __RELPATH %s\n",pBuff); } void DecodeStatus(DWORD dwInternalStatus) { if (dwInternalStatus & WBEM_OBJ_DECORATION_PART) dprintf("WBEM_OBJ_DECORATION_PART "); if (dwInternalStatus & WBEM_OBJ_INSTANCE_PART) dprintf("WBEM_OBJ_INSTANCE_PART "); if (dwInternalStatus & WBEM_OBJ_CLASS_PART) dprintf("WBEM_OBJ_CLASS_PART "); if (dwInternalStatus & WBEM_OBJ_CLASS_PART_INTERNAL) dprintf("WBEM_OBJ_CLASS_PART_INTERNAL "); if (dwInternalStatus & WBEM_OBJ_CLASS_PART_SHARED) dprintf("WBEM_OBJ_CLASS_PART_SHARED "); }; DECLARE_API(wc) { INIT_API(); DEFINE_CPP_VAR( CWbemClass, varCWbemClass); CWbemClass * pCls = GET_CPP_VAR_PTR( CWbemClass , varCWbemClass ); ULONG_PTR pByte = 0; pByte = GetExpression(args); if (pByte){ ReadMemory(pByte,pCls,sizeof(CWbemClass),0); dprintf(" m_nRef %d m_bOwnMemory %d\n",pCls->m_nRef,pCls->m_bOwnMemory); dprintf(" m_nCurrentProp %08x m_lEnumFlags %08x m_lExtEnumFlags %08x\n",pCls->m_nCurrentProp,pCls->m_lEnumFlags,pCls->m_lExtEnumFlags); dprintf(" m_dwInternalStatus %08x m_pMergedClassObject %08x\n",pCls->m_dwInternalStatus,pCls->m_pMergedClassObject); BYTE * pData = pCls->m_DecorationPart.m_pfFlags; BYTE pBuff1[256]; GetCompressedString((ULONG_PTR)pCls->m_DecorationPart.m_pcsServer,pBuff1,sizeof(pBuff1)); BYTE pBuff2[256]; GetCompressedString((ULONG_PTR)pCls->m_DecorationPart.m_pcsNamespace,pBuff2,sizeof(pBuff2)); BYTE b=0xff; if (pData){ ReadMemory((ULONG_PTR)pData,&b,sizeof(b),0); } dprintf(" m_DecorationPart.m_pfFlags %p FLAG %02x\n",pData,b); dprintf(" Server: %s Namespace: %s\n",pBuff1,pBuff2); dprintf(" m_LockData: m_lLock %d m_lLockCount %d m_dwThreadId %x\n",pCls->m_LockData.m_lLock,pCls->m_LockData.m_lLockCount,pCls->m_LockData.m_dwThreadId); dprintf(" m_Lock.m_pData %p\n",pCls->m_Lock.m_pData); //dprintf(" m_pBlobControl %08x m_refDataTable %08x m_refDataHeap %08x m_refDerivationList %08x\n",pCls->m_pBlobControl,((void *)&pCls->m_refDataTable),((void *)&pCls->m_refDataHeap),((void *)&pCls->m_refDerivationList)); dprintf(" m_pBlobControl %p\n",pCls->m_pBlobControl); DEFINE_CPP_VAR( CDataTable,varCDataTable); CDataTable * pCData = GET_CPP_VAR_PTR(CDataTable,varCDataTable); if(pCData){ ReadMemory((ULONG_PTR)(&(pCls->m_refDataTable)),pCData,sizeof(CDataTable),0); dprintf(" m_pNullness %p m_pData %p m_nLength %x m_nProps %x m_pContainer %08x\n",pCData->m_pNullness,pCData->m_pData,pCData->m_nLength,pCData->m_nProps,pCData->m_pContainer); } DEFINE_CPP_VAR(CFastHeap,varCFastHeap); CFastHeap * pFHeap = GET_CPP_VAR_PTR( CFastHeap , varCFastHeap ); DWORD * pFoo = (DWORD *)&(pCls->m_refDataHeap); ReadMemory((ULONG_PTR )pFoo,pFHeap,sizeof(CFastHeap),0); dprintf(" FH m_pHeapData %p m_pHeapHeader %p m_pContainer %p\n",pFHeap->m_pHeapData,pFHeap->m_pHeapHeader,pFHeap->m_pContainer); dprintf(" m_nTotalLength %x\n",pCls->m_nTotalLength); dprintf(" m_ParentPart at offset %x\n",(ULONG_PTR)&pCls->m_ParentPart-(ULONG_PTR)pCls); dprintf(" m_ParentPart.m_pClassPart at offset %x\n",(ULONG_PTR)&(pCls->m_ParentPart.m_ClassPart)-(ULONG_PTR)pCls); DumpClass(&(pCls->m_ParentPart.m_ClassPart)); dprintf(" m_CombinedPart at offset %x\n",(ULONG_PTR)&pCls->m_CombinedPart-(ULONG_PTR)pCls); DumpClass(&(pCls->m_CombinedPart.m_ClassPart)); dprintf(" m_pClass %08x\n",pCls->m_ParentPart.m_pClass); } else { dprintf("invalid address %s\n",args); } } void DumpInstance(CInstancePart * pIns) { dprintf(" m_pContainer %08x m_pHeader %08x\n",pIns->m_pContainer,pIns->m_pHeader); dprintf(" DT m_DataTable m_pNullness %08x m_pData %08x\n",pIns->m_DataTable.m_pNullness,pIns->m_DataTable.m_pData); dprintf(" m_nLength %x m_nProps %x m_pContainer %08x\n",pIns->m_DataTable.m_nLength,pIns->m_DataTable.m_nProps,pIns->m_DataTable.m_pContainer); dprintf(" Q m_Qualifiers m_nPropagationFlag %08x m_nRef %x m_pControl %08x\n",pIns->m_Qualifiers.m_nPropagationFlag,pIns->m_Qualifiers.m_nRef,pIns->m_Qualifiers.m_pControl); dprintf(" m_pContainer %08x m_pSecondarySet %08x\n",pIns->m_Qualifiers.m_pContainer,pIns->m_Qualifiers.m_pSecondarySet); CFixedBSTRArray * pArr = &(pIns->m_Qualifiers.m_astrCurrentNames); dprintf(" m_nCurrentIndex %x\n",pIns->m_Qualifiers.m_nCurrentIndex); DEFINE_CPP_VAR(CInstancePart::CInstancePartHeader,varHeader); CInstancePart::CInstancePartHeader * pHeader = GET_CPP_VAR_PTR( CInstancePart::CInstancePartHeader , varHeader ); if (pIns->m_pHeader) { if (ReadMemory((ULONG_PTR)pIns->m_pHeader,pHeader,sizeof(CInstancePart::CInstancePartHeader),0)) { dprintf(" nLength %x fFlags %02x ptrClassName %08x \n",pHeader->nLength,pHeader->fFlags,pHeader->ptrClassName); } else { dprintf("RM %p\n",pIns->m_pHeader); } } dprintf(" FH m_pHeapData %08x m_pHeapHeader %08x m_pContainer %08x\n",pIns->m_Heap.m_pHeapData,pIns->m_Heap.m_pHeapHeader,pIns->m_Heap.m_pContainer); } DECLARE_API(wi) { INIT_API(); DEFINE_CPP_VAR( CWbemInstance, varCWbemInstance); CWbemInstance * pCls = GET_CPP_VAR_PTR( CWbemInstance , varCWbemInstance ); ULONG_PTR pByte = 0; pByte = GetExpression(args); if (pByte) { if (ReadMemory(pByte,pCls,sizeof(CWbemInstance),0)) { //length_t m_nTotalLength; //dprintf(" m_nTotalLength %08x\n",pCls->m_nTotalLength); dprintf(" m_nRef %d m_bOwnMemory %d\n",pCls->m_nRef,pCls->m_bOwnMemory); dprintf(" m_nCurrentProp %08x m_lEnumFlags %08x m_lExtEnumFlags %08x\n",pCls->m_nCurrentProp,pCls->m_lEnumFlags,pCls->m_lExtEnumFlags); dprintf(" m_dwInternalStatus %08x\n",pCls->m_dwInternalStatus); DecodeStatus(pCls->m_dwInternalStatus); dprintf("\n"); dprintf(" m_pMergedClassObject %08x\n",pCls->m_pMergedClassObject); BYTE * pData = pCls->m_DecorationPart.m_pfFlags; BYTE pBuff1[256]; GetCompressedString((ULONG_PTR)pCls->m_DecorationPart.m_pcsServer,pBuff1,sizeof(pBuff1)); BYTE pBuff2[256]; GetCompressedString((ULONG_PTR)pCls->m_DecorationPart.m_pcsNamespace,pBuff2,sizeof(pBuff2)); BYTE b=0xff; if (pData){ ReadMemory((ULONG_PTR)pData,&b,sizeof(b),0); } dprintf(" m_DecorationPart.m_pfFlags %p FLAG %02x\n",pData,b); dprintf(" Server: %s Namespace: %s\n",pBuff1,pBuff2); //CClassPart m_ClassPart; DumpClass(&(pCls->m_ClassPart)); //CInstancePart m_InstancePart; DumpInstance(&(pCls->m_InstancePart)); //CVar m_CachedKey; dprintf(" m_vt %08x m_value %08x m_nStatus %08x m_bCanDelete %08x\n",pCls->m_CachedKey.m_vt,pCls->m_CachedKey.m_value.pUnk,pCls->m_CachedKey.m_nStatus,pCls->m_CachedKey.m_bCanDelete); } else { dprintf("RM %p\n",pByte); } } else { dprintf("invalid address %s\n",args); } } DECLARE_API(cp) { INIT_API(); DEFINE_CPP_VAR( CClassPart, varCClassPart); CClassPart * pCls = GET_CPP_VAR_PTR( CClassPart , varCClassPart ); ULONG_PTR pByte = 0; pByte = GetExpression(args); if (pByte){ ReadMemory(pByte,pCls,sizeof(CClassPart),0); DumpClass(pCls); } else { dprintf("invalid address %s\n",args); } } /* typedef union { char cVal; // VT_I1 BYTE bVal; // VT_UI1 SHORT iVal; // VT_I2 WORD wVal; // VT_UI2 LONG lVal; // VT_I4 DWORD dwVal; // VT_UI4 VARIANT_BOOL boolVal; // VT_BOOL float fltVal; // VT_R4 double dblVal; // VT_R8 LPSTR pStr; // VT_LPSTR LPWSTR pWStr; // VT_LPWSTR BSTR Str; // VT_BSTR (stored as VT_LPWSTR) FILETIME Time; // VT_FILETIME BLOB Blob; // VT_BLOB LPCLSID pClsId; // VT_CLSID IUnknown* pUnk; // VT_UNKNOWN IDispatch* pDisp; // VT_DISPATCH CVarVector *pVarVector; // VT_EX_CVARVECTOR } METAVALUE; int m_vt; METAVALUE m_value; int m_nStatus; BOOL m_bCanDelete; */ DECLARE_API(cvar) { INIT_API(); DEFINE_CPP_VAR( CVar, varCVar); CVar * pVar = GET_CPP_VAR_PTR( CVar , varCVar ); WCHAR pwBuff[128]; CHAR pBuff[128]; ULONG_PTR pByte = 0; pByte = GetExpression(args); if (pByte){ ReadMemory(pByte,pVar,sizeof(CVar),0); switch(pVar->m_vt){ case VT_I1: dprintf("VT_I1 %02x\n",pVar->m_value.cVal); break; case VT_UI1: dprintf("VT_UI1 %02x\n",pVar->m_value.bVal); break; case VT_I2: dprintf("VT_I2 %04x\n",pVar->m_value.iVal); break; case VT_UI2: dprintf("VT_UI2 %04x\n",pVar->m_value.wVal); break; case VT_I4: dprintf("VT_I4 %08x\n",pVar->m_value.lVal); break; case VT_UI4: dprintf("VT_UI4 %08x\n",pVar->m_value.dwVal); break; case VT_BOOL: dprintf("VT_BOOL %04x\n",pVar->m_value.boolVal); break; case VT_R4: dprintf("VT_R4 %f\n",pVar->m_value.fltVal); break; case VT_R8: dprintf("VT_R8 %e\n",pVar->m_value.dblVal); break; case VT_LPSTR: ReadMemory((ULONG_PTR)pVar->m_value.pStr,pBuff,sizeof(pBuff),0); pBuff[sizeof(pBuff)-1]=0; dprintf("VT_LPSTR %s\n",pBuff); break; case VT_LPWSTR: case VT_BSTR: ReadMemory((ULONG_PTR)pVar->m_value.pWStr,pwBuff,sizeof(pwBuff),0); pwBuff[sizeof(pwBuff)-1]=0; WideCharToMultiByte(CP_ACP,0,pwBuff,-1,pBuff,sizeof(pBuff),NULL,NULL); pBuff[sizeof(pBuff)-1]=0; dprintf("VT_BSTR %s\n",pBuff); break; /* FILETIME Time; // VT_FILETIME BLOB Blob; // VT_BLOB LPCLSID pClsId; // VT_CLSID IUnknown* pUnk; // VT_UNKNOWN IDispatch* pDisp; // VT_DISPATCH */ case VT_EX_CVARVECTOR: //CVarVector *pVarVector; // VT_EX_CVARVECTOR dprintf("VT_EX_CVARVECTOR %08x\n",pVar->m_value.pVarVector); break; default: dprintf("m_vt %08x\n",pVar->m_vt); } } else { dprintf("invalid address %s\n",args); } } /* class POLARITY CVarVector { int m_nType; CFlexArray m_Array; int m_nStatus; */ LPSTR g_QualStrings[] = { "", // nothing for index 0 "key", "", "read", "write", "volatile", "provider", "dynamic", "cimwin32", "DWORD", "CIMTYPE" }; DWORD g_ValLengths[128] = { /* 0*/ 0, 0, 2, 4, 4, 8, 0, 0, 4, 0, /*10*/ 0, 2, 0, 4, 0, 0, 1, 1, 2, 4, /*20*/ 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, /*30*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*40*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*50*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*60*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*70*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*80*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*90*/ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*100*/0, 4, 4, 2, 0, 0, 0, 0, 0, 0, /*110*/0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /*120*/0, 0, 0, 0, 0, 0, 0, 0 }; int lstrlenWunal( WCHAR UNALIGNED * pStr) { int ret = 0; while (*pStr++) ret++; return ret; }; VOID ParseBlob(BYTE * pMemOrg,ULONG_PTR Addr) { DWORD ClassPartLength = 0; DWORD i; BYTE * pMem = pMemOrg; BYTE Flags; BOOL IsInstance = FALSE; BOOL SkipDecoration = TRUE; BYTE BFlags = *pMem; pMem++; if (OBJECT_FLAG_CLASS & BFlags ) { dprintf("CLASS\n"); } if (OBJECT_FLAG_INSTANCE & BFlags ) { dprintf("INSTANCE\n"); IsInstance = TRUE; } if (OBJECT_FLAG_DECORATED & BFlags) { dprintf("DECORATED\n"); } if (OBJECT_FLAG_LIMITED & BFlags) { dprintf("LIMITED\n"); } if (OBJECT_FLAG_CLIENT_ONLY & BFlags) { dprintf("CLIENT_ONLY\n"); } if (BFlags & OBJECT_FLAG_DECORATED) { SkipDecoration = FALSE; //dprintf("decoration:\n"); Flags = *pMem; pMem++; if (Flags == STRING_FLAG_UNICODE) { dprintf("SERVER : %S\n",pMem); pMem+=(1+2*lstrlenWunal((WCHAR UNALIGNED *)pMem)); } else { dprintf("SERVER : %s\n",pMem); pMem+=(1+lstrlenA((CHAR *)pMem)); } Flags = *pMem; pMem++; if (Flags == STRING_FLAG_UNICODE) { dprintf("namespace: %S\n",pMem); pMem+=(1+2*lstrlenWunal((WCHAR UNALIGNED *)pMem)); } else { dprintf("NAMESPACE: %s\n",pMem); pMem+=(1+lstrlenA((CHAR *)pMem)); } }; ClassPartLength = *((DWORD UNALIGNED *)pMem); pMem += sizeof(DWORD); BYTE Unused = *pMem; pMem++; DWORD HeapPtrName = *((DWORD UNALIGNED *)pMem); pMem += sizeof(DWORD); DWORD NullDefaultSize = *((DWORD UNALIGNED *)pMem); pMem += sizeof(DWORD); DWORD DerivationSize = *((DWORD UNALIGNED *)pMem); DerivationSize &= 0xFFFF; //dprintf("D %08x\n",DerivationSize); DWORD QualSetSize = *((DWORD UNALIGNED *)(pMem+DerivationSize)); //dprintf("Q %08x\n",QualSetSize); QualSetSize &= 0xFFFF; DWORD NumProps = *((DWORD UNALIGNED *)(pMem+DerivationSize+QualSetSize)); DWORD UNALIGNED * pPropLookup = (DWORD UNALIGNED *)(pMem+DerivationSize+QualSetSize+sizeof(DWORD)); BYTE * pPropLookup_OOP = (BYTE *)Addr + (pMem - pMemOrg) + DerivationSize+QualSetSize; BYTE * HeapPtr = pMem + DerivationSize + QualSetSize + sizeof(DWORD) + NumProps*(2*sizeof(DWORD)) + NullDefaultSize; BYTE * HeapPtr_OOP = (BYTE *)Addr + (pMem - pMemOrg) + DerivationSize + QualSetSize + sizeof(DWORD) + NumProps*(2*sizeof(DWORD)) + NullDefaultSize; //dprintf("CPLen %p N %p D %p Q %p Prop %p Heap %p\n", // ClassPartLength, // NullDefaultSize, // DerivationSize,QualSetSize,NumProps,*((DWORD UNALIGNED *)HeapPtr)); dprintf(" class_and_method\n"); dprintf(" class_Part\n"); if (0xFFFFFFFF != HeapPtrName) { BYTE * pName = HeapPtr + sizeof(DWORD) + HeapPtrName; Flags = *pName; pName++; if (Flags == STRING_FLAG_UNICODE) { dprintf(" class : %S\n",pName); } else { dprintf(" class : %s\n",pName); } } else { dprintf(" class : %08x\n",HeapPtrName); } // QualSet dprintf(" qualifierset %p\n",Addr+(pMem + DerivationSize - pMemOrg)); ULONG_PTR pEndQualSet = (ULONG_PTR)pMem + DerivationSize + QualSetSize; BYTE * pQualSet = pMem + DerivationSize + sizeof(DWORD); //dprintf(" %p %p\n",pQualSet,pEndQualSet); while((ULONG_PTR)pQualSet < pEndQualSet) { DWORD dwHeapPtr = (*((DWORD UNALIGNED *)pQualSet)); pQualSet += sizeof(DWORD); BYTE Flavor = *pQualSet; pQualSet += sizeof(BYTE); DWORD Type = (*((DWORD UNALIGNED *)pQualSet)); pQualSet += sizeof(DWORD); BYTE * pData = pQualSet; pQualSet += g_ValLengths[Type&0x7F]; if (dwHeapPtr & 0x80000000) { dprintf(" %s %02x %08x %p\n",g_QualStrings[dwHeapPtr&0x7fffffff],Flavor,Type,*(DWORD UNALIGNED *)pData); } else { dprintf(" %s %02x %08x %p\n",HeapPtr+dwHeapPtr+1+sizeof(DWORD),Flavor,Type,*(DWORD UNALIGNED *)pData); } if (CheckControlC()) break; } // property lookup table dprintf(" propertylookup %p\n",pPropLookup_OOP); for (i=0;i<NumProps;i++) { WORD UNALIGNED * pPropInfo = (WORD UNALIGNED *)(HeapPtr+sizeof(DWORD)+pPropLookup[1]); dprintf(" %08x %08x %s %08x %04x %08x %08x\n", pPropLookup[0],pPropLookup[1], HeapPtr+pPropLookup[0]+1+sizeof(DWORD), *((DWORD UNALIGNED *)pPropInfo), *(pPropInfo+2), *(DWORD UNALIGNED *)(pPropInfo+3), *(DWORD UNALIGNED *)(pPropInfo+5)); pPropLookup += 2; } DWORD dwHeapSize_ClassPart = (*((DWORD UNALIGNED *)HeapPtr))&0x7FFFFFFF; dprintf(" Heap %p size %08x\n",HeapPtr_OOP,dwHeapSize_ClassPart); dprintf(" method_Part\n"); BYTE * pMethodPart = HeapPtr + sizeof(DWORD) + dwHeapSize_ClassPart; BYTE * pMethodPart_OOP = HeapPtr_OOP + sizeof(DWORD) + dwHeapSize_ClassPart; DWORD dwSizeMethodPart = *((DWORD UNALIGNED *)pMethodPart); DWORD NumMethods = *((DWORD UNALIGNED *)(pMethodPart+sizeof(DWORD))); BYTE * pMethodDescription= pMethodPart + 2*sizeof(DWORD); BYTE * pMethodDescription_OOP = pMethodPart_OOP + 2*sizeof(DWORD); //BYTE * pHeapMethod_OOP = ; dprintf(" num_methods : %08x\n",NumMethods); dprintf(" methods_descr : %p\n",pMethodDescription_OOP); //dprintf(" heap : %p\n"); BYTE * pCombinedPart = pMethodPart + dwSizeMethodPart; BYTE * pCombinedPart_OOP = pMethodPart_OOP + dwSizeMethodPart; if (IsInstance) { dprintf(" instance\n"); DWORD dwHeapSize = 4 + (*((DWORD UNALIGNED *)HeapPtr)) & 0x7fffffff; //BYTE * HeapPtr_OOP BYTE * pInstancePart = HeapPtr+dwHeapSize; BYTE * pInstancePart_OOP = HeapPtr_OOP+dwHeapSize; DWORD dwSize = *((DWORD UNALIGNED *)pInstancePart); pInstancePart += sizeof(DWORD); BYTE IFlag = *pInstancePart; pInstancePart++; DWORD dwClassNameOffset = *((DWORD UNALIGNED *)pInstancePart); pInstancePart += sizeof(DWORD); BYTE * pDataTable = pInstancePart; BYTE * pDataTable_OOP = pInstancePart_OOP + 2*sizeof(DWORD) + sizeof(BYTE); DWORD NumBytedNullNess = ((NumProps*2)%8)?(1+((NumProps*2)/8)):((NumProps*2)/8); BYTE * pDataTableData = pInstancePart + NumBytedNullNess; BYTE * pDataTableData_OOP = pDataTable_OOP + NumBytedNullNess; pInstancePart += NullDefaultSize; // this is crucial BYTE * pQualSet = pInstancePart; BYTE * pQualSet_OOP = pDataTable_OOP + NullDefaultSize; DWORD dwQualSetSize = *((DWORD UNALIGNED *)pQualSet); pInstancePart += dwQualSetSize; BYTE * pQualSetList = pInstancePart; BYTE * pInstanceHeap; BYTE * pInstanceHeap_OOP; if (0x01 == *pQualSetList) { // empty qual set OK pInstancePart++; pInstanceHeap = pInstancePart; pInstanceHeap_OOP = pQualSet_OOP+dwQualSetSize+sizeof(BYTE); } else if (0x02 == *pQualSetList) { // multiple qualifier set dprintf("unimplemented"); return; } else { // invalid qualset } //NullDefaultSize dprintf(" begin %p\n",pInstancePart_OOP); dprintf(" data_table: null %p data %p\n",pDataTable_OOP,pDataTableData_OOP); dprintf(" qual_set %p\n",pQualSet_OOP); dprintf(" heap %p\n",pInstanceHeap_OOP); } else { dprintf(" class_and_method\n"); dprintf(" start : %p\n",pCombinedPart_OOP); } } DECLARE_API(blob) { INIT_API(); char * pArgs = (char *)_alloca(strlen(args)+1); lstrcpy(pArgs,args); ULONG_PTR pByte = 0; ULONG_PTR Size = 0; while (isspace(*pArgs)) pArgs++; char * pAddress = pArgs; //dprintf("%s %s\n",pAddress,pArgs); // skip good chars while(*pArgs && !isspace(*pArgs)) pArgs++; if(*pArgs) // if there are more chars { *pArgs = 0; //terminate string pArgs++; // skip spaces while(isspace(*pArgs)) pArgs++; if (*pArgs) { //dprintf("%s\n",pArgs); Size = GetExpression(pArgs); } } pByte = GetExpression(pAddress); if (pByte) { if (Size) { BYTE * pHereMem = (BYTE *)HeapAlloc(GetProcessHeap(),0,Size*2); if (ReadMemory(pByte,pHereMem,Size*2,0)) { //dprintf(" object @ %p size %x\n",pByte,Size); ParseBlob(pHereMem,pByte); } else { dprintf("RM %p\n",pByte); } HeapFree(GetProcessHeap(),0,pHereMem); } else { HEAP_ENTRY HeapEntry; if (ReadMemory(pByte-(sizeof(HEAP_ENTRY)),&HeapEntry,sizeof(HEAP_ENTRY),0)) { Size = HeapEntry.Size*sizeof(HEAP_ENTRY); BYTE * pHereMem = (BYTE *)HeapAlloc(GetProcessHeap(),0,Size); if (ReadMemory(pByte,pHereMem,Size,0)) { ParseBlob(pHereMem,pByte); } else { dprintf("RM %p\n",pByte); } HeapFree(GetProcessHeap(),0,pHereMem); } else { dprintf("RM %p\n",pByte); } } } } DECLARE_API(datap) { INIT_API(); ULONG_PTR Addr = GetExpression(args); if (Addr) { DWORD dwSize = 256; // and let's hope //sizeof(WBEM_DATAPACKET_HEADER) + //sizeof(WBEM_DATAPACKET_SMARTENUM_NEXT) + //sizeof(WBEM_DATAPACKET_OBJECT_ARRAY) + //sizeof(WBEM_DATAPACKET_OBJECT_HEADER); WBEM_DATAPACKET_HEADER * pData = (WBEM_DATAPACKET_HEADER *)_alloca(dwSize); if (ReadMemory(Addr,pData,dwSize,NULL)) { dprintf(" Order %08x\n",pData->dwByteOrdering); dprintf(" Header %08x DSize %08x Flags %08x %02x ", pData->dwSizeOfHeader, pData->dwDataSize, pData->dwFlags, pData->bVersion); switch(pData->bPacketType) { case WBEM_DATAPACKETTYPE_OBJECTSINK_INDICATE: { dprintf("WBEM_DATAPACKETTYPE_OBJECTSINK_INDICATE\n"); WBEM_DATAPACKET_OBJECTSINK_INDICATE UNALIGNED * pIndicate = (WBEM_DATAPACKET_OBJECTSINK_INDICATE UNALIGNED *)((BYTE *)pData + pData->dwSizeOfHeader); dprintf(" Header %08x Size %08x\n",pIndicate->dwSizeOfHeader,pIndicate->dwDataSize); WBEM_DATAPACKET_OBJECT_ARRAY UNALIGNED * pArrayPacket = (WBEM_DATAPACKET_OBJECT_ARRAY UNALIGNED *)((BYTE * )pIndicate+pIndicate->dwSizeOfHeader); dprintf(" Header %08x Size %08x NumObj %08x\n", pArrayPacket->dwSizeOfHeader, pArrayPacket->dwDataSize, pArrayPacket->dwNumObjects); WBEM_DATAPACKET_OBJECT_HEADER UNALIGNED * pObjHeader = (WBEM_DATAPACKET_OBJECT_HEADER UNALIGNED *)((BYTE*)pArrayPacket+pArrayPacket->dwSizeOfHeader); dprintf(" Header %08x dwSizeOfData %08x bObjectType ",pObjHeader->dwSizeOfHeader,pObjHeader->dwSizeOfData); switch(pObjHeader->bObjectType) { case WBEMOBJECT_NONE: dprintf("WBEMOBJECT_NONE\n"); break; case WBEMOBJECT_CLASS_FULL: dprintf("WBEMOBJECT_CLASS_FULL\n"); break; case WBEMOBJECT_INSTANCE_FULL: dprintf("WBEMOBJECT_INSTANCE_FULL\n"); break; case WBEMOBJECT_INSTANCE_NOCLASS: dprintf("WBEMOBJECT_INSTANCE_NOCLASS\n"); break; }; dprintf(" data: %p\n",Addr+pData->dwSizeOfHeader+pIndicate->dwSizeOfHeader+pArrayPacket->dwSizeOfHeader+pObjHeader->dwSizeOfHeader); } break; case WBEM_DATAPACKETTYPE_SMARTENUM_NEXT: { dprintf("WBEM_DATAPACKETTYPE_SMARTENUM_NEXT\n"); WBEM_DATAPACKET_SMARTENUM_NEXT UNALIGNED * pSNext = (WBEM_DATAPACKET_SMARTENUM_NEXT UNALIGNED *)((BYTE *)pData + pData->dwSizeOfHeader); dprintf(" Header %08x dwDataSize %08x\n",pSNext->dwSizeOfHeader,pSNext->dwDataSize); WBEM_DATAPACKET_OBJECT_ARRAY UNALIGNED * pArrayPacket = (WBEM_DATAPACKET_OBJECT_ARRAY UNALIGNED *)((BYTE * )pSNext+pSNext->dwSizeOfHeader); dprintf(" Header %08x Size %08x NumObj %08x\n", pArrayPacket->dwSizeOfHeader, pArrayPacket->dwDataSize, pArrayPacket->dwNumObjects); WBEM_DATAPACKET_OBJECT_HEADER UNALIGNED * pObjHeader = (WBEM_DATAPACKET_OBJECT_HEADER UNALIGNED *)((BYTE*)pArrayPacket+pArrayPacket->dwSizeOfHeader); dprintf(" Header %08x dwSizeOfData %08x bObjectType ",pObjHeader->dwSizeOfHeader,pObjHeader->dwSizeOfData); switch(pObjHeader->bObjectType) { case WBEMOBJECT_NONE: dprintf("WBEMOBJECT_NONE\n"); break; case WBEMOBJECT_CLASS_FULL: dprintf("WBEMOBJECT_CLASS_FULL\n"); break; case WBEMOBJECT_INSTANCE_FULL: dprintf("WBEMOBJECT_INSTANCE_FULL\n"); break; case WBEMOBJECT_INSTANCE_NOCLASS: dprintf("WBEMOBJECT_INSTANCE_NOCLASS\n"); break; }; dprintf(" data: %p\n",Addr+pData->dwSizeOfHeader+pSNext->dwSizeOfHeader+pArrayPacket->dwSizeOfHeader+pObjHeader->dwSizeOfHeader); } break; case WBEM_DATAPACKETTYPE_UNBOUNDSINK_INDICATE: { dprintf("WBEM_DATAPACKETTYPE_UNBOUNDSINK_INDICATE\n"); WBEM_DATAPACKET_UNBOUNDSINK_INDICATE UNALIGNED * pUnBoundI = (WBEM_DATAPACKET_UNBOUNDSINK_INDICATE UNALIGNED *)((BYTE *)pData + pData->dwSizeOfHeader); dprintf(" Header %08x dwDataSize %08x dwLogicalConsumerSize %08x\n",pUnBoundI->dwSizeOfHeader,pUnBoundI->dwDataSize,pUnBoundI->dwLogicalConsumerSize); } break; case WBEM_DATAPACKETTYPE_MULTITARGET_DELIVEREVENT: { dprintf("WBEM_DATAPACKETTYPE_MULTITARGET_DELIVEREVENT\n"); WBEM_DATAPACKET_MULTITARGET_DELIVEREVENT UNALIGNED * pMultiTgtEvt = (WBEM_DATAPACKET_MULTITARGET_DELIVEREVENT UNALIGNED *)((BYTE*)pData + pData->dwSizeOfHeader); dprintf(" Header %08x dwDataSize %08x\n",pMultiTgtEvt->dwSizeOfHeader,pMultiTgtEvt->dwDataSize); WBEM_DATAPACKET_OBJECT_ARRAY UNALIGNED * pArrayPacket = (WBEM_DATAPACKET_OBJECT_ARRAY UNALIGNED *)((BYTE * )pMultiTgtEvt+pMultiTgtEvt->dwSizeOfHeader); dprintf(" Header %08x Size %08x NumObj %08x\n", pArrayPacket->dwSizeOfHeader, pArrayPacket->dwDataSize, pArrayPacket->dwNumObjects); WBEM_DATAPACKET_OBJECT_HEADER UNALIGNED * pObjHeader = (WBEM_DATAPACKET_OBJECT_HEADER UNALIGNED *)((BYTE*)pArrayPacket+pArrayPacket->dwSizeOfHeader); dprintf(" Header %08x dwSizeOfData %08x bObjectType ",pObjHeader->dwSizeOfHeader,pObjHeader->dwSizeOfData); switch(pObjHeader->bObjectType) { case WBEMOBJECT_NONE: dprintf("WBEMOBJECT_NONE\n"); break; case WBEMOBJECT_CLASS_FULL: dprintf("WBEMOBJECT_CLASS_FULL\n"); break; case WBEMOBJECT_INSTANCE_FULL: dprintf("WBEMOBJECT_INSTANCE_FULL\n"); break; case WBEMOBJECT_INSTANCE_NOCLASS: dprintf("WBEMOBJECT_INSTANCE_NOCLASS\n"); break; }; } break; case WBEM_DATAPACKETTYPE_LAST: dprintf("WBEM_DATAPACKETTYPE_LAST\n"); break; } } else { dprintf("RM %p\n",Addr); } } else { dprintf("unable to resolve %s\n",args); } }
35.579091
231
0.581624
[ "object" ]