text
stringlengths
54
60.6k
<commit_before>#include <efsw/FileWatcherWin32.hpp> #include <efsw/FileSystem.hpp> #include <efsw/System.hpp> #include <efsw/String.hpp> #if EFSW_PLATFORM == EFSW_PLATFORM_WIN32 namespace efsw { FileWatcherWin32::FileWatcherWin32( FileWatcher * parent ) : FileWatcherImpl( parent ), mLastWatchID(0), mThread( NULL ) { mInitOK = true; } FileWatcherWin32::~FileWatcherWin32() { WatchVector::iterator iter = mWatches.begin(); mWatchesLock.lock(); for(; iter != mWatches.end(); ++iter) { DestroyWatch((*iter)); } mWatchesLock.unlock(); mHandles.clear(); mWatches.clear(); mInitOK = false; efSAFE_DELETE( mThread ); } WatchID FileWatcherWin32::addWatch(const std::string& directory, FileWatchListener* watcher, bool recursive) { std::string dir( directory ); FileInfo fi( dir ); if ( !fi.isDirectory() ) { return Errors::Log::createLastError( Errors::FileNotFound, dir ); } else if ( !fi.isReadable() ) { return Errors::Log::createLastError( Errors::FileNotReadable, dir ); } FileSystem::dirAddSlashAtEnd( dir ); WatchID watchid = ++mLastWatchID; WatcherStructWin32 * watch = CreateWatch( String::fromUtf8( dir ).toWideString().c_str(), recursive, FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME ); if( NULL == watch ) { return Errors::Log::createLastError( Errors::FileNotFound, dir ); } if ( pathInWatches( dir ) ) { return Errors::Log::createLastError( Errors::FileRepeated, dir ); } // Add the handle to the handles vector watch->Watch->ID = watchid; watch->Watch->Watch = this; watch->Watch->Listener = watcher; watch->Watch->DirName = new char[dir.length()+1]; strcpy(watch->Watch->DirName, dir.c_str()); mWatchesLock.lock(); mHandles.push_back( watch->Watch->DirHandle ); mWatches.push_back( watch ); mWatchesLock.unlock(); return watchid; } void FileWatcherWin32::removeWatch(const std::string& directory) { mWatchesLock.lock(); WatchVector::iterator iter = mWatches.begin(); for(; iter != mWatches.end(); ++iter) { if(directory == (*iter)->Watch->DirName) { removeWatch((*iter)->Watch->ID); return; } } mWatchesLock.unlock(); } void FileWatcherWin32::removeWatch(WatchID watchid) { mWatchesLock.lock(); WatchVector::iterator iter = mWatches.begin(); WatcherStructWin32* watch = NULL; for(; iter != mWatches.end(); ++iter) { // Find the watch ID if ( (*iter)->Watch->ID == watchid ) { watch = (*iter); mWatches.erase( iter ); // Remove handle from the handle vector HandleVector::iterator it = mHandles.begin(); for ( ; it != mHandles.end(); it++ ) { if ( watch->Watch->DirHandle == (*it) ) { mHandles.erase( it ); break; } } DestroyWatch(watch); break; } } mWatchesLock.unlock(); } void FileWatcherWin32::watch() { if ( NULL == mThread ) { mThread = new Thread( &FileWatcherWin32::run, this ); mThread->launch(); } } void FileWatcherWin32::run() { if ( mHandles.empty() ) { return; } do { if ( !mHandles.empty() ) { mWatchesLock.lock(); for ( std::size_t i = 0; i < mWatches.size(); i++ ) { WatcherStructWin32 * watch = mWatches[ i ]; // First ensure that the handle is the same, this means that the watch was not removed. if ( HasOverlappedIoCompleted( &watch->Overlapped ) && mHandles[ i ] == watch->Watch->DirHandle ) { DWORD bytes; if ( GetOverlappedResult( watch->Watch->DirHandle, &watch->Overlapped, &bytes, FALSE ) ) { WatchCallback( ERROR_SUCCESS, bytes, &watch->Overlapped ); } } } mWatchesLock.unlock(); System::sleep( 10 ); } else { // Wait for a new handle to be added System::sleep( 10 ); } } while ( mInitOK ); } void FileWatcherWin32::handleAction(Watcher* watch, const std::string& filename, unsigned long action, std::string oldFilename) { Action fwAction; switch(action) { case FILE_ACTION_RENAMED_OLD_NAME: watch->OldFileName = filename; return; case FILE_ACTION_ADDED: fwAction = Actions::Add; break; case FILE_ACTION_RENAMED_NEW_NAME: { fwAction = Actions::Moved; std::string fpath( watch->Directory + filename ); // Update the directory path if ( watch->Recursive && FileSystem::isDirectory( fpath ) ) { // Update the new directory path std::string opath( watch->Directory + watch->OldFileName ); FileSystem::dirAddSlashAtEnd( opath ); FileSystem::dirAddSlashAtEnd( fpath ); for ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ ) { if ( (*it)->Watch->Directory == opath ) { (*it)->Watch->Directory = fpath; break; } } } watch->Listener->handleFileAction(watch->ID, static_cast<WatcherWin32*>( watch )->DirName, filename, fwAction, watch->OldFileName); return; } case FILE_ACTION_REMOVED: fwAction = Actions::Delete; break; case FILE_ACTION_MODIFIED: fwAction = Actions::Modified; break; }; watch->Listener->handleFileAction(watch->ID, static_cast<WatcherWin32*>( watch )->DirName, filename, fwAction); } std::list<std::string> FileWatcherWin32::directories() { std::list<std::string> dirs; mWatchesLock.lock(); for ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ ) { dirs.push_back( std::string( (*it)->Watch->DirName ) ); } mWatchesLock.unlock(); return dirs; } bool FileWatcherWin32::pathInWatches( const std::string& path ) { for ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ ) { if ( (*it)->Watch->DirName == path ) { return true; } } return false; } } #endif <commit_msg>Fix incorrect mutex unlock in FileWatcherWin32 destructor.<commit_after>#include <efsw/FileWatcherWin32.hpp> #include <efsw/FileSystem.hpp> #include <efsw/System.hpp> #include <efsw/String.hpp> #if EFSW_PLATFORM == EFSW_PLATFORM_WIN32 namespace efsw { FileWatcherWin32::FileWatcherWin32( FileWatcher * parent ) : FileWatcherImpl( parent ), mLastWatchID(0), mThread( NULL ) { mInitOK = true; } FileWatcherWin32::~FileWatcherWin32() { WatchVector::iterator iter = mWatches.begin(); mWatchesLock.lock(); for(; iter != mWatches.end(); ++iter) { DestroyWatch((*iter)); } mHandles.clear(); mWatches.clear(); mInitOK = false; mWatchesLock.unlock(); efSAFE_DELETE( mThread ); } WatchID FileWatcherWin32::addWatch(const std::string& directory, FileWatchListener* watcher, bool recursive) { std::string dir( directory ); FileInfo fi( dir ); if ( !fi.isDirectory() ) { return Errors::Log::createLastError( Errors::FileNotFound, dir ); } else if ( !fi.isReadable() ) { return Errors::Log::createLastError( Errors::FileNotReadable, dir ); } FileSystem::dirAddSlashAtEnd( dir ); WatchID watchid = ++mLastWatchID; WatcherStructWin32 * watch = CreateWatch( String::fromUtf8( dir ).toWideString().c_str(), recursive, FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME ); if( NULL == watch ) { return Errors::Log::createLastError( Errors::FileNotFound, dir ); } if ( pathInWatches( dir ) ) { return Errors::Log::createLastError( Errors::FileRepeated, dir ); } // Add the handle to the handles vector watch->Watch->ID = watchid; watch->Watch->Watch = this; watch->Watch->Listener = watcher; watch->Watch->DirName = new char[dir.length()+1]; strcpy(watch->Watch->DirName, dir.c_str()); mWatchesLock.lock(); mHandles.push_back( watch->Watch->DirHandle ); mWatches.push_back( watch ); mWatchesLock.unlock(); return watchid; } void FileWatcherWin32::removeWatch(const std::string& directory) { mWatchesLock.lock(); WatchVector::iterator iter = mWatches.begin(); for(; iter != mWatches.end(); ++iter) { if(directory == (*iter)->Watch->DirName) { removeWatch((*iter)->Watch->ID); return; } } mWatchesLock.unlock(); } void FileWatcherWin32::removeWatch(WatchID watchid) { mWatchesLock.lock(); WatchVector::iterator iter = mWatches.begin(); WatcherStructWin32* watch = NULL; for(; iter != mWatches.end(); ++iter) { // Find the watch ID if ( (*iter)->Watch->ID == watchid ) { watch = (*iter); mWatches.erase( iter ); // Remove handle from the handle vector HandleVector::iterator it = mHandles.begin(); for ( ; it != mHandles.end(); it++ ) { if ( watch->Watch->DirHandle == (*it) ) { mHandles.erase( it ); break; } } DestroyWatch(watch); break; } } mWatchesLock.unlock(); } void FileWatcherWin32::watch() { if ( NULL == mThread ) { mThread = new Thread( &FileWatcherWin32::run, this ); mThread->launch(); } } void FileWatcherWin32::run() { if ( mHandles.empty() ) { return; } do { if ( !mHandles.empty() ) { mWatchesLock.lock(); for ( std::size_t i = 0; i < mWatches.size(); i++ ) { WatcherStructWin32 * watch = mWatches[ i ]; // First ensure that the handle is the same, this means that the watch was not removed. if ( HasOverlappedIoCompleted( &watch->Overlapped ) && mHandles[ i ] == watch->Watch->DirHandle ) { DWORD bytes; if ( GetOverlappedResult( watch->Watch->DirHandle, &watch->Overlapped, &bytes, FALSE ) ) { WatchCallback( ERROR_SUCCESS, bytes, &watch->Overlapped ); } } } mWatchesLock.unlock(); if ( mInitOK ) { System::sleep( 10 ); } } else { // Wait for a new handle to be added System::sleep( 10 ); } } while ( mInitOK ); } void FileWatcherWin32::handleAction(Watcher* watch, const std::string& filename, unsigned long action, std::string oldFilename) { Action fwAction; switch(action) { case FILE_ACTION_RENAMED_OLD_NAME: watch->OldFileName = filename; return; case FILE_ACTION_ADDED: fwAction = Actions::Add; break; case FILE_ACTION_RENAMED_NEW_NAME: { fwAction = Actions::Moved; std::string fpath( watch->Directory + filename ); // Update the directory path if ( watch->Recursive && FileSystem::isDirectory( fpath ) ) { // Update the new directory path std::string opath( watch->Directory + watch->OldFileName ); FileSystem::dirAddSlashAtEnd( opath ); FileSystem::dirAddSlashAtEnd( fpath ); for ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ ) { if ( (*it)->Watch->Directory == opath ) { (*it)->Watch->Directory = fpath; break; } } } watch->Listener->handleFileAction(watch->ID, static_cast<WatcherWin32*>( watch )->DirName, filename, fwAction, watch->OldFileName); return; } case FILE_ACTION_REMOVED: fwAction = Actions::Delete; break; case FILE_ACTION_MODIFIED: fwAction = Actions::Modified; break; }; watch->Listener->handleFileAction(watch->ID, static_cast<WatcherWin32*>( watch )->DirName, filename, fwAction); } std::list<std::string> FileWatcherWin32::directories() { std::list<std::string> dirs; mWatchesLock.lock(); for ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ ) { dirs.push_back( std::string( (*it)->Watch->DirName ) ); } mWatchesLock.unlock(); return dirs; } bool FileWatcherWin32::pathInWatches( const std::string& path ) { for ( WatchVector::iterator it = mWatches.begin(); it != mWatches.end(); it++ ) { if ( (*it)->Watch->DirName == path ) { return true; } } return false; } } #endif <|endoftext|>
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <sstream> #include <string> #include "base/debug_util.h" #include "base/logging.h" #include "testing/gtest/include/gtest/gtest.h" // Note: On Linux, this test currently only fully works on Debug builds. // See comments in the #ifdef soup if you intend to change this. // TODO(jar): BUG: 32070: Test is disabled... should be enabled. TEST(StackTrace, DISABLED_OutputToStream) { StackTrace trace; // Dump the trace into a string. std::ostringstream os; trace.OutputToStream(&os); std::string backtrace_message = os.str(); #if defined(OS_POSIX) && !defined(OS_MACOSX) && NDEBUG // Stack traces require an extra data table that bloats our binaries, // so they're turned off for release builds. We stop the test here, // at least letting us verify that the calls don't crash. return; #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && NDEBUG size_t frames_found = 0; trace.Addresses(&frames_found); ASSERT_GE(frames_found, 5u) << "No stack frames found. Skipping rest of test."; // Check if the output has symbol initialization warning. If it does, fail. ASSERT_EQ(backtrace_message.find("Dumping unresolved backtrace"), std::string::npos) << "Unable to resolve symbols. Skipping rest of test."; #if defined(OS_MACOSX) #if 0 // Disabled due to -fvisibility=hidden in build config. // Symbol resolution via the backtrace_symbol function does not work well // in OS X. // See this thread: // // http://lists.apple.com/archives/darwin-dev/2009/Mar/msg00111.html // // Just check instead that we find our way back to the "start" symbol // which should be the first symbol in the trace. // // TODO(port): Find a more reliable way to resolve symbols. // Expect to at least find main. EXPECT_TRUE(backtrace_message.find("start") != std::string::npos) << "Expected to find start in backtrace:\n" << backtrace_message; #endif #elif defined(__GLIBCXX__) // This branch is for gcc-compiled code, but not Mac due to the // above #if. // Expect a demangled symbol. EXPECT_TRUE(backtrace_message.find("testing::Test::Run()") != std::string::npos) << "Expected a demangled symbol in backtrace:\n" << backtrace_message; #elif 0 // This is the fall-through case; it used to cover Windows. // But it's disabled because of varying buildbot configs; // some lack symbols. // Expect to at least find main. EXPECT_TRUE(backtrace_message.find("main") != std::string::npos) << "Expected to find main in backtrace:\n" << backtrace_message; #if defined(OS_WIN) // MSVC doesn't allow the use of C99's __func__ within C++, so we fake it with // MSVC's __FUNCTION__ macro. #define __func__ __FUNCTION__ #endif // Expect to find this function as well. // Note: This will fail if not linked with -rdynamic (aka -export_dynamic) EXPECT_TRUE(backtrace_message.find(__func__) != std::string::npos) << "Expected to find " << __func__ << " in backtrace:\n" << backtrace_message; #endif // define(OS_MACOSX) } // The test is used for manual testing (i.e. see the raw output). // To run the test use the flags: // --gtest_filter='*DebugOutputToStream' --gtest_also_run_disabled_tests TEST(StackTrace, DISABLED_DebugOutputToStream) { StackTrace trace; std::ostringstream os; trace.OutputToStream(&os); LOG(INFO) << os.str(); } // The test is used for manual testing. See the comment above. TEST(StackTrace, DISABLED_DebugPrintBacktrace) { StackTrace().PrintBacktrace(); } <commit_msg>TTF: Re-enable to tests used only for manual testing. We still want coverage from those tests. Mark StackTrace.OutputToStream as flaky.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <sstream> #include <string> #include "base/debug_util.h" #include "base/logging.h" #include "testing/gtest/include/gtest/gtest.h" // Note: On Linux, this test currently only fully works on Debug builds. // See comments in the #ifdef soup if you intend to change this. // Flaky, crbug.com/32070. TEST(StackTrace, FLAKY_OutputToStream) { StackTrace trace; // Dump the trace into a string. std::ostringstream os; trace.OutputToStream(&os); std::string backtrace_message = os.str(); #if defined(OS_POSIX) && !defined(OS_MACOSX) && NDEBUG // Stack traces require an extra data table that bloats our binaries, // so they're turned off for release builds. We stop the test here, // at least letting us verify that the calls don't crash. return; #endif // defined(OS_POSIX) && !defined(OS_MACOSX) && NDEBUG size_t frames_found = 0; trace.Addresses(&frames_found); ASSERT_GE(frames_found, 5u) << "No stack frames found. Skipping rest of test."; // Check if the output has symbol initialization warning. If it does, fail. ASSERT_EQ(backtrace_message.find("Dumping unresolved backtrace"), std::string::npos) << "Unable to resolve symbols. Skipping rest of test."; #if defined(OS_MACOSX) #if 0 // Disabled due to -fvisibility=hidden in build config. // Symbol resolution via the backtrace_symbol function does not work well // in OS X. // See this thread: // // http://lists.apple.com/archives/darwin-dev/2009/Mar/msg00111.html // // Just check instead that we find our way back to the "start" symbol // which should be the first symbol in the trace. // // TODO(port): Find a more reliable way to resolve symbols. // Expect to at least find main. EXPECT_TRUE(backtrace_message.find("start") != std::string::npos) << "Expected to find start in backtrace:\n" << backtrace_message; #endif #elif defined(__GLIBCXX__) // This branch is for gcc-compiled code, but not Mac due to the // above #if. // Expect a demangled symbol. EXPECT_TRUE(backtrace_message.find("testing::Test::Run()") != std::string::npos) << "Expected a demangled symbol in backtrace:\n" << backtrace_message; #elif 0 // This is the fall-through case; it used to cover Windows. // But it's disabled because of varying buildbot configs; // some lack symbols. // Expect to at least find main. EXPECT_TRUE(backtrace_message.find("main") != std::string::npos) << "Expected to find main in backtrace:\n" << backtrace_message; #if defined(OS_WIN) // MSVC doesn't allow the use of C99's __func__ within C++, so we fake it with // MSVC's __FUNCTION__ macro. #define __func__ __FUNCTION__ #endif // Expect to find this function as well. // Note: This will fail if not linked with -rdynamic (aka -export_dynamic) EXPECT_TRUE(backtrace_message.find(__func__) != std::string::npos) << "Expected to find " << __func__ << " in backtrace:\n" << backtrace_message; #endif // define(OS_MACOSX) } // The test is used for manual testing, e.g., to see the raw output. TEST(StackTrace, DebugOutputToStream) { StackTrace trace; std::ostringstream os; trace.OutputToStream(&os); LOG(INFO) << os.str(); } // The test is used for manual testing, e.g., to see the raw output. TEST(StackTrace, DebugPrintBacktrace) { StackTrace().PrintBacktrace(); } <|endoftext|>
<commit_before>// Copyright 2014 Toggl Desktop developers. #include "./window_change_recorder.h" #include <sstream> #include "./get_focused_window.h" #include "./timeline_event.h" #include "Poco/Thread.h" #include "Poco/NotificationCenter.h" #include "Poco/Logger.h" namespace kopsik { bool WindowChangeRecorder::hasWindowChanged( const std::string &title, const std::string &filename) const { return ((title != last_title_) || (filename != last_filename_)); } bool WindowChangeRecorder::hasIdlenessChanged(const bool &idle) const { return last_idle_ != idle; } void WindowChangeRecorder::inspectFocusedWindow() { std::string title(""); std::string filename(""); bool idle(false); int err = getFocusedWindowInfo(&title, &filename, &idle); if (err != 0) { std::stringstream ss; ss << "Failed to get focused window info, error code: " << err; Poco::Logger::get("WindowChangeRecorder").error(ss.str()); return; } time_t now; time(&now); if (!hasIdlenessChanged(idle) && !hasWindowChanged(title, filename)) { return; } // We actually record the *previous* event. Meaning, when // you have "terminal" open and then switch to "skype", // then "terminal" gets recorded here: if (last_event_started_at_ > 0) { time_t time_delta = now - last_event_started_at_; // if window was focussed at least X seconds, save it to timeline if (time_delta >= kWindowFocusThresholdSeconds) { TimelineEvent event; event.start_time = last_event_started_at_; event.end_time = now; event.filename = last_filename_; event.title = last_title_; event.idle = last_idle_; TimelineEventNotification notification(event); Poco::AutoPtr<TimelineEventNotification> ptr(&notification); Poco::NotificationCenter::defaultCenter().postNotification(ptr); } } last_title_ = title; last_filename_ = filename; last_event_started_at_ = now; } void WindowChangeRecorder::recordLoop() { while (!recording_.isStopped()) { inspectFocusedWindow(); Poco::Thread::sleep(kWindowChangeRecordingIntervalMillis); } } error WindowChangeRecorder::Shutdown() { try { if (recording_.isRunning()) { recording_.stop(); recording_.wait(); } } catch(const Poco::Exception& exc) { return exc.displayText(); } catch(const std::exception& ex) { return ex.what(); } catch(const std::string& ex) { return ex; } return noError; } } // namespace kopsik <commit_msg>set last idle state in timeline recorder (lib)<commit_after>// Copyright 2014 Toggl Desktop developers. #include "./window_change_recorder.h" #include <sstream> #include "./get_focused_window.h" #include "./timeline_event.h" #include "Poco/Thread.h" #include "Poco/NotificationCenter.h" #include "Poco/Logger.h" namespace kopsik { bool WindowChangeRecorder::hasWindowChanged( const std::string &title, const std::string &filename) const { return ((title != last_title_) || (filename != last_filename_)); } bool WindowChangeRecorder::hasIdlenessChanged(const bool &idle) const { return last_idle_ != idle; } void WindowChangeRecorder::inspectFocusedWindow() { std::string title(""); std::string filename(""); bool idle(false); int err = getFocusedWindowInfo(&title, &filename, &idle); if (err != 0) { std::stringstream ss; ss << "Failed to get focused window info, error code: " << err; Poco::Logger::get("WindowChangeRecorder").error(ss.str()); return; } time_t now; time(&now); if (!hasIdlenessChanged(idle) && !hasWindowChanged(title, filename)) { return; } // We actually record the *previous* event. Meaning, when // you have "terminal" open and then switch to "skype", // then "terminal" gets recorded here: if (last_event_started_at_ > 0) { time_t time_delta = now - last_event_started_at_; // if window was focussed at least X seconds, save it to timeline if (time_delta >= kWindowFocusThresholdSeconds) { TimelineEvent event; event.start_time = last_event_started_at_; event.end_time = now; event.filename = last_filename_; event.title = last_title_; event.idle = last_idle_; TimelineEventNotification notification(event); Poco::AutoPtr<TimelineEventNotification> ptr(&notification); Poco::NotificationCenter::defaultCenter().postNotification(ptr); } } last_title_ = title; last_filename_ = filename; last_idle_ = idle; last_event_started_at_ = now; } void WindowChangeRecorder::recordLoop() { while (!recording_.isStopped()) { inspectFocusedWindow(); Poco::Thread::sleep(kWindowChangeRecordingIntervalMillis); } } error WindowChangeRecorder::Shutdown() { try { if (recording_.isRunning()) { recording_.stop(); recording_.wait(); } } catch(const Poco::Exception& exc) { return exc.displayText(); } catch(const std::exception& ex) { return ex.what(); } catch(const std::string& ex) { return ex; } return noError; } } // namespace kopsik <|endoftext|>
<commit_before>#include <glib-object.h> #include <cstdio> #include <cstdlib> #include <QTimer> #include <QStringList> #include <QString> #include <QDebug> #include <QDir> #include <QCoreApplication> extern "C" { #include <ccnet/ccnet-client.h> } #include "utils/utils.h" #include "utils/process.h" #include "configurator.h" #include "seafile-applet.h" #include "daemon-mgr.h" namespace { const int kConnDaemonIntervalMilli = 1000; #if defined(Q_WS_WIN) const char *kCcnetDaemonExecutable = "ccnet.exe"; const char *kSeafileDaemonExecutable = "seaf-daemon.exe"; #else const char *kCcnetDaemonExecutable = "ccnet"; const char *kSeafileDaemonExecutable = "seaf-daemon"; #endif } // namespace DaemonManager::DaemonManager() : ccnet_daemon_(0), seaf_daemon_(0), sync_client_(0) { conn_daemon_timer_ = new QTimer(this); connect(conn_daemon_timer_, SIGNAL(timeout()), this, SLOT(tryConnCcnet())); shutdown_process (kCcnetDaemonExecutable); system_shut_down_ = false; connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(systemShutDown())); } void DaemonManager::startCcnetDaemon() { sync_client_ = ccnet_client_new(); const QString config_dir = seafApplet->configurator()->ccnetDir(); const QByteArray path = config_dir.toUtf8(); if (ccnet_client_load_confdir(sync_client_, path.data()) < 0) { seafApplet->errorAndExit(tr("failed to load ccnet config dir %1").arg(config_dir)); } ccnet_daemon_ = new QProcess(this); connect(ccnet_daemon_, SIGNAL(started()), this, SLOT(onCcnetDaemonStarted())); connect(ccnet_daemon_, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onCcnetDaemonExited())); QStringList args; args << "-c" << config_dir; ccnet_daemon_->start(RESOURCE_PATH(kCcnetDaemonExecutable), args); qDebug() << "starting ccnet: " << args; } void DaemonManager::startSeafileDaemon() { const QString config_dir = seafApplet->configurator()->ccnetDir(); const QString seafile_dir = seafApplet->configurator()->seafileDir(); const QString worktree_dir = seafApplet->configurator()->worktreeDir(); seaf_daemon_ = new QProcess(this); connect(seaf_daemon_, SIGNAL(started()), this, SLOT(onSeafDaemonStarted())); connect(seaf_daemon_, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onSeafDaemonExited())); QStringList args; args << "-c" << config_dir << "-d" << seafile_dir << "-w" << worktree_dir; seaf_daemon_->start(RESOURCE_PATH(kSeafileDaemonExecutable), args); qDebug() << "starting seaf-daemon: " << args; } void DaemonManager::onCcnetDaemonStarted() { conn_daemon_timer_->start(kConnDaemonIntervalMilli); } void DaemonManager::systemShutDown() { system_shut_down_ = true; } void DaemonManager::onSeafDaemonStarted() { qDebug("seafile daemon is now running"); emit daemonStarted(); } void DaemonManager::onCcnetDaemonExited() { if (!system_shut_down_) { seafApplet->errorAndExit(tr("ccnet daemon has exited abnormally")); } } void DaemonManager::onSeafDaemonExited() { if (!system_shut_down_) { seafApplet->errorAndExit(tr("seafile daemon has exited abnormally")); } } void DaemonManager::stopAll() { qDebug("[Daemon Mgr] stopping ccnet/seafile daemon"); if (seaf_daemon_) seaf_daemon_->kill(); if (ccnet_daemon_) ccnet_daemon_->kill(); } void DaemonManager::tryConnCcnet() { qDebug("trying to connect to ccnet daemon...\n"); if (ccnet_client_connect_daemon(sync_client_, CCNET_CLIENT_SYNC) < 0) { return; } else { conn_daemon_timer_->stop(); qDebug("connected to ccnet daemon\n"); startSeafileDaemon(); } } <commit_msg>remove "ccnet/seaf-daemon exit abnormally" message<commit_after>#include <glib-object.h> #include <cstdio> #include <cstdlib> #include <QTimer> #include <QStringList> #include <QString> #include <QDebug> #include <QDir> #include <QCoreApplication> extern "C" { #include <ccnet/ccnet-client.h> } #include "utils/utils.h" #include "utils/process.h" #include "configurator.h" #include "seafile-applet.h" #include "daemon-mgr.h" namespace { const int kConnDaemonIntervalMilli = 1000; #if defined(Q_WS_WIN) const char *kCcnetDaemonExecutable = "ccnet.exe"; const char *kSeafileDaemonExecutable = "seaf-daemon.exe"; #else const char *kCcnetDaemonExecutable = "ccnet"; const char *kSeafileDaemonExecutable = "seaf-daemon"; #endif } // namespace DaemonManager::DaemonManager() : ccnet_daemon_(0), seaf_daemon_(0), sync_client_(0) { conn_daemon_timer_ = new QTimer(this); connect(conn_daemon_timer_, SIGNAL(timeout()), this, SLOT(tryConnCcnet())); shutdown_process (kCcnetDaemonExecutable); system_shut_down_ = false; connect(qApp, SIGNAL(aboutToQuit()), this, SLOT(systemShutDown())); } void DaemonManager::startCcnetDaemon() { sync_client_ = ccnet_client_new(); const QString config_dir = seafApplet->configurator()->ccnetDir(); const QByteArray path = config_dir.toUtf8(); if (ccnet_client_load_confdir(sync_client_, path.data()) < 0) { seafApplet->errorAndExit(tr("failed to load ccnet config dir %1").arg(config_dir)); } ccnet_daemon_ = new QProcess(this); connect(ccnet_daemon_, SIGNAL(started()), this, SLOT(onCcnetDaemonStarted())); connect(ccnet_daemon_, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onCcnetDaemonExited())); QStringList args; args << "-c" << config_dir; ccnet_daemon_->start(RESOURCE_PATH(kCcnetDaemonExecutable), args); qDebug() << "starting ccnet: " << args; } void DaemonManager::startSeafileDaemon() { const QString config_dir = seafApplet->configurator()->ccnetDir(); const QString seafile_dir = seafApplet->configurator()->seafileDir(); const QString worktree_dir = seafApplet->configurator()->worktreeDir(); seaf_daemon_ = new QProcess(this); connect(seaf_daemon_, SIGNAL(started()), this, SLOT(onSeafDaemonStarted())); connect(seaf_daemon_, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onSeafDaemonExited())); QStringList args; args << "-c" << config_dir << "-d" << seafile_dir << "-w" << worktree_dir; seaf_daemon_->start(RESOURCE_PATH(kSeafileDaemonExecutable), args); qDebug() << "starting seaf-daemon: " << args; } void DaemonManager::onCcnetDaemonStarted() { conn_daemon_timer_->start(kConnDaemonIntervalMilli); } void DaemonManager::systemShutDown() { system_shut_down_ = true; } void DaemonManager::onSeafDaemonStarted() { qDebug("seafile daemon is now running"); emit daemonStarted(); } void DaemonManager::onCcnetDaemonExited() { // if (!system_shut_down_) { // seafApplet->errorAndExit(tr("ccnet daemon has exited abnormally")); // } } void DaemonManager::onSeafDaemonExited() { // if (!system_shut_down_) { // seafApplet->errorAndExit(tr("seafile daemon has exited abnormally")); // } } void DaemonManager::stopAll() { qDebug("[Daemon Mgr] stopping ccnet/seafile daemon"); if (seaf_daemon_) seaf_daemon_->kill(); if (ccnet_daemon_) ccnet_daemon_->kill(); } void DaemonManager::tryConnCcnet() { qDebug("trying to connect to ccnet daemon...\n"); if (ccnet_client_connect_daemon(sync_client_, CCNET_CLIENT_SYNC) < 0) { return; } else { conn_daemon_timer_->stop(); qDebug("connected to ccnet daemon\n"); startSeafileDaemon(); } } <|endoftext|>
<commit_before>#include "Generator/Generator.h" #include "Config.h" #include "Utils/Utils.h" #include <cstring> #include <cstdlib> #include <unistd.h> #include <sys/stat.h> #include <getopt.h> #include <cstdio> /*! dalec The main compiler executable, responsible for organising the arguments for Generator, running Generator, and assembling/linking the results together using the system's compiler. */ using namespace dale; static bool isEndingOn(const char *string, const char *ending) { size_t sl = strlen (string); size_t el = strlen (ending); return (sl >= el) && (strcmp (string + (sl - el), ending) == 0); } static bool appearsToBeLib(const char *str) { return isEndingOn(str, ".o") || isEndingOn(str, ".a"); } std::string joinWithPrefix(std::vector<const char*> strings, const std::string prefix, std::string buffer) { for (std::vector<const char*>::iterator b = strings.begin(), e = strings.end(); b != e; buffer += " " + prefix + " " + (*b++)); return buffer; } int main(int argc, char **argv) { srand(time(NULL) + getpid()); progname = argv[0]; std::vector<const char*> input_files; std::vector<const char*> input_link_files; std::vector<const char*> compile_libs; std::vector<const char*> run_libs; std::vector<const char*> include_paths; std::vector<const char*> run_paths; std::vector<const char*> bitcode_paths; std::vector<const char*> static_modules; std::vector<const char*> module_paths; const char *output_path_arg = NULL; const char *module_name = NULL; int produce = ASM; int optlevel = 0; int produce_set = 0; int no_linking = 0; int debug = 0; int no_dale_stdlib = 0; int no_stdlib = 0; int remove_macros = 0; int no_common = 0; int static_mods_all = 0; int found_sm = 0; int enable_cto = 0; int version = 0; int print_expansions = 0; int option_index = 0; int forced_remove_macros = 0; static const char *options = "M:m:O:a:I:L:l:o:s:b:cdrR"; static struct option long_options[] = { { "no-dale-stdlib", no_argument, &no_dale_stdlib, 1 }, { "no-common", no_argument, &no_common, 1 }, { "no-stdlib", no_argument, &no_stdlib, 1 }, { "static-modules", no_argument, &static_mods_all, 1 }, { "static-module", required_argument, &found_sm, 1 }, { "enable-cto", no_argument, &enable_cto, 1 }, { "version", no_argument, &version, 1 }, { "print-expansions", no_argument, &print_expansions, 1 }, { 0, 0, 0, 0 } }; for (int opt; (opt = getopt_long(argc, argv, options, long_options, &option_index)) != -1; ) { switch ((char) opt) { case 'o': { if (output_path_arg) { error("an output path has already been specified"); } output_path_arg = optarg; break; } case 'O': { optlevel = (optarg[0] - '0'); if ((optlevel < 0) || (optlevel > 4)) { error("invalid optimisation level"); } break; } case 's': { produce_set = true; const char *type = optarg; if (!strcmp(type, "as")) { produce = ASM; } else if (!strcmp(type, "ir")) { produce = IR; } else if (!strcmp(type, "bc")) { produce = BitCode; } else { error("unrecognised output option"); } break; } case 'd': debug = 1; break; case 'c': no_linking = 1; break; case 'r': remove_macros = 1; forced_remove_macros = 1; break; case 'R': remove_macros = 0; forced_remove_macros = 1; break; case 'I': include_paths.push_back(optarg); break; case 'a': compile_libs.push_back(optarg); break; case 'L': run_paths.push_back(optarg); break; case 'l': run_libs.push_back(optarg); break; case 'b': bitcode_paths.push_back(optarg); break; case 'M': module_paths.push_back(optarg); break; case 'm': module_name = optarg; break; }; if (found_sm) { found_sm = 0; static_modules.push_back(optarg); } } if (version) { printf("%d.%d\n", DALE_VERSION_MAJOR, DALE_VERSION_MINOR); exit(0); } /* If the user wants an executable and has not specified either * way with respect to removing macros, then remove macros. */ if (!no_linking && !produce_set && !forced_remove_macros) { remove_macros = 1; } /* Every argument after the options is treated as an input file. * Input files that end with .o or .a should go straight to the * linker. */ while (optind != argc) { const char *input_file = argv [optind ++]; (appearsToBeLib(input_file) ? input_link_files : input_files) .push_back(input_file); } if (input_files.empty()) { error("no input files"); } /* Set output_path. */ std::string output_path; if (output_path_arg) { /* Is given. */ output_path = output_path_arg; } else { /* Otherwise, construct it. */ output_path = input_files[0]; if (no_linking) { output_path += ".o"; } else if (produce_set) { /* .unknown should never be reached. */ output_path += ((produce == IR) ? ".ll" : (produce == ASM) ? ".s" : (produce == BitCode) ? ".bc" : ".unknown" ); } else { /* Overwrite what was there. */ output_path = "a.out"; } } /* Generate an intermediate file, to be compiled and linked later * with the system compiler, by building the executable in memory * and then exporting it into the requested intermediate format. */ std::vector<std::string> so_paths; Generator generator; std::string intermediate_output_path = output_path + (produce_set ? "" : ".s"); FILE *output_file = fopen(intermediate_output_path.c_str(), "w"); if (output_file == NULL) { error("unable to open %s for writing", intermediate_output_path.c_str(), true); } int res = generator.run(&input_files, &bitcode_paths, &compile_libs, &include_paths, &module_paths, &static_modules, module_name, debug, produce, optlevel, remove_macros, no_common, no_dale_stdlib, static_mods_all, enable_cto, print_expansions, &so_paths, output_file); if (!res) { exit(1); } res = fflush(output_file); if (res != 0) { error("unable to flush the intermediate output file", true); } if (produce_set) { /* We're done. */ exit(0); } /* Prepare the strings to sew the compile command with. */ std::string run_path_str = joinWithPrefix(run_paths, "-L", ""); std::string run_lib_str = joinWithPrefix(run_libs, "-l", ""); std::string rpath_str = strcmp(SYSTEM_NAME, "Darwin") ? "" : joinWithPrefix(module_paths, "-rpath", ""); std::string input_link_file_str = joinWithPrefix(input_link_files, " ", ""); for (std::vector<std::string>::iterator b = so_paths.begin(), e = so_paths.end(); b != e; input_link_file_str += " " + (*b++)); /* Compose the compiler/linker command and execute it. */ /* DALEC_CC_FLAGS is an undocumented environment variable that can * be used to provide additional flags to the compiler call here. * It is undocumented because this call may be removed in * the future in favour of using LLVM more directly. */ const char *aux = getenv("DALE_CC_FLAGS"); std::string compile_cmd = DALE_CC; if (no_stdlib) { compile_cmd += " --nostdlib"; } if (no_linking) { compile_cmd += " -c"; } else { compile_cmd += input_link_file_str + " -lm" + (strcmp(SYSTEM_NAME, "Darwin") ? " -Wl,--gc-sections" : ""); } compile_cmd += run_lib_str + run_path_str + rpath_str + " -o " + output_path + " " + intermediate_output_path; if (aux) { compile_cmd += " "; compile_cmd += aux; fprintf(stderr, "Going to run: %s\n", compile_cmd.c_str()); } int status = system(compile_cmd.c_str()); if (status != 0) { if (debug) { fprintf(stderr, "%s\n", compile_cmd.c_str()); } error(DALE_CC " failed"); } status = remove(intermediate_output_path.c_str()); if (status != 0) { if (debug) { fprintf(stderr, "%s\n", intermediate_output_path.c_str()); } error("unable to remove temporary file"); } return 0; } <commit_msg>[master] fix static modules problem<commit_after>#include "Generator/Generator.h" #include "Config.h" #include "Utils/Utils.h" #include <cstring> #include <cstdlib> #include <unistd.h> #include <sys/stat.h> #include <getopt.h> #include <cstdio> /*! dalec The main compiler executable, responsible for organising the arguments for Generator, running Generator, and assembling/linking the results together using the system's compiler. */ using namespace dale; static bool isEndingOn(const char *string, const char *ending) { size_t sl = strlen (string); size_t el = strlen (ending); return (sl >= el) && (strcmp (string + (sl - el), ending) == 0); } static bool appearsToBeLib(const char *str) { return isEndingOn(str, ".o") || isEndingOn(str, ".a"); } std::string joinWithPrefix(std::vector<const char*> strings, const std::string prefix, std::string buffer) { for (std::vector<const char*>::iterator b = strings.begin(), e = strings.end(); b != e; buffer += " " + prefix + " " + (*b++)); return buffer; } int main(int argc, char **argv) { srand(time(NULL) + getpid()); progname = argv[0]; std::vector<const char*> input_files; std::vector<const char*> input_link_files; std::vector<const char*> compile_libs; std::vector<const char*> run_libs; std::vector<const char*> include_paths; std::vector<const char*> run_paths; std::vector<const char*> bitcode_paths; std::vector<const char*> static_modules; std::vector<const char*> module_paths; const char *output_path_arg = NULL; const char *module_name = NULL; int produce = ASM; int optlevel = 0; int produce_set = 0; int no_linking = 0; int debug = 0; int no_dale_stdlib = 0; int no_stdlib = 0; int remove_macros = 0; int no_common = 0; int static_mods_all = 0; int found_sm = 0; int enable_cto = 0; int version = 0; int print_expansions = 0; int option_index = 0; int forced_remove_macros = 0; static const char *options = "M:m:O:a:I:L:l:o:s:b:cdrR"; static struct option long_options[] = { { "no-dale-stdlib", no_argument, &no_dale_stdlib, 1 }, { "no-common", no_argument, &no_common, 1 }, { "no-stdlib", no_argument, &no_stdlib, 1 }, { "static-modules", no_argument, &static_mods_all, 1 }, { "static-module", required_argument, &found_sm, 1 }, { "enable-cto", no_argument, &enable_cto, 1 }, { "version", no_argument, &version, 1 }, { "print-expansions", no_argument, &print_expansions, 1 }, { 0, 0, 0, 0 } }; for (int opt; (opt = getopt_long(argc, argv, options, long_options, &option_index)) != -1; ) { switch ((char) opt) { case 'o': { if (output_path_arg) { error("an output path has already been specified"); } output_path_arg = optarg; break; } case 'O': { optlevel = (optarg[0] - '0'); if ((optlevel < 0) || (optlevel > 4)) { error("invalid optimisation level"); } break; } case 's': { produce_set = true; const char *type = optarg; if (!strcmp(type, "as")) { produce = ASM; } else if (!strcmp(type, "ir")) { produce = IR; } else if (!strcmp(type, "bc")) { produce = BitCode; } else { error("unrecognised output option"); } break; } case 'd': debug = 1; break; case 'c': no_linking = 1; break; case 'r': remove_macros = 1; forced_remove_macros = 1; break; case 'R': remove_macros = 0; forced_remove_macros = 1; break; case 'I': include_paths.push_back(optarg); break; case 'a': compile_libs.push_back(optarg); break; case 'L': run_paths.push_back(optarg); break; case 'l': run_libs.push_back(optarg); break; case 'b': bitcode_paths.push_back(optarg); break; case 'M': module_paths.push_back(optarg); break; case 'm': module_name = optarg; break; }; if (found_sm) { found_sm = 0; static_modules.push_back(optarg); } } /* If any module has been loaded statically, add the runtime * libraries as compile-time libraries, so that LLVM is able to * resolve external symbols during compilation. (There is * probably a better way to do this.) */ if (static_modules.size() or static_mods_all) { for (std::vector<const char*>::iterator b = run_libs.begin(), e = run_libs.end(); b != e; ++b) { FILE *fp; char libname[256]; snprintf(libname, 256, "-l%s", *b); char command[256]; snprintf(command, 256, "ld -t %s 2>/dev/null", libname); fp = popen(command, "r"); if (fp == NULL) { fprintf(stderr, "Unable to resolve library path"); abort(); } char line[256]; while (fgets(line, sizeof(line) - 1, fp) != NULL) { if (!strncmp(line, libname, strlen(libname))) { char path[256]; char *start = strchr(line, '/'); char *end = strchr(line, ')'); strncpy(path, start, (end - start)); path[end - start] = '\0'; compile_libs.push_back(path); } } } } if (version) { printf("%d.%d\n", DALE_VERSION_MAJOR, DALE_VERSION_MINOR); exit(0); } /* If the user wants an executable and has not specified either * way with respect to removing macros, then remove macros. */ if (!no_linking && !produce_set && !forced_remove_macros) { remove_macros = 1; } /* Every argument after the options is treated as an input file. * Input files that end with .o or .a should go straight to the * linker. */ while (optind != argc) { const char *input_file = argv [optind ++]; (appearsToBeLib(input_file) ? input_link_files : input_files) .push_back(input_file); } if (input_files.empty()) { error("no input files"); } /* Set output_path. */ std::string output_path; if (output_path_arg) { /* Is given. */ output_path = output_path_arg; } else { /* Otherwise, construct it. */ output_path = input_files[0]; if (no_linking) { output_path += ".o"; } else if (produce_set) { /* .unknown should never be reached. */ output_path += ((produce == IR) ? ".ll" : (produce == ASM) ? ".s" : (produce == BitCode) ? ".bc" : ".unknown" ); } else { /* Overwrite what was there. */ output_path = "a.out"; } } /* Generate an intermediate file, to be compiled and linked later * with the system compiler, by building the executable in memory * and then exporting it into the requested intermediate format. */ std::vector<std::string> so_paths; Generator generator; std::string intermediate_output_path = output_path + (produce_set ? "" : ".s"); FILE *output_file = fopen(intermediate_output_path.c_str(), "w"); if (output_file == NULL) { error("unable to open %s for writing", intermediate_output_path.c_str(), true); } int res = generator.run(&input_files, &bitcode_paths, &compile_libs, &include_paths, &module_paths, &static_modules, module_name, debug, produce, optlevel, remove_macros, no_common, no_dale_stdlib, static_mods_all, enable_cto, print_expansions, &so_paths, output_file); if (!res) { exit(1); } res = fflush(output_file); if (res != 0) { error("unable to flush the intermediate output file", true); } if (produce_set) { /* We're done. */ exit(0); } /* Prepare the strings to sew the compile command with. */ std::string run_path_str = joinWithPrefix(run_paths, "-L", ""); std::string run_lib_str = joinWithPrefix(run_libs, "-l", ""); std::string rpath_str = strcmp(SYSTEM_NAME, "Darwin") ? "" : joinWithPrefix(module_paths, "-rpath", ""); std::string input_link_file_str = joinWithPrefix(input_link_files, " ", ""); for (std::vector<std::string>::iterator b = so_paths.begin(), e = so_paths.end(); b != e; input_link_file_str += " " + (*b++)); /* Compose the compiler/linker command and execute it. */ /* DALEC_CC_FLAGS is an undocumented environment variable that can * be used to provide additional flags to the compiler call here. * It is undocumented because this call may be removed in * the future in favour of using LLVM more directly. */ const char *aux = getenv("DALE_CC_FLAGS"); std::string compile_cmd = DALE_CC; if (no_stdlib) { compile_cmd += " --nostdlib"; } if (no_linking) { compile_cmd += " -c"; } else { compile_cmd += input_link_file_str + " -lm" + (strcmp(SYSTEM_NAME, "Darwin") ? " -Wl,--gc-sections" : ""); } compile_cmd += run_lib_str + run_path_str + rpath_str + " -o " + output_path + " " + intermediate_output_path; if (aux) { compile_cmd += " "; compile_cmd += aux; fprintf(stderr, "Going to run: %s\n", compile_cmd.c_str()); } int status = system(compile_cmd.c_str()); if (status != 0) { if (debug) { fprintf(stderr, "%s\n", compile_cmd.c_str()); } error(DALE_CC " failed"); } status = remove(intermediate_output_path.c_str()); if (status != 0) { if (debug) { fprintf(stderr, "%s\n", intermediate_output_path.c_str()); } error("unable to remove temporary file"); } return 0; } <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2014, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file Packet.hxx * * Defines a DCC Packet structure. * * @author Balazs Racz * @date 10 May 2014 */ #ifndef _DCC_PACKET_HXX_ #define _DCC_PACKET_HXX_ #include <stdint.h> #include <string.h> #include "dcc/Address.hxx" namespace dcc { /** Represents a command to be sent to the track driver. Most of the commands * are "send packet X", but there are some that are controlling the track * booster itself, such as "power off". */ struct Packet { /** Maximum number of payload bytes. */ static const unsigned MAX_PAYLOAD = 6; /** Send this speed step to emergency-stop the locomotive. */ static const unsigned EMERGENCY_STOP = 0xFFFF; /** Send this speed step to switch direction of the locomotive. Only used * for marklin-14-step speed commands. */ static const unsigned CHANGE_DIR = 0xFFFF; Packet() { clear(); } struct DCC_IDLE {}; Packet(DCC_IDLE i) { clear(); set_dcc_idle(); } void clear() { memset(this, 0, sizeof(*this)); } struct pkt_t { // Always 0. uint8_t is_pkt : 1; // 0: DCC packet, 1: motorola packet. uint8_t is_marklin : 1; // typically for DCC packets: // 1: do NOT append an EC byte to the end of the packet. uint8_t skip_ec : 1; // 1: send long preamble instead of packet. 0: send normal preamble and // pkt. uint8_t send_long_preamble : 1; // 1: wait for service mode ack and report it back to the host. uint8_t sense_ack : 1; // The packet will be sent 1 + rept_count times to the wire. default: 0. uint8_t rept_count : 2; uint8_t reserved : 1; }; struct cmd_t { // Always 1. uint8_t is_pkt : 1; // Command identifier. uint8_t cmd : 7; }; union { uint8_t header_raw_data; pkt_t packet_header; cmd_t command_header; }; /** Specifies the number of used payload bytes. */ uint8_t dlc; /** Packet payload bytes. */ uint8_t payload[MAX_PAYLOAD]; /** An opaque key used by the hardware driver to attribute feedback * information to the source of the packet. This key will be sent back in * the dcc::Feedback structure. If the key is non-zero it is guaranteed * that some feedback (maybe empty) will be sent back after the packet is * transmitted to the track. */ size_t feedback_key; /** Returns true if this is a packet, false if it is a command to the * track processor. */ bool IsPacket() { return packet_header.is_pkt; } void set_cmd(uint8_t cmd) { dlc = 0; HASSERT(cmd & 1); header_raw_data = cmd; } /** Initializes the packet structure for a regular DCC packet. */ void start_dcc_packet() { header_raw_data = 0; dlc = 0; } void add_dcc_address(DccShortAddress address); void add_dcc_address(DccLongAddress address); /** Adds a speed-and-direction command (dcc baseline command) ot the * packet. Speed is maximum 14. This should be called after * add_dcc_address. */ void add_dcc_speed14(bool is_fwd, bool light, unsigned speed); template <class A> void set_dcc_speed14(A a, bool is_fwd, bool light, unsigned speed) { add_dcc_address(a); add_dcc_speed14(is_fwd, light, speed); } /** Adds a speed-and-direction command (dcc baseline command) to the * packet. Speed is maximum 28. This should be called after * add_dcc_address. */ void add_dcc_speed28(bool is_fwd, unsigned speed); template <class A> void set_dcc_speed28(A a, bool is_fwd, unsigned speed) { add_dcc_address(a); add_dcc_speed28(is_fwd, speed); } /** Adds a speed-and-direction command (dcc extended command) for 128 speed * steps to the packet. Speed is maximum 126. This shoudl be called after * add_dcc_address. */ void add_dcc_speed128(bool is_fwd, unsigned speed); template <class A> void set_dcc_speed128(A a, bool is_fwd, unsigned speed) { add_dcc_address(a); add_dcc_speed128(is_fwd, speed); } /** Adds a DCC function group command to the packet. The lowest numbered * function is always at bit zero. */ void add_dcc_function0_4(unsigned values); void add_dcc_function5_8(unsigned values); void add_dcc_function9_12(unsigned values); void add_dcc_function13_20(unsigned values); void add_dcc_function21_28(unsigned values); /** Adds a DCC POM read single CV command and the xor byte. This should be * called after add_dcc_address. */ void add_dcc_pom_read1(unsigned cv_number); /** Adds a DCC POM write single CV command and the xor byte. This should be * called after add_dcc_address. */ void add_dcc_pom_read1(unsigned cv_number, uint8_t value); /** Appends one byte to the packet payload that represents the XOR checksum * for DCC. */ void add_dcc_checksum(); /** Creates a DCC idle packet. (Includes the checksum.) */ void set_dcc_idle(); /** Creates a DCC reset-all-decoders packet. (Includes the checksum.) */ void set_dcc_reset_all_decoders(); /** Sets the packet type to marklin-motorola. Initilizes the packet with 18 * zero bits. */ void start_mm_packet(); /** Sets the address and F0 bits of an MM packet to a specific loco * address. */ void add_mm_address(MMAddress address, bool light); /** Sets the packet to a 14-step MM speed-and-light packet. Max value of * speed is 14. A special value of speed == CHANGE_DIR will signal * direction change. */ void add_mm_speed(unsigned speed); /** Sets the packet to a direction-aware 14-step MM speed-and-light * packet. Max value of speed is 14. */ void add_mm_new_speed(bool is_fwd, unsigned speed); /** Creates a speed-and-fn packet for the new MM format. * @param fn_num is the function, valid values = 1..4 * @param is whether the funciton is on or off * @param speed is the speed step (0..14). If it is set to emergency stop, * then no function packet will be generated. */ void add_mm_new_fn(unsigned fn_num, bool value, unsigned speed); /** Shifts a MM packet to the second half of the packet buffer. After this * call another add_mm_speed call is valid, which will fill in the first * half of the double packet. */ void mm_shift(); private: /** Sets the speed bits of an MM packet. Clips speed to 15, avoids speed==1 * and returns the final speed step number. */ unsigned set_mm_speed_bits(unsigned speed); }; } // namespace dcc #endif // _DCC_PACKET_HXX_ <commit_msg>Fixes incorrectly named function.<commit_after>/** \copyright * Copyright (c) 2014, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file Packet.hxx * * Defines a DCC Packet structure. * * @author Balazs Racz * @date 10 May 2014 */ #ifndef _DCC_PACKET_HXX_ #define _DCC_PACKET_HXX_ #include <stdint.h> #include <string.h> #include "dcc/Address.hxx" namespace dcc { /** Represents a command to be sent to the track driver. Most of the commands * are "send packet X", but there are some that are controlling the track * booster itself, such as "power off". */ struct Packet { /** Maximum number of payload bytes. */ static const unsigned MAX_PAYLOAD = 6; /** Send this speed step to emergency-stop the locomotive. */ static const unsigned EMERGENCY_STOP = 0xFFFF; /** Send this speed step to switch direction of the locomotive. Only used * for marklin-14-step speed commands. */ static const unsigned CHANGE_DIR = 0xFFFF; Packet() { clear(); } struct DCC_IDLE {}; Packet(DCC_IDLE i) { clear(); set_dcc_idle(); } void clear() { memset(this, 0, sizeof(*this)); } struct pkt_t { // Always 0. uint8_t is_pkt : 1; // 0: DCC packet, 1: motorola packet. uint8_t is_marklin : 1; // typically for DCC packets: // 1: do NOT append an EC byte to the end of the packet. uint8_t skip_ec : 1; // 1: send long preamble instead of packet. 0: send normal preamble and // pkt. uint8_t send_long_preamble : 1; // 1: wait for service mode ack and report it back to the host. uint8_t sense_ack : 1; // The packet will be sent 1 + rept_count times to the wire. default: 0. uint8_t rept_count : 2; uint8_t reserved : 1; }; struct cmd_t { // Always 1. uint8_t is_pkt : 1; // Command identifier. uint8_t cmd : 7; }; union { uint8_t header_raw_data; pkt_t packet_header; cmd_t command_header; }; /** Specifies the number of used payload bytes. */ uint8_t dlc; /** Packet payload bytes. */ uint8_t payload[MAX_PAYLOAD]; /** An opaque key used by the hardware driver to attribute feedback * information to the source of the packet. This key will be sent back in * the dcc::Feedback structure. If the key is non-zero it is guaranteed * that some feedback (maybe empty) will be sent back after the packet is * transmitted to the track. */ size_t feedback_key; /** Returns true if this is a packet, false if it is a command to the * track processor. */ bool IsPacket() { return packet_header.is_pkt; } void set_cmd(uint8_t cmd) { dlc = 0; HASSERT(cmd & 1); header_raw_data = cmd; } /** Initializes the packet structure for a regular DCC packet. */ void start_dcc_packet() { header_raw_data = 0; dlc = 0; } void add_dcc_address(DccShortAddress address); void add_dcc_address(DccLongAddress address); /** Adds a speed-and-direction command (dcc baseline command) ot the * packet. Speed is maximum 14. This should be called after * add_dcc_address. */ void add_dcc_speed14(bool is_fwd, bool light, unsigned speed); template <class A> void set_dcc_speed14(A a, bool is_fwd, bool light, unsigned speed) { add_dcc_address(a); add_dcc_speed14(is_fwd, light, speed); } /** Adds a speed-and-direction command (dcc baseline command) to the * packet. Speed is maximum 28. This should be called after * add_dcc_address. */ void add_dcc_speed28(bool is_fwd, unsigned speed); template <class A> void set_dcc_speed28(A a, bool is_fwd, unsigned speed) { add_dcc_address(a); add_dcc_speed28(is_fwd, speed); } /** Adds a speed-and-direction command (dcc extended command) for 128 speed * steps to the packet. Speed is maximum 126. This shoudl be called after * add_dcc_address. */ void add_dcc_speed128(bool is_fwd, unsigned speed); template <class A> void set_dcc_speed128(A a, bool is_fwd, unsigned speed) { add_dcc_address(a); add_dcc_speed128(is_fwd, speed); } /** Adds a DCC function group command to the packet. The lowest numbered * function is always at bit zero. */ void add_dcc_function0_4(unsigned values); void add_dcc_function5_8(unsigned values); void add_dcc_function9_12(unsigned values); void add_dcc_function13_20(unsigned values); void add_dcc_function21_28(unsigned values); /** Adds a DCC POM read single CV command and the xor byte. This should be * called after add_dcc_address. */ void add_dcc_pom_read1(unsigned cv_number); /** Adds a DCC POM write single CV command and the xor byte. This should be * called after add_dcc_address. */ void add_dcc_pom_write1(unsigned cv_number, uint8_t value); /** Appends one byte to the packet payload that represents the XOR checksum * for DCC. */ void add_dcc_checksum(); /** Creates a DCC idle packet. (Includes the checksum.) */ void set_dcc_idle(); /** Creates a DCC reset-all-decoders packet. (Includes the checksum.) */ void set_dcc_reset_all_decoders(); /** Sets the packet type to marklin-motorola. Initilizes the packet with 18 * zero bits. */ void start_mm_packet(); /** Sets the address and F0 bits of an MM packet to a specific loco * address. */ void add_mm_address(MMAddress address, bool light); /** Sets the packet to a 14-step MM speed-and-light packet. Max value of * speed is 14. A special value of speed == CHANGE_DIR will signal * direction change. */ void add_mm_speed(unsigned speed); /** Sets the packet to a direction-aware 14-step MM speed-and-light * packet. Max value of speed is 14. */ void add_mm_new_speed(bool is_fwd, unsigned speed); /** Creates a speed-and-fn packet for the new MM format. * @param fn_num is the function, valid values = 1..4 * @param is whether the funciton is on or off * @param speed is the speed step (0..14). If it is set to emergency stop, * then no function packet will be generated. */ void add_mm_new_fn(unsigned fn_num, bool value, unsigned speed); /** Shifts a MM packet to the second half of the packet buffer. After this * call another add_mm_speed call is valid, which will fill in the first * half of the double packet. */ void mm_shift(); private: /** Sets the speed bits of an MM packet. Clips speed to 15, avoids speed==1 * and returns the final speed step number. */ unsigned set_mm_speed_bits(unsigned speed); }; } // namespace dcc #endif // _DCC_PACKET_HXX_ <|endoftext|>
<commit_before>#include "DELTAPAK.H" #include "CONTROL.H" #include "ITEMS.H" #include "OBJECTS.H" #include "SPECIFIC.H" #include "SPOTCAM.H" #include <stddef.h> struct CUTSEQ_ROUTINES cutseq_control_routines[45]; unsigned short crane_pistols_info[11]; unsigned short craneguard_pistols_info[7]; short admiral_chat_ranges_joby2[12]; short sergie_chat_ranges_joby2[8]; short lara_chat_ranges_joby3[6]; short lara_chat_ranges_joby4[10]; short admiral_chat_ranges_joby4[20]; unsigned short larson_pistols_info1[2]; short lara_chat_ranges_andrea1[4]; short larson_chat_ranges1[12]; short pierre_chat_ranges1[30]; short lara_chat_ranges_andrea2[32]; short larson_chat_ranges2[8]; short pierre_chat_ranges2[34]; short admiral_chat_ranges_joby5[18]; short sergie_chat_ranges_joby5[20]; short lara_chat_ranges_joby9[12]; short admiral_chat_ranges_joby9[36]; short lara_chat_ranges_joby10[12]; short admiral_chat_ranges_joby10[42]; unsigned short andrea3_pistols_info[5]; short lara_chat_ranges_andrea3[14]; short larson_chat_ranges3[14]; short lara_chat_ranges_andrea3b[12]; short larson_chat_ranges3b[4]; short priest_chat_ranges_andy7[32]; short lara_chat_ranges_andy7[14]; short lara_chat_ranges_joby7[10]; short lara_chat_ranges_andrea4[22]; short pierre_chat_ranges4[48]; int cuntercunter; char jobyfrigger; int cutrot; int GLOBAL_playing_cutseq; int cutseq_trig; int cutseq_num; unsigned char disable_horizon; char cutseq_busy_timeout; short frig_shadow_bbox[6]; int cut_seethrough; char lara_chat_cnt; char actor_chat_cnt; struct NEW_CUTSCENE* GLOBAL_cutme; int lastcamnum; int GLOBAL_cutseq_frame; int GLOBAL_numcutseq_frames; int GLOBAL_oldcamtype; struct PACKNODE* camera_pnodes; struct PACKNODE* actor_pnodes[10]; struct ITEM_INFO duff_item; int numnailed; char old_status_flags[32]; unsigned short old_status_flags2[32]; unsigned long cutseq_meshbits[10]; unsigned long cutseq_meshswapbits[10]; struct RESIDENT_THING cutseq_resident_addresses[47]; char* GLOBAL_resident_depack_buffers; int cutseq_malloc_used; char* cutseq_malloc_ptr; int cutseq_malloc_free; unsigned short old_lara_holster; short temp_rotation_buffer[160]; #define WORLD_UNITS_PER_SECTOR 1024 #define SECTOR_TO_WORLD(S) ((S) > (0) ? ((S * WORLD_UNITS_PER_SECTOR) + (WORLD_UNITS_PER_SECTOR / 2)) : (0)) void trigger_title_spotcam(int num)//32904, 32D9C { struct ITEM_INFO* item;//v0 int s2 = num; jobyfrigger = 0; int v0 = 4; if (num == 1)//Church seq { //Man holding umbrella at church area (TITLE.TRC) item = ResetCutanimate(ANIMATING10); item->pos.x_pos = SECTOR_TO_WORLD(58); item->pos.y_pos = SECTOR_TO_WORLD(0); item->pos.z_pos = SECTOR_TO_WORLD(41); item->room_number = 0; //Female walking with man holding umbrella, church area (TITLE.TRC) item = ResetCutanimate(ANIMATING11); item->pos.x_pos = SECTOR_TO_WORLD(58); item->pos.y_pos = SECTOR_TO_WORLD(0); item->pos.z_pos = SECTOR_TO_WORLD(41); item->room_number = 0; v0 = 2; if (num == 1) { int a0 = 83; int a1 = 0; //S_CDPlay(short track /*$s0*/, int mode /*$s1*/); if (s2 == 2)//0x32EB0(r) { S_Warn("[trigger_title_spotcam] - Unimplemented condition!\n"); }//0x32EC8(r) if (s2 == 3)//0x32EC8 { S_Warn("[trigger_title_spotcam] - Unimplemented condition!\n"); }//032EE0 if (s2 == 4) { S_Warn("[trigger_title_spotcam] - Unimplemented condition!\n"); } a0 = s2 << 0x10; a0 >>= 0x10; InitialiseSpotCam(a0); }//0x32A18 }//32968 } struct ITEM_INFO* ResetCutanimate(int objnum)//32A80, 32F18 { #if 1 struct ITEM_INFO* item; // $s1 int a0 = objnum;//guessed int s0 = a0; item = find_a_fucking_item(objnum); //actually probably a table storing all initial item anims/frames? //char* a00 = &objects[0]; //FIXME needs init s0 <<= 6; //char* s00 = &objects[s0]; //s1 = v0;//? //v1 = s0[0x26]; //v0 = &anims[0]; //a2 = &items[0]; //s1[0x14] = v1;//short store //v1 <<= 16; //v1 >>=16; //a1 = v1 << 2; //a1 += v1; //a1 <<= 3; //a1 += v0; //a2 = s1 - a2; //v0 = a2 << 3; //v0 -= a2; //v1 = v0 << 6; //v0 += v1; //v0 <<= 3; //v0 += a2; //a0 = v0 << 15; //a0 -= v0; //a0 <<= 3; //a0 += a2; //a0 <<= 12; //v0 = a1[0x18]//short //a0 >>= 16; //s1[0x16] = v0; //store half RemoveActiveItem(0); //v0 = s1; //v1 = s1[0x28]//half //a0 = s1[0x84]//word //v1 &= 0xC1FF; //s1[0x28] = v1;//half //v1 = -7; //a0 &= v1; //s1[0x84] = a0//word #endif return item; } void handle_cutseq_triggering(int name)//2C3C4, 2C6EC { S_Warn("[handle_cutseq_triggering] - Unimplemented!\n"); } struct ITEM_INFO* find_a_fucking_item(int object_number)//2DF50(<), 2E1E0(<) { int i; if (level_items > 0) { for (i = 0; i < level_items; i++) { if (items[i].object_number == object_number) { return &items[i]; } } } return NULL; }<commit_msg>Add ResetCutanimate();<commit_after>#include "DELTAPAK.H" #include "CONTROL.H" #include "DRAW.H" #include "ITEMS.H" #include "OBJECTS.H" #include "SETUP.H" #include "SPECIFIC.H" #include "SPOTCAM.H" #include <stddef.h> struct CUTSEQ_ROUTINES cutseq_control_routines[45]; unsigned short crane_pistols_info[11]; unsigned short craneguard_pistols_info[7]; short admiral_chat_ranges_joby2[12]; short sergie_chat_ranges_joby2[8]; short lara_chat_ranges_joby3[6]; short lara_chat_ranges_joby4[10]; short admiral_chat_ranges_joby4[20]; unsigned short larson_pistols_info1[2]; short lara_chat_ranges_andrea1[4]; short larson_chat_ranges1[12]; short pierre_chat_ranges1[30]; short lara_chat_ranges_andrea2[32]; short larson_chat_ranges2[8]; short pierre_chat_ranges2[34]; short admiral_chat_ranges_joby5[18]; short sergie_chat_ranges_joby5[20]; short lara_chat_ranges_joby9[12]; short admiral_chat_ranges_joby9[36]; short lara_chat_ranges_joby10[12]; short admiral_chat_ranges_joby10[42]; unsigned short andrea3_pistols_info[5]; short lara_chat_ranges_andrea3[14]; short larson_chat_ranges3[14]; short lara_chat_ranges_andrea3b[12]; short larson_chat_ranges3b[4]; short priest_chat_ranges_andy7[32]; short lara_chat_ranges_andy7[14]; short lara_chat_ranges_joby7[10]; short lara_chat_ranges_andrea4[22]; short pierre_chat_ranges4[48]; int cuntercunter; char jobyfrigger; int cutrot; int GLOBAL_playing_cutseq; int cutseq_trig; int cutseq_num; unsigned char disable_horizon; char cutseq_busy_timeout; short frig_shadow_bbox[6]; int cut_seethrough; char lara_chat_cnt; char actor_chat_cnt; struct NEW_CUTSCENE* GLOBAL_cutme; int lastcamnum; int GLOBAL_cutseq_frame; int GLOBAL_numcutseq_frames; int GLOBAL_oldcamtype; struct PACKNODE* camera_pnodes; struct PACKNODE* actor_pnodes[10]; struct ITEM_INFO duff_item; int numnailed; char old_status_flags[32]; unsigned short old_status_flags2[32]; unsigned long cutseq_meshbits[10]; unsigned long cutseq_meshswapbits[10]; struct RESIDENT_THING cutseq_resident_addresses[47]; char* GLOBAL_resident_depack_buffers; int cutseq_malloc_used; char* cutseq_malloc_ptr; int cutseq_malloc_free; unsigned short old_lara_holster; short temp_rotation_buffer[160]; #define WORLD_UNITS_PER_SECTOR 1024 #define SECTOR_TO_WORLD(S) ((S) > (0) ? ((S * WORLD_UNITS_PER_SECTOR) + (WORLD_UNITS_PER_SECTOR / 2)) : (0)) void trigger_title_spotcam(int num)//32904, 32D9C { struct ITEM_INFO* item;//v0 int s2 = num; jobyfrigger = 0; int v0 = 4; if (num == 1)//Church seq { //Man holding umbrella at church area (TITLE.TRC) item = ResetCutanimate(ANIMATING10); item->pos.x_pos = SECTOR_TO_WORLD(58); item->pos.y_pos = SECTOR_TO_WORLD(0); item->pos.z_pos = SECTOR_TO_WORLD(41); item->room_number = 0; //Female walking with man holding umbrella, church area (TITLE.TRC) item = ResetCutanimate(ANIMATING11); item->pos.x_pos = SECTOR_TO_WORLD(58); item->pos.y_pos = SECTOR_TO_WORLD(0); item->pos.z_pos = SECTOR_TO_WORLD(41); item->room_number = 0; v0 = 2; if (num == 1) { int a0 = 83; int a1 = 0; //S_CDPlay(short track /*$s0*/, int mode /*$s1*/); if (s2 == 2)//0x32EB0(r) { S_Warn("[trigger_title_spotcam] - Unimplemented condition!\n"); }//0x32EC8(r) if (s2 == 3)//0x32EC8 { S_Warn("[trigger_title_spotcam] - Unimplemented condition!\n"); }//032EE0 if (s2 == 4) { S_Warn("[trigger_title_spotcam] - Unimplemented condition!\n"); } a0 = s2 << 0x10; a0 >>= 0x10; InitialiseSpotCam(a0); }//0x32A18 }//32968 } struct ITEM_INFO* ResetCutanimate(int objnum)//32A80, 32F18 { #if 1 struct ITEM_INFO* item; // $s1 item = find_a_fucking_item(objnum); item->anim_number = *(short*) &objects[(objnum << 6) + 38];//0x237, basically objects[objnum]+38 item->frame_number = anims[item->anim_number].frame_base; RemoveActiveItem((int) (item - &items[0]));//index into items passed? item->flags &= 0xC1FF; #if 0 int test = *(int*) item->active; test &= -7; *(int*) item->active = test; #endif #endif return item; } void handle_cutseq_triggering(int name)//2C3C4, 2C6EC { S_Warn("[handle_cutseq_triggering] - Unimplemented!\n"); } struct ITEM_INFO* find_a_fucking_item(int object_number)//2DF50(<), 2E1E0(<) { int i; if (level_items > 0) { for (i = 0; i < level_items; i++) { if (items[i].object_number == object_number) { return &items[i]; } } } return NULL; }<|endoftext|>
<commit_before>// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "util/metrics.h" #include "util/collection-metrics.h" #include "util/memory-metrics.h" #include <gtest/gtest.h> #include <boost/scoped_ptr.hpp> #include "util/jni-util.h" #include "util/thread.h" using namespace boost; using namespace rapidjson; using namespace std; namespace impala { template <typename M, typename T> void AssertValue(M* metric, const T& value, const string& human_readable) { EXPECT_EQ(metric->value(), value); if (!human_readable.empty()) { EXPECT_EQ(metric->ToHumanReadable(), human_readable); } } TEST(MetricsTest, CounterMetrics) { MetricGroup metrics("CounterMetrics"); IntCounter* int_counter = metrics.AddCounter("counter", 0L); AssertValue(int_counter, 0, "0"); int_counter->Increment(1); AssertValue(int_counter, 1, "1"); int_counter->Increment(10); AssertValue(int_counter, 11, "11"); int_counter->set_value(3456); AssertValue(int_counter, 3456, "3.46K"); IntCounter* int_counter_with_units = metrics.AddCounter("counter_with_units", 10L, TCounterType::BYTES); AssertValue(int_counter_with_units, 10, "10.00 B"); } TEST(MetricsTest, GaugeMetrics) { MetricGroup metrics("GaugeMetrics"); IntGauge* int_gauge = metrics.AddGauge("gauge", 0L); AssertValue(int_gauge, 0, "0"); int_gauge->Increment(-1); AssertValue(int_gauge, -1, "-1"); int_gauge->Increment(10); AssertValue(int_gauge, 9, "9"); int_gauge->set_value(3456); AssertValue(int_gauge, 3456, "3456"); IntGauge* int_gauge_with_units = metrics.AddGauge("gauge_with_units", 10L, TCounterType::TIME_S); AssertValue(int_gauge_with_units, 10, "10s000ms"); } TEST(MetricsTest, PropertyMetrics) { MetricGroup metrics("PropertyMetrics"); BooleanProperty* bool_property = metrics.AddProperty("bool_property", false); AssertValue(bool_property, false, "false"); bool_property->set_value(true); AssertValue(bool_property, true, "true"); StringProperty* string_property = metrics.AddProperty("string_property", string("string1")); AssertValue(string_property, "string1", "string1"); string_property->set_value("string2"); AssertValue(string_property, "string2", "string2"); } TEST(MetricsTest, NonFiniteValues) { MetricGroup metrics("NanValues"); DoubleGauge* gauge = metrics.AddGauge("inf_value", 1.0 / 0); AssertValue(gauge, 1.0 / 0.0, "inf"); gauge->set_value(0.0 / 0.0); EXPECT_TRUE(isnan(gauge->value())); // 0.0 / 0.0 can either be nan or -nan (compiler dependant) EXPECT_TRUE(gauge->ToHumanReadable() == "-nan" || gauge->ToHumanReadable() == "nan"); } TEST(MetricsTest, SetMetrics) { MetricGroup metrics("SetMetrics"); set<int> item_set; item_set.insert(4); item_set.insert(5); item_set.insert(6); SetMetric<int>* set_metric = metrics.RegisterMetric(new SetMetric<int>("set", item_set)); EXPECT_EQ(set_metric->ToHumanReadable(), "[4, 5, 6]"); set_metric->Add(7); set_metric->Add(7); set_metric->Remove(4); set_metric->Remove(4); EXPECT_EQ(set_metric->ToHumanReadable(), "[5, 6, 7]"); } TEST(MetricsTest, StatsMetrics) { // Uninitialised stats metrics don't print anything other than the count MetricGroup metrics("StatsMetrics"); StatsMetric<double>* stats_metric = metrics.RegisterMetric( new StatsMetric<double>("stats", TCounterType::UNIT)); EXPECT_EQ(stats_metric->ToHumanReadable(), "count: 0"); stats_metric->Update(0.0); stats_metric->Update(1.0); stats_metric->Update(2.0); EXPECT_EQ(stats_metric->ToHumanReadable(), "count: 3, last: 2.000000, min: 0.000000, " "max: 2.000000, mean: 1.000000, stddev: 0.816497"); StatsMetric<double>* stats_metric_with_units = metrics.RegisterMetric( new StatsMetric<double>("stats_units", TCounterType::BYTES)); EXPECT_EQ(stats_metric_with_units->ToHumanReadable(), "count: 0"); stats_metric_with_units->Update(0.0); stats_metric_with_units->Update(1.0); stats_metric_with_units->Update(2.0); EXPECT_EQ(stats_metric_with_units->ToHumanReadable(), "count: 3, last: 2.00 B, min: 0, " "max: 2.00 B, mean: 1.00 B, stddev: 0.82 B"); } TEST(MetricsTest, MemMetric) { #ifndef ADDRESS_SANITIZER MetricGroup metrics("MemMetrics"); RegisterMemoryMetrics(&metrics, false); // Smoke test to confirm that tcmalloc metrics are returning reasonable values. UIntGauge* bytes_in_use = metrics.FindMetricForTesting<UIntGauge> ("tcmalloc.bytes-in-use"); DCHECK(bytes_in_use != NULL); uint64_t cur_in_use = bytes_in_use->value(); scoped_ptr<uint64_t> chunk(new uint64_t); EXPECT_GT(cur_in_use, 0); EXPECT_GT(bytes_in_use->value(), cur_in_use); UIntGauge* total_bytes_reserved = metrics.FindMetricForTesting<UIntGauge>("tcmalloc.total-bytes-reserved"); DCHECK(total_bytes_reserved != NULL); DCHECK_GT(total_bytes_reserved->value(), 0); UIntGauge* pageheap_free_bytes = metrics.FindMetricForTesting<UIntGauge>("tcmalloc.pageheap-free-bytes"); DCHECK(pageheap_free_bytes != NULL); UIntGauge* pageheap_unmapped_bytes = metrics.FindMetricForTesting<UIntGauge>("tcmalloc.pageheap-unmapped-bytes"); EXPECT_TRUE(pageheap_unmapped_bytes != NULL); #endif } TEST(MetricsTest, JvmMetrics) { MetricGroup metrics("JvmMetrics"); RegisterMemoryMetrics(&metrics, true); UIntGauge* jvm_total_used = metrics.GetChildGroup("jvm")->FindMetricForTesting<UIntGauge>( "jvm.total.current-usage-bytes"); ASSERT_TRUE(jvm_total_used != NULL); EXPECT_GT(jvm_total_used->value(), 0); UIntGauge* jvm_peak_total_used = metrics.GetChildGroup("jvm")->FindMetricForTesting<UIntGauge>( "jvm.total.peak-current-usage-bytes"); ASSERT_TRUE(jvm_peak_total_used != NULL); EXPECT_GT(jvm_peak_total_used->value(), 0); } void AssertJson(const Value& val, const string& name, const string& value, const string& description, const string& kind="", const string& units="") { EXPECT_EQ(val["name"].GetString(), name); EXPECT_EQ(val["human_readable"].GetString(), value); EXPECT_EQ(val["description"].GetString(), description); if (!kind.empty()) EXPECT_EQ(val["kind"].GetString(), kind); if (!units.empty()) EXPECT_EQ(val["units"].GetString(), units); } TEST(MetricsJsonTest, Counters) { MetricGroup metrics("CounterMetrics"); metrics.AddCounter("counter", 0L); Document document; Value val; metrics.ToJson(true, &document, &val); const Value& counter_val = val["metrics"][0u]; AssertJson(counter_val, "counter", "0", "", "COUNTER", "UNIT"); EXPECT_EQ(counter_val["value"].GetInt(), 0); } TEST(MetricsJsonTest, Gauges) { MetricGroup metrics("GaugeMetrics"); metrics.AddGauge("gauge", 10L); Document document; Value val; metrics.ToJson(true, &document, &val); AssertJson(val["metrics"][0u], "gauge", "10", "", "GAUGE", "NONE"); EXPECT_EQ(val["metrics"][0u]["value"].GetInt(), 10); } TEST(MetricsJsonTest, Properties) { MetricGroup metrics("Properties"); metrics.AddProperty("property", string("my value")); Document document; Value val; metrics.ToJson(true, &document, &val); AssertJson(val["metrics"][0u], "property", "my value", "", "PROPERTY", "NONE"); EXPECT_EQ(string(val["metrics"][0u]["value"].GetString()), "my value"); } TEST(MetricsJsonTest, SetMetrics) { MetricGroup metrics("SetMetrics"); set<int> item_set; item_set.insert(4); item_set.insert(5); item_set.insert(6); metrics.RegisterMetric(new SetMetric<int>("set", item_set)); Document document; Value val; metrics.ToJson(true, &document, &val); const Value& set_val = val["metrics"][0u]; ASSERT_TRUE(set_val["items"].IsArray()); EXPECT_EQ(set_val["items"].Size(), 3); EXPECT_EQ(set_val["items"][0u].GetInt(), 4); EXPECT_EQ(set_val["items"][1].GetInt(), 5); EXPECT_EQ(set_val["items"][2].GetInt(), 6); AssertJson(set_val, "set", "[4, 5, 6]", ""); } TEST(MetricsJsonTest, StatsMetrics) { MetricGroup metrics("StatsMetrics"); StatsMetric<double>* metric = metrics.RegisterMetric(new StatsMetric<double>("stats_metric", TCounterType::UNIT)); metric->Update(10.0); metric->Update(20.0); Document document; Value val; metrics.ToJson(true, &document, &val); const Value& stats_val = val["metrics"][0u]; AssertJson(stats_val, "stats_metric", "count: 2, last: 20.000000, min: 10.000000, " "max: 20.000000, mean: 15.000000, stddev: 5.000000", "", "", "UNIT"); EXPECT_EQ(stats_val["count"].GetInt(), 2); EXPECT_EQ(stats_val["last"].GetDouble(), 20.0); EXPECT_EQ(stats_val["min"].GetDouble(), 10.0); EXPECT_EQ(stats_val["max"].GetDouble(), 20.0); EXPECT_EQ(stats_val["mean"].GetDouble(), 15.0); EXPECT_EQ(stats_val["stddev"].GetDouble(), 5.0); } TEST(MetricsJsonTest, UnitsAndDescription) { MetricGroup metrics("Units"); metrics.AddCounter("counter", 2048, TCounterType::BYTES, "description"); Document document; Value val; metrics.ToJson(true, &document, &val); const Value& counter_val = val["metrics"][0u]; AssertJson(counter_val, "counter", "2.00 KB", "description", "COUNTER", "BYTES"); EXPECT_EQ(counter_val["value"].GetInt(), 2048); } TEST(MetricGroupTest, JsonTest) { MetricGroup metrics("JsonTest"); metrics.AddCounter("counter1", 2048, TCounterType::BYTES, "description"); metrics.AddCounter("counter2", 2048, TCounterType::BYTES, "description"); metrics.GetChildGroup("child1"); metrics.GetChildGroup("child2")->AddCounter("child_counter", 0); IntCounter* counter = metrics.FindMetricForTesting<IntCounter>(string("child_counter")); ASSERT_NE(counter, reinterpret_cast<IntCounter*>(NULL)); Document document; Value val; metrics.ToJson(true, &document, &val); EXPECT_EQ(val["metrics"].Size(), 2); EXPECT_EQ(val["name"].GetString(), string("JsonTest")); EXPECT_EQ(val["child_groups"].Size(), 2); EXPECT_EQ(val["child_groups"][0u]["name"].GetString(), string("child1")); EXPECT_EQ(val["child_groups"][0u]["metrics"].Size(), 0); EXPECT_EQ(val["child_groups"][1]["name"].GetString(), string("child2")); EXPECT_EQ(val["child_groups"][1]["metrics"].Size(), 1); } } int main(int argc, char **argv) { google::InitGoogleLogging(argv[0]); ::testing::InitGoogleTest(&argc, argv); impala::InitThreading(); impala::JniUtil::Init(); return RUN_ALL_TESTS(); } <commit_msg>Use literals for nonfinite doubles in metrics-test<commit_after>// Copyright 2012 Cloudera Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "util/metrics.h" #include "util/collection-metrics.h" #include "util/memory-metrics.h" #include <gtest/gtest.h> #include <boost/scoped_ptr.hpp> #include <limits> #include "util/jni-util.h" #include "util/thread.h" using namespace boost; using namespace rapidjson; using namespace std; namespace impala { template <typename M, typename T> void AssertValue(M* metric, const T& value, const string& human_readable) { EXPECT_EQ(metric->value(), value); if (!human_readable.empty()) { EXPECT_EQ(metric->ToHumanReadable(), human_readable); } } TEST(MetricsTest, CounterMetrics) { MetricGroup metrics("CounterMetrics"); IntCounter* int_counter = metrics.AddCounter("counter", 0L); AssertValue(int_counter, 0, "0"); int_counter->Increment(1); AssertValue(int_counter, 1, "1"); int_counter->Increment(10); AssertValue(int_counter, 11, "11"); int_counter->set_value(3456); AssertValue(int_counter, 3456, "3.46K"); IntCounter* int_counter_with_units = metrics.AddCounter("counter_with_units", 10L, TCounterType::BYTES); AssertValue(int_counter_with_units, 10, "10.00 B"); } TEST(MetricsTest, GaugeMetrics) { MetricGroup metrics("GaugeMetrics"); IntGauge* int_gauge = metrics.AddGauge("gauge", 0L); AssertValue(int_gauge, 0, "0"); int_gauge->Increment(-1); AssertValue(int_gauge, -1, "-1"); int_gauge->Increment(10); AssertValue(int_gauge, 9, "9"); int_gauge->set_value(3456); AssertValue(int_gauge, 3456, "3456"); IntGauge* int_gauge_with_units = metrics.AddGauge("gauge_with_units", 10L, TCounterType::TIME_S); AssertValue(int_gauge_with_units, 10, "10s000ms"); } TEST(MetricsTest, PropertyMetrics) { MetricGroup metrics("PropertyMetrics"); BooleanProperty* bool_property = metrics.AddProperty("bool_property", false); AssertValue(bool_property, false, "false"); bool_property->set_value(true); AssertValue(bool_property, true, "true"); StringProperty* string_property = metrics.AddProperty("string_property", string("string1")); AssertValue(string_property, "string1", "string1"); string_property->set_value("string2"); AssertValue(string_property, "string2", "string2"); } TEST(MetricsTest, NonFiniteValues) { MetricGroup metrics("NanValues"); double inf = numeric_limits<double>::infinity(); DoubleGauge* gauge = metrics.AddGauge("inf_value", inf); AssertValue(gauge, inf, "inf"); double nan = numeric_limits<double>::quiet_NaN(); gauge->set_value(nan); EXPECT_TRUE(isnan(gauge->value())); EXPECT_TRUE(gauge->ToHumanReadable() == "nan"); } TEST(MetricsTest, SetMetrics) { MetricGroup metrics("SetMetrics"); set<int> item_set; item_set.insert(4); item_set.insert(5); item_set.insert(6); SetMetric<int>* set_metric = metrics.RegisterMetric(new SetMetric<int>("set", item_set)); EXPECT_EQ(set_metric->ToHumanReadable(), "[4, 5, 6]"); set_metric->Add(7); set_metric->Add(7); set_metric->Remove(4); set_metric->Remove(4); EXPECT_EQ(set_metric->ToHumanReadable(), "[5, 6, 7]"); } TEST(MetricsTest, StatsMetrics) { // Uninitialised stats metrics don't print anything other than the count MetricGroup metrics("StatsMetrics"); StatsMetric<double>* stats_metric = metrics.RegisterMetric( new StatsMetric<double>("stats", TCounterType::UNIT)); EXPECT_EQ(stats_metric->ToHumanReadable(), "count: 0"); stats_metric->Update(0.0); stats_metric->Update(1.0); stats_metric->Update(2.0); EXPECT_EQ(stats_metric->ToHumanReadable(), "count: 3, last: 2.000000, min: 0.000000, " "max: 2.000000, mean: 1.000000, stddev: 0.816497"); StatsMetric<double>* stats_metric_with_units = metrics.RegisterMetric( new StatsMetric<double>("stats_units", TCounterType::BYTES)); EXPECT_EQ(stats_metric_with_units->ToHumanReadable(), "count: 0"); stats_metric_with_units->Update(0.0); stats_metric_with_units->Update(1.0); stats_metric_with_units->Update(2.0); EXPECT_EQ(stats_metric_with_units->ToHumanReadable(), "count: 3, last: 2.00 B, min: 0, " "max: 2.00 B, mean: 1.00 B, stddev: 0.82 B"); } TEST(MetricsTest, MemMetric) { #ifndef ADDRESS_SANITIZER MetricGroup metrics("MemMetrics"); RegisterMemoryMetrics(&metrics, false); // Smoke test to confirm that tcmalloc metrics are returning reasonable values. UIntGauge* bytes_in_use = metrics.FindMetricForTesting<UIntGauge> ("tcmalloc.bytes-in-use"); DCHECK(bytes_in_use != NULL); uint64_t cur_in_use = bytes_in_use->value(); scoped_ptr<uint64_t> chunk(new uint64_t); EXPECT_GT(cur_in_use, 0); EXPECT_GT(bytes_in_use->value(), cur_in_use); UIntGauge* total_bytes_reserved = metrics.FindMetricForTesting<UIntGauge>("tcmalloc.total-bytes-reserved"); DCHECK(total_bytes_reserved != NULL); DCHECK_GT(total_bytes_reserved->value(), 0); UIntGauge* pageheap_free_bytes = metrics.FindMetricForTesting<UIntGauge>("tcmalloc.pageheap-free-bytes"); DCHECK(pageheap_free_bytes != NULL); UIntGauge* pageheap_unmapped_bytes = metrics.FindMetricForTesting<UIntGauge>("tcmalloc.pageheap-unmapped-bytes"); EXPECT_TRUE(pageheap_unmapped_bytes != NULL); #endif } TEST(MetricsTest, JvmMetrics) { MetricGroup metrics("JvmMetrics"); RegisterMemoryMetrics(&metrics, true); UIntGauge* jvm_total_used = metrics.GetChildGroup("jvm")->FindMetricForTesting<UIntGauge>( "jvm.total.current-usage-bytes"); ASSERT_TRUE(jvm_total_used != NULL); EXPECT_GT(jvm_total_used->value(), 0); UIntGauge* jvm_peak_total_used = metrics.GetChildGroup("jvm")->FindMetricForTesting<UIntGauge>( "jvm.total.peak-current-usage-bytes"); ASSERT_TRUE(jvm_peak_total_used != NULL); EXPECT_GT(jvm_peak_total_used->value(), 0); } void AssertJson(const Value& val, const string& name, const string& value, const string& description, const string& kind="", const string& units="") { EXPECT_EQ(val["name"].GetString(), name); EXPECT_EQ(val["human_readable"].GetString(), value); EXPECT_EQ(val["description"].GetString(), description); if (!kind.empty()) EXPECT_EQ(val["kind"].GetString(), kind); if (!units.empty()) EXPECT_EQ(val["units"].GetString(), units); } TEST(MetricsJsonTest, Counters) { MetricGroup metrics("CounterMetrics"); metrics.AddCounter("counter", 0L); Document document; Value val; metrics.ToJson(true, &document, &val); const Value& counter_val = val["metrics"][0u]; AssertJson(counter_val, "counter", "0", "", "COUNTER", "UNIT"); EXPECT_EQ(counter_val["value"].GetInt(), 0); } TEST(MetricsJsonTest, Gauges) { MetricGroup metrics("GaugeMetrics"); metrics.AddGauge("gauge", 10L); Document document; Value val; metrics.ToJson(true, &document, &val); AssertJson(val["metrics"][0u], "gauge", "10", "", "GAUGE", "NONE"); EXPECT_EQ(val["metrics"][0u]["value"].GetInt(), 10); } TEST(MetricsJsonTest, Properties) { MetricGroup metrics("Properties"); metrics.AddProperty("property", string("my value")); Document document; Value val; metrics.ToJson(true, &document, &val); AssertJson(val["metrics"][0u], "property", "my value", "", "PROPERTY", "NONE"); EXPECT_EQ(string(val["metrics"][0u]["value"].GetString()), "my value"); } TEST(MetricsJsonTest, SetMetrics) { MetricGroup metrics("SetMetrics"); set<int> item_set; item_set.insert(4); item_set.insert(5); item_set.insert(6); metrics.RegisterMetric(new SetMetric<int>("set", item_set)); Document document; Value val; metrics.ToJson(true, &document, &val); const Value& set_val = val["metrics"][0u]; ASSERT_TRUE(set_val["items"].IsArray()); EXPECT_EQ(set_val["items"].Size(), 3); EXPECT_EQ(set_val["items"][0u].GetInt(), 4); EXPECT_EQ(set_val["items"][1].GetInt(), 5); EXPECT_EQ(set_val["items"][2].GetInt(), 6); AssertJson(set_val, "set", "[4, 5, 6]", ""); } TEST(MetricsJsonTest, StatsMetrics) { MetricGroup metrics("StatsMetrics"); StatsMetric<double>* metric = metrics.RegisterMetric(new StatsMetric<double>("stats_metric", TCounterType::UNIT)); metric->Update(10.0); metric->Update(20.0); Document document; Value val; metrics.ToJson(true, &document, &val); const Value& stats_val = val["metrics"][0u]; AssertJson(stats_val, "stats_metric", "count: 2, last: 20.000000, min: 10.000000, " "max: 20.000000, mean: 15.000000, stddev: 5.000000", "", "", "UNIT"); EXPECT_EQ(stats_val["count"].GetInt(), 2); EXPECT_EQ(stats_val["last"].GetDouble(), 20.0); EXPECT_EQ(stats_val["min"].GetDouble(), 10.0); EXPECT_EQ(stats_val["max"].GetDouble(), 20.0); EXPECT_EQ(stats_val["mean"].GetDouble(), 15.0); EXPECT_EQ(stats_val["stddev"].GetDouble(), 5.0); } TEST(MetricsJsonTest, UnitsAndDescription) { MetricGroup metrics("Units"); metrics.AddCounter("counter", 2048, TCounterType::BYTES, "description"); Document document; Value val; metrics.ToJson(true, &document, &val); const Value& counter_val = val["metrics"][0u]; AssertJson(counter_val, "counter", "2.00 KB", "description", "COUNTER", "BYTES"); EXPECT_EQ(counter_val["value"].GetInt(), 2048); } TEST(MetricGroupTest, JsonTest) { MetricGroup metrics("JsonTest"); metrics.AddCounter("counter1", 2048, TCounterType::BYTES, "description"); metrics.AddCounter("counter2", 2048, TCounterType::BYTES, "description"); metrics.GetChildGroup("child1"); metrics.GetChildGroup("child2")->AddCounter("child_counter", 0); IntCounter* counter = metrics.FindMetricForTesting<IntCounter>(string("child_counter")); ASSERT_NE(counter, reinterpret_cast<IntCounter*>(NULL)); Document document; Value val; metrics.ToJson(true, &document, &val); EXPECT_EQ(val["metrics"].Size(), 2); EXPECT_EQ(val["name"].GetString(), string("JsonTest")); EXPECT_EQ(val["child_groups"].Size(), 2); EXPECT_EQ(val["child_groups"][0u]["name"].GetString(), string("child1")); EXPECT_EQ(val["child_groups"][0u]["metrics"].Size(), 0); EXPECT_EQ(val["child_groups"][1]["name"].GetString(), string("child2")); EXPECT_EQ(val["child_groups"][1]["metrics"].Size(), 1); } } int main(int argc, char **argv) { google::InitGoogleLogging(argv[0]); ::testing::InitGoogleTest(&argc, argv); impala::InitThreading(); impala::JniUtil::Init(); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before><commit_msg>Cleaned up comments.<commit_after><|endoftext|>
<commit_before>#include <regex> #include "foo_musicbrainz.h" #include "MetadataProcessor.h" using namespace std::tr1; namespace foo_musicbrainz { // {2311DC1D-1A81-4496-9139-678481C813F8} const GUID MetadataProcessor::class_guid = { 0x2311dc1d, 0x1a81, 0x4496, { 0x91, 0x39, 0x67, 0x84, 0x81, 0xc8, 0x13, 0xf8 } }; void MetadataProcessor::apply_all(ReleaseList &release_list) { service_enum_t<MetadataProcessor> processors; service_ptr_t<MetadataProcessor> processor; while (processors.next(processor)) { apply_one(processor, release_list); } } void MetadataProcessor::apply_one(service_ptr_t<MetadataProcessor> processor, ReleaseList &release_list) { auto entities = processor->get_entities(); bool process_release_list = entities & release_list_entity; bool process_release = entities & release_entity; bool process_medium = entities & medium_entity; bool process_track = entities & track_entity; if (entities < release_list_entity) return; bool after_release_list = entities > release_list_entity; bool after_release = entities > release_entity; bool after_medium = entities > medium_entity; if (process_release_list) { processor->process(release_list); } if (!after_release_list) return; for (size_t i = 0; i < release_list.count(); i++) { auto release = release_list[i]; if (process_release) { processor->process(*release); } if (!after_release) continue; auto medium_list = release->get_medium_list(); for (size_t j = 0; j < medium_list->count(); j++) { auto medium = medium_list->get(j); if (process_medium) { processor->process(*release); } if (!after_medium) continue; auto track_list = medium->get_track_list(); for (size_t k = 0; k < track_list->count(); k++) { auto track = track_list->get(k); if (process_track) { processor->process(*track); } } } } } } <commit_msg>Implemented “No feat.” as a metadata processor service. Closes #3.<commit_after>#include <regex> #include "foo_musicbrainz.h" #include "MetadataProcessor.h" using namespace std::tr1; namespace foo_musicbrainz { // {2311DC1D-1A81-4496-9139-678481C813F8} const GUID MetadataProcessor::class_guid = { 0x2311dc1d, 0x1a81, 0x4496, { 0x91, 0x39, 0x67, 0x84, 0x81, 0xc8, 0x13, 0xf8 } }; void MetadataProcessor::apply_all(ReleaseList &release_list) { service_enum_t<MetadataProcessor> processors; service_ptr_t<MetadataProcessor> processor; while (processors.next(processor)) { apply_one(processor, release_list); } } void MetadataProcessor::apply_one(service_ptr_t<MetadataProcessor> processor, ReleaseList &release_list) { auto entities = processor->get_entities(); bool process_release_list = entities & release_list_entity; bool process_release = entities & release_entity; bool process_medium = entities & medium_entity; bool process_track = entities & track_entity; if (entities < release_list_entity) return; bool after_release_list = entities > release_list_entity; bool after_release = entities > release_entity; bool after_medium = entities > medium_entity; if (process_release_list) { processor->process(release_list); } if (!after_release_list) return; for (size_t i = 0; i < release_list.count(); i++) { auto release = release_list[i]; if (process_release) { processor->process(*release); } if (!after_release) continue; auto medium_list = release->get_medium_list(); for (size_t j = 0; j < medium_list->count(); j++) { auto medium = medium_list->get(j); if (process_medium) { processor->process(*release); } if (!after_medium) continue; auto track_list = medium->get_track_list(); for (size_t k = 0; k < track_list->count(); k++) { auto track = track_list->get(k); if (process_track) { processor->process(*track); } } } } } class RemoveFeatProcessor : public MetadataProcessor { public: Entities get_entities() { return track_entity; } bool is_enabled() { return Preferences::no_feat; } void process(Track &track) { auto recording = track.get_recording(); auto title = recording->get_title(); static regex rx("^(.+?)(\\s+\\(feat\\.\\s+.+\\))?$"); cmatch matches; if (regex_search(title.get_ptr(), matches, rx)) { recording->set_title(matches[1].str().data()); } } }; service_factory_single_t<RemoveFeatProcessor> remove_feat_processor; } <|endoftext|>
<commit_before>// // AnsyncStreamSession.hpp // Pods // // Created by jinchu darwin on 15/9/29. // // #ifndef AnsyncStreamSession_hpp #define AnsyncStreamSession_hpp #include <cstddef> #include <functional> #include <vector> #include <queue> #include <string> #include <videocore/system/util.h> #include <videocore/system/JobQueue.hpp> #include <videocore/system/PreBuffer.hpp> #include <videocore/stream/IStreamSession.hpp> namespace videocore { typedef enum { kAsyncStreamStateNone = 0, kAsyncStreamStateConnecting = 1, kAsyncStreamStateConnected = 2, kAsyncStreamStateDisconnecting = 4, kAsyncStreamStateDisconnected = 5, kAsyncStreamStateError = 6, } AsyncStreamState_T; typedef std::vector<uint8_t> AsyncStreamBuffer; typedef std::shared_ptr<AsyncStreamBuffer> AsyncStreamBufferSP; #pragma mark - #pragma mark AnsyncStreamSession typedef std::function<void(StreamStatus_T status)> SSConnectionStatus_T; typedef std::function<void(AsyncStreamBuffer& abuff)> SSAnsyncReadCallBack_T; typedef std::function<void()> SSAnsyncWriteCallBack_T; class AsyncStreamReader; class AsyncStreamWriter; class AsyncStreamSession { public: AsyncStreamSession(IStreamSession *stream); ~AsyncStreamSession(); void connect(const std::string &host, int port, SSConnectionStatus_T statuscb); void disconnect(); void write(uint8_t *buffer, size_t length, SSAnsyncWriteCallBack_T writecb=nullptr); void readLength(size_t length, SSAnsyncReadCallBack_T readcb); void readLength(size_t length, AsyncStreamBufferSP orgbuf, size_t offset, SSAnsyncReadCallBack_T readcb); private: void setState(AsyncStreamState_T state); std::shared_ptr<AsyncStreamReader> getCurrentReader(); void doReadData(); bool innnerReadData(); void finishCurrentReader(); std::shared_ptr<AsyncStreamWriter> getCurrentWriter(); void doWriteData(); void innerWriteData(); void finishCurrentWriter(); private: std::unique_ptr<IStreamSession> m_stream; JobQueue m_eventTriggerJob; JobQueue m_socketJob; std::queue<std::shared_ptr<AsyncStreamReader>> m_readerQueue; std::queue<std::shared_ptr<AsyncStreamWriter>> m_writerQueue; SSConnectionStatus_T m_connectionStatusCB; AsyncStreamState_T m_state; PreallocBuffer m_inputBuffer; bool m_doReadingData; }; } #endif /* AnsyncStreamSession_hpp */ <commit_msg>Delete AsyncStreamSession.hpp<commit_after><|endoftext|>
<commit_before>#include <set> #include <vector> #include "dg/ReadWriteGraph/ReadWriteGraph.h" #include "dg/BBlocksBuilder.h" namespace dg { namespace dda { RWNode UNKNOWN_MEMLOC; RWNode *UNKNOWN_MEMORY = &UNKNOWN_MEMLOC; #ifndef NDEBUG void RWNode::dump() const { std::cout << getID() << "\n"; } void RWNodeCall::dump() const { std::cout << getID() << " calls ["; unsigned n = 0; for (auto& cv : callees) { if (n++ > 0) { std::cout << ", "; } if (auto *subg = cv.getSubgraph()) { const auto& nm = subg->getName(); if (nm.empty()) { std::cout << subg; } else { std::cout << nm; } } else { std::cout << cv.getCalledValue()->getID(); } } std::cout << "]\n"; } void RWNodeRet::dump() const { std::cout << getID() << " returns to ["; unsigned n = 0; for (auto *r : returns) { if (n++ > 0) { std::cout << ", "; } std::cout << r->getID(); } std::cout << "]\n"; } void RWBBlock::dump() const { std::cout << "bblock " << this << "\n"; for (auto *n : _nodes) { std::cout << " "; n->dump(); } } #endif void RWNodeCall::addCallee(RWSubgraph *s) { callees.emplace_back(s); s->addCaller(this); } void ReadWriteGraph::removeUselessNodes() { } void RWSubgraph::buildBBlocks(bool /*dce*/) { assert(getRoot() && "No root node"); DBG(dda, "Building basic blocks"); BBlocksBuilder<RWBBlock> builder; _bblocks = std::move(builder.buildAndGetBlocks(getRoot())); assert(getRoot()->getBBlock() && "Root node has no BBlock"); // should we eliminate dead code? // The dead code are the nodes that have no basic block assigned // (follows from the DFS nature of the block builder algorithm) /* if (!dce) return; for (auto& nd : _nodes) { if (nd->getBBlock() == nullptr) { nd->isolate(); nd.reset(); } } */ } // split the block on the first call and return the // block containing the rest of the instructions // (or nullptr if there's nothing else to do) static RWBBlock * splitBlockOnFirstCall(RWBBlock *block, std::vector<std::unique_ptr<RWBBlock>>& newblocks) { for (auto *node : block->getNodes()) { if (auto *call = RWNodeCall::get(node)) { if (call->callsOneUndefined()) { // ignore calls that call one udefined function, // those behave just like usual read/write continue; } DBG(dda, "Splitting basic block around " << node->getID()); auto blks = block->splitAround(node); if (blks.first) newblocks.push_back(std::move(blks.first)); if (blks.second) { newblocks.push_back(std::move(blks.second)); return newblocks.back().get(); } } } return nullptr; } void RWSubgraph::splitBBlocksOnCalls() { DBG_SECTION_BEGIN(dda, "Splitting basic blocks on calls"); if (_bblocks.size() == 0) return; #ifndef NDEBUG auto *entry = _bblocks[0].get(); #endif std::vector<std::unique_ptr<RWBBlock>> newblocks; for (auto& bblock : _bblocks) { auto *cur = bblock.get(); while(cur) { cur = splitBlockOnFirstCall(cur, newblocks); } } for (auto& bblock : newblocks) { _bblocks.push_back(std::move(bblock)); } assert(entry == _bblocks[0].get() && "splitBBlocksOnCalls() changed the entry"); DBG_SECTION_END(dda, "Splitting basic blocks on calls finished"); } } // namespace dda } // namespace dg <commit_msg>rwg: fix splitting blocks on calls<commit_after>#include <set> #include <vector> #include "dg/ReadWriteGraph/ReadWriteGraph.h" #include "dg/BBlocksBuilder.h" namespace dg { namespace dda { RWNode UNKNOWN_MEMLOC; RWNode *UNKNOWN_MEMORY = &UNKNOWN_MEMLOC; #ifndef NDEBUG void RWNode::dump() const { std::cout << getID() << "\n"; } void RWNodeCall::dump() const { std::cout << getID() << " calls ["; unsigned n = 0; for (auto& cv : callees) { if (n++ > 0) { std::cout << ", "; } if (auto *subg = cv.getSubgraph()) { const auto& nm = subg->getName(); if (nm.empty()) { std::cout << subg; } else { std::cout << nm; } } else { std::cout << cv.getCalledValue()->getID(); } } std::cout << "]\n"; } void RWNodeRet::dump() const { std::cout << getID() << " returns to ["; unsigned n = 0; for (auto *r : returns) { if (n++ > 0) { std::cout << ", "; } std::cout << r->getID(); } std::cout << "]\n"; } void RWBBlock::dump() const { std::cout << "bblock " << this << "\n"; for (auto *n : _nodes) { std::cout << " "; n->dump(); } } #endif void RWNodeCall::addCallee(RWSubgraph *s) { callees.emplace_back(s); s->addCaller(this); } void ReadWriteGraph::removeUselessNodes() { } void RWSubgraph::buildBBlocks(bool /*dce*/) { assert(getRoot() && "No root node"); DBG(dda, "Building basic blocks"); BBlocksBuilder<RWBBlock> builder; _bblocks = std::move(builder.buildAndGetBlocks(getRoot())); assert(getRoot()->getBBlock() && "Root node has no BBlock"); // should we eliminate dead code? // The dead code are the nodes that have no basic block assigned // (follows from the DFS nature of the block builder algorithm) /* if (!dce) return; for (auto& nd : _nodes) { if (nd->getBBlock() == nullptr) { nd->isolate(); nd.reset(); } } */ } // split the block on the first call and return the // block containing the rest of the instructions // (or nullptr if there's nothing else to do) static RWBBlock * splitBlockOnFirstCall(RWBBlock *block, std::vector<std::unique_ptr<RWBBlock>>& newblocks) { for (auto *node : block->getNodes()) { if (auto *call = RWNodeCall::get(node)) { if (call->callsOneUndefined()) { // ignore calls that call one udefined function, // those behave just like usual read/write continue; } DBG(dda, "Splitting basic block around " << node->getID()); auto blks = block->splitAround(node); if (blks.first) newblocks.push_back(std::move(blks.first)); if (blks.second) { newblocks.push_back(std::move(blks.second)); return newblocks.back().get(); } else { return nullptr; } } } return nullptr; } void RWSubgraph::splitBBlocksOnCalls() { DBG_SECTION_BEGIN(dda, "Splitting basic blocks on calls"); if (_bblocks.size() == 0) return; #ifndef NDEBUG auto *entry = _bblocks[0].get(); #endif std::vector<std::unique_ptr<RWBBlock>> newblocks; for (auto& bblock : _bblocks) { auto *cur = bblock.get(); while(cur) { cur = splitBlockOnFirstCall(cur, newblocks); } } for (auto& bblock : newblocks) { _bblocks.push_back(std::move(bblock)); } assert(entry == _bblocks[0].get() && "splitBBlocksOnCalls() changed the entry"); DBG_SECTION_END(dda, "Splitting basic blocks on calls finished"); } } // namespace dda } // namespace dg <|endoftext|>
<commit_before>//===----- CallGraphAnalysis.cpp - Call graph construction ----*- C++ -*---===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SILAnalysis/CallGraphAnalysis.h" #include "swift/Basic/Fallthrough.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include <algorithm> #include <utility> using namespace swift; #define DEBUG_TYPE "call-graph" STATISTIC(NumCallGraphNodes, "# of call graph nodes created"); STATISTIC(NumAppliesWithEdges, "# of call sites with edges"); STATISTIC(NumAppliesWithoutEdges, "# of call sites without edges"); STATISTIC(NumAppliesOfBuiltins, "# of call sites calling builtins"); CallGraph::CallGraph(SILModule *Mod, bool completeModule) : M(*Mod) { // Build the initial call graph by creating a node for each // function, and an edge for each direct call to a free function. // TODO: Handle other kinds of applies. unsigned NodeOrdinal = 0; for (auto &F : M) addCallGraphNode(&F, NodeOrdinal++); EdgeOrdinal = 0; for (auto &F : M) if (F.isDefinition()) addEdges(&F); } CallGraph::~CallGraph() { // Clean up all call graph nodes. for (auto &P : FunctionToNodeMap) { P.second->~CallGraphNode(); } // Clean up all call graph edges. for (auto &P : ApplyToEdgeMap) { P.second->~CallGraphEdge(); } // Clean up all SCCs. for (CallGraphSCC *SCC : BottomUpSCCOrder) { SCC->~CallGraphSCC(); } } void CallGraph::addCallGraphNode(SILFunction *F, unsigned NodeOrdinal) { // TODO: Compute this from the call graph itself after stripping // unreachable nodes from graph. ++NumCallGraphNodes; auto *Node = new (Allocator) CallGraphNode(F, NodeOrdinal); assert(!FunctionToNodeMap.count(F) && "Added function already has a call graph node!"); FunctionToNodeMap[F] = Node; // TODO: Only add functions clearly visible from outside our // compilation scope as roots. if (F->isDefinition()) CallGraphRoots.push_back(Node); } bool CallGraph::tryGetCalleeSet(SILValue Callee, CallGraphEdge::CalleeSetType &CalleeSet, bool &Complete) { assert(CalleeSet.empty() && "Expected empty callee set!"); switch (Callee->getKind()) { case ValueKind::ThinToThickFunctionInst: Callee = cast<ThinToThickFunctionInst>(Callee)->getOperand(); SWIFT_FALLTHROUGH; case ValueKind::FunctionRefInst: { auto *CalleeFn = cast<FunctionRefInst>(Callee)->getReferencedFunction(); auto *CalleeNode = getCallGraphNode(CalleeFn); assert(CalleeNode && "Expected to have a call graph node for all functions!"); CalleeSet.insert(CalleeNode); Complete = true; return true; } case ValueKind::PartialApplyInst: return tryGetCalleeSet(cast<PartialApplyInst>(Callee)->getCallee(), CalleeSet, Complete); case ValueKind::DynamicMethodInst: // TODO: Decide how to handle these in graph construction and // analysis passes. We might just leave them out of the // graph. return false; case ValueKind::SILArgument: // First-pass call-graph construction will not do anything with // these, but a second pass can potentially statically determine // the called function in some cases. return false; case ValueKind::ApplyInst: // TODO: Probably not worth iterating invocation- then // reverse-invocation order to catch this. return false; case ValueKind::TupleExtractInst: // TODO: It would be good to tunnel through extracts so that we // can build a more accurate call graph prior to any // optimizations. return false; case ValueKind::StructExtractInst: // TODO: It would be good to tunnel through extracts so that we // can build a more accurate call graph prior to any // optimizations. return false; case ValueKind::BuiltinInst: ++NumAppliesOfBuiltins; return false; case ValueKind::WitnessMethodInst: { auto *WMI = cast<WitnessMethodInst>(Callee); SILFunction *CalleeFn; ArrayRef<Substitution> Subs; SILWitnessTable *WT; std::tie(CalleeFn, WT, Subs) = WMI->getModule().lookUpFunctionInWitnessTable(WMI->getConformance(), WMI->getMember()); if (!CalleeFn) return false; auto *CalleeNode = getCallGraphNode(CalleeFn); assert(CalleeNode && "Expected to have a call graph node for all functions!"); CalleeSet.insert(CalleeNode); Complete = true; return true; } case ValueKind::ClassMethodInst: case ValueKind::SuperMethodInst: // TODO: Each of these requires specific handling. return false; default: assert(!isa<MethodInst>(Callee) && "Unhandled method instruction in call graph construction!"); // There are cases where we will be very hard pressed to determine // what we are calling. return false; } } static void orderEdges(const llvm::SmallPtrSetImpl<CallGraphEdge *> &Edges, llvm::SmallVectorImpl<CallGraphEdge *> &OrderedEdges) { for (auto *Edge : Edges) OrderedEdges.push_back(Edge); std::sort(OrderedEdges.begin(), OrderedEdges.end(), [](CallGraphEdge *left, CallGraphEdge *right) { return left->getOrdinal() < right->getOrdinal(); }); } static void orderCallees(const CallGraphEdge::CalleeSetType &Callees, llvm::SmallVectorImpl<CallGraphNode *> &OrderedNodes) { for (auto *Node : Callees) OrderedNodes.push_back(Node); std::sort(OrderedNodes.begin(), OrderedNodes.end(), [](CallGraphNode *left, CallGraphNode *right) { return left->getOrdinal() < right->getOrdinal(); }); } void CallGraph::addEdgesForApply(FullApplySite AI, CallGraphNode *CallerNode) { CallGraphEdge::CalleeSetType CalleeSet; bool Complete = false; if (tryGetCalleeSet(AI.getCallee(), CalleeSet, Complete)) { auto *Edge = new (Allocator) CallGraphEdge(AI, CalleeSet, Complete, EdgeOrdinal++); assert(!ApplyToEdgeMap.count(AI) && "Added apply that already has an edge node!\n"); ApplyToEdgeMap[AI] = Edge; CallerNode->addCalleeEdge(Edge); llvm::SmallVector<CallGraphNode *, 4> OrderedNodes; orderCallees(CalleeSet, OrderedNodes); for (auto *CalleeNode : OrderedNodes) CalleeNode->addCallerEdge(Edge); // TODO: Compute this from the call graph itself after stripping // unreachable nodes from graph. ++NumAppliesWithEdges; return; } ++NumAppliesWithoutEdges; } void CallGraph::removeEdge(CallGraphEdge *Edge) { // Remove the edge from all the potential callee call graph nodes. auto &CalleeSet = Edge->getPartialCalleeSet(); for (auto *CalleeNode : CalleeSet) CalleeNode->removeCallerEdge(Edge); // Remove the edge from the caller's call graph node. auto Apply = Edge->getApply(); auto *CallerNode = getCallGraphNode(Apply.getFunction()); CallerNode->removeCalleeEdge(Edge); // Remove the mapping from the apply to this edge. ApplyToEdgeMap.erase(Apply); // Call the destructor for the edge. The memory will be reclaimed // when the call graph is deleted by virtue of the bump pointer // allocator. Edge->~CallGraphEdge(); } // Remove the call graph edges associated with an apply, where the // apply is known to the call graph. void CallGraph::removeEdgesForApply(FullApplySite AI) { assert(ApplyToEdgeMap.count(AI) && "Expected apply to be in edge map!"); removeEdge(ApplyToEdgeMap[AI]); } void CallGraph::markCallerEdgesOfCalleesIncomplete(FullApplySite AI) { auto *Edge = getCallGraphEdge(AI); // We are not guaranteed to have an edge for every apply. if (!Edge) return; for (auto *Node : Edge->getPartialCalleeSet()) Node->markCallerEdgesIncomplete(); } void CallGraph::addEdges(SILFunction *F) { auto *CallerNode = getCallGraphNode(F); assert(CallerNode && "Expected call graph node for function!"); for (auto &BB : *F) { for (auto &I : BB) { if (auto *AI = dyn_cast<ApplyInst>(&I)) { addEdgesForApply(AI, CallerNode); } if (auto *FRI = dyn_cast<FunctionRefInst>(&I)) { auto *CalleeFn = FRI->getReferencedFunction(); if (!CalleeFn->isPossiblyUsedExternally()) { bool hasAllApplyUsers = std::none_of(FRI->use_begin(), FRI->use_end(), [](const Operand *Op) { return !isa<ApplyInst>(Op->getUser()); }); // If we have a non-apply user of this function, mark its caller set // as being incomplete. if (!hasAllApplyUsers) { auto *CalleeNode = getCallGraphNode(CalleeFn); CalleeNode->markCallerEdgesIncomplete(); } } } } } } /// Finds SCCs in the call graph. Our call graph has an unconventional /// form where each edge of the graph is really a multi-edge that can /// point to multiple call graph nodes in the case where we can call /// one of several different functions. class CallGraphSCCFinder { unsigned NextDFSNum; llvm::SmallVectorImpl<CallGraphSCC *> &TheSCCs; llvm::DenseMap<CallGraphNode *, unsigned> DFSNum; llvm::DenseMap<CallGraphNode *, unsigned> MinDFSNum; llvm::SetVector<CallGraphNode *> DFSStack; /// The CallGraphSCCFinder does not own this bump ptr allocator, so does not /// call the destructor of objects allocated from it. llvm::BumpPtrAllocator &BPA; public: CallGraphSCCFinder(llvm::SmallVectorImpl<CallGraphSCC *> &TheSCCs, llvm::BumpPtrAllocator &BPA) : NextDFSNum(0), TheSCCs(TheSCCs), BPA(BPA) {} void DFS(CallGraphNode *Node) { // Set the DFSNum for this node if we haven't already, and if we // have, which indicates it's already been visited, return. if (!DFSNum.insert(std::make_pair(Node, NextDFSNum)).second) return; assert(MinDFSNum.find(Node) == MinDFSNum.end() && "Node should not already have a minimum DFS number!"); MinDFSNum[Node] = NextDFSNum; ++NextDFSNum; DFSStack.insert(Node); llvm::SmallVector<CallGraphEdge *, 4> OrderedEdges; orderEdges(Node->getCalleeEdges(), OrderedEdges); for (auto *ApplyEdge : OrderedEdges) { llvm::SmallVector<CallGraphNode *, 4> OrderedNodes; orderCallees(ApplyEdge->getPartialCalleeSet(), OrderedNodes); for (auto *CalleeNode : OrderedNodes) { if (DFSNum.find(CalleeNode) == DFSNum.end()) { DFS(CalleeNode); MinDFSNum[Node] = std::min(MinDFSNum[Node], MinDFSNum[CalleeNode]); } else if (DFSStack.count(CalleeNode)) { MinDFSNum[Node] = std::min(MinDFSNum[Node], DFSNum[CalleeNode]); } } } // If this node is the root of an SCC (including SCCs with a // single node), pop the SCC and push it on our SCC stack. if (DFSNum[Node] == MinDFSNum[Node]) { auto *SCC = new (BPA) CallGraphSCC(); CallGraphNode *Popped; do { Popped = DFSStack.pop_back_val(); SCC->SCCNodes.push_back(Popped); } while (Popped != Node); TheSCCs.push_back(SCC); } } }; void CallGraph::computeBottomUpSCCOrder() { if (!BottomUpSCCOrder.empty()) { for (auto *SCC : BottomUpSCCOrder) SCC->~CallGraphSCC(); BottomUpSCCOrder.clear(); } CallGraphSCCFinder SCCFinder(BottomUpSCCOrder, Allocator); for (auto *Node : getCallGraphRoots()) SCCFinder.DFS(Node); } void CallGraph::computeBottomUpFunctionOrder() { // We do not need to call any destructors here. BottomUpFunctionOrder.clear(); computeBottomUpSCCOrder(); for (auto *SCC : BottomUpSCCOrder) for (auto *Node : SCC->SCCNodes) BottomUpFunctionOrder.push_back(Node->getFunction()); } //===----------------------------------------------------------------------===// // CallGraph Verification //===----------------------------------------------------------------------===// void CallGraph::verify() const { #ifndef NDEBUG // For every function in the module, add it to our SILFunction set. llvm::DenseSet<SILFunction *> Functions; for (auto &F : M) Functions.insert(&F); // For every (SILFunction, CallGraphNode) pair FuncPair in the SILFunction to // CallGraphNode map check that: // // a. FuncPair.first is a SILFunction in the current module. // b. FuncPair.first is the SILFunction inside the CallGraphNode // FuncPair.second. // c. All callee CallGraphEdges mapped to FuncPair.second have ApplyInsts // which are in the SILFunction FuncPair.first. // for (auto &P : FunctionToNodeMap) { assert(Functions.count(P.first) && "Func in FunctionToNodeMap but not " "in module!?"); assert(P.second->getFunction() == P.first && "Func mapped to node, but node has different Function inside?!"); for (CallGraphEdge *Edge : P.second->getCalleeEdges()) { assert(Edge->getApply().getFunction() == P.first && "ApplyInst in callee set that is not in the Callee function?!"); } } // For every pair (ApplyInst, CallGraphEdge) ApplyPair in the Apply to // CallGraphEdge map, check that: // // a. ApplyPair.second.getApply() == ApplyPair.first. // b. ApplyPair.first->getFunction() is in the SILFunction to // CallGraphNode map and the CallGraphEdge for ApplyPair is one of // CallSiteEdges in the mapped to CallGraphNode. // for (auto &P : ApplyToEdgeMap) { assert(P.second->getApply() == P.first && "Apply mapped to CallSiteEdge but not vis-a-versa?!"); assert(Functions.count(P.first.getFunction()) && "Apply in func not in module?!"); CallGraphNode *Node = getCallGraphNode(P.first.getFunction()); assert(Node && "Apply without call graph node"); bool FoundEdge = false; for (CallGraphEdge *Edge : Node->getCalleeEdges()) { if (Edge == P.second) { FoundEdge = true; break; } } assert(FoundEdge && "Failed to find Apply CallGraphEdge in Apply inst " "parent function's caller"); } #endif } void CallGraphAnalysis::verify() const { #ifndef NDEBUG // If we don't have a callgraph, return. if (!CG) return; CG->verify(); #endif } <commit_msg>Update comments and assert messages in call graph verifier.<commit_after>//===----- CallGraphAnalysis.cpp - Call graph construction ----*- C++ -*---===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "swift/SILAnalysis/CallGraphAnalysis.h" #include "swift/Basic/Fallthrough.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/Statistic.h" #include <algorithm> #include <utility> using namespace swift; #define DEBUG_TYPE "call-graph" STATISTIC(NumCallGraphNodes, "# of call graph nodes created"); STATISTIC(NumAppliesWithEdges, "# of call sites with edges"); STATISTIC(NumAppliesWithoutEdges, "# of call sites without edges"); STATISTIC(NumAppliesOfBuiltins, "# of call sites calling builtins"); CallGraph::CallGraph(SILModule *Mod, bool completeModule) : M(*Mod) { // Build the initial call graph by creating a node for each // function, and an edge for each direct call to a free function. // TODO: Handle other kinds of applies. unsigned NodeOrdinal = 0; for (auto &F : M) addCallGraphNode(&F, NodeOrdinal++); EdgeOrdinal = 0; for (auto &F : M) if (F.isDefinition()) addEdges(&F); } CallGraph::~CallGraph() { // Clean up all call graph nodes. for (auto &P : FunctionToNodeMap) { P.second->~CallGraphNode(); } // Clean up all call graph edges. for (auto &P : ApplyToEdgeMap) { P.second->~CallGraphEdge(); } // Clean up all SCCs. for (CallGraphSCC *SCC : BottomUpSCCOrder) { SCC->~CallGraphSCC(); } } void CallGraph::addCallGraphNode(SILFunction *F, unsigned NodeOrdinal) { // TODO: Compute this from the call graph itself after stripping // unreachable nodes from graph. ++NumCallGraphNodes; auto *Node = new (Allocator) CallGraphNode(F, NodeOrdinal); assert(!FunctionToNodeMap.count(F) && "Added function already has a call graph node!"); FunctionToNodeMap[F] = Node; // TODO: Only add functions clearly visible from outside our // compilation scope as roots. if (F->isDefinition()) CallGraphRoots.push_back(Node); } bool CallGraph::tryGetCalleeSet(SILValue Callee, CallGraphEdge::CalleeSetType &CalleeSet, bool &Complete) { assert(CalleeSet.empty() && "Expected empty callee set!"); switch (Callee->getKind()) { case ValueKind::ThinToThickFunctionInst: Callee = cast<ThinToThickFunctionInst>(Callee)->getOperand(); SWIFT_FALLTHROUGH; case ValueKind::FunctionRefInst: { auto *CalleeFn = cast<FunctionRefInst>(Callee)->getReferencedFunction(); auto *CalleeNode = getCallGraphNode(CalleeFn); assert(CalleeNode && "Expected to have a call graph node for all functions!"); CalleeSet.insert(CalleeNode); Complete = true; return true; } case ValueKind::PartialApplyInst: return tryGetCalleeSet(cast<PartialApplyInst>(Callee)->getCallee(), CalleeSet, Complete); case ValueKind::DynamicMethodInst: // TODO: Decide how to handle these in graph construction and // analysis passes. We might just leave them out of the // graph. return false; case ValueKind::SILArgument: // First-pass call-graph construction will not do anything with // these, but a second pass can potentially statically determine // the called function in some cases. return false; case ValueKind::ApplyInst: // TODO: Probably not worth iterating invocation- then // reverse-invocation order to catch this. return false; case ValueKind::TupleExtractInst: // TODO: It would be good to tunnel through extracts so that we // can build a more accurate call graph prior to any // optimizations. return false; case ValueKind::StructExtractInst: // TODO: It would be good to tunnel through extracts so that we // can build a more accurate call graph prior to any // optimizations. return false; case ValueKind::BuiltinInst: ++NumAppliesOfBuiltins; return false; case ValueKind::WitnessMethodInst: { auto *WMI = cast<WitnessMethodInst>(Callee); SILFunction *CalleeFn; ArrayRef<Substitution> Subs; SILWitnessTable *WT; std::tie(CalleeFn, WT, Subs) = WMI->getModule().lookUpFunctionInWitnessTable(WMI->getConformance(), WMI->getMember()); if (!CalleeFn) return false; auto *CalleeNode = getCallGraphNode(CalleeFn); assert(CalleeNode && "Expected to have a call graph node for all functions!"); CalleeSet.insert(CalleeNode); Complete = true; return true; } case ValueKind::ClassMethodInst: case ValueKind::SuperMethodInst: // TODO: Each of these requires specific handling. return false; default: assert(!isa<MethodInst>(Callee) && "Unhandled method instruction in call graph construction!"); // There are cases where we will be very hard pressed to determine // what we are calling. return false; } } static void orderEdges(const llvm::SmallPtrSetImpl<CallGraphEdge *> &Edges, llvm::SmallVectorImpl<CallGraphEdge *> &OrderedEdges) { for (auto *Edge : Edges) OrderedEdges.push_back(Edge); std::sort(OrderedEdges.begin(), OrderedEdges.end(), [](CallGraphEdge *left, CallGraphEdge *right) { return left->getOrdinal() < right->getOrdinal(); }); } static void orderCallees(const CallGraphEdge::CalleeSetType &Callees, llvm::SmallVectorImpl<CallGraphNode *> &OrderedNodes) { for (auto *Node : Callees) OrderedNodes.push_back(Node); std::sort(OrderedNodes.begin(), OrderedNodes.end(), [](CallGraphNode *left, CallGraphNode *right) { return left->getOrdinal() < right->getOrdinal(); }); } void CallGraph::addEdgesForApply(FullApplySite AI, CallGraphNode *CallerNode) { CallGraphEdge::CalleeSetType CalleeSet; bool Complete = false; if (tryGetCalleeSet(AI.getCallee(), CalleeSet, Complete)) { auto *Edge = new (Allocator) CallGraphEdge(AI, CalleeSet, Complete, EdgeOrdinal++); assert(!ApplyToEdgeMap.count(AI) && "Added apply that already has an edge node!\n"); ApplyToEdgeMap[AI] = Edge; CallerNode->addCalleeEdge(Edge); llvm::SmallVector<CallGraphNode *, 4> OrderedNodes; orderCallees(CalleeSet, OrderedNodes); for (auto *CalleeNode : OrderedNodes) CalleeNode->addCallerEdge(Edge); // TODO: Compute this from the call graph itself after stripping // unreachable nodes from graph. ++NumAppliesWithEdges; return; } ++NumAppliesWithoutEdges; } void CallGraph::removeEdge(CallGraphEdge *Edge) { // Remove the edge from all the potential callee call graph nodes. auto &CalleeSet = Edge->getPartialCalleeSet(); for (auto *CalleeNode : CalleeSet) CalleeNode->removeCallerEdge(Edge); // Remove the edge from the caller's call graph node. auto Apply = Edge->getApply(); auto *CallerNode = getCallGraphNode(Apply.getFunction()); CallerNode->removeCalleeEdge(Edge); // Remove the mapping from the apply to this edge. ApplyToEdgeMap.erase(Apply); // Call the destructor for the edge. The memory will be reclaimed // when the call graph is deleted by virtue of the bump pointer // allocator. Edge->~CallGraphEdge(); } // Remove the call graph edges associated with an apply, where the // apply is known to the call graph. void CallGraph::removeEdgesForApply(FullApplySite AI) { assert(ApplyToEdgeMap.count(AI) && "Expected apply to be in edge map!"); removeEdge(ApplyToEdgeMap[AI]); } void CallGraph::markCallerEdgesOfCalleesIncomplete(FullApplySite AI) { auto *Edge = getCallGraphEdge(AI); // We are not guaranteed to have an edge for every apply. if (!Edge) return; for (auto *Node : Edge->getPartialCalleeSet()) Node->markCallerEdgesIncomplete(); } void CallGraph::addEdges(SILFunction *F) { auto *CallerNode = getCallGraphNode(F); assert(CallerNode && "Expected call graph node for function!"); for (auto &BB : *F) { for (auto &I : BB) { if (auto *AI = dyn_cast<ApplyInst>(&I)) { addEdgesForApply(AI, CallerNode); } if (auto *FRI = dyn_cast<FunctionRefInst>(&I)) { auto *CalleeFn = FRI->getReferencedFunction(); if (!CalleeFn->isPossiblyUsedExternally()) { bool hasAllApplyUsers = std::none_of(FRI->use_begin(), FRI->use_end(), [](const Operand *Op) { return !isa<ApplyInst>(Op->getUser()); }); // If we have a non-apply user of this function, mark its caller set // as being incomplete. if (!hasAllApplyUsers) { auto *CalleeNode = getCallGraphNode(CalleeFn); CalleeNode->markCallerEdgesIncomplete(); } } } } } } /// Finds SCCs in the call graph. Our call graph has an unconventional /// form where each edge of the graph is really a multi-edge that can /// point to multiple call graph nodes in the case where we can call /// one of several different functions. class CallGraphSCCFinder { unsigned NextDFSNum; llvm::SmallVectorImpl<CallGraphSCC *> &TheSCCs; llvm::DenseMap<CallGraphNode *, unsigned> DFSNum; llvm::DenseMap<CallGraphNode *, unsigned> MinDFSNum; llvm::SetVector<CallGraphNode *> DFSStack; /// The CallGraphSCCFinder does not own this bump ptr allocator, so does not /// call the destructor of objects allocated from it. llvm::BumpPtrAllocator &BPA; public: CallGraphSCCFinder(llvm::SmallVectorImpl<CallGraphSCC *> &TheSCCs, llvm::BumpPtrAllocator &BPA) : NextDFSNum(0), TheSCCs(TheSCCs), BPA(BPA) {} void DFS(CallGraphNode *Node) { // Set the DFSNum for this node if we haven't already, and if we // have, which indicates it's already been visited, return. if (!DFSNum.insert(std::make_pair(Node, NextDFSNum)).second) return; assert(MinDFSNum.find(Node) == MinDFSNum.end() && "Node should not already have a minimum DFS number!"); MinDFSNum[Node] = NextDFSNum; ++NextDFSNum; DFSStack.insert(Node); llvm::SmallVector<CallGraphEdge *, 4> OrderedEdges; orderEdges(Node->getCalleeEdges(), OrderedEdges); for (auto *ApplyEdge : OrderedEdges) { llvm::SmallVector<CallGraphNode *, 4> OrderedNodes; orderCallees(ApplyEdge->getPartialCalleeSet(), OrderedNodes); for (auto *CalleeNode : OrderedNodes) { if (DFSNum.find(CalleeNode) == DFSNum.end()) { DFS(CalleeNode); MinDFSNum[Node] = std::min(MinDFSNum[Node], MinDFSNum[CalleeNode]); } else if (DFSStack.count(CalleeNode)) { MinDFSNum[Node] = std::min(MinDFSNum[Node], DFSNum[CalleeNode]); } } } // If this node is the root of an SCC (including SCCs with a // single node), pop the SCC and push it on our SCC stack. if (DFSNum[Node] == MinDFSNum[Node]) { auto *SCC = new (BPA) CallGraphSCC(); CallGraphNode *Popped; do { Popped = DFSStack.pop_back_val(); SCC->SCCNodes.push_back(Popped); } while (Popped != Node); TheSCCs.push_back(SCC); } } }; void CallGraph::computeBottomUpSCCOrder() { if (!BottomUpSCCOrder.empty()) { for (auto *SCC : BottomUpSCCOrder) SCC->~CallGraphSCC(); BottomUpSCCOrder.clear(); } CallGraphSCCFinder SCCFinder(BottomUpSCCOrder, Allocator); for (auto *Node : getCallGraphRoots()) SCCFinder.DFS(Node); } void CallGraph::computeBottomUpFunctionOrder() { // We do not need to call any destructors here. BottomUpFunctionOrder.clear(); computeBottomUpSCCOrder(); for (auto *SCC : BottomUpSCCOrder) for (auto *Node : SCC->SCCNodes) BottomUpFunctionOrder.push_back(Node->getFunction()); } //===----------------------------------------------------------------------===// // CallGraph Verification //===----------------------------------------------------------------------===// void CallGraph::verify() const { #ifndef NDEBUG // For every function in the module, add it to our SILFunction set. llvm::DenseSet<SILFunction *> Functions; for (auto &F : M) Functions.insert(&F); // For every pair (SILFunction, CallGraphNode) in the // function-to-node map, verify: // // a. The function is in the current module. // b. The call graph node is for that same function. // c. All the callee edges of the node have an apply that lives // in that function. // for (auto &P : FunctionToNodeMap) { assert(Functions.count(P.first) && "Function in call graph but not in module!?"); assert(P.second->getFunction() == P.first && "Func mapped to node, but node has different Function inside?!"); for (CallGraphEdge *Edge : P.second->getCalleeEdges()) { assert(Edge->getApply().getFunction() == P.first && "Apply in callee set that is not in the callee function?!"); } } // For every pair (FullApplySite, CallGraphEdge) in the apply-to-edge // map, verify: // // a. The edge's apply is identical to the map key that maps // to the edge. // b. The apply is in a function in the module. // c. That function has a call graph node. // d. The edge is one of the callee edges of that call graph node. // for (auto &P : ApplyToEdgeMap) { assert(P.second->getApply() == P.first && "Apply mapped to CallSiteEdge but not vis-a-versa?!"); assert(Functions.count(P.first.getFunction()) && "Apply in func not in module?!"); CallGraphNode *Node = getCallGraphNode(P.first.getFunction()); assert(Node && "Apply without call graph node"); bool FoundEdge = false; for (CallGraphEdge *Edge : Node->getCalleeEdges()) { if (Edge == P.second) { FoundEdge = true; break; } } assert(FoundEdge && "Failed to find Apply CallGraphEdge in Apply inst " "parent function's caller"); } #endif } void CallGraphAnalysis::verify() const { #ifndef NDEBUG // If we don't have a callgraph, return. if (!CG) return; CG->verify(); #endif } <|endoftext|>
<commit_before>//===- DivRemPairs.cpp - Hoist/decompose division and remainder -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass hoists and/or decomposes integer division and remainder // instructions to enable CFG improvements and better codegen. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/DivRemPairs.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Function.h" #include "llvm/Pass.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/BypassSlowDivision.h" using namespace llvm; #define DEBUG_TYPE "div-rem-pairs" STATISTIC(NumPairs, "Number of div/rem pairs"); STATISTIC(NumHoisted, "Number of instructions hoisted"); STATISTIC(NumDecomposed, "Number of instructions decomposed"); /// Find matching pairs of integer div/rem ops (they have the same numerator, /// denominator, and signedness). If they exist in different basic blocks, bring /// them together by hoisting or replace the common division operation that is /// implicit in the remainder: /// X % Y <--> X - ((X / Y) * Y). /// /// We can largely ignore the normal safety and cost constraints on speculation /// of these ops when we find a matching pair. This is because we are already /// guaranteed that any exceptions and most cost are already incurred by the /// first member of the pair. /// /// Note: This transform could be an oddball enhancement to EarlyCSE, GVN, or /// SimplifyCFG, but it's split off on its own because it's different enough /// that it doesn't quite match the stated objectives of those passes. static bool optimizeDivRem(Function &F, const TargetTransformInfo &TTI, const DominatorTree &DT) { bool Changed = false; // Insert all divide and remainder instructions into maps keyed by their // operands and opcode (signed or unsigned). DenseMap<DivRemMapKey, Instruction *> DivMap, RemMap; for (auto &BB : F) { for (auto &I : BB) { if (I.getOpcode() == Instruction::SDiv) DivMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I; else if (I.getOpcode() == Instruction::UDiv) DivMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I; else if (I.getOpcode() == Instruction::SRem) RemMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I; else if (I.getOpcode() == Instruction::URem) RemMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I; } } // We can iterate over either map because we are only looking for matched // pairs. Choose remainders for efficiency because they are usually even more // rare than division. for (auto &RemPair : RemMap) { // Find the matching division instruction from the division map. Instruction *DivInst = DivMap[RemPair.getFirst()]; if (!DivInst) continue; // We have a matching pair of div/rem instructions. If one dominates the // other, hoist and/or replace one. NumPairs++; Instruction *RemInst = RemPair.getSecond(); bool IsSigned = DivInst->getOpcode() == Instruction::SDiv; bool HasDivRemOp = TTI.hasDivRemOp(DivInst->getType(), IsSigned); // If the target supports div+rem and the instructions are in the same block // already, there's nothing to do. The backend should handle this. If the // target does not support div+rem, then we will decompose the rem. if (HasDivRemOp && RemInst->getParent() == DivInst->getParent()) continue; bool DivDominates = DT.dominates(DivInst, RemInst); if (!DivDominates && !DT.dominates(RemInst, DivInst)) continue; if (HasDivRemOp) { // The target has a single div/rem operation. Hoist the lower instruction // to make the matched pair visible to the backend. if (DivDominates) RemInst->moveAfter(DivInst); else DivInst->moveAfter(RemInst); NumHoisted++; } else { // The target does not have a single div/rem operation. Decompose the // remainder calculation as: // X % Y --> X - ((X / Y) * Y). Value *X = RemInst->getOperand(0); Value *Y = RemInst->getOperand(1); Instruction *Mul = BinaryOperator::CreateMul(DivInst, Y); Instruction *Sub = BinaryOperator::CreateSub(X, Mul); // If the remainder dominates, then hoist the division up to that block: // // bb1: // %rem = srem %x, %y // bb2: // %div = sdiv %x, %y // --> // bb1: // %div = sdiv %x, %y // %mul = mul %div, %y // %rem = sub %x, %mul // // If the division dominates, it's already in the right place. The mul+sub // will be in a different block because we don't assume that they are // cheap to speculatively execute: // // bb1: // %div = sdiv %x, %y // bb2: // %rem = srem %x, %y // --> // bb1: // %div = sdiv %x, %y // bb2: // %mul = mul %div, %y // %rem = sub %x, %mul // // If the div and rem are in the same block, we do the same transform, // but any code movement would be within the same block. if (!DivDominates) DivInst->moveBefore(RemInst); Mul->insertAfter(RemInst); Sub->insertAfter(Mul); // Now kill the explicit remainder. We have replaced it with: // (sub X, (mul (div X, Y), Y) RemInst->replaceAllUsesWith(Sub); RemInst->eraseFromParent(); NumDecomposed++; } Changed = true; } return Changed; } // Pass manager boilerplate below here. namespace { struct DivRemPairsLegacyPass : public FunctionPass { static char ID; DivRemPairsLegacyPass() : FunctionPass(ID) { initializeDivRemPairsLegacyPassPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<DominatorTreeWrapperPass>(); AU.addRequired<TargetTransformInfoWrapperPass>(); AU.setPreservesCFG(); AU.addPreserved<DominatorTreeWrapperPass>(); AU.addPreserved<GlobalsAAWrapperPass>(); FunctionPass::getAnalysisUsage(AU); } bool runOnFunction(Function &F) override { if (skipFunction(F)) return false; auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); return optimizeDivRem(F, TTI, DT); } }; } char DivRemPairsLegacyPass::ID = 0; INITIALIZE_PASS_BEGIN(DivRemPairsLegacyPass, "div-rem-pairs", "Hoist/decompose integer division and remainder", false, false) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_END(DivRemPairsLegacyPass, "div-rem-pairs", "Hoist/decompose integer division and remainder", false, false) FunctionPass *llvm::createDivRemPairsPass() { return new DivRemPairsLegacyPass(); } PreservedAnalyses DivRemPairsPass::run(Function &F, FunctionAnalysisManager &FAM) { TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F); DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F); if (!optimizeDivRem(F, TTI, DT)) return PreservedAnalyses::all(); // TODO: This pass just hoists/replaces math ops - all analyses are preserved? PreservedAnalyses PA; PA.preserveSet<CFGAnalyses>(); PA.preserve<GlobalsAA>(); return PA; } <commit_msg>Merging r330792:<commit_after>//===- DivRemPairs.cpp - Hoist/decompose division and remainder -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass hoists and/or decomposes integer division and remainder // instructions to enable CFG improvements and better codegen. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/DivRemPairs.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Function.h" #include "llvm/Pass.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/BypassSlowDivision.h" using namespace llvm; #define DEBUG_TYPE "div-rem-pairs" STATISTIC(NumPairs, "Number of div/rem pairs"); STATISTIC(NumHoisted, "Number of instructions hoisted"); STATISTIC(NumDecomposed, "Number of instructions decomposed"); /// Find matching pairs of integer div/rem ops (they have the same numerator, /// denominator, and signedness). If they exist in different basic blocks, bring /// them together by hoisting or replace the common division operation that is /// implicit in the remainder: /// X % Y <--> X - ((X / Y) * Y). /// /// We can largely ignore the normal safety and cost constraints on speculation /// of these ops when we find a matching pair. This is because we are already /// guaranteed that any exceptions and most cost are already incurred by the /// first member of the pair. /// /// Note: This transform could be an oddball enhancement to EarlyCSE, GVN, or /// SimplifyCFG, but it's split off on its own because it's different enough /// that it doesn't quite match the stated objectives of those passes. static bool optimizeDivRem(Function &F, const TargetTransformInfo &TTI, const DominatorTree &DT) { bool Changed = false; // Insert all divide and remainder instructions into maps keyed by their // operands and opcode (signed or unsigned). DenseMap<DivRemMapKey, Instruction *> DivMap; // Use a MapVector for RemMap so that instructions are moved/inserted in a // deterministic order. MapVector<DivRemMapKey, Instruction *> RemMap; for (auto &BB : F) { for (auto &I : BB) { if (I.getOpcode() == Instruction::SDiv) DivMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I; else if (I.getOpcode() == Instruction::UDiv) DivMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I; else if (I.getOpcode() == Instruction::SRem) RemMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I; else if (I.getOpcode() == Instruction::URem) RemMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I; } } // We can iterate over either map because we are only looking for matched // pairs. Choose remainders for efficiency because they are usually even more // rare than division. for (auto &RemPair : RemMap) { // Find the matching division instruction from the division map. Instruction *DivInst = DivMap[RemPair.first]; if (!DivInst) continue; // We have a matching pair of div/rem instructions. If one dominates the // other, hoist and/or replace one. NumPairs++; Instruction *RemInst = RemPair.second; bool IsSigned = DivInst->getOpcode() == Instruction::SDiv; bool HasDivRemOp = TTI.hasDivRemOp(DivInst->getType(), IsSigned); // If the target supports div+rem and the instructions are in the same block // already, there's nothing to do. The backend should handle this. If the // target does not support div+rem, then we will decompose the rem. if (HasDivRemOp && RemInst->getParent() == DivInst->getParent()) continue; bool DivDominates = DT.dominates(DivInst, RemInst); if (!DivDominates && !DT.dominates(RemInst, DivInst)) continue; if (HasDivRemOp) { // The target has a single div/rem operation. Hoist the lower instruction // to make the matched pair visible to the backend. if (DivDominates) RemInst->moveAfter(DivInst); else DivInst->moveAfter(RemInst); NumHoisted++; } else { // The target does not have a single div/rem operation. Decompose the // remainder calculation as: // X % Y --> X - ((X / Y) * Y). Value *X = RemInst->getOperand(0); Value *Y = RemInst->getOperand(1); Instruction *Mul = BinaryOperator::CreateMul(DivInst, Y); Instruction *Sub = BinaryOperator::CreateSub(X, Mul); // If the remainder dominates, then hoist the division up to that block: // // bb1: // %rem = srem %x, %y // bb2: // %div = sdiv %x, %y // --> // bb1: // %div = sdiv %x, %y // %mul = mul %div, %y // %rem = sub %x, %mul // // If the division dominates, it's already in the right place. The mul+sub // will be in a different block because we don't assume that they are // cheap to speculatively execute: // // bb1: // %div = sdiv %x, %y // bb2: // %rem = srem %x, %y // --> // bb1: // %div = sdiv %x, %y // bb2: // %mul = mul %div, %y // %rem = sub %x, %mul // // If the div and rem are in the same block, we do the same transform, // but any code movement would be within the same block. if (!DivDominates) DivInst->moveBefore(RemInst); Mul->insertAfter(RemInst); Sub->insertAfter(Mul); // Now kill the explicit remainder. We have replaced it with: // (sub X, (mul (div X, Y), Y) RemInst->replaceAllUsesWith(Sub); RemInst->eraseFromParent(); NumDecomposed++; } Changed = true; } return Changed; } // Pass manager boilerplate below here. namespace { struct DivRemPairsLegacyPass : public FunctionPass { static char ID; DivRemPairsLegacyPass() : FunctionPass(ID) { initializeDivRemPairsLegacyPassPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<DominatorTreeWrapperPass>(); AU.addRequired<TargetTransformInfoWrapperPass>(); AU.setPreservesCFG(); AU.addPreserved<DominatorTreeWrapperPass>(); AU.addPreserved<GlobalsAAWrapperPass>(); FunctionPass::getAnalysisUsage(AU); } bool runOnFunction(Function &F) override { if (skipFunction(F)) return false; auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); return optimizeDivRem(F, TTI, DT); } }; } char DivRemPairsLegacyPass::ID = 0; INITIALIZE_PASS_BEGIN(DivRemPairsLegacyPass, "div-rem-pairs", "Hoist/decompose integer division and remainder", false, false) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_END(DivRemPairsLegacyPass, "div-rem-pairs", "Hoist/decompose integer division and remainder", false, false) FunctionPass *llvm::createDivRemPairsPass() { return new DivRemPairsLegacyPass(); } PreservedAnalyses DivRemPairsPass::run(Function &F, FunctionAnalysisManager &FAM) { TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F); DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F); if (!optimizeDivRem(F, TTI, DT)) return PreservedAnalyses::all(); // TODO: This pass just hoists/replaces math ops - all analyses are preserved? PreservedAnalyses PA; PA.preserveSet<CFGAnalyses>(); PA.preserve<GlobalsAA>(); return PA; } <|endoftext|>
<commit_before> // .\Release\x64\benchmarks.exe --benchmark_repetitions=10 --benchmark_min_time=2 --benchmark_filter=Geopotential // NOLINT(whitespace/line_length) #include "physics/geopotential_body.hpp" #include <random> #include <vector> #include "astronomy/fortran_astrodynamics_toolkit.hpp" #include "astronomy/frames.hpp" #include "base/not_null.hpp" #include "benchmark/benchmark.h" #include "geometry/grassmann.hpp" #include "geometry/named_quantities.hpp" #include "geometry/r3_element.hpp" #include "numerics/fixed_arrays.hpp" #include "numerics/legendre.hpp" #include "physics/solar_system.hpp" #include "quantities/named_quantities.hpp" #include "quantities/parser.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" namespace principia { namespace physics { using astronomy::ICRS; using astronomy::ITRS; using base::not_null; using geometry::Displacement; using geometry::Instant; using geometry::R3Element; using geometry::Vector; using numerics::FixedMatrix; using numerics::LegendreNormalizationFactor; using physics::SolarSystem; using quantities::Acceleration; using quantities::Angle; using quantities::Exponentiation; using quantities::GravitationalParameter; using quantities::Length; using quantities::ParseQuantity; using quantities::Pow; using quantities::Quotient; using quantities::SIUnit; using quantities::Sqrt; using quantities::si::Degree; using quantities::si::Metre; using quantities::si::Radian; using quantities::si::Second; template<typename Frame> Vector<Quotient<Acceleration, GravitationalParameter>, Frame> GeneralSphericalHarmonicsAccelerationCpp( Geopotential<Frame> const& geopotential, Instant const& t, Displacement<Frame> const& r) { auto const r² = r.Norm²(); auto const r_norm = Sqrt(r²); auto const one_over_r³ = r_norm / (r² * r²); return geopotential.GeneralSphericalHarmonicsAcceleration( t, r, r_norm, r², one_over_r³); } // For fairness, the Fortran implementation is wrapped to have the same API as // the C++ one. template<typename Frame, int degree, int order> Vector<Quotient<Acceleration, GravitationalParameter>, Frame> GeneralSphericalHarmonicsAccelerationF90( not_null<OblateBody<Frame> const*> const body, double const mu, double const rbar, FixedMatrix<double, degree + 1, order + 1> const& cnm, FixedMatrix<double, degree + 1, order + 1> const& snm, Instant const& t, Displacement<Frame> const& r) { struct SurfaceFrame; auto const from_surface_frame = body->template FromSurfaceFrame<SurfaceFrame>(t); auto const to_surface_frame = from_surface_frame.Inverse(); Displacement<SurfaceFrame> const r_surface = to_surface_frame(r); auto const acceleration_surface = Vector<Quotient<Acceleration, GravitationalParameter>, SurfaceFrame>( SIUnit<Quotient<Acceleration, GravitationalParameter>>() * astronomy::fortran_astrodynamics_toolkit:: ComputeGravityAccelerationLear<degree, order>( r_surface.coordinates() / Metre, mu, rbar, cnm, snm)); return from_surface_frame(acceleration_surface); } OblateBody<ICRS> MakeEarthBody(SolarSystem<ICRS>& solar_system, int const max_degree) { solar_system.LimitOblatenessToDegree("Earth", max_degree); auto earth_message = solar_system.gravity_model_message("Earth"); Angle const earth_right_ascension_of_pole = 0 * Degree; Angle const earth_declination_of_pole = 90 * Degree; auto const earth_μ = solar_system.gravitational_parameter("Earth"); auto const earth_reference_radius = ParseQuantity<Length>(earth_message.reference_radius()); MassiveBody::Parameters const massive_body_parameters(earth_μ); RotatingBody<ICRS>::Parameters rotating_body_parameters( /*mean_radius=*/solar_system.mean_radius("Earth"), /*reference_angle=*/0 * Radian, /*reference_instant=*/Instant(), /*angular_frequency=*/1 * Radian / Second, earth_right_ascension_of_pole, earth_declination_of_pole); return OblateBody<ICRS>( massive_body_parameters, rotating_body_parameters, OblateBody<ICRS>::Parameters::ReadFromMessage( earth_message.geopotential(), earth_reference_radius)); } void BM_ComputeGeopotentialCpp(benchmark::State& state) { int const max_degree = state.range_x(); SolarSystem<ICRS> solar_system_2000( SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt", SOLUTION_DIR / "astronomy" / "sol_initial_state_jd_2451545_000000000.proto.txt"); auto const earth = MakeEarthBody(solar_system_2000, max_degree); Geopotential<ICRS> const geopotential(&earth, /*tolerance=*/0); std::mt19937_64 random(42); std::uniform_real_distribution<> distribution(-1e7, 1e7); std::vector<Displacement<ICRS>> displacements; for (int i = 0; i < 1e3; ++i) { displacements.push_back(earth.FromSurfaceFrame<ITRS>(Instant())( Displacement<ITRS>({distribution(random) * Metre, distribution(random) * Metre, distribution(random) * Metre}))); } while (state.KeepRunning()) { Vector<Exponentiation<Length, -2>, ICRS> acceleration; for (auto const& displacement : displacements) { acceleration = GeneralSphericalHarmonicsAccelerationCpp( geopotential, Instant(), displacement); } benchmark::DoNotOptimize(acceleration); } } #define PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(d) \ case (d): { \ numerics::FixedMatrix<double, (d) + 1, (d) + 1> cnm; \ numerics::FixedMatrix<double, (d) + 1, (d) + 1> snm; \ for (int n = 0; n <= (d); ++n) { \ for (int m = 0; m <= n; ++m) { \ cnm[n][m] = earth.cos()[n][m] * LegendreNormalizationFactor(n, m); \ snm[n][m] = earth.sin()[n][m] * LegendreNormalizationFactor(n, m); \ } \ } \ while (state.KeepRunning()) { \ Vector<Exponentiation<Length, -2>, ICRS> acceleration; \ for (auto const& displacement : displacements) { \ acceleration = \ GeneralSphericalHarmonicsAccelerationF90<ICRS, (d), (d)>( \ &earth, mu, rbar, cnm, snm, Instant(), displacement); \ } \ benchmark::DoNotOptimize(acceleration); \ } \ break; \ } void BM_ComputeGeopotentialF90(benchmark::State& state) { int const max_degree = state.range_x(); SolarSystem<ICRS> solar_system_2000( SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt", SOLUTION_DIR / "astronomy" / "sol_initial_state_jd_2451545_000000000.proto.txt"); auto const earth = MakeEarthBody(solar_system_2000, max_degree); double mu = earth.gravitational_parameter() / SIUnit<GravitationalParameter>(); double rbar = earth.reference_radius() / Metre; std::mt19937_64 random(42); std::uniform_real_distribution<> distribution(-1e7, 1e7); std::vector<Displacement<ICRS>> displacements; for (int i = 0; i < 1e3; ++i) { displacements.push_back(earth.FromSurfaceFrame<ITRS>(Instant())( Displacement<ITRS>({distribution(random) * Metre, distribution(random) * Metre, distribution(random) * Metre}))); } switch (max_degree) { PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(2); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(3); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(4); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(5); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(6); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(7); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(8); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(9); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(10); } } #undef PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90 BENCHMARK(BM_ComputeGeopotentialCpp)->Arg(2)->Arg(3)->Arg(5)->Arg(10); BENCHMARK(BM_ComputeGeopotentialF90)->Arg(2)->Arg(3)->Arg(5)->Arg(10); } // namespace physics } // namespace principia <commit_msg>A benchmark by distance.<commit_after> // .\Release\x64\benchmarks.exe --benchmark_repetitions=10 --benchmark_min_time=2 --benchmark_filter=Geopotential // NOLINT(whitespace/line_length) #include "physics/geopotential_body.hpp" #include <random> #include <vector> #include "astronomy/fortran_astrodynamics_toolkit.hpp" #include "astronomy/frames.hpp" #include "base/not_null.hpp" #include "benchmark/benchmark.h" #include "geometry/grassmann.hpp" #include "geometry/named_quantities.hpp" #include "geometry/r3_element.hpp" #include "numerics/fixed_arrays.hpp" #include "numerics/legendre.hpp" #include "physics/solar_system.hpp" #include "quantities/named_quantities.hpp" #include "quantities/parser.hpp" #include "quantities/quantities.hpp" #include "quantities/si.hpp" namespace principia { namespace physics { using astronomy::ICRS; using astronomy::ITRS; using base::not_null; using geometry::Displacement; using geometry::Instant; using geometry::R3Element; using geometry::Vector; using numerics::FixedMatrix; using numerics::LegendreNormalizationFactor; using physics::SolarSystem; using quantities::Acceleration; using quantities::Angle; using quantities::Exponentiation; using quantities::GravitationalParameter; using quantities::Length; using quantities::ParseQuantity; using quantities::Pow; using quantities::Quotient; using quantities::SIUnit; using quantities::Sqrt; using quantities::si::Degree; using quantities::si::Kilo; using quantities::si::Metre; using quantities::si::Radian; using quantities::si::Second; template<typename Frame> Vector<Quotient<Acceleration, GravitationalParameter>, Frame> GeneralSphericalHarmonicsAccelerationCpp( Geopotential<Frame> const& geopotential, Instant const& t, Displacement<Frame> const& r) { auto const r² = r.Norm²(); auto const r_norm = Sqrt(r²); auto const one_over_r³ = r_norm / (r² * r²); return geopotential.GeneralSphericalHarmonicsAcceleration( t, r, r_norm, r², one_over_r³); } // For fairness, the Fortran implementation is wrapped to have the same API as // the C++ one. template<typename Frame, int degree, int order> Vector<Quotient<Acceleration, GravitationalParameter>, Frame> GeneralSphericalHarmonicsAccelerationF90( not_null<OblateBody<Frame> const*> const body, double const mu, double const rbar, FixedMatrix<double, degree + 1, order + 1> const& cnm, FixedMatrix<double, degree + 1, order + 1> const& snm, Instant const& t, Displacement<Frame> const& r) { struct SurfaceFrame; auto const from_surface_frame = body->template FromSurfaceFrame<SurfaceFrame>(t); auto const to_surface_frame = from_surface_frame.Inverse(); Displacement<SurfaceFrame> const r_surface = to_surface_frame(r); auto const acceleration_surface = Vector<Quotient<Acceleration, GravitationalParameter>, SurfaceFrame>( SIUnit<Quotient<Acceleration, GravitationalParameter>>() * astronomy::fortran_astrodynamics_toolkit:: ComputeGravityAccelerationLear<degree, order>( r_surface.coordinates() / Metre, mu, rbar, cnm, snm)); return from_surface_frame(acceleration_surface); } OblateBody<ICRS> MakeEarthBody(SolarSystem<ICRS>& solar_system, int const max_degree) { solar_system.LimitOblatenessToDegree("Earth", max_degree); auto earth_message = solar_system.gravity_model_message("Earth"); Angle const earth_right_ascension_of_pole = 0 * Degree; Angle const earth_declination_of_pole = 90 * Degree; auto const earth_μ = solar_system.gravitational_parameter("Earth"); auto const earth_reference_radius = ParseQuantity<Length>(earth_message.reference_radius()); MassiveBody::Parameters const massive_body_parameters(earth_μ); RotatingBody<ICRS>::Parameters rotating_body_parameters( /*mean_radius=*/solar_system.mean_radius("Earth"), /*reference_angle=*/0 * Radian, /*reference_instant=*/Instant(), /*angular_frequency=*/1 * Radian / Second, earth_right_ascension_of_pole, earth_declination_of_pole); return OblateBody<ICRS>( massive_body_parameters, rotating_body_parameters, OblateBody<ICRS>::Parameters::ReadFromMessage( earth_message.geopotential(), earth_reference_radius)); } void BM_ComputeGeopotentialCpp(benchmark::State& state) { int const max_degree = state.range(0); SolarSystem<ICRS> solar_system_2000( SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt", SOLUTION_DIR / "astronomy" / "sol_initial_state_jd_2451545_000000000.proto.txt"); auto const earth = MakeEarthBody(solar_system_2000, max_degree); Geopotential<ICRS> const geopotential(&earth, /*tolerance=*/0); std::mt19937_64 random(42); std::uniform_real_distribution<> distribution(-1e7, 1e7); std::vector<Displacement<ICRS>> displacements; for (int i = 0; i < 1e3; ++i) { displacements.push_back(earth.FromSurfaceFrame<ITRS>(Instant())( Displacement<ITRS>({distribution(random) * Metre, distribution(random) * Metre, distribution(random) * Metre}))); } while (state.KeepRunning()) { Vector<Exponentiation<Length, -2>, ICRS> acceleration; for (auto const& displacement : displacements) { acceleration = GeneralSphericalHarmonicsAccelerationCpp( geopotential, Instant(), displacement); } benchmark::DoNotOptimize(acceleration); } } void BM_ComputeGeopotentialDistance(benchmark::State& state) { // Check the performance around this distance. May be used to tell apart the // various contributions. double const distance_in_kilometres = state.range(0); SolarSystem<ICRS> solar_system_2000( SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt", SOLUTION_DIR / "astronomy" / "sol_initial_state_jd_2451545_000000000.proto.txt"); auto const earth = MakeEarthBody(solar_system_2000, /*max_degree=*/10); Geopotential<ICRS> const geopotential(&earth, /*tolerance=*/0x1.0p-24); std::mt19937_64 random(42); std::uniform_real_distribution<> distribution(0.9 * distance_in_kilometres, 1.1 * distance_in_kilometres); std::vector<Displacement<ICRS>> displacements; for (int i = 0; i < 1e3; ++i) { displacements.push_back(earth.FromSurfaceFrame<ITRS>(Instant())( Displacement<ITRS>({distribution(random) * Kilo(Metre), distribution(random) * Kilo(Metre), distribution(random) * Kilo(Metre)}))); } while (state.KeepRunning()) { Vector<Exponentiation<Length, -2>, ICRS> acceleration; for (auto const& displacement : displacements) { acceleration = GeneralSphericalHarmonicsAccelerationCpp( geopotential, Instant(), displacement); } benchmark::DoNotOptimize(acceleration); } } #define PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(d) \ case (d): { \ numerics::FixedMatrix<double, (d) + 1, (d) + 1> cnm; \ numerics::FixedMatrix<double, (d) + 1, (d) + 1> snm; \ for (int n = 0; n <= (d); ++n) { \ for (int m = 0; m <= n; ++m) { \ cnm[n][m] = earth.cos()[n][m] * LegendreNormalizationFactor(n, m); \ snm[n][m] = earth.sin()[n][m] * LegendreNormalizationFactor(n, m); \ } \ } \ while (state.KeepRunning()) { \ Vector<Exponentiation<Length, -2>, ICRS> acceleration; \ for (auto const& displacement : displacements) { \ acceleration = \ GeneralSphericalHarmonicsAccelerationF90<ICRS, (d), (d)>( \ &earth, mu, rbar, cnm, snm, Instant(), displacement); \ } \ benchmark::DoNotOptimize(acceleration); \ } \ break; \ } void BM_ComputeGeopotentialF90(benchmark::State& state) { int const max_degree = state.range(0); SolarSystem<ICRS> solar_system_2000( SOLUTION_DIR / "astronomy" / "sol_gravity_model.proto.txt", SOLUTION_DIR / "astronomy" / "sol_initial_state_jd_2451545_000000000.proto.txt"); auto const earth = MakeEarthBody(solar_system_2000, max_degree); double mu = earth.gravitational_parameter() / SIUnit<GravitationalParameter>(); double rbar = earth.reference_radius() / Metre; std::mt19937_64 random(42); std::uniform_real_distribution<> distribution(-1e7, 1e7); std::vector<Displacement<ICRS>> displacements; for (int i = 0; i < 1e3; ++i) { displacements.push_back(earth.FromSurfaceFrame<ITRS>(Instant())( Displacement<ITRS>({distribution(random) * Metre, distribution(random) * Metre, distribution(random) * Metre}))); } switch (max_degree) { PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(2); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(3); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(4); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(5); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(6); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(7); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(8); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(9); PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90(10); } } #undef PRINCIPIA_CASE_COMPUTE_GEOPOTENTIAL_F90 BENCHMARK(BM_ComputeGeopotentialCpp)->Arg(2)->Arg(3)->Arg(5)->Arg(10); BENCHMARK(BM_ComputeGeopotentialF90)->Arg(2)->Arg(3)->Arg(5)->Arg(10); BENCHMARK(BM_ComputeGeopotentialDistance) ->Arg(80'000) // C₂₂, S₂₂, J₂. ->Arg(500'000) // J₂. ->Arg(5'000'000); // Central } // namespace physics } // namespace principia <|endoftext|>
<commit_before>//===- DivRemPairs.cpp - Hoist/decompose division and remainder -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass hoists and/or decomposes integer division and remainder // instructions to enable CFG improvements and better codegen. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/DivRemPairs.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Function.h" #include "llvm/Pass.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/BypassSlowDivision.h" using namespace llvm; #define DEBUG_TYPE "div-rem-pairs" STATISTIC(NumPairs, "Number of div/rem pairs"); STATISTIC(NumHoisted, "Number of instructions hoisted"); STATISTIC(NumDecomposed, "Number of instructions decomposed"); /// Find matching pairs of integer div/rem ops (they have the same numerator, /// denominator, and signedness). If they exist in different basic blocks, bring /// them together by hoisting or replace the common division operation that is /// implicit in the remainder: /// X % Y <--> X - ((X / Y) * Y). /// /// We can largely ignore the normal safety and cost constraints on speculation /// of these ops when we find a matching pair. This is because we are already /// guaranteed that any exceptions and most cost are already incurred by the /// first member of the pair. /// /// Note: This transform could be an oddball enhancement to EarlyCSE, GVN, or /// SimplifyCFG, but it's split off on its own because it's different enough /// that it doesn't quite match the stated objectives of those passes. static bool optimizeDivRem(Function &F, const TargetTransformInfo &TTI, const DominatorTree &DT) { bool Changed = false; // Insert all divide and remainder instructions into maps keyed by their // operands and opcode (signed or unsigned). DenseMap<DivRemMapKey, Instruction *> DivMap, RemMap; for (auto &BB : F) { for (auto &I : BB) { if (I.getOpcode() == Instruction::SDiv) DivMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I; else if (I.getOpcode() == Instruction::UDiv) DivMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I; else if (I.getOpcode() == Instruction::SRem) RemMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I; else if (I.getOpcode() == Instruction::URem) RemMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I; } } // We can iterate over either map because we are only looking for matched // pairs. Choose remainders for efficiency because they are usually even more // rare than division. for (auto &RemPair : RemMap) { // Find the matching division instruction from the division map. Instruction *DivInst = DivMap[RemPair.getFirst()]; if (!DivInst) continue; // We have a matching pair of div/rem instructions. If one dominates the // other, hoist and/or replace one. NumPairs++; Instruction *RemInst = RemPair.getSecond(); bool IsSigned = DivInst->getOpcode() == Instruction::SDiv; bool HasDivRemOp = TTI.hasDivRemOp(DivInst->getType(), IsSigned); // If the target supports div+rem and the instructions are in the same block // already, there's nothing to do. The backend should handle this. If the // target does not support div+rem, then we will decompose the rem. if (HasDivRemOp && RemInst->getParent() == DivInst->getParent()) continue; bool DivDominates = DT.dominates(DivInst, RemInst); if (!DivDominates && !DT.dominates(RemInst, DivInst)) continue; if (HasDivRemOp) { // The target has a single div/rem operation. Hoist the lower instruction // to make the matched pair visible to the backend. if (DivDominates) RemInst->moveAfter(DivInst); else DivInst->moveAfter(RemInst); NumHoisted++; } else { // The target does not have a single div/rem operation. Decompose the // remainder calculation as: // X % Y --> X - ((X / Y) * Y). Value *X = RemInst->getOperand(0); Value *Y = RemInst->getOperand(1); Instruction *Mul = BinaryOperator::CreateMul(DivInst, Y); Instruction *Sub = BinaryOperator::CreateSub(X, Mul); // If the remainder dominates, then hoist the division up to that block: // // bb1: // %rem = srem %x, %y // bb2: // %div = sdiv %x, %y // --> // bb1: // %div = sdiv %x, %y // %mul = mul %div, %y // %rem = sub %x, %mul // // If the division dominates, it's already in the right place. The mul+sub // will be in a different block because we don't assume that they are // cheap to speculatively execute: // // bb1: // %div = sdiv %x, %y // bb2: // %rem = srem %x, %y // --> // bb1: // %div = sdiv %x, %y // bb2: // %mul = mul %div, %y // %rem = sub %x, %mul // // If the div and rem are in the same block, we do the same transform, // but any code movement would be within the same block. if (!DivDominates) DivInst->moveBefore(RemInst); Mul->insertAfter(RemInst); Sub->insertAfter(Mul); // Now kill the explicit remainder. We have replaced it with: // (sub X, (mul (div X, Y), Y) RemInst->replaceAllUsesWith(Sub); RemInst->eraseFromParent(); NumDecomposed++; } Changed = true; } return Changed; } // Pass manager boilerplate below here. namespace { struct DivRemPairsLegacyPass : public FunctionPass { static char ID; DivRemPairsLegacyPass() : FunctionPass(ID) { initializeDivRemPairsLegacyPassPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<DominatorTreeWrapperPass>(); AU.addRequired<TargetTransformInfoWrapperPass>(); AU.setPreservesCFG(); AU.addPreserved<DominatorTreeWrapperPass>(); AU.addPreserved<GlobalsAAWrapperPass>(); FunctionPass::getAnalysisUsage(AU); } bool runOnFunction(Function &F) override { if (skipFunction(F)) return false; auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); return optimizeDivRem(F, TTI, DT); } }; } char DivRemPairsLegacyPass::ID = 0; INITIALIZE_PASS_BEGIN(DivRemPairsLegacyPass, "div-rem-pairs", "Hoist/decompose integer division and remainder", false, false) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_END(DivRemPairsLegacyPass, "div-rem-pairs", "Hoist/decompose integer division and remainder", false, false) FunctionPass *llvm::createDivRemPairsPass() { return new DivRemPairsLegacyPass(); } PreservedAnalyses DivRemPairsPass::run(Function &F, FunctionAnalysisManager &FAM) { TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F); DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F); if (!optimizeDivRem(F, TTI, DT)) return PreservedAnalyses::all(); // TODO: This pass just hoists/replaces math ops - all analyses are preserved? PreservedAnalyses PA; PA.preserveSet<CFGAnalyses>(); PA.preserve<GlobalsAA>(); return PA; } <commit_msg>[DivRemPairs] Fix non-determinism in use list order.<commit_after>//===- DivRemPairs.cpp - Hoist/decompose division and remainder -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass hoists and/or decomposes integer division and remainder // instructions to enable CFG improvements and better codegen. // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/DivRemPairs.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/Analysis/GlobalsModRef.h" #include "llvm/Analysis/TargetTransformInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/Function.h" #include "llvm/Pass.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/BypassSlowDivision.h" using namespace llvm; #define DEBUG_TYPE "div-rem-pairs" STATISTIC(NumPairs, "Number of div/rem pairs"); STATISTIC(NumHoisted, "Number of instructions hoisted"); STATISTIC(NumDecomposed, "Number of instructions decomposed"); /// Find matching pairs of integer div/rem ops (they have the same numerator, /// denominator, and signedness). If they exist in different basic blocks, bring /// them together by hoisting or replace the common division operation that is /// implicit in the remainder: /// X % Y <--> X - ((X / Y) * Y). /// /// We can largely ignore the normal safety and cost constraints on speculation /// of these ops when we find a matching pair. This is because we are already /// guaranteed that any exceptions and most cost are already incurred by the /// first member of the pair. /// /// Note: This transform could be an oddball enhancement to EarlyCSE, GVN, or /// SimplifyCFG, but it's split off on its own because it's different enough /// that it doesn't quite match the stated objectives of those passes. static bool optimizeDivRem(Function &F, const TargetTransformInfo &TTI, const DominatorTree &DT) { bool Changed = false; // Insert all divide and remainder instructions into maps keyed by their // operands and opcode (signed or unsigned). DenseMap<DivRemMapKey, Instruction *> DivMap; // Use a MapVector for RemMap so that instructions are moved/inserted in a // deterministic order. MapVector<DivRemMapKey, Instruction *> RemMap; for (auto &BB : F) { for (auto &I : BB) { if (I.getOpcode() == Instruction::SDiv) DivMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I; else if (I.getOpcode() == Instruction::UDiv) DivMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I; else if (I.getOpcode() == Instruction::SRem) RemMap[DivRemMapKey(true, I.getOperand(0), I.getOperand(1))] = &I; else if (I.getOpcode() == Instruction::URem) RemMap[DivRemMapKey(false, I.getOperand(0), I.getOperand(1))] = &I; } } // We can iterate over either map because we are only looking for matched // pairs. Choose remainders for efficiency because they are usually even more // rare than division. for (auto &RemPair : RemMap) { // Find the matching division instruction from the division map. Instruction *DivInst = DivMap[RemPair.first]; if (!DivInst) continue; // We have a matching pair of div/rem instructions. If one dominates the // other, hoist and/or replace one. NumPairs++; Instruction *RemInst = RemPair.second; bool IsSigned = DivInst->getOpcode() == Instruction::SDiv; bool HasDivRemOp = TTI.hasDivRemOp(DivInst->getType(), IsSigned); // If the target supports div+rem and the instructions are in the same block // already, there's nothing to do. The backend should handle this. If the // target does not support div+rem, then we will decompose the rem. if (HasDivRemOp && RemInst->getParent() == DivInst->getParent()) continue; bool DivDominates = DT.dominates(DivInst, RemInst); if (!DivDominates && !DT.dominates(RemInst, DivInst)) continue; if (HasDivRemOp) { // The target has a single div/rem operation. Hoist the lower instruction // to make the matched pair visible to the backend. if (DivDominates) RemInst->moveAfter(DivInst); else DivInst->moveAfter(RemInst); NumHoisted++; } else { // The target does not have a single div/rem operation. Decompose the // remainder calculation as: // X % Y --> X - ((X / Y) * Y). Value *X = RemInst->getOperand(0); Value *Y = RemInst->getOperand(1); Instruction *Mul = BinaryOperator::CreateMul(DivInst, Y); Instruction *Sub = BinaryOperator::CreateSub(X, Mul); // If the remainder dominates, then hoist the division up to that block: // // bb1: // %rem = srem %x, %y // bb2: // %div = sdiv %x, %y // --> // bb1: // %div = sdiv %x, %y // %mul = mul %div, %y // %rem = sub %x, %mul // // If the division dominates, it's already in the right place. The mul+sub // will be in a different block because we don't assume that they are // cheap to speculatively execute: // // bb1: // %div = sdiv %x, %y // bb2: // %rem = srem %x, %y // --> // bb1: // %div = sdiv %x, %y // bb2: // %mul = mul %div, %y // %rem = sub %x, %mul // // If the div and rem are in the same block, we do the same transform, // but any code movement would be within the same block. if (!DivDominates) DivInst->moveBefore(RemInst); Mul->insertAfter(RemInst); Sub->insertAfter(Mul); // Now kill the explicit remainder. We have replaced it with: // (sub X, (mul (div X, Y), Y) RemInst->replaceAllUsesWith(Sub); RemInst->eraseFromParent(); NumDecomposed++; } Changed = true; } return Changed; } // Pass manager boilerplate below here. namespace { struct DivRemPairsLegacyPass : public FunctionPass { static char ID; DivRemPairsLegacyPass() : FunctionPass(ID) { initializeDivRemPairsLegacyPassPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequired<DominatorTreeWrapperPass>(); AU.addRequired<TargetTransformInfoWrapperPass>(); AU.setPreservesCFG(); AU.addPreserved<DominatorTreeWrapperPass>(); AU.addPreserved<GlobalsAAWrapperPass>(); FunctionPass::getAnalysisUsage(AU); } bool runOnFunction(Function &F) override { if (skipFunction(F)) return false; auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); return optimizeDivRem(F, TTI, DT); } }; } char DivRemPairsLegacyPass::ID = 0; INITIALIZE_PASS_BEGIN(DivRemPairsLegacyPass, "div-rem-pairs", "Hoist/decompose integer division and remainder", false, false) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_END(DivRemPairsLegacyPass, "div-rem-pairs", "Hoist/decompose integer division and remainder", false, false) FunctionPass *llvm::createDivRemPairsPass() { return new DivRemPairsLegacyPass(); } PreservedAnalyses DivRemPairsPass::run(Function &F, FunctionAnalysisManager &FAM) { TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F); DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F); if (!optimizeDivRem(F, TTI, DT)) return PreservedAnalyses::all(); // TODO: This pass just hoists/replaces math ops - all analyses are preserved? PreservedAnalyses PA; PA.preserveSet<CFGAnalyses>(); PA.preserve<GlobalsAA>(); return PA; } <|endoftext|>
<commit_before>//===- SimplifyCFG.cpp - CFG Simplification Pass --------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements dead code elimination and basic block merging. // // Specifically, this: // * removes basic blocks with no predecessors // * merges a basic block into its predecessor if there is only one and the // predecessor only has one successor. // * Eliminates PHI nodes for basic blocks with a single predecessor // * Eliminates a basic block that only contains an unconditional branch // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "simplifycfg" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/Constants.h" #include "llvm/Instructions.h" #include "llvm/Module.h" #include "llvm/Support/CFG.h" #include "llvm/Support/Compiler.h" #include "llvm/Pass.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Statistic.h" using namespace llvm; STATISTIC(NumSimpl, "Number of blocks simplified"); namespace { struct VISIBILITY_HIDDEN CFGSimplifyPass : public FunctionPass { virtual bool runOnFunction(Function &F); }; RegisterPass<CFGSimplifyPass> X("simplifycfg", "Simplify the CFG"); } // Public interface to the CFGSimplification pass FunctionPass *llvm::createCFGSimplificationPass() { return new CFGSimplifyPass(); } static bool MarkAliveBlocks(BasicBlock *BB, SmallPtrSet<BasicBlock*, 16> &Reachable) { if (!Reachable.insert(BB)) return false; // Do a quick scan of the basic block, turning any obviously unreachable // instructions into LLVM unreachable insts. The instruction combining pass // canonnicalizes unreachable insts into stores to null or undef. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ++BBI) if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) if (isa<ConstantPointerNull>(SI->getOperand(1)) || isa<UndefValue>(SI->getOperand(1))) { // Loop over all of the successors, removing BB's entry from any PHI // nodes. for (succ_iterator I = succ_begin(BB), SE = succ_end(BB); I != SE; ++I) (*I)->removePredecessor(BB); new UnreachableInst(SI); // All instructions after this are dead. for (; BBI != E; ) { if (!BBI->use_empty()) BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); BB->getInstList().erase(BBI++); } break; } bool Changed = ConstantFoldTerminator(BB); for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) Changed |= MarkAliveBlocks(*SI, Reachable); return Changed; } // It is possible that we may require multiple passes over the code to fully // simplify the CFG. // bool CFGSimplifyPass::runOnFunction(Function &F) { SmallPtrSet<BasicBlock*, 16> Reachable; bool Changed = MarkAliveBlocks(F.begin(), Reachable); // If there are unreachable blocks in the CFG... if (Reachable.size() != F.size()) { assert(Reachable.size() < F.size()); NumSimpl += F.size()-Reachable.size(); // Loop over all of the basic blocks that are not reachable, dropping all of // their internal references... for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) if (!Reachable.count(BB)) { for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI!=SE; ++SI) if (Reachable.count(*SI)) (*SI)->removePredecessor(BB); BB->dropAllReferences(); } for (Function::iterator I = ++F.begin(); I != F.end();) if (!Reachable.count(I)) I = F.getBasicBlockList().erase(I); else ++I; Changed = true; } bool LocalChange = true; while (LocalChange) { LocalChange = false; // Loop over all of the basic blocks (except the first one) and remove them // if they are unneeded... // for (Function::iterator BBIt = ++F.begin(); BBIt != F.end(); ) { if (SimplifyCFG(BBIt++)) { LocalChange = true; ++NumSimpl; } } Changed |= LocalChange; } return Changed; } <commit_msg>Use a worklist-driven algorithm instead of a recursive one.<commit_after>//===- SimplifyCFG.cpp - CFG Simplification Pass --------------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements dead code elimination and basic block merging. // // Specifically, this: // * removes basic blocks with no predecessors // * merges a basic block into its predecessor if there is only one and the // predecessor only has one successor. // * Eliminates PHI nodes for basic blocks with a single predecessor // * Eliminates a basic block that only contains an unconditional branch // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "simplifycfg" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/Local.h" #include "llvm/Constants.h" #include "llvm/Instructions.h" #include "llvm/Module.h" #include "llvm/Support/CFG.h" #include "llvm/Support/Compiler.h" #include "llvm/Pass.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/Statistic.h" using namespace llvm; STATISTIC(NumSimpl, "Number of blocks simplified"); namespace { struct VISIBILITY_HIDDEN CFGSimplifyPass : public FunctionPass { virtual bool runOnFunction(Function &F); }; RegisterPass<CFGSimplifyPass> X("simplifycfg", "Simplify the CFG"); } // Public interface to the CFGSimplification pass FunctionPass *llvm::createCFGSimplificationPass() { return new CFGSimplifyPass(); } static bool MarkAliveBlocks(BasicBlock *BB, SmallPtrSet<BasicBlock*, 16> &Reachable) { std::vector<BasicBlock*> Worklist; Worklist.push_back(BB); bool Changed = false; while (!Worklist.empty()) { BB = Worklist.back(); Worklist.pop_back(); if (!Reachable.insert(BB)) continue; // Do a quick scan of the basic block, turning any obviously unreachable // instructions into LLVM unreachable insts. The instruction combining pass // canonnicalizes unreachable insts into stores to null or undef. for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ++BBI) if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) if (isa<ConstantPointerNull>(SI->getOperand(1)) || isa<UndefValue>(SI->getOperand(1))) { // Loop over all of the successors, removing BB's entry from any PHI // nodes. for (succ_iterator I = succ_begin(BB), SE = succ_end(BB); I != SE;++I) (*I)->removePredecessor(BB); new UnreachableInst(SI); // All instructions after this are dead. while (BBI != E) { if (!BBI->use_empty()) BBI->replaceAllUsesWith(UndefValue::get(BBI->getType())); BB->getInstList().erase(BBI++); } break; } Changed |= ConstantFoldTerminator(BB); for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) Worklist.push_back(*SI); } return Changed; } // It is possible that we may require multiple passes over the code to fully // simplify the CFG. // bool CFGSimplifyPass::runOnFunction(Function &F) { SmallPtrSet<BasicBlock*, 16> Reachable; bool Changed = MarkAliveBlocks(F.begin(), Reachable); // If there are unreachable blocks in the CFG... if (Reachable.size() != F.size()) { assert(Reachable.size() < F.size()); NumSimpl += F.size()-Reachable.size(); // Loop over all of the basic blocks that are not reachable, dropping all of // their internal references... for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) if (!Reachable.count(BB)) { for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI!=SE; ++SI) if (Reachable.count(*SI)) (*SI)->removePredecessor(BB); BB->dropAllReferences(); } for (Function::iterator I = ++F.begin(); I != F.end();) if (!Reachable.count(I)) I = F.getBasicBlockList().erase(I); else ++I; Changed = true; } bool LocalChange = true; while (LocalChange) { LocalChange = false; // Loop over all of the basic blocks (except the first one) and remove them // if they are unneeded... // for (Function::iterator BBIt = ++F.begin(); BBIt != F.end(); ) { if (SimplifyCFG(BBIt++)) { LocalChange = true; ++NumSimpl; } } Changed |= LocalChange; } return Changed; } <|endoftext|>
<commit_before>#include "SDLWindow.h" #include "SDLApplication.h" #ifdef HX_WINDOWS #include <SDL_syswm.h> #include <Windows.h> #undef CreateWindow #endif namespace lime { static bool displayModeSet = false; SDLWindow::SDLWindow (Application* application, int width, int height, int flags, const char* title) { currentApplication = application; this->flags = flags; int sdlFlags = 0; if (flags & WINDOW_FLAG_FULLSCREEN) sdlFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP; if (flags & WINDOW_FLAG_RESIZABLE) sdlFlags |= SDL_WINDOW_RESIZABLE; if (flags & WINDOW_FLAG_BORDERLESS) sdlFlags |= SDL_WINDOW_BORDERLESS; if (flags & WINDOW_FLAG_HIDDEN) sdlFlags |= SDL_WINDOW_HIDDEN; if (flags & WINDOW_FLAG_MINIMIZED) sdlFlags |= SDL_WINDOW_MINIMIZED; if (flags & WINDOW_FLAG_MAXIMIZED) sdlFlags |= SDL_WINDOW_MAXIMIZED; #ifndef EMSCRIPTEN if (flags & WINDOW_FLAG_ALWAYS_ON_TOP) sdlFlags |= SDL_WINDOW_ALWAYS_ON_TOP; #endif #if defined (HX_WINDOWS) && defined (NATIVE_TOOLKIT_SDL_ANGLE) OSVERSIONINFOEXW osvi = { sizeof (osvi), 0, 0, 0, 0, {0}, 0, 0 }; DWORDLONG const dwlConditionMask = VerSetConditionMask (VerSetConditionMask (VerSetConditionMask (0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL), VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); osvi.dwMajorVersion = HIBYTE (_WIN32_WINNT_VISTA); osvi.dwMinorVersion = LOBYTE (_WIN32_WINNT_VISTA); osvi.wServicePackMajor = 0; if (VerifyVersionInfoW (&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) == FALSE) { flags &= ~WINDOW_FLAG_HARDWARE; } #endif if (flags & WINDOW_FLAG_HARDWARE) { sdlFlags |= SDL_WINDOW_OPENGL; if (flags & WINDOW_FLAG_ALLOW_HIGHDPI) { sdlFlags |= SDL_WINDOW_ALLOW_HIGHDPI; } #if defined (HX_WINDOWS) && defined (NATIVE_TOOLKIT_SDL_ANGLE) SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute (SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_SetHint (SDL_HINT_VIDEO_WIN_D3DCOMPILER, "d3dcompiler_47.dll"); #endif #if defined (RASPBERRYPI) SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute (SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_SetHint (SDL_HINT_RENDER_DRIVER, "opengles2"); #endif if (flags & WINDOW_FLAG_DEPTH_BUFFER) { SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 32 - (flags & WINDOW_FLAG_STENCIL_BUFFER) ? 8 : 0); } if (flags & WINDOW_FLAG_STENCIL_BUFFER) { SDL_GL_SetAttribute (SDL_GL_STENCIL_SIZE, 8); } if (flags & WINDOW_FLAG_HW_AA_HIRES) { SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, true); SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, 4); } else if (flags & WINDOW_FLAG_HW_AA) { SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, true); SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, 2); } if (flags & WINDOW_FLAG_COLOR_DEPTH_32_BIT) { SDL_GL_SetAttribute (SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute (SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute (SDL_GL_ALPHA_SIZE, 8); } else { SDL_GL_SetAttribute (SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute (SDL_GL_GREEN_SIZE, 6); SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 5); } } sdlWindow = SDL_CreateWindow (title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, sdlFlags); if (!sdlWindow) { printf ("Could not create SDL window: %s.\n", SDL_GetError ()); } //((SDLApplication*)currentApplication)->RegisterWindow (this); #ifdef HX_WINDOWS HINSTANCE handle = ::GetModuleHandle (nullptr); HICON icon = ::LoadIcon (handle, MAKEINTRESOURCE (1)); if (icon != nullptr) { SDL_SysWMinfo wminfo; SDL_VERSION (&wminfo.version); if (SDL_GetWindowWMInfo (sdlWindow, &wminfo) == 1) { HWND hwnd = wminfo.info.win.window; #ifdef _WIN64 ::SetClassLongPtr (hwnd, GCLP_HICON, reinterpret_cast<LONG_PTR>(icon)); #else ::SetClassLong (hwnd, GCL_HICON, reinterpret_cast<LONG>(icon)); #endif } } #endif } SDLWindow::~SDLWindow () { if (sdlWindow) { SDL_DestroyWindow (sdlWindow); sdlWindow = 0; } } void SDLWindow::Alert (const char* message, const char* title) { #ifdef HX_WINDOWS int count = 0; int speed = 0; bool stopOnForeground = true; SDL_SysWMinfo info; SDL_VERSION (&info.version); SDL_GetWindowWMInfo (sdlWindow, &info); FLASHWINFO fi; fi.cbSize = sizeof (FLASHWINFO); fi.hwnd = info.info.win.window; fi.dwFlags = stopOnForeground ? FLASHW_ALL | FLASHW_TIMERNOFG : FLASHW_ALL | FLASHW_TIMER; fi.uCount = count; fi.dwTimeout = speed; FlashWindowEx (&fi); #endif if (message) { SDL_ShowSimpleMessageBox (SDL_MESSAGEBOX_INFORMATION, title, message, sdlWindow); } } void SDLWindow::Close () { if (sdlWindow) { SDL_DestroyWindow (sdlWindow); sdlWindow = 0; } } void SDLWindow::Focus () { SDL_RaiseWindow (sdlWindow); } int SDLWindow::GetDisplay () { return SDL_GetWindowDisplayIndex (sdlWindow); } void SDLWindow::GetDisplayMode (DisplayMode* displayMode) { SDL_DisplayMode mode; SDL_GetWindowDisplayMode (sdlWindow, &mode); displayMode->width = mode.w; displayMode->height = mode.h; switch (mode.format) { case SDL_PIXELFORMAT_ARGB8888: displayMode->pixelFormat = ARGB32; break; case SDL_PIXELFORMAT_BGRA8888: case SDL_PIXELFORMAT_BGRX8888: displayMode->pixelFormat = BGRA32; break; default: displayMode->pixelFormat = RGBA32; } displayMode->refreshRate = mode.refresh_rate; } bool SDLWindow::GetEnableTextEvents () { return SDL_IsTextInputActive (); } int SDLWindow::GetHeight () { int width; int height; SDL_GetWindowSize (sdlWindow, &width, &height); return height; } uint32_t SDLWindow::GetID () { return SDL_GetWindowID (sdlWindow); } int SDLWindow::GetWidth () { int width; int height; SDL_GetWindowSize (sdlWindow, &width, &height); return width; } int SDLWindow::GetX () { int x; int y; SDL_GetWindowPosition (sdlWindow, &x, &y); return x; } int SDLWindow::GetY () { int x; int y; SDL_GetWindowPosition (sdlWindow, &x, &y); return y; } void SDLWindow::Move (int x, int y) { SDL_SetWindowPosition (sdlWindow, x, y); } void SDLWindow::Resize (int width, int height) { SDL_SetWindowSize (sdlWindow, width, height); } bool SDLWindow::SetBorderless (bool borderless) { if (borderless) { SDL_SetWindowBordered (sdlWindow, SDL_FALSE); } else { SDL_SetWindowBordered (sdlWindow, SDL_TRUE); } return borderless; } void SDLWindow::SetDisplayMode (DisplayMode* displayMode) { Uint32 pixelFormat = 0; switch (displayMode->pixelFormat) { case ARGB32: pixelFormat = SDL_PIXELFORMAT_ARGB8888; break; case BGRA32: pixelFormat = SDL_PIXELFORMAT_BGRA8888; break; default: pixelFormat = SDL_PIXELFORMAT_RGBA8888; } SDL_DisplayMode mode = { pixelFormat, displayMode->width, displayMode->height, displayMode->refreshRate, 0 }; if (SDL_SetWindowDisplayMode (sdlWindow, &mode) == 0) { displayModeSet = true; if (SDL_GetWindowFlags (sdlWindow) & SDL_WINDOW_FULLSCREEN_DESKTOP) { SDL_SetWindowFullscreen (sdlWindow, SDL_WINDOW_FULLSCREEN); } } } void SDLWindow::SetEnableTextEvents (bool enabled) { if (enabled) { SDL_StartTextInput (); } else { SDL_StopTextInput (); } } bool SDLWindow::SetFullscreen (bool fullscreen) { if (fullscreen) { if (displayModeSet) { SDL_SetWindowFullscreen (sdlWindow, SDL_WINDOW_FULLSCREEN); } else { SDL_SetWindowFullscreen (sdlWindow, SDL_WINDOW_FULLSCREEN_DESKTOP); } } else { SDL_SetWindowFullscreen (sdlWindow, 0); } return fullscreen; } void SDLWindow::SetIcon (ImageBuffer *imageBuffer) { SDL_Surface *surface = SDL_CreateRGBSurfaceFrom (imageBuffer->data->Data (), imageBuffer->width, imageBuffer->height, imageBuffer->bitsPerPixel, imageBuffer->Stride (), 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000); if (surface) { SDL_SetWindowIcon (sdlWindow, surface); SDL_FreeSurface (surface); } } bool SDLWindow::SetMaximized (bool maximized) { if (maximized) { SDL_MaximizeWindow (sdlWindow); } else { SDL_RestoreWindow (sdlWindow); } return maximized; } bool SDLWindow::SetMinimized (bool minimized) { if (minimized) { SDL_MinimizeWindow (sdlWindow); } else { SDL_RestoreWindow (sdlWindow); } return minimized; } bool SDLWindow::SetResizable (bool resizable) { #ifndef EMSCRIPTEN if (resizable) { SDL_SetWindowResizable (sdlWindow, SDL_TRUE); } else { SDL_SetWindowResizable (sdlWindow, SDL_FALSE); } return (SDL_GetWindowFlags (sdlWindow) & SDL_WINDOW_RESIZABLE); #else return resizable; #endif } const char* SDLWindow::SetTitle (const char* title) { SDL_SetWindowTitle (sdlWindow, title); return title; } Window* CreateWindow (Application* application, int width, int height, int flags, const char* title) { return new SDLWindow (application, width, height, flags, title); } } <commit_msg>Revert "Allow older GL context version on iOS"<commit_after>#include "SDLWindow.h" #include "SDLApplication.h" #ifdef HX_WINDOWS #include <SDL_syswm.h> #include <Windows.h> #undef CreateWindow #endif namespace lime { static bool displayModeSet = false; SDLWindow::SDLWindow (Application* application, int width, int height, int flags, const char* title) { currentApplication = application; this->flags = flags; int sdlFlags = 0; if (flags & WINDOW_FLAG_FULLSCREEN) sdlFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP; if (flags & WINDOW_FLAG_RESIZABLE) sdlFlags |= SDL_WINDOW_RESIZABLE; if (flags & WINDOW_FLAG_BORDERLESS) sdlFlags |= SDL_WINDOW_BORDERLESS; if (flags & WINDOW_FLAG_HIDDEN) sdlFlags |= SDL_WINDOW_HIDDEN; if (flags & WINDOW_FLAG_MINIMIZED) sdlFlags |= SDL_WINDOW_MINIMIZED; if (flags & WINDOW_FLAG_MAXIMIZED) sdlFlags |= SDL_WINDOW_MAXIMIZED; #ifndef EMSCRIPTEN if (flags & WINDOW_FLAG_ALWAYS_ON_TOP) sdlFlags |= SDL_WINDOW_ALWAYS_ON_TOP; #endif #if defined (HX_WINDOWS) && defined (NATIVE_TOOLKIT_SDL_ANGLE) OSVERSIONINFOEXW osvi = { sizeof (osvi), 0, 0, 0, 0, {0}, 0, 0 }; DWORDLONG const dwlConditionMask = VerSetConditionMask (VerSetConditionMask (VerSetConditionMask (0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL), VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); osvi.dwMajorVersion = HIBYTE (_WIN32_WINNT_VISTA); osvi.dwMinorVersion = LOBYTE (_WIN32_WINNT_VISTA); osvi.wServicePackMajor = 0; if (VerifyVersionInfoW (&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, dwlConditionMask) == FALSE) { flags &= ~WINDOW_FLAG_HARDWARE; } #endif if (flags & WINDOW_FLAG_HARDWARE) { sdlFlags |= SDL_WINDOW_OPENGL; if (flags & WINDOW_FLAG_ALLOW_HIGHDPI) { sdlFlags |= SDL_WINDOW_ALLOW_HIGHDPI; } #if defined (HX_WINDOWS) && defined (NATIVE_TOOLKIT_SDL_ANGLE) SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute (SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_SetHint (SDL_HINT_VIDEO_WIN_D3DCOMPILER, "d3dcompiler_47.dll"); #endif #if defined (RASPBERRYPI) SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute (SDL_GL_CONTEXT_MINOR_VERSION, 0); SDL_SetHint (SDL_HINT_RENDER_DRIVER, "opengles2"); #endif #if defined (IPHONE) || defined (APPLETV) SDL_GL_SetAttribute (SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES); SDL_GL_SetAttribute (SDL_GL_CONTEXT_MAJOR_VERSION, 3); #endif if (flags & WINDOW_FLAG_DEPTH_BUFFER) { SDL_GL_SetAttribute (SDL_GL_DEPTH_SIZE, 32 - (flags & WINDOW_FLAG_STENCIL_BUFFER) ? 8 : 0); } if (flags & WINDOW_FLAG_STENCIL_BUFFER) { SDL_GL_SetAttribute (SDL_GL_STENCIL_SIZE, 8); } if (flags & WINDOW_FLAG_HW_AA_HIRES) { SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, true); SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, 4); } else if (flags & WINDOW_FLAG_HW_AA) { SDL_GL_SetAttribute (SDL_GL_MULTISAMPLEBUFFERS, true); SDL_GL_SetAttribute (SDL_GL_MULTISAMPLESAMPLES, 2); } if (flags & WINDOW_FLAG_COLOR_DEPTH_32_BIT) { SDL_GL_SetAttribute (SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute (SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute (SDL_GL_ALPHA_SIZE, 8); } else { SDL_GL_SetAttribute (SDL_GL_RED_SIZE, 5); SDL_GL_SetAttribute (SDL_GL_GREEN_SIZE, 6); SDL_GL_SetAttribute (SDL_GL_BLUE_SIZE, 5); } } sdlWindow = SDL_CreateWindow (title, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, sdlFlags); if (!sdlWindow) { printf ("Could not create SDL window: %s.\n", SDL_GetError ()); } //((SDLApplication*)currentApplication)->RegisterWindow (this); #ifdef HX_WINDOWS HINSTANCE handle = ::GetModuleHandle (nullptr); HICON icon = ::LoadIcon (handle, MAKEINTRESOURCE (1)); if (icon != nullptr) { SDL_SysWMinfo wminfo; SDL_VERSION (&wminfo.version); if (SDL_GetWindowWMInfo (sdlWindow, &wminfo) == 1) { HWND hwnd = wminfo.info.win.window; #ifdef _WIN64 ::SetClassLongPtr (hwnd, GCLP_HICON, reinterpret_cast<LONG_PTR>(icon)); #else ::SetClassLong (hwnd, GCL_HICON, reinterpret_cast<LONG>(icon)); #endif } } #endif } SDLWindow::~SDLWindow () { if (sdlWindow) { SDL_DestroyWindow (sdlWindow); sdlWindow = 0; } } void SDLWindow::Alert (const char* message, const char* title) { #ifdef HX_WINDOWS int count = 0; int speed = 0; bool stopOnForeground = true; SDL_SysWMinfo info; SDL_VERSION (&info.version); SDL_GetWindowWMInfo (sdlWindow, &info); FLASHWINFO fi; fi.cbSize = sizeof (FLASHWINFO); fi.hwnd = info.info.win.window; fi.dwFlags = stopOnForeground ? FLASHW_ALL | FLASHW_TIMERNOFG : FLASHW_ALL | FLASHW_TIMER; fi.uCount = count; fi.dwTimeout = speed; FlashWindowEx (&fi); #endif if (message) { SDL_ShowSimpleMessageBox (SDL_MESSAGEBOX_INFORMATION, title, message, sdlWindow); } } void SDLWindow::Close () { if (sdlWindow) { SDL_DestroyWindow (sdlWindow); sdlWindow = 0; } } void SDLWindow::Focus () { SDL_RaiseWindow (sdlWindow); } int SDLWindow::GetDisplay () { return SDL_GetWindowDisplayIndex (sdlWindow); } void SDLWindow::GetDisplayMode (DisplayMode* displayMode) { SDL_DisplayMode mode; SDL_GetWindowDisplayMode (sdlWindow, &mode); displayMode->width = mode.w; displayMode->height = mode.h; switch (mode.format) { case SDL_PIXELFORMAT_ARGB8888: displayMode->pixelFormat = ARGB32; break; case SDL_PIXELFORMAT_BGRA8888: case SDL_PIXELFORMAT_BGRX8888: displayMode->pixelFormat = BGRA32; break; default: displayMode->pixelFormat = RGBA32; } displayMode->refreshRate = mode.refresh_rate; } bool SDLWindow::GetEnableTextEvents () { return SDL_IsTextInputActive (); } int SDLWindow::GetHeight () { int width; int height; SDL_GetWindowSize (sdlWindow, &width, &height); return height; } uint32_t SDLWindow::GetID () { return SDL_GetWindowID (sdlWindow); } int SDLWindow::GetWidth () { int width; int height; SDL_GetWindowSize (sdlWindow, &width, &height); return width; } int SDLWindow::GetX () { int x; int y; SDL_GetWindowPosition (sdlWindow, &x, &y); return x; } int SDLWindow::GetY () { int x; int y; SDL_GetWindowPosition (sdlWindow, &x, &y); return y; } void SDLWindow::Move (int x, int y) { SDL_SetWindowPosition (sdlWindow, x, y); } void SDLWindow::Resize (int width, int height) { SDL_SetWindowSize (sdlWindow, width, height); } bool SDLWindow::SetBorderless (bool borderless) { if (borderless) { SDL_SetWindowBordered (sdlWindow, SDL_FALSE); } else { SDL_SetWindowBordered (sdlWindow, SDL_TRUE); } return borderless; } void SDLWindow::SetDisplayMode (DisplayMode* displayMode) { Uint32 pixelFormat = 0; switch (displayMode->pixelFormat) { case ARGB32: pixelFormat = SDL_PIXELFORMAT_ARGB8888; break; case BGRA32: pixelFormat = SDL_PIXELFORMAT_BGRA8888; break; default: pixelFormat = SDL_PIXELFORMAT_RGBA8888; } SDL_DisplayMode mode = { pixelFormat, displayMode->width, displayMode->height, displayMode->refreshRate, 0 }; if (SDL_SetWindowDisplayMode (sdlWindow, &mode) == 0) { displayModeSet = true; if (SDL_GetWindowFlags (sdlWindow) & SDL_WINDOW_FULLSCREEN_DESKTOP) { SDL_SetWindowFullscreen (sdlWindow, SDL_WINDOW_FULLSCREEN); } } } void SDLWindow::SetEnableTextEvents (bool enabled) { if (enabled) { SDL_StartTextInput (); } else { SDL_StopTextInput (); } } bool SDLWindow::SetFullscreen (bool fullscreen) { if (fullscreen) { if (displayModeSet) { SDL_SetWindowFullscreen (sdlWindow, SDL_WINDOW_FULLSCREEN); } else { SDL_SetWindowFullscreen (sdlWindow, SDL_WINDOW_FULLSCREEN_DESKTOP); } } else { SDL_SetWindowFullscreen (sdlWindow, 0); } return fullscreen; } void SDLWindow::SetIcon (ImageBuffer *imageBuffer) { SDL_Surface *surface = SDL_CreateRGBSurfaceFrom (imageBuffer->data->Data (), imageBuffer->width, imageBuffer->height, imageBuffer->bitsPerPixel, imageBuffer->Stride (), 0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000); if (surface) { SDL_SetWindowIcon (sdlWindow, surface); SDL_FreeSurface (surface); } } bool SDLWindow::SetMaximized (bool maximized) { if (maximized) { SDL_MaximizeWindow (sdlWindow); } else { SDL_RestoreWindow (sdlWindow); } return maximized; } bool SDLWindow::SetMinimized (bool minimized) { if (minimized) { SDL_MinimizeWindow (sdlWindow); } else { SDL_RestoreWindow (sdlWindow); } return minimized; } bool SDLWindow::SetResizable (bool resizable) { #ifndef EMSCRIPTEN if (resizable) { SDL_SetWindowResizable (sdlWindow, SDL_TRUE); } else { SDL_SetWindowResizable (sdlWindow, SDL_FALSE); } return (SDL_GetWindowFlags (sdlWindow) & SDL_WINDOW_RESIZABLE); #else return resizable; #endif } const char* SDLWindow::SetTitle (const char* title) { SDL_SetWindowTitle (sdlWindow, title); return title; } Window* CreateWindow (Application* application, int width, int height, int flags, const char* title) { return new SDLWindow (application, width, height, flags, title); } } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <sstream> #include <string> #include <map> #include <vector> using namespace std; void bubbleSort(vector<string>, int); int main(int argc, char *argv[]) { ifstream inFile; istringstream line; map<string, int> wordCount; map<int, vector<string>> byCount; string word = ""; string sLine = ""; int longestLine = 0; int longestWord = 0; int numLongestLines = 0; int numFiles = 0; int numLongestWord = 0; int length = 0; int subLength = 0; int size = 0; int q = 0; bool mFlag = false; bool cFlag = false; //initialization of the bool bFlag = false; //possible flags bool xFlag = false; //a flag is an argument whose first character is a dash //so any file names or paths that start with a dash are //considered flags //therefore I do not have to check for the //case in which a directory or file's name starts with a - for (int j = 1; j < argc; j++) { if (argv[j][0] == '-') { switch (argv[j][1]) { case 'm': mFlag = true; break; case 'c': cFlag = true; break; case 'b': bFlag = true; break; //if the flag is unrecognized default: //xFlag set to false, string printed //then the loops break and return main xFlag = true; cout << argv[j] << " UNRECOGNIZED FLAG"; break; } } else { numFiles++; } if (xFlag) //stops the main loop { break; } } if (xFlag) // returns main and terminates the program safely { return 0; } else if (numFiles == 0) { cout << "NO FILES" << endl; return 0; } for (int i = 1; i < argc; i++) { if (argv[i][0] != '-') { inFile.open(argv[i]); if (inFile.is_open()) { while (getline(inFile, sLine)) { if (sLine == "") { continue; } length = inFile.gcount(); line.str(sLine); if (length > longestLine) { longestLine = length; numLongestLines = 1; } else if (length == longestLine) { numLongestLines++; } while (line >> word) { while (word == "") { subLength++; } if ((word.length()) == (unsigned)longestWord) { wordCount[word]++; } else if ((word.length()) > (unsigned)longestWord) { wordCount.erase(wordCount.begin(), wordCount.end()); wordCount[word]++; longestWord = word.length(); } } if (bFlag) { subLength--; longestLine -= subLength; } } inFile.close(); } else { cout << argv[i] << " FILE NOT FOUND" << endl; } } else { continue; } cout << argv[i] << ":" << endl; if (mFlag) { map<string, int>::iterator cit; for (cit = wordCount.begin(); cit != wordCount.end(); cit++) { //goes to the map index for the count of the word //then adds the word to the vector at that index byCount[cit->second].push_back(cit->first); } //gets the last key in the map which should be the highest occurring words map<int, vector<string>>::reverse_iterator sit = byCount.rbegin(); //assigns the quantity of highest occurring words to numLongestWord numLongestWord = sit->first; //trims the vector at that key location byCount[numLongestWord].shrink_to_fit(); //sorts the vector at that key location bubbleSort(&byCount[numLongestWord], byCount[numLongestWord].size()); vector<string>::iterator qit = byCount[numLongestWord].begin(); size = byCount[numLongestWord].size(); q = 0; while (qit != byCount[numLongestWord].end()) { if (q < size - 1) { if (cFlag) { cout << *qit << " (" << numLongestWord << "), "; } else { cout << *qit << ", "; } } else { if (cFlag) { cout << *qit << " (" << numLongestWord << ")"; } else { cout << *qit; } } q++; qit++; cout << endl; } } else { map<string, int>::iterator it; for (it = wordCount.begin(); it != wordCount.end(); it++) {//sorted and comma-separated longest words cout << it->first << ", "; } } cout << endl; cout << longestLine; if (cFlag) { cout << " (" << numLongestLines << ")"; } cout << endl; } } void bubbleSort(vector<string> &toSort, int size) { int z; int newZ; string mid; for(z = size; z != 0; n = newZ) { for(int y = 1; y < z;) { if(toSort[y-1] > toSort[y]) { mid = toSort[y-1]; toSort[y-1] = toSort[y]; toSort[y] = mid; newZ = y; } } z = newZ; } }<commit_msg>Nevermind, used #include <algorithm> for sort instead<commit_after>#include <iostream> #include <fstream> #include <sstream> #include <string> #include <map> #include <vector> #include <algorithm> using namespace std; int main(int argc, char *argv[]) { ifstream inFile; istringstream line; map<string, int> wordCount; map<int, vector<string>> byCount; string word = ""; string sLine = ""; int longestLine = 0; int longestWord = 0; int numLongestLines = 0; int numFiles = 0; int numLongestWord = 0; int length = 0; int subLength = 0; int size = 0; int q = 0; bool mFlag = false; bool cFlag = false; //initialization of the bool bFlag = false; //possible flags bool xFlag = false; //a flag is an argument whose first character is a dash //so any file names or paths that start with a dash are //considered flags //therefore I do not have to check for the //case in which a directory or file's name starts with a - for (int j = 1; j < argc; j++) { if (argv[j][0] == '-') { switch (argv[j][1]) { case 'm': mFlag = true; break; case 'c': cFlag = true; break; case 'b': bFlag = true; break; //if the flag is unrecognized default: //xFlag set to false, string printed //then the loops break and return main xFlag = true; cout << argv[j] << " UNRECOGNIZED FLAG"; break; } } else { numFiles++; } if (xFlag) //stops the main loop { break; } } if (xFlag) // returns main and terminates the program safely { return 0; } else if (numFiles == 0) { cout << "NO FILES" << endl; return 0; } for (int i = 1; i < argc; i++) { if (argv[i][0] != '-') { inFile.open(argv[i]); if (inFile.is_open()) { while (getline(inFile, sLine)) { if (sLine == "") { continue; } length = inFile.gcount(); line.str(sLine); if (length > longestLine) { longestLine = length; numLongestLines = 1; } else if (length == longestLine) { numLongestLines++; } while (line >> word) { while (word == "") { subLength++; } if ((word.length()) == (unsigned)longestWord) { wordCount[word]++; } else if ((word.length()) > (unsigned)longestWord) { wordCount.erase(wordCount.begin(), wordCount.end()); wordCount[word]++; longestWord = word.length(); } } if (bFlag) { subLength--; longestLine -= subLength; } } inFile.close(); } else { cout << argv[i] << " FILE NOT FOUND" << endl; } } else { continue; } cout << argv[i] << ":" << endl; if (mFlag) { map<string, int>::iterator cit; for (cit = wordCount.begin(); cit != wordCount.end(); cit++) { //goes to the map index for the count of the word //then adds the word to the vector at that index byCount[cit->second].push_back(cit->first); } //gets the last key in the map which should be the highest occurring words map<int, vector<string>>::reverse_iterator sit = byCount.rbegin(); //assigns the quantity of highest occurring words to numLongestWord numLongestWord = sit->first; //trims the vector at that key location byCount[numLongestWord].shrink_to_fit(); //sorts the vector at that key location sort(&byCount[numLongestWord], byCount[numLongestWord].size()); vector<string>::iterator qit = byCount[numLongestWord].begin(); size = byCount[numLongestWord].size(); q = 0; while (qit != byCount[numLongestWord].end()) { if (q < size - 1) { if (cFlag) { cout << *qit << " (" << numLongestWord << "), "; } else { cout << *qit << ", "; } } else { if (cFlag) { cout << *qit << " (" << numLongestWord << ")"; } else { cout << *qit; } } q++; qit++; cout << endl; } } else { map<string, int>::iterator it; for (it = wordCount.begin(); it != wordCount.end(); it++) {//sorted and comma-separated longest words cout << it->first << ", "; } } cout << endl; cout << longestLine; if (cFlag) { cout << " (" << numLongestLines << ")"; } cout << endl; } }<|endoftext|>
<commit_before>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "sk_tool_utils.h" #include "Resources.h" #include "SkGradientShader.h" #include "SkTypeface.h" #include "SkStream.h" #include "SkPaint.h" static void make_checker(SkBitmap* bm, int size, int numChecks) { bm->allocN32Pixels(size, size); for (int y = 0; y < size; ++y) { for (int x = 0; x < size; ++x) { SkPMColor* s = bm->getAddr32(x, y); int cx = (x * numChecks) / size; int cy = (y * numChecks) / size; if ((cx+cy)%2) { *s = 0xFFFFFFFF; } else { *s = 0xFF000000; } } } } static void setTypeface(SkPaint* paint, const char name[], SkFontStyle style) { sk_tool_utils::set_portable_typeface(paint, name, style); } class DownsampleBitmapGM : public skiagm::GM { public: SkBitmap fBM; SkString fName; bool fBitmapMade; SkFilterQuality fFilterQuality; DownsampleBitmapGM(SkFilterQuality filterQuality) : fFilterQuality(filterQuality) { this->setBGColor(sk_tool_utils::color_to_565(0xFFDDDDDD)); fBitmapMade = false; } const char* filterQualityToString() { static const char *filterQualityNames[] = { "none", "low", "medium", "high" }; return filterQualityNames[fFilterQuality]; } protected: SkString onShortName() override { return fName; } SkISize onISize() override { make_bitmap_wrapper(); return SkISize::Make(fBM.width(), 4 * fBM.height()); } void make_bitmap_wrapper() { if (!fBitmapMade) { fBitmapMade = true; make_bitmap(); } } virtual void make_bitmap() = 0; void onDraw(SkCanvas* canvas) override { make_bitmap_wrapper(); int curY = 0; int curHeight; float curScale = 1; do { SkMatrix matrix; matrix.setScale( curScale, curScale ); SkPaint paint; paint.setFilterQuality(fFilterQuality); canvas->save(); canvas->translate(0, (SkScalar)curY); canvas->concat(matrix); canvas->drawBitmap(fBM, 0, 0, &paint); canvas->restore(); curHeight = (int) (fBM.height() * curScale + 2); curY += curHeight; curScale *= 0.75f; } while (curHeight >= 2 && curY < 4*fBM.height()); } private: typedef skiagm::GM INHERITED; }; class DownsampleBitmapTextGM: public DownsampleBitmapGM { public: DownsampleBitmapTextGM(float textSize, SkFilterQuality filterQuality) : INHERITED(filterQuality), fTextSize(textSize) { fName.printf("downsamplebitmap_text_%s_%.2fpt", this->filterQualityToString(), fTextSize); } protected: float fTextSize; void make_bitmap() override { fBM.allocN32Pixels(int(fTextSize * 8), int(fTextSize * 6)); SkCanvas canvas(fBM); canvas.drawColor(SK_ColorWHITE); SkPaint paint; paint.setAntiAlias(true); paint.setSubpixelText(true); paint.setTextSize(fTextSize); setTypeface(&paint, "serif", SkFontStyle()); canvas.drawString("Hamburgefons", fTextSize/2, 1.2f*fTextSize, paint); setTypeface(&paint, "serif", SkFontStyle::Bold()); canvas.drawString("Hamburgefons", fTextSize/2, 2.4f*fTextSize, paint); setTypeface(&paint, "serif", SkFontStyle::Italic()); canvas.drawString("Hamburgefons", fTextSize/2, 3.6f*fTextSize, paint); setTypeface(&paint, "serif", SkFontStyle::BoldItalic()); canvas.drawString("Hamburgefons", fTextSize/2, 4.8f*fTextSize, paint); } private: typedef DownsampleBitmapGM INHERITED; }; class DownsampleBitmapCheckerboardGM: public DownsampleBitmapGM { public: DownsampleBitmapCheckerboardGM(int size, int numChecks, SkFilterQuality filterQuality) : INHERITED(filterQuality), fSize(size), fNumChecks(numChecks) { fName.printf("downsamplebitmap_checkerboard_%s_%d_%d", this->filterQualityToString(), fSize, fNumChecks); } protected: int fSize; int fNumChecks; void make_bitmap() override { make_checker(&fBM, fSize, fNumChecks); } private: typedef DownsampleBitmapGM INHERITED; }; class DownsampleBitmapImageGM: public DownsampleBitmapGM { public: DownsampleBitmapImageGM(const char filename[], SkFilterQuality filterQuality) : INHERITED(filterQuality), fFilename(filename) { fName.printf("downsamplebitmap_image_%s_%s", this->filterQualityToString(), filename); } protected: SkString fFilename; int fSize; void make_bitmap() override { if (!GetResourceAsBitmap(fFilename.c_str(), &fBM)) { fBM.allocN32Pixels(1, 1); fBM.eraseARGB(255, 255, 0 , 0); // red == bad } fSize = fBM.height(); } private: typedef DownsampleBitmapGM INHERITED; }; DEF_GM( return new DownsampleBitmapTextGM(72, kHigh_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapCheckerboardGM(512,256, kHigh_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapImageGM("images/mandrill_512.png", kHigh_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapTextGM(72, kMedium_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapCheckerboardGM(512,256, kMedium_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapImageGM("images/mandrill_512.png", kMedium_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapTextGM(72, kLow_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapCheckerboardGM(512,256, kLow_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapImageGM("images/mandrill_512.png", kLow_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapTextGM(72, kNone_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapCheckerboardGM(512,256, kNone_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapImageGM("images/mandrill_512.png", kNone_SkFilterQuality); ) <commit_msg>The downsamplebitmap_image GMs only use one image.<commit_after>/* * Copyright 2013 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" #include "sk_tool_utils.h" #include "Resources.h" #include "SkGradientShader.h" #include "SkTypeface.h" #include "SkStream.h" #include "SkPaint.h" static void make_checker(SkBitmap* bm, int size, int numChecks) { bm->allocN32Pixels(size, size); for (int y = 0; y < size; ++y) { for (int x = 0; x < size; ++x) { SkPMColor* s = bm->getAddr32(x, y); int cx = (x * numChecks) / size; int cy = (y * numChecks) / size; if ((cx+cy)%2) { *s = 0xFFFFFFFF; } else { *s = 0xFF000000; } } } } static void setTypeface(SkPaint* paint, const char name[], SkFontStyle style) { sk_tool_utils::set_portable_typeface(paint, name, style); } class DownsampleBitmapGM : public skiagm::GM { public: SkBitmap fBM; SkString fName; bool fBitmapMade; SkFilterQuality fFilterQuality; DownsampleBitmapGM(SkFilterQuality filterQuality) : fFilterQuality(filterQuality) { this->setBGColor(sk_tool_utils::color_to_565(0xFFDDDDDD)); fBitmapMade = false; } const char* filterQualityToString() { static const char *filterQualityNames[] = { "none", "low", "medium", "high" }; return filterQualityNames[fFilterQuality]; } protected: SkString onShortName() override { return fName; } SkISize onISize() override { make_bitmap_wrapper(); return SkISize::Make(fBM.width(), 4 * fBM.height()); } void make_bitmap_wrapper() { if (!fBitmapMade) { fBitmapMade = true; make_bitmap(); } } virtual void make_bitmap() = 0; void onDraw(SkCanvas* canvas) override { make_bitmap_wrapper(); int curY = 0; int curHeight; float curScale = 1; do { SkMatrix matrix; matrix.setScale( curScale, curScale ); SkPaint paint; paint.setFilterQuality(fFilterQuality); canvas->save(); canvas->translate(0, (SkScalar)curY); canvas->concat(matrix); canvas->drawBitmap(fBM, 0, 0, &paint); canvas->restore(); curHeight = (int) (fBM.height() * curScale + 2); curY += curHeight; curScale *= 0.75f; } while (curHeight >= 2 && curY < 4*fBM.height()); } private: typedef skiagm::GM INHERITED; }; class DownsampleBitmapTextGM: public DownsampleBitmapGM { public: DownsampleBitmapTextGM(float textSize, SkFilterQuality filterQuality) : INHERITED(filterQuality), fTextSize(textSize) { fName.printf("downsamplebitmap_text_%s_%.2fpt", this->filterQualityToString(), fTextSize); } protected: float fTextSize; void make_bitmap() override { fBM.allocN32Pixels(int(fTextSize * 8), int(fTextSize * 6)); SkCanvas canvas(fBM); canvas.drawColor(SK_ColorWHITE); SkPaint paint; paint.setAntiAlias(true); paint.setSubpixelText(true); paint.setTextSize(fTextSize); setTypeface(&paint, "serif", SkFontStyle()); canvas.drawString("Hamburgefons", fTextSize/2, 1.2f*fTextSize, paint); setTypeface(&paint, "serif", SkFontStyle::Bold()); canvas.drawString("Hamburgefons", fTextSize/2, 2.4f*fTextSize, paint); setTypeface(&paint, "serif", SkFontStyle::Italic()); canvas.drawString("Hamburgefons", fTextSize/2, 3.6f*fTextSize, paint); setTypeface(&paint, "serif", SkFontStyle::BoldItalic()); canvas.drawString("Hamburgefons", fTextSize/2, 4.8f*fTextSize, paint); } private: typedef DownsampleBitmapGM INHERITED; }; class DownsampleBitmapCheckerboardGM: public DownsampleBitmapGM { public: DownsampleBitmapCheckerboardGM(int size, int numChecks, SkFilterQuality filterQuality) : INHERITED(filterQuality), fSize(size), fNumChecks(numChecks) { fName.printf("downsamplebitmap_checkerboard_%s_%d_%d", this->filterQualityToString(), fSize, fNumChecks); } protected: int fSize; int fNumChecks; void make_bitmap() override { make_checker(&fBM, fSize, fNumChecks); } private: typedef DownsampleBitmapGM INHERITED; }; class DownsampleBitmapImageGM: public DownsampleBitmapGM { public: explicit DownsampleBitmapImageGM(SkFilterQuality filterQuality) : INHERITED(filterQuality) { fName.printf("downsamplebitmap_image_%s", this->filterQualityToString()); } protected: int fSize; void make_bitmap() override { if (!GetResourceAsBitmap("images/mandrill_512.png", &fBM)) { fBM.allocN32Pixels(1, 1); fBM.eraseARGB(255, 255, 0 , 0); // red == bad } fSize = fBM.height(); } private: typedef DownsampleBitmapGM INHERITED; }; DEF_GM( return new DownsampleBitmapTextGM(72, kHigh_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapCheckerboardGM(512,256, kHigh_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapImageGM(kHigh_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapTextGM(72, kMedium_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapCheckerboardGM(512,256, kMedium_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapImageGM(kMedium_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapTextGM(72, kLow_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapCheckerboardGM(512,256, kLow_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapImageGM(kLow_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapTextGM(72, kNone_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapCheckerboardGM(512,256, kNone_SkFilterQuality); ) DEF_GM( return new DownsampleBitmapImageGM(kNone_SkFilterQuality); ) <|endoftext|>
<commit_before>#include <random> #include <String> #include <thread> #include <chrono> #include <iostream> #include <fstream> #include <mutex> using namespace std; using namespace std::chrono; unsigned int total_points; unsigned int total_circle; mutex total_points_mutex; mutex total_circle_mutex; // Create a distribution // uniform_real_distribution<double> distribution(0.0, 1.0); // Use this to get a random value from our random engine e // auto x = distribution(e); template <typename T> T average(T t[], int n) { T s = t[n - 1]; for (int i = 0; i < (n - 1); i++) s += t[i]; return s / n; } unsigned int correct_pi_digits(double p){ double actualPI = 3.1415926535897931; unsigned int i; for (i = 1; i < 16; i++) { double multiple = pow(10.0, i); double a = trunc(multiple * p); double b = trunc(multiple * actualPI); if (a != b) break; } return i; } void monte_carlo_pi(unsigned int iterations) { // Create a random engine auto millis = duration_cast<milliseconds>(system_clock::now().time_since_epoch()); default_random_engine e(millis.count()); // Create a distribution - we want doubles between 0.0 and 1.0 uniform_real_distribution<double> distribution(0.0, 1.0); // Keep track of number of points in circle unsigned int in_circle = 0; // Iterate for (unsigned int i = 0; i < iterations; ++i) { // Generate random point auto x = distribution(e); auto y = distribution(e); // Get length of vector defined - use Pythagarous auto length = sqrt((x * x) + (y * y)); // Check if in circle if (length <= 1.0) ++in_circle; } { std::lock_guard<std::mutex> lock(total_points_mutex); total_points += iterations; } { std::lock_guard<std::mutex> lock(total_circle_mutex); total_circle += in_circle; } // Calculate pi // auto pi = (4.0 * in_circle) / static_cast<double>(iterations); // cout << pi << endl; } const unsigned int loops = 5; int main() { cout << correct_pi_digits(3.1415926535897931) << endl; cout << correct_pi_digits(3.141592) << endl; cout << correct_pi_digits(3.1435926535897931) << endl; // Create data file ofstream data("montecarlo.csv", ofstream::out); data << "numbers per thread, threads, Avg Time(ms), Avg PI, Avg Error"<< endl; for (unsigned int total_numbers = 8; total_numbers <= 32; ++total_numbers) { cout << "\n total_numbers = " << total_numbers <<" - " << pow(2.0, total_numbers - 1) << endl; for (unsigned int num_threads = 1; num_threads <= 32; ++num_threads) { unsigned int thread_iterations = static_cast<unsigned int>(pow(2.0, total_numbers - 1) / num_threads); if (thread_iterations < 3) { continue; } // Write number of threads // cout << "Number of threads = " << num_threads << ", Numbers per thread // = " << thread_iterations << endl; // Write number of threads to the file double* pi_values = new double[loops]; long long* times = new long long[loops]; double* errors = new double[loops]; for (unsigned int iters = 0; iters < loops; ++iters) { { std::lock_guard<std::mutex> lock(total_points_mutex); total_points = 0; } { std::lock_guard<std::mutex> lock(total_circle_mutex); total_circle = 0; } // Get the start time auto start = system_clock::now(); //----------------------- Do work ----------------- // We need to create total_threads threads vector<thread> threads; for (unsigned int n = 0; n < num_threads; ++n) // Working in base 2 to make things a bit easier threads.push_back(thread(monte_carlo_pi, thread_iterations)); // Join the threads (wait for them to finish) for (auto &t : threads) t.join(); //-------------------------------------------------- // Get the end time auto end = system_clock::now(); // Get the total time auto total = end - start; // Convert to milliseconds and output to file double pi = (4.0 * total_circle) / static_cast<double>(total_points); long long ms = duration_cast<milliseconds>(total).count(); double actualPI = 3.1415926535897931; double error = abs((pi - actualPI) / actualPI) * 100.0; pi_values[iters] = pi; times[iters] = ms; errors[iters] = error; /* cout << num_threads << " threads computed Pi: " << pi << " In: " << ms << " milliseconds, Error: " << error << "%" << endl; data << ", " << ms << "ms"; */ } auto avg_pi = average(pi_values, loops); auto avg_time = average(times, loops); auto avg_err = average(errors, loops); cout << num_threads << " threads\tnumbers " << thread_iterations << "\t" << avg_pi << "\t" << avg_time << "ms\tscore " << correct_pi_digits(avg_pi) << " " << std::string(correct_pi_digits(avg_pi), '#') << endl; data << total_numbers << "," << num_threads << "," << avg_time << "," << avg_pi << "," << avg_err << endl; delete pi_values; delete times; delete errors; data << endl; } } // Close the file data.close(); return 0; }<commit_msg>some pi stuff<commit_after>#include <random> #include <String> #include <thread> #include <chrono> #include <iostream> #include <fstream> #include <mutex> using namespace std; using namespace std::chrono; unsigned int total_points; unsigned int total_circle; mutex total_points_mutex; mutex total_circle_mutex; #define MIN_THREADS 8 #define MAX_THREADS 8 #define LOOPS 10 #define MIN_POWER 8 #define MAX_POWER 32 // Create a distribution // uniform_real_distribution<double> distribution(0.0, 1.0); // Use this to get a random value from our random engine e // auto x = distribution(e); template <typename T> T average(T t[], int n) { T s = t[n - 1]; for (int i = 0; i < (n - 1); i++) s += t[i]; return s / n; } unsigned int correct_pi_digits(double p) { double actualPI = 3.1415926535897931; unsigned int i; for (i = 1; i < 16; i++) { double multiple = pow(10.0, i); double a = trunc(multiple * p); double b = trunc(multiple * actualPI); if (a != b) break; } return i; } void monte_carlo_pi(unsigned int iterations) { // Create a random engine auto millis = duration_cast<milliseconds>(system_clock::now().time_since_epoch()); default_random_engine e(millis.count()); // Create a distribution - we want doubles between 0.0 and 1.0 uniform_real_distribution<double> distribution(0.0, 1.0); // Keep track of number of points in circle unsigned int in_circle = 0; // Iterate for (unsigned int i = 0; i < iterations; ++i) { // Generate random point auto x = distribution(e); auto y = distribution(e); // Get length of vector defined - use Pythagarous auto length = abs(x * x) + abs(y * y); // Check if in circle if (length <= 1.0) ++in_circle; } { std::lock_guard<std::mutex> lock(total_points_mutex); total_points += iterations; } { std::lock_guard<std::mutex> lock(total_circle_mutex); total_circle += in_circle; } // Calculate pi // auto pi = (4.0 * in_circle) / static_cast<double>(iterations); // cout << pi << endl; } int main() { // Create data file ofstream data("montecarlo.csv", ofstream::out); data << "numbers per thread, threads, Avg Time(ms), Avg PI, Avg Error" << endl; for (unsigned int total_numbers = 1024; true; total_numbers+= 1024) { cout << "\n total_numbers = " << total_numbers << " - " << total_numbers << endl; for (unsigned int num_threads = MIN_THREADS; num_threads <= MAX_THREADS; ++num_threads) { unsigned int thread_iterations = static_cast<unsigned int>(total_numbers / num_threads); if (thread_iterations < 3) { continue; } // Write number of threads // cout << "Number of threads = " << num_threads << ", Numbers per thread // = " << thread_iterations << endl; // Write number of threads to the file unsigned int pi_digits[LOOPS]; long long times[LOOPS]; double errors[LOOPS]; for (unsigned int iters = 0; iters < LOOPS; ++iters) { { std::lock_guard<std::mutex> lock(total_points_mutex); total_points = 0; } { std::lock_guard<std::mutex> lock(total_circle_mutex); total_circle = 0; } // Get the start time auto start = system_clock::now(); //----------------------- Do work ----------------- // We need to create total_threads threads vector<thread> threads; for (unsigned int n = 0; n < num_threads; ++n) // Working in base 2 to make things a bit easier threads.push_back(thread(monte_carlo_pi, thread_iterations)); // Join the threads (wait for them to finish) for (auto &t : threads) t.join(); //-------------------------------------------------- // Get the end time auto end = system_clock::now(); // Get the total time auto total = end - start; // Convert to milliseconds and output to file double pi = (4.0 * total_circle) / static_cast<double>(total_points); long long ms = duration_cast<milliseconds>(total).count(); double actualPI = 3.1415926535897931; double error = abs((pi - actualPI) / actualPI) * 100.0; pi_digits[iters] = correct_pi_digits(pi); times[iters] = ms; errors[iters] = error; /* cout << num_threads << " threads computed Pi: " << pi << " In: " << ms << " milliseconds, Error: " << error << "%" << endl; data << ", " << ms << "ms"; */ } auto avg_digits = floor(average(pi_digits, LOOPS)); auto avg_time = average(times, LOOPS); auto avg_err = average(errors, LOOPS); cout << num_threads << " threads\tnumbers " << thread_iterations << "\t" << avg_time << "ms\tscore " << avg_digits << " " << std::string(avg_digits, '#') << endl; data << total_numbers << "," << num_threads << "," << avg_time << "," << avg_digits << "," << avg_err << endl; data << endl; } } // Close the file data.close(); return 0; }<|endoftext|>
<commit_before>/** * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io> * Authors: * - Laura Schlimmer <laura@eventql.io> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <poll.h> #include <thread> #include "eventql/eventql.h" #include "eventql/util/application.h" #include "eventql/util/logging.h" #include "eventql/util/WallClock.h" #include "eventql/util/return_code.h" #include "eventql/util/cli/CLI.h" #include "eventql/util/io/inputstream.h" #include "eventql/util/cli/term.h" #include "eventql/util/cli/flagparser.h" #include "eventql/util/thread/threadpool.h" #include "eventql/cli/cli_config.h" struct Waiter { //FIXME better naming uint64_t num_requests; }; struct TimeWindow { static constexpr auto kMillisPerWindow = 1 * kMillisPerSecond; TimeWindow(size_t requests_per_window) : requests_per_window_(requests_per_window), requests_done_(0) {} void addRequest() { ++requests_done_; } uint64_t getRemainingMillis() { UnixTime now; auto duration = now - start_; if (kMillisPerWindow < duration.milliseconds()) { return 0; } else { return kMillisPerWindow - duration.milliseconds(); } } size_t getRemainingRequests() { if (requests_per_window_ < requests_done_) { return 0; } else { return requests_per_window_ - requests_done_; } } void clear() { requests_done_ = 0; UnixTime now; start_ = now; } protected: size_t requests_per_window_; size_t requests_done_; UnixTime start_; }; static constexpr auto kMaxErrors = 10; struct RequestStats { uint64_t failed_requests; uint64_t successful_requests; }; ReturnCode sendQuery( const String& query, const String& qry_db, evql_client_t* client) { uint64_t qry_flags = 0; if (!qry_db.empty()) { qry_flags |= EVQL_QUERY_SWITCHDB; } int rc = evql_query(client, query.c_str(), qry_db.c_str(), qry_flags); size_t result_ncols; if (rc == 0) { rc = evql_num_columns(client, &result_ncols); } while (rc >= 0) { const char** fields; size_t* field_lens; rc = evql_fetch_row(client, &fields, &field_lens); if (rc < 1) { break; } } evql_client_releasebuffers(client); if (rc == -1) { return ReturnCode::error("EIOERROR", evql_client_geterror(client)); } else { return ReturnCode::success(); } } void print( RequestStats* rstats, OutputStream* stdout_os) { stdout_os->write(StringUtil::format( "total: $0 -- successful: $1 -- failed: $2 -- rate: \n", rstats->successful_requests + rstats->failed_requests, rstats->successful_requests, rstats->failed_requests)); } int main(int argc, const char** argv) { cli::FlagParser flags; flags.defineFlag( "help", cli::FlagParser::T_SWITCH, false, "?", NULL, "help", "<help>"); flags.defineFlag( "version", cli::FlagParser::T_SWITCH, false, "v", NULL, "print version", "<switch>"); flags.defineFlag( "host", cli::FlagParser::T_STRING, true, "h", NULL, "eventql server hostname", "<host>"); flags.defineFlag( "port", cli::FlagParser::T_INTEGER, true, "p", NULL, "eventql server port", "<port>"); flags.defineFlag( "database", cli::FlagParser::T_STRING, false, "d", NULL, "database", "<db>"); flags.defineFlag( "query", cli::FlagParser::T_STRING, true, "q", NULL, "query str", "<query>"); flags.defineFlag( "threads", cli::FlagParser::T_INTEGER, false, "t", "10", "number of threads", "<threads>"); flags.defineFlag( "rate", cli::FlagParser::T_INTEGER, false, "r", "1", "number of requests per second", "<rate>"); flags.defineFlag( "max", cli::FlagParser::T_INTEGER, false, "n", NULL, "number of requests per second", "<rate>"); flags.defineFlag( "loglevel", cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Vector<String> cmd_argv = flags.getArgv(); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); Application::init(); Application::logToStderr("evqlbenchmark"); auto stdin_is = InputStream::getStdin(); auto stdout_os = OutputStream::getStdout(); auto stderr_os = OutputStream::getStderr(); bool print_help = flags.isSet("help"); bool print_version = flags.isSet("version"); if (print_version || print_help) { auto stdout_os = OutputStream::getStdout(); stdout_os->write( StringUtil::format( "EventQL $0 ($1)\n" "Copyright (c) 2016, DeepCortex GmbH. All rights reserved.\n\n", eventql::kVersionString, eventql::kBuildID)); } if (print_version) { return 1; } if (print_help) { stdout_os->write( "Usage: $ evqlbenchmark [OPTIONS] <command> [<args>]\n\n" " -D, --database <db> Select a database\n" " -h, --host <hostname> Set the EventQL server hostname\n" " -p, --port <port> Set the EventQL server port\n" " -?, --help <topic> Display a command's help text and exit\n" " -v, --version Display the version of this binary and exit\n\n" "evqlbenchmark commands:\n" ); return 1; } logInfo("evqlbenchmark", "starting benchmark"); String qry_db; if (flags.isSet("database")) { qry_db = flags.getString("database"); } uint64_t num_threads; uint64_t max_requests; bool has_max_requests = false; try { num_threads = flags.getInt("threads"); max_requests = flags.getInt("max"); has_max_requests = true; } catch (const std::exception& e) { logFatal("evqlbenchmark", e.what()); return 0; } auto qry_str = flags.getString("query"); const UnixTime global_start; std::mutex m; RequestStats rstats; rstats.successful_requests = 0; rstats.failed_requests = 0; Vector<Waiter> waiters; auto num_stored_times = 10; std::queue<uint64_t> times(num_stored_times); Vector<std::thread> threads; for (size_t i = 0; i < num_threads; ++i) { /* init waiter */ Waiter waiter; waiter.num_requests = 0; waiters.emplace_back(waiter); threads.emplace_back(std::thread([&] () { /* connect to eventql client */ auto client = evql_client_init(); if (!client) { logFatal("evqlbenchmark", "can't initialize eventql client"); return 0; } { auto rc = evql_client_connect( client, flags.getString("host").c_str(), flags.getInt("port"), qry_db.c_str(), 0); if (rc < 0) { logFatal( "evqlbenchmark", "can't connect to eventql client: $0", evql_client_geterror(client)); return 0; } } for (;;) { /* insert time of current request */ m.lock(); auto now = WallClock::now(); m.unlock(); auto rc = sendQuery(qry_str, qry_db, client); if (!rc.isSuccess()) { logFatal("evqlbenchmark", "executing query failed: $0", rc.getMessage()); ++rstats.failed_requests; } else { ++rstats.successful_requests; } print(&rstats, stdout_os.get()); /* stop */ if (rstats.failed_requests > kMaxErrors || (has_max_requests && rstats.failed_requests + rstats.successful_requests >= max_requests)) { break; } } evql_client_close(client); })); } for (auto& t : threads) { t.join(); } print(&rstats, stdout_os.get()); return 0; } <commit_msg>calculate sleep time<commit_after>/** * Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io> * Authors: * - Laura Schlimmer <laura@eventql.io> * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License ("the license") as * published by the Free Software Foundation, either version 3 of the License, * or any later version. * * In accordance with Section 7(e) of the license, the licensing of the Program * under the license does not imply a trademark license. Therefore any rights, * title and interest in our trademarks remain entirely with us. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the license for more details. * * You can be released from the requirements of the license by purchasing a * commercial license. Buying such a license is mandatory as soon as you develop * commercial activities involving this program without disclosing the source * code of your own applications */ #include <queue> #include <thread> #include "eventql/eventql.h" #include "eventql/util/application.h" #include "eventql/util/logging.h" #include "eventql/util/WallClock.h" #include "eventql/util/return_code.h" #include "eventql/util/cli/CLI.h" #include "eventql/util/io/inputstream.h" #include "eventql/util/cli/term.h" #include "eventql/util/cli/flagparser.h" #include "eventql/util/thread/threadpool.h" #include "eventql/cli/cli_config.h" struct Waiter { //FIXME better naming uint64_t num_requests; }; static constexpr auto kMaxErrors = 10; struct RequestStats { uint64_t failed_requests; uint64_t successful_requests; }; ReturnCode sendQuery( const String& query, const String& qry_db, evql_client_t* client) { uint64_t qry_flags = 0; if (!qry_db.empty()) { qry_flags |= EVQL_QUERY_SWITCHDB; } int rc = evql_query(client, query.c_str(), qry_db.c_str(), qry_flags); size_t result_ncols; if (rc == 0) { rc = evql_num_columns(client, &result_ncols); } while (rc >= 0) { const char** fields; size_t* field_lens; rc = evql_fetch_row(client, &fields, &field_lens); if (rc < 1) { break; } } evql_client_releasebuffers(client); if (rc == -1) { return ReturnCode::error("EIOERROR", evql_client_geterror(client)); } else { return ReturnCode::success(); } } void print( RequestStats* rstats, OutputStream* stdout_os) { stdout_os->write(StringUtil::format( "total: $0 -- successful: $1 -- failed: $2 -- rate: \n", rstats->successful_requests + rstats->failed_requests, rstats->successful_requests, rstats->failed_requests)); } int main(int argc, const char** argv) { cli::FlagParser flags; flags.defineFlag( "help", cli::FlagParser::T_SWITCH, false, "?", NULL, "help", "<help>"); flags.defineFlag( "version", cli::FlagParser::T_SWITCH, false, "v", NULL, "print version", "<switch>"); flags.defineFlag( "host", cli::FlagParser::T_STRING, true, "h", NULL, "eventql server hostname", "<host>"); flags.defineFlag( "port", cli::FlagParser::T_INTEGER, true, "p", NULL, "eventql server port", "<port>"); flags.defineFlag( "database", cli::FlagParser::T_STRING, false, "d", NULL, "database", "<db>"); flags.defineFlag( "query", cli::FlagParser::T_STRING, true, "q", NULL, "query str", "<query>"); flags.defineFlag( "threads", cli::FlagParser::T_INTEGER, false, "t", "10", "number of threads", "<threads>"); flags.defineFlag( "rate", cli::FlagParser::T_INTEGER, false, "r", "1", "number of requests per second", "<rate>"); flags.defineFlag( "max", cli::FlagParser::T_INTEGER, false, "n", NULL, "number of requests per second", "<rate>"); flags.defineFlag( "loglevel", cli::FlagParser::T_STRING, false, NULL, "INFO", "loglevel", "<level>"); flags.parseArgv(argc, argv); Vector<String> cmd_argv = flags.getArgv(); Logger::get()->setMinimumLogLevel( strToLogLevel(flags.getString("loglevel"))); Application::init(); Application::logToStderr("evqlbenchmark"); auto stdin_is = InputStream::getStdin(); auto stdout_os = OutputStream::getStdout(); auto stderr_os = OutputStream::getStderr(); bool print_help = flags.isSet("help"); bool print_version = flags.isSet("version"); if (print_version || print_help) { auto stdout_os = OutputStream::getStdout(); stdout_os->write( StringUtil::format( "EventQL $0 ($1)\n" "Copyright (c) 2016, DeepCortex GmbH. All rights reserved.\n\n", eventql::kVersionString, eventql::kBuildID)); } if (print_version) { return 1; } if (print_help) { stdout_os->write( "Usage: $ evqlbenchmark [OPTIONS] <command> [<args>]\n\n" " -D, --database <db> Select a database\n" " -h, --host <hostname> Set the EventQL server hostname\n" " -p, --port <port> Set the EventQL server port\n" " -?, --help <topic> Display a command's help text and exit\n" " -v, --version Display the version of this binary and exit\n\n" "evqlbenchmark commands:\n" ); return 1; } logInfo("evqlbenchmark", "starting benchmark"); String qry_db; if (flags.isSet("database")) { qry_db = flags.getString("database"); } uint64_t num_threads = flags.getInt("threads"); uint64_t rate = flags.getInt("rate"); /* request duration per microsecond */ auto target_duration = 1 * kMicrosPerSecond / rate; uint64_t max_requests; bool has_max_requests = false; if (flags.isSet("max")) { max_requests = flags.getInt("max"); has_max_requests = true; } auto qry_str = flags.getString("query"); const UnixTime global_start; std::mutex m; RequestStats rstats; rstats.successful_requests = 0; rstats.failed_requests = 0; Vector<Waiter> waiters; auto num_stored_times = 10; std::queue<uint64_t> times; Vector<std::thread> threads; for (size_t i = 0; i < num_threads; ++i) { /* init waiter */ Waiter waiter; waiter.num_requests = 0; waiters.emplace_back(waiter); threads.emplace_back(std::thread([&] () { /* connect to eventql client */ auto client = evql_client_init(); if (!client) { logFatal("evqlbenchmark", "can't initialize eventql client"); return 0; } { auto rc = evql_client_connect( client, flags.getString("host").c_str(), flags.getInt("port"), qry_db.c_str(), 0); if (rc < 0) { logFatal( "evqlbenchmark", "can't connect to eventql client: $0", evql_client_geterror(client)); return 0; } } for (;;) { /* calculate sleep time */ auto now = WallClock::now(); uint64_t sleep = 0; m.lock(); if (times.size() > 0) { auto total_duration = times.back() - times.front(); auto avg_duration = total_duration / times.size(); sleep = target_duration - avg_duration; } if (times.size() == 10) { times.pop(); } times.push(now.unixMicros()); //push after sleep? m.unlock(); usleep(sleep); auto rc = sendQuery(qry_str, qry_db, client); if (!rc.isSuccess()) { logFatal("evqlbenchmark", "executing query failed: $0", rc.getMessage()); ++rstats.failed_requests; } else { ++rstats.successful_requests; } print(&rstats, stdout_os.get()); /* stop */ if (rstats.failed_requests > kMaxErrors || (has_max_requests && rstats.failed_requests + rstats.successful_requests >= max_requests)) { break; } } evql_client_close(client); })); } for (auto& t : threads) { t.join(); } print(&rstats, stdout_os.get()); return 0; } <|endoftext|>
<commit_before>#pragma once #include <fstream> #include <Eigen/Dense> template<class Matrix> void readEigenMatrixFromFile(const std::string &filename, Matrix& matrix, bool binary = true) { if (binary) { std::ifstream in(filename, std::ifstream::binary); typename Matrix::Index rows = 0, cols = 0; in.read((char*)(&rows), sizeof(typename Matrix::Index)); in.read((char*)(&cols), sizeof(typename Matrix::Index)); matrix.resize(rows, cols); in.read((char*)matrix.data(), rows*cols*sizeof(typename Matrix::Scalar)); in.close(); } else { std::ifstream in(filename.c_str(), std::ios::in); // Read file contents into a vector std::string line; typename Matrix::Scalar d; std::vector<typename Matrix::Scalar> v; int n_rows = 0; while (getline(in, line)) { ++n_rows; std::stringstream input_line(line); while (!input_line.eof()) { input_line >> d; v.emplace_back(d); } } in.close(); // Construct matrix int n_cols = v.size()/n_rows; matrix = Eigen::Matrix<typename Matrix::Scalar,Eigen::Dynamic,Eigen::Dynamic>(n_rows, n_cols); for (size_t i = 0; i < n_rows; i++) for (size_t j = 0; j < n_cols; j++) matrix(i,j) = v[i*n_cols + j]; } } template<class Matrix> void writeEigenMatrixToFile(const std::string &filename, const Matrix& matrix, bool binary = true) { if (binary) { std::ofstream out(filename, std::ofstream::binary); typename Matrix::Index rows = matrix.rows(), cols = matrix.cols(); out.write((char*)(&rows), sizeof(typename Matrix::Index)); out.write((char*)(&cols), sizeof(typename Matrix::Index)); out.write((char*)matrix.data(), rows*cols*sizeof(typename Matrix::Scalar)); out.close(); } else { std::ofstream out(filename.c_str(), std::ios::out); out << matrix << "\n"; out.close(); } } template<typename ScalarT> void readVectorFromFile(const std::string &filename, std::vector<ScalarT> &vec, bool binary = true) { Eigen::Matrix<ScalarT, Eigen::Dynamic, 1> vec_e; readEigenMatrixFromFile(filename, vec_e, binary); vec.resize(vec_e.size()); Eigen::Matrix<ScalarT, Eigen::Dynamic, 1>::Map(&vec[0], vec_e.size()) = vec_e; } template<typename ScalarT> void writeVectorToFile(const std::string &filename, const std::vector<ScalarT> &vec, bool binary = true) { Eigen::Matrix<ScalarT, Eigen::Dynamic, 1> vec_e = Eigen::Matrix<ScalarT, Eigen::Dynamic, 1>::Map(&vec[0], vec.size()); writeEigenMatrixToFile(filename, vec_e, binary); } <commit_msg>Minor changes<commit_after>#pragma once #include <fstream> #include <Eigen/Dense> template<class Matrix> void readEigenMatrixFromFile(const std::string &filename, Matrix &matrix, bool binary = true) { if (binary) { std::ifstream in(filename, std::ifstream::binary); typename Matrix::Index rows = 0, cols = 0; in.read((char*)(&rows), sizeof(typename Matrix::Index)); in.read((char*)(&cols), sizeof(typename Matrix::Index)); matrix.resize(rows, cols); in.read((char*)matrix.data(), rows*cols*sizeof(typename Matrix::Scalar)); in.close(); } else { std::ifstream in(filename.c_str(), std::ios::in); // Read file contents into a vector std::string line; typename Matrix::Scalar d; std::vector<typename Matrix::Scalar> v; size_t n_rows = 0; while (getline(in, line)) { n_rows++; std::stringstream input_line(line); while (!input_line.eof()) { input_line >> d; v.emplace_back(d); } } in.close(); // Construct matrix size_t n_cols = v.size()/n_rows; matrix.resize(n_rows, n_cols); for (size_t i = 0; i < n_rows; i++) { for (size_t j = 0; j < n_cols; j++) { matrix(i,j) = v[i * n_cols + j]; } } } } template<class Matrix> void writeEigenMatrixToFile(const std::string &filename, const Matrix &matrix, bool binary = true) { if (binary) { std::ofstream out(filename, std::ofstream::binary); typename Matrix::Index rows = matrix.rows(), cols = matrix.cols(); out.write((char*)(&rows), sizeof(typename Matrix::Index)); out.write((char*)(&cols), sizeof(typename Matrix::Index)); out.write((char*)matrix.data(), rows*cols*sizeof(typename Matrix::Scalar)); out.close(); } else { std::ofstream out(filename.c_str(), std::ios::out); out << matrix << "\n"; out.close(); } } template<typename ScalarT> void readVectorFromFile(const std::string &filename, std::vector<ScalarT> &vec, bool binary = true) { Eigen::Matrix<ScalarT, Eigen::Dynamic, 1> vec_e; readEigenMatrixFromFile<Eigen::Matrix<ScalarT, Eigen::Dynamic, 1> >(filename, vec_e, binary); vec.resize(vec_e.size()); Eigen::Matrix<ScalarT, Eigen::Dynamic, 1>::Map(&vec[0], vec_e.size()) = vec_e; } template<typename ScalarT> void writeVectorToFile(const std::string &filename, const std::vector<ScalarT> &vec, bool binary = true) { Eigen::Matrix<ScalarT, Eigen::Dynamic, 1> vec_e = Eigen::Matrix<ScalarT, Eigen::Dynamic, 1>::Map(&vec[0], vec.size()); writeEigenMatrixToFile<Eigen::Matrix<ScalarT, Eigen::Dynamic, 1> >(filename, vec_e, binary); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dlgname.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-01-05 16:24:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <tools/ref.hxx> #include <tools/list.hxx> #ifndef _SHL_HXX #include <tools/shl.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #pragma hdrstop #include "dialogs.hrc" #include "dlgname.hxx" #include "dlgname.hrc" #include "dialmgr.hxx" /************************************************************************* |* |* Dialog zum Editieren eines Namens |* \************************************************************************/ SvxNameDialog::SvxNameDialog( Window* pWindow, const String& rName, const String& rDesc ) : ModalDialog ( pWindow, ResId( RID_SVXDLG_NAME, DIALOG_MGR() ) ), aFtDescription ( this, ResId( FT_DESCRIPTION ) ), aEdtName ( this, ResId( EDT_STRING ) ), aBtnOK ( this, ResId( BTN_OK ) ), aBtnCancel ( this, ResId( BTN_CANCEL ) ), aBtnHelp ( this, ResId( BTN_HELP ) ) { FreeResource(); aFtDescription.SetText( rDesc ); aEdtName.SetText( rName ); aEdtName.SetSelection(Selection(SELECTION_MIN, SELECTION_MAX)); ModifyHdl(&aEdtName); aEdtName.SetModifyHdl(LINK(this, SvxNameDialog, ModifyHdl)); } /* -----------------------------27.02.2002 15:22------------------------------ ---------------------------------------------------------------------------*/ IMPL_LINK(SvxNameDialog, ModifyHdl, Edit*, pEdit) { if(aCheckNameHdl.IsSet()) aBtnOK.Enable(aCheckNameHdl.Call(this) > 0); return 0; } /************************************************************************* |* |* Dialog zum Abbrechen, Speichern oder Hinzufuegen |* \************************************************************************/ SvxMessDialog::SvxMessDialog( Window* pWindow, const String& rText, const String& rDesc, Image* pImg ) : ModalDialog ( pWindow, ResId( RID_SVXDLG_MESSBOX, DIALOG_MGR() ) ), aFtDescription ( this, ResId( FT_DESCRIPTION ) ), aBtn1 ( this, ResId( BTN_1 ) ), aBtn2 ( this, ResId( BTN_2 ) ), aBtnCancel ( this, ResId( BTN_CANCEL ) ), aFtImage ( this ) { FreeResource(); if( pImg ) { pImage = new Image( *pImg ); aFtImage.SetImage( *pImage ); aFtImage.SetStyle( ( aFtImage.GetStyle()/* | WB_NOTABSTOP */) & ~WB_3DLOOK ); aFtImage.SetPosSizePixel( LogicToPixel( Point( 3, 6 ), MAP_APPFONT ), aFtImage.GetImage().GetSizePixel() ); aFtImage.Show(); } SetText( rText ); aFtDescription.SetText( rDesc ); aBtn1.SetClickHdl( LINK( this, SvxMessDialog, Button1Hdl ) ); aBtn2.SetClickHdl( LINK( this, SvxMessDialog, Button2Hdl ) ); } SvxMessDialog::~SvxMessDialog() { if( pImage ) delete pImage; } /*************************************************************************/ IMPL_LINK_INLINE_START( SvxMessDialog, Button1Hdl, Button *, EMPTYARG ) { EndDialog( RET_BTN_1 ); return 0; } IMPL_LINK_INLINE_END( SvxMessDialog, Button1Hdl, Button *, EMPTYARG ) /*************************************************************************/ IMPL_LINK_INLINE_START( SvxMessDialog, Button2Hdl, Button *, EMPTYARG ) { EndDialog( RET_BTN_2 ); return 0; } IMPL_LINK_INLINE_END( SvxMessDialog, Button2Hdl, Button *, EMPTYARG ) /*************************************************************************/ void SvxMessDialog::SetButtonText( USHORT nBtnId, const String& rNewTxt ) { switch ( nBtnId ) { case MESS_BTN_1: aBtn1.SetText( rNewTxt ); break; case MESS_BTN_2: aBtn2.SetText( rNewTxt ); break; default: DBG_ERROR( "Falsche Button-Nummer!!!" ); } } <commit_msg>INTEGRATION: CWS dialogdiet (1.2.490); FILE MERGED 2004/01/19 21:02:47 mba 1.2.490.2: RESYNC: (1.2-1.3); FILE MERGED 2004/01/13 03:12:03 mwu 1.2.490.1: DialogDiet 2004_01_13<commit_after>/************************************************************************* * * $RCSfile: dlgname.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2004-02-03 18:25:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <tools/ref.hxx> #include <tools/list.hxx> #ifndef _SHL_HXX #include <tools/shl.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #pragma hdrstop #include "dialogs.hrc" #include "dlgname.hxx" #include "defdlgname.hxx" //CHINA001 #include "dlgname.hrc" #include "dialmgr.hxx" /************************************************************************* |* |* Dialog zum Editieren eines Namens |* \************************************************************************/ SvxNameDialog::SvxNameDialog( Window* pWindow, const String& rName, const String& rDesc ) : ModalDialog ( pWindow, ResId( RID_SVXDLG_NAME, DIALOG_MGR() ) ), aFtDescription ( this, ResId( FT_DESCRIPTION ) ), aEdtName ( this, ResId( EDT_STRING ) ), aBtnOK ( this, ResId( BTN_OK ) ), aBtnCancel ( this, ResId( BTN_CANCEL ) ), aBtnHelp ( this, ResId( BTN_HELP ) ) { FreeResource(); aFtDescription.SetText( rDesc ); aEdtName.SetText( rName ); aEdtName.SetSelection(Selection(SELECTION_MIN, SELECTION_MAX)); ModifyHdl(&aEdtName); aEdtName.SetModifyHdl(LINK(this, SvxNameDialog, ModifyHdl)); } /* -----------------------------27.02.2002 15:22------------------------------ ---------------------------------------------------------------------------*/ IMPL_LINK(SvxNameDialog, ModifyHdl, Edit*, pEdit) { if(aCheckNameHdl.IsSet()) aBtnOK.Enable(aCheckNameHdl.Call(this) > 0); return 0; } /************************************************************************* |* |* Dialog zum Abbrechen, Speichern oder Hinzufuegen |* \************************************************************************/ SvxMessDialog::SvxMessDialog( Window* pWindow, const String& rText, const String& rDesc, Image* pImg ) : ModalDialog ( pWindow, ResId( RID_SVXDLG_MESSBOX, DIALOG_MGR() ) ), aFtDescription ( this, ResId( FT_DESCRIPTION ) ), aBtn1 ( this, ResId( BTN_1 ) ), aBtn2 ( this, ResId( BTN_2 ) ), aBtnCancel ( this, ResId( BTN_CANCEL ) ), aFtImage ( this ) { FreeResource(); if( pImg ) { pImage = new Image( *pImg ); aFtImage.SetImage( *pImage ); aFtImage.SetStyle( ( aFtImage.GetStyle()/* | WB_NOTABSTOP */) & ~WB_3DLOOK ); aFtImage.SetPosSizePixel( LogicToPixel( Point( 3, 6 ), MAP_APPFONT ), aFtImage.GetImage().GetSizePixel() ); aFtImage.Show(); } SetText( rText ); aFtDescription.SetText( rDesc ); aBtn1.SetClickHdl( LINK( this, SvxMessDialog, Button1Hdl ) ); aBtn2.SetClickHdl( LINK( this, SvxMessDialog, Button2Hdl ) ); } SvxMessDialog::~SvxMessDialog() { if( pImage ) delete pImage; } /*************************************************************************/ IMPL_LINK_INLINE_START( SvxMessDialog, Button1Hdl, Button *, EMPTYARG ) { EndDialog( RET_BTN_1 ); return 0; } IMPL_LINK_INLINE_END( SvxMessDialog, Button1Hdl, Button *, EMPTYARG ) /*************************************************************************/ IMPL_LINK_INLINE_START( SvxMessDialog, Button2Hdl, Button *, EMPTYARG ) { EndDialog( RET_BTN_2 ); return 0; } IMPL_LINK_INLINE_END( SvxMessDialog, Button2Hdl, Button *, EMPTYARG ) /*************************************************************************/ void SvxMessDialog::SetButtonText( USHORT nBtnId, const String& rNewTxt ) { switch ( nBtnId ) { case MESS_BTN_1: aBtn1.SetText( rNewTxt ); break; case MESS_BTN_2: aBtn2.SetText( rNewTxt ); break; default: DBG_ERROR( "Falsche Button-Nummer!!!" ); } } <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2013, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file control_flow.cxx * * Class running processes with asynchronous I/O. * * @author Balazs Racz * @date 5 Aug 2013 */ #include "executor/control_flow.hxx" void ControlFlow::Run() { LOG(VERBOSE, "ControlFlow::Run %p", this); HASSERT(state_); do { ControlFlowAction action = (this->*state_)(); // We got a WaitForNotification. if (!action.next_state_) return; state_ = action.next_state_; } while (1); } ControlFlow::ControlFlowAction ControlFlow::Exit() { if (done_) { state_ = &ControlFlow::Terminated; done_->Notify(); } else { delete this; } // If we return waitfornotification, the run method will not access *this // anymore, which is perfect if we just deleted ourselves. return WaitForNotification(); } ControlFlow::ControlFlowAction ControlFlow::NotStarted() { return WaitForNotification(); } ControlFlow::ControlFlowAction ControlFlow::Terminated() { return WaitForNotification(); } ControlFlow::SleepData::~SleepData() { if (timer_handle != NULL) { os_timer_delete(timer_handle); timer_handle = NULL; } } void ControlFlow::NotifyControlFlowTimer(SleepData* entry) { LockHolder h(executor()); entry->callback_count++; // here we use that executor's mutex is reentrant. Notify(); } long long ControlFlow::control_flow_single_timer(void* arg_flow, void* arg_entry) { ControlFlow::SleepData* entry = static_cast<ControlFlow::SleepData*>(arg_entry); ControlFlow* flow = static_cast<ControlFlow*>(arg_flow); flow->NotifyControlFlowTimer(entry); return OS_TIMER_NONE; // no restart. } long long ControlFlow::control_flow_repeated_timer(void* arg_flow, void* arg_entry) { ControlFlow::SleepData* entry = static_cast<ControlFlow::SleepData*>(arg_entry); ControlFlow* flow = static_cast<ControlFlow*>(arg_flow); flow->NotifyControlFlowTimer(entry); return OS_TIMER_RESTART; } ControlFlow::ControlFlowAction ControlFlow::Sleep(SleepData* data, long long delay_nsec, MemberFunction next_state) { HASSERT(data->callback_count == 0); if (data->timer_handle == NULL) { data->timer_handle = os_timer_create(&control_flow_single_timer, this, data); } os_timer_start(data->timer_handle, delay_nsec); return WaitForTimerWakeUpAndCall(data, next_state); } void ControlFlow::WakeUpRepeatedly(SleepData* data, long long period_nsec) { if (data->timer_handle != NULL) { os_timer_delete(data->timer_handle); } data->timer_handle = os_timer_create(&control_flow_repeated_timer, this, data); os_timer_start(data->timer_handle, period_nsec); } void ControlFlow::StopTimer(SleepData* data) { HASSERT(data->timer_handle != NULL); os_timer_delete(data->timer_handle); data->timer_handle = NULL; } ControlFlow::ControlFlowAction ControlFlow::WaitForTimerWakeUpAndCall( SleepData* data, MemberFunction next_state) { next_state_ = next_state; sub_flow_.sleep = data; // We use CallImmediately here in case the timer has expired before (or // immediately). Useful especially for repeated calls. return CallImmediately(&ControlFlow::WaitForTimer); } ControlFlow::ControlFlowAction ControlFlow::WaitForTimer() { { LockHolder h(executor_); if (sub_flow_.sleep->callback_count == 0) return WaitForNotification(); --sub_flow_.sleep->callback_count; } return CallImmediately(next_state_); } //! Implementation state that is waiting for another flow to finish. ControlFlow::ControlFlowAction ControlFlow::WaitForControlFlow() { LockHolder h(executor_); if (sub_flow_.called_flow->IsDone()) { return CallImmediately(next_state_); } else { return WaitForNotification(); } } <commit_msg>Allows a timer to be stopped without penalties. A spurious notification later has to be tolerated. Changes control flow timer stop to not deallocate the timer.<commit_after>/** \copyright * Copyright (c) 2013, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file control_flow.cxx * * Class running processes with asynchronous I/O. * * @author Balazs Racz * @date 5 Aug 2013 */ #include "executor/control_flow.hxx" void ControlFlow::Run() { LOG(VERBOSE, "ControlFlow::Run %p", this); HASSERT(state_); do { ControlFlowAction action = (this->*state_)(); // We got a WaitForNotification. if (!action.next_state_) return; state_ = action.next_state_; } while (1); } ControlFlow::ControlFlowAction ControlFlow::Exit() { if (done_) { state_ = &ControlFlow::Terminated; done_->Notify(); } else { delete this; } // If we return waitfornotification, the run method will not access *this // anymore, which is perfect if we just deleted ourselves. return WaitForNotification(); } ControlFlow::ControlFlowAction ControlFlow::NotStarted() { return WaitForNotification(); } ControlFlow::ControlFlowAction ControlFlow::Terminated() { return WaitForNotification(); } ControlFlow::SleepData::~SleepData() { if (timer_handle != NULL) { os_timer_delete(timer_handle); timer_handle = NULL; } } void ControlFlow::NotifyControlFlowTimer(SleepData* entry) { LockHolder h(executor()); entry->callback_count++; // here we use that executor's mutex is reentrant. Notify(); } long long ControlFlow::control_flow_single_timer(void* arg_flow, void* arg_entry) { ControlFlow::SleepData* entry = static_cast<ControlFlow::SleepData*>(arg_entry); ControlFlow* flow = static_cast<ControlFlow*>(arg_flow); flow->NotifyControlFlowTimer(entry); return OS_TIMER_NONE; // no restart. } long long ControlFlow::control_flow_repeated_timer(void* arg_flow, void* arg_entry) { ControlFlow::SleepData* entry = static_cast<ControlFlow::SleepData*>(arg_entry); ControlFlow* flow = static_cast<ControlFlow*>(arg_flow); flow->NotifyControlFlowTimer(entry); return OS_TIMER_RESTART; } ControlFlow::ControlFlowAction ControlFlow::Sleep(SleepData* data, long long delay_nsec, MemberFunction next_state) { data->callback_count = 0; if (data->timer_handle == NULL) { data->timer_handle = os_timer_create(&control_flow_single_timer, this, data); } os_timer_start(data->timer_handle, delay_nsec); return WaitForTimerWakeUpAndCall(data, next_state); } void ControlFlow::WakeUpRepeatedly(SleepData* data, long long period_nsec) { if (data->timer_handle != NULL) { os_timer_delete(data->timer_handle); } data->timer_handle = os_timer_create(&control_flow_repeated_timer, this, data); os_timer_start(data->timer_handle, period_nsec); } void ControlFlow::StopTimer(SleepData* data) { HASSERT(data->timer_handle != NULL); os_timer_stop(data->timer_handle); } ControlFlow::ControlFlowAction ControlFlow::WaitForTimerWakeUpAndCall( SleepData* data, MemberFunction next_state) { next_state_ = next_state; sub_flow_.sleep = data; // We use CallImmediately here in case the timer has expired before (or // immediately). Useful especially for repeated calls. return CallImmediately(&ControlFlow::WaitForTimer); } ControlFlow::ControlFlowAction ControlFlow::WaitForTimer() { { LockHolder h(executor_); if (sub_flow_.sleep->callback_count == 0) return WaitForNotification(); --sub_flow_.sleep->callback_count; } return CallImmediately(next_state_); } //! Implementation state that is waiting for another flow to finish. ControlFlow::ControlFlowAction ControlFlow::WaitForControlFlow() { LockHolder h(executor_); if (sub_flow_.called_flow->IsDone()) { return CallImmediately(next_state_); } else { return WaitForNotification(); } } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include <fstream> #include "cpp_utils/assert.hpp" //Assertions #include "cpp_utils/io.hpp" // For binary writing #include "etl/etl.hpp" #include "layer.hpp" #include "layer_traits.hpp" #include "util/tmp.hpp" namespace dll { /*! * \brief Base class for RNN layers (fast / dynamic) */ template <typename Derived, typename Desc> struct base_rnn_layer : layer<Derived> { using desc = Desc; ///< The descriptor of the layer using derived_t = Derived; ///< The derived type (CRTP) using weight = typename desc::weight; ///< The data type for this layer using this_type = base_rnn_layer<derived_t, desc>; ///< The type of this layer using base_type = layer<Derived>; ///< The base type static constexpr auto activation_function = desc::activation_function; ///< The layer's activation function /*! * \brief Initialize the neural layer */ base_rnn_layer() : base_type() { // Nothing to init here } base_rnn_layer(const base_rnn_layer& rhs) = delete; base_rnn_layer(base_rnn_layer&& rhs) = delete; base_rnn_layer& operator=(const base_rnn_layer& rhs) = delete; base_rnn_layer& operator=(base_rnn_layer&& rhs) = delete; /*! * \brief Apply the layer to the given batch of input. * * \param x A batch of input * \param output A batch of output that will be filled * \param w The W weights matrix * \param u The U weights matrix */ template <typename H, typename V, typename W, typename U, typename B> static void forward_batch_impl(H&& output, const V& x, const W& w, const U& u, const B& b, size_t time_steps, size_t sequence_length, size_t hidden_units) { const auto Batch = etl::dim<0>(x); etl::dyn_matrix<float, 3> x_t(time_steps, etl::dim<0>(x), sequence_length); etl::dyn_matrix<float, 3> s_t(time_steps, etl::dim<0>(x), hidden_units); // 1. Rearrange input for (size_t b = 0; b < Batch; ++b) { for (size_t t = 0; t < time_steps; ++t) { x_t(t)(b) = x(b)(t); } } // 2. Forward propagation through time // t == 0 s_t(0) = f_activate<activation_function>(bias_add_2d(x_t(0) * u, b)); for (size_t t = 1; t < time_steps; ++t) { s_t(t) = f_activate<activation_function>(bias_add_2d(x_t(t) * u + s_t(t - 1) * w, b)); } // 3. Rearrange the output for (size_t b = 0; b < Batch; ++b) { for (size_t t = 0; t < time_steps; ++t) { output(b)(t) = s_t(t)(b); } } } /*! * \brief Backpropagate the errors to the previous layers * \param output The ETL expression into which write the output * \param context The training context */ template <typename H, typename C, typename W> void backward_batch_impl(H&& output, C& context, const W& w, size_t time_steps, size_t sequence_length, size_t hidden_units, size_t bptt_steps) const { const size_t Batch = etl::dim<0>(context.errors); etl::dyn_matrix<float, 3> output_t(time_steps, Batch, sequence_length); etl::dyn_matrix<float, 3> s_t(time_steps, Batch, hidden_units); etl::dyn_matrix<float, 3> o_t(time_steps, Batch, hidden_units); // 1. Rearrange o/s for (size_t b = 0; b < Batch; ++b) { for (size_t t = 0; t < time_steps; ++t) { s_t(t)(b) = context.output(b)(t); } } for (size_t b = 0; b < Batch; ++b) { for (size_t t = 0; t < time_steps; ++t) { o_t(t)(b) = context.errors(b)(t); } } // 2. Backpropagation through time size_t t = time_steps - 1; do { output_t(t) = etl::force_temporary(o_t(t) >> f_derivative<activation_function>(s_t(t))); size_t bptt_step = t; const size_t last_step = std::max(int(time_steps) - int(bptt_steps), 0); do { output_t(t) = (output_t(t) * trans(w)) >> f_derivative<activation_function>(s_t(bptt_step - 1)); --bptt_step; } while (bptt_step > last_step); // bptt_step = 0 --t; // If only the last time step is used, no need to use the other errors if /*constexpr*/ (desc::parameters::template contains<last_only>()) { break; } } while (t != 0); // 3. Rearrange for the output for (size_t b = 0; b < Batch; ++b) { for (size_t t = 0; t < time_steps; ++t) { output(b)(t) = output_t(t)(b); } } } /*! * \brief Compute the gradients for this layer, if any * \param context The trainng context */ template <typename C, typename W> static void compute_gradients_impl(C& context, const W& w, size_t time_steps, size_t sequence_length, size_t hidden_units, size_t bptt_steps) { const size_t Batch = etl::dim<0>(context.errors); auto& x = context.input; auto& s = context.output; etl::dyn_matrix<float, 3> x_t(time_steps, Batch, sequence_length); etl::dyn_matrix<float, 3> s_t(time_steps, Batch, hidden_units); etl::dyn_matrix<float, 3> o_t(time_steps, Batch, hidden_units); etl::dyn_matrix<float, 3> d_h_t(time_steps, Batch, hidden_units); // 1. Rearrange x/s for (size_t b = 0; b < Batch; ++b) { for (size_t t = 0; t < time_steps; ++t) { x_t(t)(b) = x(b)(t); } } for (size_t b = 0; b < Batch; ++b) { for (size_t t = 0; t < time_steps; ++t) { s_t(t)(b) = s(b)(t); } } for (size_t b = 0; b < Batch; ++b) { for (size_t t = 0; t < time_steps; ++t) { o_t(t)(b) = context.errors(b)(t); } } auto& w_grad = std::get<0>(context.up.context)->grad; auto& u_grad = std::get<1>(context.up.context)->grad; auto& b_grad = std::get<2>(context.up.context)->grad; w_grad = 0; u_grad = 0; b_grad = 0; size_t ttt = time_steps - 1; do { const size_t last_step = std::max(int(time_steps) - int(bptt_steps), 0); // Backpropagation through time for (int tt = ttt; tt >= int(last_step); --tt) { const size_t t = tt; if(t == time_steps - 1){ d_h_t(t) = o_t(t) >> f_derivative<activation_function>(s_t(t)); } else { d_h_t(t) = (o_t(t) + d_h_t(t + 1)) >> f_derivative<activation_function>(s_t(t)); } if (t > 0) { w_grad += etl::batch_outer(s_t(t - 1), d_h_t(t)); } u_grad += etl::batch_outer(x_t(t), d_h_t(t)); b_grad += etl::bias_batch_sum_2d(d_h_t(t)); // Update for next steps d_h_t(t) = d_h_t(t) * trans(w); } --ttt; // If only the last time step is used, no need to use the other errors if /*constexpr*/ (desc::parameters::template contains<last_only>()) { break; } } while (ttt != 0); } /*! * \brief Backup the weights in the secondary weights matrix */ void backup_weights() { unique_safe_get(as_derived().bak_w) = as_derived().w; unique_safe_get(as_derived().bak_u) = as_derived().u; unique_safe_get(as_derived().bak_b) = as_derived().b; } /*! * \brief Restore the weights from the secondary weights matrix */ void restore_weights() { as_derived().w = *as_derived().bak_w; as_derived().u = *as_derived().bak_u; as_derived().b = *as_derived().bak_b; } /*! * \brief Load the weigts into the given stream */ void store(std::ostream& os) const { cpp::binary_write_all(os, as_derived().w); cpp::binary_write_all(os, as_derived().u); cpp::binary_write_all(os, as_derived().b); } /*! * \brief Load the weigts from the given stream */ void load(std::istream& is) { cpp::binary_load_all(is, as_derived().w); cpp::binary_load_all(is, as_derived().u); cpp::binary_load_all(is, as_derived().b); } /*! * \brief Load the weigts into the given file */ void store(const std::string& file) const { std::ofstream os(file, std::ofstream::binary); store(os); } /*! * \brief Load the weigts from the given file */ void load(const std::string& file) { std::ifstream is(file, std::ifstream::binary); load(is); } /*! * \brief Returns the trainable variables of this layer. * \return a tuple containing references to the variables of this layer */ decltype(auto) trainable_parameters() { return std::make_tuple(std::ref(as_derived().w), std::ref(as_derived().u), std::ref(as_derived().b)); } /*! * \brief Returns the trainable variables of this layer. * \return a tuple containing references to the variables of this layer */ decltype(auto) trainable_parameters() const { return std::make_tuple(std::cref(as_derived().w), std::cref(as_derived().u), std::cref(as_derived().b)); } private: //CRTP Deduction /*! * \brief Returns a reference to the derived object, i.e. the object using the CRTP injector. * \return a reference to the derived object. */ derived_t& as_derived() { return *static_cast<derived_t*>(this); } /*! * \brief Returns a reference to the derived object, i.e. the object using the CRTP injector. * \return a reference to the derived object. */ const derived_t& as_derived() const { return *static_cast<const derived_t*>(this); } }; } //end of dll namespace <commit_msg>Use a cache for RNN<commit_after>//======================================================================= // Copyright (c) 2014-2017 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #pragma once #include <fstream> #include "cpp_utils/assert.hpp" //Assertions #include "cpp_utils/io.hpp" // For binary writing #include "etl/etl.hpp" #include "layer.hpp" #include "layer_traits.hpp" #include "util/tmp.hpp" namespace dll { /*! * \brief Base class for RNN layers (fast / dynamic) */ template <typename Derived, typename Desc> struct base_rnn_layer : layer<Derived> { using desc = Desc; ///< The descriptor of the layer using derived_t = Derived; ///< The derived type (CRTP) using weight = typename desc::weight; ///< The data type for this layer using this_type = base_rnn_layer<derived_t, desc>; ///< The type of this layer using base_type = layer<Derived>; ///< The base type static constexpr auto activation_function = desc::activation_function; ///< The layer's activation function /*! * \brief Initialize the neural layer */ base_rnn_layer() : base_type() { // Nothing to init here } base_rnn_layer(const base_rnn_layer& rhs) = delete; base_rnn_layer(base_rnn_layer&& rhs) = delete; base_rnn_layer& operator=(const base_rnn_layer& rhs) = delete; base_rnn_layer& operator=(base_rnn_layer&& rhs) = delete; mutable etl::dyn_matrix<float, 3> x_t; mutable etl::dyn_matrix<float, 3> s_t; void prepare_cache(size_t Batch, size_t time_steps, size_t sequence_length, size_t hidden_units) const { if (cpp_unlikely(!x_t.memory_start())) { x_t.resize(time_steps, Batch, sequence_length); s_t.resize(time_steps, Batch, hidden_units); } } /*! * \brief Apply the layer to the given batch of input. * * \param x A batch of input * \param output A batch of output that will be filled * \param w The W weights matrix * \param u The U weights matrix */ template <typename H, typename V, typename W, typename U, typename B> void forward_batch_impl(H&& output, const V& x, const W& w, const U& u, const B& b, size_t time_steps, size_t sequence_length, size_t hidden_units) const { const auto Batch = etl::dim<0>(x); prepare_cache(Batch, time_steps, sequence_length, hidden_units); // 1. Rearrange input for (size_t b = 0; b < Batch; ++b) { for (size_t t = 0; t < time_steps; ++t) { x_t(t)(b) = x(b)(t); } } // 2. Forward propagation through time // t == 0 s_t(0) = f_activate<activation_function>(bias_add_2d(x_t(0) * u, b)); for (size_t t = 1; t < time_steps; ++t) { s_t(t) = f_activate<activation_function>(bias_add_2d(x_t(t) * u + s_t(t - 1) * w, b)); } // 3. Rearrange the output for (size_t b = 0; b < Batch; ++b) { for (size_t t = 0; t < time_steps; ++t) { output(b)(t) = s_t(t)(b); } } } /*! * \brief Backpropagate the errors to the previous layers * \param output The ETL expression into which write the output * \param context The training context */ template <typename H, typename C, typename W> void backward_batch_impl(H&& output, C& context, const W& w, size_t time_steps, size_t sequence_length, size_t hidden_units, size_t bptt_steps) const { const size_t Batch = etl::dim<0>(context.errors); etl::dyn_matrix<float, 3> output_t(time_steps, Batch, sequence_length); etl::dyn_matrix<float, 3> s_t(time_steps, Batch, hidden_units); etl::dyn_matrix<float, 3> o_t(time_steps, Batch, hidden_units); // 1. Rearrange o/s for (size_t b = 0; b < Batch; ++b) { for (size_t t = 0; t < time_steps; ++t) { s_t(t)(b) = context.output(b)(t); } } for (size_t b = 0; b < Batch; ++b) { for (size_t t = 0; t < time_steps; ++t) { o_t(t)(b) = context.errors(b)(t); } } // 2. Backpropagation through time size_t t = time_steps - 1; do { output_t(t) = etl::force_temporary(o_t(t) >> f_derivative<activation_function>(s_t(t))); size_t bptt_step = t; const size_t last_step = std::max(int(time_steps) - int(bptt_steps), 0); do { output_t(t) = (output_t(t) * trans(w)) >> f_derivative<activation_function>(s_t(bptt_step - 1)); --bptt_step; } while (bptt_step > last_step); // bptt_step = 0 --t; // If only the last time step is used, no need to use the other errors if /*constexpr*/ (desc::parameters::template contains<last_only>()) { break; } } while (t != 0); // 3. Rearrange for the output for (size_t b = 0; b < Batch; ++b) { for (size_t t = 0; t < time_steps; ++t) { output(b)(t) = output_t(t)(b); } } } /*! * \brief Compute the gradients for this layer, if any * \param context The trainng context */ template <typename C, typename W> void compute_gradients_impl(C& context, const W& w, size_t time_steps, size_t sequence_length, size_t hidden_units, size_t bptt_steps) const { cpp_unused(sequence_length); const size_t Batch = etl::dim<0>(context.errors); etl::dyn_matrix<float, 3> o_t(time_steps, Batch, hidden_units); etl::dyn_matrix<float, 3> d_h_t(time_steps, Batch, hidden_units); // 1. Rearrange errors for (size_t b = 0; b < Batch; ++b) { for (size_t t = 0; t < time_steps; ++t) { o_t(t)(b) = context.errors(b)(t); } } // 2. Get the gradients from the context auto& w_grad = std::get<0>(context.up.context)->grad; auto& u_grad = std::get<1>(context.up.context)->grad; auto& b_grad = std::get<2>(context.up.context)->grad; w_grad = 0; u_grad = 0; b_grad = 0; // 3. Backpropagation through time size_t ttt = time_steps - 1; do { const size_t last_step = std::max(int(time_steps) - int(bptt_steps), 0); // Backpropagation through time for (int tt = ttt; tt >= int(last_step); --tt) { const size_t t = tt; if(t == time_steps - 1){ d_h_t(t) = o_t(t) >> f_derivative<activation_function>(s_t(t)); } else { d_h_t(t) = (o_t(t) + d_h_t(t + 1)) >> f_derivative<activation_function>(s_t(t)); } if (t > 0) { w_grad += etl::batch_outer(s_t(t - 1), d_h_t(t)); } u_grad += etl::batch_outer(x_t(t), d_h_t(t)); b_grad += etl::bias_batch_sum_2d(d_h_t(t)); // Update for next steps d_h_t(t) = d_h_t(t) * trans(w); } --ttt; // If only the last time step is used, no need to use the other errors if /*constexpr*/ (desc::parameters::template contains<last_only>()) { break; } } while (ttt != 0); } /*! * \brief Backup the weights in the secondary weights matrix */ void backup_weights() { unique_safe_get(as_derived().bak_w) = as_derived().w; unique_safe_get(as_derived().bak_u) = as_derived().u; unique_safe_get(as_derived().bak_b) = as_derived().b; } /*! * \brief Restore the weights from the secondary weights matrix */ void restore_weights() { as_derived().w = *as_derived().bak_w; as_derived().u = *as_derived().bak_u; as_derived().b = *as_derived().bak_b; } /*! * \brief Load the weigts into the given stream */ void store(std::ostream& os) const { cpp::binary_write_all(os, as_derived().w); cpp::binary_write_all(os, as_derived().u); cpp::binary_write_all(os, as_derived().b); } /*! * \brief Load the weigts from the given stream */ void load(std::istream& is) { cpp::binary_load_all(is, as_derived().w); cpp::binary_load_all(is, as_derived().u); cpp::binary_load_all(is, as_derived().b); } /*! * \brief Load the weigts into the given file */ void store(const std::string& file) const { std::ofstream os(file, std::ofstream::binary); store(os); } /*! * \brief Load the weigts from the given file */ void load(const std::string& file) { std::ifstream is(file, std::ifstream::binary); load(is); } /*! * \brief Returns the trainable variables of this layer. * \return a tuple containing references to the variables of this layer */ decltype(auto) trainable_parameters() { return std::make_tuple(std::ref(as_derived().w), std::ref(as_derived().u), std::ref(as_derived().b)); } /*! * \brief Returns the trainable variables of this layer. * \return a tuple containing references to the variables of this layer */ decltype(auto) trainable_parameters() const { return std::make_tuple(std::cref(as_derived().w), std::cref(as_derived().u), std::cref(as_derived().b)); } private: //CRTP Deduction /*! * \brief Returns a reference to the derived object, i.e. the object using the CRTP injector. * \return a reference to the derived object. */ derived_t& as_derived() { return *static_cast<derived_t*>(this); } /*! * \brief Returns a reference to the derived object, i.e. the object using the CRTP injector. * \return a reference to the derived object. */ const derived_t& as_derived() const { return *static_cast<const derived_t*>(this); } }; } //end of dll namespace <|endoftext|>
<commit_before><commit_msg>Translate German comments<commit_after><|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef ETL_TEMPORARY_BINARY_EXPR_HPP #define ETL_TEMPORARY_BINARY_EXPR_HPP #include <iostream> //For stream support #include <ostream> #include <memory> //For shared_ptr #include "traits_lite.hpp" #include "iterator.hpp" #include "tmp.hpp" #include "comparable.hpp" #include "iterable.hpp" namespace etl { template <typename T, typename AExpr, typename BExpr, typename Op, typename Forced> struct temporary_binary_expr final : comparable<temporary_binary_expr<T, AExpr, BExpr, Op, Forced>>, iterable<temporary_binary_expr<T, AExpr, BExpr, Op, Forced>> { using value_type = T; using result_type = std::conditional_t<std::is_same<Forced, void>::value, typename Op::template result_type<AExpr, BExpr>, Forced>; using data_type = std::conditional_t<std::is_same<Forced, void>::value, std::shared_ptr<result_type>, result_type>; using memory_type = value_type*; using const_memory_type = const value_type*; private: static_assert(cpp::and_c<is_etl_expr<AExpr>, is_etl_expr<BExpr>>::value, "Both arguments must be ETL expr"); using this_type = temporary_binary_expr<T, AExpr, BExpr, Op, Forced>; AExpr _a; BExpr _b; data_type _c; bool evaluated = false; public: //Cannot be constructed with no args temporary_binary_expr() = delete; //Construct a new expression temporary_binary_expr(AExpr a, BExpr b) : _a(a), _b(b) { //Nothing else to init } //Construct a new expression temporary_binary_expr(AExpr a, BExpr b, std::conditional_t<std::is_same<Forced,void>::value, int, Forced> c) : _a(a), _b(b), _c(c) { //Nothing else to init } //Copy an expression temporary_binary_expr(const temporary_binary_expr& e) : _a(e._a), _b(e._b), _c(e._c) { //Nothing else to init } //Move an expression temporary_binary_expr(temporary_binary_expr&& e) : _a(e._a), _b(e._b), _c(optional_move<std::is_same<Forced,void>::value>(e._c)), evaluated(e.evaluated) { e.evaluated = false; } //Expressions are invariant temporary_binary_expr& operator=(const temporary_binary_expr&) = delete; temporary_binary_expr& operator=(temporary_binary_expr&&) = delete; //Accessors std::add_lvalue_reference_t<AExpr> a(){ return _a; } cpp::add_const_lvalue_t<AExpr> a() const { return _a; } std::add_lvalue_reference_t<BExpr> b(){ return _b; } cpp::add_const_lvalue_t<BExpr> b() const { return _b; } //Apply the expression value_type operator[](std::size_t i){ return result()[i]; } value_type operator[](std::size_t i) const { return result()[i]; } template<typename... S, cpp_enable_if(sizeof...(S) == sub_size_compare<this_type>::value)> value_type operator()(S... args){ static_assert(cpp::all_convertible_to<std::size_t, S...>::value, "Invalid size types"); return result()(args...); } template<typename ST = T, typename A = AExpr, typename B = BExpr, typename O = Op, typename F = Forced, cpp_enable_if((sub_size_compare<temporary_binary_expr<ST, A, B, O, F>>::value > 1))> auto operator()(std::size_t i){ return sub(*this, i); } iterator<const this_type> begin() const noexcept { return {*this, 0}; } iterator<const this_type> end() const noexcept { return {*this, size(*this)}; } void evaluate(){ if(!evaluated){ Op::apply(_a, _b, result()); evaluated = true; } } template<typename Result, typename F = Forced, cpp_disable_if(std::is_same<F, void>::value)> void direct_evaluate(Result&& r){ evaluate(); //TODO Normally, this should not be necessary if(&r != &result()){ r = result(); } } template<typename Result, typename F = Forced, cpp_enable_if(std::is_same<F, void>::value)> void direct_evaluate(Result&& result){ Op::apply(_a, _b, std::forward<Result>(result)); } template<typename F = Forced, cpp_disable_if(std::is_same<F, void>::value)> void allocate_temporary() const { //NOP } template<typename F = Forced, cpp_enable_if(std::is_same<F, void>::value)> void allocate_temporary(){ if(!_c){ _c.reset(Op::allocate(_a, _b)); } } //{{{ Direct memory access memory_type memory_start() noexcept { return result().memory_start(); } const_memory_type memory_start() const noexcept { return result().memory_start(); } memory_type memory_end() noexcept { return result().memory_end(); } const_memory_type memory_end() const noexcept { return result().memory_end(); } //}}} private: using get_result_op = std::conditional_t<std::is_same<Forced, void>::value, dereference_op, forward_op>; result_type& result(){ return get_result_op::apply(_c); } const result_type& result() const { return get_result_op::apply(_c); } }; template <typename T, typename AExpr, typename BExpr, typename Op, typename Forced> std::ostream& operator<<(std::ostream& os, const temporary_binary_expr<T, AExpr, BExpr, Op, Forced>& expr){ return os << Op::desc() << "(" << expr.a() << ", " << expr.b() << ")"; } } //end of namespace etl #endif <commit_msg>Introduce temporary_unary_expr<commit_after>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef ETL_TEMPORARY_BINARY_EXPR_HPP #define ETL_TEMPORARY_BINARY_EXPR_HPP #include <iostream> //For stream support #include <ostream> #include <memory> //For shared_ptr #include "traits_lite.hpp" #include "iterator.hpp" #include "tmp.hpp" #include "comparable.hpp" #include "iterable.hpp" namespace etl { template <typename T, typename AExpr, typename Op, typename Forced> struct temporary_unary_expr final : comparable<temporary_unary_expr<T, AExpr, Op, Forced>>, iterable<temporary_unary_expr<T, AExpr, Op, Forced>> { using value_type = T; using result_type = std::conditional_t<std::is_same<Forced, void>::value, typename Op::template result_type<AExpr>, Forced>; using data_type = std::conditional_t<std::is_same<Forced, void>::value, std::shared_ptr<result_type>, result_type>; using memory_type = value_type*; using const_memory_type = const value_type*; private: static_assert(is_etl_expr<AExpr>::value, "The argument must be an ETL expr"); using this_type = temporary_unary_expr<T, AExpr, Op, Forced>; AExpr _a; data_type _c; bool evaluated = false; public: //Cannot be constructed with no args temporary_unary_expr() = delete; //Construct a new expression temporary_unary_expr(AExpr a) : _a(a) { //Nothing else to init } //Construct a new expression temporary_unary_expr(AExpr a, std::conditional_t<std::is_same<Forced,void>::value, int, Forced> c) : _a(a), _c(c) { //Nothing else to init } //Copy an expression temporary_unary_expr(const temporary_unary_expr& e) : _a(e._a), _c(e._c) { //Nothing else to init } //Move an expression temporary_unary_expr(temporary_unary_expr&& e) : _a(e._a), _c(optional_move<std::is_same<Forced,void>::value>(e._c)), evaluated(e.evaluated) { e.evaluated = false; } //Expressions are invariant temporary_unary_expr& operator=(const temporary_unary_expr&) = delete; temporary_unary_expr& operator=(temporary_unary_expr&&) = delete; //Accessors std::add_lvalue_reference_t<AExpr> a(){ return _a; } cpp::add_const_lvalue_t<AExpr> a() const { return _a; } //Apply the expression value_type operator[](std::size_t i){ return result()[i]; } value_type operator[](std::size_t i) const { return result()[i]; } template<typename... S, cpp_enable_if(sizeof...(S) == sub_size_compare<this_type>::value)> value_type operator()(S... args){ static_assert(cpp::all_convertible_to<std::size_t, S...>::value, "Invalid size types"); return result()(args...); } template<typename ST = T, typename A = AExpr, typename O = Op, typename F = Forced, cpp_enable_if((sub_size_compare<temporary_unary_expr<ST, A, O, F>>::value > 1))> auto operator()(std::size_t i){ return sub(*this, i); } iterator<const this_type> begin() const noexcept { return {*this, 0}; } iterator<const this_type> end() const noexcept { return {*this, size(*this)}; } void evaluate(){ if(!evaluated){ Op::apply(_a, result()); evaluated = true; } } template<typename Result, typename F = Forced, cpp_disable_if(std::is_same<F, void>::value)> void direct_evaluate(Result&& r){ evaluate(); //TODO Normally, this should not be necessary if(&r != &result()){ r = result(); } } template<typename Result, typename F = Forced, cpp_enable_if(std::is_same<F, void>::value)> void direct_evaluate(Result&& result){ Op::apply(_a, std::forward<Result>(result)); } template<typename F = Forced, cpp_disable_if(std::is_same<F, void>::value)> void allocate_temporary() const { //NOP } template<typename F = Forced, cpp_enable_if(std::is_same<F, void>::value)> void allocate_temporary(){ if(!_c){ _c.reset(Op::allocate(_a)); } } //{{{ Direct memory access memory_type memory_start() noexcept { return result().memory_start(); } const_memory_type memory_start() const noexcept { return result().memory_start(); } memory_type memory_end() noexcept { return result().memory_end(); } const_memory_type memory_end() const noexcept { return result().memory_end(); } //}}} private: using get_result_op = std::conditional_t<std::is_same<Forced, void>::value, dereference_op, forward_op>; result_type& result(){ return get_result_op::apply(_c); } const result_type& result() const { return get_result_op::apply(_c); } }; template <typename T, typename AExpr, typename BExpr, typename Op, typename Forced> struct temporary_binary_expr final : comparable<temporary_binary_expr<T, AExpr, BExpr, Op, Forced>>, iterable<temporary_binary_expr<T, AExpr, BExpr, Op, Forced>> { using value_type = T; using result_type = std::conditional_t<std::is_same<Forced, void>::value, typename Op::template result_type<AExpr, BExpr>, Forced>; using data_type = std::conditional_t<std::is_same<Forced, void>::value, std::shared_ptr<result_type>, result_type>; using memory_type = value_type*; using const_memory_type = const value_type*; private: static_assert(is_etl_expr<AExpr>::value && is_etl_expr<BExpr>::value, "Both arguments must be ETL expr"); using this_type = temporary_binary_expr<T, AExpr, BExpr, Op, Forced>; AExpr _a; BExpr _b; data_type _c; bool evaluated = false; public: //Cannot be constructed with no args temporary_binary_expr() = delete; //Construct a new expression temporary_binary_expr(AExpr a, BExpr b) : _a(a), _b(b) { //Nothing else to init } //Construct a new expression temporary_binary_expr(AExpr a, BExpr b, std::conditional_t<std::is_same<Forced,void>::value, int, Forced> c) : _a(a), _b(b), _c(c) { //Nothing else to init } //Copy an expression temporary_binary_expr(const temporary_binary_expr& e) : _a(e._a), _b(e._b), _c(e._c) { //Nothing else to init } //Move an expression temporary_binary_expr(temporary_binary_expr&& e) : _a(e._a), _b(e._b), _c(optional_move<std::is_same<Forced,void>::value>(e._c)), evaluated(e.evaluated) { e.evaluated = false; } //Expressions are invariant temporary_binary_expr& operator=(const temporary_binary_expr&) = delete; temporary_binary_expr& operator=(temporary_binary_expr&&) = delete; //Accessors std::add_lvalue_reference_t<AExpr> a(){ return _a; } cpp::add_const_lvalue_t<AExpr> a() const { return _a; } std::add_lvalue_reference_t<BExpr> b(){ return _b; } cpp::add_const_lvalue_t<BExpr> b() const { return _b; } //Apply the expression value_type operator[](std::size_t i){ return result()[i]; } value_type operator[](std::size_t i) const { return result()[i]; } template<typename... S, cpp_enable_if(sizeof...(S) == sub_size_compare<this_type>::value)> value_type operator()(S... args){ static_assert(cpp::all_convertible_to<std::size_t, S...>::value, "Invalid size types"); return result()(args...); } template<typename ST = T, typename A = AExpr, typename B = BExpr, typename O = Op, typename F = Forced, cpp_enable_if((sub_size_compare<temporary_binary_expr<ST, A, B, O, F>>::value > 1))> auto operator()(std::size_t i){ return sub(*this, i); } iterator<const this_type> begin() const noexcept { return {*this, 0}; } iterator<const this_type> end() const noexcept { return {*this, size(*this)}; } void evaluate(){ if(!evaluated){ Op::apply(_a, _b, result()); evaluated = true; } } template<typename Result, typename F = Forced, cpp_disable_if(std::is_same<F, void>::value)> void direct_evaluate(Result&& r){ evaluate(); //TODO Normally, this should not be necessary if(&r != &result()){ r = result(); } } template<typename Result, typename F = Forced, cpp_enable_if(std::is_same<F, void>::value)> void direct_evaluate(Result&& result){ Op::apply(_a, _b, std::forward<Result>(result)); } template<typename F = Forced, cpp_disable_if(std::is_same<F, void>::value)> void allocate_temporary() const { //NOP } template<typename F = Forced, cpp_enable_if(std::is_same<F, void>::value)> void allocate_temporary(){ if(!_c){ _c.reset(Op::allocate(_a, _b)); } } //{{{ Direct memory access memory_type memory_start() noexcept { return result().memory_start(); } const_memory_type memory_start() const noexcept { return result().memory_start(); } memory_type memory_end() noexcept { return result().memory_end(); } const_memory_type memory_end() const noexcept { return result().memory_end(); } //}}} private: using get_result_op = std::conditional_t<std::is_same<Forced, void>::value, dereference_op, forward_op>; result_type& result(){ return get_result_op::apply(_c); } const result_type& result() const { return get_result_op::apply(_c); } }; template <typename T, typename AExpr, typename Op, typename Forced> std::ostream& operator<<(std::ostream& os, const temporary_unary_expr<T, AExpr, Op, Forced>& expr){ return os << Op::desc() << "(" << expr.a() << ")"; } template <typename T, typename AExpr, typename BExpr, typename Op, typename Forced> std::ostream& operator<<(std::ostream& os, const temporary_binary_expr<T, AExpr, BExpr, Op, Forced>& expr){ return os << Op::desc() << "(" << expr.a() << ", " << expr.b() << ")"; } } //end of namespace etl #endif <|endoftext|>
<commit_before>// Copyright (c) 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 "quic/core/qpack/qpack_header_table.h" #include "absl/strings/string_view.h" #include "quic/core/qpack/qpack_static_table.h" #include "quic/platform/api/quic_logging.h" namespace quic { // Explicitly instantiate templated public non-virtual base class methods. template bool QpackHeaderTableBase<QpackEncoderDynamicTable>::EntryFitsDynamicTableCapacity( absl::string_view name, absl::string_view value) const; template bool QpackHeaderTableBase< QpackEncoderDynamicTable>::SetDynamicTableCapacity(uint64_t capacity); template bool QpackHeaderTableBase<QpackEncoderDynamicTable>::SetMaximumDynamicTableCapacity( uint64_t maximum_dynamic_table_capacity); template bool QpackHeaderTableBase<QpackDecoderDynamicTable>::EntryFitsDynamicTableCapacity( absl::string_view name, absl::string_view value) const; template bool QpackHeaderTableBase< QpackDecoderDynamicTable>::SetDynamicTableCapacity(uint64_t capacity); template bool QpackHeaderTableBase<QpackDecoderDynamicTable>::SetMaximumDynamicTableCapacity( uint64_t maximum_dynamic_table_capacity); template <typename DynamicEntryTable> QpackHeaderTableBase<DynamicEntryTable>::QpackHeaderTableBase() : dynamic_table_size_(0), dynamic_table_capacity_(0), maximum_dynamic_table_capacity_(0), max_entries_(0), dropped_entry_count_(0), dynamic_table_entry_referenced_(false) {} template <typename DynamicEntryTable> bool QpackHeaderTableBase<DynamicEntryTable>::EntryFitsDynamicTableCapacity( absl::string_view name, absl::string_view value) const { return QpackEntry::Size(name, value) <= dynamic_table_capacity_; } template <typename DynamicEntryTable> uint64_t QpackHeaderTableBase<DynamicEntryTable>::InsertEntry( absl::string_view name, absl::string_view value) { QUICHE_DCHECK(EntryFitsDynamicTableCapacity(name, value)); const uint64_t index = dropped_entry_count_ + dynamic_entries_.size(); // Copy name and value before modifying the container, because evicting // entries or even inserting a new one might invalidate |name| or |value| if // they point to an entry. QpackEntry new_entry((std::string(name)), (std::string(value))); const size_t entry_size = new_entry.Size(); EvictDownToCapacity(dynamic_table_capacity_ - entry_size); dynamic_table_size_ += entry_size; dynamic_entries_.push_back(std::move(new_entry)); return index; } template <typename DynamicEntryTable> bool QpackHeaderTableBase<DynamicEntryTable>::SetDynamicTableCapacity( uint64_t capacity) { if (capacity > maximum_dynamic_table_capacity_) { return false; } dynamic_table_capacity_ = capacity; EvictDownToCapacity(capacity); QUICHE_DCHECK_LE(dynamic_table_size_, dynamic_table_capacity_); return true; } template <typename DynamicEntryTable> bool QpackHeaderTableBase<DynamicEntryTable>::SetMaximumDynamicTableCapacity( uint64_t maximum_dynamic_table_capacity) { if (maximum_dynamic_table_capacity_ == 0) { maximum_dynamic_table_capacity_ = maximum_dynamic_table_capacity; max_entries_ = maximum_dynamic_table_capacity / 32; return true; } // If the value is already set, it should not be changed. return maximum_dynamic_table_capacity == maximum_dynamic_table_capacity_; } template <typename DynamicEntryTable> void QpackHeaderTableBase<DynamicEntryTable>::RemoveEntryFromEnd() { const uint64_t entry_size = dynamic_entries_.front().Size(); QUICHE_DCHECK_GE(dynamic_table_size_, entry_size); dynamic_table_size_ -= entry_size; dynamic_entries_.pop_front(); ++dropped_entry_count_; } template <typename DynamicEntryTable> void QpackHeaderTableBase<DynamicEntryTable>::EvictDownToCapacity( uint64_t capacity) { while (dynamic_table_size_ > capacity) { QUICHE_DCHECK(!dynamic_entries_.empty()); RemoveEntryFromEnd(); } } QpackEncoderHeaderTable::QpackEncoderHeaderTable() : static_index_(ObtainQpackStaticTable().GetStaticIndex()), static_name_index_(ObtainQpackStaticTable().GetStaticNameIndex()) {} uint64_t QpackEncoderHeaderTable::InsertEntry(absl::string_view name, absl::string_view value) { const uint64_t index = QpackHeaderTableBase<QpackEncoderDynamicTable>::InsertEntry(name, value); // Make name and value point to the new entry. name = dynamic_entries().back().name(); value = dynamic_entries().back().value(); auto index_result = dynamic_index_.insert( std::make_pair(QpackLookupEntry{name, value}, index)); if (!index_result.second) { // An entry with the same name and value already exists. It needs to be // replaced, because |dynamic_index_| tracks the most recent entry for a // given name and value. QUICHE_DCHECK_GT(index, index_result.first->second); dynamic_index_.erase(index_result.first); auto result = dynamic_index_.insert( std::make_pair(QpackLookupEntry{name, value}, index)); QUICHE_CHECK(result.second); } auto name_result = dynamic_name_index_.insert({name, index}); if (!name_result.second) { // An entry with the same name already exists. It needs to be replaced, // because |dynamic_name_index_| tracks the most recent entry for a given // name. QUICHE_DCHECK_GT(index, name_result.first->second); dynamic_name_index_.erase(name_result.first); auto result = dynamic_name_index_.insert({name, index}); QUICHE_CHECK(result.second); } return index; } QpackEncoderHeaderTable::MatchType QpackEncoderHeaderTable::FindHeaderField( absl::string_view name, absl::string_view value, bool* is_static, uint64_t* index) const { QpackLookupEntry query{name, value}; // Look for exact match in static table. auto index_it = static_index_.find(query); if (index_it != static_index_.end()) { *index = index_it->second; *is_static = true; return MatchType::kNameAndValue; } // Look for exact match in dynamic table. index_it = dynamic_index_.find(query); if (index_it != dynamic_index_.end()) { *index = index_it->second; *is_static = false; return MatchType::kNameAndValue; } // Look for name match in static table. auto name_index_it = static_name_index_.find(name); if (name_index_it != static_name_index_.end()) { *index = name_index_it->second; *is_static = true; return MatchType::kName; } // Look for name match in dynamic table. name_index_it = dynamic_name_index_.find(name); if (name_index_it != dynamic_name_index_.end()) { *index = name_index_it->second; *is_static = false; return MatchType::kName; } return MatchType::kNoMatch; } uint64_t QpackEncoderHeaderTable::MaxInsertSizeWithoutEvictingGivenEntry( uint64_t index) const { QUICHE_DCHECK_LE(dropped_entry_count(), index); if (index > inserted_entry_count()) { // All entries are allowed to be evicted. return dynamic_table_capacity(); } // Initialize to current available capacity. uint64_t max_insert_size = dynamic_table_capacity() - dynamic_table_size(); uint64_t entry_index = dropped_entry_count(); for (const auto& entry : dynamic_entries()) { if (entry_index >= index) { break; } ++entry_index; max_insert_size += entry.Size(); } return max_insert_size; } uint64_t QpackEncoderHeaderTable::draining_index( float draining_fraction) const { QUICHE_DCHECK_LE(0.0, draining_fraction); QUICHE_DCHECK_LE(draining_fraction, 1.0); const uint64_t required_space = draining_fraction * dynamic_table_capacity(); uint64_t space_above_draining_index = dynamic_table_capacity() - dynamic_table_size(); if (dynamic_entries().empty() || space_above_draining_index >= required_space) { return dropped_entry_count(); } auto it = dynamic_entries().begin(); uint64_t entry_index = dropped_entry_count(); while (space_above_draining_index < required_space) { space_above_draining_index += it->Size(); ++it; ++entry_index; if (it == dynamic_entries().end()) { return inserted_entry_count(); } } return entry_index; } void QpackEncoderHeaderTable::RemoveEntryFromEnd() { const QpackEntry* const entry = &dynamic_entries().front(); const uint64_t index = dropped_entry_count(); auto index_it = dynamic_index_.find({entry->name(), entry->value()}); // Remove |dynamic_index_| entry only if it points to the same // QpackEntry in dynamic_entries(). if (index_it != dynamic_index_.end() && index_it->second == index) { dynamic_index_.erase(index_it); } auto name_it = dynamic_name_index_.find(entry->name()); // Remove |dynamic_name_index_| entry only if it points to the same // QpackEntry in dynamic_entries(). if (name_it != dynamic_name_index_.end() && name_it->second == index) { dynamic_name_index_.erase(name_it); } QpackHeaderTableBase<QpackEncoderDynamicTable>::RemoveEntryFromEnd(); } QpackDecoderHeaderTable::QpackDecoderHeaderTable() : static_entries_(ObtainQpackStaticTable().GetStaticEntries()) {} QpackDecoderHeaderTable::~QpackDecoderHeaderTable() { for (auto& entry : observers_) { entry.second->Cancel(); } } uint64_t QpackDecoderHeaderTable::InsertEntry(absl::string_view name, absl::string_view value) { const uint64_t index = QpackHeaderTableBase<QpackDecoderDynamicTable>::InsertEntry(name, value); // Notify and deregister observers whose threshold is met, if any. while (!observers_.empty()) { auto it = observers_.begin(); if (it->first > inserted_entry_count()) { break; } Observer* observer = it->second; observers_.erase(it); observer->OnInsertCountReachedThreshold(); } return index; } const QpackEntry* QpackDecoderHeaderTable::LookupEntry(bool is_static, uint64_t index) const { if (is_static) { if (index >= static_entries_.size()) { return nullptr; } return &static_entries_[index]; } if (index < dropped_entry_count()) { return nullptr; } index -= dropped_entry_count(); if (index >= dynamic_entries().size()) { return nullptr; } return &dynamic_entries()[index]; } void QpackDecoderHeaderTable::RegisterObserver(uint64_t required_insert_count, Observer* observer) { QUICHE_DCHECK_GT(required_insert_count, 0u); observers_.insert({required_insert_count, observer}); } void QpackDecoderHeaderTable::UnregisterObserver(uint64_t required_insert_count, Observer* observer) { auto it = observers_.lower_bound(required_insert_count); while (it != observers_.end() && it->first == required_insert_count) { if (it->second == observer) { observers_.erase(it); return; } ++it; } // |observer| must have been registered. QUIC_NOTREACHED(); } } // namespace quic <commit_msg>Explicitly instantiate all possible non-inline member functions of templated class QpackHeaderTableBase.<commit_after>// Copyright (c) 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 "quic/core/qpack/qpack_header_table.h" #include "absl/strings/string_view.h" #include "quic/core/qpack/qpack_static_table.h" #include "quic/platform/api/quic_logging.h" namespace quic { // Explicitly instantiate all possible templated non-inline base class methods. template QpackHeaderTableBase<QpackEncoderDynamicTable>::QpackHeaderTableBase(); template bool QpackHeaderTableBase<QpackEncoderDynamicTable>::EntryFitsDynamicTableCapacity( absl::string_view name, absl::string_view value) const; template uint64_t QpackHeaderTableBase<QpackEncoderDynamicTable>::InsertEntry( absl::string_view name, absl::string_view value); template bool QpackHeaderTableBase< QpackEncoderDynamicTable>::SetDynamicTableCapacity(uint64_t capacity); template bool QpackHeaderTableBase<QpackEncoderDynamicTable>::SetMaximumDynamicTableCapacity( uint64_t maximum_dynamic_table_capacity); template void QpackHeaderTableBase<QpackEncoderDynamicTable>::RemoveEntryFromEnd(); template void QpackHeaderTableBase< QpackEncoderDynamicTable>::EvictDownToCapacity(uint64_t capacity); template QpackHeaderTableBase<QpackDecoderDynamicTable>::QpackHeaderTableBase(); template bool QpackHeaderTableBase<QpackDecoderDynamicTable>::EntryFitsDynamicTableCapacity( absl::string_view name, absl::string_view value) const; template uint64_t QpackHeaderTableBase<QpackDecoderDynamicTable>::InsertEntry( absl::string_view name, absl::string_view value); template bool QpackHeaderTableBase< QpackDecoderDynamicTable>::SetDynamicTableCapacity(uint64_t capacity); template bool QpackHeaderTableBase<QpackDecoderDynamicTable>::SetMaximumDynamicTableCapacity( uint64_t maximum_dynamic_table_capacity); template void QpackHeaderTableBase<QpackDecoderDynamicTable>::RemoveEntryFromEnd(); template void QpackHeaderTableBase< QpackDecoderDynamicTable>::EvictDownToCapacity(uint64_t capacity); template <typename DynamicEntryTable> QpackHeaderTableBase<DynamicEntryTable>::QpackHeaderTableBase() : dynamic_table_size_(0), dynamic_table_capacity_(0), maximum_dynamic_table_capacity_(0), max_entries_(0), dropped_entry_count_(0), dynamic_table_entry_referenced_(false) {} template <typename DynamicEntryTable> bool QpackHeaderTableBase<DynamicEntryTable>::EntryFitsDynamicTableCapacity( absl::string_view name, absl::string_view value) const { return QpackEntry::Size(name, value) <= dynamic_table_capacity_; } template <typename DynamicEntryTable> uint64_t QpackHeaderTableBase<DynamicEntryTable>::InsertEntry( absl::string_view name, absl::string_view value) { QUICHE_DCHECK(EntryFitsDynamicTableCapacity(name, value)); const uint64_t index = dropped_entry_count_ + dynamic_entries_.size(); // Copy name and value before modifying the container, because evicting // entries or even inserting a new one might invalidate |name| or |value| if // they point to an entry. QpackEntry new_entry((std::string(name)), (std::string(value))); const size_t entry_size = new_entry.Size(); EvictDownToCapacity(dynamic_table_capacity_ - entry_size); dynamic_table_size_ += entry_size; dynamic_entries_.push_back(std::move(new_entry)); return index; } template <typename DynamicEntryTable> bool QpackHeaderTableBase<DynamicEntryTable>::SetDynamicTableCapacity( uint64_t capacity) { if (capacity > maximum_dynamic_table_capacity_) { return false; } dynamic_table_capacity_ = capacity; EvictDownToCapacity(capacity); QUICHE_DCHECK_LE(dynamic_table_size_, dynamic_table_capacity_); return true; } template <typename DynamicEntryTable> bool QpackHeaderTableBase<DynamicEntryTable>::SetMaximumDynamicTableCapacity( uint64_t maximum_dynamic_table_capacity) { if (maximum_dynamic_table_capacity_ == 0) { maximum_dynamic_table_capacity_ = maximum_dynamic_table_capacity; max_entries_ = maximum_dynamic_table_capacity / 32; return true; } // If the value is already set, it should not be changed. return maximum_dynamic_table_capacity == maximum_dynamic_table_capacity_; } template <typename DynamicEntryTable> void QpackHeaderTableBase<DynamicEntryTable>::RemoveEntryFromEnd() { const uint64_t entry_size = dynamic_entries_.front().Size(); QUICHE_DCHECK_GE(dynamic_table_size_, entry_size); dynamic_table_size_ -= entry_size; dynamic_entries_.pop_front(); ++dropped_entry_count_; } template <typename DynamicEntryTable> void QpackHeaderTableBase<DynamicEntryTable>::EvictDownToCapacity( uint64_t capacity) { while (dynamic_table_size_ > capacity) { QUICHE_DCHECK(!dynamic_entries_.empty()); RemoveEntryFromEnd(); } } QpackEncoderHeaderTable::QpackEncoderHeaderTable() : static_index_(ObtainQpackStaticTable().GetStaticIndex()), static_name_index_(ObtainQpackStaticTable().GetStaticNameIndex()) {} uint64_t QpackEncoderHeaderTable::InsertEntry(absl::string_view name, absl::string_view value) { const uint64_t index = QpackHeaderTableBase<QpackEncoderDynamicTable>::InsertEntry(name, value); // Make name and value point to the new entry. name = dynamic_entries().back().name(); value = dynamic_entries().back().value(); auto index_result = dynamic_index_.insert( std::make_pair(QpackLookupEntry{name, value}, index)); if (!index_result.second) { // An entry with the same name and value already exists. It needs to be // replaced, because |dynamic_index_| tracks the most recent entry for a // given name and value. QUICHE_DCHECK_GT(index, index_result.first->second); dynamic_index_.erase(index_result.first); auto result = dynamic_index_.insert( std::make_pair(QpackLookupEntry{name, value}, index)); QUICHE_CHECK(result.second); } auto name_result = dynamic_name_index_.insert({name, index}); if (!name_result.second) { // An entry with the same name already exists. It needs to be replaced, // because |dynamic_name_index_| tracks the most recent entry for a given // name. QUICHE_DCHECK_GT(index, name_result.first->second); dynamic_name_index_.erase(name_result.first); auto result = dynamic_name_index_.insert({name, index}); QUICHE_CHECK(result.second); } return index; } QpackEncoderHeaderTable::MatchType QpackEncoderHeaderTable::FindHeaderField( absl::string_view name, absl::string_view value, bool* is_static, uint64_t* index) const { QpackLookupEntry query{name, value}; // Look for exact match in static table. auto index_it = static_index_.find(query); if (index_it != static_index_.end()) { *index = index_it->second; *is_static = true; return MatchType::kNameAndValue; } // Look for exact match in dynamic table. index_it = dynamic_index_.find(query); if (index_it != dynamic_index_.end()) { *index = index_it->second; *is_static = false; return MatchType::kNameAndValue; } // Look for name match in static table. auto name_index_it = static_name_index_.find(name); if (name_index_it != static_name_index_.end()) { *index = name_index_it->second; *is_static = true; return MatchType::kName; } // Look for name match in dynamic table. name_index_it = dynamic_name_index_.find(name); if (name_index_it != dynamic_name_index_.end()) { *index = name_index_it->second; *is_static = false; return MatchType::kName; } return MatchType::kNoMatch; } uint64_t QpackEncoderHeaderTable::MaxInsertSizeWithoutEvictingGivenEntry( uint64_t index) const { QUICHE_DCHECK_LE(dropped_entry_count(), index); if (index > inserted_entry_count()) { // All entries are allowed to be evicted. return dynamic_table_capacity(); } // Initialize to current available capacity. uint64_t max_insert_size = dynamic_table_capacity() - dynamic_table_size(); uint64_t entry_index = dropped_entry_count(); for (const auto& entry : dynamic_entries()) { if (entry_index >= index) { break; } ++entry_index; max_insert_size += entry.Size(); } return max_insert_size; } uint64_t QpackEncoderHeaderTable::draining_index( float draining_fraction) const { QUICHE_DCHECK_LE(0.0, draining_fraction); QUICHE_DCHECK_LE(draining_fraction, 1.0); const uint64_t required_space = draining_fraction * dynamic_table_capacity(); uint64_t space_above_draining_index = dynamic_table_capacity() - dynamic_table_size(); if (dynamic_entries().empty() || space_above_draining_index >= required_space) { return dropped_entry_count(); } auto it = dynamic_entries().begin(); uint64_t entry_index = dropped_entry_count(); while (space_above_draining_index < required_space) { space_above_draining_index += it->Size(); ++it; ++entry_index; if (it == dynamic_entries().end()) { return inserted_entry_count(); } } return entry_index; } void QpackEncoderHeaderTable::RemoveEntryFromEnd() { const QpackEntry* const entry = &dynamic_entries().front(); const uint64_t index = dropped_entry_count(); auto index_it = dynamic_index_.find({entry->name(), entry->value()}); // Remove |dynamic_index_| entry only if it points to the same // QpackEntry in dynamic_entries(). if (index_it != dynamic_index_.end() && index_it->second == index) { dynamic_index_.erase(index_it); } auto name_it = dynamic_name_index_.find(entry->name()); // Remove |dynamic_name_index_| entry only if it points to the same // QpackEntry in dynamic_entries(). if (name_it != dynamic_name_index_.end() && name_it->second == index) { dynamic_name_index_.erase(name_it); } QpackHeaderTableBase<QpackEncoderDynamicTable>::RemoveEntryFromEnd(); } QpackDecoderHeaderTable::QpackDecoderHeaderTable() : static_entries_(ObtainQpackStaticTable().GetStaticEntries()) {} QpackDecoderHeaderTable::~QpackDecoderHeaderTable() { for (auto& entry : observers_) { entry.second->Cancel(); } } uint64_t QpackDecoderHeaderTable::InsertEntry(absl::string_view name, absl::string_view value) { const uint64_t index = QpackHeaderTableBase<QpackDecoderDynamicTable>::InsertEntry(name, value); // Notify and deregister observers whose threshold is met, if any. while (!observers_.empty()) { auto it = observers_.begin(); if (it->first > inserted_entry_count()) { break; } Observer* observer = it->second; observers_.erase(it); observer->OnInsertCountReachedThreshold(); } return index; } const QpackEntry* QpackDecoderHeaderTable::LookupEntry(bool is_static, uint64_t index) const { if (is_static) { if (index >= static_entries_.size()) { return nullptr; } return &static_entries_[index]; } if (index < dropped_entry_count()) { return nullptr; } index -= dropped_entry_count(); if (index >= dynamic_entries().size()) { return nullptr; } return &dynamic_entries()[index]; } void QpackDecoderHeaderTable::RegisterObserver(uint64_t required_insert_count, Observer* observer) { QUICHE_DCHECK_GT(required_insert_count, 0u); observers_.insert({required_insert_count, observer}); } void QpackDecoderHeaderTable::UnregisterObserver(uint64_t required_insert_count, Observer* observer) { auto it = observers_.lower_bound(required_insert_count); while (it != observers_.end() && it->first == required_insert_count) { if (it->second == observer) { observers_.erase(it); return; } ++it; } // |observer| must have been registered. QUIC_NOTREACHED(); } } // namespace quic <|endoftext|>
<commit_before>// Copyright 2015 Markus Ilmola // 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. #ifndef GENERATOR_ITERATOR_HPP #define GENERATOR_ITERATOR_HPP #include <cassert> #include <stdexcept> #include <iterator> #include "utils.hpp" namespace generator { /// An iterator that can be used to "drive" a generator. /// Note that iterator mutates the generator. template <typename Generator> class Iterator : public std::iterator<std::input_iterator_tag, typename GeneratedType<Generator>::Type> { private: Generator* generator_; typename GeneratedType<Generator>::Type value_; public: /// Creates a dummy end iterator. Iterator() noexcept : generator_{nullptr}, value_{} { } /// Iterator to the given generator. Iterator(Generator& generator) noexcept : generator_{&generator}, value_{} { if (generator_->done()) generator_ = nullptr; else value_ = generator_->generate(); } /// Advance the iterator. /// Might make the iterator "out of range". /// @throws std::out_of_range If the iterator is out of range. Iterator& operator++() { if (!generator_) throw std::out_of_range("Iterator out of range!"); generator_->next(); if (generator_->done()) generator_ = nullptr; else value_ = generator_->generate(); return *this; } /// Get reference to the current generated value. /// @throws std::out_of_range If the iterator is out of range. const typename Iterator::value_type& operator*() const { if (!generator_) throw std::out_of_range("Iterator out of range!"); return value_; } /// Get pointer to the current generated value. /// @throws std::out_of_range If the iterator is out of range const typename Iterator::value_type* operator->() const { if (!generator_) throw std::out_of_range("Iterator out of range!"); return &value_; } /// Iterators are equal if both are out of range or both iterate the same /// generator. bool operator==(const Iterator& that) const noexcept { return generator_ == that.generator_; } bool operator!=(const Iterator& that) const noexcept { return generator_ != that.generator_; } }; /// Will return an iterator to the generator. template <typename Generator> Iterator<Generator> begin(Generator& generator) noexcept { return Iterator<Generator>{generator}; } /// Returns a dummy end iterator template <typename Generator> Iterator<Generator> end(const Generator&) noexcept { return Iterator<Generator>{}; } } #endif <commit_msg>Remove the deprecated std::iterator.<commit_after>// Copyright 2015 Markus Ilmola // 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. #ifndef GENERATOR_ITERATOR_HPP #define GENERATOR_ITERATOR_HPP #include <cassert> #include <stdexcept> #include "utils.hpp" namespace generator { /// An iterator that can be used to "drive" a generator. /// Note that iterator mutates the generator. template <typename Generator> class Iterator { private: Generator* generator_; typename GeneratedType<Generator>::Type value_; public: using iterator_category = std::input_iterator_tag; using value_type = typename GeneratedType<Generator>::Type; using difference_type = std::ptrdiff_t; using pointer = value_type*; using reference = value_type&; /// Creates a dummy end iterator. Iterator() noexcept : generator_{nullptr}, value_{} { } /// Iterator to the given generator. Iterator(Generator& generator) noexcept : generator_{&generator}, value_{} { if (generator_->done()) generator_ = nullptr; else value_ = generator_->generate(); } /// Advance the iterator. /// Might make the iterator "out of range". /// @throws std::out_of_range If the iterator is out of range. Iterator& operator++() { if (!generator_) throw std::out_of_range("Iterator out of range!"); generator_->next(); if (generator_->done()) generator_ = nullptr; else value_ = generator_->generate(); return *this; } /// Get reference to the current generated value. /// @throws std::out_of_range If the iterator is out of range. const typename Iterator::value_type& operator*() const { if (!generator_) throw std::out_of_range("Iterator out of range!"); return value_; } /// Get pointer to the current generated value. /// @throws std::out_of_range If the iterator is out of range const typename Iterator::value_type* operator->() const { if (!generator_) throw std::out_of_range("Iterator out of range!"); return &value_; } /// Iterators are equal if both are out of range or both iterate the same /// generator. bool operator==(const Iterator& that) const noexcept { return generator_ == that.generator_; } bool operator!=(const Iterator& that) const noexcept { return generator_ != that.generator_; } }; /// Will return an iterator to the generator. template <typename Generator> Iterator<Generator> begin(Generator& generator) noexcept { return Iterator<Generator>{generator}; } /// Returns a dummy end iterator template <typename Generator> Iterator<Generator> end(const Generator&) noexcept { return Iterator<Generator>{}; } } #endif <|endoftext|>
<commit_before><commit_msg>Convert Svptrarr usage to std::vector<commit_after><|endoftext|>
<commit_before>/** * @file iprofile.hpp * @brief Component Profile interface class * @author Byunghun Hwang<bhhwang@nsynapse.com> * @date 2015. 6. 21 * @details Read component profile interface */ #ifndef _COSSB_IPROFILE_HPP_ #define _COSSB_IPROFILE_HPP_ #include <string> #include <vector> #include <map> #include <boost/lexical_cast.hpp> #include <cstring> #include "../util/format.h" #include "../util/uuid.hpp" using namespace std; namespace cossb { namespace service { /** * @brief service method type */ enum class methodtype : int { PUBLISH = 1, SUBSCRIBE, UNDEFINED, }; /** * @brief service method */ typedef struct _service_method { public: _service_method():method(methodtype::UNDEFINED) {} _service_method(const char* type) { string strType = type; std::transform(strType.begin(), strType.end(), strType.begin(), ::tolower); if(strType.compare("publish")==0) method = methodtype::PUBLISH; else if(strType.compare("subscribe")==0) method = methodtype::SUBSCRIBE; else method = methodtype::UNDEFINED; } const char* str() { string mt = "Undefined"; switch(method) { case methodtype::PUBLISH: mt = "Publish"; break; case methodtype::SUBSCRIBE: mt = "Subscribe"; break; case methodtype::UNDEFINED: mt = "Undefined"; break; } return mt.c_str(); } _service_method& operator= (_service_method const& m) { this->method = m.method; return *this; } private: methodtype method = methodtype::UNDEFINED; } service_method; /** * @brief service description */ typedef struct _service_desc { string name; //service name service_method method; string topic; //service topic const char* show() { return fmt::format("Name : {}\nMethod : {}\nTopic : {}", name, method.str(), topic).c_str(); } } service_desc; /** * @brief profile service section container */ typedef vector<service::service_desc> service_desc_container; } /* namespace service */ namespace interface { class iprofile; } namespace profile { /** * @brief device description */ typedef struct _device_desc { util::uuid unique_id; string devicename; string component_required; bool operator< (const _device_desc& other) const { return (this->unique_id < other.unique_id); } } device_desc; /** * @brief profile information section container */ typedef map<string, string> profile_info_container; enum class section : unsigned int { info = 0, //component information property, //properties resource, //related resource service, //service supporting }; class type_value { public: type_value():value("") { } virtual ~type_value() { } friend class interface::iprofile; template<typename T> inline T as(T default_value) { try { T val = boost::lexical_cast<T>(value); return val; } catch( boost::bad_lexical_cast const& ) { return default_value; } } int asInt(int default_value) { return as(default_value); } unsigned int asUInt(unsigned int default_value) { return as(default_value); } unsigned long asUlong(unsigned long default_value) { return as(default_value); } double asDouble(double default_value) { return as(default_value); } float asFloat(float default_value) { return as(default_value); } bool asBool(bool default_value) { return as(default_value); } string asString(string default_value) { return as(default_value); } unsigned char asUChar(unsigned char default_value) { return as(default_value); } char asChar(char default_value) { return as(default_value); } private: std::string value; }; } namespace driver { class component_driver; } namespace interface { class iprofile { friend class driver::component_driver; public: iprofile() { _service_desc_container = new service::service_desc_container; } virtual ~iprofile() { delete _service_desc_container; } /** * @brief get profile */ virtual profile::type_value get(profile::section section, const char* element) = 0; /** * @brief update profile value */ virtual bool update(profile::section section, const char* element, const char* value) = 0; /** * @brief save profile */ virtual bool save() = 0; /** * @brief get multiple service descriptions */ service::service_desc_container* get_service_descs() const { return _service_desc_container; } private: /** * @brief load profile */ virtual bool load(const char* filepath) = 0; protected: /** * @brief */ void set(profile::type_value& profile, string value) { profile.value = value; } protected: /** * @brief service description container */ service::service_desc_container* _service_desc_container = nullptr; }; } /* namespace interface */ } /* namespace cossb */ #endif <commit_msg>update little<commit_after>/** * @file iprofile.hpp * @brief Component Profile interface class * @author Byunghun Hwang<bhhwang@nsynapse.com> * @date 2015. 6. 21 * @details Read component profile interface */ #ifndef _COSSB_IPROFILE_HPP_ #define _COSSB_IPROFILE_HPP_ #include <string> #include <vector> #include <map> #include <boost/lexical_cast.hpp> #include <cstring> #include "../util/format.h" #include "../util/uuid.hpp" #include <ext/json.hpp> #include <exception.hpp> using namespace std; namespace cossb { namespace service { /** * @brief service method type */ enum class methodtype : int { PUBLISH = 1, SUBSCRIBE, UNDEFINED, }; /** * @brief service method */ typedef struct _service_method { public: _service_method():method(methodtype::UNDEFINED) {} _service_method(const char* type) { string strType = type; std::transform(strType.begin(), strType.end(), strType.begin(), ::tolower); if(strType.compare("publish")==0) method = methodtype::PUBLISH; else if(strType.compare("subscribe")==0) method = methodtype::SUBSCRIBE; else method = methodtype::UNDEFINED; } const char* str() { string mt = "Undefined"; switch(method) { case methodtype::PUBLISH: mt = "Publish"; break; case methodtype::SUBSCRIBE: mt = "Subscribe"; break; case methodtype::UNDEFINED: mt = "Undefined"; break; } return mt.c_str(); } _service_method& operator= (_service_method const& m) { this->method = m.method; return *this; } private: methodtype method = methodtype::UNDEFINED; } service_method; /** * @brief service description */ typedef struct _service_desc { string name; //service name service_method method; string topic; //service topic const char* show() { return fmt::format("Name : {}\nMethod : {}\nTopic : {}", name, method.str(), topic).c_str(); } } service_desc; /** * @brief profile service section container */ typedef vector<service::service_desc> service_desc_container; } /* namespace service */ namespace interface { class iprofile; } namespace profile { /** * @brief device description */ typedef struct _device_desc { using json = nlohmann::json; util::uuid unique_id; string devicename; string component; int component_version = 0; string mac; string manufacturer; string author; string protocol; int port = 0; bool operator< (const _device_desc& other) const { return (this->unique_id < other.unique_id); } /** * @brief return as string (dump) */ const char* dump() { return this->profile.dump().c_str(); } /** * @brief construct */ _device_desc(const char* data, int size) { try { profile = json::parse(data); if(profile.find("uuid")!=profile.end()) this->unique_id = util::uuid(profile["uuid"].get<string>()); if(profile.find("devicename")!=profile.end()) this->devicename = profile["devicename"].get<string>(); if(profile.find("mac")!=profile.end()) this->mac = profile["mac"].get<string>(); if(profile.find("component")!=profile.end()) this->component = profile["component"].get<string>(); if(profile.find("manufacturer")!=profile.end()) this->manufacturer = profile["manufacturer"].get<string>(); if(profile.find("author")!=profile.end()) this->author = profile["author"].get<string>(); if(profile.find("protocol")!=profile.end()) this->protocol = profile["protocol"].get<string>(); if(profile.find("manufacturer")!=profile.end()) this->manufacturer = profile["manufacturer"].get<string>(); if(profile.find("port")!=profile.end()) this->port = profile["port"].get<int>(); if(profile.find("component_version")!=profile.end()) this->component_version = profile["component_version"].get<int>(); } catch(std::exception& e) { throw profile::exception(cossb::profile::excode::PROFILE_INVALID, e.what()); } } private: json profile; } device_desc; /** * @brief profile information section container */ typedef map<string, string> profile_info_container; enum class section : unsigned int { info = 0, //component information property, //properties resource, //related resource service, //service supporting }; class type_value { public: type_value():value("") { } virtual ~type_value() { } friend class interface::iprofile; template<typename T> inline T as(T default_value) { try { T val = boost::lexical_cast<T>(value); return val; } catch( boost::bad_lexical_cast const& ) { return default_value; } } int asInt(int default_value) { return as(default_value); } unsigned int asUInt(unsigned int default_value) { return as(default_value); } unsigned long asUlong(unsigned long default_value) { return as(default_value); } double asDouble(double default_value) { return as(default_value); } float asFloat(float default_value) { return as(default_value); } bool asBool(bool default_value) { return as(default_value); } string asString(string default_value) { return as(default_value); } unsigned char asUChar(unsigned char default_value) { return as(default_value); } char asChar(char default_value) { return as(default_value); } private: std::string value; }; } namespace driver { class component_driver; } namespace interface { class iprofile { friend class driver::component_driver; public: iprofile() { _service_desc_container = new service::service_desc_container; } virtual ~iprofile() { delete _service_desc_container; } /** * @brief get profile */ virtual profile::type_value get(profile::section section, const char* element) = 0; /** * @brief update profile value */ virtual bool update(profile::section section, const char* element, const char* value) = 0; /** * @brief save profile */ virtual bool save() = 0; /** * @brief get multiple service descriptions */ service::service_desc_container* get_service_descs() const { return _service_desc_container; } private: /** * @brief load profile */ virtual bool load(const char* filepath) = 0; protected: /** * @brief */ void set(profile::type_value& profile, string value) { profile.value = value; } protected: /** * @brief service description container */ service::service_desc_container* _service_desc_container = nullptr; }; } /* namespace interface */ } /* namespace cossb */ #endif <|endoftext|>
<commit_before>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_SESSION_HPP_INCLUDED #define TORRENT_SESSION_HPP_INCLUDED #include <algorithm> #include <vector> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/limits.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/config.hpp" #include "libtorrent/torrent_handle.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/session_status.hpp" #include "libtorrent/version.hpp" #include "libtorrent/fingerprint.hpp" #include "libtorrent/disk_io_thread.hpp" #include "libtorrent/peer_id.hpp" #include "libtorrent/alert.hpp" // alert::error_notification #include "libtorrent/add_torrent_params.hpp" #include "libtorrent/storage.hpp" #include <boost/preprocessor/cat.hpp> #ifdef _MSC_VER # include <eh.h> #endif namespace libtorrent { struct torrent_plugin; class torrent; class ip_filter; class port_filter; class connection_queue; class natpmp; class upnp; class alert; // this is used to create linker errors when trying to link to // a library with a conflicting build configuration than the application #ifdef TORRENT_DEBUG #define G _release #else #define G _debug #endif #ifdef TORRENT_USE_OPENSSL #define S _ssl #else #define S _nossl #endif #ifdef TORRENT_DISABLE_DHT #define D _nodht #else #define D _dht #endif #ifdef TORRENT_DISABLE_POOL_ALLOCATOR #define P _nopoolalloc #else #define P _poolalloc #endif #define TORRENT_LINK_TEST_PREFIX libtorrent_build_config #define TORRENT_LINK_TEST_NAME BOOST_PP_CAT(TORRENT_LINK_TEST_PREFIX, BOOST_PP_CAT(P, BOOST_PP_CAT(D, BOOST_PP_CAT(S, G)))) #undef P #undef D #undef S #undef G inline void test_link() { extern void TORRENT_LINK_TEST_NAME(); TORRENT_LINK_TEST_NAME(); } session_settings min_memory_usage(); session_settings high_performance_seed(); namespace aux { // workaround for microsofts // hardware exceptions that makes // it hard to debug stuff #ifdef _MSC_VER struct eh_initializer { eh_initializer() { ::_set_se_translator(straight_to_debugger); } static void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*) { throw; } }; #else struct eh_initializer {}; #endif struct session_impl; } class TORRENT_EXPORT session_proxy { friend class session; public: session_proxy() {} private: session_proxy(boost::shared_ptr<aux::session_impl> impl) : m_impl(impl) {} boost::shared_ptr<aux::session_impl> m_impl; }; class TORRENT_EXPORT session: public boost::noncopyable, aux::eh_initializer { public: session(fingerprint const& print = fingerprint("LT" , LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0) , int flags = start_default_features | add_default_plugins , int alert_mask = alert::error_notification #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING , std::string logpath = "." #endif ); session( fingerprint const& print , std::pair<int, int> listen_port_range , char const* listen_interface = "0.0.0.0" , int flags = start_default_features | add_default_plugins , int alert_mask = alert::error_notification #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING , std::string logpath = "." #endif ); ~session(); void save_state(entry& e) const; void load_state(lazy_entry const& e); // returns a list of all torrents in this session std::vector<torrent_handle> get_torrents() const; io_service& get_io_service(); // returns an invalid handle in case the torrent doesn't exist torrent_handle find_torrent(sha1_hash const& info_hash) const; // all torrent_handles must be destructed before the session is destructed! #ifndef BOOST_NO_EXCEPTIONS torrent_handle add_torrent(add_torrent_params const& params); #endif torrent_handle add_torrent(add_torrent_params const& params, error_code& ec); #ifndef TORRENT_NO_DEPRECATE // deprecated in 0.14 TORRENT_DEPRECATED_PREFIX torrent_handle add_torrent( torrent_info const& ti , std::string const& save_path , entry const& resume_data = entry() , storage_mode_t storage_mode = storage_mode_sparse , bool paused = false , storage_constructor_type sc = default_storage_constructor) TORRENT_DEPRECATED; // deprecated in 0.14 TORRENT_DEPRECATED_PREFIX torrent_handle add_torrent( boost::intrusive_ptr<torrent_info> ti , std::string const& save_path , entry const& resume_data = entry() , storage_mode_t storage_mode = storage_mode_sparse , bool paused = false , storage_constructor_type sc = default_storage_constructor , void* userdata = 0) TORRENT_DEPRECATED; // deprecated in 0.14 TORRENT_DEPRECATED_PREFIX torrent_handle add_torrent( char const* tracker_url , sha1_hash const& info_hash , char const* name , std::string const& save_path , entry const& resume_data = entry() , storage_mode_t storage_mode = storage_mode_sparse , bool paused = false , storage_constructor_type sc = default_storage_constructor , void* userdata = 0) TORRENT_DEPRECATED; #endif session_proxy abort() { return session_proxy(m_impl); } void pause(); void resume(); bool is_paused() const; session_status status() const; cache_status get_cache_status() const; void get_cache_info(sha1_hash const& ih , std::vector<cached_piece_info>& ret) const; #ifndef TORRENT_DISABLE_DHT void start_dht(entry const& startup_state = entry()); void stop_dht(); void set_dht_settings(dht_settings const& settings); entry dht_state() const; void add_dht_node(std::pair<std::string, int> const& node); void add_dht_router(std::pair<std::string, int> const& node); bool is_dht_running() const; #endif #ifndef TORRENT_DISABLE_ENCRYPTION void set_pe_settings(pe_settings const& settings); pe_settings const& get_pe_settings() const; #endif #ifndef TORRENT_DISABLE_EXTENSIONS void add_extension(boost::function<boost::shared_ptr<torrent_plugin>(torrent*, void*)> ext); #endif #ifndef TORRENT_DISABLE_GEO_IP int as_for_ip(address const& addr); bool load_asnum_db(char const* file); bool load_country_db(char const* file); #if TORRENT_USE_WSTRING bool load_country_db(wchar_t const* file); bool load_asnum_db(wchar_t const* file); #endif #endif void load_state(entry const& ses_state); entry state() const; void set_ip_filter(ip_filter const& f); ip_filter const& get_ip_filter() const; void set_port_filter(port_filter const& f); void set_peer_id(peer_id const& pid); void set_key(int key); peer_id id() const; bool is_listening() const; // if the listen port failed in some way // you can retry to listen on another port- // range with this function. If the listener // succeeded and is currently listening, // a call to this function will shut down the // listen port and reopen it using these new // properties (the given interface and port range). // As usual, if the interface is left as 0 // this function will return false on failure. // If it fails, it will also generate alerts describing // the error. It will return true on success. bool listen_on( std::pair<int, int> const& port_range , const char* net_interface = 0); // returns the port we ended up listening on unsigned short listen_port() const; // Get the number of uploads. int num_uploads() const; // Get the number of connections. This number also contains the // number of half open connections. int num_connections() const; enum options_t { none = 0, delete_files = 1 }; enum session_flags_t { add_default_plugins = 1, start_default_features = 2 }; void remove_torrent(const torrent_handle& h, int options = none); void set_settings(session_settings const& s); session_settings const& settings(); void set_peer_proxy(proxy_settings const& s); void set_web_seed_proxy(proxy_settings const& s); void set_tracker_proxy(proxy_settings const& s); proxy_settings const& peer_proxy() const; proxy_settings const& web_seed_proxy() const; proxy_settings const& tracker_proxy() const; #ifndef TORRENT_DISABLE_DHT void set_dht_proxy(proxy_settings const& s); proxy_settings const& dht_proxy() const; #endif #if TORRENT_USE_I2P void set_i2p_proxy(proxy_settings const& s); proxy_settings const& i2p_proxy() const; #endif int upload_rate_limit() const; int download_rate_limit() const; int local_upload_rate_limit() const; int local_download_rate_limit() const; int max_half_open_connections() const; void set_local_upload_rate_limit(int bytes_per_second); void set_local_download_rate_limit(int bytes_per_second); void set_upload_rate_limit(int bytes_per_second); void set_download_rate_limit(int bytes_per_second); void set_max_uploads(int limit); void set_max_connections(int limit); void set_max_half_open_connections(int limit); int max_connections() const; int max_uploads() const; std::auto_ptr<alert> pop_alert(); #ifndef TORRENT_NO_DEPRECATE TORRENT_DEPRECATED_PREFIX void set_severity_level(alert::severity_t s) TORRENT_DEPRECATED; #endif void set_alert_mask(int m); size_t set_alert_queue_size_limit(size_t queue_size_limit_); alert const* wait_for_alert(time_duration max_wait); void set_alert_dispatch(boost::function<void(alert const&)> const& fun); connection_queue& get_connection_queue(); // starts/stops UPnP, NATPMP or LSD port mappers // they are stopped by default void start_lsd(); natpmp* start_natpmp(); upnp* start_upnp(); void stop_lsd(); void stop_natpmp(); void stop_upnp(); private: // data shared between the main thread // and the working thread boost::shared_ptr<aux::session_impl> m_impl; }; } #endif // TORRENT_SESSION_HPP_INCLUDED <commit_msg>disable exception-only functions when exceptions are disabled<commit_after>/* Copyright (c) 2006, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_SESSION_HPP_INCLUDED #define TORRENT_SESSION_HPP_INCLUDED #include <algorithm> #include <vector> #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/limits.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/config.hpp" #include "libtorrent/torrent_handle.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/session_status.hpp" #include "libtorrent/version.hpp" #include "libtorrent/fingerprint.hpp" #include "libtorrent/disk_io_thread.hpp" #include "libtorrent/peer_id.hpp" #include "libtorrent/alert.hpp" // alert::error_notification #include "libtorrent/add_torrent_params.hpp" #include "libtorrent/storage.hpp" #include <boost/preprocessor/cat.hpp> #ifdef _MSC_VER # include <eh.h> #endif namespace libtorrent { struct torrent_plugin; class torrent; class ip_filter; class port_filter; class connection_queue; class natpmp; class upnp; class alert; // this is used to create linker errors when trying to link to // a library with a conflicting build configuration than the application #ifdef TORRENT_DEBUG #define G _release #else #define G _debug #endif #ifdef TORRENT_USE_OPENSSL #define S _ssl #else #define S _nossl #endif #ifdef TORRENT_DISABLE_DHT #define D _nodht #else #define D _dht #endif #ifdef TORRENT_DISABLE_POOL_ALLOCATOR #define P _nopoolalloc #else #define P _poolalloc #endif #define TORRENT_LINK_TEST_PREFIX libtorrent_build_config #define TORRENT_LINK_TEST_NAME BOOST_PP_CAT(TORRENT_LINK_TEST_PREFIX, BOOST_PP_CAT(P, BOOST_PP_CAT(D, BOOST_PP_CAT(S, G)))) #undef P #undef D #undef S #undef G inline void test_link() { extern void TORRENT_LINK_TEST_NAME(); TORRENT_LINK_TEST_NAME(); } session_settings min_memory_usage(); session_settings high_performance_seed(); namespace aux { // workaround for microsofts // hardware exceptions that makes // it hard to debug stuff #ifdef _MSC_VER struct eh_initializer { eh_initializer() { ::_set_se_translator(straight_to_debugger); } static void straight_to_debugger(unsigned int, _EXCEPTION_POINTERS*) { throw; } }; #else struct eh_initializer {}; #endif struct session_impl; } class TORRENT_EXPORT session_proxy { friend class session; public: session_proxy() {} private: session_proxy(boost::shared_ptr<aux::session_impl> impl) : m_impl(impl) {} boost::shared_ptr<aux::session_impl> m_impl; }; class TORRENT_EXPORT session: public boost::noncopyable, aux::eh_initializer { public: session(fingerprint const& print = fingerprint("LT" , LIBTORRENT_VERSION_MAJOR, LIBTORRENT_VERSION_MINOR, 0, 0) , int flags = start_default_features | add_default_plugins , int alert_mask = alert::error_notification #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING , std::string logpath = "." #endif ); session( fingerprint const& print , std::pair<int, int> listen_port_range , char const* listen_interface = "0.0.0.0" , int flags = start_default_features | add_default_plugins , int alert_mask = alert::error_notification #if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING , std::string logpath = "." #endif ); ~session(); void save_state(entry& e) const; void load_state(lazy_entry const& e); // returns a list of all torrents in this session std::vector<torrent_handle> get_torrents() const; io_service& get_io_service(); // returns an invalid handle in case the torrent doesn't exist torrent_handle find_torrent(sha1_hash const& info_hash) const; // all torrent_handles must be destructed before the session is destructed! #ifndef BOOST_NO_EXCEPTIONS torrent_handle add_torrent(add_torrent_params const& params); #endif torrent_handle add_torrent(add_torrent_params const& params, error_code& ec); #ifndef BOOST_NO_EXCEPTIONS #ifndef TORRENT_NO_DEPRECATE // deprecated in 0.14 TORRENT_DEPRECATED_PREFIX torrent_handle add_torrent( torrent_info const& ti , std::string const& save_path , entry const& resume_data = entry() , storage_mode_t storage_mode = storage_mode_sparse , bool paused = false , storage_constructor_type sc = default_storage_constructor) TORRENT_DEPRECATED; // deprecated in 0.14 TORRENT_DEPRECATED_PREFIX torrent_handle add_torrent( boost::intrusive_ptr<torrent_info> ti , std::string const& save_path , entry const& resume_data = entry() , storage_mode_t storage_mode = storage_mode_sparse , bool paused = false , storage_constructor_type sc = default_storage_constructor , void* userdata = 0) TORRENT_DEPRECATED; // deprecated in 0.14 TORRENT_DEPRECATED_PREFIX torrent_handle add_torrent( char const* tracker_url , sha1_hash const& info_hash , char const* name , std::string const& save_path , entry const& resume_data = entry() , storage_mode_t storage_mode = storage_mode_sparse , bool paused = false , storage_constructor_type sc = default_storage_constructor , void* userdata = 0) TORRENT_DEPRECATED; #endif #endif session_proxy abort() { return session_proxy(m_impl); } void pause(); void resume(); bool is_paused() const; session_status status() const; cache_status get_cache_status() const; void get_cache_info(sha1_hash const& ih , std::vector<cached_piece_info>& ret) const; #ifndef TORRENT_DISABLE_DHT void start_dht(entry const& startup_state = entry()); void stop_dht(); void set_dht_settings(dht_settings const& settings); entry dht_state() const; void add_dht_node(std::pair<std::string, int> const& node); void add_dht_router(std::pair<std::string, int> const& node); bool is_dht_running() const; #endif #ifndef TORRENT_DISABLE_ENCRYPTION void set_pe_settings(pe_settings const& settings); pe_settings const& get_pe_settings() const; #endif #ifndef TORRENT_DISABLE_EXTENSIONS void add_extension(boost::function<boost::shared_ptr<torrent_plugin>(torrent*, void*)> ext); #endif #ifndef TORRENT_DISABLE_GEO_IP int as_for_ip(address const& addr); bool load_asnum_db(char const* file); bool load_country_db(char const* file); #if TORRENT_USE_WSTRING bool load_country_db(wchar_t const* file); bool load_asnum_db(wchar_t const* file); #endif #endif void load_state(entry const& ses_state); entry state() const; void set_ip_filter(ip_filter const& f); ip_filter const& get_ip_filter() const; void set_port_filter(port_filter const& f); void set_peer_id(peer_id const& pid); void set_key(int key); peer_id id() const; bool is_listening() const; // if the listen port failed in some way // you can retry to listen on another port- // range with this function. If the listener // succeeded and is currently listening, // a call to this function will shut down the // listen port and reopen it using these new // properties (the given interface and port range). // As usual, if the interface is left as 0 // this function will return false on failure. // If it fails, it will also generate alerts describing // the error. It will return true on success. bool listen_on( std::pair<int, int> const& port_range , const char* net_interface = 0); // returns the port we ended up listening on unsigned short listen_port() const; // Get the number of uploads. int num_uploads() const; // Get the number of connections. This number also contains the // number of half open connections. int num_connections() const; enum options_t { none = 0, delete_files = 1 }; enum session_flags_t { add_default_plugins = 1, start_default_features = 2 }; void remove_torrent(const torrent_handle& h, int options = none); void set_settings(session_settings const& s); session_settings const& settings(); void set_peer_proxy(proxy_settings const& s); void set_web_seed_proxy(proxy_settings const& s); void set_tracker_proxy(proxy_settings const& s); proxy_settings const& peer_proxy() const; proxy_settings const& web_seed_proxy() const; proxy_settings const& tracker_proxy() const; #ifndef TORRENT_DISABLE_DHT void set_dht_proxy(proxy_settings const& s); proxy_settings const& dht_proxy() const; #endif #if TORRENT_USE_I2P void set_i2p_proxy(proxy_settings const& s); proxy_settings const& i2p_proxy() const; #endif int upload_rate_limit() const; int download_rate_limit() const; int local_upload_rate_limit() const; int local_download_rate_limit() const; int max_half_open_connections() const; void set_local_upload_rate_limit(int bytes_per_second); void set_local_download_rate_limit(int bytes_per_second); void set_upload_rate_limit(int bytes_per_second); void set_download_rate_limit(int bytes_per_second); void set_max_uploads(int limit); void set_max_connections(int limit); void set_max_half_open_connections(int limit); int max_connections() const; int max_uploads() const; std::auto_ptr<alert> pop_alert(); #ifndef TORRENT_NO_DEPRECATE TORRENT_DEPRECATED_PREFIX void set_severity_level(alert::severity_t s) TORRENT_DEPRECATED; #endif void set_alert_mask(int m); size_t set_alert_queue_size_limit(size_t queue_size_limit_); alert const* wait_for_alert(time_duration max_wait); void set_alert_dispatch(boost::function<void(alert const&)> const& fun); connection_queue& get_connection_queue(); // starts/stops UPnP, NATPMP or LSD port mappers // they are stopped by default void start_lsd(); natpmp* start_natpmp(); upnp* start_upnp(); void stop_lsd(); void stop_natpmp(); void stop_upnp(); private: // data shared between the main thread // and the working thread boost::shared_ptr<aux::session_impl> m_impl; }; } #endif // TORRENT_SESSION_HPP_INCLUDED <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: beziersh.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2007-09-27 11:54:02 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SWBEZIERSH_HXX #define _SWBEZIERSH_HXX #include "basesh.hxx" class SwBezierShell: public SwBaseShell { public: SFX_DECL_INTERFACE(SW_BEZIERSHELL) TYPEINFO(); SwBezierShell(SwView &rView); void GetState(SfxItemSet &); void Execute(SfxRequest &); }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.3.242); FILE MERGED 2008/03/31 16:58:27 rt 1.3.242.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: beziersh.hxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SWBEZIERSH_HXX #define _SWBEZIERSH_HXX #include "basesh.hxx" class SwBezierShell: public SwBaseShell { public: SFX_DECL_INTERFACE(SW_BEZIERSHELL) TYPEINFO(); SwBezierShell(SwView &rView); void GetState(SfxItemSet &); void Execute(SfxRequest &); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: insrule.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2007-04-26 09:13:18 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #include "uiparam.hxx" #include "hintids.hxx" #ifndef _GALLERY_HXX_ //autogen #include <svx/gallery.hxx> #endif #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SVX_BRSHITEM_HXX //autogen #include <svx/brshitem.hxx> #endif #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #include "swtypes.hxx" #include "docsh.hxx" #include "insrule.hxx" #include "swvset.hxx" #include "insrule.hrc" #include "misc.hrc" #include "helpid.h" /*------------------------------------------------------------------------ Beschreibung: ------------------------------------------------------------------------*/ SwInsertGrfRulerDlg::SwInsertGrfRulerDlg( Window* pParent ) : SfxModalDialog(pParent, SW_RES(DLG_INSERT_RULER)), aSelectionFL(this, SW_RES(FL_SEL )), pExampleVS (new SwRulerValueSet(this, SW_RES(VS_EXAMPLE ))), aOkPB (this, SW_RES(PB_OK )), aCancelPB (this, SW_RES(PB_CANCEL )), aHelpPB (this, SW_RES(PB_HELP )), sSimple (SW_RES(ST_SIMPLE)), nSelPos(USHRT_MAX) { FreeResource(); pExampleVS->SetLineCount(6); pExampleVS->SetColCount(1); pExampleVS->SetSelectHdl(LINK(this, SwInsertGrfRulerDlg, SelectHdl)); pExampleVS->SetDoubleClickHdl(LINK(this, SwInsertGrfRulerDlg, DoubleClickHdl)); pExampleVS->GrabFocus(); // Grafiknamen ermitteln GalleryExplorer::BeginLocking(GALLERY_THEME_RULERS); GalleryExplorer::FillObjList( GALLERY_THEME_RULERS, aGrfNames ); pExampleVS->SetHelpId(HID_VS_RULER); Color aColor(COL_WHITE); pExampleVS->InsertItem( 1, 1); pExampleVS->SetItemText( 1, sSimple); for(USHORT i = 1; i <= aGrfNames.Count(); i++) { pExampleVS->InsertItem( i + 1, i); pExampleVS->SetItemText( i + 1, *((String*)aGrfNames.GetObject(i-1))); } pExampleVS->Show(); } /*-----------------14.02.97 13.18------------------- --------------------------------------------------*/ SwInsertGrfRulerDlg::~SwInsertGrfRulerDlg() { GalleryExplorer::EndLocking(GALLERY_THEME_RULERS); delete pExampleVS; } /*-----------------14.02.97 13.17------------------- --------------------------------------------------*/ String SwInsertGrfRulerDlg::GetGraphicName() { String sRet; USHORT nSel = nSelPos - 2; //align selection position with ValueSet index if(nSel < aGrfNames.Count()) sRet = URIHelper::SmartRel2Abs( INetURLObject(), *(String*) aGrfNames.GetObject(nSel), URIHelper::GetMaybeFileHdl()); return sRet; } /*-----------------14.02.97 13.20------------------- --------------------------------------------------*/ IMPL_LINK(SwInsertGrfRulerDlg, SelectHdl, ValueSet*, pVS) { nSelPos = pVS->GetSelectItemId(); aOkPB.Enable(); return 0; } /*-----------------14.02.97 14.17------------------- --------------------------------------------------*/ SwRulerValueSet::SwRulerValueSet( Window* pParent, const ResId& rResId ) : SvxBmpNumValueSet(pParent, rResId) { SetStyle( GetStyle() & ~WB_ITEMBORDER ); } /*-----------------14.02.97 14.17------------------- --------------------------------------------------*/ SwRulerValueSet::~SwRulerValueSet() { } /*-----------------14.02.97 13.42------------------- --------------------------------------------------*/ void __EXPORT SwRulerValueSet::UserDraw( const UserDrawEvent& rUDEvt ) { Rectangle aRect = rUDEvt.GetRect(); OutputDevice* pDev = rUDEvt.GetDevice(); USHORT nItemId = rUDEvt.GetItemId(); Point aBLPos = aRect.TopLeft(); // Itemzaehlung beginnt bei 1, und die 1. ist die einfache Linie if(nItemId > 1) { Graphic aGraphic; if(GalleryExplorer::GetGraphicObj( GALLERY_THEME_RULERS, nItemId - 2, &aGraphic)) { Size aGrfSize = aGraphic.GetPrefSize(); if(aGrfSize.Width() && aGrfSize.Height()) { int nRelGrf = aGrfSize.Height() * 100 / aGrfSize.Width(); Size aWinSize = aRect.GetSize(); Size aPaintSize = aWinSize; int nRelWin = aWinSize.Height() * 100 / aWinSize.Width(); if(nRelGrf > nRelWin) { aPaintSize.Width() = aWinSize.Height() * 100 / nRelGrf; aBLPos.X() += (aWinSize.Width() - aPaintSize.Width()) /2; } else { aPaintSize.Height() = aWinSize.Width() * nRelGrf/100; aBLPos.Y() += (aWinSize.Height() - aPaintSize.Height()) /2; } aBLPos.X() -= aPaintSize.Width() /2; aBLPos.Y() -= aPaintSize.Height() /2; aPaintSize.Width() *= 2; aPaintSize.Height() *= 2; if(aPaintSize.Height() < 2) aPaintSize.Height() = 2; Region aRegion = pDev->GetClipRegion(); pDev->SetClipRegion(aRect); aGraphic.Draw(pDev, aBLPos, aPaintSize); pDev->SetClipRegion(aRegion); } } else { SetGrfNotFound(TRUE); } } else { // Text fuer einfache Linie painten Font aOldFont = pDev->GetFont(); Font aFont = pDev->GetFont(); Size aSize = aFont.GetSize(); int nRectHeight = aRect.GetHeight(); aSize.Height() = nRectHeight * 2 / 3; aFont.SetSize(aSize); pDev->SetFont(aFont); String aText(GetItemText(nItemId)); aSize.Width() = pDev->GetTextWidth(aText); aSize.Height() = pDev->GetTextHeight(); Point aPos(aBLPos); aPos.Y() += (nRectHeight - aSize.Height()) / 2; aPos.X() += (aRect.GetWidth() - aSize.Width()) / 2; pDev->DrawText(aPos, aText); pDev->SetFont(aOldFont); } } /*-----------------15.02.97 10.03------------------- --------------------------------------------------*/ IMPL_LINK(SwInsertGrfRulerDlg, DoubleClickHdl, ValueSet*, pVS) { EndDialog(RET_OK); return 0; } <commit_msg>INTEGRATION: CWS pchfix04 (1.10.100); FILE MERGED 2007/02/05 08:27:49 os 1.10.100.1: #i73604# usage of ITEMID_* removed<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: insrule.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: kz $ $Date: 2007-05-10 16:20:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifdef SW_DLLIMPLEMENTATION #undef SW_DLLIMPLEMENTATION #endif #include "hintids.hxx" #ifndef _GALLERY_HXX_ //autogen #include <svx/gallery.hxx> #endif #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SVX_BRSHITEM_HXX //autogen #include <svx/brshitem.hxx> #endif #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #include "swtypes.hxx" #include "docsh.hxx" #include "insrule.hxx" #include "swvset.hxx" #include "insrule.hrc" #include "misc.hrc" #include "helpid.h" /*------------------------------------------------------------------------ Beschreibung: ------------------------------------------------------------------------*/ SwInsertGrfRulerDlg::SwInsertGrfRulerDlg( Window* pParent ) : SfxModalDialog(pParent, SW_RES(DLG_INSERT_RULER)), aSelectionFL(this, SW_RES(FL_SEL )), pExampleVS (new SwRulerValueSet(this, SW_RES(VS_EXAMPLE ))), aOkPB (this, SW_RES(PB_OK )), aCancelPB (this, SW_RES(PB_CANCEL )), aHelpPB (this, SW_RES(PB_HELP )), sSimple (SW_RES(ST_SIMPLE)), nSelPos(USHRT_MAX) { FreeResource(); pExampleVS->SetLineCount(6); pExampleVS->SetColCount(1); pExampleVS->SetSelectHdl(LINK(this, SwInsertGrfRulerDlg, SelectHdl)); pExampleVS->SetDoubleClickHdl(LINK(this, SwInsertGrfRulerDlg, DoubleClickHdl)); pExampleVS->GrabFocus(); // Grafiknamen ermitteln GalleryExplorer::BeginLocking(GALLERY_THEME_RULERS); GalleryExplorer::FillObjList( GALLERY_THEME_RULERS, aGrfNames ); pExampleVS->SetHelpId(HID_VS_RULER); Color aColor(COL_WHITE); pExampleVS->InsertItem( 1, 1); pExampleVS->SetItemText( 1, sSimple); for(USHORT i = 1; i <= aGrfNames.Count(); i++) { pExampleVS->InsertItem( i + 1, i); pExampleVS->SetItemText( i + 1, *((String*)aGrfNames.GetObject(i-1))); } pExampleVS->Show(); } /*-----------------14.02.97 13.18------------------- --------------------------------------------------*/ SwInsertGrfRulerDlg::~SwInsertGrfRulerDlg() { GalleryExplorer::EndLocking(GALLERY_THEME_RULERS); delete pExampleVS; } /*-----------------14.02.97 13.17------------------- --------------------------------------------------*/ String SwInsertGrfRulerDlg::GetGraphicName() { String sRet; USHORT nSel = nSelPos - 2; //align selection position with ValueSet index if(nSel < aGrfNames.Count()) sRet = URIHelper::SmartRel2Abs( INetURLObject(), *(String*) aGrfNames.GetObject(nSel), URIHelper::GetMaybeFileHdl()); return sRet; } /*-----------------14.02.97 13.20------------------- --------------------------------------------------*/ IMPL_LINK(SwInsertGrfRulerDlg, SelectHdl, ValueSet*, pVS) { nSelPos = pVS->GetSelectItemId(); aOkPB.Enable(); return 0; } /*-----------------14.02.97 14.17------------------- --------------------------------------------------*/ SwRulerValueSet::SwRulerValueSet( Window* pParent, const ResId& rResId ) : SvxBmpNumValueSet(pParent, rResId) { SetStyle( GetStyle() & ~WB_ITEMBORDER ); } /*-----------------14.02.97 14.17------------------- --------------------------------------------------*/ SwRulerValueSet::~SwRulerValueSet() { } /*-----------------14.02.97 13.42------------------- --------------------------------------------------*/ void __EXPORT SwRulerValueSet::UserDraw( const UserDrawEvent& rUDEvt ) { Rectangle aRect = rUDEvt.GetRect(); OutputDevice* pDev = rUDEvt.GetDevice(); USHORT nItemId = rUDEvt.GetItemId(); Point aBLPos = aRect.TopLeft(); // Itemzaehlung beginnt bei 1, und die 1. ist die einfache Linie if(nItemId > 1) { Graphic aGraphic; if(GalleryExplorer::GetGraphicObj( GALLERY_THEME_RULERS, nItemId - 2, &aGraphic)) { Size aGrfSize = aGraphic.GetPrefSize(); if(aGrfSize.Width() && aGrfSize.Height()) { int nRelGrf = aGrfSize.Height() * 100 / aGrfSize.Width(); Size aWinSize = aRect.GetSize(); Size aPaintSize = aWinSize; int nRelWin = aWinSize.Height() * 100 / aWinSize.Width(); if(nRelGrf > nRelWin) { aPaintSize.Width() = aWinSize.Height() * 100 / nRelGrf; aBLPos.X() += (aWinSize.Width() - aPaintSize.Width()) /2; } else { aPaintSize.Height() = aWinSize.Width() * nRelGrf/100; aBLPos.Y() += (aWinSize.Height() - aPaintSize.Height()) /2; } aBLPos.X() -= aPaintSize.Width() /2; aBLPos.Y() -= aPaintSize.Height() /2; aPaintSize.Width() *= 2; aPaintSize.Height() *= 2; if(aPaintSize.Height() < 2) aPaintSize.Height() = 2; Region aRegion = pDev->GetClipRegion(); pDev->SetClipRegion(aRect); aGraphic.Draw(pDev, aBLPos, aPaintSize); pDev->SetClipRegion(aRegion); } } else { SetGrfNotFound(TRUE); } } else { // Text fuer einfache Linie painten Font aOldFont = pDev->GetFont(); Font aFont = pDev->GetFont(); Size aSize = aFont.GetSize(); int nRectHeight = aRect.GetHeight(); aSize.Height() = nRectHeight * 2 / 3; aFont.SetSize(aSize); pDev->SetFont(aFont); String aText(GetItemText(nItemId)); aSize.Width() = pDev->GetTextWidth(aText); aSize.Height() = pDev->GetTextHeight(); Point aPos(aBLPos); aPos.Y() += (nRectHeight - aSize.Height()) / 2; aPos.X() += (aRect.GetWidth() - aSize.Width()) / 2; pDev->DrawText(aPos, aText); pDev->SetFont(aOldFont); } } /*-----------------15.02.97 10.03------------------- --------------------------------------------------*/ IMPL_LINK(SwInsertGrfRulerDlg, DoubleClickHdl, ValueSet*, pVS) { EndDialog(RET_OK); return 0; } <|endoftext|>
<commit_before>/* * Manipulator.hh * * Copyright 2005, Francis ANDRE. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #ifndef _LOG4CPP_MANIPULATOR_HH #define _LOG4CPP_MANIPULATOR_HH #include <iostream> #include <log4cpp/Portability.hh> namespace log4cpp { class LOG4CPP_EXPORT width { private: unsigned int size; public: inline width(unsigned int i) : size(i) {} friend LOG4CPP_EXPORT std::ostream& operator<< (std::ostream& os, const width& w); }; class LOG4CPP_EXPORT tab { private: unsigned int size; public: inline tab(unsigned int i) : size(i) {} friend LOG4CPP_EXPORT std::ostream& operator<< (std::ostream& os, const tab& w); }; }; #endif<commit_msg>added newline at end of file<commit_after>/* * Manipulator.hh * * Copyright 2005, Francis ANDRE. All rights reserved. * * See the COPYING file for the terms of usage and distribution. */ #ifndef _LOG4CPP_MANIPULATOR_HH #define _LOG4CPP_MANIPULATOR_HH #include <iostream> #include <log4cpp/Portability.hh> namespace log4cpp { class LOG4CPP_EXPORT width { private: unsigned int size; public: inline width(unsigned int i) : size(i) {} friend LOG4CPP_EXPORT std::ostream& operator<< (std::ostream& os, const width& w); }; class LOG4CPP_EXPORT tab { private: unsigned int size; public: inline tab(unsigned int i) : size(i) {} friend LOG4CPP_EXPORT std::ostream& operator<< (std::ostream& os, const tab& w); }; }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtsh4.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-16 23:40:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _CRSSKIP_HXX #include <crsskip.hxx> #endif /* * private Methoden, die den Cursor ueber Suchen bewegen. Das * Aufheben der Selektion muss auf der Ebene darueber erfolgen. */ /* * Der Anfang eines Wortes ist das Folgen eines nicht- * Trennzeichens auf Trennzeichen. Ferner das Folgen von * nicht-Satztrennern auf Satztrenner. Der Absatzanfang ist * ebenfalls Wortanfang. */ FASTBOOL SwWrtShell::_SttWrd() { if ( IsSttPara() ) return 1; /* * temporaeren Cursor ohne Selektion erzeugen */ Push(); ClearMark(); if( !GoStartWord() ) // nicht gefunden --> an den Absatzanfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); // falls vorher Mark gesetzt war, zusammenfassen Combine(); return 1; } /* * Das Ende eines Wortes ist das Folgen von Trennzeichen auf * nicht-Trennzeichen. Unter dem Ende eines Wortes wird * ebenfalls die Folge von Worttrennzeichen auf Interpunktions- * zeichen verstanden. Das Absatzende ist ebenfalls Wortende. */ FASTBOOL SwWrtShell::_EndWrd() { if ( IsEndWrd() ) return 1; // temporaeren Cursor ohne Selektion erzeugen Push(); ClearMark(); if( !GoEndWord() ) // nicht gefunden --> an das Absatz Ende SwCrsrShell::MovePara(fnParaCurr, fnParaEnd); ClearMark(); // falls vorher Mark gesetzt war, zusammenfassen Combine(); return 1; } FASTBOOL SwWrtShell::_NxtWrd() { if( IsEndPara() ) // wenn schon am Ende, dann naechsten ??? { if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) // Document - Ende ?? { Pop( FALSE ); return 0L; } return 1; } Push(); ClearMark(); if( !GoNextWord() ) // nicht gefunden --> das AbsatzEnde ist Ende vom Wort SwCrsrShell::MovePara( fnParaCurr, fnParaEnd ); ClearMark(); Combine(); return 1; } FASTBOOL SwWrtShell::_PrvWrd() { if(IsSttPara()) { // wenn schon am Anfang, dann naechsten ??? if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { // Document - Anfang ?? Pop( FALSE ); return 0; } return 1; } Push(); ClearMark(); if( !GoPrevWord() ) // nicht gefunden --> an den Absatz Anfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); Combine(); return 1; } FASTBOOL SwWrtShell::_FwdSentence() { Push(); ClearMark(); if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } if( !GoNextSentence() && !IsEndPara() ) SwCrsrShell::MovePara(fnParaCurr, fnParaEnd); ClearMark(); Combine(); return 1; } FASTBOOL SwWrtShell::_BwdSentence() { Push(); ClearMark(); if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } if(IsSttPara()) { Pop(); return 1; } if( !GoPrevSentence() && !IsSttPara() ) // nicht gefunden --> an den Absatz Anfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); Combine(); return 1; } FASTBOOL SwWrtShell::_FwdPara() { Push(); ClearMark(); if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } SwCrsrShell::Left(1,CRSR_SKIP_CHARS); FASTBOOL bRet = SwCrsrShell::MovePara(fnParaNext, fnParaStart); ClearMark(); Combine(); return bRet; } FASTBOOL SwWrtShell::_BwdPara() { Push(); ClearMark(); if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } SwCrsrShell::Right(1,CRSR_SKIP_CHARS); if(!IsSttOfPara()) SttPara(); FASTBOOL bRet = SwCrsrShell::MovePara(fnParaPrev, fnParaStart); ClearMark(); Combine(); return bRet; } <commit_msg>INTEGRATION: CWS swwarnings (1.7.222); FILE MERGED 2007/02/22 15:06:53 tl 1.7.222.1: #i69287# warning-free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: wrtsh4.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2007-09-27 12:53:55 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sw.hxx" #ifndef _WRTSH_HXX #include <wrtsh.hxx> #endif #ifndef _CRSSKIP_HXX #include <crsskip.hxx> #endif /* * private Methoden, die den Cursor ueber Suchen bewegen. Das * Aufheben der Selektion muss auf der Ebene darueber erfolgen. */ /* * Der Anfang eines Wortes ist das Folgen eines nicht- * Trennzeichens auf Trennzeichen. Ferner das Folgen von * nicht-Satztrennern auf Satztrenner. Der Absatzanfang ist * ebenfalls Wortanfang. */ BOOL SwWrtShell::_SttWrd() { if ( IsSttPara() ) return 1; /* * temporaeren Cursor ohne Selektion erzeugen */ Push(); ClearMark(); if( !GoStartWord() ) // nicht gefunden --> an den Absatzanfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); // falls vorher Mark gesetzt war, zusammenfassen Combine(); return 1; } /* * Das Ende eines Wortes ist das Folgen von Trennzeichen auf * nicht-Trennzeichen. Unter dem Ende eines Wortes wird * ebenfalls die Folge von Worttrennzeichen auf Interpunktions- * zeichen verstanden. Das Absatzende ist ebenfalls Wortende. */ BOOL SwWrtShell::_EndWrd() { if ( IsEndWrd() ) return 1; // temporaeren Cursor ohne Selektion erzeugen Push(); ClearMark(); if( !GoEndWord() ) // nicht gefunden --> an das Absatz Ende SwCrsrShell::MovePara(fnParaCurr, fnParaEnd); ClearMark(); // falls vorher Mark gesetzt war, zusammenfassen Combine(); return 1; } BOOL SwWrtShell::_NxtWrd() { if( IsEndPara() ) // wenn schon am Ende, dann naechsten ??? { if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) // Document - Ende ?? { Pop( FALSE ); return 0L; } return 1; } Push(); ClearMark(); if( !GoNextWord() ) // nicht gefunden --> das AbsatzEnde ist Ende vom Wort SwCrsrShell::MovePara( fnParaCurr, fnParaEnd ); ClearMark(); Combine(); return 1; } BOOL SwWrtShell::_PrvWrd() { if(IsSttPara()) { // wenn schon am Anfang, dann naechsten ??? if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { // Document - Anfang ?? Pop( FALSE ); return 0; } return 1; } Push(); ClearMark(); if( !GoPrevWord() ) // nicht gefunden --> an den Absatz Anfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); Combine(); return 1; } BOOL SwWrtShell::_FwdSentence() { Push(); ClearMark(); if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } if( !GoNextSentence() && !IsEndPara() ) SwCrsrShell::MovePara(fnParaCurr, fnParaEnd); ClearMark(); Combine(); return 1; } BOOL SwWrtShell::_BwdSentence() { Push(); ClearMark(); if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } if(IsSttPara()) { Pop(); return 1; } if( !GoPrevSentence() && !IsSttPara() ) // nicht gefunden --> an den Absatz Anfang SwCrsrShell::MovePara( fnParaCurr, fnParaStart ); ClearMark(); Combine(); return 1; } BOOL SwWrtShell::_FwdPara() { Push(); ClearMark(); if(!SwCrsrShell::Right(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } SwCrsrShell::Left(1,CRSR_SKIP_CHARS); BOOL bRet = SwCrsrShell::MovePara(fnParaNext, fnParaStart); ClearMark(); Combine(); return bRet; } BOOL SwWrtShell::_BwdPara() { Push(); ClearMark(); if(!SwCrsrShell::Left(1,CRSR_SKIP_CHARS)) { Pop(FALSE); return 0; } SwCrsrShell::Right(1,CRSR_SKIP_CHARS); if(!IsSttOfPara()) SttPara(); BOOL bRet = SwCrsrShell::MovePara(fnParaPrev, fnParaStart); ClearMark(); Combine(); return bRet; } <|endoftext|>
<commit_before>/************************************************************ * * OTRecordList.hpp * */ /************************************************************ -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 * OPEN TRANSACTIONS * * Financial Cryptography and Digital Cash * Library, Protocol, API, Server, CLI, GUI * * -- Anonymous Numbered Accounts. * -- Untraceable Digital Cash. * -- Triple-Signed Receipts. * -- Cheques, Vouchers, Transfers, Inboxes. * -- Basket Currencies, Markets, Payment Plans. * -- Signed, XML, Ricardian-style Contracts. * -- Scripted smart contracts. * * Copyright (C) 2010-2013 by "Fellow Traveler" (A pseudonym) * * EMAIL: * FellowTraveler@rayservers.net * * BITCOIN: 1NtTPVVjDsUfDWybS4BwvHpG2pdS9RnYyQ * * KEY FINGERPRINT (PGP Key in license file): * 9DD5 90EB 9292 4B48 0484 7910 0308 00ED F951 BB8E * * OFFICIAL PROJECT WIKI(s): * https://github.com/FellowTraveler/Moneychanger * https://github.com/FellowTraveler/Open-Transactions/wiki * * WEBSITE: * http://www.OpenTransactions.org/ * * Components and licensing: * -- Moneychanger..A Java client GUI.....LICENSE:.....GPLv3 * -- otlib.........A class library.......LICENSE:...LAGPLv3 * -- otapi.........A client API..........LICENSE:...LAGPLv3 * -- opentxs/ot....Command-line client...LICENSE:...LAGPLv3 * -- otserver......Server Application....LICENSE:....AGPLv3 * Github.com/FellowTraveler/Open-Transactions/wiki/Components * * All of the above OT components were designed and written by * Fellow Traveler, with the exception of Moneychanger, which * was contracted out to Vicky C (bitcointrader4@gmail.com). * The open-source community has since actively contributed. * * ----------------------------------------------------- * * LICENSE: * This program is free software: you can redistribute it * and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your * option) any later version. * * ADDITIONAL PERMISSION under the GNU Affero GPL version 3 * section 7: (This paragraph applies only to the LAGPLv3 * components listed above.) If you modify this Program, or * any covered work, by linking or combining it with other * code, such other code is not for that reason alone subject * to any of the requirements of the GNU Affero GPL version 3. * (==> This means if you are only using the OT API, then you * don't have to open-source your code--only your changes to * Open-Transactions itself must be open source. Similar to * LGPLv3, except it applies to software-as-a-service, not * just to distributing binaries.) * * Extra WAIVER for OpenSSL, Lucre, and all other libraries * used by Open Transactions: This program is released under * the AGPL with the additional exemption that compiling, * linking, and/or using OpenSSL is allowed. The same is true * for any other open source libraries included in this * project: complete waiver from the AGPL is hereby granted to * compile, link, and/or use them with Open-Transactions, * according to their own terms, as long as the rest of the * Open-Transactions terms remain respected, with regard to * the Open-Transactions code itself. * * Lucre License: * This code is also "dual-license", meaning that Ben Lau- * rie's license must also be included and respected, since * the code for Lucre is also included with Open Transactions. * See Open-Transactions/src/otlib/lucre/LUCRE_LICENSE.txt * The Laurie requirements are light, but if there is any * problem with his license, simply remove the Lucre code. * Although there are no other blind token algorithms in Open * Transactions (yet. credlib is coming), the other functions * will continue to operate. * See Lucre on Github: https://github.com/benlaurie/lucre * ----------------------------------------------------- * 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/ * * If you would like to use this software outside of the free * software license, please contact FellowTraveler. * (Unfortunately many will run anonymously and untraceably, * so who could really stop them?) * * DISCLAIMER: * 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. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQIcBAEBAgAGBQJRSsfJAAoJEAMIAO35UbuOQT8P/RJbka8etf7wbxdHQNAY+2cC vDf8J3X8VI+pwMqv6wgTVy17venMZJa4I4ikXD/MRyWV1XbTG0mBXk/7AZk7Rexk KTvL/U1kWiez6+8XXLye+k2JNM6v7eej8xMrqEcO0ZArh/DsLoIn1y8p8qjBI7+m aE7lhstDiD0z8mwRRLKFLN2IH5rAFaZZUvj5ERJaoYUKdn4c+RcQVei2YOl4T0FU LWND3YLoH8naqJXkaOKEN4UfJINCwxhe5Ke9wyfLWLUO7NamRkWD2T7CJ0xocnD1 sjAzlVGNgaFDRflfIF4QhBx1Ddl6wwhJfw+d08bjqblSq8aXDkmFA7HeunSFKkdn oIEOEgyj+veuOMRJC5pnBJ9vV+7qRdDKQWaCKotynt4sWJDGQ9kWGWm74SsNaduN TPMyr9kNmGsfR69Q2Zq/FLcLX/j8ESxU+HYUB4vaARw2xEOu2xwDDv6jt0j3Vqsg x7rWv4S/Eh18FDNDkVRChiNoOIilLYLL6c38uMf1pnItBuxP3uhgY6COm59kVaRh nyGTYCDYD2TK+fI9o89F1297uDCwEJ62U0Q7iTDp5QuXCoxkPfv8/kX6lS6T3y9G M9mqIoLbIQ1EDntFv7/t6fUTS2+46uCrdZWbQ5RjYXdrzjij02nDmJAm2BngnZvd kamH0Y/n11lCvo1oQxM+ =uSzz -----END PGP SIGNATURE----- **************************************************************/ #ifndef __OTClient__OTRecordList__ #define __OTClient__OTRecordList__ #include "OTCommon.hpp" #include "OTRecord.hpp" #include _CINTTYPES #include _MEMORY #include <iostream> #include <vector> #include <list> #include <map> #include <string> // For address book lookups. Your client app inherits this and provides // addr storage/lookup through this simple interface. OTRecordList then // calls it. // class OTNameLookup { public: EXPORT OTNameLookup() { } EXPORT virtual ~OTNameLookup(); EXPORT virtual std::string GetNymName(const std::string & str_id, // NymID const std::string * p_server_id=NULL) const; EXPORT virtual std::string GetAcctName(const std::string & str_id, // AcctID const std::string * p_nym_id=NULL, const std::string * p_server_id=NULL, const std::string * p_asset_id=NULL) const; }; /* // OVERLOAD THE ABOVE CLASS; make a subclass that does an address book lookup // however is appropriate for your client. // class OTNameLookupIPhone : public OTNameLookup { public: virtual std::string GetNymName(const std::string & str_id) const; virtual std::string GetAcctName(const std::string & str_id) const; }; */ // ------------------------------------------------ // Client app makes an instance of its own subclass of OTNameLookup. // Client app also makes an instance of OTLookupCaller (below.) // Client app then gives the caller a pointer to the namelookup. // Client app then passes the caller to OT via OT_API_Set_AddrBookCallback. // OTRecord and OTRecordList then call the caller. // class OTLookupCaller { protected: OTNameLookup * _callback; public: EXPORT OTLookupCaller() : _callback(NULL) { } EXPORT ~OTLookupCaller(); EXPORT OTNameLookup * getCallback() { return _callback; } EXPORT void delCallback(); EXPORT void setCallback(OTNameLookup *cb); EXPORT bool isCallbackSet() const; EXPORT std::string GetNymName(const std::string & str_id, // NymID const std::string * p_server_id=NULL) const; EXPORT std::string GetAcctName(const std::string & str_id, // AcctID const std::string * p_nym_id=NULL, const std::string * p_server_id=NULL, const std::string * p_asset_id=NULL) const; }; // ------------------------------------------------ EXPORT bool OT_API_Set_AddrBookCallback(OTLookupCaller & theCaller); // OTLookupCaller must have OTNameLookup attached already. typedef _WeakPtr<OTRecord> weak_ptr_OTRecord; typedef _SharedPtr<OTRecord> shared_ptr_OTRecord; typedef std::vector<shared_ptr_OTRecord> vec_OTRecordList; // ------------------------------------------------------------- typedef std::list<std::string> list_of_strings; // ------------------------------------------------------------- typedef std::map<std::string, std::string> map_of_strings; class OTRecordList { OTNameLookup * m_pLookup; // ------------------------------------------------ // Defaults to false. If you set it true, it will run a lot faster. (And give you less data.) bool m_bRunFast; // ------------------------------------------------ bool m_bAutoAcceptCheques; // Cheques and vouchers, NOT invoices. bool m_bAutoAcceptReceipts; bool m_bAutoAcceptTransfers; bool m_bAutoAcceptCash; // ------------------------------------------------ static std::string s_strTextTo; // "To: " static std::string s_strTextFrom; // "From: " // ------------------------------------------------ list_of_strings m_servers; map_of_strings m_assets; // <asset_type_id, asset_name> list_of_strings m_accounts; list_of_strings m_nyms; // ------------------------------------------------ vec_OTRecordList m_contents; // ------------------------------------------------ static const std::string s_blank; static const std::string s_message_type; // ******************************************** public: // ADDRESS BOOK CALLBACK static bool setAddrBookCaller(OTLookupCaller & theCaller); static OTLookupCaller * getAddrBookCaller(); protected: // ADDRESS BOOK CALLER static OTLookupCaller * s_pCaller; // ******************************************** public: EXPORT OTRecordList(); // This one expects that s_pCaller is not NULL. OTRecordList(OTNameLookup & theLookup); EXPORT ~OTRecordList(); // ------------------------------------------------ EXPORT static const char * textTo () { return s_strTextTo .c_str(); } EXPORT static const char * textFrom() { return s_strTextFrom.c_str(); } EXPORT static void setTextTo (const std::string text) { s_strTextTo = text; } EXPORT static void setTextFrom(const std::string text) { s_strTextFrom = text; } // ------------------------------------------------ EXPORT void SetFastMode() { m_bRunFast = true; } // ------------------------------------------------ // SETUP: EXPORT void SetServerID(const std::string str_id); // Set the default server here. EXPORT void AddServerID(const std::string str_id); // Unless you have many servers, then use this. EXPORT void ClearServers(); // Also clears m_contents EXPORT void SetAssetID(const std::string str_id); // Etc. EXPORT void AddAssetID(const std::string str_id); EXPORT void ClearAssets(); // Also clears m_contents EXPORT void SetNymID(const std::string str_id); EXPORT void AddNymID(const std::string str_id); EXPORT void ClearNyms(); // Also clears m_contents EXPORT void SetAccountID(const std::string str_id); EXPORT void AddAccountID(const std::string str_id); EXPORT void ClearAccounts(); // Also clears m_contents // ------------------------------------------------ EXPORT void AcceptChequesAutomatically (bool bVal=true); EXPORT void AcceptReceiptsAutomatically (bool bVal=true); EXPORT void AcceptTransfersAutomatically(bool bVal=true); EXPORT void AcceptCashAutomatically (bool bVal=true); EXPORT bool DoesAcceptChequesAutomatically (); EXPORT bool DoesAcceptReceiptsAutomatically (); EXPORT bool DoesAcceptTransfersAutomatically(); EXPORT bool DoesAcceptCashAutomatically (); EXPORT bool PerformAutoAccept(); // Before populating, process out any items we're supposed to accept automatically. // ------------------------------------------------ // POPULATE: EXPORT bool Populate(); // Populates m_contents from OT API. Calls ClearContents(). EXPORT void ClearContents(); // Clears m_contents (NOT nyms, accounts, servers, or asset types.) // ------------------------------------------------ // RETRIEVE: // EXPORT int32_t size(); EXPORT _SharedPtr<OTRecord> GetRecord(int32_t nIndex); EXPORT bool RemoveRecord(int32_t nIndex); // ------------------------------------------------ }; /* // TO USE: OTRecordList blah; blah.SetServerID("id goes here"); blah.SetAssetID("id goes here"); blah.SetNymID("id goes here"); blah.SetAccountID("id goes here"); blah.Populate(); // THEN: int nSize = blah.size(); int nIndex = [0 .. nSize-1] weak_ptr_OTRecord record = blah.GetRecord(nIndex); // ACCESSING THE RECORD: shared_ptr_OTRecord pRecord(record); if (!sp) { // It's NULL -- this means OTRecordList got re-populated. // (Which means the list control on the UI needs to get // re-populated with fresh pointers.) } else // Pointer is good { pRecord->GetName(); // Etc. } // THEN LATER: blah.Populate(); Etc. */ #endif /* defined(__OTClient__OTRecordList__) */ <commit_msg>fix add export for OTRecordList (win)<commit_after>/************************************************************ * * OTRecordList.hpp * */ /************************************************************ -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 * OPEN TRANSACTIONS * * Financial Cryptography and Digital Cash * Library, Protocol, API, Server, CLI, GUI * * -- Anonymous Numbered Accounts. * -- Untraceable Digital Cash. * -- Triple-Signed Receipts. * -- Cheques, Vouchers, Transfers, Inboxes. * -- Basket Currencies, Markets, Payment Plans. * -- Signed, XML, Ricardian-style Contracts. * -- Scripted smart contracts. * * Copyright (C) 2010-2013 by "Fellow Traveler" (A pseudonym) * * EMAIL: * FellowTraveler@rayservers.net * * BITCOIN: 1NtTPVVjDsUfDWybS4BwvHpG2pdS9RnYyQ * * KEY FINGERPRINT (PGP Key in license file): * 9DD5 90EB 9292 4B48 0484 7910 0308 00ED F951 BB8E * * OFFICIAL PROJECT WIKI(s): * https://github.com/FellowTraveler/Moneychanger * https://github.com/FellowTraveler/Open-Transactions/wiki * * WEBSITE: * http://www.OpenTransactions.org/ * * Components and licensing: * -- Moneychanger..A Java client GUI.....LICENSE:.....GPLv3 * -- otlib.........A class library.......LICENSE:...LAGPLv3 * -- otapi.........A client API..........LICENSE:...LAGPLv3 * -- opentxs/ot....Command-line client...LICENSE:...LAGPLv3 * -- otserver......Server Application....LICENSE:....AGPLv3 * Github.com/FellowTraveler/Open-Transactions/wiki/Components * * All of the above OT components were designed and written by * Fellow Traveler, with the exception of Moneychanger, which * was contracted out to Vicky C (bitcointrader4@gmail.com). * The open-source community has since actively contributed. * * ----------------------------------------------------- * * LICENSE: * This program is free software: you can redistribute it * and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your * option) any later version. * * ADDITIONAL PERMISSION under the GNU Affero GPL version 3 * section 7: (This paragraph applies only to the LAGPLv3 * components listed above.) If you modify this Program, or * any covered work, by linking or combining it with other * code, such other code is not for that reason alone subject * to any of the requirements of the GNU Affero GPL version 3. * (==> This means if you are only using the OT API, then you * don't have to open-source your code--only your changes to * Open-Transactions itself must be open source. Similar to * LGPLv3, except it applies to software-as-a-service, not * just to distributing binaries.) * * Extra WAIVER for OpenSSL, Lucre, and all other libraries * used by Open Transactions: This program is released under * the AGPL with the additional exemption that compiling, * linking, and/or using OpenSSL is allowed. The same is true * for any other open source libraries included in this * project: complete waiver from the AGPL is hereby granted to * compile, link, and/or use them with Open-Transactions, * according to their own terms, as long as the rest of the * Open-Transactions terms remain respected, with regard to * the Open-Transactions code itself. * * Lucre License: * This code is also "dual-license", meaning that Ben Lau- * rie's license must also be included and respected, since * the code for Lucre is also included with Open Transactions. * See Open-Transactions/src/otlib/lucre/LUCRE_LICENSE.txt * The Laurie requirements are light, but if there is any * problem with his license, simply remove the Lucre code. * Although there are no other blind token algorithms in Open * Transactions (yet. credlib is coming), the other functions * will continue to operate. * See Lucre on Github: https://github.com/benlaurie/lucre * ----------------------------------------------------- * 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/ * * If you would like to use this software outside of the free * software license, please contact FellowTraveler. * (Unfortunately many will run anonymously and untraceably, * so who could really stop them?) * * DISCLAIMER: * 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. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQIcBAEBAgAGBQJRSsfJAAoJEAMIAO35UbuOQT8P/RJbka8etf7wbxdHQNAY+2cC vDf8J3X8VI+pwMqv6wgTVy17venMZJa4I4ikXD/MRyWV1XbTG0mBXk/7AZk7Rexk KTvL/U1kWiez6+8XXLye+k2JNM6v7eej8xMrqEcO0ZArh/DsLoIn1y8p8qjBI7+m aE7lhstDiD0z8mwRRLKFLN2IH5rAFaZZUvj5ERJaoYUKdn4c+RcQVei2YOl4T0FU LWND3YLoH8naqJXkaOKEN4UfJINCwxhe5Ke9wyfLWLUO7NamRkWD2T7CJ0xocnD1 sjAzlVGNgaFDRflfIF4QhBx1Ddl6wwhJfw+d08bjqblSq8aXDkmFA7HeunSFKkdn oIEOEgyj+veuOMRJC5pnBJ9vV+7qRdDKQWaCKotynt4sWJDGQ9kWGWm74SsNaduN TPMyr9kNmGsfR69Q2Zq/FLcLX/j8ESxU+HYUB4vaARw2xEOu2xwDDv6jt0j3Vqsg x7rWv4S/Eh18FDNDkVRChiNoOIilLYLL6c38uMf1pnItBuxP3uhgY6COm59kVaRh nyGTYCDYD2TK+fI9o89F1297uDCwEJ62U0Q7iTDp5QuXCoxkPfv8/kX6lS6T3y9G M9mqIoLbIQ1EDntFv7/t6fUTS2+46uCrdZWbQ5RjYXdrzjij02nDmJAm2BngnZvd kamH0Y/n11lCvo1oQxM+ =uSzz -----END PGP SIGNATURE----- **************************************************************/ #ifndef __OTClient__OTRecordList__ #define __OTClient__OTRecordList__ #include "OTCommon.hpp" #include "OTRecord.hpp" #include _CINTTYPES #include _MEMORY #include <iostream> #include <vector> #include <list> #include <map> #include <string> // For address book lookups. Your client app inherits this and provides // addr storage/lookup through this simple interface. OTRecordList then // calls it. // class OTNameLookup { public: EXPORT OTNameLookup() { } EXPORT virtual ~OTNameLookup(); EXPORT virtual std::string GetNymName(const std::string & str_id, // NymID const std::string * p_server_id=NULL) const; EXPORT virtual std::string GetAcctName(const std::string & str_id, // AcctID const std::string * p_nym_id=NULL, const std::string * p_server_id=NULL, const std::string * p_asset_id=NULL) const; }; /* // OVERLOAD THE ABOVE CLASS; make a subclass that does an address book lookup // however is appropriate for your client. // class OTNameLookupIPhone : public OTNameLookup { public: virtual std::string GetNymName(const std::string & str_id) const; virtual std::string GetAcctName(const std::string & str_id) const; }; */ // ------------------------------------------------ // Client app makes an instance of its own subclass of OTNameLookup. // Client app also makes an instance of OTLookupCaller (below.) // Client app then gives the caller a pointer to the namelookup. // Client app then passes the caller to OT via OT_API_Set_AddrBookCallback. // OTRecord and OTRecordList then call the caller. // class OTLookupCaller { protected: OTNameLookup * _callback; public: EXPORT OTLookupCaller() : _callback(NULL) { } EXPORT ~OTLookupCaller(); EXPORT OTNameLookup * getCallback() { return _callback; } EXPORT void delCallback(); EXPORT void setCallback(OTNameLookup *cb); EXPORT bool isCallbackSet() const; EXPORT std::string GetNymName(const std::string & str_id, // NymID const std::string * p_server_id=NULL) const; EXPORT std::string GetAcctName(const std::string & str_id, // AcctID const std::string * p_nym_id=NULL, const std::string * p_server_id=NULL, const std::string * p_asset_id=NULL) const; }; // ------------------------------------------------ EXPORT bool OT_API_Set_AddrBookCallback(OTLookupCaller & theCaller); // OTLookupCaller must have OTNameLookup attached already. typedef _WeakPtr<OTRecord> weak_ptr_OTRecord; typedef _SharedPtr<OTRecord> shared_ptr_OTRecord; typedef std::vector<shared_ptr_OTRecord> vec_OTRecordList; // ------------------------------------------------------------- typedef std::list<std::string> list_of_strings; // ------------------------------------------------------------- typedef std::map<std::string, std::string> map_of_strings; class OTRecordList { OTNameLookup * m_pLookup; // ------------------------------------------------ // Defaults to false. If you set it true, it will run a lot faster. (And give you less data.) bool m_bRunFast; // ------------------------------------------------ bool m_bAutoAcceptCheques; // Cheques and vouchers, NOT invoices. bool m_bAutoAcceptReceipts; bool m_bAutoAcceptTransfers; bool m_bAutoAcceptCash; // ------------------------------------------------ static std::string s_strTextTo; // "To: " static std::string s_strTextFrom; // "From: " // ------------------------------------------------ list_of_strings m_servers; map_of_strings m_assets; // <asset_type_id, asset_name> list_of_strings m_accounts; list_of_strings m_nyms; // ------------------------------------------------ vec_OTRecordList m_contents; // ------------------------------------------------ static const std::string s_blank; static const std::string s_message_type; // ******************************************** public: // ADDRESS BOOK CALLBACK static bool setAddrBookCaller(OTLookupCaller & theCaller); static OTLookupCaller * getAddrBookCaller(); protected: // ADDRESS BOOK CALLER static OTLookupCaller * s_pCaller; // ******************************************** public: EXPORT OTRecordList(); // This one expects that s_pCaller is not NULL. EXPORT OTRecordList(OTNameLookup & theLookup); EXPORT ~OTRecordList(); // ------------------------------------------------ EXPORT static const char * textTo () { return s_strTextTo .c_str(); } EXPORT static const char * textFrom() { return s_strTextFrom.c_str(); } EXPORT static void setTextTo (const std::string text) { s_strTextTo = text; } EXPORT static void setTextFrom(const std::string text) { s_strTextFrom = text; } // ------------------------------------------------ EXPORT void SetFastMode() { m_bRunFast = true; } // ------------------------------------------------ // SETUP: EXPORT void SetServerID(const std::string str_id); // Set the default server here. EXPORT void AddServerID(const std::string str_id); // Unless you have many servers, then use this. EXPORT void ClearServers(); // Also clears m_contents EXPORT void SetAssetID(const std::string str_id); // Etc. EXPORT void AddAssetID(const std::string str_id); EXPORT void ClearAssets(); // Also clears m_contents EXPORT void SetNymID(const std::string str_id); EXPORT void AddNymID(const std::string str_id); EXPORT void ClearNyms(); // Also clears m_contents EXPORT void SetAccountID(const std::string str_id); EXPORT void AddAccountID(const std::string str_id); EXPORT void ClearAccounts(); // Also clears m_contents // ------------------------------------------------ EXPORT void AcceptChequesAutomatically (bool bVal=true); EXPORT void AcceptReceiptsAutomatically (bool bVal=true); EXPORT void AcceptTransfersAutomatically(bool bVal=true); EXPORT void AcceptCashAutomatically (bool bVal=true); EXPORT bool DoesAcceptChequesAutomatically (); EXPORT bool DoesAcceptReceiptsAutomatically (); EXPORT bool DoesAcceptTransfersAutomatically(); EXPORT bool DoesAcceptCashAutomatically (); EXPORT bool PerformAutoAccept(); // Before populating, process out any items we're supposed to accept automatically. // ------------------------------------------------ // POPULATE: EXPORT bool Populate(); // Populates m_contents from OT API. Calls ClearContents(). EXPORT void ClearContents(); // Clears m_contents (NOT nyms, accounts, servers, or asset types.) // ------------------------------------------------ // RETRIEVE: // EXPORT int32_t size(); EXPORT _SharedPtr<OTRecord> GetRecord(int32_t nIndex); EXPORT bool RemoveRecord(int32_t nIndex); // ------------------------------------------------ }; /* // TO USE: OTRecordList blah; blah.SetServerID("id goes here"); blah.SetAssetID("id goes here"); blah.SetNymID("id goes here"); blah.SetAccountID("id goes here"); blah.Populate(); // THEN: int nSize = blah.size(); int nIndex = [0 .. nSize-1] weak_ptr_OTRecord record = blah.GetRecord(nIndex); // ACCESSING THE RECORD: shared_ptr_OTRecord pRecord(record); if (!sp) { // It's NULL -- this means OTRecordList got re-populated. // (Which means the list control on the UI needs to get // re-populated with fresh pointers.) } else // Pointer is good { pRecord->GetName(); // Etc. } // THEN LATER: blah.Populate(); Etc. */ #endif /* defined(__OTClient__OTRecordList__) */ <|endoftext|>
<commit_before>// Copyright (c) 2016-2019 Daniel Frey and Dr. Colin Hirsch // Please see LICENSE for license or visit https://github.com/taocpp/taopq/ #ifndef TAO_PQ_TRANSACTION_HPP #define TAO_PQ_TRANSACTION_HPP #include <memory> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <tao/pq/parameter_traits.hpp> #include <tao/pq/result.hpp> namespace tao::pq { namespace internal { // TODO: move these helpers to their own header? template< typename S, typename = std::make_index_sequence< S::size() > > struct inclusive_scan; template< typename T, T... Ns, std::size_t... Is > struct inclusive_scan< std::integer_sequence< T, Ns... >, std::index_sequence< Is... > > { template< std::size_t I > static constexpr T partial_sum = ( T( 0 ) + ... + ( ( Is < I ) ? Ns : T( 0 ) ) ); using type = std::integer_sequence< T, partial_sum< Is >... >; }; template< typename S > using inclusive_scan_t = typename inclusive_scan< S >::type; template< std::size_t I, typename S, typename = std::make_index_sequence< S::size() > > struct select; template< std::size_t I, typename T, T... Ns, std::size_t... Is > struct select< I, std::integer_sequence< T, Ns... >, std::index_sequence< Is... > > : std::integral_constant< T, ( T( 0 ) + ... + ( ( Is == I ) ? Ns : T( 0 ) ) ) > {}; template< typename, typename > struct make; template< std::size_t... Is, std::size_t... Ns > struct make< std::index_sequence< Is... >, std::index_sequence< Ns... > > { template< std::size_t I > static constexpr std::size_t count = ( 0 + ... + ( ( Ns < I ) ? 1 : 0 ) ); using outer = std::index_sequence< count< Is >... >; using inner = std::index_sequence< ( Is - select< count< Is >, std::index_sequence< Ns... > >::value )... >; }; template< std::size_t... Ns > using gen = make< std::make_index_sequence< ( 0 + ... + Ns ) >, inclusive_scan_t< std::index_sequence< Ns... > > >; } // namespace internal class connection; class table_writer; class transaction : public std::enable_shared_from_this< transaction > { public: enum class isolation_level { default_isolation_level, serializable, repeatable_read, read_committed, read_uncommitted }; friend class table_writer; protected: std::shared_ptr< connection > m_connection; explicit transaction( const std::shared_ptr< pq::connection >& connection ); virtual ~transaction() = 0; virtual bool v_is_direct() const = 0; virtual void v_commit() = 0; virtual void v_rollback() = 0; virtual void v_reset() noexcept = 0; [[nodiscard]] transaction*& current_transaction() const noexcept; void check_current_transaction() const; private: [[nodiscard]] result execute_params( const char* statement, const int n_params, const char* const param_values[], const int param_lengths[], const int param_formats[] ); template< std::size_t... Os, std::size_t... Is, typename... Ts > [[nodiscard]] result execute_indexed( const char* statement, std::index_sequence< Os... > /*unused*/, std::index_sequence< Is... > /*unused*/, const std::tuple< Ts... >& tuple ) { const char* const param_values[] = { std::get< Os >( tuple ).template c_str< Is >()... }; const int param_lengths[] = { std::get< Os >( tuple ).template size< Is >()... }; const int param_formats[] = { std::get< Os >( tuple ).template format< Is >()... }; return execute_params( statement, sizeof...( Os ), param_values, param_lengths, param_formats ); } template< typename... Ts > [[nodiscard]] result execute_traits( const char* statement, const Ts&... ts ) { using gen = internal::gen< Ts::columns... >; return execute_indexed( statement, typename gen::outer(), typename gen::inner(), std::tie( ts... ) ); } public: transaction( const transaction& ) = delete; void operator=( const transaction& ) = delete; void commit(); void rollback(); [[nodiscard]] std::shared_ptr< transaction > subtransaction(); template< typename... As > result execute( const char* statement, As&&... as ) { return execute_traits( statement, parameter_traits< std::decay_t< As > >( std::forward< As >( as ) )... ); } template< typename... As > result execute( const std::string& statement, As&&... as ) { return execute( statement.c_str(), std::forward< As >( as )... ); } // short-cut for no-arguments invocations result execute( const char* statement ) { return execute_params( statement, 0, nullptr, nullptr, nullptr ); } result execute( const std::string& statement ) { return execute( statement.c_str() ); } }; } // namespace tao::pq #endif <commit_msg>Simplify<commit_after>// Copyright (c) 2016-2019 Daniel Frey and Dr. Colin Hirsch // Please see LICENSE for license or visit https://github.com/taocpp/taopq/ #ifndef TAO_PQ_TRANSACTION_HPP #define TAO_PQ_TRANSACTION_HPP #include <memory> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <tao/pq/parameter_traits.hpp> #include <tao/pq/result.hpp> namespace tao::pq { namespace internal { // TODO: move these helpers to their own header? template< typename S, typename = std::make_index_sequence< S::size() > > struct inclusive_scan; template< typename T, T... Ns, std::size_t... Is > struct inclusive_scan< std::integer_sequence< T, Ns... >, std::index_sequence< Is... > > { template< std::size_t I > static constexpr T partial_sum = ( T( 0 ) + ... + ( ( Is < I ) ? Ns : T( 0 ) ) ); using type = std::integer_sequence< T, partial_sum< Is >... >; }; template< typename S > using inclusive_scan_t = typename inclusive_scan< S >::type; template< std::size_t I, typename S, typename = std::make_index_sequence< S::size() > > struct select; template< std::size_t I, typename T, T... Ns, std::size_t... Is > struct select< I, std::integer_sequence< T, Ns... >, std::index_sequence< Is... > > : std::integral_constant< T, ( T( 0 ) + ... + ( ( Is == I ) ? Ns : T( 0 ) ) ) > {}; template< typename, typename > struct make; template< std::size_t... Is, std::size_t... Ns > struct make< std::index_sequence< Is... >, std::index_sequence< Ns... > > { template< std::size_t I > static constexpr std::size_t count = ( 0 + ... + ( ( Ns < I ) ? 1 : 0 ) ); using outer = std::index_sequence< count< Is >... >; using inner = std::index_sequence< ( Is - select< count< Is >, std::index_sequence< Ns... > >::value )... >; }; template< std::size_t... Ns > using gen = make< std::make_index_sequence< ( 0 + ... + Ns ) >, inclusive_scan_t< std::index_sequence< Ns... > > >; } // namespace internal class connection; class table_writer; class transaction : public std::enable_shared_from_this< transaction > { public: enum class isolation_level { default_isolation_level, serializable, repeatable_read, read_committed, read_uncommitted }; friend class table_writer; protected: std::shared_ptr< connection > m_connection; explicit transaction( const std::shared_ptr< pq::connection >& connection ); virtual ~transaction() = 0; virtual bool v_is_direct() const = 0; virtual void v_commit() = 0; virtual void v_rollback() = 0; virtual void v_reset() noexcept = 0; [[nodiscard]] transaction*& current_transaction() const noexcept; void check_current_transaction() const; private: [[nodiscard]] result execute_params( const char* statement, const int n_params, const char* const param_values[], const int param_lengths[], const int param_formats[] ); template< std::size_t... Os, std::size_t... Is, typename... Ts > [[nodiscard]] result execute_indexed( const char* statement, std::index_sequence< Os... > /*unused*/, std::index_sequence< Is... > /*unused*/, const std::tuple< Ts... >& tuple ) { const char* const param_values[] = { std::get< Os >( tuple ).template c_str< Is >()... }; const int param_lengths[] = { std::get< Os >( tuple ).template size< Is >()... }; const int param_formats[] = { std::get< Os >( tuple ).template format< Is >()... }; return execute_params( statement, sizeof...( Os ), param_values, param_lengths, param_formats ); } template< typename... Ts > [[nodiscard]] result execute_traits( const char* statement, const Ts&... ts ) { using gen = internal::gen< Ts::columns... >; return execute_indexed( statement, typename gen::outer(), typename gen::inner(), std::tie( ts... ) ); } public: transaction( const transaction& ) = delete; void operator=( const transaction& ) = delete; void commit(); void rollback(); [[nodiscard]] std::shared_ptr< transaction > subtransaction(); template< typename... As > result execute( const char* statement, As&&... as ) { return execute_traits( statement, parameter_traits< std::decay_t< As > >( std::forward< As >( as ) )... ); } // short-cut for no-arguments invocations result execute( const char* statement ) { return execute_params( statement, 0, nullptr, nullptr, nullptr ); } template< typename... As > result execute( const std::string& statement, As&&... as ) { return execute( statement.c_str(), std::forward< As >( as )... ); } }; } // namespace tao::pq #endif <|endoftext|>
<commit_before>#pragma once #include <ctime> #include <list> #include <tudocomp_stat/Json.hpp> namespace tdc { class Stat { private: static Stat* s_current; inline static unsigned long current_time_millis() { timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1000L + t.tv_nsec / 1000000L; } class Data { friend class Stat; private: std::string title; unsigned long time_start; unsigned long time_end; ssize_t mem_off; ssize_t mem_current; ssize_t mem_peak; json::Array stats; std::list<Data> children; template<typename T> inline void log_stat(const std::string& key, const T& value) { json::Object pair; pair.set("key", key); pair.set("value", value); stats.add(pair); } public: inline json::Object to_json() const { json::Object obj; obj.set("title", title); obj.set("timeStart", time_start); obj.set("timeEnd", time_end); obj.set("memOff", mem_off); obj.set("memPeak", mem_peak); obj.set("memFinal", mem_current); obj.set("stats", stats); json::Array sub; for(auto it = children.begin(); it != children.end(); ++it) { sub.add(it->to_json()); } obj.set("sub", sub); return obj; } }; Stat* m_parent; Data m_data; bool m_track_memory; inline void track_alloc_internal(size_t bytes) { if(m_track_memory) { m_data.mem_current += bytes; m_data.mem_peak = std::max(m_data.mem_peak, m_data.mem_current); if(m_parent) m_parent->track_alloc_internal(bytes); } } inline void track_free_internal(size_t bytes) { if(m_track_memory) { m_data.mem_current -= bytes; if(m_parent) m_parent->track_free_internal(bytes); } } public: inline static void track_alloc(size_t bytes) { if(s_current) s_current->track_alloc_internal(bytes); } inline static void track_free(size_t bytes) { if(s_current) s_current->track_free_internal(bytes); } inline Stat(const std::string& title) { m_parent = s_current; s_current = this; m_data.title = title; m_data.mem_off = m_parent ? m_parent->m_data.mem_current : 0; m_data.mem_current = 0; m_data.mem_peak = 0; m_data.time_end = 0; m_data.time_start = current_time_millis(); m_track_memory = true; // TODO: artificially un-track self? } ~Stat() { // finish m_data.time_end = current_time_millis(); m_track_memory = false; // add data to parent's data if(m_parent) { m_parent->m_data.children.push_back(m_data); } // pop parent s_current = m_parent; // TODO: artificially re-track self? } template<typename T> inline void log_stat(const std::string& key, const T& value) { m_track_memory = false; // TODO: ? m_data.log_stat(key, value); m_track_memory = true; // TODO: ? } inline Data& data() { m_data.time_end = current_time_millis(); return m_data; } }; } <commit_msg>Custom memory management in Stat class<commit_after>#pragma once #include <cstring> #include <ctime> #include <tudocomp_stat/Json.hpp> namespace tdc { class Stat { private: static Stat* s_current; inline static unsigned long current_time_millis() { timespec t; clock_gettime(CLOCK_MONOTONIC, &t); return t.tv_sec * 1000L + t.tv_nsec / 1000000L; } class Data { friend class Stat; public: static constexpr size_t STR_BUFFER_SIZE = 64; private: struct keyval { keyval* next; char key[STR_BUFFER_SIZE]; char val[STR_BUFFER_SIZE]; inline keyval() : next(nullptr) { } ~keyval() { if(next) delete next; } }; public: //TODO private char title[STR_BUFFER_SIZE]; unsigned long time_start; unsigned long time_end; ssize_t mem_off; ssize_t mem_current; ssize_t mem_peak; keyval* first_stat; Data* first_child; Data* next_sibling; inline Data() : first_stat(nullptr), first_child(nullptr), next_sibling(nullptr) { } ~Data() { if(first_stat) delete first_stat; if(first_child) delete first_child; if(next_sibling) delete next_sibling; } template<typename T> inline void log_stat(const char* key, const T& value) { keyval* kv = new keyval(); { json::TValue<T> t(value); std::stringstream ss; t.str(ss); strncpy(kv->key, key, STR_BUFFER_SIZE); strncpy(kv->val, ss.str().c_str(), STR_BUFFER_SIZE); } if(first_stat) { keyval* last = first_stat; while(last->next) { last = last->next; } last->next = kv; } else { first_stat = kv; } } public: inline json::Object to_json() const { json::Object obj; obj.set("title", title); obj.set("timeStart", time_start); obj.set("timeEnd", time_end); obj.set("memOff", mem_off); obj.set("memPeak", mem_peak); obj.set("memFinal", mem_current); json::Array stats; keyval* kv = first_stat; while(kv) { json::Object pair; pair.set("key", std::string(kv->key)); pair.set("value", std::string(kv->val)); stats.add(pair); kv = kv->next; } obj.set("stats", stats); json::Array sub; Data* child = first_child; while(child) { sub.add(child->to_json()); child = child->next_sibling; } obj.set("sub", sub); return obj; } }; Stat* m_parent; Data* m_data; bool m_track_memory; inline void append_child(Data* data) { if(m_data->first_child) { Data* last = data->first_child; while(last->next_sibling) { last = last->next_sibling; } last->next_sibling = data; } else { m_data->first_child = data; } } inline void track_alloc_internal(size_t bytes) { if(m_track_memory) { m_data->mem_current += bytes; m_data->mem_peak = std::max(m_data->mem_peak, m_data->mem_current); if(m_parent) m_parent->track_alloc_internal(bytes); } } inline void track_free_internal(size_t bytes) { if(m_track_memory) { m_data->mem_current -= bytes; if(m_parent) m_parent->track_free_internal(bytes); } } public: inline static void track_alloc(size_t bytes) { if(s_current && s_current->m_track_memory) { printf("[%s] alloc: %zu\n", s_current->m_data->title, bytes); s_current->track_alloc_internal(bytes); } } inline static void track_free(size_t bytes) { if(s_current && s_current->m_track_memory) { printf("[%s] free: %zu\n", s_current->m_data->title, bytes); s_current->track_free_internal(bytes); } } inline Stat(const char* title) { m_parent = s_current; if(m_parent) m_parent->m_track_memory = false; m_data = new Data(); if(m_parent) m_parent->m_track_memory = true; strncpy(m_data->title, title, Data::STR_BUFFER_SIZE); s_current = this; m_track_memory = true; m_data->mem_off = m_parent ? m_parent->m_data->mem_current : 0; m_data->mem_current = 0; m_data->mem_peak = 0; m_data->time_end = 0; m_data->time_start = current_time_millis(); m_track_memory = true; } ~Stat() { // finish m_track_memory = false; m_data->time_end = current_time_millis(); if(m_parent) { // add data to parent's data m_parent->append_child(m_data); } else { // if this was the root, delete data delete m_data; } // pop parent s_current = m_parent; } template<typename T> inline void log_stat(const char* key, const T& value) { m_track_memory = false; m_data->log_stat(key, value); m_track_memory = true; } inline void to_json(std::ostream& out) { m_data->time_end = current_time_millis(); m_track_memory = false; m_data->to_json().str(out); m_track_memory = true; } }; } <|endoftext|>
<commit_before>/* PICCANTE The hottest HDR imaging library! http://vcg.isti.cnr.it/piccante Copyright (C) 2014 Visual Computing Laboratory - ISTI CNR http://vcg.isti.cnr.it First author: Francesco Banterle This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef PIC_UTIL_INDEXED_ARRAY_HPP #define PIC_UTIL_INDEXED_ARRAY_HPP #include <vector> #include "../util/math.hpp" namespace pic { /** * @brief IntCoord */ typedef std::vector<int> IntCoord; /** * @brief The IndexedArray class */ class IndexedArray { public: IndexedArray() { } /** * @brief bFuncNotNeg * @param val * @return */ static bool bFuncNotNeg(float val) { return val > 0.0f; } /** * @brief bFuncNotZero * @param val * @return */ static bool bFuncNotZero(float val) { return (val < 0.0f) || (val > 0.0f); } /** * @brief bFuncNeg * @param val * @return */ static bool bFuncNeg(float val) { return (val < 0.0f); } /** * @brief findSimple collects coordinates of data which satisfies a bool function func. * @param data * @param nData * @param ret * @param stride */ static void findSimple(float *data, int nData, bool(*func)(float), IntCoord &ret, int stride = 1) { for(int i = 0; i < nData; i += stride) { if(func(data[i])) { ret.push_back(i); } } } /** * @brief find collects coordinates of data which satisfies a bool function func. * @param data * @param nData * @param param * @param ret */ static void find(float *data, int nData, bool(*func)(float, std::vector<float>), std::vector<float> param, IntCoord &ret) { for(int i = 0; i < nData; i++) { if(func(data[i], param)) { ret.push_back(i); } } } /** * @brief mean computes the mean value. * @param data * @param coord * @return */ static float mean(float *data, IntCoord &coord) { if(coord.empty()) { return FLT_MAX; } float ret = 0.0f; for(auto i = 0; i < coord.size(); i++) { ret += data[coord[i]]; } return ret / float(coord.size()); } /** * @brief min computes the min value. * @param data * @param coord * @return */ static float min(float *data, IntCoord &coord) { if(coord.empty()) { return FLT_MAX; } float ret = data[coord[0]]; for(unsigned int i = 1; i < coord.size(); i++) { int j = coord[i]; ret = MIN(ret, data[j]); } return ret; } /** * @brief max computes the max value. * @param data * @param coord * @return */ static float max(float *data, IntCoord &coord) { if(coord.empty()) { return -FLT_MAX; } float ret = data[coord[0]]; for(unsigned int i = 1; i < coord.size(); i++) { int j = coord[i]; ret = MAX(ret, data[j]); } return ret; } /** * @brief percentile * @param data * @param coord * @param percent * @return */ static float percentile(float *data, IntCoord &coord, float percent) { if(coord.empty()) { return FLT_MAX; } auto n = coord.size(); float *tmp = new float[n]; for(unsigned int i = 0; i < n; i++) { int j = coord[i]; tmp[i] = data[j]; } std::sort(tmp, tmp + n); percent = CLAMPi(percent, 0.0f, 1.0f); float ret = tmp[int(float(n - 1) * percent)]; delete[] tmp; return ret; } /** * @brief scale scales values. * @param coord * @param scaling */ static void scale(IntCoord &coord, int scale) { for(unsigned int i = 0; i < coord.size(); i++) { coord.at(i) = coord.at(i) * scale; } } /** * @brief log10Mean computes mean in the log10 domain. * @param data * @param coord * @return */ static float log10Mean(float *data, IntCoord &coord) { if(coord.empty()) { return FLT_MAX; } float delta = 1e-6f; float ret = 0.0f; for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; ret += log10f(data[j] + delta); } return ret / float(coord.size()); } /** * @brief log2Mean computes mean in the log2 domain. * @param data * @param coord * @return */ static float log2Mean(float *data, IntCoord &coord) { if(coord.empty()) { return FLT_MAX; } float delta = 1e-6f; float ret = 0.0f; float log2f = logf(2.0f); for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; ret += logf(data[j] + delta) / log2f; } return ret / float(coord.size()); } /** * @brief negative computes the negative value given a val reference point. * @param data * @param coord * @param referencePoint */ static void negative(float *data, IntCoord &coord, float referencePoint = 1.0f) { for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; data[j] = referencePoint - data[j]; } } /** * @brief add is the additive operator. * @param data * @param coord * @param val */ static void add(float *data, IntCoord &coord, float val) { for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; data[j] += val; } } /** * @brief sub is the subtractive operator. * @param data * @param coord * @param val */ static void sub(float *data, IntCoord &coord, float val) { for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; data[j] -= val; } } /** * @brief mul is the multiplicative operator. * @param data * @param coord * @param val */ static void mul(float *data, IntCoord &coord, float val) { for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; data[j] *= val; } } /** * @brief div is the division operator. * @param data * @param coord * @param val */ static void div(float *data, IntCoord &coord, float val) { for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; data[j] /= val; } } /** * @brief assign * @param dataDst * @param coord * @param val */ static void assign(float *data, IntCoord &coord, float val) { for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; data[j] = val; } } /** * @brief Assign * @param dataDst * @param coord * @param dataSrc */ static void assign(float *dataDst, IntCoord &coord, float *dataSrc) { for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; dataDst[j] = dataSrc[j]; } } }; } // end namespace pic #endif /* PIC_UTIL_INDEXED_ARRAY_HPP */ <commit_msg>Update indexed_array.hpp<commit_after>/* PICCANTE The hottest HDR imaging library! http://vcg.isti.cnr.it/piccante Copyright (C) 2014 Visual Computing Laboratory - ISTI CNR http://vcg.isti.cnr.it First author: Francesco Banterle This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef PIC_UTIL_INDEXED_ARRAY_HPP #define PIC_UTIL_INDEXED_ARRAY_HPP #include <vector> #include "../util/math.hpp" namespace pic { /** * @brief IntCoord */ typedef std::vector<int> IntCoord; /** * @brief The IndexedArray class */ class IndexedArray { public: IndexedArray() { } /** * @brief bFuncNotNeg * @param val * @return */ static bool bFuncNotNeg(float val) { return val > 0.0f; } /** * @brief bFuncNotZero * @param val * @return */ static bool bFuncNotZero(float val) { return (val < 0.0f) || (val > 0.0f); } /** * @brief bFuncNeg * @param val * @return */ static bool bFuncNeg(float val) { return (val < 0.0f); } /** * @brief findSimple collects coordinates of data which satisfies a bool function func. * @param data * @param nData * @param ret * @param stride */ static void findSimple(float *data, int nData, bool(*func)(float), IntCoord &ret, int stride = 1) { for(int i = 0; i < nData; i += stride) { if(func(data[i])) { ret.push_back(i); } } } /** * @brief find collects coordinates of data which satisfies a bool function func. * @param data * @param nData * @param param * @param ret */ static void find(float *data, int nData, bool(*func)(float, std::vector<float>), std::vector<float> param, IntCoord &ret) { for(int i = 0; i < nData; i++) { if(func(data[i], param)) { ret.push_back(i); } } } /** * @brief mean computes the mean value. * @param data * @param coord * @return */ static float mean(float *data, IntCoord &coord) { if(coord.empty()) { return FLT_MAX; } float ret = 0.0f; for(unsigned int i = 0; i < coord.size(); i++) { ret += data[coord[i]]; } return ret / float(coord.size()); } /** * @brief min computes the min value. * @param data * @param coord * @return */ static float min(float *data, IntCoord &coord) { if(coord.empty()) { return FLT_MAX; } float ret = data[coord[0]]; for(unsigned int i = 1; i < coord.size(); i++) { int j = coord[i]; ret = MIN(ret, data[j]); } return ret; } /** * @brief max computes the max value. * @param data * @param coord * @return */ static float max(float *data, IntCoord &coord) { if(coord.empty()) { return -FLT_MAX; } float ret = data[coord[0]]; for(unsigned int i = 1; i < coord.size(); i++) { int j = coord[i]; ret = MAX(ret, data[j]); } return ret; } /** * @brief percentile * @param data * @param coord * @param percent * @return */ static float percentile(float *data, IntCoord &coord, float percent) { if(coord.empty()) { return FLT_MAX; } unsigned int n = coord.size(); float *tmp = new float[n]; for(unsigned int i = 0; i < n; i++) { int j = coord[i]; tmp[i] = data[j]; } std::sort(tmp, tmp + n); percent = CLAMPi(percent, 0.0f, 1.0f); float ret = tmp[int(float(n - 1) * percent)]; delete[] tmp; return ret; } /** * @brief scale scales values. * @param coord * @param scaling */ static void scale(IntCoord &coord, int scale) { for(unsigned int i = 0; i < coord.size(); i++) { coord.at(i) = coord.at(i) * scale; } } /** * @brief log10Mean computes mean in the log10 domain. * @param data * @param coord * @return */ static float log10Mean(float *data, IntCoord &coord) { if(coord.empty()) { return FLT_MAX; } float delta = 1e-6f; float ret = 0.0f; for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; ret += log10f(data[j] + delta); } return ret / float(coord.size()); } /** * @brief log2Mean computes mean in the log2 domain. * @param data * @param coord * @return */ static float log2Mean(float *data, IntCoord &coord) { if(coord.empty()) { return FLT_MAX; } float delta = 1e-6f; float ret = 0.0f; float log2f = logf(2.0f); for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; ret += logf(data[j] + delta) / log2f; } return ret / float(coord.size()); } /** * @brief negative computes the negative value given a val reference point. * @param data * @param coord * @param referencePoint */ static void negative(float *data, IntCoord &coord, float referencePoint = 1.0f) { for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; data[j] = referencePoint - data[j]; } } /** * @brief add is the additive operator. * @param data * @param coord * @param val */ static void add(float *data, IntCoord &coord, float val) { for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; data[j] += val; } } /** * @brief sub is the subtractive operator. * @param data * @param coord * @param val */ static void sub(float *data, IntCoord &coord, float val) { for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; data[j] -= val; } } /** * @brief mul is the multiplicative operator. * @param data * @param coord * @param val */ static void mul(float *data, IntCoord &coord, float val) { for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; data[j] *= val; } } /** * @brief div is the division operator. * @param data * @param coord * @param val */ static void div(float *data, IntCoord &coord, float val) { for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; data[j] /= val; } } /** * @brief assign * @param dataDst * @param coord * @param val */ static void assign(float *data, IntCoord &coord, float val) { for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; data[j] = val; } } /** * @brief Assign * @param dataDst * @param coord * @param dataSrc */ static void assign(float *dataDst, IntCoord &coord, float *dataSrc) { for(unsigned int i = 0; i < coord.size(); i++) { int j = coord[i]; dataDst[j] = dataSrc[j]; } } }; } // end namespace pic #endif /* PIC_UTIL_INDEXED_ARRAY_HPP */ <|endoftext|>
<commit_before>// Copyright (c) 2016, The University of Texas at Austin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. // ROS includes #include "ros/ros.h" // temoto includes #include "navigate_robot.h" /** This method is executed when temoto/navigate_robot_service service is called. * It updates target_pose_stamped based on the client's request and sets the new_move_req flag to let main() know that moving of the robot has been requested. * @param req temoto::Goal service request. * @param res temoto::Goal service response. * @return always true. */ bool NavigateRobotInterface::serviceUpdate(temoto::Goal::Request &req, temoto::Goal::Response &res) { // ROS_INFO("[temoto/navigate_robot] New service update requested."); navigation_goal_stamped_ = req.goal; new_navgoal_requested_ = true; return true; } // end serviceUpdate /** Plans and executes the navigation of the robot to the pose stored in navigation_goal_stamped_. */ void NavigateRobotInterface::requestNavigation() { move_base_msgs::MoveBaseGoal goal; goal.target_pose = navigation_goal_stamped_; ROS_INFO("[temoto/navigate_robot] Sending navigation goal"); move_base_aclient_.sendGoal(goal); move_base_aclient_.waitForResult(); if(move_base_aclient_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) ROS_INFO("[temoto/navigate_robot] Navigation goal achieved"); else ROS_INFO("[temoto/navigate_robot] Navigation goal failed for some reason"); return; } int main(int argc, char** argv) { ros::init(argc, argv, "navigate_robot"); ros::NodeHandle n; ros::AsyncSpinner spinner(1); spinner.start(); //tell the action client that we want to spin a thread by default // MoveBaseClient ac("move_base", true); NavigateRobotInterface navigateIF("move_base"); //wait for the action server to come up while( !navigateIF.move_base_aclient_.waitForServer( ros::Duration(5.0) ) ) { ROS_INFO("[temoto/navigate_robot] Waiting for the move_base action server to come up"); } // Set up service for navigate_robot_srv; if there's a service request, call serviceUpdate() function ros::ServiceServer service = n.advertiseService("temoto/navigate_robot_srv", &NavigateRobotInterface::serviceUpdate, &navigateIF); while (ros::ok()) { // if new navigation goal has been requested if (navigateIF.new_navgoal_requested_) { // navigate the robot to requested goal navigateIF.requestNavigation(); navigateIF.new_navgoal_requested_ = false; } } // move_base_msgs::MoveBaseGoal goal; // // //we'll send a goal to the robot to move 1 meter forward // goal.target_pose.header.frame_id = "base_link"; // goal.target_pose.header.stamp = ros::Time::now(); // // goal.target_pose.pose.position.x = 1.0; // goal.target_pose.pose.orientation.w = 1.0; // // ROS_INFO("Sending goal"); // navigateIF.move_base_aclient_.sendGoal(goal); // // navigateIF.move_base_aclient_.waitForResult(); // // if(navigateIF.move_base_aclient_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) // ROS_INFO("Hooray, the base moved 1 meter forward"); // else // ROS_INFO("The base failed to move forward 1 meter for some reason"); return 0; }<commit_msg>untested changes to navigate_robot<commit_after>// Copyright (c) 2016, The University of Texas at Austin // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 navigate_robot.cpp * * @brief ROS server that acts as an interface for ROS navigation stack. * * @author karl.kruusamae(at)utexas.edu */ // TODO TODO TODO TODO TODO TODO TODO // Remove servive part, and instead simply access it as a library. Have goal, cancel and get feedback functions. // Perhaps some class variables that are updated based on local callbacks. #include "navigate_robot.h" /** This method is executed when temoto/navigate_robot_service service is called. * It updates target_pose_stamped based on the client's request and sets the new_move_req flag to let main() know that moving of the robot has been requested. * @param req temoto::Goal service request. * @param res temoto::Goal service response. * @return always true. */ bool NavigateRobotInterface::serviceUpdate(temoto::Goal::Request &req, temoto::Goal::Response &res) { // ROS_INFO("[temoto/navigate_robot] New service update requested."); navigation_goal_stamped_ = req.goal; new_navgoal_requested_ = true; return true; } // end serviceUpdate /** Plans and executes the navigation of the robot to the pose stored in navigation_goal_stamped_. */ void NavigateRobotInterface::requestNavigation() { move_base_msgs::MoveBaseGoal goal; goal.target_pose = navigation_goal_stamped_; ROS_INFO("[temoto/navigate_robot] Sending navigation goal"); move_base_aclient_.sendGoal(goal); move_base_aclient_.waitForResult(); if(move_base_aclient_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) ROS_INFO("[temoto/navigate_robot] Navigation goal achieved"); else ROS_INFO("[temoto/navigate_robot] Navigation goal failed for some reason"); return; } void NavigateRobotInterface::sendNavigationGoal(geometry_msgs::PoseStamped goal) { move_base_msgs::MoveBaseGoal mb_goal; mb_goal.target_pose = goal; ROS_INFO("[temoto/navigate_robot] Sending navigation goal"); move_base_aclient_.sendGoal(mb_goal); // move_base_aclient_.waitForResult(); // if(move_base_aclient_.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) // ROS_INFO("[temoto/navigate_robot] Navigation goal achieved"); // else // ROS_INFO("[temoto/navigate_robot] Navigation goal failed for some reason"); return; } void NavigateRobotInterface::abortNavigation() { move_base_aclient_.cancelGoal(); return; } void NavigateRobotInterface::checkNavigationStatus() { move_base_aclient_.getState(); return; } int main(int argc, char** argv) { ros::init(argc, argv, "navigate_robot"); ros::NodeHandle n; ros::AsyncSpinner spinner(1); spinner.start(); //tell the action client that we want to spin a thread by default // MoveBaseClient ac("move_base", true); NavigateRobotInterface navigateIF("move_base"); //wait for the action server to come up while( !navigateIF.move_base_aclient_.waitForServer( ros::Duration(5.0) ) ) { ROS_INFO("[temoto/navigate_robot] Waiting for the move_base action server to come up"); } // Set up service for navigate_robot_srv; if there's a service request, call serviceUpdate() function ros::ServiceServer service = n.advertiseService("temoto/navigate_robot_srv", &NavigateRobotInterface::serviceUpdate, &navigateIF); while ( ros::ok() ) { // if new navigation goal has been requested if (navigateIF.new_navgoal_requested_) { // navigate the robot to requested goal navigateIF.requestNavigation(); navigateIF.new_navgoal_requested_ = false; } } return 0; }<|endoftext|>
<commit_before>#ifndef CATOMIC_STACK #define CATOMIC_STACK #include<atomic> #include<memory> //shared_ptr, make_shared #include<utility> //forward, move namespace nThread { template<class T> class CAtomic_stack { public: using value_type=T; private: struct Node { value_type data; std::shared_ptr<Node> next; template<class shared_ptrFwdRef,class ... Args> Node(shared_ptrFwdRef &&next_,Args &&...args) :data{std::forward<decltype(args)>(args)...},next{std::forward<decltype(next_)>(next_)}{} ~Node() { while(next.use_count()==1) { std::shared_ptr<Node> p{std::move(next->next)}; next.reset(); next=std::move(p); } } }; std::shared_ptr<Node> begin_; public: CAtomic_stack()=default; CAtomic_stack(const CAtomic_stack &)=delete; template<class ... Args> void emplace(Args &&...args) { const std::shared_ptr<Node> node{std::make_shared<Node>(std::atomic_load_explicit(&begin_,std::memory_order_relaxed),std::forward<decltype(args)>(args)...)}; while(!std::atomic_compare_exchange_weak_explicit(&begin_,&node->next,node,std::memory_order_release,std::memory_order_relaxed)) ; } template<class ... Args> inline void emplace_not_ts(Args &&...args) { begin_=std::make_shared<Node>(begin_,std::forward<decltype(args)>(args)...); } inline bool empty() const noexcept { return !begin_.operator bool(); } inline bool is_lock_free() const noexcept { return std::atomic_is_lock_free(&begin_); } //if constructor or assignment operator you use here is not noexcept, it may not be exception safety value_type pop() noexcept { std::shared_ptr<Node> node{std::atomic_load_explicit(&begin_,std::memory_order_relaxed)}; while(!std::atomic_compare_exchange_weak_explicit(&begin_,&node,node->next,std::memory_order_acquire,std::memory_order_relaxed)) ; return std::move(node->data); } CAtomic_stack& operator=(const CAtomic_stack &)=delete; }; } #endif<commit_msg>add comment<commit_after>#ifndef CATOMIC_STACK #define CATOMIC_STACK #include<atomic> #include<memory> //shared_ptr, make_shared #include<utility> //forward, move namespace nThread { template<class T> class CAtomic_stack { public: using value_type=T; private: struct Node { value_type data; std::shared_ptr<Node> next; template<class shared_ptrFwdRef,class ... Args> Node(shared_ptrFwdRef &&next_,Args &&...args) :data{std::forward<decltype(args)>(args)...},next{std::forward<decltype(next_)>(next_)}{} ~Node() { while(next.use_count()==1) { std::shared_ptr<Node> p{std::move(next->next)}; next.reset(); next=std::move(p); } } }; std::shared_ptr<Node> begin_; public: CAtomic_stack()=default; CAtomic_stack(const CAtomic_stack &)=delete; template<class ... Args> void emplace(Args &&...args) { const std::shared_ptr<Node> node{std::make_shared<Node>(std::atomic_load_explicit(&begin_,std::memory_order_relaxed),std::forward<decltype(args)>(args)...)}; while(!std::atomic_compare_exchange_weak_explicit(&begin_,&node->next,node,std::memory_order_release,std::memory_order_relaxed)) ; } //1. do not call emplace_not_ts with greater than or equal to 2 threads //2. do not call CAtomic_stack::pop at same time template<class ... Args> inline void emplace_not_ts(Args &&...args) { begin_=std::make_shared<Node>(begin_,std::forward<decltype(args)>(args)...); } inline bool empty() const noexcept { return !begin_.operator bool(); } inline bool is_lock_free() const noexcept { return std::atomic_is_lock_free(&begin_); } //if constructor or assignment operator you use here is not noexcept, it may not be exception safety value_type pop() noexcept { std::shared_ptr<Node> node{std::atomic_load_explicit(&begin_,std::memory_order_relaxed)}; while(!std::atomic_compare_exchange_weak_explicit(&begin_,&node,node->next,std::memory_order_acquire,std::memory_order_relaxed)) ; return std::move(node->data); } CAtomic_stack& operator=(const CAtomic_stack &)=delete; }; } #endif<|endoftext|>
<commit_before>/*********************************************************************** created: Sep 11 2014 author: Luca Ebach <lucaebach@gmail.com> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ /************************************************************************** * The following libs (and corresponding headers) are needed to compile and to link: * CEGUIBase * CEGUIOpenGLRenderer * CEGUICoreWindowRendererSet * default CEGUI xml parser (and dependencies) * SDL2main * SDL2 * OpengGL * glm headers (as part of CEGUIBase) ***************************************************************************/ #include <iostream> #include <CEGUI/CEGUI.h> #include <CEGUI/RendererModules/OpenGL/GL3Renderer.h> #include <SDL.h> #include <SDL_opengl.h> #include "sdl_scancode_to_dinput_mappings.h" static SDL_Window* window; static SDL_GLContext context; CEGUI::Key::Scan toCEGUIKey(SDL_Scancode key) { return static_cast<CEGUI::Key::Scan>(scanCodeToKeyNum[static_cast<int>(key)]); } void injectUTF8Text(const char* utf8str) { static SDL_iconv_t cd = SDL_iconv_t(-1); if (cd == SDL_iconv_t(-1)) { // note: just "UTF-32" doesn't work as toFormat, because then you get BOMs, which we don't want. const char* toFormat = "UTF-32LE"; // TODO: what does CEGUI expect on big endian machines? cd = SDL_iconv_open(toFormat, "UTF-8"); if (cd == SDL_iconv_t(-1)) { std::cerr << "Couldn't initialize SDL_iconv for UTF-8 to UTF-32!" << std::endl; return; } } // utf8str has at most SDL_TEXTINPUTEVENT_TEXT_SIZE (32) chars, // so we won't have have more utf32 chars than that Uint32 utf32buf[SDL_TEXTINPUTEVENT_TEXT_SIZE] = {0}; // we'll convert utf8str to a utf32 string, saved in utf32buf. // the utf32 chars will be injected into cegui size_t len = strlen(utf8str); size_t inbytesleft = len; size_t outbytesleft = 4 * SDL_TEXTINPUTEVENT_TEXT_SIZE; // *4 because utf-32 needs 4x as much space as utf-8 char* outbuf = (char*)utf32buf; size_t n = SDL_iconv(cd, &utf8str, &inbytesleft, &outbuf, &outbytesleft); if (n == size_t(-1)) // some error occured during iconv { std::cerr << "Converting UTF-8 string " << utf8str << " from SDL_TEXTINPUT to UTF-32 failed!" << std::endl; } for (int i = 0; i < SDL_TEXTINPUTEVENT_TEXT_SIZE; ++i) { if (utf32buf[i] == 0) break; // end of string CEGUI::System::getSingleton().getDefaultGUIContext().injectChar(utf32buf[i]); } // reset cd so it can be used again SDL_iconv(cd, NULL, &inbytesleft, NULL, &outbytesleft); } void initSDL() { // init everything from SDL if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cerr << "SDL could not be initialized!" << std::endl << "Error message: " << SDL_GetError() << std::endl; exit(1); } // create opengl window with size of 800x600px window = SDL_CreateWindow("CEGUI + SDL2 window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); if (!window) { std::cerr << "Could not create SDL window: " << SDL_GetError() << std::endl; SDL_Quit(); exit(1); } // disable native mouse cursor SDL_ShowCursor(0); // setup opengl rendering context context = SDL_GL_CreateContext(window); } void initCEGUI() { using namespace CEGUI; // create renderer and enable extra states OpenGL3Renderer& cegui_renderer = OpenGL3Renderer::create(Sizef(800.f, 600.f)); cegui_renderer.enableExtraStateSettings(true); // create CEGUI system object System::create(cegui_renderer); // setup resource directories DefaultResourceProvider* rp = static_cast<DefaultResourceProvider*>(System::getSingleton().getResourceProvider()); rp->setResourceGroupDirectory("schemes", "datafiles/schemes/"); rp->setResourceGroupDirectory("imagesets", "datafiles/imagesets/"); rp->setResourceGroupDirectory("fonts", "datafiles/fonts/"); rp->setResourceGroupDirectory("layouts", "datafiles/layouts/"); rp->setResourceGroupDirectory("looknfeels", "datafiles/looknfeel/"); rp->setResourceGroupDirectory("lua_scripts", "datafiles/lua_scripts/"); rp->setResourceGroupDirectory("schemas", "datafiles/xml_schemas/"); // set default resource groups ImageManager::setImagesetDefaultResourceGroup("imagesets"); Font::setDefaultResourceGroup("fonts"); Scheme::setDefaultResourceGroup("schemes"); WidgetLookManager::setDefaultResourceGroup("looknfeels"); WindowManager::setDefaultResourceGroup("layouts"); ScriptModule::setDefaultResourceGroup("lua_scripts"); XMLParser* parser = System::getSingleton().getXMLParser(); if (parser->isPropertyPresent("SchemaDefaultResourceGroup")) parser->setProperty("SchemaDefaultResourceGroup", "schemas"); // load TaharezLook scheme and DejaVuSans-10 font SchemeManager::getSingleton().createFromFile("TaharezLook.scheme", "schemes"); FontManager::getSingleton().createFromFile("DejaVuSans-10.font"); // set default font and cursor image and tooltip type System::getSingleton().getDefaultGUIContext().setDefaultFont("DejaVuSans-10"); System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("TaharezLook/MouseArrow"); System::getSingleton().getDefaultGUIContext().setDefaultTooltipType("TaharezLook/Tooltip"); } void initWindows() { using namespace CEGUI; ///////////////////////////////////////////////////////////// // Add your gui initialisation code in here. // You can use the following code as an inspiration for // creating your own windows. // But you should preferably use layout loading because you won't // have to recompile everytime you change the layout. ///////////////////////////////////////////////////////////// // load layout Window* root = WindowManager::getSingleton().loadLayoutFromFile("application_templates.layout"); System::getSingleton().getDefaultGUIContext().setRootWindow(root); } // convert SDL mouse button to CEGUI mouse button CEGUI::MouseButton SDLtoCEGUIMouseButton(const Uint8& button) { using namespace CEGUI; switch (button) { case SDL_BUTTON_LEFT: return LeftButton; case SDL_BUTTON_MIDDLE: return MiddleButton; case SDL_BUTTON_RIGHT: return RightButton; case SDL_BUTTON_X1: return X1Button; case SDL_BUTTON_X2: return X2Button; default: return NoButton; } } int main(int argc, char* argv[]) { using namespace CEGUI; // init SDL initSDL(); // init cegui initCEGUI(); // notify system of the window size System::getSingleton().notifyDisplaySizeChanged(Sizef(800.f, 600.f)); // initialise windows and setup layout initWindows(); // set gl clear color glClearColor(0, 0, 0, 255); bool quit = false; SDL_Event event; float time = SDL_GetTicks() / 1000.f; OpenGL3Renderer* renderer = static_cast<OpenGL3Renderer*>(System::getSingleton().getRenderer()); // repeat until a quit is requested while (!quit && !SDL_QuitRequested()) { // query and process events while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: quit = true; break; case SDL_MOUSEMOTION: CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(static_cast<float>(event.motion.x), static_cast<float>(event.motion.y)); break; case SDL_MOUSEBUTTONDOWN: CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseButtonDown(SDLtoCEGUIMouseButton(event.button.button)); break; case SDL_MOUSEBUTTONUP: CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseButtonUp(SDLtoCEGUIMouseButton(event.button.button)); break; case SDL_MOUSEWHEEL: CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseWheelChange(static_cast<float>(event.wheel.y)); break; case SDL_KEYDOWN: CEGUI::System::getSingleton().getDefaultGUIContext().injectKeyDown(toCEGUIKey(event.key.keysym.scancode)); break; case SDL_KEYUP: CEGUI::System::getSingleton().getDefaultGUIContext().injectKeyUp(toCEGUIKey(event.key.keysym.scancode)); break; case SDL_TEXTINPUT: injectUTF8Text(event.text.text); break; case SDL_WINDOWEVENT: if (event.window.event == SDL_WINDOWEVENT_RESIZED) { System::getSingleton().notifyDisplaySizeChanged(Sizef(static_cast<float>(event.window.data1), static_cast<float>(event.window.data2))); glViewport(0, 0, event.window.data1, event.window.data2); } else if (event.window.event == SDL_WINDOWEVENT_LEAVE) { CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseLeaves(); } break; default: break; } } glClear(GL_COLOR_BUFFER_BIT); // inject time pulses const float newtime = SDL_GetTicks() / 1000.f; const float time_elapsed = newtime - time; System::getSingleton().injectTimePulse(time_elapsed); System::getSingleton().getDefaultGUIContext().injectTimePulse(time_elapsed); time = newtime; // render gui renderer->beginRendering(); System::getSingleton().renderAllGUIContexts(); renderer->endRendering(); // swap buffers SDL_GL_SwapWindow(window); } // destroy system and renderer System::destroy(); OpenGL3Renderer::destroy(*renderer); renderer = 0; // delete SDL GL context SDL_GL_DeleteContext(context); // destroy SDL window SDL_DestroyWindow(window); // cleanup SDL SDL_Quit(); return 0; } <commit_msg>MOD: docu<commit_after>/*********************************************************************** created: Sep 11 2014 author: Luca Ebach <bitbucket@lucebac.net> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2015 Paul D Turner & The CEGUI Development Team * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ /************************************************************************** * The following libs (and corresponding headers) are needed to compile and to link: * CEGUIBase * CEGUIOpenGLRenderer * CEGUICoreWindowRendererSet * default CEGUI xml parser (and dependencies) * SDL2main (windows only) * SDL2 * OpengGL * glm headers (as part of CEGUIBase) ***************************************************************************/ #include <iostream> #include <CEGUI/CEGUI.h> #include <CEGUI/RendererModules/OpenGL/GL3Renderer.h> #include <SDL.h> #include <SDL_opengl.h> #include "sdl_scancode_to_dinput_mappings.h" static SDL_Window* window; static SDL_GLContext context; CEGUI::Key::Scan toCEGUIKey(SDL_Scancode key) { return static_cast<CEGUI::Key::Scan>(scanCodeToKeyNum[static_cast<int>(key)]); } void injectUTF8Text(const char* utf8str) { static SDL_iconv_t cd = SDL_iconv_t(-1); if (cd == SDL_iconv_t(-1)) { // note: just "UTF-32" doesn't work as toFormat, because then you get BOMs, which we don't want. const char* toFormat = "UTF-32LE"; // TODO: what does CEGUI expect on big endian machines? cd = SDL_iconv_open(toFormat, "UTF-8"); if (cd == SDL_iconv_t(-1)) { std::cerr << "Couldn't initialize SDL_iconv for UTF-8 to UTF-32!" << std::endl; return; } } // utf8str has at most SDL_TEXTINPUTEVENT_TEXT_SIZE (32) chars, // so we won't have have more utf32 chars than that Uint32 utf32buf[SDL_TEXTINPUTEVENT_TEXT_SIZE] = {0}; // we'll convert utf8str to a utf32 string, saved in utf32buf. // the utf32 chars will be injected into cegui size_t len = strlen(utf8str); size_t inbytesleft = len; size_t outbytesleft = 4 * SDL_TEXTINPUTEVENT_TEXT_SIZE; // *4 because utf-32 needs 4x as much space as utf-8 char* outbuf = (char*)utf32buf; size_t n = SDL_iconv(cd, &utf8str, &inbytesleft, &outbuf, &outbytesleft); if (n == size_t(-1)) // some error occured during iconv { std::cerr << "Converting UTF-8 string " << utf8str << " from SDL_TEXTINPUT to UTF-32 failed!" << std::endl; } for (int i = 0; i < SDL_TEXTINPUTEVENT_TEXT_SIZE; ++i) { if (utf32buf[i] == 0) break; // end of string CEGUI::System::getSingleton().getDefaultGUIContext().injectChar(utf32buf[i]); } // reset cd so it can be used again SDL_iconv(cd, NULL, &inbytesleft, NULL, &outbytesleft); } void initSDL() { // init everything from SDL if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { std::cerr << "SDL could not be initialized!" << std::endl << "Error message: " << SDL_GetError() << std::endl; exit(1); } // create opengl window with size of 800x600px window = SDL_CreateWindow("CEGUI + SDL2 window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); if (!window) { std::cerr << "Could not create SDL window: " << SDL_GetError() << std::endl; SDL_Quit(); exit(1); } // disable native mouse cursor SDL_ShowCursor(0); // setup opengl rendering context context = SDL_GL_CreateContext(window); } void initCEGUI() { using namespace CEGUI; // create renderer and enable extra states OpenGL3Renderer& cegui_renderer = OpenGL3Renderer::create(Sizef(800.f, 600.f)); cegui_renderer.enableExtraStateSettings(true); // create CEGUI system object System::create(cegui_renderer); // setup resource directories DefaultResourceProvider* rp = static_cast<DefaultResourceProvider*>(System::getSingleton().getResourceProvider()); rp->setResourceGroupDirectory("schemes", "datafiles/schemes/"); rp->setResourceGroupDirectory("imagesets", "datafiles/imagesets/"); rp->setResourceGroupDirectory("fonts", "datafiles/fonts/"); rp->setResourceGroupDirectory("layouts", "datafiles/layouts/"); rp->setResourceGroupDirectory("looknfeels", "datafiles/looknfeel/"); rp->setResourceGroupDirectory("lua_scripts", "datafiles/lua_scripts/"); rp->setResourceGroupDirectory("schemas", "datafiles/xml_schemas/"); // set default resource groups ImageManager::setImagesetDefaultResourceGroup("imagesets"); Font::setDefaultResourceGroup("fonts"); Scheme::setDefaultResourceGroup("schemes"); WidgetLookManager::setDefaultResourceGroup("looknfeels"); WindowManager::setDefaultResourceGroup("layouts"); ScriptModule::setDefaultResourceGroup("lua_scripts"); XMLParser* parser = System::getSingleton().getXMLParser(); if (parser->isPropertyPresent("SchemaDefaultResourceGroup")) parser->setProperty("SchemaDefaultResourceGroup", "schemas"); // load TaharezLook scheme and DejaVuSans-10 font SchemeManager::getSingleton().createFromFile("TaharezLook.scheme", "schemes"); FontManager::getSingleton().createFromFile("DejaVuSans-10.font"); // set default font and cursor image and tooltip type System::getSingleton().getDefaultGUIContext().setDefaultFont("DejaVuSans-10"); System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("TaharezLook/MouseArrow"); System::getSingleton().getDefaultGUIContext().setDefaultTooltipType("TaharezLook/Tooltip"); } void initWindows() { using namespace CEGUI; ///////////////////////////////////////////////////////////// // Add your gui initialisation code in here. // You can use the following code as an inspiration for // creating your own windows. // But you should preferably use layout loading because you won't // have to recompile everytime you change the layout. ///////////////////////////////////////////////////////////// // load layout Window* root = WindowManager::getSingleton().loadLayoutFromFile("application_templates.layout"); System::getSingleton().getDefaultGUIContext().setRootWindow(root); } // convert SDL mouse button to CEGUI mouse button CEGUI::MouseButton SDLtoCEGUIMouseButton(const Uint8& button) { using namespace CEGUI; switch (button) { case SDL_BUTTON_LEFT: return LeftButton; case SDL_BUTTON_MIDDLE: return MiddleButton; case SDL_BUTTON_RIGHT: return RightButton; case SDL_BUTTON_X1: return X1Button; case SDL_BUTTON_X2: return X2Button; default: return NoButton; } } int main(int argc, char* argv[]) { using namespace CEGUI; // init SDL initSDL(); // init cegui initCEGUI(); // notify system of the window size System::getSingleton().notifyDisplaySizeChanged(Sizef(800.f, 600.f)); // initialise windows and setup layout initWindows(); // set gl clear color glClearColor(0, 0, 0, 255); bool quit = false; SDL_Event event; float time = SDL_GetTicks() / 1000.f; OpenGL3Renderer* renderer = static_cast<OpenGL3Renderer*>(System::getSingleton().getRenderer()); // repeat until a quit is requested while (!quit && !SDL_QuitRequested()) { // query and process events while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: quit = true; break; case SDL_MOUSEMOTION: CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(static_cast<float>(event.motion.x), static_cast<float>(event.motion.y)); break; case SDL_MOUSEBUTTONDOWN: CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseButtonDown(SDLtoCEGUIMouseButton(event.button.button)); break; case SDL_MOUSEBUTTONUP: CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseButtonUp(SDLtoCEGUIMouseButton(event.button.button)); break; case SDL_MOUSEWHEEL: CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseWheelChange(static_cast<float>(event.wheel.y)); break; case SDL_KEYDOWN: CEGUI::System::getSingleton().getDefaultGUIContext().injectKeyDown(toCEGUIKey(event.key.keysym.scancode)); break; case SDL_KEYUP: CEGUI::System::getSingleton().getDefaultGUIContext().injectKeyUp(toCEGUIKey(event.key.keysym.scancode)); break; case SDL_TEXTINPUT: injectUTF8Text(event.text.text); break; case SDL_WINDOWEVENT: if (event.window.event == SDL_WINDOWEVENT_RESIZED) { System::getSingleton().notifyDisplaySizeChanged(Sizef(static_cast<float>(event.window.data1), static_cast<float>(event.window.data2))); glViewport(0, 0, event.window.data1, event.window.data2); } else if (event.window.event == SDL_WINDOWEVENT_LEAVE) { CEGUI::System::getSingleton().getDefaultGUIContext().injectMouseLeaves(); } break; default: break; } } glClear(GL_COLOR_BUFFER_BIT); // inject time pulses const float newtime = SDL_GetTicks() / 1000.f; const float time_elapsed = newtime - time; System::getSingleton().injectTimePulse(time_elapsed); System::getSingleton().getDefaultGUIContext().injectTimePulse(time_elapsed); time = newtime; // render gui renderer->beginRendering(); System::getSingleton().renderAllGUIContexts(); renderer->endRendering(); // swap buffers SDL_GL_SwapWindow(window); } // destroy system and renderer System::destroy(); OpenGL3Renderer::destroy(*renderer); renderer = 0; // delete SDL GL context SDL_GL_DeleteContext(context); // destroy SDL window SDL_DestroyWindow(window); // cleanup SDL SDL_Quit(); return 0; } <|endoftext|>
<commit_before>/** * This file is part of the "FnordMetric" project * Copyright (c) 2011-2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <assert.h> #include <signal.h> #include <string.h> #include <fnord/exception.h> #include <fnord/exceptionhandler.h> #include <fnord/inspect.h> #include <fnord/logging.h> #include <fnord/StackTrace.h> namespace fnord { using fnord::Exception; CatchAndLogExceptionHandler::CatchAndLogExceptionHandler( const String& component) : component_(component) {} void CatchAndLogExceptionHandler::onException( const std::exception& error) const { logError(component_, error, "Uncaught exception"); } CatchAndAbortExceptionHandler::CatchAndAbortExceptionHandler( const std::string& message) : message_(message) {} void CatchAndAbortExceptionHandler::onException( const std::exception& error) const { fprintf(stderr, "%s\n\n", message_.c_str()); // FIXPAUL try { auto rte = dynamic_cast<const fnord::Exception&>(error); rte.debugPrint(); } catch (const std::exception& cast_error) { fprintf(stderr, "foreign exception: %s\n", error.what()); } fprintf(stderr, "Aborting...\n"); abort(); // core dump if enabled } static std::string globalEHandlerMessage; static void globalSEGVHandler(int sig) { fprintf(stderr, "%s\n", globalEHandlerMessage.c_str()); fprintf(stderr, "signal: %s\n", strsignal(sig)); StackTrace strace; strace.debugPrint(2); exit(EXIT_FAILURE); } static void globalEHandler() { fprintf(stderr, "%s\n", globalEHandlerMessage.c_str()); auto ex = std::current_exception(); if (ex == nullptr) { fprintf(stderr, "<no active exception>\n"); return; } try { std::rethrow_exception(ex); } catch (const fnord::Exception& e) { e.debugPrint(); } catch (const std::exception& e) { fprintf(stderr, "foreign exception: %s\n", e.what()); } exit(EXIT_FAILURE); } void CatchAndAbortExceptionHandler::installGlobalHandlers() { globalEHandlerMessage = message_; std::set_terminate(&globalEHandler); std::set_unexpected(&globalEHandler); signal(SIGILL, &globalSEGVHandler); signal(SIGABRT, &globalSEGVHandler); signal(SIGFPE, &globalSEGVHandler); signal(SIGSEGV, &globalSEGVHandler); signal(SIGBUS, &globalSEGVHandler); signal(SIGSYS, &globalSEGVHandler); } } // namespace fnord <commit_msg>use sigaction()<commit_after>/** * This file is part of the "FnordMetric" project * Copyright (c) 2011-2014 Paul Asmuth, Google Inc. * * FnordMetric is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License v3.0. You should have received a * copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ #include <stdlib.h> #include <assert.h> #include <signal.h> #include <string.h> #include <fnord/exception.h> #include <fnord/exceptionhandler.h> #include <fnord/inspect.h> #include <fnord/logging.h> #include <fnord/StackTrace.h> namespace fnord { using fnord::Exception; CatchAndLogExceptionHandler::CatchAndLogExceptionHandler( const String& component) : component_(component) {} void CatchAndLogExceptionHandler::onException( const std::exception& error) const { logError(component_, error, "Uncaught exception"); } CatchAndAbortExceptionHandler::CatchAndAbortExceptionHandler( const std::string& message) : message_(message) {} void CatchAndAbortExceptionHandler::onException( const std::exception& error) const { fprintf(stderr, "%s\n\n", message_.c_str()); // FIXPAUL try { auto rte = dynamic_cast<const fnord::Exception&>(error); rte.debugPrint(); } catch (const std::exception& cast_error) { fprintf(stderr, "foreign exception: %s\n", error.what()); } fprintf(stderr, "Aborting...\n"); abort(); // core dump if enabled } static std::string globalEHandlerMessage; static void globalSEGVHandler(int sig, siginfo_t* siginfo, void* ctx) { fprintf(stderr, "%s\n", globalEHandlerMessage.c_str()); fprintf(stderr, "signal: %s\n", strsignal(sig)); StackTrace strace; strace.debugPrint(2); exit(EXIT_FAILURE); } static void globalEHandler() { fprintf(stderr, "%s\n", globalEHandlerMessage.c_str()); auto ex = std::current_exception(); if (ex == nullptr) { fprintf(stderr, "<no active exception>\n"); return; } try { std::rethrow_exception(ex); } catch (const fnord::Exception& e) { e.debugPrint(); } catch (const std::exception& e) { fprintf(stderr, "foreign exception: %s\n", e.what()); } exit(EXIT_FAILURE); } void CatchAndAbortExceptionHandler::installGlobalHandlers() { globalEHandlerMessage = message_; std::set_terminate(&globalEHandler); std::set_unexpected(&globalEHandler); struct sigaction sigact; memset(&sigact, 0, sizeof(sigact)); sigact.sa_sigaction = &globalSEGVHandler; sigact.sa_flags = SA_SIGINFO; if (sigaction(SIGSEGV, &sigact, NULL) < 0) { RAISE_ERRNO(kIOError, "sigaction() failed"); } if (sigaction(SIGABRT, &sigact, NULL) < 0) { RAISE_ERRNO(kIOError, "sigaction() failed"); } if (sigaction(SIGBUS, &sigact, NULL) < 0) { RAISE_ERRNO(kIOError, "sigaction() failed"); } if (sigaction(SIGSYS, &sigact, NULL) < 0) { RAISE_ERRNO(kIOError, "sigaction() failed"); } if (sigaction(SIGILL, &sigact, NULL) < 0) { RAISE_ERRNO(kIOError, "sigaction() failed"); } if (sigaction(SIGFPE, &sigact, NULL) < 0) { RAISE_ERRNO(kIOError, "sigaction() failed"); } } } // namespace fnord <|endoftext|>
<commit_before><commit_msg>Format and cleanup CameraTest app<commit_after><|endoftext|>
<commit_before>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" #include "Game.h" #include "Editor.h" #include "Input.h" #include "BlueRayUtils.h" #include "World.h" #include "Action.h" #include "FPSRoleLocal.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); m_pRole->SetActorPosition(vec3(0, 0, 0)); //设置角色初始位置。以门处作为原点,三维坐标系vec3是向量 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); m_pRayControl = new CRayControl(); return 1; } int CGameProcess::ShutDown() //关闭游戏进程 { delete m_pRole; delete m_pSkillSystem; delete m_pCameraBase; delete m_pStarControl; delete m_pRayControl; DelAllListen(); return 0; } int CGameProcess::Update() { float ifps = g_Engine.pGame->GetIFps(); if (g_Engine.pInput->IsKeyDown('1')) { CAction* pAction = m_pRole->OrceAction("attack02"); if (pAction) { pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f); m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('2')) { CAction* pAction = m_pRole->OrceAction("skill01"); if (pAction) { m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('3')) { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CRoleBase* pTarget = NULL; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 15.0f) { pTarget = m_vAIList[i]; break; } } if (pTarget) { CVector<int> vTarget; vTarget.Append(pTarget->GetRoleID()); pAction->SetupSkillBulletTarget(vTarget); m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1); } } } else if (g_Engine.pInput->IsKeyDown('4'))//多发子弹 { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CVector<int> vTarget; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) { vTarget.Append(m_vAIList[i]->GetRoleID()); } } if (!vTarget.Empty()) { pAction->SetupSkillBulletTarget(vTarget); } } } else if (g_Engine.pInput->IsKeyDown('5')) { CAction* pAction = m_pRole->OrceAction("skill03"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; pAction->SetupSkillTargetPoint(vPos); } } else if (g_Engine.pInput->IsKeyDown('6')) { CAction* pAction = m_pRole->OrceAction("skill06"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vPos.Append(m_vAIList[i]->GetPosition()); } pAction->SetupSkillTargetPoint(vPos); } } else if (g_Engine.pInput->IsKeyDown('7')) { CAction* pAction = m_pRole->OrceAction("skill05"); if (pAction) { m_pRole->StopMove(); CVector<int> vTarget; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vTarget.Append(m_vAIList[i]->GetRoleID()); } if (!vTarget.Empty()) { pAction->SetupSkillBulletTarget(vTarget); } } } else if (g_Engine.pInput->IsKeyDown('8')) { CAction* pAction = m_pRole->OrceAction("skill07"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vPos.Append(m_vAIList[i]->GetPosition()); } pAction->SetupSkillBulletPosition(vPos); } } else if (g_Engine.pInput->IsKeyDown('9')) { CAction* pAction = m_pRole->OrceAction("skill08"); if (pAction) { m_pRole->StopMove(); pAction->SetupSkillBulletDirection(1); } } else if (g_Engine.pInput->IsKeyUp(CInput::KEY_ESC)) { g_Engine.pApp->Exit(); } if(g_Engine.pInput->IsLBDown()) { vec3 p0,p1; BlueRay::GetPlayerMouseDirection(p0,p1); vec3 vRetPoint,vRetNormal; int nS = -1; g_Engine.pWorld->GetIntersection(p0,p1,CBRObject::MASK_SCENE,vRetPoint,vRetNormal,nS); if(-1 != nS) { m_pRole->MoveToPath(vRetPoint); } } for(int i = 0;i < 20;i++) { if(!m_vAIList[i]->IsMoveing()) { vec3 vPos = vec3(g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),1.1f); m_vAIList[i]->MoveToPath(vPos); } m_vAIList[i]->Update(ifps); } if (g_Engine.pInput->IsLBDown()) //shubiaozuojian { g_pSysControl->SetMouseGrab(1); m_pStarControl->Click(); } if (g_Engine.pInput->IsKeyDown(CInput::KEY_ESC)) { g_pSysControl->SetMouseGrab(0); } m_pCameraBase->SetMouseControls(g_pSysControl->GetMouseGrab()); m_pCameraBase->Update(ifps); m_pRole->SetActorDirection(m_pCameraBase->GetViewDirection()); m_pRole->UpdateActor(ifps); m_pCameraBase->SetPosition(m_pRole->GetActorPosition() + m_pRole->GetCameraOffset()); return 0; } <commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" #include "Game.h" #include "Editor.h" #include "Input.h" #include "BlueRayUtils.h" #include "World.h" #include "Action.h" #include "FPSRoleLocal.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); m_pRole->SetActorPosition(vec3(0, 0, 0)); //设置角色初始位置。以门处作为原点,三维坐标系vec3是向量 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); m_pRayControl = new CRayControl(); return 1; } int CGameProcess::ShutDown() //关闭游戏进程 { delete m_pRole; delete m_pSkillSystem; delete m_pCameraBase; delete m_pStarControl; delete m_pRayControl; DelAllListen(); return 0; } int CGameProcess::Update() { float ifps = g_Engine.pGame->GetIFps(); if (g_Engine.pInput->IsKeyDown('1')) { CAction* pAction = m_pRole->OrceAction("attack02"); if (pAction) { pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f); m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('2')) { CAction* pAction = m_pRole->OrceAction("skill01"); if (pAction) { m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('3')) { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CRoleBase* pTarget = NULL; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 15.0f) { pTarget = m_vAIList[i]; break; } } if (pTarget) { CVector<int> vTarget; vTarget.Append(pTarget->GetRoleID()); pAction->SetupSkillBulletTarget(vTarget); m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1); } } } else if (g_Engine.pInput->IsKeyDown('4'))//多发子弹 { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CVector<int> vTarget; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) { vTarget.Append(m_vAIList[i]->GetRoleID()); } } if (!vTarget.Empty()) { pAction->SetupSkillBulletTarget(vTarget); } } } else if (g_Engine.pInput->IsKeyDown('5')) { CAction* pAction = m_pRole->OrceAction("skill03"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; pAction->SetupSkillTargetPoint(vPos); } } else if (g_Engine.pInput->IsKeyDown('6')) { CAction* pAction = m_pRole->OrceAction("skill06"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vPos.Append(m_vAIList[i]->GetPosition()); } pAction->SetupSkillTargetPoint(vPos); } } else if (g_Engine.pInput->IsKeyDown('7')) { CAction* pAction = m_pRole->OrceAction("skill05"); if (pAction) { m_pRole->StopMove(); CVector<int> vTarget; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vTarget.Append(m_vAIList[i]->GetRoleID()); } if (!vTarget.Empty()) { pAction->SetupSkillBulletTarget(vTarget); } } } else if (g_Engine.pInput->IsKeyDown('8')) { CAction* pAction = m_pRole->OrceAction("skill07"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vPos.Append(m_vAIList[i]->GetPosition()); } pAction->SetupSkillBulletPosition(vPos); } } else if (g_Engine.pInput->IsKeyDown('9')) { CAction* pAction = m_pRole->OrceAction("skill08"); if (pAction) { m_pRole->StopMove(); pAction->SetupSkillBulletDirection(1); } } else if (g_Engine.pInput->IsKeyUp(CInput::KEY_ESC)) { g_Engine.pApp->Exit(); } if(g_Engine.pInput->IsLBDown()) { vec3 p0,p1; BlueRay::GetPlayerMouseDirection(p0,p1); vec3 vRetPoint,vRetNormal; int nS = -1; g_Engine.pWorld->GetIntersection(p0,p1,CBRObject::MASK_SCENE,vRetPoint,vRetNormal,nS); if(-1 != nS) { m_pRole->MoveToPath(vRetPoint); } } for(int i = 0;i < 20;i++) { if(!m_vAIList[i]->IsMoveing()) { vec3 vPos = vec3(g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),1.1f); m_vAIList[i]->MoveToPath(vPos); } m_vAIList[i]->Update(ifps); } if (g_Engine.pInput->IsLBDown()) //shubiaozuojian { g_pSysControl->SetMouseGrab(1); m_pStarControl->Click(); } if (g_Engine.pInput->IsKeyDown(CInput::KEY_ESC)) { g_pSysControl->SetMouseGrab(0); } m_pCameraBase->SetMouseControls(g_pSysControl->GetMouseGrab()); m_pCameraBase->Update(ifps); m_pRole->SetActorDirection(m_pCameraBase->GetViewDirection()); m_pRole->UpdateActor(ifps); m_pCameraBase->SetPosition(m_pRole->GetActorPosition() + m_pRole->GetCameraOffset()); vec3 x = m_pCameraBase->GetModelview().getRow3(0); vec3 y = m_pCameraBase->GetModelview().getRow3(1); vec3 z = m_pCameraBase->GetModelview().getRow3(2); return 0; } <|endoftext|>
<commit_before>#ifndef ATOMIC_STACK #define ATOMIC_STACK #include<atomic> #include<memory> //allocator, shared_ptr #include<type_traits> #include<utility> //move #include"Node.hpp" #include"../tool/CAlloc_obj.hpp" namespace nThread { struct Use_pop_if_exist{}; struct Do_not_use_pop_if_exist{}; //for UsePopIfExist, only Use_pop_if_exist and Do_not_use_pop_if_exist are allowed template<class T,class PopIfExist=Do_not_use_pop_if_exist,class Alloc=std::allocator<T>> struct Atomic_stack { using allocator_type=typename nTool::CAlloc_obj<T,Alloc>::allocator_type; using element_type=Node<nTool::CAlloc_obj<T,Alloc>>; using size_type=typename nTool::CAlloc_obj<T,Alloc>::size_type; using value_type=typename nTool::CAlloc_obj<T,Alloc>::value_type; static constexpr bool POP_IF_EXIST{std::is_same<PopIfExist,Use_pop_if_exist>::value}; std::shared_ptr<element_type> begin; Atomic_stack()=default; Atomic_stack(const Atomic_stack &)=delete; //you have to guarantee the std::shared_ptr<element_type> is unique void emplace(std::shared_ptr<element_type> &&val) noexcept { using namespace std; while(1<val.use_count()) //prevent ABA problem ; val->next=atomic_load_explicit(&begin,memory_order_relaxed); while(!atomic_compare_exchange_weak_explicit(&begin,&val->next,val,memory_order_release,memory_order_relaxed)) ; count_.add(); } //do not call Atomic_stack::emplace, emplace_not_ts, Atomic_stack::pop or Atomic_stack::pop_not_ts at same time void emplace_not_ts(std::shared_ptr<element_type> &&val) noexcept { //yes, don't need to prevent ABA problem val->next=begin; begin=std::move(val); count_.add(); } inline bool empty() const noexcept { return !begin.operator bool(); } inline bool is_lock_free() const noexcept { return std::atomic_is_lock_free(&begin); } std::shared_ptr<element_type> pop() noexcept { count_.sub(); return pop_(); } //return std::shared_ptr<element_type>{} if empty() return true; otherwise, call pop() std::shared_ptr<element_type> pop_if_exist() noexcept { using is_enable=std::enable_if_t<POP_IF_EXIST>; if(count_.sub_if_greater_than_0()) return pop_(); return std::shared_ptr<element_type>{}; } //do not call Atomic_stack::emplace, Atomic_stack::emplace_not_ts, Atomic_stack::pop or pop_not_ts at same time std::shared_ptr<element_type> pop_not_ts() noexcept { count_.sub(); const std::shared_ptr<element_type> node{std::move(begin)}; begin=std::move(node->next); return node; } inline size_type size() const noexcept { using is_enable=std::enable_if_t<POP_IF_EXIST>; return count_.size(); } Atomic_stack& operator=(const Atomic_stack &)=delete; private: using check_UsePopIfExist_type=std::enable_if_t<std::is_same<PopIfExist,Use_pop_if_exist>::value||std::is_same<PopIfExist,Do_not_use_pop_if_exist>::value>; class Count { std::atomic<size_type> count_; public: Count() noexcept :count_{0}{} Count(const Count &)=delete; inline void add() noexcept { count_.fetch_add(1,std::memory_order_release); } inline size_type size() const noexcept { return count_.load(std::memory_order_acquire); } inline void sub() noexcept { count_.fetch_sub(1,std::memory_order_release); } bool sub_if_greater_than_0() noexcept { auto val{count_.load(std::memory_order_relaxed)}; do { if(!val) return false; }while(!count_.compare_exchange_weak(val,val-1,std::memory_order_acquire,std::memory_order_relaxed)); return true; } Count& operator=(const Count &)=delete; }; struct Empty { inline void add() const noexcept{} inline void sub() const noexcept{} }; std::conditional_t<POP_IF_EXIST,Count,Empty> count_; std::shared_ptr<element_type> pop_() noexcept { using namespace std; shared_ptr<element_type> node{atomic_load_explicit(&begin,memory_order_relaxed)}; while(!atomic_compare_exchange_weak_explicit(&begin,&node,atomic_load(&node->next),memory_order_acquire,memory_order_relaxed)) ; return node; } }; } #endif<commit_msg>fix comment and empty()<commit_after>#ifndef ATOMIC_STACK #define ATOMIC_STACK #include<atomic> #include<memory> //allocator, shared_ptr #include<type_traits> #include<utility> //move #include"Node.hpp" #include"../tool/CAlloc_obj.hpp" namespace nThread { struct Use_pop_if_exist{}; struct Do_not_use_pop_if_exist{}; //for UsePopIfExist, only Use_pop_if_exist and Do_not_use_pop_if_exist are allowed template<class T,class PopIfExist=Do_not_use_pop_if_exist,class Alloc=std::allocator<T>> struct Atomic_stack { using allocator_type=typename nTool::CAlloc_obj<T,Alloc>::allocator_type; using element_type=Node<nTool::CAlloc_obj<T,Alloc>>; using size_type=typename nTool::CAlloc_obj<T,Alloc>::size_type; using value_type=typename nTool::CAlloc_obj<T,Alloc>::value_type; static constexpr bool POP_IF_EXIST{std::is_same<PopIfExist,Use_pop_if_exist>::value}; std::shared_ptr<element_type> begin; Atomic_stack()=default; Atomic_stack(const Atomic_stack &)=delete; //you have to guarantee the std::shared_ptr<element_type> is unique void emplace(std::shared_ptr<element_type> &&val) noexcept { using namespace std; while(1<val.use_count()) //prevent ABA problem ; val->next=atomic_load_explicit(&begin,memory_order_relaxed); while(!atomic_compare_exchange_weak_explicit(&begin,&val->next,val,memory_order_release,memory_order_relaxed)) ; count_.add(); } //do not call other member functions (including const member functions) at same time void emplace_not_ts(std::shared_ptr<element_type> &&val) noexcept { //yes, don't need to prevent ABA problem val->next=begin; begin=std::move(val); count_.add(); } inline bool empty() const noexcept { return !std::atomic_load_explicit(&begin,std::memory_order_acquire); } inline bool is_lock_free() const noexcept { return std::atomic_is_lock_free(&begin); } std::shared_ptr<element_type> pop() noexcept { count_.sub(); return pop_(); } //return std::shared_ptr<element_type>{} if empty() return true; otherwise, call pop() std::shared_ptr<element_type> pop_if_exist() noexcept { using is_enable=std::enable_if_t<POP_IF_EXIST>; if(count_.sub_if_greater_than_0()) return pop_(); return std::shared_ptr<element_type>{}; } //do not call Atomic_stack::emplace, Atomic_stack::emplace_not_ts, Atomic_stack::pop or pop_not_ts at same time std::shared_ptr<element_type> pop_not_ts() noexcept { count_.sub(); const std::shared_ptr<element_type> node{std::move(begin)}; begin=std::move(node->next); return node; } inline size_type size() const noexcept { using is_enable=std::enable_if_t<POP_IF_EXIST>; return count_.size(); } Atomic_stack& operator=(const Atomic_stack &)=delete; private: using check_UsePopIfExist_type=std::enable_if_t<std::is_same<PopIfExist,Use_pop_if_exist>::value||std::is_same<PopIfExist,Do_not_use_pop_if_exist>::value>; class Count { std::atomic<size_type> count_; public: Count() noexcept :count_{0}{} Count(const Count &)=delete; inline void add() noexcept { count_.fetch_add(1,std::memory_order_release); } inline size_type size() const noexcept { return count_.load(std::memory_order_acquire); } inline void sub() noexcept { count_.fetch_sub(1,std::memory_order_release); } bool sub_if_greater_than_0() noexcept { auto val{count_.load(std::memory_order_relaxed)}; do { if(!val) return false; }while(!count_.compare_exchange_weak(val,val-1,std::memory_order_acquire,std::memory_order_relaxed)); return true; } Count& operator=(const Count &)=delete; }; struct Empty { inline void add() const noexcept{} inline void sub() const noexcept{} }; std::conditional_t<POP_IF_EXIST,Count,Empty> count_; std::shared_ptr<element_type> pop_() noexcept { using namespace std; shared_ptr<element_type> node{atomic_load_explicit(&begin,memory_order_relaxed)}; while(!atomic_compare_exchange_weak_explicit(&begin,&node,atomic_load(&node->next),memory_order_acquire,memory_order_relaxed)) ; return node; } }; } #endif<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: testclient.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: rt $ $Date: 2003-04-23 16:44:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <string.h> #if OSL_DEBUG_LEVEL == 0 #define NDEBUG #endif #include <assert.h> #ifndef _OSL_TIME_H_ #include <osl/time.h> #endif #include <osl/mutex.hxx> #include <osl/module.h> #include <osl/thread.h> #include <osl/conditn.h> #include <osl/diagnose.h> #include <uno/mapping.hxx> #include <cppuhelper/servicefactory.hxx> #include <com/sun/star/connection/XConnector.hpp> #include <com/sun/star/bridge/XBridgeFactory.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/lang/DisposedException.hpp> #include <com/sun/star/lang/XMain.hpp> #include <com/sun/star/test/performance/XPerformanceTest.hpp> #include <cppuhelper/weak.hxx> #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #include <test/XTestFactory.hpp> using namespace ::test; using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::bridge; using namespace ::com::sun::star::registry; using namespace ::com::sun::star::connection; using namespace ::com::sun::star::test::performance; #include "testcomp.h" void doPerformanceTest( const Reference < XPerformanceTest > & xBench ) { printf( "not implemented\n" ); // sal_Int32 i,nLoop = 2000; // sal_Int32 tStart, tEnd , tEnd2; // //------------------------------------ // // oneway calls // i = nLoop; // tStart = GetTickCount(); // while (i--) // xBench->async(); // tEnd = GetTickCount(); // xBench->sync(); // tEnd2 = GetTickCount(); // printf( "%d %d %d\n" , nLoop, tEnd - tStart , tEnd2 -tStart ); // // synchron calls // i = nLoop; // tStart = GetTickCount(); // while (i--) // xBench->sync(); // tEnd = GetTickCount(); // printf( "%d %d \n" , nLoop, tEnd - tStart ); } void testLatency( const Reference < XConnection > &r , sal_Bool bReply ) { sal_Int32 nLoop = 10000; TimeValue aStartTime, aEndTime; osl_getSystemTime( &aStartTime ); sal_Int32 i; for( i = 0 ; i < nLoop ; i++ ) { Sequence< sal_Int8 > s1( 200 ); r->write( s1 ); r->read( s1 , 12 ); r->read( s1 , 48 ); } osl_getSystemTime( &aEndTime ); double fStart = (double)aStartTime.Seconds + ((double)aStartTime.Nanosec / 1000000000.0); double fEnd = (double)aEndTime.Seconds + ((double)aEndTime.Nanosec / 1000000000.0); printf( "System latency per call : %g\n" , (( fEnd-fStart )/2.) / ((double)(nLoop)) ); } int main( int argc, char *argv[] ) { sal_Bool bUseNew = ( 3 == argc ); if( argc < 2 ) { printf( "usage : testclient [-r] connectionstring\n" " -r reverse call me test (server calls client)" ); return 0; } OUString sConnectionString; OUString sProtocol; sal_Bool bLatency = sal_False; sal_Bool bReverse = sal_False; parseCommandLine( argv , &sConnectionString , &sProtocol , &bLatency , &bReverse ); { Reference< XMultiServiceFactory > rSMgr = createRegistryServiceFactory( OUString( RTL_CONSTASCII_USTRINGPARAM("client.rdb")) ); Reference < XConnector > rConnector( createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.connection.Connector")), OUString( RTL_CONSTASCII_USTRINGPARAM("connector.uno" SAL_DLLEXTENSION)), rSMgr ), UNO_QUERY ); try { Reference < XConnection > rConnection = rConnector->connect( sConnectionString ); printf( "%s\n" , OUStringToOString( rConnection->getDescription(), RTL_TEXTENCODING_ASCII_US ).pData->buffer ); if( bLatency ) { testLatency( rConnection , sal_False ); testLatency( rConnection , sal_True ); } else { // just ensure that it is registered createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.Bridge.iiop")), OUString( RTL_CONSTASCII_USTRINGPARAM("remotebridge.uno" SAL_DLLEXTENSION)), rSMgr ); Reference < XBridgeFactory > rFactory( createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.BridgeFactory")), OUString( RTL_CONSTASCII_USTRINGPARAM("bridgefac.uno" SAL_DLLEXTENSION)), rSMgr ), UNO_QUERY ); if( rFactory.is() ) { Reference < XBridge > rBridge = rFactory->createBridge( OUString( RTL_CONSTASCII_USTRINGPARAM("bla blub")), sProtocol, rConnection, new OInstanceProvider ); { // test the factory Reference < XBridge > rBridge2 = rFactory->getBridge( OUString( RTL_CONSTASCII_USTRINGPARAM("bla blub")) ); assert( rBridge2.is() ); assert( rBridge2->getDescription() == rBridge->getDescription( ) ); assert( rBridge2->getName() == rBridge->getName() ); assert( rBridge2 == rBridge ); } Reference < XInterface > rInitialObject = rBridge->getInstance( OUString( RTL_CONSTASCII_USTRINGPARAM("bridges-testobject")) ); if( rInitialObject.is() ) { printf( "got the remote object\n" ); if( ! bReverse ) { // Reference < XComponent > rPerfTest( rInitialObject , UNO_QUERY ); // if( rPerfTest.is() ) // { // // doPerformanceTest( rPerfTest ); // } // else // { testRemote( rInitialObject ); // } } } // Reference < XComponent > rComp( rBridge , UNO_QUERY ); // rComp->dispose(); rInitialObject = Reference < XInterface > (); printf( "Waiting...\n" ); TimeValue value={bReverse ?1000 :2,0}; osl_waitThread( &value ); printf( "Closing...\n" ); } Reference < XBridge > rBridge = rFactory->getBridge( OUString( RTL_CONSTASCII_USTRINGPARAM("bla blub")) ); // assert( ! rBridge.is() ); } } catch( DisposedException & e ) { OString o = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); printf( "A remote object reference became invalid\n%s\n" , o.pData->buffer ); } catch( Exception &e ) { OString o = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); printf( "Login failed, got an Exception !\n%s\n" , o.pData->buffer ); } Reference < XComponent > rComp( rSMgr , UNO_QUERY ); rComp->dispose(); } printf( "Closed\n" ); return 0; } <commit_msg>INTEGRATION: CWS ooo19126 (1.10.194); FILE MERGED 2005/09/05 17:08:02 rt 1.10.194.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: testclient.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2005-09-07 22:51:20 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <string.h> #if OSL_DEBUG_LEVEL == 0 #define NDEBUG #endif #include <assert.h> #ifndef _OSL_TIME_H_ #include <osl/time.h> #endif #include <osl/mutex.hxx> #include <osl/module.h> #include <osl/thread.h> #include <osl/conditn.h> #include <osl/diagnose.h> #include <uno/mapping.hxx> #include <cppuhelper/servicefactory.hxx> #include <com/sun/star/connection/XConnector.hpp> #include <com/sun/star/bridge/XBridgeFactory.hpp> #include <com/sun/star/lang/XComponent.hpp> #include <com/sun/star/lang/DisposedException.hpp> #include <com/sun/star/lang/XMain.hpp> #include <com/sun/star/test/performance/XPerformanceTest.hpp> #include <cppuhelper/weak.hxx> #ifndef _CPPUHELPER_FACTORY_HXX_ #include <cppuhelper/factory.hxx> #endif #include <test/XTestFactory.hpp> using namespace ::test; using namespace ::rtl; using namespace ::cppu; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::bridge; using namespace ::com::sun::star::registry; using namespace ::com::sun::star::connection; using namespace ::com::sun::star::test::performance; #include "testcomp.h" void doPerformanceTest( const Reference < XPerformanceTest > & xBench ) { printf( "not implemented\n" ); // sal_Int32 i,nLoop = 2000; // sal_Int32 tStart, tEnd , tEnd2; // //------------------------------------ // // oneway calls // i = nLoop; // tStart = GetTickCount(); // while (i--) // xBench->async(); // tEnd = GetTickCount(); // xBench->sync(); // tEnd2 = GetTickCount(); // printf( "%d %d %d\n" , nLoop, tEnd - tStart , tEnd2 -tStart ); // // synchron calls // i = nLoop; // tStart = GetTickCount(); // while (i--) // xBench->sync(); // tEnd = GetTickCount(); // printf( "%d %d \n" , nLoop, tEnd - tStart ); } void testLatency( const Reference < XConnection > &r , sal_Bool bReply ) { sal_Int32 nLoop = 10000; TimeValue aStartTime, aEndTime; osl_getSystemTime( &aStartTime ); sal_Int32 i; for( i = 0 ; i < nLoop ; i++ ) { Sequence< sal_Int8 > s1( 200 ); r->write( s1 ); r->read( s1 , 12 ); r->read( s1 , 48 ); } osl_getSystemTime( &aEndTime ); double fStart = (double)aStartTime.Seconds + ((double)aStartTime.Nanosec / 1000000000.0); double fEnd = (double)aEndTime.Seconds + ((double)aEndTime.Nanosec / 1000000000.0); printf( "System latency per call : %g\n" , (( fEnd-fStart )/2.) / ((double)(nLoop)) ); } int main( int argc, char *argv[] ) { sal_Bool bUseNew = ( 3 == argc ); if( argc < 2 ) { printf( "usage : testclient [-r] connectionstring\n" " -r reverse call me test (server calls client)" ); return 0; } OUString sConnectionString; OUString sProtocol; sal_Bool bLatency = sal_False; sal_Bool bReverse = sal_False; parseCommandLine( argv , &sConnectionString , &sProtocol , &bLatency , &bReverse ); { Reference< XMultiServiceFactory > rSMgr = createRegistryServiceFactory( OUString( RTL_CONSTASCII_USTRINGPARAM("client.rdb")) ); Reference < XConnector > rConnector( createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.connection.Connector")), OUString( RTL_CONSTASCII_USTRINGPARAM("connector.uno" SAL_DLLEXTENSION)), rSMgr ), UNO_QUERY ); try { Reference < XConnection > rConnection = rConnector->connect( sConnectionString ); printf( "%s\n" , OUStringToOString( rConnection->getDescription(), RTL_TEXTENCODING_ASCII_US ).pData->buffer ); if( bLatency ) { testLatency( rConnection , sal_False ); testLatency( rConnection , sal_True ); } else { // just ensure that it is registered createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.Bridge.iiop")), OUString( RTL_CONSTASCII_USTRINGPARAM("remotebridge.uno" SAL_DLLEXTENSION)), rSMgr ); Reference < XBridgeFactory > rFactory( createComponent( OUString( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.bridge.BridgeFactory")), OUString( RTL_CONSTASCII_USTRINGPARAM("bridgefac.uno" SAL_DLLEXTENSION)), rSMgr ), UNO_QUERY ); if( rFactory.is() ) { Reference < XBridge > rBridge = rFactory->createBridge( OUString( RTL_CONSTASCII_USTRINGPARAM("bla blub")), sProtocol, rConnection, new OInstanceProvider ); { // test the factory Reference < XBridge > rBridge2 = rFactory->getBridge( OUString( RTL_CONSTASCII_USTRINGPARAM("bla blub")) ); assert( rBridge2.is() ); assert( rBridge2->getDescription() == rBridge->getDescription( ) ); assert( rBridge2->getName() == rBridge->getName() ); assert( rBridge2 == rBridge ); } Reference < XInterface > rInitialObject = rBridge->getInstance( OUString( RTL_CONSTASCII_USTRINGPARAM("bridges-testobject")) ); if( rInitialObject.is() ) { printf( "got the remote object\n" ); if( ! bReverse ) { // Reference < XComponent > rPerfTest( rInitialObject , UNO_QUERY ); // if( rPerfTest.is() ) // { // // doPerformanceTest( rPerfTest ); // } // else // { testRemote( rInitialObject ); // } } } // Reference < XComponent > rComp( rBridge , UNO_QUERY ); // rComp->dispose(); rInitialObject = Reference < XInterface > (); printf( "Waiting...\n" ); TimeValue value={bReverse ?1000 :2,0}; osl_waitThread( &value ); printf( "Closing...\n" ); } Reference < XBridge > rBridge = rFactory->getBridge( OUString( RTL_CONSTASCII_USTRINGPARAM("bla blub")) ); // assert( ! rBridge.is() ); } } catch( DisposedException & e ) { OString o = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); printf( "A remote object reference became invalid\n%s\n" , o.pData->buffer ); } catch( Exception &e ) { OString o = OUStringToOString( e.Message , RTL_TEXTENCODING_ASCII_US ); printf( "Login failed, got an Exception !\n%s\n" , o.pData->buffer ); } Reference < XComponent > rComp( rSMgr , UNO_QUERY ); rComp->dispose(); } printf( "Closed\n" ); return 0; } <|endoftext|>
<commit_before><commit_msg>further adventures in memory management<commit_after><|endoftext|>
<commit_before><commit_msg>Log backing_store regardless of previous setting<commit_after><|endoftext|>
<commit_before>void Make_Init(char *file){ TFile * rootf = new TFile(file,"READ"); if(!rootf->IsOpen()){ cerr<<"no file: "<<file<<endl; return; } AliTPCParam* par = (AliTPCParam*)rootf->Get("75x40_100x60"); if(!par){ cerr<<"no AliTPCParam 75x40_100x60 in file: "<<file<<endl; return; } int fNTimeBins = 446; int fNRowLow = par->GetNRowLow(); int fNRowUp = par->GetNRowUp(); int fNRow= fNRowLow+ fNRowUp; int fNSectorLow = par->GetNInnerSector(); int fNSectorUp = par->GetNOuterSector(); int fNSector = fNSectorLow + fNSectorUp; int fNSlice = fNSectorLow; FILE *f = fopen("Init.cxx","w"); fprintf(f,"void AliL3Transform::Init(){\n"); fprintf(f," //sector:\n"); fprintf(f," fNTimeBins = %d;\n",fNTimeBins); fprintf(f," fNRowLow = %d;\n",fNRowLow); fprintf(f," fNRowUp = %d;\n",fNRowUp); fprintf(f," fNSectorLow = %d;\n",fNSectorLow); fprintf(f," fNSectorUp = %d;\n",fNSectorUp); fprintf(f," fNSector = %d;\n",fNSector); fprintf(f," fPadPitchWidthLow = %f;\n",par->GetPadPitchWidth(0)); fprintf(f," fPadPitchWidthUp = %f;\n",par->GetPadPitchWidth(fNSectorLow)); fprintf(f," fZWidth = %.20f;\n",par->GetZWidth()); fprintf(f," fZSigma = %.20f;\n",par->GetZSigma()); fprintf(f,"\n //slices:\n"); fprintf(f," fNSlice = %d;\n",fNSectorLow); fprintf(f," fNRow = %d;\n",fNRow); // fprintf(f," fPi = 3.14159265358979323846;\n"); fprintf(f," fPi = %.15f;\n",TMath::Pi()); fprintf(f," for(Int_t i=0;i<36;i++){\n"); fprintf(f," fCos[i] = cos(fPi/9*i);\n"); fprintf(f," fSin[i] = sin(fPi/9*i);\n"); fprintf(f," }\n\n"); for(Int_t i=0;i<fNRow;i++){ int sec,row; if( i < fNRowLow){sec =0;row =i;} else{sec = fNSectorLow;row =i-fNRowLow;} fprintf(f," fX[%d] = %3.15f;\n",i,par->GetPadRowRadii(sec,row)); } for(Int_t i=0;i<fNRow;i++){ int sec,row; if( i < fNRowLow){sec =0;row =i;} else{sec = fNSectorLow;row =i-fNRowLow;} fprintf(f," fNPads[%d] = %d;\n",i,par->GetNPads(sec,row)); } fprintf(f,"}\n"); fclose(f); } <commit_msg>also checks timebins<commit_after>void Make_Init(char *file){ TFile * rootf = new TFile(file,"READ"); if(!rootf->IsOpen()){ cerr<<"no file: "<<file<<endl; return; } AliTPCParam* par = (AliTPCParam*)rootf->Get("75x40_100x60"); if(!par){ cerr<<"no AliTPCParam 75x40_100x60 in file: "<<file<<endl; return; } int fNTimeBins = par->GetMaxTBin(); int fNRowLow = par->GetNRowLow(); int fNRowUp = par->GetNRowUp(); int fNRow= fNRowLow+ fNRowUp; int fNSectorLow = par->GetNInnerSector(); int fNSectorUp = par->GetNOuterSector(); int fNSector = fNSectorLow + fNSectorUp; int fNSlice = fNSectorLow; FILE *f = fopen("Init.cxx","w"); fprintf(f,"void AliL3Transform::Init(){\n"); fprintf(f," //sector:\n"); fprintf(f," fNTimeBins = %d;\n",fNTimeBins); fprintf(f," fNRowLow = %d;\n",fNRowLow); fprintf(f," fNRowUp = %d;\n",fNRowUp); fprintf(f," fNSectorLow = %d;\n",fNSectorLow); fprintf(f," fNSectorUp = %d;\n",fNSectorUp); fprintf(f," fNSector = %d;\n",fNSector); fprintf(f," fPadPitchWidthLow = %f;\n",par->GetPadPitchWidth(0)); fprintf(f," fPadPitchWidthUp = %f;\n",par->GetPadPitchWidth(fNSectorLow)); fprintf(f," fZWidth = %.20f;\n",par->GetZWidth()); fprintf(f," fZSigma = %.20f;\n",par->GetZSigma()); fprintf(f,"\n //slices:\n"); fprintf(f," fNSlice = %d;\n",fNSectorLow); fprintf(f," fNRow = %d;\n",fNRow); // fprintf(f," fPi = 3.14159265358979323846;\n"); fprintf(f," fPi = %.15f;\n",TMath::Pi()); fprintf(f," for(Int_t i=0;i<36;i++){\n"); fprintf(f," fCos[i] = cos(fPi/9*i);\n"); fprintf(f," fSin[i] = sin(fPi/9*i);\n"); fprintf(f," }\n\n"); for(Int_t i=0;i<fNRow;i++){ int sec,row; if( i < fNRowLow){sec =0;row =i;} else{sec = fNSectorLow;row =i-fNRowLow;} fprintf(f," fX[%d] = %3.15f;\n",i,par->GetPadRowRadii(sec,row)); } for(Int_t i=0;i<fNRow;i++){ int sec,row; if( i < fNRowLow){sec =0;row =i;} else{sec = fNSectorLow;row =i-fNRowLow;} fprintf(f," fNPads[%d] = %d;\n",i,par->GetNPads(sec,row)); } fprintf(f,"}\n"); fclose(f); } <|endoftext|>
<commit_before>/*! * \file Partie.hpp * \brief Fichier contenant les entêtes de la classe Partie * \author François Hallereau * \author Sébastien Vallée * \date 12.2014 */ #ifndef PARTIE_HPP #define PARTIE_HPP #include <string> // pour le type std::string #include <vector> //for std::vector #include <map> //inclusion des classes independantes necessaires #include "Observer.hpp" #include "../Jeux/Cite/Observable.hpp" #include "../ClassesUtiles/Aleatoire.cpp" #include "../ClassesUtiles/listeChainee.cpp" #include "../Jeux/Quartiers/Quartier.hpp" //inclusion des classes dependantes #include "../Jeux/Cite/Cite.hpp" #include "Pioche.hpp" //inclusion des classes interdependantes class Joueur; class Personnage; #include "AssociationPersonnageJoueur.hpp" //-------------------------------------------------- /*! * \class Partie * \brief Classe gérant une partie */ class Partie : public Observer{ private : //attributs int limiteTailleVille_; //!< limite de quartier mettant fin à la partie bool villeComplete_; //!< vrai lorsqu'un joueur a au moins limiteTailleVille quartier Pioche * pioche_; //!< pioche de la partie AssociationPersonnageJoueur * roles_; //!< role de chaque joueur //méthodes privées void entreDeuxTours(); void choixDesPersonnages(); void lancementDuTour(); void update(int taille); bool finDuJeu();/ void proclamerLeVainqueur(); public : Partie(Pioche *pioche, int tailleVille); ~Partie(); void nouveauJoueur(Joueur *joueur); void nouveauPersonnage(Personnage *personnage); void debuterLeJeu(); void decompteDesPoints(map<string,int> *tmp); void associer(Personnage *p, Joueur *j); vector<Quartier*> piocher(int nombre); int prendrePiece(int nombre); void modifierOrdreJoueur(Joueur *j); void modifierOrdreJoueur(Joueur *j, Joueur *jj); Joueur* retrouverJ(Personnage *p); Personnage* retrouverP(Joueur *j); int nbJoueurs(); int nbPersonnages(); vector<Joueur*> recupererListeJoueurs(); }; //inclusion des classes dépendants de partie #include "../Joueurs/Comportement.hpp" #include "../Joueurs/IA/Comportements/ComportementIA.hpp" #include "../Jeux/Personnages/Personnage.hpp" #include "../Joueurs/Joueur.hpp" #include "../Joueurs/IA/IA.hpp" #include "../Joueurs/IA/Comportements/ComportementIA.cpp" #include "AssociationPersonnageJoueur.cpp" /******************************************************************************/ #include "Partie.cpp" #endif // PARTIE_HPP <commit_msg>improve doc, DonneePartie full doc<commit_after>/*! * \file Partie.hpp * \brief Fichier contenant les entêtes de la classe Partie * \author François Hallereau * \author Sébastien Vallée * \date 12.2014 */ #ifndef PARTIE_HPP #define PARTIE_HPP #include <string> // pour le type std::string #include <vector> //for std::vector #include <map> //inclusion des classes independantes necessaires #include "Observer.hpp" #include "../Jeux/Cite/Observable.hpp" #include "../ClassesUtiles/Aleatoire.cpp" #include "../ClassesUtiles/listeChainee.cpp" #include "../Jeux/Quartiers/Quartier.hpp" //inclusion des classes dependantes #include "../Jeux/Cite/Cite.hpp" #include "Pioche.hpp" //inclusion des classes interdependantes class Joueur; class Personnage; #include "AssociationPersonnageJoueur.hpp" //-------------------------------------------------- /*! * \class Partie * \brief Classe gérant une partie */ class Partie : public Observer{ private : //attributs int limiteTailleVille_; //!< limite de quartier mettant fin à la partie bool villeComplete_; //!< vrai lorsqu'un joueur a au moins #limiteTailleVille_ quartier Pioche * pioche_; //!< pioche de la partie AssociationPersonnageJoueur * roles_; //!< role de chaque joueur //méthodes privées void entreDeuxTours(); void choixDesPersonnages(); void lancementDuTour(); void update(int taille); bool finDuJeu();/ void proclamerLeVainqueur(); public : Partie(Pioche *pioche, int tailleVille); ~Partie(); void nouveauJoueur(Joueur *joueur); void nouveauPersonnage(Personnage *personnage); void debuterLeJeu(); void decompteDesPoints(map<string,int> *tmp); void associer(Personnage *p, Joueur *j); vector<Quartier*> piocher(int nombre); int prendrePiece(int nombre); void modifierOrdreJoueur(Joueur *j); void modifierOrdreJoueur(Joueur *j, Joueur *jj); Joueur* retrouverJ(Personnage *p); Personnage* retrouverP(Joueur *j); int nbJoueurs(); int nbPersonnages(); vector<Joueur*> recupererListeJoueurs(); }; //inclusion des classes dépendants de partie #include "../Joueurs/Comportement.hpp" #include "../Joueurs/IA/Comportements/ComportementIA.hpp" #include "../Jeux/Personnages/Personnage.hpp" #include "../Joueurs/Joueur.hpp" #include "../Joueurs/IA/IA.hpp" #include "../Joueurs/IA/Comportements/ComportementIA.cpp" #include "AssociationPersonnageJoueur.cpp" /******************************************************************************/ #include "Partie.cpp" #endif // PARTIE_HPP <|endoftext|>
<commit_before><commit_msg>Removed unnecessary RocksDB options<commit_after><|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //_________________________________________________________________________ // PHOS digit: Id // energy // 3 identifiers for the primary particle(s) at the origine of the digit // The digits are made in FinishEvent() by summing all the hits in a single PHOS crystal or PPSD gas cell // //*-- Author: Laurent Aphecetche & Yves Schutz (SUBATECH) & Dmitri Peressounko (RRC KI & SUBATECH) // --- ROOT system --- // --- Standard library --- // --- AliRoot header files --- #include "AliPHOSDigit.h" ClassImp(AliPHOSDigit) //____________________________________________________________________________ AliPHOSDigit::AliPHOSDigit() { // default ctor fIndexInList = -1 ; fNprimary = 0 ; fNMaxPrimary = 5 ; } //____________________________________________________________________________ AliPHOSDigit::AliPHOSDigit(Int_t primary, Int_t id, Int_t digEnergy, Float_t time, Int_t index) { // ctor with all data fNMaxPrimary = 5 ; fAmp = digEnergy ; fTime = time ; fId = id ; fIndexInList = index ; if( primary != -1){ fNprimary = 1 ; fPrimary[0] = primary ; } else{ //If the contribution of this primary smaller than fDigitThreshold (AliPHOSv1) fNprimary = 0 ; fPrimary[0] = -1 ; } Int_t i ; for ( i = 1; i < fNMaxPrimary ; i++) fPrimary[i] = -1 ; } //____________________________________________________________________________ AliPHOSDigit::AliPHOSDigit(const AliPHOSDigit & digit) { // copy ctor fNMaxPrimary = digit.fNMaxPrimary ; Int_t i ; for ( i = 0; i < fNMaxPrimary ; i++) fPrimary[i] = digit.fPrimary[i] ; fAmp = digit.fAmp ; fTime = digit.fTime ; fId = digit.fId; fIndexInList = digit.fIndexInList ; fNprimary = digit.fNprimary ; } //____________________________________________________________________________ AliPHOSDigit::~AliPHOSDigit() { // Delete array of primiries if any } //____________________________________________________________________________ Int_t AliPHOSDigit::Compare(const TObject * obj) const { // Compares two digits with respect to its Id // to sort according increasing Id Int_t rv ; AliPHOSDigit * digit = (AliPHOSDigit *)obj ; Int_t iddiff = fId - digit->GetId() ; if ( iddiff > 0 ) rv = 1 ; else if ( iddiff < 0 ) rv = -1 ; else rv = 0 ; return rv ; } //____________________________________________________________________________ Int_t AliPHOSDigit::GetPrimary(Int_t index) const { // retrieves the primary particle number given its index in the list Int_t rv = -1 ; if ( index <= fNprimary && index > 0){ rv = fPrimary[index-1] ; } return rv ; } //____________________________________________________________________________ void AliPHOSDigit::Print(Option_t *option) const { printf("PHOS digit: Amp=%d, Id=%d\n",fAmp,fId); } //____________________________________________________________________________ void AliPHOSDigit::ShiftPrimary(Int_t shift) { //shifts primary number to BIG offset, to separate primary in different TreeK Int_t index ; for(index = 0; index <fNprimary; index ++ ){ fPrimary[index] = fPrimary[index]+ shift ; } } //____________________________________________________________________________ Bool_t AliPHOSDigit::operator==(AliPHOSDigit const & digit) const { // Two digits are equal if they have the same Id if ( fId == digit.fId ) return kTRUE ; else return kFALSE ; } //____________________________________________________________________________ AliPHOSDigit& AliPHOSDigit::operator+(AliPHOSDigit const & digit) { // Adds the amplitude of digits and completes the list of primary particles // if amplitude is larger than Int_t toAdd = fNprimary ; if(digit.fNprimary>0){ if(fAmp < digit.fAmp){//most energetic primary in digit => first primaries in list from second digit for (Int_t index = 0 ; index < digit.fNprimary ; index++){ for (Int_t old = 0 ; old < fNprimary ; old++) { //already have this primary? if(fPrimary[old] == (digit.fPrimary)[index]){ fPrimary[old] = -1 ; //removed toAdd-- ; break ; } } } if(digit.fNprimary+toAdd >fNMaxPrimary) //Do not change primary list Error("Operator +", "Increase NMaxPrimary") ; else{ for(Int_t index = fNprimary-1 ; index >=0 ; index--){ //move old primaries if(fPrimary[index]>-1){ fPrimary[fNprimary+toAdd]=fPrimary[index] ; toAdd-- ; } } //copy new primaries for(Int_t index = 0; index < digit.fNprimary ; index++){ fPrimary[index] = (digit.fPrimary)[index] ; } } } else{ //add new primaries to the end for(Int_t index = 0 ; index < digit.fNprimary ; index++){ Bool_t deja = kTRUE ; for(Int_t old = 0 ; old < fNprimary; old++) { //already have this primary? if(fPrimary[old] == (digit.fPrimary)[index]){ deja = kFALSE; break ; } } if(deja){ fPrimary[fNprimary] = (digit.fPrimary)[index] ; fNprimary++ ; if(fNprimary>fNMaxPrimary) { Error("Operator +", "Increase NMaxPrimary") ; break ; } } } } } fAmp += digit.fAmp ; if(fTime > digit.fTime) fTime = digit.fTime ; return *this ; } //____________________________________________________________________________ ostream& operator << ( ostream& out , const AliPHOSDigit & digit) { // Prints the data of the digit // out << "ID " << digit.fId << " Energy = " << digit.fAmp << " Time = " << digit.fTime << endl ; // Int_t i ; // for(i=0;i<digit.fNprimary;i++) // out << "Primary " << i+1 << " = " << digit.fPrimary[i] << endl ; // out << "Position in list = " << digit.fIndexInList << endl ; digit.Warning("operator <<", "Implement differently") ; return out ; } <commit_msg>fNPrimaries now increased if adding<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //_________________________________________________________________________ // PHOS digit: Id // energy // 3 identifiers for the primary particle(s) at the origine of the digit // The digits are made in FinishEvent() by summing all the hits in a single PHOS crystal or PPSD gas cell // //*-- Author: Laurent Aphecetche & Yves Schutz (SUBATECH) & Dmitri Peressounko (RRC KI & SUBATECH) // --- ROOT system --- // --- Standard library --- // --- AliRoot header files --- #include "AliPHOSDigit.h" ClassImp(AliPHOSDigit) //____________________________________________________________________________ AliPHOSDigit::AliPHOSDigit() { // default ctor fIndexInList = -1 ; fNprimary = 0 ; fNMaxPrimary = 5 ; } //____________________________________________________________________________ AliPHOSDigit::AliPHOSDigit(Int_t primary, Int_t id, Int_t digEnergy, Float_t time, Int_t index) { // ctor with all data fNMaxPrimary = 5 ; fAmp = digEnergy ; fTime = time ; fId = id ; fIndexInList = index ; if( primary != -1){ fNprimary = 1 ; fPrimary[0] = primary ; } else{ //If the contribution of this primary smaller than fDigitThreshold (AliPHOSv1) fNprimary = 0 ; fPrimary[0] = -1 ; } Int_t i ; for ( i = 1; i < fNMaxPrimary ; i++) fPrimary[i] = -1 ; } //____________________________________________________________________________ AliPHOSDigit::AliPHOSDigit(const AliPHOSDigit & digit) { // copy ctor fNMaxPrimary = digit.fNMaxPrimary ; Int_t i ; for ( i = 0; i < fNMaxPrimary ; i++) fPrimary[i] = digit.fPrimary[i] ; fAmp = digit.fAmp ; fTime = digit.fTime ; fId = digit.fId; fIndexInList = digit.fIndexInList ; fNprimary = digit.fNprimary ; } //____________________________________________________________________________ AliPHOSDigit::~AliPHOSDigit() { // Delete array of primiries if any } //____________________________________________________________________________ Int_t AliPHOSDigit::Compare(const TObject * obj) const { // Compares two digits with respect to its Id // to sort according increasing Id Int_t rv ; AliPHOSDigit * digit = (AliPHOSDigit *)obj ; Int_t iddiff = fId - digit->GetId() ; if ( iddiff > 0 ) rv = 1 ; else if ( iddiff < 0 ) rv = -1 ; else rv = 0 ; return rv ; } //____________________________________________________________________________ Int_t AliPHOSDigit::GetPrimary(Int_t index) const { // retrieves the primary particle number given its index in the list Int_t rv = -1 ; if ( index <= fNprimary && index > 0){ rv = fPrimary[index-1] ; } return rv ; } //____________________________________________________________________________ void AliPHOSDigit::Print(Option_t *option) const { printf("PHOS digit: Amp=%d, Id=%d\n",fAmp,fId); } //____________________________________________________________________________ void AliPHOSDigit::ShiftPrimary(Int_t shift) { //shifts primary number to BIG offset, to separate primary in different TreeK Int_t index ; for(index = 0; index <fNprimary; index ++ ){ fPrimary[index] = fPrimary[index]+ shift ; } } //____________________________________________________________________________ Bool_t AliPHOSDigit::operator==(AliPHOSDigit const & digit) const { // Two digits are equal if they have the same Id if ( fId == digit.fId ) return kTRUE ; else return kFALSE ; } //____________________________________________________________________________ AliPHOSDigit& AliPHOSDigit::operator+(AliPHOSDigit const & digit) { // Adds the amplitude of digits and completes the list of primary particles // if amplitude is larger than Int_t toAdd = fNprimary ; if(digit.fNprimary>0){ if(fAmp < digit.fAmp){//most energetic primary in second digit => first primaries in list from second digit for (Int_t index = 0 ; index < digit.fNprimary ; index++){ for (Int_t old = 0 ; old < fNprimary ; old++) { //already have this primary? if(fPrimary[old] == (digit.fPrimary)[index]){ fPrimary[old] = -1 ; //removed toAdd-- ; break ; } } } Int_t nNewPrimaries = digit.fNprimary+toAdd ; if(nNewPrimaries >fNMaxPrimary) //Do not change primary list Error("Operator +", "Increase NMaxPrimary") ; else{ for(Int_t index = fNprimary-1 ; index >=0 ; index--){ //move old primaries if(fPrimary[index]>-1){ fPrimary[fNprimary+toAdd]=fPrimary[index] ; toAdd-- ; } } //copy new primaries for(Int_t index = 0; index < digit.fNprimary ; index++){ fPrimary[index] = (digit.fPrimary)[index] ; } fNprimary = nNewPrimaries ; } } else{ //add new primaries to the end for(Int_t index = 0 ; index < digit.fNprimary ; index++){ Bool_t deja = kTRUE ; for(Int_t old = 0 ; old < fNprimary; old++) { //already have this primary? if(fPrimary[old] == (digit.fPrimary)[index]){ deja = kFALSE; break ; } } if(deja){ fPrimary[fNprimary] = (digit.fPrimary)[index] ; fNprimary++ ; if(fNprimary>fNMaxPrimary) { Error("Operator +", "Increase NMaxPrimary") ; break ; } } } } } fAmp += digit.fAmp ; if(fTime > digit.fTime) fTime = digit.fTime ; return *this ; } //____________________________________________________________________________ ostream& operator << ( ostream& out , const AliPHOSDigit & digit) { // Prints the data of the digit // out << "ID " << digit.fId << " Energy = " << digit.fAmp << " Time = " << digit.fTime << endl ; // Int_t i ; // for(i=0;i<digit.fNprimary;i++) // out << "Primary " << i+1 << " = " << digit.fPrimary[i] << endl ; // out << "Position in list = " << digit.fIndexInList << endl ; digit.Warning("operator <<", "Implement differently") ; return out ; } <|endoftext|>
<commit_before>/* The MIT License * * Copyright (c) 2010 OTClient, https://github.com/edubart/otclient * * 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 "uibutton.h" void UIButton::onInputEvent(const InputEvent& event) { if(event.type == EV_MOUSE_LDOWN && getRect().contains(event.mousePos)) { m_state = UI::ButtonDown; } else if(event.type == EV_MOUSE_LUP && m_state == UI::ButtonDown) { m_state = UI::ButtonUp; if(getRect().contains(event.mousePos)) { if(m_buttonClickCallback) m_buttonClickCallback(); } } } <commit_msg>all callbacks must go through dispatcher<commit_after>/* The MIT License * * Copyright (c) 2010 OTClient, https://github.com/edubart/otclient * * 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 "uibutton.h" #include "core/dispatcher.h" void UIButton::onInputEvent(const InputEvent& event) { if(event.type == EV_MOUSE_LDOWN && getRect().contains(event.mousePos)) { m_state = UI::ButtonDown; } else if(event.type == EV_MOUSE_LUP && m_state == UI::ButtonDown) { m_state = UI::ButtonUp; if(getRect().contains(event.mousePos)) { if(m_buttonClickCallback) { g_dispatcher.addTask(m_buttonClickCallback); } } } } <|endoftext|>
<commit_before>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * * This file is part of dlvhex. * * dlvhex 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. * * dlvhex 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 dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file EvalHeuristicGreedy.cpp * @author Christoph Redl * * @brief Evaluation heuristic that groups components in as few units as possible. * This maximizes the effect of external behavior learning. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include "dlvhex2/EvalHeuristicGreedy.h" #include "dlvhex2/EvalHeuristicShared.h" #include "dlvhex2/Logger.h" #include "dlvhex2/ProgramCtx.h" #include "dlvhex2/AttributeGraph.h" #include <boost/unordered_map.hpp> #include <boost/property_map/property_map.hpp> #include <boost/graph/breadth_first_search.hpp> #include <boost/graph/visitors.hpp> #include <boost/graph/depth_first_search.hpp> #include <boost/graph/properties.hpp> #include <boost/scoped_ptr.hpp> //#include <fstream> DLVHEX_NAMESPACE_BEGIN bool EvalHeuristicGreedy::mergeComponents(ProgramCtx& ctx, const ComponentGraph::ComponentInfo& ci1, const ComponentGraph::ComponentInfo& ci2, bool negativeExternalDependency) const{ if (ctx.config.getOption("LiberalSafety") && ctx.config.getOption("IncludeAuxInputInAuxiliaries")){ // here we could always merge // however, we do this only if there are no negative external dependencies between the components (as this comes at exponential cost) return !negativeExternalDependency; }else{ // never merge components with outer external atoms (they could become inner ones) if (!ci1.outerEatoms.empty() || !ci2.outerEatoms.empty()) return false; // if both components have a fixed domain we can safely merge them // (both can be solved by guess&check mg) if (ci1.fixedDomain && ci2.fixedDomain) return true; // if both components are solved by wellfounded mg and none of them has outer external atoms, then we merge them // (the resulting component will still be wellfounded and an outer external atom can not become an inner one) if (!ci1.innerEatomsNonmonotonic && !ci1.negativeDependencyBetweenRules && !ci1.disjunctiveHeads && ci1.innerEatoms.size() > 0 && ci1.outerEatoms.size() == 0 && !ci2.innerEatomsNonmonotonic && !ci2.negativeDependencyBetweenRules && !ci2.disjunctiveHeads && ci2.innerEatoms.size() > 0 && ci2.outerEatoms.size() == 0) return true; // otherwise: don't merge them return false; } } EvalHeuristicGreedy::EvalHeuristicGreedy(): Base() { } EvalHeuristicGreedy::~EvalHeuristicGreedy() { } typedef ComponentGraph::Component Component; typedef ComponentGraph::ComponentIterator ComponentIterator; typedef std::vector<Component> ComponentContainer; typedef ComponentGraph::ComponentSet ComponentSet; namespace internalgreedy { // collect all components on the way struct DFSVisitor: public boost::default_dfs_visitor { const ComponentGraph& cg; ComponentSet& comps; DFSVisitor(const ComponentGraph& cg, ComponentSet& comps): boost::default_dfs_visitor(), cg(cg), comps(comps) {} DFSVisitor(const DFSVisitor& other): boost::default_dfs_visitor(), cg(other.cg), comps(other.comps) {} template<typename GraphT> void discover_vertex(Component comp, const GraphT&) { comps.insert(comp); } }; template<typename ComponentGraph, typename Set> void transitivePredecessorComponents(const ComponentGraph& compgraph, Component from, Set& preds) { // we need a hash map, as component graph is no graph with vecS-storage // typedef boost::unordered_map<Component, boost::default_color_type> CompColorHashMap; typedef boost::associative_property_map<CompColorHashMap> CompColorMap; CompColorHashMap ccWhiteHashMap; // fill white hash map ComponentIterator cit, cit_end; for(boost::tie(cit, cit_end) = compgraph.getComponents(); cit != cit_end; ++cit) { //boost::put(ccWhiteHashMap, *cit, boost::white_color); ccWhiteHashMap[*cit] = boost::white_color; } CompColorHashMap ccHashMap(ccWhiteHashMap); // // do DFS // DFSVisitor dfs_vis(compgraph, preds); //LOG("doing dfs visit for root " << *itr); boost::depth_first_visit( compgraph.getInternalGraph(), from, dfs_vis, CompColorMap(ccHashMap)); DBGLOG(DBG,"predecessors of " << from << " are " << printrange(preds)); } } // required for some GCCs for DFSVisitor CopyConstructible Concept Check using namespace internalgreedy; void EvalHeuristicGreedy::build(EvalGraphBuilder& builder) { ProgramCtx& ctx = builder.getProgramCtx(); ComponentGraph& compgraph = builder.getComponentGraph(); #if 0 { std::string fnamev = "my_initial_ClonedCompGraphVerbose.dot"; std::ofstream filev(fnamev.c_str()); compgraph.writeGraphViz(filev, true); } #endif bool didSomething; do { didSomething = false; // // forall external components e: // merge with all rules that // * depend on e // * do not contain external atoms // * do not depend on something e does not (transitively) depend on // { ComponentIterator cit; for(cit = compgraph.getComponents().first; // do not use boost::tie here! the container is modified in the loop! cit != compgraph.getComponents().second; ++cit) { Component comp = *cit; if( compgraph.propsOf(comp).outerEatoms.empty() )// || !compgraph.propsOf(comp).innerRules.empty() || !compgraph.propsOf(comp).innerConstraints.empty() ) continue; DBGLOG(DBG,"checking component " << comp); LOG(ANALYZE,"checking whether to collapse external component " << comp << " with successors"); // get predecessors ComponentSet preds; transitivePredecessorComponents(compgraph, comp, preds); // get successors ComponentSet collapse; bool addedToCollapse; // do this as long as we find new ones // if we do not do this loop, we might miss something // as PredecessorIterator not necessarily honours topological order // (TODO this could be made more efficient) do { addedToCollapse = false; ComponentGraph::SuccessorIterator sit, sit_end; for(boost::tie(sit, sit_end) = compgraph.getProvides(comp); sit != sit_end; ++sit) { Component succ = compgraph.sourceOf(*sit); // skip successors with eatoms if( !compgraph.propsOf(succ).outerEatoms.empty() ) continue; // do not check found stuff twice if( collapse.find(succ) != collapse.end() ) continue; DBGLOG(DBG,"found successor " << succ); ComponentGraph::PredecessorIterator pit, pit_end; bool good = true; for(boost::tie(pit, pit_end) = compgraph.getDependencies(succ); pit != pit_end; ++pit) { Component dependson = compgraph.targetOf(*pit); if( preds.find(dependson) == preds.end() ) { LOG(DBG,"successor bad as it depends on other node " << dependson); good = false; break; } } if( good ) { // collapse with this collapse.insert(succ); preds.insert(succ); addedToCollapse = true; } } } while(addedToCollapse); // collapse if not nonempty if( !collapse.empty() ) { collapse.insert(comp); Component c = compgraph.collapseComponents(collapse); LOG(ANALYZE,"collapse of " << printrange(collapse) << " yielded new component " << c); // restart loop after collapse cit = compgraph.getComponents().first; didSomething = true; } } } // // forall components c1: // merge with all other components c2 such that no cycle is broken // that is, there must not be a path of length >=2 from c2 to c1 // { ComponentIterator cit = compgraph.getComponents().first; while(cit != compgraph.getComponents().second) { Component comp = *cit; ComponentSet collapse; DBGLOG(DBG,"checking component " << comp); ComponentIterator cit2 = cit; cit2++; while( cit2 != compgraph.getComponents().second ) { Component comp2 = *cit2; DBGLOG(DBG,"checking other component " << comp2); bool breakCycle = false; // check if there is a path of length >=2 from comp2 to comp // that is, there is a path from a predecessor of comp2 to comp ComponentSet preds2; { ComponentGraph::PredecessorIterator pit, pit_end; for(boost::tie(pit, pit_end) = compgraph.getDependencies(comp2); pit != pit_end; ++pit) { preds2.insert(compgraph.targetOf(*pit)); } } BOOST_FOREACH (Component comp2s, preds2){ ComponentSet reachable; transitivePredecessorComponents(compgraph, comp2s, reachable); if (std::find(reachable.begin(), reachable.end(), comp) != reachable.end() && comp2s != comp){ // path of length >=2 DBGLOG(DBG, "do not merge because this would break a cycle"); breakCycle = true; break; } } // check if there is a path of length >=2 from comp to comp2 // that is, there is a path from a predecessor of comp to comp2 ComponentSet preds; { ComponentGraph::PredecessorIterator pit, pit_end; for(boost::tie(pit, pit_end) = compgraph.getDependencies(comp); pit != pit_end; ++pit) { preds.insert(compgraph.targetOf(*pit)); } } BOOST_FOREACH (Component comps, preds){ ComponentSet reachable; transitivePredecessorComponents(compgraph, comps, reachable); if (std::find(reachable.begin(), reachable.end(), comp2) != reachable.end() && comps != comp2){ // path of length >=2 DBGLOG(DBG, "do not merge because this would break a cycle"); breakCycle = true; break; } } std::set<std::pair<ComponentGraph::Component, ComponentGraph::Component> > negdep; std::set<ComponentGraph::Component> nonmonotonicTransitivePredecessor; if (ctx.config.getOption("LiberalSafety") && ctx.config.getOption("IncludeAuxInputInAuxiliaries")){ if (ctx.config.getOption("LiberalSafety") && ctx.config.getOption("IncludeAuxInputInAuxiliaries")){ // check if there is a nonmonotonic external dependency from comp to comp2 BOOST_FOREACH (ComponentGraph::Dependency dep, compgraph.getDependencies()){ const ComponentGraph::DependencyInfo& di = compgraph.getDependencyInfo(dep); if (di.externalNonmonotonicPredicateInput){ // check if the nonmonotonic predicate dependency is eliminated if we consider only necessary external atoms BOOST_FOREACH (ComponentGraph::DependencyInfo::DepEdge de, di.depEdges){ if (de.get<2>().externalNonmonotonicPredicateInput && ctx.attrgraph->isExternalAtomNecessaryForDomainExpansionSafety(de.get<0>())){ // not eliminated negdep.insert(std::pair<ComponentGraph::Component, ComponentGraph::Component>(compgraph.sourceOf(dep), compgraph.targetOf(dep))); nonmonotonicTransitivePredecessor.insert(compgraph.sourceOf(dep)); break; } } } } } } // if this is the case, then do not merge if (!breakCycle){ // we do not want to merge if a component in transitivePredecessorComponents is reachable from exactly one of comp and comp2 bool nd = false; if (ctx.config.getOption("LiberalSafety") && ctx.config.getOption("IncludeAuxInputInAuxiliaries")){ ComponentSet reachable1, reachable2; transitivePredecessorComponents(compgraph, comp, reachable1); transitivePredecessorComponents(compgraph, comp2, reachable2); bool nonmonTrans1 = false; bool nonmonTrans2 = false; BOOST_FOREACH (Component c, reachable1) if (nonmonotonicTransitivePredecessor.find(c) != nonmonotonicTransitivePredecessor.end()) nonmonTrans1 = true; BOOST_FOREACH (Component c, reachable2) if (nonmonotonicTransitivePredecessor.find(c) != nonmonotonicTransitivePredecessor.end()) nonmonTrans2 = true; bool nd = nonmonTrans1 != nonmonTrans2; // bool nd = (negdep.find(std::pair<Component, Component>(comp, comp2)) != negdep.end()) || // (negdep.find(std::pair<Component, Component>(comp2, comp)) != negdep.end()); } if (mergeComponents(ctx, compgraph.propsOf(comp), compgraph.propsOf(comp2), nd)){ if (std::find(collapse.begin(), collapse.end(), comp2) == collapse.end()){ collapse.insert(comp2); // merge only one pair at a time, otherwise this could create cycles which are not detected above: // e.g. C1 C2 --> C3 --> C4 // C1 can be merged with C2 and C1 can be merged with C4, but it can't be merged with both of them because this would create a cycle // This is only detected if we see {C1, C2} (or {C1, C4}) as intermediate result break; } } } cit2++; } if( !collapse.empty() ) { // collapse! (decreases graph size) collapse.insert(comp); assert(collapse.size() > 1); Component c = compgraph.collapseComponents(collapse); LOG(ANALYZE,"collapse of " << printrange(collapse) << " yielded new component " << c); // restart loop after collapse cit = compgraph.getComponents().first; didSomething = true; } else { // advance ++cit; } } } } while(didSomething); // // create eval units using topological sort // ComponentContainer sortedcomps; evalheur::topologicalSortComponents(compgraph.getInternalGraph(), sortedcomps); LOG(ANALYZE,"now creating evaluation units from components " << printrange(sortedcomps)); #if 0 { std::string fnamev = "my_ClonedCompGraphVerbose.dot"; std::ofstream filev(fnamev.c_str()); compgraph.writeGraphViz(filev, true); } #endif for(ComponentContainer::const_iterator it = sortedcomps.begin(); it != sortedcomps.end(); ++it) { // just create a unit from each component (we collapsed above) std::list<Component> comps; comps.push_back(*it); std::list<Component> ccomps; EvalGraphBuilder::EvalUnit u = builder.createEvalUnit(comps, ccomps); LOG(ANALYZE,"component " << *it << " became eval unit " << u); } } DLVHEX_NAMESPACE_END // Local Variables: // mode: C++ // End: <commit_msg>fix a bug in greedy heuristics<commit_after>/* dlvhex -- Answer-Set Programming with external interfaces. * Copyright (C) 2005, 2006, 2007 Roman Schindlauer * Copyright (C) 2006, 2007, 2008, 2009, 2010 Thomas Krennwallner * Copyright (C) 2009, 2010 Peter Schüller * * This file is part of dlvhex. * * dlvhex 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. * * dlvhex 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 dlvhex; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA. */ /** * @file EvalHeuristicGreedy.cpp * @author Christoph Redl * * @brief Evaluation heuristic that groups components in as few units as possible. * This maximizes the effect of external behavior learning. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif // HAVE_CONFIG_H #include "dlvhex2/EvalHeuristicGreedy.h" #include "dlvhex2/EvalHeuristicShared.h" #include "dlvhex2/Logger.h" #include "dlvhex2/ProgramCtx.h" #include "dlvhex2/AttributeGraph.h" #include <boost/unordered_map.hpp> #include <boost/property_map/property_map.hpp> #include <boost/graph/breadth_first_search.hpp> #include <boost/graph/visitors.hpp> #include <boost/graph/depth_first_search.hpp> #include <boost/graph/properties.hpp> #include <boost/scoped_ptr.hpp> //#include <fstream> DLVHEX_NAMESPACE_BEGIN bool EvalHeuristicGreedy::mergeComponents(ProgramCtx& ctx, const ComponentGraph::ComponentInfo& ci1, const ComponentGraph::ComponentInfo& ci2, bool negativeExternalDependency) const{ if (ctx.config.getOption("LiberalSafety") && ctx.config.getOption("IncludeAuxInputInAuxiliaries")){ // here we could always merge // however, we do this only if there are no negative external dependencies between the components (as this comes at exponential cost) return !negativeExternalDependency; }else{ // never merge components with outer external atoms (they could become inner ones) if (!ci1.outerEatoms.empty() || !ci2.outerEatoms.empty()) return false; // if both components have a fixed domain we can safely merge them // (both can be solved by guess&check mg) if (ci1.fixedDomain && ci2.fixedDomain) return true; // if both components are solved by wellfounded mg and none of them has outer external atoms, then we merge them // (the resulting component will still be wellfounded and an outer external atom can not become an inner one) if (!ci1.innerEatomsNonmonotonic && !ci1.negativeDependencyBetweenRules && !ci1.disjunctiveHeads && ci1.innerEatoms.size() > 0 && ci1.outerEatoms.size() == 0 && !ci2.innerEatomsNonmonotonic && !ci2.negativeDependencyBetweenRules && !ci2.disjunctiveHeads && ci2.innerEatoms.size() > 0 && ci2.outerEatoms.size() == 0) return true; // otherwise: don't merge them return false; } } EvalHeuristicGreedy::EvalHeuristicGreedy(): Base() { } EvalHeuristicGreedy::~EvalHeuristicGreedy() { } typedef ComponentGraph::Component Component; typedef ComponentGraph::ComponentIterator ComponentIterator; typedef std::vector<Component> ComponentContainer; typedef ComponentGraph::ComponentSet ComponentSet; namespace internalgreedy { // collect all components on the way struct DFSVisitor: public boost::default_dfs_visitor { const ComponentGraph& cg; ComponentSet& comps; DFSVisitor(const ComponentGraph& cg, ComponentSet& comps): boost::default_dfs_visitor(), cg(cg), comps(comps) {} DFSVisitor(const DFSVisitor& other): boost::default_dfs_visitor(), cg(other.cg), comps(other.comps) {} template<typename GraphT> void discover_vertex(Component comp, const GraphT&) { comps.insert(comp); } }; template<typename ComponentGraph, typename Set> void transitivePredecessorComponents(const ComponentGraph& compgraph, Component from, Set& preds) { // we need a hash map, as component graph is no graph with vecS-storage // typedef boost::unordered_map<Component, boost::default_color_type> CompColorHashMap; typedef boost::associative_property_map<CompColorHashMap> CompColorMap; CompColorHashMap ccWhiteHashMap; // fill white hash map ComponentIterator cit, cit_end; for(boost::tie(cit, cit_end) = compgraph.getComponents(); cit != cit_end; ++cit) { //boost::put(ccWhiteHashMap, *cit, boost::white_color); ccWhiteHashMap[*cit] = boost::white_color; } CompColorHashMap ccHashMap(ccWhiteHashMap); // // do DFS // DFSVisitor dfs_vis(compgraph, preds); //LOG("doing dfs visit for root " << *itr); boost::depth_first_visit( compgraph.getInternalGraph(), from, dfs_vis, CompColorMap(ccHashMap)); DBGLOG(DBG,"predecessors of " << from << " are " << printrange(preds)); } } // required for some GCCs for DFSVisitor CopyConstructible Concept Check using namespace internalgreedy; void EvalHeuristicGreedy::build(EvalGraphBuilder& builder) { ProgramCtx& ctx = builder.getProgramCtx(); ComponentGraph& compgraph = builder.getComponentGraph(); #if 0 { std::string fnamev = "my_initial_ClonedCompGraphVerbose.dot"; std::ofstream filev(fnamev.c_str()); compgraph.writeGraphViz(filev, true); } #endif bool didSomething; do { didSomething = false; // // forall external components e: // merge with all rules that // * depend on e // * do not contain external atoms // * do not depend on something e does not (transitively) depend on // { ComponentIterator cit; for(cit = compgraph.getComponents().first; // do not use boost::tie here! the container is modified in the loop! cit != compgraph.getComponents().second; ++cit) { Component comp = *cit; if( compgraph.propsOf(comp).outerEatoms.empty() )// || !compgraph.propsOf(comp).innerRules.empty() || !compgraph.propsOf(comp).innerConstraints.empty() ) continue; DBGLOG(DBG,"checking component " << comp); LOG(ANALYZE,"checking whether to collapse external component " << comp << " with successors"); // get predecessors ComponentSet preds; transitivePredecessorComponents(compgraph, comp, preds); // get successors ComponentSet collapse; bool addedToCollapse; // do this as long as we find new ones // if we do not do this loop, we might miss something // as PredecessorIterator not necessarily honours topological order // (TODO this could be made more efficient) do { addedToCollapse = false; ComponentGraph::SuccessorIterator sit, sit_end; for(boost::tie(sit, sit_end) = compgraph.getProvides(comp); sit != sit_end; ++sit) { Component succ = compgraph.sourceOf(*sit); // skip successors with eatoms if( !compgraph.propsOf(succ).outerEatoms.empty() ) continue; // do not check found stuff twice if( collapse.find(succ) != collapse.end() ) continue; DBGLOG(DBG,"found successor " << succ); ComponentGraph::PredecessorIterator pit, pit_end; bool good = true; for(boost::tie(pit, pit_end) = compgraph.getDependencies(succ); pit != pit_end; ++pit) { Component dependson = compgraph.targetOf(*pit); if( preds.find(dependson) == preds.end() ) { LOG(DBG,"successor bad as it depends on other node " << dependson); good = false; break; } } if( good ) { // collapse with this collapse.insert(succ); preds.insert(succ); addedToCollapse = true; } } } while(addedToCollapse); // collapse if not nonempty if( !collapse.empty() ) { collapse.insert(comp); Component c = compgraph.collapseComponents(collapse); LOG(ANALYZE,"collapse of " << printrange(collapse) << " yielded new component " << c); // restart loop after collapse cit = compgraph.getComponents().first; didSomething = true; } } } // // forall components c1: // merge with all other components c2 such that no cycle is broken // that is, there must not be a path of length >=2 from c2 to c1 // { ComponentIterator cit = compgraph.getComponents().first; while(cit != compgraph.getComponents().second) { Component comp = *cit; ComponentSet collapse; DBGLOG(DBG,"checking component " << comp); ComponentIterator cit2 = cit; cit2++; while( cit2 != compgraph.getComponents().second ) { Component comp2 = *cit2; DBGLOG(DBG,"checking other component " << comp2); bool breakCycle = false; // check if there is a path of length >=2 from comp2 to comp // that is, there is a path from a predecessor of comp2 to comp ComponentSet preds2; { ComponentGraph::PredecessorIterator pit, pit_end; for(boost::tie(pit, pit_end) = compgraph.getDependencies(comp2); pit != pit_end; ++pit) { preds2.insert(compgraph.targetOf(*pit)); } } BOOST_FOREACH (Component comp2s, preds2){ ComponentSet reachable; transitivePredecessorComponents(compgraph, comp2s, reachable); if (std::find(reachable.begin(), reachable.end(), comp) != reachable.end() && comp2s != comp){ // path of length >=2 DBGLOG(DBG, "do not merge because this would break a cycle"); breakCycle = true; break; } } // check if there is a path of length >=2 from comp to comp2 // that is, there is a path from a predecessor of comp to comp2 ComponentSet preds; { ComponentGraph::PredecessorIterator pit, pit_end; for(boost::tie(pit, pit_end) = compgraph.getDependencies(comp); pit != pit_end; ++pit) { preds.insert(compgraph.targetOf(*pit)); } } BOOST_FOREACH (Component comps, preds){ ComponentSet reachable; transitivePredecessorComponents(compgraph, comps, reachable); if (std::find(reachable.begin(), reachable.end(), comp2) != reachable.end() && comps != comp2){ // path of length >=2 DBGLOG(DBG, "do not merge because this would break a cycle"); breakCycle = true; break; } } std::set<std::pair<ComponentGraph::Component, ComponentGraph::Component> > negdep; std::set<ComponentGraph::Component> nonmonotonicTransitivePredecessor; if (ctx.config.getOption("LiberalSafety") && ctx.config.getOption("IncludeAuxInputInAuxiliaries")){ if (ctx.config.getOption("LiberalSafety") && ctx.config.getOption("IncludeAuxInputInAuxiliaries")){ // check if there is a nonmonotonic external dependency from comp to comp2 BOOST_FOREACH (ComponentGraph::Dependency dep, compgraph.getDependencies()){ const ComponentGraph::DependencyInfo& di = compgraph.getDependencyInfo(dep); if (di.externalNonmonotonicPredicateInput){ // check if the nonmonotonic predicate dependency is eliminated if we consider only necessary external atoms BOOST_FOREACH (ComponentGraph::DependencyInfo::DepEdge de, di.depEdges){ if (de.get<2>().externalNonmonotonicPredicateInput && ctx.attrgraph->isExternalAtomNecessaryForDomainExpansionSafety(de.get<0>())){ // not eliminated negdep.insert(std::pair<ComponentGraph::Component, ComponentGraph::Component>(compgraph.sourceOf(dep), compgraph.targetOf(dep))); nonmonotonicTransitivePredecessor.insert(compgraph.sourceOf(dep)); break; } } } } } } // if this is the case, then do not merge if (!breakCycle){ // we do not want to merge if a component in transitivePredecessorComponents is reachable from exactly one of comp and comp2 bool nd = false; if (ctx.config.getOption("LiberalSafety") && ctx.config.getOption("IncludeAuxInputInAuxiliaries")){ ComponentSet reachable1, reachable2; transitivePredecessorComponents(compgraph, comp, reachable1); transitivePredecessorComponents(compgraph, comp2, reachable2); bool nonmonTrans1 = false; bool nonmonTrans2 = false; BOOST_FOREACH (Component c, reachable1) if (nonmonotonicTransitivePredecessor.find(c) != nonmonotonicTransitivePredecessor.end()) nonmonTrans1 = true; BOOST_FOREACH (Component c, reachable2) if (nonmonotonicTransitivePredecessor.find(c) != nonmonotonicTransitivePredecessor.end()) nonmonTrans2 = true; nd = nonmonTrans1 != nonmonTrans2; // bool nd = (negdep.find(std::pair<Component, Component>(comp, comp2)) != negdep.end()) || // (negdep.find(std::pair<Component, Component>(comp2, comp)) != negdep.end()); } if (mergeComponents(ctx, compgraph.propsOf(comp), compgraph.propsOf(comp2), nd)){ if (std::find(collapse.begin(), collapse.end(), comp2) == collapse.end()){ collapse.insert(comp2); // merge only one pair at a time, otherwise this could create cycles which are not detected above: // e.g. C1 C2 --> C3 --> C4 // C1 can be merged with C2 and C1 can be merged with C4, but it can't be merged with both of them because this would create a cycle // This is only detected if we see {C1, C2} (or {C1, C4}) as intermediate result break; } } } cit2++; } if( !collapse.empty() ) { // collapse! (decreases graph size) collapse.insert(comp); assert(collapse.size() > 1); Component c = compgraph.collapseComponents(collapse); LOG(ANALYZE,"collapse of " << printrange(collapse) << " yielded new component " << c); // restart loop after collapse cit = compgraph.getComponents().first; didSomething = true; } else { // advance ++cit; } } } } while(didSomething); // // create eval units using topological sort // ComponentContainer sortedcomps; evalheur::topologicalSortComponents(compgraph.getInternalGraph(), sortedcomps); LOG(ANALYZE,"now creating evaluation units from components " << printrange(sortedcomps)); #if 0 { std::string fnamev = "my_ClonedCompGraphVerbose.dot"; std::ofstream filev(fnamev.c_str()); compgraph.writeGraphViz(filev, true); } #endif for(ComponentContainer::const_iterator it = sortedcomps.begin(); it != sortedcomps.end(); ++it) { // just create a unit from each component (we collapsed above) std::list<Component> comps; comps.push_back(*it); std::list<Component> ccomps; EvalGraphBuilder::EvalUnit u = builder.createEvalUnit(comps, ccomps); LOG(ANALYZE,"component " << *it << " became eval unit " << u); } } DLVHEX_NAMESPACE_END // Local Variables: // mode: C++ // End: <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkAppendFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkAppendFilter.h" vtkAppendFilter::vtkAppendFilter() { this->InputList = vtkDataSetCollection::New(); } vtkAppendFilter::~vtkAppendFilter() { this->InputList->Delete(); this->InputList = NULL; } // Add a dataset to the list of data to append. void vtkAppendFilter::AddInput(vtkDataSet *ds) { if ( ! this->InputList->IsItemPresent(ds) ) { this->Modified(); this->InputList->AddItem(ds); } } // Remove a dataset from the list of data to append. void vtkAppendFilter::RemoveInput(vtkDataSet *ds) { if ( this->InputList->IsItemPresent(ds) ) { this->Modified(); this->InputList->RemoveItem(ds); } } void vtkAppendFilter::Update() { unsigned long int mtime, dsMtime; vtkDataSet *ds; // make sure input is available if ( this->InputList->GetNumberOfItems() < 1 ) { vtkErrorMacro(<< "No input...can't execute!"); return; } // prevent chasing our tail if (this->Updating) { return; } this->Updating = 1; for (mtime=0, this->InputList->InitTraversal(); (ds = this->InputList->GetNextItem()); ) { ds->Update(); dsMtime = ds->GetMTime(); if ( dsMtime > mtime ) { mtime = dsMtime; } } this->Updating = 0; if ( mtime > this->ExecuteTime || this->GetMTime() > this->ExecuteTime ) { for (this->InputList->InitTraversal();(ds=this->InputList->GetNextItem());) { if ( ds->GetDataReleased() ) { ds->ForceUpdate(); } } if ( this->StartMethod ) { (*this->StartMethod)(this->StartMethodArg); } this->Output->Initialize(); //clear output // reset AbortExecute flag and Progress this->AbortExecute = 0; this->Progress = 0.0; this->Execute(); this->ExecuteTime.Modified(); if ( !this->AbortExecute ) { this->UpdateProgress(1.0); } this->SetDataReleased(0); if ( this->EndMethod ) { (*this->EndMethod)(this->EndMethodArg); } } for (this->InputList->InitTraversal();(ds = this->InputList->GetNextItem());) { if ( ds->ShouldIReleaseData() ) { ds->ReleaseData(); } } } // Append data sets into single unstructured grid void vtkAppendFilter::Execute() { int scalarsPresent, vectorsPresent, normalsPresent, tcoordsPresent; int tensorsPresent, fieldPresent; int numPts, numCells, ptOffset; vtkPoints *newPts; vtkPointData *pd = NULL; vtkIdList *ptIds, *newPtIds; int i; vtkDataSet *ds; int ptId, cellId; vtkUnstructuredGrid *output = (vtkUnstructuredGrid *)this->Output; vtkPointData *outputPD = output->GetPointData(); vtkDebugMacro(<<"Appending data together"); // loop over all data sets, checking to see what point data is available. numPts = 0; numCells = 0; scalarsPresent = 1; vectorsPresent = 1; normalsPresent = 1; tcoordsPresent = 1; tensorsPresent = 1; fieldPresent = 1; for (this->InputList->InitTraversal(); (ds = this->InputList->GetNextItem()); ) { numPts += ds->GetNumberOfPoints(); numCells += ds->GetNumberOfCells(); pd = ds->GetPointData(); if ( pd->GetScalars() == NULL ) { scalarsPresent &= 0; } if ( pd->GetVectors() == NULL ) { vectorsPresent &= 0; } if ( pd->GetNormals() == NULL ) { normalsPresent &= 0; } if ( pd->GetTCoords() == NULL ) { tcoordsPresent &= 0; } if ( pd->GetTensors() == NULL ) { tensorsPresent &= 0; } if ( pd->GetFieldData() == NULL ) { fieldPresent &= 0; } } if ( numPts < 1 || numCells < 1 ) { vtkErrorMacro(<<"No data to append!"); return; } // Now can allocate memory output->Allocate(numCells); //allocate storage for geometry/topology if ( !scalarsPresent ) { outputPD->CopyScalarsOff(); } if ( !vectorsPresent ) { outputPD->CopyVectorsOff(); } if ( !normalsPresent ) { outputPD->CopyNormalsOff(); } if ( !tcoordsPresent ) { outputPD->CopyTCoordsOff(); } if ( !tensorsPresent ) { outputPD->CopyTensorsOff(); } if ( !fieldPresent ) { outputPD->CopyFieldDataOff(); } outputPD->CopyAllocate(pd,numPts); newPts = vtkPoints::New(); newPts->SetNumberOfPoints(numPts); ptIds = vtkIdList::New(); ptIds->Allocate(VTK_CELL_SIZE); newPtIds = vtkIdList::New(); newPtIds->Allocate(VTK_CELL_SIZE); for (ptOffset=0, this->InputList->InitTraversal(); (ds = this->InputList->GetNextItem()); ptOffset+=numPts) { numPts = ds->GetNumberOfPoints(); numCells = ds->GetNumberOfCells(); pd = ds->GetPointData(); // copy points and point data for (ptId=0; ptId < numPts; ptId++) { newPts->SetPoint(ptId+ptOffset,ds->GetPoint(ptId)); outputPD->CopyData(pd,ptId,ptId+ptOffset); } // copy cells for (cellId=0; cellId < numCells; cellId++) { ds->GetCellPoints(cellId, ptIds); newPtIds->Reset (); for (i=0; i < ptIds->GetNumberOfIds(); i++) { newPtIds->InsertId(i,ptIds->GetId(i)+ptOffset); } output->InsertNextCell(ds->GetCellType(cellId),newPtIds); } } // // Update ourselves and release memory // output->SetPoints(newPts); newPts->Delete(); ptIds->Delete(); newPtIds->Delete(); } void vtkAppendFilter::PrintSelf(ostream& os, vtkIndent indent) { vtkFilter::PrintSelf(os,indent); os << indent << "Input DataSets:\n"; this->InputList->PrintSelf(os,indent.GetNextIndent()); } <commit_msg>ERR: Was not passing cell data<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkAppendFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include "vtkAppendFilter.h" vtkAppendFilter::vtkAppendFilter() { this->InputList = vtkDataSetCollection::New(); } vtkAppendFilter::~vtkAppendFilter() { this->InputList->Delete(); this->InputList = NULL; } // Add a dataset to the list of data to append. void vtkAppendFilter::AddInput(vtkDataSet *ds) { if ( ! this->InputList->IsItemPresent(ds) ) { this->Modified(); this->InputList->AddItem(ds); } } // Remove a dataset from the list of data to append. void vtkAppendFilter::RemoveInput(vtkDataSet *ds) { if ( this->InputList->IsItemPresent(ds) ) { this->Modified(); this->InputList->RemoveItem(ds); } } void vtkAppendFilter::Update() { unsigned long int mtime, dsMtime; vtkDataSet *ds; // make sure input is available if ( this->InputList->GetNumberOfItems() < 1 ) { vtkErrorMacro(<< "No input...can't execute!"); return; } // prevent chasing our tail if (this->Updating) { return; } this->Updating = 1; for (mtime=0, this->InputList->InitTraversal(); (ds = this->InputList->GetNextItem()); ) { ds->Update(); dsMtime = ds->GetMTime(); if ( dsMtime > mtime ) { mtime = dsMtime; } } this->Updating = 0; if ( mtime > this->ExecuteTime || this->GetMTime() > this->ExecuteTime ) { for (this->InputList->InitTraversal();(ds=this->InputList->GetNextItem());) { if ( ds->GetDataReleased() ) { ds->ForceUpdate(); } } if ( this->StartMethod ) { (*this->StartMethod)(this->StartMethodArg); } this->Output->Initialize(); //clear output // reset AbortExecute flag and Progress this->AbortExecute = 0; this->Progress = 0.0; this->Execute(); this->ExecuteTime.Modified(); if ( !this->AbortExecute ) { this->UpdateProgress(1.0); } this->SetDataReleased(0); if ( this->EndMethod ) { (*this->EndMethod)(this->EndMethodArg); } } for (this->InputList->InitTraversal();(ds = this->InputList->GetNextItem());) { if ( ds->ShouldIReleaseData() ) { ds->ReleaseData(); } } } // Append data sets into single unstructured grid void vtkAppendFilter::Execute() { int scalarsPresentInPD, vectorsPresentInPD; int normalsPresentInPD, tcoordsPresentInPD; int tensorsPresentInPD, fieldPresentInPD; int scalarsPresentInCD, vectorsPresentInCD; int normalsPresentInCD, tcoordsPresentInCD; int tensorsPresentInCD, fieldPresentInCD; int numPts, numCells, ptOffset, cellOffset; vtkPoints *newPts; vtkPointData *pd = NULL; vtkCellData *cd = NULL; vtkIdList *ptIds, *newPtIds; int i; vtkDataSet *ds; int ptId, cellId, newCellId; vtkUnstructuredGrid *output = (vtkUnstructuredGrid *)this->Output; vtkPointData *outputPD = output->GetPointData(); vtkCellData *outputCD = output->GetCellData(); vtkDebugMacro(<<"Appending data together"); // loop over all data sets, checking to see what point data is available. numPts = 0; numCells = 0; scalarsPresentInPD = 1; vectorsPresentInPD = 1; normalsPresentInPD = 1; tcoordsPresentInPD = 1; tensorsPresentInPD = 1; fieldPresentInPD = 1; scalarsPresentInCD = 1; vectorsPresentInCD = 1; normalsPresentInCD = 1; tcoordsPresentInCD = 1; tensorsPresentInCD = 1; fieldPresentInCD = 1; for (this->InputList->InitTraversal(); (ds = this->InputList->GetNextItem()); ) { numPts += ds->GetNumberOfPoints(); numCells += ds->GetNumberOfCells(); pd = ds->GetPointData(); if ( pd && pd->GetScalars() == NULL ) { scalarsPresentInPD &= 0; } if ( pd && pd->GetVectors() == NULL ) { vectorsPresentInPD &= 0; } if ( pd && pd->GetNormals() == NULL ) { normalsPresentInPD &= 0; } if ( pd && pd->GetTCoords() == NULL ) { tcoordsPresentInPD &= 0; } if ( pd && pd->GetTensors() == NULL ) { tensorsPresentInPD &= 0; } if ( pd && pd->GetFieldData() == NULL ) { fieldPresentInPD &= 0; } cd = ds->GetCellData(); if ( cd && cd->GetScalars() == NULL ) { scalarsPresentInCD &= 0; } if ( cd && cd->GetVectors() == NULL ) { vectorsPresentInCD &= 0; } if ( cd && cd->GetNormals() == NULL ) { normalsPresentInCD &= 0; } if ( cd && cd->GetTCoords() == NULL ) { tcoordsPresentInCD &= 0; } if ( cd && cd->GetTensors() == NULL ) { tensorsPresentInCD &= 0; } if ( cd && cd->GetFieldData() == NULL ) { fieldPresentInCD &= 0; } } if ( numPts < 1 || numCells < 1 ) { vtkErrorMacro(<<"No data to append!"); return; } // Now can allocate memory output->Allocate(numCells); //allocate storage for geometry/topology if ( !scalarsPresentInPD ) { outputPD->CopyScalarsOff(); } if ( !vectorsPresentInPD ) { outputPD->CopyVectorsOff(); } if ( !normalsPresentInPD ) { outputPD->CopyNormalsOff(); } if ( !tcoordsPresentInPD ) { outputPD->CopyTCoordsOff(); } if ( !tensorsPresentInPD ) { outputPD->CopyTensorsOff(); } if ( !fieldPresentInPD ) { outputPD->CopyFieldDataOff(); } outputPD->CopyAllocate(pd,numPts); // now do cell data if ( !scalarsPresentInCD ) { outputCD->CopyScalarsOff(); } if ( !vectorsPresentInCD ) { outputCD->CopyVectorsOff(); } if ( !normalsPresentInCD ) { outputCD->CopyNormalsOff(); } if ( !tcoordsPresentInCD ) { outputCD->CopyTCoordsOff(); } if ( !tensorsPresentInCD ) { outputCD->CopyTensorsOff(); } if ( !fieldPresentInCD ) { outputCD->CopyFieldDataOff(); } outputCD->CopyAllocate(cd,numCells); newPts = vtkPoints::New(); newPts->SetNumberOfPoints(numPts); ptIds = vtkIdList::New(); ptIds->Allocate(VTK_CELL_SIZE); newPtIds = vtkIdList::New(); newPtIds->Allocate(VTK_CELL_SIZE); for (ptOffset=0, cellOffset=0, this->InputList->InitTraversal(); (ds = this->InputList->GetNextItem()); ptOffset+=numPts, cellOffset+=numCells) { numPts = ds->GetNumberOfPoints(); numCells = ds->GetNumberOfCells(); pd = ds->GetPointData(); // copy points and point data for (ptId=0; ptId < numPts; ptId++) { newPts->SetPoint(ptId+ptOffset,ds->GetPoint(ptId)); outputPD->CopyData(pd,ptId,ptId+ptOffset); } cd = ds->GetCellData(); // copy cell and cell data for (cellId=0; cellId < numCells; cellId++) { ds->GetCellPoints(cellId, ptIds); newPtIds->Reset (); for (i=0; i < ptIds->GetNumberOfIds(); i++) { newPtIds->InsertId(i,ptIds->GetId(i)+ptOffset); } newCellId = output->InsertNextCell(ds->GetCellType(cellId),newPtIds); outputCD->CopyData(cd,cellId,newCellId); } } // // Update ourselves and release memory // output->SetPoints(newPts); newPts->Delete(); ptIds->Delete(); newPtIds->Delete(); } void vtkAppendFilter::PrintSelf(ostream& os, vtkIndent indent) { vtkFilter::PrintSelf(os,indent); os << indent << "Input DataSets:\n"; this->InputList->PrintSelf(os,indent.GetNextIndent()); } <|endoftext|>
<commit_before>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2016 Baldur Karlsson * * 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 "renderdoccmd.h" #include <locale.h> #include <replay/renderdoc_replay.h> #include <string.h> #include <unistd.h> #include <string> #include <android_native_app_glue.h> #define ANativeActivity_onCreate __attribute__((visibility("default"))) ANativeActivity_onCreate extern "C" { #include <android_native_app_glue.c> } #include <android/log.h> #define LOGCAT_TAG "renderdoc" using std::string; struct android_app *android_state; void Daemonise() { } void DisplayRendererPreview(ReplayRenderer *renderer, TextureDisplay &displayCfg, uint32_t width, uint32_t height) { ANativeWindow *connectionScreenWindow = android_state->window; ReplayOutput *out = ReplayRenderer_CreateOutput(renderer, eWindowingSystem_Android, connectionScreenWindow, eOutputType_TexDisplay); OutputConfig c = {eOutputType_TexDisplay}; ReplayOutput_SetOutputConfig(out, c); ReplayOutput_SetTextureDisplay(out, displayCfg); for(int i = 0; i < 100; i++) { ReplayRenderer_SetFrameEvent(renderer, 10000000, true); __android_log_print(ANDROID_LOG_INFO, LOGCAT_TAG, "Frame %i", i); ReplayOutput_Display(out); usleep(100000); } } void handle_cmd(android_app *app, int32_t cmd) { switch(cmd) { case APP_CMD_INIT_WINDOW: { // The window is being shown, get it ready. __android_log_print(ANDROID_LOG_INFO, LOGCAT_TAG, "APP_CMD_INIT_WINDOW: android_state->window: %p", android_state->window); const char *argv[] = { "renderdoccmd", "replay", "/sdcard/capture.rdc", }; int argc = sizeof(argv) / sizeof(argv[0]); renderdoccmd(argc, (char **)argv); break; } case APP_CMD_TERM_WINDOW: // The window is being hidden or closed, clean it up. // DeleteVulkan(); break; default: __android_log_print(ANDROID_LOG_INFO, LOGCAT_TAG, "event not handled: %d", cmd); } } void android_main(struct android_app *state) { android_state = state; android_state->onAppCmd = handle_cmd; __android_log_print(ANDROID_LOG_INFO, LOGCAT_TAG, "android_main android_state->window: %p", android_state->window); // Used to poll the events in the main loop int events; android_poll_source *source; do { if(ALooper_pollAll(1, nullptr, &events, (void **)&source) >= 0) { if(source != NULL) source->process(android_state, source); } } while(android_state->destroyRequested == 0); } <commit_msg>Pass in apk parameters via am start ... -e renderdoccmd "args"<commit_after>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2016 Baldur Karlsson * * 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 "renderdoccmd.h" #include <locale.h> #include <replay/renderdoc_replay.h> #include <string.h> #include <unistd.h> #include <string> #include <android_native_app_glue.h> #define ANativeActivity_onCreate __attribute__((visibility("default"))) ANativeActivity_onCreate extern "C" { #include <android_native_app_glue.c> } #include <android/log.h> #define LOGCAT_TAG "renderdoc" using std::string; using std::vector; using std::istringstream; struct android_app *android_state; void Daemonise() { } void DisplayRendererPreview(ReplayRenderer *renderer, TextureDisplay &displayCfg, uint32_t width, uint32_t height) { ANativeWindow *connectionScreenWindow = android_state->window; ReplayOutput *out = ReplayRenderer_CreateOutput(renderer, eWindowingSystem_Android, connectionScreenWindow, eOutputType_TexDisplay); OutputConfig c = {eOutputType_TexDisplay}; ReplayOutput_SetOutputConfig(out, c); ReplayOutput_SetTextureDisplay(out, displayCfg); for(int i = 0; i < 100; i++) { ReplayRenderer_SetFrameEvent(renderer, 10000000, true); __android_log_print(ANDROID_LOG_INFO, LOGCAT_TAG, "Frame %i", i); ReplayOutput_Display(out); usleep(100000); } } // Returns the renderdoccmd arguments passed via am start // Examples: am start ... -e renderdoccmd "remoteserver" // -e renderdoccmd "replay /sdcard/capture.rdc" vector<string> getRenderdoccmdArgs() { JNIEnv *env; android_state->activity->vm->AttachCurrentThread(&env, 0); jobject me = android_state->activity->clazz; jclass acl = env->GetObjectClass(me); // class pointer of NativeActivity jmethodID giid = env->GetMethodID(acl, "getIntent", "()Landroid/content/Intent;"); jobject intent = env->CallObjectMethod(me, giid); // Got our intent jclass icl = env->GetObjectClass(intent); // class pointer of Intent jmethodID gseid = env->GetMethodID(icl, "getStringExtra", "(Ljava/lang/String;)Ljava/lang/String;"); jstring jsParam1 = (jstring)env->CallObjectMethod(intent, gseid, env->NewStringUTF("renderdoccmd")); vector<string> ret; if(!jsParam1) return ret; // No arg value found ret.push_back("renderdoccmd"); const char *param1 = env->GetStringUTFChars(jsParam1, 0); istringstream iss(param1); while(iss) { string sub; iss >> sub; ret.push_back(sub); } return ret; } void handle_cmd(android_app *app, int32_t cmd) { switch(cmd) { case APP_CMD_INIT_WINDOW: { vector<string> args = getRenderdoccmdArgs(); if(!args.size()) break; // Nothing for APK to do. renderdoccmd(args); break; } case APP_CMD_TERM_WINDOW: break; default: __android_log_print(ANDROID_LOG_INFO, LOGCAT_TAG, "event not handled: %d", cmd); } } void android_main(struct android_app *state) { android_state = state; android_state->onAppCmd = handle_cmd; __android_log_print(ANDROID_LOG_INFO, LOGCAT_TAG, "android_main android_state->window: %p", android_state->window); // Used to poll the events in the main loop int events; android_poll_source *source; do { if(ALooper_pollAll(1, nullptr, &events, (void **)&source) >= 0) { if(source != NULL) source->process(android_state, source); } } while(android_state->destroyRequested == 0); } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //-----------------------------------------------------// // // // Date : March 25 2004 // // This reads the file PMD.RecPoints.root(TreeR), // // calls the Clustering algorithm and stores the // // clustering output in PMD.RecPoints.root(TreeR) // // // //-----------------------------------------------------// #include <Riostream.h> #include <TMath.h> #include <TTree.h> #include <TObjArray.h> #include <TClonesArray.h> #include <TFile.h> #include <TBranch.h> #include <TNtuple.h> #include <TParticle.h> #include "AliPMDcluster.h" #include "AliPMDclupid.h" #include "AliPMDrecpoint1.h" #include "AliPMDrecdata.h" #include "AliPMDrechit.h" #include "AliPMDUtility.h" #include "AliPMDDiscriminator.h" #include "AliPMDEmpDiscriminator.h" #include "AliPMDtracker.h" #include "AliESDPmdTrack.h" #include "AliESDEvent.h" #include "AliLog.h" ClassImp(AliPMDtracker) AliPMDtracker::AliPMDtracker(): fTreeR(0), fRecpoints(new TClonesArray("AliPMDrecpoint1", 10)), fRechits(new TClonesArray("AliPMDrechit", 10)), fPMDcontin(new TObjArray()), fPMDcontout(new TObjArray()), fPMDutil(new AliPMDUtility()), fPMDrecpoint(0), fPMDclin(0), fPMDclout(0), fXvertex(0.), fYvertex(0.), fZvertex(0.), fSigmaX(0.), fSigmaY(0.), fSigmaZ(0.) { // // Default Constructor // } //--------------------------------------------------------------------// AliPMDtracker:: AliPMDtracker(const AliPMDtracker & /* tracker */): TObject(/* tracker */), fTreeR(0), fRecpoints(NULL), fRechits(NULL), fPMDcontin(NULL), fPMDcontout(NULL), fPMDutil(NULL), fPMDrecpoint(0), fPMDclin(0), fPMDclout(0), fXvertex(0.), fYvertex(0.), fZvertex(0.), fSigmaX(0.), fSigmaY(0.), fSigmaZ(0.) { // copy constructor AliError("Copy constructor not allowed"); } //--------------------------------------------------------------------// AliPMDtracker& AliPMDtracker::operator=(const AliPMDtracker & /* tracker */) { // assignment operator AliError("Assignment operator not allowed"); return *this; } //--------------------------------------------------------------------// AliPMDtracker::~AliPMDtracker() { // Destructor if (fRecpoints) { fRecpoints->Clear(); } if (fRechits) { fRechits->Clear(); } if (fPMDcontin) { fPMDcontin->Delete(); delete fPMDcontin; fPMDcontin=0; } if (fPMDcontout) { fPMDcontout->Delete(); delete fPMDcontout; fPMDcontout=0; } delete fPMDutil; } //--------------------------------------------------------------------// void AliPMDtracker::LoadClusters(TTree *treein) { // Load the Reconstructed tree fTreeR = treein; } //--------------------------------------------------------------------// void AliPMDtracker::Clusters2Tracks(AliESDEvent *event) { // Converts digits to recpoints after running clustering // algorithm on CPV plane and PREshower plane // Int_t idet; Int_t ismn; Int_t trackno, trackpid; Float_t clusdata[6]; Int_t *irow; Int_t *icol; Int_t *itra; Int_t *ipid; Float_t *cadc; AliPMDrechit *rechit = 0x0; TBranch *branch = fTreeR->GetBranch("PMDRecpoint"); if (!branch) { AliError("PMDRecpoint branch not found"); return; } branch->SetAddress(&fRecpoints); TBranch *branch1 = fTreeR->GetBranch("PMDRechit"); if (!branch1) { AliError("PMDRechit branch not found"); return; } branch1->SetAddress(&fRechits); Int_t ncrhit = 0; Int_t nmodules = (Int_t) branch->GetEntries(); AliDebug(1,Form("Number of modules filled in treeR = %d",nmodules)); for (Int_t imodule = 0; imodule < nmodules; imodule++) { branch->GetEntry(imodule); Int_t nentries = fRecpoints->GetLast(); AliDebug(2,Form("Number of clusters per modules filled in treeR = %d" ,nentries)); for(Int_t ient = 0; ient < nentries+1; ient++) { fPMDrecpoint = (AliPMDrecpoint1*)fRecpoints->UncheckedAt(ient); idet = fPMDrecpoint->GetDetector(); ismn = fPMDrecpoint->GetSMNumber(); clusdata[0] = fPMDrecpoint->GetClusX(); clusdata[1] = fPMDrecpoint->GetClusY(); clusdata[2] = fPMDrecpoint->GetClusADC(); clusdata[3] = fPMDrecpoint->GetClusCells(); clusdata[4] = fPMDrecpoint->GetClusSigmaX(); clusdata[5] = fPMDrecpoint->GetClusSigmaY(); if (clusdata[4] >= 0. && clusdata[5] >= 0.) { // extract the associated cell information branch1->GetEntry(ncrhit); Int_t nenbr1 = fRechits->GetLast() + 1; irow = new Int_t[nenbr1]; icol = new Int_t[nenbr1]; itra = new Int_t[nenbr1]; ipid = new Int_t[nenbr1]; cadc = new Float_t[nenbr1]; for (Int_t ient1 = 0; ient1 < nenbr1; ient1++) { rechit = (AliPMDrechit*)fRechits->UncheckedAt(ient1); //irow[ient1] = rechit->GetCellX(); //icol[ient1] = rechit->GetCellY(); itra[ient1] = rechit->GetCellTrack(); ipid[ient1] = rechit->GetCellPid(); cadc[ient1] = rechit->GetCellAdc(); } AssignTrPidToCluster(nenbr1, itra, ipid, cadc, trackno, trackpid); delete [] irow; delete [] icol; delete [] itra; delete [] ipid; delete [] cadc; fPMDclin = new AliPMDrecdata(idet,ismn,trackno,trackpid,clusdata); fPMDcontin->Add(fPMDclin); ncrhit++; } } } AliPMDDiscriminator *pmddiscriminator = new AliPMDEmpDiscriminator(); pmddiscriminator->Discrimination(fPMDcontin,fPMDcontout); const Float_t kzpos = 361.5; // middle of the PMD Int_t det,smn,trno,trpid,mstat; Float_t xpos,ypos; Float_t adc, ncell, radx, rady; Float_t xglobal = 0., yglobal = 0., zglobal = 0; Float_t pid; Int_t nentries2 = fPMDcontout->GetEntries(); AliDebug(1,Form("Number of clusters coming after discrimination = %d" ,nentries2)); for (Int_t ient1 = 0; ient1 < nentries2; ient1++) { fPMDclout = (AliPMDclupid*)fPMDcontout->UncheckedAt(ient1); det = fPMDclout->GetDetector(); smn = fPMDclout->GetSMN(); trno = fPMDclout->GetClusTrackNo(); trpid = fPMDclout->GetClusTrackPid(); mstat = fPMDclout->GetClusMatching(); xpos = fPMDclout->GetClusX(); ypos = fPMDclout->GetClusY(); adc = fPMDclout->GetClusADC(); ncell = fPMDclout->GetClusCells(); radx = fPMDclout->GetClusSigmaX(); rady = fPMDclout->GetClusSigmaY(); pid = fPMDclout->GetClusPID(); // /********************************************************************** * det : Detector, 0: PRE & 1:CPV * * smn : Serial Module Number 0 to 23 for each plane * * xpos : x-position of the cluster * * ypos : y-position of the cluster * * THESE xpos & ypos are not the true xpos and ypos * * for some of the unit modules. They are rotated. * * adc : ADC contained in the cluster * * ncell : Number of cells contained in the cluster * * rad : radius of the cluster (1d fit) * **********************************************************************/ // fPMDutil->RectGeomCellPos(smn,xpos,ypos,xglobal,yglobal); if (det == 0) { zglobal = kzpos + 1.6; // PREshower plane } else if (det == 1) { zglobal = kzpos - 1.7; // CPV plane } // Fill ESD AliESDPmdTrack *esdpmdtr = new AliESDPmdTrack(); esdpmdtr->SetDetector(det); esdpmdtr->SetSmn(smn); esdpmdtr->SetClusterTrackNo(trno); esdpmdtr->SetClusterTrackPid(trpid); esdpmdtr->SetClusterMatching(mstat); esdpmdtr->SetClusterX(xglobal); esdpmdtr->SetClusterY(yglobal); esdpmdtr->SetClusterZ(zglobal); esdpmdtr->SetClusterADC(adc); esdpmdtr->SetClusterCells(ncell); esdpmdtr->SetClusterPID(pid); esdpmdtr->SetClusterSigmaX(radx); esdpmdtr->SetClusterSigmaY(rady); event->AddPmdTrack(esdpmdtr); } fPMDcontin->Delete(); fPMDcontout->Delete(); } //--------------------------------------------------------------------// void AliPMDtracker::AssignTrPidToCluster(Int_t nentry, Int_t *itra, Int_t *ipid, Float_t *cadc, Int_t &trackno, Int_t &trackpid) { // assign the track number and the corresponding pid to a cluster // split cluster part will be done at the time of calculating eff/pur Int_t *phentry = new Int_t [nentry]; Int_t *trenergy = 0x0; Int_t *sortcoord = 0x0; Int_t ngtrack = 0; for (Int_t i = 0; i < nentry; i++) { phentry[i] = -1; if (ipid[i] == 22) { phentry[ngtrack] = i; ngtrack++; } } if (ngtrack == 0) { // hadron track // no need of track number, set to -1 trackpid = 8; trackno = -1; } else if (ngtrack == 1) { // only one photon track // track number set to photon track trackpid = 1; trackno = itra[phentry[0]]; } else if (ngtrack > 1) { // more than one photon track trenergy = new Int_t [ngtrack]; sortcoord = new Int_t [ngtrack]; for (Int_t i = 0; i < ngtrack; i++) { trenergy[i] = 0.; for (Int_t j = 0; j < nentry; j++) { if (ipid[j] == 22 && itra[j] == itra[phentry[i]]) { trenergy[i] += cadc[j]; } } } Bool_t jsort = true; TMath::Sort(ngtrack,trenergy,sortcoord,jsort); Int_t gtr = sortcoord[0]; trackno = itra[phentry[gtr]]; // highest adc track trackpid = 1; delete [] trenergy; delete [] sortcoord; } // end of ngtrack > 1 } //--------------------------------------------------------------------// void AliPMDtracker::SetVertex(Double_t vtx[3], Double_t evtx[3]) { fXvertex = vtx[0]; fYvertex = vtx[1]; fZvertex = vtx[2]; fSigmaX = evtx[0]; fSigmaY = evtx[1]; fSigmaZ = evtx[2]; } //--------------------------------------------------------------------// void AliPMDtracker::ResetClusters() { if (fRecpoints) fRecpoints->Clear(); } //--------------------------------------------------------------------// <commit_msg>Bug fixed for the CPV plane to get the correct track number in ESD file<commit_after>/*************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //-----------------------------------------------------// // // // Date : March 25 2004 // // This reads the file PMD.RecPoints.root(TreeR), // // calls the Clustering algorithm and stores the // // clustering output in PMD.RecPoints.root(TreeR) // // // //-----------------------------------------------------// #include <Riostream.h> #include <TMath.h> #include <TTree.h> #include <TObjArray.h> #include <TClonesArray.h> #include <TFile.h> #include <TBranch.h> #include <TNtuple.h> #include <TParticle.h> #include "AliPMDcluster.h" #include "AliPMDclupid.h" #include "AliPMDrecpoint1.h" #include "AliPMDrecdata.h" #include "AliPMDrechit.h" #include "AliPMDUtility.h" #include "AliPMDDiscriminator.h" #include "AliPMDEmpDiscriminator.h" #include "AliPMDtracker.h" #include "AliESDPmdTrack.h" #include "AliESDEvent.h" #include "AliLog.h" ClassImp(AliPMDtracker) AliPMDtracker::AliPMDtracker(): fTreeR(0), fRecpoints(new TClonesArray("AliPMDrecpoint1", 10)), fRechits(new TClonesArray("AliPMDrechit", 10)), fPMDcontin(new TObjArray()), fPMDcontout(new TObjArray()), fPMDutil(new AliPMDUtility()), fPMDrecpoint(0), fPMDclin(0), fPMDclout(0), fXvertex(0.), fYvertex(0.), fZvertex(0.), fSigmaX(0.), fSigmaY(0.), fSigmaZ(0.) { // // Default Constructor // } //--------------------------------------------------------------------// AliPMDtracker:: AliPMDtracker(const AliPMDtracker & /* tracker */): TObject(/* tracker */), fTreeR(0), fRecpoints(NULL), fRechits(NULL), fPMDcontin(NULL), fPMDcontout(NULL), fPMDutil(NULL), fPMDrecpoint(0), fPMDclin(0), fPMDclout(0), fXvertex(0.), fYvertex(0.), fZvertex(0.), fSigmaX(0.), fSigmaY(0.), fSigmaZ(0.) { // copy constructor AliError("Copy constructor not allowed"); } //--------------------------------------------------------------------// AliPMDtracker& AliPMDtracker::operator=(const AliPMDtracker & /* tracker */) { // assignment operator AliError("Assignment operator not allowed"); return *this; } //--------------------------------------------------------------------// AliPMDtracker::~AliPMDtracker() { // Destructor if (fRecpoints) { fRecpoints->Clear(); } if (fRechits) { fRechits->Clear(); } if (fPMDcontin) { fPMDcontin->Delete(); delete fPMDcontin; fPMDcontin=0; } if (fPMDcontout) { fPMDcontout->Delete(); delete fPMDcontout; fPMDcontout=0; } delete fPMDutil; } //--------------------------------------------------------------------// void AliPMDtracker::LoadClusters(TTree *treein) { // Load the Reconstructed tree fTreeR = treein; } //--------------------------------------------------------------------// void AliPMDtracker::Clusters2Tracks(AliESDEvent *event) { // Converts digits to recpoints after running clustering // algorithm on CPV plane and PREshower plane // Int_t idet; Int_t ismn; Int_t trackno, trackpid; Float_t clusdata[6]; Int_t *irow; Int_t *icol; Int_t *itra; Int_t *ipid; Float_t *cadc; AliPMDrechit *rechit = 0x0; TBranch *branch = fTreeR->GetBranch("PMDRecpoint"); if (!branch) { AliError("PMDRecpoint branch not found"); return; } branch->SetAddress(&fRecpoints); TBranch *branch1 = fTreeR->GetBranch("PMDRechit"); if (!branch1) { AliError("PMDRechit branch not found"); return; } branch1->SetAddress(&fRechits); Int_t ncrhit = 0; Int_t nmodules = (Int_t) branch->GetEntries(); AliDebug(1,Form("Number of modules filled in treeR = %d",nmodules)); for (Int_t imodule = 0; imodule < nmodules; imodule++) { branch->GetEntry(imodule); Int_t nentries = fRecpoints->GetLast(); AliDebug(2,Form("Number of clusters per modules filled in treeR = %d" ,nentries)); for(Int_t ient = 0; ient < nentries+1; ient++) { fPMDrecpoint = (AliPMDrecpoint1*)fRecpoints->UncheckedAt(ient); idet = fPMDrecpoint->GetDetector(); ismn = fPMDrecpoint->GetSMNumber(); clusdata[0] = fPMDrecpoint->GetClusX(); clusdata[1] = fPMDrecpoint->GetClusY(); clusdata[2] = fPMDrecpoint->GetClusADC(); clusdata[3] = fPMDrecpoint->GetClusCells(); clusdata[4] = fPMDrecpoint->GetClusSigmaX(); clusdata[5] = fPMDrecpoint->GetClusSigmaY(); if (clusdata[4] >= 0. && clusdata[5] >= 0.) { // extract the associated cell information branch1->GetEntry(ncrhit); Int_t nenbr1 = fRechits->GetLast() + 1; irow = new Int_t[nenbr1]; icol = new Int_t[nenbr1]; itra = new Int_t[nenbr1]; ipid = new Int_t[nenbr1]; cadc = new Float_t[nenbr1]; for (Int_t ient1 = 0; ient1 < nenbr1; ient1++) { rechit = (AliPMDrechit*)fRechits->UncheckedAt(ient1); //irow[ient1] = rechit->GetCellX(); //icol[ient1] = rechit->GetCellY(); itra[ient1] = rechit->GetCellTrack(); ipid[ient1] = rechit->GetCellPid(); cadc[ient1] = rechit->GetCellAdc(); } if (idet == 0) { AssignTrPidToCluster(nenbr1, itra, ipid, cadc, trackno, trackpid); } else if (idet == 1) { trackno = itra[0]; trackpid = ipid[0]; } delete [] irow; delete [] icol; delete [] itra; delete [] ipid; delete [] cadc; fPMDclin = new AliPMDrecdata(idet,ismn,trackno,trackpid,clusdata); fPMDcontin->Add(fPMDclin); ncrhit++; } } } AliPMDDiscriminator *pmddiscriminator = new AliPMDEmpDiscriminator(); pmddiscriminator->Discrimination(fPMDcontin,fPMDcontout); const Float_t kzpos = 361.5; // middle of the PMD Int_t det,smn,trno,trpid,mstat; Float_t xpos,ypos; Float_t adc, ncell, radx, rady; Float_t xglobal = 0., yglobal = 0., zglobal = 0; Float_t pid; Int_t nentries2 = fPMDcontout->GetEntries(); AliDebug(1,Form("Number of clusters coming after discrimination = %d" ,nentries2)); for (Int_t ient1 = 0; ient1 < nentries2; ient1++) { fPMDclout = (AliPMDclupid*)fPMDcontout->UncheckedAt(ient1); det = fPMDclout->GetDetector(); smn = fPMDclout->GetSMN(); trno = fPMDclout->GetClusTrackNo(); trpid = fPMDclout->GetClusTrackPid(); mstat = fPMDclout->GetClusMatching(); xpos = fPMDclout->GetClusX(); ypos = fPMDclout->GetClusY(); adc = fPMDclout->GetClusADC(); ncell = fPMDclout->GetClusCells(); radx = fPMDclout->GetClusSigmaX(); rady = fPMDclout->GetClusSigmaY(); pid = fPMDclout->GetClusPID(); // /********************************************************************** * det : Detector, 0: PRE & 1:CPV * * smn : Serial Module Number 0 to 23 for each plane * * xpos : x-position of the cluster * * ypos : y-position of the cluster * * THESE xpos & ypos are not the true xpos and ypos * * for some of the unit modules. They are rotated. * * adc : ADC contained in the cluster * * ncell : Number of cells contained in the cluster * * rad : radius of the cluster (1d fit) * **********************************************************************/ // fPMDutil->RectGeomCellPos(smn,xpos,ypos,xglobal,yglobal); if (det == 0) { zglobal = kzpos + 1.6; // PREshower plane } else if (det == 1) { zglobal = kzpos - 1.7; // CPV plane } // Fill ESD AliESDPmdTrack *esdpmdtr = new AliESDPmdTrack(); esdpmdtr->SetDetector(det); esdpmdtr->SetSmn(smn); esdpmdtr->SetClusterTrackNo(trno); esdpmdtr->SetClusterTrackPid(trpid); esdpmdtr->SetClusterMatching(mstat); esdpmdtr->SetClusterX(xglobal); esdpmdtr->SetClusterY(yglobal); esdpmdtr->SetClusterZ(zglobal); esdpmdtr->SetClusterADC(adc); esdpmdtr->SetClusterCells(ncell); esdpmdtr->SetClusterPID(pid); esdpmdtr->SetClusterSigmaX(radx); esdpmdtr->SetClusterSigmaY(rady); event->AddPmdTrack(esdpmdtr); } fPMDcontin->Delete(); fPMDcontout->Delete(); } //--------------------------------------------------------------------// void AliPMDtracker::AssignTrPidToCluster(Int_t nentry, Int_t *itra, Int_t *ipid, Float_t *cadc, Int_t &trackno, Int_t &trackpid) { // assign the track number and the corresponding pid to a cluster // split cluster part will be done at the time of calculating eff/pur Int_t *phentry = new Int_t [nentry]; Int_t *trenergy = 0x0; Int_t *sortcoord = 0x0; Int_t ngtrack = 0; for (Int_t i = 0; i < nentry; i++) { phentry[i] = -1; if (ipid[i] == 22) { phentry[ngtrack] = i; ngtrack++; } } if (ngtrack == 0) { // hadron track // no need of track number, set to -1 trackpid = 8; trackno = -1; } else if (ngtrack == 1) { // only one photon track // track number set to photon track trackpid = 1; trackno = itra[phentry[0]]; } else if (ngtrack > 1) { // more than one photon track trenergy = new Int_t [ngtrack]; sortcoord = new Int_t [ngtrack]; for (Int_t i = 0; i < ngtrack; i++) { trenergy[i] = 0.; for (Int_t j = 0; j < nentry; j++) { if (ipid[j] == 22 && itra[j] == itra[phentry[i]]) { trenergy[i] += cadc[j]; } } } Bool_t jsort = true; TMath::Sort(ngtrack,trenergy,sortcoord,jsort); Int_t gtr = sortcoord[0]; trackno = itra[phentry[gtr]]; // highest adc track trackpid = 1; delete [] trenergy; delete [] sortcoord; } // end of ngtrack > 1 } //--------------------------------------------------------------------// void AliPMDtracker::SetVertex(Double_t vtx[3], Double_t evtx[3]) { fXvertex = vtx[0]; fYvertex = vtx[1]; fZvertex = vtx[2]; fSigmaX = evtx[0]; fSigmaY = evtx[1]; fSigmaZ = evtx[2]; } //--------------------------------------------------------------------// void AliPMDtracker::ResetClusters() { if (fRecpoints) fRecpoints->Clear(); } //--------------------------------------------------------------------// <|endoftext|>
<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "browser/api/atom_api_app.h" #include "base/values.h" #include "base/command_line.h" #include "browser/browser.h" #include "common/v8_conversions.h" #include "vendor/node/src/node.h" namespace atom { namespace api { App::App(v8::Handle<v8::Object> wrapper) : EventEmitter(wrapper) { Browser::Get()->AddObserver(this); } App::~App() { Browser::Get()->RemoveObserver(this); } void App::OnWillQuit(bool* prevent_default) { *prevent_default = Emit("will-quit"); } void App::OnWindowAllClosed() { Emit("window-all-closed"); } void App::OnOpenFile(bool* prevent_default, const std::string& file_path) { base::ListValue args; args.AppendString(file_path); *prevent_default = Emit("open-file", &args); } void App::OnOpenURL(const std::string& url) { base::ListValue args; args.AppendString(url); Emit("open-url", &args); } void App::OnWillFinishLaunching() { Emit("will-finish-launching"); } void App::OnFinishLaunching() { Emit("finish-launching"); } // static v8::Handle<v8::Value> App::New(const v8::Arguments &args) { v8::HandleScope scope; if (!args.IsConstructCall()) return node::ThrowError("Require constructor call"); new App(args.This()); return args.This(); } // static v8::Handle<v8::Value> App::Quit(const v8::Arguments &args) { v8::HandleScope scope; Browser::Get()->Quit(); return v8::Undefined(); } // static v8::Handle<v8::Value> App::Exit(const v8::Arguments &args) { v8::HandleScope scope; exit(args[0]->IntegerValue()); return v8::Undefined(); } // static v8::Handle<v8::Value> App::Terminate(const v8::Arguments &args) { v8::HandleScope scope; Browser::Get()->Terminate(); return v8::Undefined(); } // static v8::Handle<v8::Value> App::Focus(const v8::Arguments &args) { v8::HandleScope scope; Browser::Get()->Focus(); return v8::Undefined(); } // static v8::Handle<v8::Value> App::GetVersion(const v8::Arguments &args) { v8::HandleScope scope; std::string version(Browser::Get()->GetVersion()); return v8::String::New(version.data(), version.size()); } // static v8::Handle<v8::Value> App::SetVersion(const v8::Arguments &args) { v8::HandleScope scope; std::string version; if (!FromV8Arguments(args, &version)) return node::ThrowError("Bad argument"); Browser::Get()->SetVersion(version); return v8::Undefined(); } // static v8::Handle<v8::Value> App::GetName(const v8::Arguments &args) { v8::HandleScope scope; std::string name(Browser::Get()->GetName()); return v8::String::New(name.data(), version.size()); } // static v8::Handle<v8::Value> App::SetName(const v8::Arguments &args) { v8::HandleScope scope; std::string name; if (!FromV8Arguments(args, &name)) return node::ThrowError("Bad argument"); Browser::Get()->SetName(name); return v8::Undefined(); } // static v8::Handle<v8::Value> App::AppendSwitch(const v8::Arguments &args) { v8::HandleScope scope; std::string switch_string; if (!FromV8Arguments(args, &switch_string)) return node::ThrowError("Bad argument"); if (args.Length() == 1) { CommandLine::ForCurrentProcess()->AppendSwitch(switch_string); } else { std::string value = FromV8Value(args[1]); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switch_string, value); } return v8::Undefined(); } // static v8::Handle<v8::Value> App::AppendArgument(const v8::Arguments &args) { v8::HandleScope scope; std::string value; if (!FromV8Arguments(args, &value)) return node::ThrowError("Bad argument"); CommandLine::ForCurrentProcess()->AppendArg(value); return v8::Undefined(); } #if defined(OS_MACOSX) // static v8::Handle<v8::Value> App::DockBounce(const v8::Arguments& args) { std::string type = FromV8Value(args[0]); int request_id = -1; if (type == "critical") request_id = Browser::Get()->DockBounce(Browser::BOUNCE_CRITICAL); else if (type == "informational") request_id = Browser::Get()->DockBounce(Browser::BOUNCE_INFORMATIONAL); else return node::ThrowTypeError("Invalid bounce type"); return v8::Integer::New(request_id); } // static v8::Handle<v8::Value> App::DockCancelBounce(const v8::Arguments& args) { Browser::Get()->DockCancelBounce(FromV8Value(args[0])); return v8::Undefined(); } // static v8::Handle<v8::Value> App::DockSetBadgeText(const v8::Arguments& args) { Browser::Get()->DockSetBadgeText(FromV8Value(args[0])); return v8::Undefined(); } // static v8::Handle<v8::Value> App::DockGetBadgeText(const v8::Arguments& args) { std::string text(Browser::Get()->DockGetBadgeText()); return ToV8Value(text); } #endif // defined(OS_MACOSX) // static void App::Initialize(v8::Handle<v8::Object> target) { v8::HandleScope scope; v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(App::New); t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(v8::String::NewSymbol("Application")); NODE_SET_PROTOTYPE_METHOD(t, "quit", Quit); NODE_SET_PROTOTYPE_METHOD(t, "exit", Exit); NODE_SET_PROTOTYPE_METHOD(t, "terminate", Terminate); NODE_SET_PROTOTYPE_METHOD(t, "focus", Focus); NODE_SET_PROTOTYPE_METHOD(t, "getVersion", GetVersion); NODE_SET_PROTOTYPE_METHOD(t, "setVersion", SetVersion); NODE_SET_PROTOTYPE_METHOD(t, "getName", GetName); NODE_SET_PROTOTYPE_METHOD(t, "setName", SetName); target->Set(v8::String::NewSymbol("Application"), t->GetFunction()); NODE_SET_METHOD(target, "appendSwitch", AppendSwitch); NODE_SET_METHOD(target, "appendArgument", AppendArgument); #if defined(OS_MACOSX) NODE_SET_METHOD(target, "dockBounce", DockBounce); NODE_SET_METHOD(target, "dockCancelBounce", DockCancelBounce); NODE_SET_METHOD(target, "dockSetBadgeText", DockSetBadgeText); NODE_SET_METHOD(target, "dockGetBadgeText", DockGetBadgeText); #endif // defined(OS_MACOSX) } } // namespace api } // namespace atom NODE_MODULE(atom_browser_app, atom::api::App::Initialize) <commit_msg>Simplify V8 operations.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "browser/api/atom_api_app.h" #include "base/values.h" #include "base/command_line.h" #include "browser/browser.h" #include "common/v8_conversions.h" #include "vendor/node/src/node.h" namespace atom { namespace api { App::App(v8::Handle<v8::Object> wrapper) : EventEmitter(wrapper) { Browser::Get()->AddObserver(this); } App::~App() { Browser::Get()->RemoveObserver(this); } void App::OnWillQuit(bool* prevent_default) { *prevent_default = Emit("will-quit"); } void App::OnWindowAllClosed() { Emit("window-all-closed"); } void App::OnOpenFile(bool* prevent_default, const std::string& file_path) { base::ListValue args; args.AppendString(file_path); *prevent_default = Emit("open-file", &args); } void App::OnOpenURL(const std::string& url) { base::ListValue args; args.AppendString(url); Emit("open-url", &args); } void App::OnWillFinishLaunching() { Emit("will-finish-launching"); } void App::OnFinishLaunching() { Emit("finish-launching"); } // static v8::Handle<v8::Value> App::New(const v8::Arguments &args) { v8::HandleScope scope; if (!args.IsConstructCall()) return node::ThrowError("Require constructor call"); new App(args.This()); return args.This(); } // static v8::Handle<v8::Value> App::Quit(const v8::Arguments &args) { v8::HandleScope scope; Browser::Get()->Quit(); return v8::Undefined(); } // static v8::Handle<v8::Value> App::Exit(const v8::Arguments &args) { v8::HandleScope scope; exit(args[0]->IntegerValue()); return v8::Undefined(); } // static v8::Handle<v8::Value> App::Terminate(const v8::Arguments &args) { v8::HandleScope scope; Browser::Get()->Terminate(); return v8::Undefined(); } // static v8::Handle<v8::Value> App::Focus(const v8::Arguments &args) { v8::HandleScope scope; Browser::Get()->Focus(); return v8::Undefined(); } // static v8::Handle<v8::Value> App::GetVersion(const v8::Arguments &args) { return ToV8Value(Browser::Get()->GetVersion()); } // static v8::Handle<v8::Value> App::SetVersion(const v8::Arguments &args) { v8::HandleScope scope; std::string version; if (!FromV8Arguments(args, &version)) return node::ThrowError("Bad argument"); Browser::Get()->SetVersion(version); return v8::Undefined(); } // static v8::Handle<v8::Value> App::GetName(const v8::Arguments &args) { return ToV8Value(Browser::Get()->GetName()); } // static v8::Handle<v8::Value> App::SetName(const v8::Arguments &args) { v8::HandleScope scope; std::string name; if (!FromV8Arguments(args, &name)) return node::ThrowError("Bad argument"); Browser::Get()->SetName(name); return v8::Undefined(); } // static v8::Handle<v8::Value> App::AppendSwitch(const v8::Arguments &args) { v8::HandleScope scope; std::string switch_string; if (!FromV8Arguments(args, &switch_string)) return node::ThrowError("Bad argument"); if (args.Length() == 1) { CommandLine::ForCurrentProcess()->AppendSwitch(switch_string); } else { std::string value = FromV8Value(args[1]); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switch_string, value); } return v8::Undefined(); } // static v8::Handle<v8::Value> App::AppendArgument(const v8::Arguments &args) { v8::HandleScope scope; std::string value; if (!FromV8Arguments(args, &value)) return node::ThrowError("Bad argument"); CommandLine::ForCurrentProcess()->AppendArg(value); return v8::Undefined(); } #if defined(OS_MACOSX) // static v8::Handle<v8::Value> App::DockBounce(const v8::Arguments& args) { std::string type; if (!FromV8Arguments(args, &type)) return node::ThrowError("Bad argument"); int request_id = -1; if (type == "critical") request_id = Browser::Get()->DockBounce(Browser::BOUNCE_CRITICAL); else if (type == "informational") request_id = Browser::Get()->DockBounce(Browser::BOUNCE_INFORMATIONAL); else return node::ThrowTypeError("Invalid bounce type"); return ToV8Value(request_id); } // static v8::Handle<v8::Value> App::DockCancelBounce(const v8::Arguments& args) { Browser::Get()->DockCancelBounce(FromV8Value(args[0])); return v8::Undefined(); } // static v8::Handle<v8::Value> App::DockSetBadgeText(const v8::Arguments& args) { Browser::Get()->DockSetBadgeText(FromV8Value(args[0])); return v8::Undefined(); } // static v8::Handle<v8::Value> App::DockGetBadgeText(const v8::Arguments& args) { std::string text(Browser::Get()->DockGetBadgeText()); return ToV8Value(text); } #endif // defined(OS_MACOSX) // static void App::Initialize(v8::Handle<v8::Object> target) { v8::HandleScope scope; v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(App::New); t->InstanceTemplate()->SetInternalFieldCount(1); t->SetClassName(v8::String::NewSymbol("Application")); NODE_SET_PROTOTYPE_METHOD(t, "quit", Quit); NODE_SET_PROTOTYPE_METHOD(t, "exit", Exit); NODE_SET_PROTOTYPE_METHOD(t, "terminate", Terminate); NODE_SET_PROTOTYPE_METHOD(t, "focus", Focus); NODE_SET_PROTOTYPE_METHOD(t, "getVersion", GetVersion); NODE_SET_PROTOTYPE_METHOD(t, "setVersion", SetVersion); NODE_SET_PROTOTYPE_METHOD(t, "getName", GetName); NODE_SET_PROTOTYPE_METHOD(t, "setName", SetName); target->Set(v8::String::NewSymbol("Application"), t->GetFunction()); NODE_SET_METHOD(target, "appendSwitch", AppendSwitch); NODE_SET_METHOD(target, "appendArgument", AppendArgument); #if defined(OS_MACOSX) NODE_SET_METHOD(target, "dockBounce", DockBounce); NODE_SET_METHOD(target, "dockCancelBounce", DockCancelBounce); NODE_SET_METHOD(target, "dockSetBadgeText", DockSetBadgeText); NODE_SET_METHOD(target, "dockGetBadgeText", DockGetBadgeText); #endif // defined(OS_MACOSX) } } // namespace api } // namespace atom NODE_MODULE(atom_browser_app, atom::api::App::Initialize) <|endoftext|>
<commit_before>#pragma once #include "xml_doc.hpp" #include "libxml2_error_handlers.hpp" #include <libxml/xpath.h> #include <memory> #include <iostream> class FreeXPathCtxt { public: auto operator( )( xmlXPathContext *xpathCtxt ) const -> void { xmlXPathFreeContext( xpathCtxt ); } }; class XPathCtxt { friend class XPathQuery; public: XPathCtxt( ) : xpathCtxt_{nullptr} {} explicit XPathCtxt( const XmlDoc &xml ) : xml_{xml}, xpathCtxt_{xmlXPathNewContext( xml_.xmlDoc_.get( ) )} { xpathHandler_.registerHandler( xpathCtxt_.get( ) ); } XPathCtxt( const XPathCtxt &xpathCtxt ) : xml_{xpathCtxt.xml_} { if ( xpathCtxt ) { xpathCtxt_.reset( xmlXPathNewContext( xml_.xmlDoc_.get( ) ) ); xpathHandler_.registerHandler( xpathCtxt_.get( ) ); } } XPathCtxt( XPathCtxt &&xpathCtxt ) : xml_{std::move( xpathCtxt.xml_ )}, xpathCtxt_{std::move( xpathCtxt.xpathCtxt_ )}, xpathHandler_{std::move( xpathCtxt.xpathHandler_ )} {} auto operator=( const XPathCtxt &rhs ) -> XPathCtxt & { if ( this != &rhs ) { xml_ = rhs.xml_; if ( rhs ) { xpathCtxt_.reset( xmlXPathNewContext( xml_.xmlDoc_.get( ) ) ); xpathHandler_ = rhs.xpathHandler_; } else { xpathCtxt_.reset( nullptr ); } } return *this; } auto operator=( XPathCtxt &&xpathCtxt ) -> XPathCtxt & { xml_ = std::move( xpathCtxt.xml_ ); xpathCtxt_ = std::move( xpathCtxt.xpathCtxt_ ); xpathHandler_ = std::move( xpathCtxt.xpathHandler_ ); return *this; } explicit operator bool( ) const { return ( xpathCtxt_ != nullptr && xpathCtxt_->doc != nullptr ); } friend auto operator>>( const XmlDoc &xml, XPathCtxt &xpathCtxt ) -> XPathCtxt & { xpathCtxt.xml_ = xml; xpathCtxt.xpathCtxt_.reset( xmlXPathNewContext( xpathCtxt.xml_.xmlDoc_.get( ) ) ); xpathCtxt.xpathHandler_.registerHandler( xpathCtxt.xpathCtxt_.get( ) ); // ist this correct? return xpathCtxt; } auto errorHandler( ) const -> const IErrorHandler & { return xpathHandler_; } private: XmlDoc xml_; using XPathCtxtT = std::unique_ptr<xmlXPathContext, FreeXPathCtxt>; XPathCtxtT xpathCtxt_; XPathErrorHandler xpathHandler_; }; <commit_msg>Fixed initialisation bug<commit_after>#pragma once #include "xml_doc.hpp" #include "libxml2_error_handlers.hpp" #include <libxml/xpath.h> #include <memory> #include <iostream> class FreeXPathCtxt { public: auto operator( )( xmlXPathContext *xpathCtxt ) const -> void { xmlXPathFreeContext( xpathCtxt ); } }; class XPathCtxt { friend class XPathQuery; public: XPathCtxt( ) : xpathCtxt_{nullptr} {} explicit XPathCtxt( const XmlDoc &xml ) : xpathCtxt_{xmlXPathNewContext( xml.xmlDoc_.get( ) )}, xml_{xml} { xpathHandler_.registerHandler( xpathCtxt_.get( ) ); } XPathCtxt( const XPathCtxt &xpathCtxt ) : xml_{xpathCtxt.xml_} { if ( xpathCtxt ) { xpathCtxt_.reset( xmlXPathNewContext( xpathCtxt.xml_.xmlDoc_.get( ) ) ); xpathHandler_.registerHandler( xpathCtxt_.get( ) ); } } XPathCtxt( XPathCtxt &&xpathCtxt ) : xpathCtxt_{std::move( xpathCtxt.xpathCtxt_ )}, xml_{std::move( xpathCtxt.xml_ )}, xpathHandler_{std::move( xpathCtxt.xpathHandler_ )} {} auto operator=( const XPathCtxt &rhs ) -> XPathCtxt & { if ( this != &rhs ) { xml_ = rhs.xml_; if ( rhs ) { xpathCtxt_.reset( xmlXPathNewContext( rhs.xml_.xmlDoc_.get( ) ) ); xpathHandler_ = rhs.xpathHandler_; } else { xpathCtxt_.reset( nullptr ); } } return *this; } auto operator=( XPathCtxt &&xpathCtxt ) -> XPathCtxt & { xml_ = std::move( xpathCtxt.xml_ ); xpathCtxt_ = std::move( xpathCtxt.xpathCtxt_ ); xpathHandler_ = std::move( xpathCtxt.xpathHandler_ ); return *this; } explicit operator bool( ) const { return ( xpathCtxt_ != nullptr && xpathCtxt_->doc != nullptr ); } friend auto operator>>( const XmlDoc &xml, XPathCtxt &xpathCtxt ) -> XPathCtxt & { xpathCtxt.xml_ = xml; xpathCtxt.xpathCtxt_.reset( xmlXPathNewContext( xpathCtxt.xml_.xmlDoc_.get( ) ) ); xpathCtxt.xpathHandler_.registerHandler( xpathCtxt.xpathCtxt_.get( ) ); // ist this correct? return xpathCtxt; } auto errorHandler( ) const -> const IErrorHandler & { return xpathHandler_; } private: using XPathCtxtT = std::unique_ptr<xmlXPathContext, FreeXPathCtxt>; XPathCtxtT xpathCtxt_; XmlDoc xml_; XPathErrorHandler xpathHandler_; }; <|endoftext|>
<commit_before>// // libavg - Media Playback Engine. // Copyright (C) 2003-2006 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "Filterflipuv.h" #include "Pixeldefs.h" #include <assert.h> namespace avg { FilterFlipUV::FilterFlipUV() : Filter() { } FilterFlipUV::~FilterFlipUV() { } void FilterFlipUV::applyInPlace(BitmapPtr pBmp) const { PixelFormat PF = pBmp->getPixelFormat(); assert(pBmp->getPixelFormat() == YCbCr422); for (int y = 0; y < pBmp->getSize().y; y++) { unsigned char * pLine = pBmp->getPixels()+y*pBmp->getStride(); for (int x = 0; x < pBmp->getSize().x/2; x++) { unsigned char tmp = pLine[x*4+1]; pLine[x*4+1] = pLine[x*4+3]; pLine[x*4+3] = tmp; } } } } // namespace <commit_msg>Fixed compiler warning.<commit_after>// // libavg - Media Playback Engine. // Copyright (C) 2003-2006 Ulrich von Zadow // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Current versions can be found at www.libavg.de // #include "Filterflipuv.h" #include "Pixeldefs.h" #include <assert.h> namespace avg { FilterFlipUV::FilterFlipUV() : Filter() { } FilterFlipUV::~FilterFlipUV() { } void FilterFlipUV::applyInPlace(BitmapPtr pBmp) const { assert(pBmp->getPixelFormat() == YCbCr422); for (int y = 0; y < pBmp->getSize().y; y++) { unsigned char * pLine = pBmp->getPixels()+y*pBmp->getStride(); for (int x = 0; x < pBmp->getSize().x/2; x++) { unsigned char tmp = pLine[x*4+1]; pLine[x*4+1] = pLine[x*4+3]; pLine[x*4+3] = tmp; } } } } // namespace <|endoftext|>
<commit_before>/* * CLDevice.hpp * * Created on: Oct 24, 2009 * Author: Craig Rasmussen */ #ifndef CLDEVICE_HPP_ #define CLDEVICE_HPP_ #include "pv_opencl.h" #include <stdlib.h> #define CL_DEVICE_DEFAULT 1 //////////////////////////////////////////////////////////////////////////////// namespace PV { class CLBuffer; class CLKernel; class CLDevice { protected: int device_id; // device id (normally 0 for GPU, 1 for CPU) public: CLDevice(int device); int initialize(int device); static void print_error_code(int code); int id() { return device_id; } CLBuffer * createBuffer(cl_mem_flags flags, size_t size, void * host_ptr); CLBuffer * createReadBuffer(size_t size) { return createBuffer(CL_MEM_READ_ONLY, size, NULL); } CLBuffer * createWriteBuffer(size_t size) { return createBuffer(CL_MEM_WRITE_ONLY, size, NULL); } CLBuffer * createBuffer(size_t size, void * host_ptr) { return createBuffer(CL_MEM_USE_HOST_PTR, size, host_ptr); } CLKernel * createKernel(const char * filename, const char * name); // int copyResultsBuffer(cl_mem output, void * results, size_t size); int query_device_info(); int query_device_info(int id, cl_device_id device); protected: cl_uint num_devices; // number of computing devices cl_device_id device_ids[MAX_DEVICES]; // compute device id cl_context context; // compute context cl_command_queue commands; // compute command queue }; } // namespace PV #endif /* CLDEVICE_HPP_ */ <commit_msg>Added destructor for exit TAU profiling.<commit_after>/* * CLDevice.hpp * * Created on: Oct 24, 2009 * Author: Craig Rasmussen */ #ifndef CLDEVICE_HPP_ #define CLDEVICE_HPP_ #include "pv_opencl.h" #include <stdlib.h> #define CL_DEVICE_DEFAULT 1 //////////////////////////////////////////////////////////////////////////////// namespace PV { class CLBuffer; class CLKernel; class CLDevice { protected: int device_id; // device id (normally 0 for GPU, 1 for CPU) public: CLDevice(int device); virtual ~CLDevice(); int initialize(int device); static void print_error_code(int code); int id() { return device_id; } CLBuffer * createBuffer(cl_mem_flags flags, size_t size, void * host_ptr); CLBuffer * createReadBuffer(size_t size) { return createBuffer(CL_MEM_READ_ONLY, size, NULL); } CLBuffer * createWriteBuffer(size_t size) { return createBuffer(CL_MEM_WRITE_ONLY, size, NULL); } CLBuffer * createBuffer(size_t size, void * host_ptr) { return createBuffer(CL_MEM_USE_HOST_PTR, size, host_ptr); } CLKernel * createKernel(const char * filename, const char * name); // int copyResultsBuffer(cl_mem output, void * results, size_t size); int query_device_info(); int query_device_info(int id, cl_device_id device); protected: cl_uint num_devices; // number of computing devices cl_device_id device_ids[MAX_DEVICES]; // compute device id cl_context context; // compute context cl_command_queue commands; // compute command queue }; } // namespace PV #endif /* CLDEVICE_HPP_ */ <|endoftext|>
<commit_before>/* The MIT License (MIT) Copyright (c) [2016] [BTC.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. */ #include "StratumServerGrin.h" #include "StratumSessionGrin.h" #include "CommonGrin.h" #include <boost/make_unique.hpp> #include <algorithm> unique_ptr<StratumSession> StratumServerGrin::createConnection( struct bufferevent *bev, struct sockaddr *saddr, uint32_t sessionID) { return boost::make_unique<StratumSessionGrin>(*this, bev, saddr, sessionID); } void StratumServerGrin::checkAndUpdateShare( size_t chainId, ShareGrin &share, shared_ptr<StratumJobEx> exjob, const vector<uint64_t > &proofs, const std::set<uint64_t> &jobDiffs, const string &workFullName, uint256 &blockHash) { auto sjob = dynamic_cast<StratumJobGrin *>(exjob->sjob_); DLOG(INFO) << "checking share nonce: " << std::hex << share.nonce() << ", pre_pow: " << sjob->prePowStr_ << ", edge_bits: " << share.edgebits(); if (exjob->isStale()) { share.set_status(StratumStatus::JOB_NOT_FOUND); return; } PreProofGrin preProof; preProof.prePow = sjob->prePow_; preProof.nonce = share.nonce(); if (!VerifyPowGrin(preProof, share.edgebits(), proofs)) { share.set_status(StratumStatus::INVALID_SOLUTION); return; } blockHash = PowHashGrin(share.height(), share.edgebits(), preProof.prePow.secondaryScaling.value(), proofs); share.set_hashprefix(blockHash.GetCheapHash()); uint64_t scaledShareDiff = PowDifficultyGrin(share.height(), share.edgebits(), preProof.prePow.secondaryScaling.value(), proofs); DLOG(INFO) << "compare share difficulty: " << scaledShareDiff << ", network difficulty: " << sjob->difficulty_; // print out high diff share if (scaledShareDiff / sjob->difficulty_ >= 1024) { LOG(INFO) << "high diff share, share difficulty: " << scaledShareDiff << ", network difficulty: " << sjob->difficulty_ << ", worker: " << workFullName; } if (isSubmitInvalidBlock_ || scaledShareDiff >= sjob->difficulty_) { LOG(INFO) << "solution found, share difficulty: " << scaledShareDiff << ", network difficulty: " << sjob->difficulty_ << ", worker: " << workFullName; share.set_status(StratumStatus::SOLVED); LOG(INFO) << "solved share: " << share.toString(); return; } // higher difficulty is prior for (auto itr = jobDiffs.rbegin(); itr != jobDiffs.rend(); itr++) { uint64_t jobDiff = *itr; uint64_t scaledJobDiff = jobDiff * share.scaling(); DLOG(INFO) << "compare share difficulty: " << scaledShareDiff << ", job difficulty: " << scaledJobDiff; if (isEnableSimulator_ || scaledShareDiff >= scaledJobDiff) { share.set_sharediff(jobDiff); share.set_status(StratumStatus::ACCEPT); return; } } share.set_status(StratumStatus::LOW_DIFFICULTY); return; } void StratumServerGrin::sendSolvedShare2Kafka( size_t chainId, const ShareGrin &share, shared_ptr<StratumJobEx> exjob, const vector<uint64_t> &proofs, const StratumWorker &worker, const uint256 &blockHash) { string proofArray; if (!proofs.empty()) { proofArray = std::accumulate( std::next(proofs.begin()), proofs.end(), std::to_string(proofs.front()), [](string a, int b) { return std::move(a) + "," + std::to_string(b); }); } auto sjob = dynamic_cast<StratumJobGrin *>(exjob->sjob_); string blockHashStr; Bin2Hex(blockHash.begin(), blockHash.size(), blockHashStr); string msg = Strings::Format( "{\"prePow\":\"%s\"" ",\"height\":%" PRIu64 ",\"edgeBits\":%" PRIu32 ",\"nonce\":%" PRIu64 ",\"proofs\":[%s]" ",\"userId\":%" PRId32 ",\"workerId\":%" PRId64 ",\"workerFullName\":\"%s\"" ",\"blockHash\":\"%s\"" "}", sjob->prePowStr_.c_str(), sjob->height_, share.edgebits(), share.nonce(), proofArray.c_str(), worker.userId(chainId), worker.workerHashId_, filterWorkerName(worker.fullName_).c_str(), blockHashStr.c_str()); ServerBase::sendSolvedShare2Kafka(chainId, msg.c_str(), msg.length()); } JobRepository* StratumServerGrin::createJobRepository( size_t chainId, const char *kafkaBrokers, const char *consumerTopic, const string &fileLastNotifyTime) { return new JobRepositoryGrin{chainId, this, kafkaBrokers, consumerTopic, fileLastNotifyTime}; } JobRepositoryGrin::JobRepositoryGrin( size_t chainId, StratumServerGrin *server, const char *kafkaBrokers, const char *consumerTopic, const string &fileLastNotifyTime) : JobRepositoryBase{chainId, server, kafkaBrokers, consumerTopic, fileLastNotifyTime} , lastHeight_{0} { } StratumJob* JobRepositoryGrin::createStratumJob() { return new StratumJobGrin; } void JobRepositoryGrin::broadcastStratumJob(StratumJob *sjob) { auto sjobGrin = dynamic_cast<StratumJobGrin*>(sjob); LOG(INFO) << "broadcast stratum job " << std::hex << sjobGrin->jobId_; bool isClean = false; if (sjobGrin->height_ != lastHeight_) { isClean = true; lastHeight_ = sjobGrin->height_; LOG(INFO) << "received new height stratum job, height: " << sjobGrin->height_ << ", prePow: " << sjobGrin->prePowStr_; } shared_ptr<StratumJobEx> exJob{createStratumJobEx(sjobGrin, isClean)}; { ScopeLock sl(lock_); if (isClean) { // mark all jobs as stale, should do this before insert new job // stale shares will not be rejected, they will be marked as ACCEPT_STALE and have lower rewards. for (auto it : exJobs_) { it.second->markStale(); } // Grin miners do not like frequent job switching, hence we only send jobs: // - when there is a new height // - when miner calls getjobtemplate // - when mining notify interval expires sendMiningNotify(exJob); } // insert new job exJobs_[sjobGrin->jobId_] = exJob; } } <commit_msg>Grin fix potential race condition<commit_after>/* The MIT License (MIT) Copyright (c) [2016] [BTC.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. */ #include "StratumServerGrin.h" #include "StratumSessionGrin.h" #include "CommonGrin.h" #include <boost/make_unique.hpp> #include <algorithm> unique_ptr<StratumSession> StratumServerGrin::createConnection( struct bufferevent *bev, struct sockaddr *saddr, uint32_t sessionID) { return boost::make_unique<StratumSessionGrin>(*this, bev, saddr, sessionID); } void StratumServerGrin::checkAndUpdateShare( size_t chainId, ShareGrin &share, shared_ptr<StratumJobEx> exjob, const vector<uint64_t > &proofs, const std::set<uint64_t> &jobDiffs, const string &workFullName, uint256 &blockHash) { auto sjob = dynamic_cast<StratumJobGrin *>(exjob->sjob_); DLOG(INFO) << "checking share nonce: " << std::hex << share.nonce() << ", pre_pow: " << sjob->prePowStr_ << ", edge_bits: " << share.edgebits(); if (exjob->isStale()) { share.set_status(StratumStatus::JOB_NOT_FOUND); return; } PreProofGrin preProof; preProof.prePow = sjob->prePow_; preProof.nonce = share.nonce(); if (!VerifyPowGrin(preProof, share.edgebits(), proofs)) { share.set_status(StratumStatus::INVALID_SOLUTION); return; } blockHash = PowHashGrin(share.height(), share.edgebits(), preProof.prePow.secondaryScaling.value(), proofs); share.set_hashprefix(blockHash.GetCheapHash()); uint64_t scaledShareDiff = PowDifficultyGrin(share.height(), share.edgebits(), preProof.prePow.secondaryScaling.value(), proofs); DLOG(INFO) << "compare share difficulty: " << scaledShareDiff << ", network difficulty: " << sjob->difficulty_; // print out high diff share if (scaledShareDiff / sjob->difficulty_ >= 1024) { LOG(INFO) << "high diff share, share difficulty: " << scaledShareDiff << ", network difficulty: " << sjob->difficulty_ << ", worker: " << workFullName; } if (isSubmitInvalidBlock_ || scaledShareDiff >= sjob->difficulty_) { LOG(INFO) << "solution found, share difficulty: " << scaledShareDiff << ", network difficulty: " << sjob->difficulty_ << ", worker: " << workFullName; share.set_status(StratumStatus::SOLVED); LOG(INFO) << "solved share: " << share.toString(); return; } // higher difficulty is prior for (auto itr = jobDiffs.rbegin(); itr != jobDiffs.rend(); itr++) { uint64_t jobDiff = *itr; uint64_t scaledJobDiff = jobDiff * share.scaling(); DLOG(INFO) << "compare share difficulty: " << scaledShareDiff << ", job difficulty: " << scaledJobDiff; if (isEnableSimulator_ || scaledShareDiff >= scaledJobDiff) { share.set_sharediff(jobDiff); share.set_status(StratumStatus::ACCEPT); return; } } share.set_status(StratumStatus::LOW_DIFFICULTY); return; } void StratumServerGrin::sendSolvedShare2Kafka( size_t chainId, const ShareGrin &share, shared_ptr<StratumJobEx> exjob, const vector<uint64_t> &proofs, const StratumWorker &worker, const uint256 &blockHash) { string proofArray; if (!proofs.empty()) { proofArray = std::accumulate( std::next(proofs.begin()), proofs.end(), std::to_string(proofs.front()), [](string a, int b) { return std::move(a) + "," + std::to_string(b); }); } auto sjob = dynamic_cast<StratumJobGrin *>(exjob->sjob_); string blockHashStr; Bin2Hex(blockHash.begin(), blockHash.size(), blockHashStr); string msg = Strings::Format( "{\"prePow\":\"%s\"" ",\"height\":%" PRIu64 ",\"edgeBits\":%" PRIu32 ",\"nonce\":%" PRIu64 ",\"proofs\":[%s]" ",\"userId\":%" PRId32 ",\"workerId\":%" PRId64 ",\"workerFullName\":\"%s\"" ",\"blockHash\":\"%s\"" "}", sjob->prePowStr_.c_str(), sjob->height_, share.edgebits(), share.nonce(), proofArray.c_str(), worker.userId(chainId), worker.workerHashId_, filterWorkerName(worker.fullName_).c_str(), blockHashStr.c_str()); ServerBase::sendSolvedShare2Kafka(chainId, msg.c_str(), msg.length()); } JobRepository* StratumServerGrin::createJobRepository( size_t chainId, const char *kafkaBrokers, const char *consumerTopic, const string &fileLastNotifyTime) { return new JobRepositoryGrin{chainId, this, kafkaBrokers, consumerTopic, fileLastNotifyTime}; } JobRepositoryGrin::JobRepositoryGrin( size_t chainId, StratumServerGrin *server, const char *kafkaBrokers, const char *consumerTopic, const string &fileLastNotifyTime) : JobRepositoryBase{chainId, server, kafkaBrokers, consumerTopic, fileLastNotifyTime} , lastHeight_{0} { } StratumJob* JobRepositoryGrin::createStratumJob() { return new StratumJobGrin; } void JobRepositoryGrin::broadcastStratumJob(StratumJob *sjob) { auto sjobGrin = dynamic_cast<StratumJobGrin*>(sjob); LOG(INFO) << "broadcast stratum job " << std::hex << sjobGrin->jobId_; bool isClean = false; if (sjobGrin->height_ != lastHeight_) { isClean = true; lastHeight_ = sjobGrin->height_; LOG(INFO) << "received new height stratum job, height: " << sjobGrin->height_ << ", prePow: " << sjobGrin->prePowStr_; } shared_ptr<StratumJobEx> exJob{createStratumJobEx(sjobGrin, isClean)}; { ScopeLock sl(lock_); if (isClean) { // mark all jobs as stale, should do this before insert new job // stale shares will not be rejected, they will be marked as ACCEPT_STALE and have lower rewards. for (auto it : exJobs_) { it.second->markStale(); } } // insert new job exJobs_[sjobGrin->jobId_] = exJob; } // sending data in lock scope may cause implicit race condition in libevent if (isClean) { // Grin miners do not like frequent job switching, hence we only send jobs: // - when there is a new height // - when miner calls getjobtemplate // - when mining notify interval expires sendMiningNotify(exJob); } } <|endoftext|>
<commit_before>#include "StageCanvas.h" #include "ViewFrustum.h" #include <ee/panel_msg.h> #include <ee/Exception.h> #include <ee/ExceptionDlg.h> #include <node3/RenderCtxStack.h> #include <gum/RenderContext.h> namespace e3d { StageCanvas::StageCanvas(wxWindow* stage_wnd, ee::EditPanelImpl* stage) : ee::OnePassCanvas(stage_wnd, stage, nullptr, true, true) , m_cam_uvn(sm::vec3(0, 0, -2), sm::vec3(0, 0, 0), sm::vec3(0, 1, 0)) { } void StageCanvas::Refresh() { auto ctx = n3::RenderCtxStack::Instance()->Top(); if (ctx) { const_cast<n3::RenderContext*>(ctx)->SetModelView(GetCameraUVN().GetModelViewMat()); } ee::SetCanvasDirtySJ::Instance()->SetDirty(); } sm::vec2 StageCanvas::TransPos3ProjectToScreen(const sm::vec3& proj) const { sm::mat4 mat_modelview = GetCameraUVN().GetModelViewMat(); sm::vec3 v0 = mat_modelview * proj; sm::vec3 v1 = m_mat_projection * v0; v1.z = v0.z; return ViewFrustum::TransPos3ProjectToScreen(v1, m_width, m_height); } void StageCanvas::OnSize(int w, int h) { auto ctx = const_cast<n3::RenderContext*>(n3::RenderCtxStack::Instance()->Top()); if (!ctx) { return; } // m_cam_uvn.SetScreenSize(w, h); ctx->SetScreen(w, h); float hh = 1.0f * h / w; const float CAM_NEAR = 1; const float CAM_FAR = 3; //const float CAM_NEAR = 0.1f; //const float CAM_FAR = 100; auto mat_proj = sm::mat4::Perspective(-1, 1, -hh, hh, CAM_NEAR, CAM_FAR); ctx->SetProjection(mat_proj); } }<commit_msg>[FIXED] calc cam's proj mat<commit_after>#include "StageCanvas.h" #include "ViewFrustum.h" #include <ee/panel_msg.h> #include <ee/Exception.h> #include <ee/ExceptionDlg.h> #include <node3/RenderCtxStack.h> #include <gum/RenderContext.h> namespace e3d { StageCanvas::StageCanvas(wxWindow* stage_wnd, ee::EditPanelImpl* stage) : ee::OnePassCanvas(stage_wnd, stage, nullptr, true, true) , m_cam_uvn(sm::vec3(0, 0, -2), sm::vec3(0, 0, 0), sm::vec3(0, 1, 0)) { } void StageCanvas::Refresh() { auto ctx = n3::RenderCtxStack::Instance()->Top(); if (ctx) { const_cast<n3::RenderContext*>(ctx)->SetModelView(GetCameraUVN().GetModelViewMat()); } ee::SetCanvasDirtySJ::Instance()->SetDirty(); } sm::vec2 StageCanvas::TransPos3ProjectToScreen(const sm::vec3& proj) const { sm::mat4 mat_modelview = GetCameraUVN().GetModelViewMat(); sm::vec3 v0 = mat_modelview * proj; sm::vec3 v1 = m_mat_projection * v0; v1.z = v0.z; return ViewFrustum::TransPos3ProjectToScreen(v1, m_width, m_height); } void StageCanvas::OnSize(int w, int h) { auto ctx = const_cast<n3::RenderContext*>(n3::RenderCtxStack::Instance()->Top()); if (!ctx) { return; } // m_cam_uvn.SetScreenSize(w, h); ctx->SetScreen(w, h); static const float ZNEAR = 0.1f; static const float ZFAR = 100; static const float ANGLE_OF_VIEW = 90; const float ASPECT = w / (float)h; ////////////////////////////////////////////////////////////////////////// float scale = tan(ANGLE_OF_VIEW * 0.5 * SM_DEG_TO_RAD) * ZNEAR; auto mat_proj = sm::mat4::Perspective(- ASPECT * scale, ASPECT * scale, -scale, scale, ZNEAR, ZFAR); ////////////////////////////////////////////////////////////////////////// // auto mat_proj = sm::mat4::Perspective(ANGLE_OF_VIEW, ASPECT, ZNEAR, ZFAR); ////////////////////////////////////////////////////////////////////////// ctx->SetProjection(mat_proj); } }<|endoftext|>
<commit_before><commit_msg>gui: correct net descriptor sink/source for bterms<commit_after><|endoftext|>
<commit_before>#include "ActionNodeModel.hpp" #include "ConditionNodeModel.hpp" #include "LuaNodeModel.h" #include <QTextEdit> #include <QBoxLayout> #include <QFormLayout> #include <QLineEdit> #include <QDebug> #include <QFile> #include <QDomDocument> #include <QEvent> #include <iostream> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) #include <windows.h> #else #include <dirent.h> //dirent would also work for windows to find file in a directory but <windows.h> has a better font #endif #include <fstream> QStringList LuaNodeModel::get_all_files_names_within_folder(std::string folder, std::string type) { QStringList names; std::string search_path = folder + "/"+type+"*.lua"; #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) //OS is windows WIN32_FIND_DATA fd; HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd); if(hFind != INVALID_HANDLE_VALUE) { do { // read all (real) files in current folder // , delete '!' read other 2 default folder . and .. if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) { names.push_back(QString(fd.cFileName)); } }while(::FindNextFile(hFind, &fd)); ::FindClose(hFind); } #else //OS is unix DIR *dir; struct dirent *ent; if ((dir = opendir (search_path.c_str())) != NULL) { /* print all the files and directories within directory */ while ((ent = readdir (dir)) != NULL) { names.push_back(QString(ent->d_name)); } closedir (dir); } else { /* could not open directory */ perror (""); } #endif return names; } LuaNodeModel::LuaNodeModel(QString name, const NodeFactory::ParametersModel& parameter_model): BehaviorTreeNodeModel(name, parameter_model), _parameter_model(parameter_model) { _main_widget = new QWidget; _label = new QLabel( _main_widget ); _ID_selection_combobox = new QComboBox(_main_widget); std::cout << "combobox created" << std::endl; _label->setText( name ); QVBoxLayout *main_layout = new QVBoxLayout( _main_widget ); QHBoxLayout *top_layout = new QHBoxLayout( ); //_line_edit = new QLineEdit(_main_widget); _text_edit = new QTextEdit (_main_widget); _text_edit->setTextColor(Qt::black); _text_edit->setReadOnly(true); _ID_selection_combobox->setStyleSheet("color: black; background-color: white"); //_line_edit->setStyleSheet("background-color: white"); _params_widget = new QWidget( _main_widget ); _form_layout = new QFormLayout( _params_widget ); top_layout->addWidget( _label ); top_layout->addWidget( _ID_selection_combobox ); main_layout->addLayout(top_layout); //main_layout->addWidget(_params_widget); //main_layout->addWidget(_line_edit); main_layout->addWidget(_text_edit); QStringList combo_items = get_all_files_names_within_folder(".", name.toStdString()); _ID_selection_combobox->addItems(combo_items); std::cout << "combobox items added" << std::endl; _ID_selection_combobox->setCurrentIndex(0); QFont font = _label->font(); font.setPointSize(10); font.setBold(true); _label->setFont(font); QPalette palette = _label->palette(); palette.setColor(_label->foregroundRole(), Qt::white); _label->setPalette(palette); _main_widget->setAttribute(Qt::WA_NoSystemBackground); _main_widget->setLayout( main_layout ); _form_layout->setHorizontalSpacing(5); _form_layout->setVerticalSpacing(2); _form_layout->setContentsMargins(0, 0, 0, 0); _params_widget->setStyleSheet("color: white;"); main_layout->setMargin(0); _main_widget->setStyleSheet("background-color: transparent; color: white; "); if(!combo_items.empty()) { onComboBoxUpdated(combo_items[0]); } // _text_edit->viewport()->installEventFilter(this); connect(_text_edit, SIGNAL(textChanged()),this, SLOT(onTextBoxUpdated())); // connect(_text_edit, SIGNAL(doubleClicked(const QModelIndex&)),this, // SLOT(onTextBoxUpdated())); connect(_ID_selection_combobox, SIGNAL(currentIndexChanged(QString)), this, SLOT(onComboBoxUpdated(QString)) ); } //bool LuaNodeModel::eventFilter(QObject* object, QEvent* event) //{ // if (event->type() == QEvent::MouseButtonDblClick) // { // std::cout << "Double click" << std::endl; // editor_.setWindowTitle(QObject::tr("Code Editor Example")); // editor_.show(); // std::cout << "Done!" << std::endl; // } // return true; //} QString LuaNodeModel::caption() const { return type(); } QString LuaNodeModel::type() const { return _ID_selection_combobox->currentText(); } QString LuaNodeModel::get_line_edit() { return _line_edit->text(); } QString LuaNodeModel::get_text_edit() { return _text_edit->toPlainText(); } void LuaNodeModel::lastComboItem() { _ID_selection_combobox->setCurrentIndex(3); } std::vector<std::pair<QString, QString>> LuaNodeModel::getCurrentParameters() const { std::vector<std::pair<QString, QString>> out; for(int row = 0; row < _form_layout->rowCount(); row++) { auto label_item = _form_layout->itemAt(row, QFormLayout::LabelRole); auto field_item = _form_layout->itemAt(row, QFormLayout::FieldRole); if( label_item && field_item ) { QLabel* label = static_cast<QLabel*>( label_item->widget() ); QLineEdit* line = dynamic_cast<QLineEdit*>( field_item->widget() ); QComboBox* combo = dynamic_cast<QComboBox*>( field_item->widget() ); if( line ){ out.push_back( { label->text(), line->text() } ); } else if( combo ) { out.push_back( { label->text(), combo->currentText() } ); } break; } } return out; } QJsonObject LuaNodeModel::save() const { QJsonObject nodeJson; nodeJson["type"] = type(); nodeJson["ID"] = caption(); return nodeJson; } void LuaNodeModel::restore(std::map<QString,QString> attributes) { // we expect to find at least two attributes, "name" and "ID". // Other nodes represent parameters. std::cout << "restoring: " << std::endl; { auto v_type = attributes.find("ID"); if ( v_type == attributes.end() ) { throw std::runtime_error("the TreeNodeModel needs a [ID] to be restored"); } const QString type_name = v_type->second; _ID_selection_combobox->setCurrentText( type_name ); onComboBoxUpdated( type_name ); attributes.erase(v_type); //-------------------------- auto v_name = attributes.find("name"); if ( v_name != attributes.end() ) { _ID = v_name->second; attributes.erase(v_name); } else{ _ID = v_type->second; } } for (auto it: attributes) { const QString& param_name = it.first; const QString& value = it.second; bool found = false; for(int row = 0; row < _form_layout->rowCount(); row++) { auto label_item = _form_layout->itemAt(row, QFormLayout::LabelRole); auto field_item = _form_layout->itemAt(row, QFormLayout::FieldRole); if( label_item && field_item ) { QLabel* label = static_cast<QLabel*>( label_item->widget() ); //----------------------------- if(label->text() == param_name) { QLineEdit* line = dynamic_cast<QLineEdit*>( field_item->widget() ); QComboBox* combo = dynamic_cast<QComboBox*>( field_item->widget() ); if( line ){ line->setText(value); found = true; } else if( combo ) { int res = combo->findText(value); if( res < 0) { qDebug() << "Error: the combo ["<< param_name << "] does not contain the value '"<< value ; } else { combo->setCurrentText(value); found = true; } } break; } } // end for if( !found ) { qDebug() << "Error: the parameter ["<< param_name << "] is not present in " << name() << " / " << type(); } } } } void LuaNodeModel::restore(const QJsonObject &nodeJson) { std::map<QString,QString> attributes; for(auto it = nodeJson.begin(); it != nodeJson.end(); it++ ) { attributes.insert( std::make_pair(it.key(), it.value().toString()) ); } restore(attributes); } void LuaNodeModel::lock(bool locked) { _ID_selection_combobox->setEnabled( !locked ); _text_edit->setEnabled(!locked); // for(int row = 0; row < _form_layout->rowCount(); row++) // { // auto field_item = _form_layout->itemAt(row, QFormLayout::FieldRole); // if( field_item ) // { // QLineEdit* line = dynamic_cast<QLineEdit*>( field_item->widget() ); // QComboBox* combo = dynamic_cast<QComboBox*>( field_item->widget() ); // if( line ){ // line->setReadOnly( locked ); // } // else if( combo ) // { // combo->setEnabled( !locked ); // } // } // } } //void LuaNodeModel::onComboBoxUpdated(QString item_text) //{ // while ( _form_layout->count() != 0) // { // QLayoutItem *forDeletion = _form_layout->takeAt(0); // delete forDeletion->widget(); // delete forDeletion; // } // int row = 0; // //TODO: check if found // const auto& params = _parameter_model.at(item_text); // _params_widget->setVisible( params.size() > 0); // for(const NodeFactory::ParamWidget& param: params ) // { // QWidget* field_widget = param.instance_factory(); // field_widget->setStyleSheet("color: white; background-color: gray; border: 1px solid #FFFFFF"); // _form_layout->setWidget(row, QFormLayout::LabelRole, new QLabel( param.label, _params_widget )); // _form_layout->setWidget(row, QFormLayout::FieldRole, field_widget); // row++; // } // _params_widget->adjustSize(); // _main_widget->adjustSize(); // emit adjustSize(); //} void LuaNodeModel::onComboBoxUpdated(QString item_text) { std::ifstream file(item_text.toStdString()); std::string str; std::string file_contents; while (std::getline(file, str)) { file_contents += str; file_contents.push_back('\n'); } _text_edit->setText(file_contents.c_str()); } void LuaNodeModel::onCodeUpdated() { std::ifstream file(filename().c_str()); std::string str; std::string file_contents; while (std::getline(file, str)) { file_contents += str; file_contents.push_back('\n'); } _text_edit->setText(file_contents.c_str()); } void LuaNodeModel::onTextBoxUpdated() { //std::cout << "not saving file, edit LuaNodeModel::onTextBoxUpdated" << std::endl; return; // std::ofstream myfile; // myfile.open (_ID_selection_combobox->currentText().toStdString().c_str()); // myfile << _text_edit->toPlainText().toStdString().c_str(); // myfile.close(); // std::cout << "new data added" << std::endl; } std::string LuaNodeModel::filename() { return _ID_selection_combobox->currentText().toStdString(); } <commit_msg>added regex for unix<commit_after>#include "ActionNodeModel.hpp" #include "ConditionNodeModel.hpp" #include "LuaNodeModel.h" #include <QTextEdit> #include <QBoxLayout> #include <QFormLayout> #include <QLineEdit> #include <QDebug> #include <QFile> #include <QDomDocument> #include <QEvent> #include <iostream> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) #include <windows.h> #else #include <dirent.h> //dirent could also work for windows to find file in a directory but <windows.h> has a better font #include <regex> #endif #include <fstream> QStringList LuaNodeModel::get_all_files_names_within_folder(std::string folder, std::string type) { QStringList names; std::string search_path = folder + "/"+type+"*.lua"; #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) //OS is windows WIN32_FIND_DATA fd; HANDLE hFind = ::FindFirstFile(search_path.c_str(), &fd); if(hFind != INVALID_HANDLE_VALUE) { do { // read all (real) files in current folder // , delete '!' read other 2 default folder . and .. if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) { names.push_back(QString(fd.cFileName)); } }while(::FindNextFile(hFind, &fd)); ::FindClose(hFind); } #else //OS is unix DIR *dir; struct dirent *ent; std::regex txt_regex(search_path.c_str()); if ((dir = opendir (folder)) != NULL) { /* print all the files and directories within directory */ while ((ent = readdir (dir)) != NULL) { if(std::regex_match(ent->d_name, txt_regex)) { names.push_back(QString(ent->d_name)); } } closedir (dir); } else { /* could not open directory */ perror (""); } #endif return names; } LuaNodeModel::LuaNodeModel(QString name, const NodeFactory::ParametersModel& parameter_model): BehaviorTreeNodeModel(name, parameter_model), _parameter_model(parameter_model) { _main_widget = new QWidget; _label = new QLabel( _main_widget ); _ID_selection_combobox = new QComboBox(_main_widget); std::cout << "combobox created" << std::endl; _label->setText( name ); QVBoxLayout *main_layout = new QVBoxLayout( _main_widget ); QHBoxLayout *top_layout = new QHBoxLayout( ); //_line_edit = new QLineEdit(_main_widget); _text_edit = new QTextEdit (_main_widget); _text_edit->setTextColor(Qt::black); _text_edit->setReadOnly(true); _ID_selection_combobox->setStyleSheet("color: black; background-color: white"); //_line_edit->setStyleSheet("background-color: white"); _params_widget = new QWidget( _main_widget ); _form_layout = new QFormLayout( _params_widget ); top_layout->addWidget( _label ); top_layout->addWidget( _ID_selection_combobox ); main_layout->addLayout(top_layout); //main_layout->addWidget(_params_widget); //main_layout->addWidget(_line_edit); main_layout->addWidget(_text_edit); QStringList combo_items = get_all_files_names_within_folder(".", name.toStdString()); _ID_selection_combobox->addItems(combo_items); std::cout << "combobox items added" << std::endl; _ID_selection_combobox->setCurrentIndex(0); QFont font = _label->font(); font.setPointSize(10); font.setBold(true); _label->setFont(font); QPalette palette = _label->palette(); palette.setColor(_label->foregroundRole(), Qt::white); _label->setPalette(palette); _main_widget->setAttribute(Qt::WA_NoSystemBackground); _main_widget->setLayout( main_layout ); _form_layout->setHorizontalSpacing(5); _form_layout->setVerticalSpacing(2); _form_layout->setContentsMargins(0, 0, 0, 0); _params_widget->setStyleSheet("color: white;"); main_layout->setMargin(0); _main_widget->setStyleSheet("background-color: transparent; color: white; "); if(!combo_items.empty()) { onComboBoxUpdated(combo_items[0]); } // _text_edit->viewport()->installEventFilter(this); connect(_text_edit, SIGNAL(textChanged()),this, SLOT(onTextBoxUpdated())); // connect(_text_edit, SIGNAL(doubleClicked(const QModelIndex&)),this, // SLOT(onTextBoxUpdated())); connect(_ID_selection_combobox, SIGNAL(currentIndexChanged(QString)), this, SLOT(onComboBoxUpdated(QString)) ); } //bool LuaNodeModel::eventFilter(QObject* object, QEvent* event) //{ // if (event->type() == QEvent::MouseButtonDblClick) // { // std::cout << "Double click" << std::endl; // editor_.setWindowTitle(QObject::tr("Code Editor Example")); // editor_.show(); // std::cout << "Done!" << std::endl; // } // return true; //} QString LuaNodeModel::caption() const { return type(); } QString LuaNodeModel::type() const { return _ID_selection_combobox->currentText(); } QString LuaNodeModel::get_line_edit() { return _line_edit->text(); } QString LuaNodeModel::get_text_edit() { return _text_edit->toPlainText(); } void LuaNodeModel::lastComboItem() { _ID_selection_combobox->setCurrentIndex(3); } std::vector<std::pair<QString, QString>> LuaNodeModel::getCurrentParameters() const { std::vector<std::pair<QString, QString>> out; for(int row = 0; row < _form_layout->rowCount(); row++) { auto label_item = _form_layout->itemAt(row, QFormLayout::LabelRole); auto field_item = _form_layout->itemAt(row, QFormLayout::FieldRole); if( label_item && field_item ) { QLabel* label = static_cast<QLabel*>( label_item->widget() ); QLineEdit* line = dynamic_cast<QLineEdit*>( field_item->widget() ); QComboBox* combo = dynamic_cast<QComboBox*>( field_item->widget() ); if( line ){ out.push_back( { label->text(), line->text() } ); } else if( combo ) { out.push_back( { label->text(), combo->currentText() } ); } break; } } return out; } QJsonObject LuaNodeModel::save() const { QJsonObject nodeJson; nodeJson["type"] = type(); nodeJson["ID"] = caption(); return nodeJson; } void LuaNodeModel::restore(std::map<QString,QString> attributes) { // we expect to find at least two attributes, "name" and "ID". // Other nodes represent parameters. std::cout << "restoring: " << std::endl; { auto v_type = attributes.find("ID"); if ( v_type == attributes.end() ) { throw std::runtime_error("the TreeNodeModel needs a [ID] to be restored"); } const QString type_name = v_type->second; _ID_selection_combobox->setCurrentText( type_name ); onComboBoxUpdated( type_name ); attributes.erase(v_type); //-------------------------- auto v_name = attributes.find("name"); if ( v_name != attributes.end() ) { _ID = v_name->second; attributes.erase(v_name); } else{ _ID = v_type->second; } } for (auto it: attributes) { const QString& param_name = it.first; const QString& value = it.second; bool found = false; for(int row = 0; row < _form_layout->rowCount(); row++) { auto label_item = _form_layout->itemAt(row, QFormLayout::LabelRole); auto field_item = _form_layout->itemAt(row, QFormLayout::FieldRole); if( label_item && field_item ) { QLabel* label = static_cast<QLabel*>( label_item->widget() ); //----------------------------- if(label->text() == param_name) { QLineEdit* line = dynamic_cast<QLineEdit*>( field_item->widget() ); QComboBox* combo = dynamic_cast<QComboBox*>( field_item->widget() ); if( line ){ line->setText(value); found = true; } else if( combo ) { int res = combo->findText(value); if( res < 0) { qDebug() << "Error: the combo ["<< param_name << "] does not contain the value '"<< value ; } else { combo->setCurrentText(value); found = true; } } break; } } // end for if( !found ) { qDebug() << "Error: the parameter ["<< param_name << "] is not present in " << name() << " / " << type(); } } } } void LuaNodeModel::restore(const QJsonObject &nodeJson) { std::map<QString,QString> attributes; for(auto it = nodeJson.begin(); it != nodeJson.end(); it++ ) { attributes.insert( std::make_pair(it.key(), it.value().toString()) ); } restore(attributes); } void LuaNodeModel::lock(bool locked) { _ID_selection_combobox->setEnabled( !locked ); _text_edit->setEnabled(!locked); // for(int row = 0; row < _form_layout->rowCount(); row++) // { // auto field_item = _form_layout->itemAt(row, QFormLayout::FieldRole); // if( field_item ) // { // QLineEdit* line = dynamic_cast<QLineEdit*>( field_item->widget() ); // QComboBox* combo = dynamic_cast<QComboBox*>( field_item->widget() ); // if( line ){ // line->setReadOnly( locked ); // } // else if( combo ) // { // combo->setEnabled( !locked ); // } // } // } } //void LuaNodeModel::onComboBoxUpdated(QString item_text) //{ // while ( _form_layout->count() != 0) // { // QLayoutItem *forDeletion = _form_layout->takeAt(0); // delete forDeletion->widget(); // delete forDeletion; // } // int row = 0; // //TODO: check if found // const auto& params = _parameter_model.at(item_text); // _params_widget->setVisible( params.size() > 0); // for(const NodeFactory::ParamWidget& param: params ) // { // QWidget* field_widget = param.instance_factory(); // field_widget->setStyleSheet("color: white; background-color: gray; border: 1px solid #FFFFFF"); // _form_layout->setWidget(row, QFormLayout::LabelRole, new QLabel( param.label, _params_widget )); // _form_layout->setWidget(row, QFormLayout::FieldRole, field_widget); // row++; // } // _params_widget->adjustSize(); // _main_widget->adjustSize(); // emit adjustSize(); //} void LuaNodeModel::onComboBoxUpdated(QString item_text) { std::ifstream file(item_text.toStdString()); std::string str; std::string file_contents; while (std::getline(file, str)) { file_contents += str; file_contents.push_back('\n'); } _text_edit->setText(file_contents.c_str()); } void LuaNodeModel::onCodeUpdated() { std::ifstream file(filename().c_str()); std::string str; std::string file_contents; while (std::getline(file, str)) { file_contents += str; file_contents.push_back('\n'); } _text_edit->setText(file_contents.c_str()); } void LuaNodeModel::onTextBoxUpdated() { //std::cout << "not saving file, edit LuaNodeModel::onTextBoxUpdated" << std::endl; return; // std::ofstream myfile; // myfile.open (_ID_selection_combobox->currentText().toStdString().c_str()); // myfile << _text_edit->toPlainText().toStdString().c_str(); // myfile.close(); // std::cout << "new data added" << std::endl; } std::string LuaNodeModel::filename() { return _ID_selection_combobox->currentText().toStdString(); } <|endoftext|>
<commit_before>/* * Chrome Token Signing Native Host * * 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 "CngCapiSigner.h" #include "BinaryUtils.h" #include "HostExceptions.h" #include <Windows.h> #include <ncrypt.h> #include <WinCrypt.h> #include <cryptuiapi.h> using namespace std; string CngCapiSigner::sign() { BCRYPT_PKCS1_PADDING_INFO padInfo; DWORD obtainKeyStrategy = CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG; vector<unsigned char> digest = BinaryUtils::hex2bin(getHash()->c_str()); ALG_ID alg = 0; switch (digest.size()) { case BINARY_SHA1_LENGTH: padInfo.pszAlgId = NCRYPT_SHA1_ALGORITHM; alg = CALG_SHA1; break; case BINARY_SHA224_LENGTH: padInfo.pszAlgId = L"SHA224"; obtainKeyStrategy = CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG; break; case BINARY_SHA256_LENGTH: padInfo.pszAlgId = NCRYPT_SHA256_ALGORITHM; alg = CALG_SHA_256; break; case BINARY_SHA384_LENGTH: padInfo.pszAlgId = NCRYPT_SHA384_ALGORITHM; alg = CALG_SHA_384; break; case BINARY_SHA512_LENGTH: padInfo.pszAlgId = NCRYPT_SHA512_ALGORITHM; alg = CALG_SHA_512; break; default: throw InvalidHashException(); } SECURITY_STATUS err = 0; DWORD size = 256; vector<unsigned char> signature(size, 0); HCERTSTORE store = CertOpenSystemStore(0, L"MY"); if (!store) { throw TechnicalException("Failed to open Cert Store"); } vector<unsigned char> certInBinary = BinaryUtils::hex2bin(getCertInHex()->c_str()); PCCERT_CONTEXT certFromBinary = CertCreateCertificateContext(X509_ASN_ENCODING, &certInBinary[0], certInBinary.size()); PCCERT_CONTEXT certInStore = CertFindCertificateInStore(store, X509_ASN_ENCODING, 0, CERT_FIND_EXISTING, certFromBinary, 0); CertFreeCertificateContext(certFromBinary); if (!certInStore) { CertCloseStore(store, 0); throw NoCertificatesException(); } DWORD flags = obtainKeyStrategy | CRYPT_ACQUIRE_COMPARE_KEY_FLAG; DWORD spec = 0; BOOL freeKeyHandle = false; HCRYPTPROV_OR_NCRYPT_KEY_HANDLE key = NULL; BOOL gotKey = true; gotKey = CryptAcquireCertificatePrivateKey(certInStore, flags, 0, &key, &spec, &freeKeyHandle); CertFreeCertificateContext(certInStore); CertCloseStore(store, 0); switch (spec) { case CERT_NCRYPT_KEY_SPEC: { err = NCryptSignHash(key, &padInfo, PBYTE(&digest[0]), DWORD(digest.size()), &signature[0], DWORD(signature.size()), (DWORD*)&size, BCRYPT_PAD_PKCS1); if (freeKeyHandle) { NCryptFreeObject(key); } break; } case AT_SIGNATURE: { HCRYPTHASH hash = 0; if (!CryptCreateHash(key, alg, 0, 0, &hash)) { if (freeKeyHandle) { CryptReleaseContext(key, 0); } throw TechnicalException("CreateHash failed"); } if (!CryptSetHashParam(hash, HP_HASHVAL, digest.data(), 0)) { if (freeKeyHandle) { CryptReleaseContext(key, 0); } CryptDestroyHash(hash); throw TechnicalException("SetHashParam failed"); } CryptSignHashW(hash, AT_SIGNATURE, 0, 0, LPBYTE(signature.data()), &size); err = GetLastError(); if (freeKeyHandle) { CryptReleaseContext(key, 0); } CryptDestroyHash(hash); reverse(signature.begin(), signature.end()); break; } default: throw TechnicalException("Incompatible key"); } switch (err) { case ERROR_SUCCESS: break; case SCARD_W_CANCELLED_BY_USER: case ERROR_CANCELLED: throw UserCancelledException("Signing was cancelled"); case SCARD_W_CHV_BLOCKED: throw PinBlockedException(); case NTE_INVALID_HANDLE: throw TechnicalException("The supplied handle is invalid"); default: throw TechnicalException("Signing failed"); } signature.resize(size); return BinaryUtils::bin2hex(signature); } <commit_msg>fix capi signing so that error is only set to getLastError() when signing is not successful<commit_after>/* * Chrome Token Signing Native Host * * 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 "CngCapiSigner.h" #include "BinaryUtils.h" #include "HostExceptions.h" #include <Windows.h> #include <ncrypt.h> #include <WinCrypt.h> #include <cryptuiapi.h> #include "Logger.h" using namespace std; string CngCapiSigner::sign() { BCRYPT_PKCS1_PADDING_INFO padInfo; DWORD obtainKeyStrategy = CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG; vector<unsigned char> digest = BinaryUtils::hex2bin(getHash()->c_str()); ALG_ID alg = 0; switch (digest.size()) { case BINARY_SHA1_LENGTH: padInfo.pszAlgId = NCRYPT_SHA1_ALGORITHM; alg = CALG_SHA1; break; case BINARY_SHA224_LENGTH: padInfo.pszAlgId = L"SHA224"; obtainKeyStrategy = CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG; break; case BINARY_SHA256_LENGTH: padInfo.pszAlgId = NCRYPT_SHA256_ALGORITHM; alg = CALG_SHA_256; break; case BINARY_SHA384_LENGTH: padInfo.pszAlgId = NCRYPT_SHA384_ALGORITHM; alg = CALG_SHA_384; break; case BINARY_SHA512_LENGTH: padInfo.pszAlgId = NCRYPT_SHA512_ALGORITHM; alg = CALG_SHA_512; break; default: throw InvalidHashException(); } SECURITY_STATUS err = 0; DWORD size = 256; vector<unsigned char> signature(size, 0); HCERTSTORE store = CertOpenSystemStore(0, L"MY"); if (!store) { throw TechnicalException("Failed to open Cert Store"); } vector<unsigned char> certInBinary = BinaryUtils::hex2bin(getCertInHex()->c_str()); PCCERT_CONTEXT certFromBinary = CertCreateCertificateContext(X509_ASN_ENCODING, &certInBinary[0], certInBinary.size()); PCCERT_CONTEXT certInStore = CertFindCertificateInStore(store, X509_ASN_ENCODING, 0, CERT_FIND_EXISTING, certFromBinary, 0); CertFreeCertificateContext(certFromBinary); if (!certInStore) { CertCloseStore(store, 0); throw NoCertificatesException(); } DWORD flags = obtainKeyStrategy | CRYPT_ACQUIRE_COMPARE_KEY_FLAG; DWORD spec = 0; BOOL freeKeyHandle = false; HCRYPTPROV_OR_NCRYPT_KEY_HANDLE key = NULL; BOOL gotKey = true; gotKey = CryptAcquireCertificatePrivateKey(certInStore, flags, 0, &key, &spec, &freeKeyHandle); CertFreeCertificateContext(certInStore); CertCloseStore(store, 0); switch (spec) { case CERT_NCRYPT_KEY_SPEC: { err = NCryptSignHash(key, &padInfo, PBYTE(&digest[0]), DWORD(digest.size()), &signature[0], DWORD(signature.size()), (DWORD*)&size, BCRYPT_PAD_PKCS1); if (freeKeyHandle) { NCryptFreeObject(key); } break; } case AT_SIGNATURE: { HCRYPTHASH hash = 0; if (!CryptCreateHash(key, alg, 0, 0, &hash)) { if (freeKeyHandle) { CryptReleaseContext(key, 0); } throw TechnicalException("CreateHash failed"); } if (!CryptSetHashParam(hash, HP_HASHVAL, digest.data(), 0)) { if (freeKeyHandle) { CryptReleaseContext(key, 0); } CryptDestroyHash(hash); throw TechnicalException("SetHashParam failed"); } INT retCode = CryptSignHashW(hash, AT_SIGNATURE, 0, 0, LPBYTE(signature.data()), &size); err = retCode ? ERROR_SUCCESS : GetLastError(); _log("CryptSignHash() return code: %u (%s) %x", retCode, retCode ? "SUCCESS" : "FAILURE", err); if (freeKeyHandle) { CryptReleaseContext(key, 0); } CryptDestroyHash(hash); reverse(signature.begin(), signature.end()); break; } default: throw TechnicalException("Incompatible key"); } switch (err) { case ERROR_SUCCESS: break; case SCARD_W_CANCELLED_BY_USER: case ERROR_CANCELLED: throw UserCancelledException("Signing was cancelled"); case SCARD_W_CHV_BLOCKED: throw PinBlockedException(); case NTE_INVALID_HANDLE: throw TechnicalException("The supplied handle is invalid"); default: throw TechnicalException("Signing failed"); } signature.resize(size); return BinaryUtils::bin2hex(signature); } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <algorithm> #include <memory> #include "variant.hpp" #include "Context.hpp" #include "GlobalContext.hpp" #include "FunctionContext.hpp" #include "BlockContext.hpp" #include "VisitorUtils.hpp" #include "ast/ContextAnnotator.hpp" #include "ast/SourceFile.hpp" #include "ast/ASTVisitor.hpp" using namespace eddic; //TODO This design is far from perfect, the Pass should be a static_visitor itself, but that //would mean exposing all the AST node in the header namespace { struct AnnotateVisitor : public boost::static_visitor<> { std::shared_ptr<GlobalContext> globalContext; std::shared_ptr<FunctionContext> functionContext; std::shared_ptr<Context> currentContext; AUTO_RECURSE_BUILTIN_OPERATORS() AUTO_RECURSE_UNARY_VALUES() AUTO_RECURSE_TERNARY() AUTO_RECURSE_PREFIX() AUTO_RECURSE_SUFFIX() AUTO_RECURSE_MEMBER_FUNCTION_CALLS() AUTO_IGNORE_FALSE() AUTO_IGNORE_TRUE() AUTO_IGNORE_NULL() AUTO_IGNORE_LITERAL() AUTO_IGNORE_CHAR_LITERAL() AUTO_IGNORE_FLOAT() AUTO_IGNORE_INTEGER() AUTO_IGNORE_INTEGER_SUFFIX() void operator()(ast::FunctionCall& functionCall){ functionCall.Content->context = currentContext; visit_each(*this, functionCall.Content->values); } template<typename Loop> void annotateWhileLoop(Loop& loop){ currentContext = loop.Content->context = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit(*this, loop.Content->condition); visit_each(*this, loop.Content->instructions); currentContext = currentContext->parent(); } void operator()(ast::While& while_){ annotateWhileLoop(while_); } void operator()(ast::DoWhile& while_){ annotateWhileLoop(while_); } void operator()(ast::Switch& switch_){ switch_.Content->context = currentContext; visit(*this, switch_.Content->value); visit_each_non_variant(*this, switch_.Content->cases); visit_optional_non_variant(*this, switch_.Content->default_case); } void operator()(ast::SwitchCase& switch_case){ visit(*this, switch_case.value); currentContext = switch_case.context = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit_each(*this, switch_case.instructions); currentContext = currentContext->parent(); } void operator()(ast::DefaultCase& default_case){ currentContext = default_case.context = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit_each(*this, default_case.instructions); currentContext = currentContext->parent(); } void operator()(ast::For& for_){ currentContext = for_.Content->context = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit_optional(*this, for_.Content->start); visit_optional(*this, for_.Content->condition); visit_optional(*this, for_.Content->repeat); visit_each(*this, for_.Content->instructions); currentContext = currentContext->parent(); } template<typename Loop> void annotateSimpleLoop(Loop& loop){ loop.Content->context = currentContext = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit_each(*this, loop.Content->instructions); currentContext = currentContext->parent(); } void operator()(ast::Foreach& foreach){ annotateSimpleLoop(foreach); } void operator()(ast::ForeachIn& foreach){ annotateSimpleLoop(foreach); } void operator()(ast::If& if_){ currentContext = if_.Content->context = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit(*this, if_.Content->condition); visit_each(*this, if_.Content->instructions); currentContext = currentContext->parent(); visit_each_non_variant(*this, if_.Content->elseIfs); visit_optional_non_variant(*this, if_.Content->else_); } void operator()(ast::ElseIf& elseIf){ currentContext = elseIf.context = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit(*this, elseIf.condition); visit_each(*this, elseIf.instructions); currentContext = currentContext->parent(); } void operator()(ast::Else& else_){ currentContext = else_.context = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit_each(*this, else_.instructions); currentContext = currentContext->parent(); } void operator()(ast::StructDeclaration& declaration){ declaration.Content->context = currentContext; visit_each(*this, declaration.Content->values); } void operator()(ast::VariableDeclaration& declaration){ declaration.Content->context = currentContext; visit_optional(*this, declaration.Content->value); } void operator()(ast::ArrayDeclaration& declaration){ declaration.Content->context = currentContext; visit(*this, declaration.Content->size); } void operator()(ast::Assignment& assignment){ visit(*this, assignment.Content->left_value); visit(*this, assignment.Content->value); } void operator()(ast::Delete& delete_){ delete_.Content->context = currentContext; } void operator()(ast::Swap& swap){ swap.Content->context = currentContext; } void operator()(ast::Expression& value){ visit(*this, value.Content->first); for_each(value.Content->operations.begin(), value.Content->operations.end(), [&](ast::Operation& operation){ visit(*this, operation.get<1>()); }); } void operator()(ast::VariableValue& variable){ variable.Content->context = currentContext; } void operator()(ast::DereferenceValue& variable){ visit(*this, variable.Content->ref); } void operator()(ast::MemberValue& value){ value.Content->context = currentContext; visit(*this, value.Content->location); } void operator()(ast::ArrayValue& array){ array.Content->context = currentContext; visit(*this, array.Content->indexValue); } void operator()(ast::Return& return_){ return_.Content->context = functionContext; visit(*this, return_.Content->value); } void operator()(ast::Cast& cast){ cast.Content->context = currentContext; visit(*this, cast.Content->value); } void operator()(ast::New& new_){ new_.Content->context = currentContext; visit_each(*this, new_.Content->values); } void operator()(ast::NewArray& new_){ new_.Content->context = currentContext; visit(*this, new_.Content->size); } }; inline AnnotateVisitor make_visitor(std::shared_ptr<GlobalContext> globalContext, std::shared_ptr<FunctionContext> functionContext, std::shared_ptr<Context> currentContext){ AnnotateVisitor visitor; visitor.globalContext = globalContext; visitor.currentContext = currentContext; visitor.functionContext = functionContext; return visitor; } } //end of anonymous namespace void ast::ContextAnnotationPass::apply_program(ast::SourceFile& program, bool indicator){ if(indicator){ currentContext = globalContext = program.Content->context; } else { currentContext = program.Content->context = globalContext = std::make_shared<GlobalContext>(platform); for(auto& block : program.Content->blocks){ if(auto* ptr = boost::get<ast::GlobalVariableDeclaration>(&block)){ ptr->Content->context = currentContext; } else if(auto* ptr = boost::get<ast::GlobalArrayDeclaration>(&block)){ ptr->Content->context = currentContext; } } } } #define HANDLE_FUNCTION() \ currentContext = function.Content->context = functionContext = std::make_shared<FunctionContext>(currentContext, globalContext, platform, configuration); \ auto visitor = make_visitor(globalContext, functionContext, currentContext); \ visit_each(visitor, function.Content->instructions); \ currentContext = currentContext->parent(); void ast::ContextAnnotationPass::apply_function(ast::FunctionDeclaration& function){ HANDLE_FUNCTION(); } void ast::ContextAnnotationPass::apply_struct_function(ast::FunctionDeclaration& function){ HANDLE_FUNCTION(); } void ast::ContextAnnotationPass::apply_struct_constructor(ast::Constructor& function){ HANDLE_FUNCTION(); } void ast::ContextAnnotationPass::apply_struct_destructor(ast::Destructor& function){ HANDLE_FUNCTION(); } <commit_msg>The ArrayValue does not have a context anymore<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <algorithm> #include <memory> #include "variant.hpp" #include "Context.hpp" #include "GlobalContext.hpp" #include "FunctionContext.hpp" #include "BlockContext.hpp" #include "VisitorUtils.hpp" #include "ast/ContextAnnotator.hpp" #include "ast/SourceFile.hpp" #include "ast/ASTVisitor.hpp" using namespace eddic; //TODO This design is far from perfect, the Pass should be a static_visitor itself, but that //would mean exposing all the AST node in the header namespace { struct AnnotateVisitor : public boost::static_visitor<> { std::shared_ptr<GlobalContext> globalContext; std::shared_ptr<FunctionContext> functionContext; std::shared_ptr<Context> currentContext; AUTO_RECURSE_BUILTIN_OPERATORS() AUTO_RECURSE_UNARY_VALUES() AUTO_RECURSE_TERNARY() AUTO_RECURSE_PREFIX() AUTO_RECURSE_SUFFIX() AUTO_RECURSE_MEMBER_FUNCTION_CALLS() AUTO_IGNORE_FALSE() AUTO_IGNORE_TRUE() AUTO_IGNORE_NULL() AUTO_IGNORE_LITERAL() AUTO_IGNORE_CHAR_LITERAL() AUTO_IGNORE_FLOAT() AUTO_IGNORE_INTEGER() AUTO_IGNORE_INTEGER_SUFFIX() void operator()(ast::FunctionCall& functionCall){ functionCall.Content->context = currentContext; visit_each(*this, functionCall.Content->values); } template<typename Loop> void annotateWhileLoop(Loop& loop){ currentContext = loop.Content->context = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit(*this, loop.Content->condition); visit_each(*this, loop.Content->instructions); currentContext = currentContext->parent(); } void operator()(ast::While& while_){ annotateWhileLoop(while_); } void operator()(ast::DoWhile& while_){ annotateWhileLoop(while_); } void operator()(ast::Switch& switch_){ switch_.Content->context = currentContext; visit(*this, switch_.Content->value); visit_each_non_variant(*this, switch_.Content->cases); visit_optional_non_variant(*this, switch_.Content->default_case); } void operator()(ast::SwitchCase& switch_case){ visit(*this, switch_case.value); currentContext = switch_case.context = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit_each(*this, switch_case.instructions); currentContext = currentContext->parent(); } void operator()(ast::DefaultCase& default_case){ currentContext = default_case.context = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit_each(*this, default_case.instructions); currentContext = currentContext->parent(); } void operator()(ast::For& for_){ currentContext = for_.Content->context = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit_optional(*this, for_.Content->start); visit_optional(*this, for_.Content->condition); visit_optional(*this, for_.Content->repeat); visit_each(*this, for_.Content->instructions); currentContext = currentContext->parent(); } template<typename Loop> void annotateSimpleLoop(Loop& loop){ loop.Content->context = currentContext = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit_each(*this, loop.Content->instructions); currentContext = currentContext->parent(); } void operator()(ast::Foreach& foreach){ annotateSimpleLoop(foreach); } void operator()(ast::ForeachIn& foreach){ annotateSimpleLoop(foreach); } void operator()(ast::If& if_){ currentContext = if_.Content->context = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit(*this, if_.Content->condition); visit_each(*this, if_.Content->instructions); currentContext = currentContext->parent(); visit_each_non_variant(*this, if_.Content->elseIfs); visit_optional_non_variant(*this, if_.Content->else_); } void operator()(ast::ElseIf& elseIf){ currentContext = elseIf.context = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit(*this, elseIf.condition); visit_each(*this, elseIf.instructions); currentContext = currentContext->parent(); } void operator()(ast::Else& else_){ currentContext = else_.context = std::make_shared<BlockContext>(currentContext, functionContext, globalContext); visit_each(*this, else_.instructions); currentContext = currentContext->parent(); } void operator()(ast::StructDeclaration& declaration){ declaration.Content->context = currentContext; visit_each(*this, declaration.Content->values); } void operator()(ast::VariableDeclaration& declaration){ declaration.Content->context = currentContext; visit_optional(*this, declaration.Content->value); } void operator()(ast::ArrayDeclaration& declaration){ declaration.Content->context = currentContext; visit(*this, declaration.Content->size); } void operator()(ast::Assignment& assignment){ visit(*this, assignment.Content->left_value); visit(*this, assignment.Content->value); } void operator()(ast::Delete& delete_){ delete_.Content->context = currentContext; } void operator()(ast::Swap& swap){ swap.Content->context = currentContext; } void operator()(ast::Expression& value){ visit(*this, value.Content->first); for_each(value.Content->operations.begin(), value.Content->operations.end(), [&](ast::Operation& operation){ visit(*this, operation.get<1>()); }); } void operator()(ast::VariableValue& variable){ variable.Content->context = currentContext; } void operator()(ast::DereferenceValue& variable){ visit(*this, variable.Content->ref); } void operator()(ast::MemberValue& value){ value.Content->context = currentContext; visit(*this, value.Content->location); } void operator()(ast::ArrayValue& array){ visit(*this, array.Content->ref); visit(*this, array.Content->indexValue); } void operator()(ast::Return& return_){ return_.Content->context = functionContext; visit(*this, return_.Content->value); } void operator()(ast::Cast& cast){ cast.Content->context = currentContext; visit(*this, cast.Content->value); } void operator()(ast::New& new_){ new_.Content->context = currentContext; visit_each(*this, new_.Content->values); } void operator()(ast::NewArray& new_){ new_.Content->context = currentContext; visit(*this, new_.Content->size); } }; inline AnnotateVisitor make_visitor(std::shared_ptr<GlobalContext> globalContext, std::shared_ptr<FunctionContext> functionContext, std::shared_ptr<Context> currentContext){ AnnotateVisitor visitor; visitor.globalContext = globalContext; visitor.currentContext = currentContext; visitor.functionContext = functionContext; return visitor; } } //end of anonymous namespace void ast::ContextAnnotationPass::apply_program(ast::SourceFile& program, bool indicator){ if(indicator){ currentContext = globalContext = program.Content->context; } else { currentContext = program.Content->context = globalContext = std::make_shared<GlobalContext>(platform); for(auto& block : program.Content->blocks){ if(auto* ptr = boost::get<ast::GlobalVariableDeclaration>(&block)){ ptr->Content->context = currentContext; } else if(auto* ptr = boost::get<ast::GlobalArrayDeclaration>(&block)){ ptr->Content->context = currentContext; } } } } #define HANDLE_FUNCTION() \ currentContext = function.Content->context = functionContext = std::make_shared<FunctionContext>(currentContext, globalContext, platform, configuration); \ auto visitor = make_visitor(globalContext, functionContext, currentContext); \ visit_each(visitor, function.Content->instructions); \ currentContext = currentContext->parent(); void ast::ContextAnnotationPass::apply_function(ast::FunctionDeclaration& function){ HANDLE_FUNCTION(); } void ast::ContextAnnotationPass::apply_struct_function(ast::FunctionDeclaration& function){ HANDLE_FUNCTION(); } void ast::ContextAnnotationPass::apply_struct_constructor(ast::Constructor& function){ HANDLE_FUNCTION(); } void ast::ContextAnnotationPass::apply_struct_destructor(ast::Destructor& function){ HANDLE_FUNCTION(); } <|endoftext|>
<commit_before>#include "common.h" #include "hex/basics/error.h" #include "hex/game/game.h" #include "hex/game/game_arbiter.h" #include "hex/game/game_messages.h" #include "hex/game/combat/combat.h" #include "hex/game/movement/movement.h" GameArbiter::GameArbiter(Game *game, MessageReceiver *publisher): game(game), publisher(publisher) { } GameArbiter::~GameArbiter() { } void GameArbiter::receive(boost::shared_ptr<Message> command) { try { process_command(command); } catch (const DataError& err) { BOOST_LOG_TRIVIAL(error) << "Invalid command received; " << err.what(); } } void GameArbiter::process_command(boost::shared_ptr<Message> command) { switch (command->type) { case UnitMove: { boost::shared_ptr<UnitMoveMessage> cmd = boost::dynamic_pointer_cast<UnitMoveMessage>(command); int stack_id = cmd->data1; IntSet units = cmd->data2; Path& path = cmd->data3; int target_id = cmd->data4; UnitStack::pointer stack = game->stacks.get(stack_id); if (units.empty() || !stack->has_units(units) || path.empty()) { throw DataError() << "Invalid UnitMove message"; } /* Check that the move is allowed; shorten it if necessary */ Point end_pos = path.back(); UnitStack::pointer end_stack = game->level.tiles[end_pos].stack; int end_stack_id = end_stack ? end_stack->id : 0; if (end_stack_id != target_id) { path.pop_back(); target_id = 0; } MovementModel movement(&game->level); UnitStack::pointer selected_stack = stack->copy_subset(units); unsigned int allowed_steps = movement.check_path(*selected_stack, path); bool truncated = allowed_steps < path.size(); int attack_target_id = target_id; if (truncated) target_id = 0; path.resize(allowed_steps); if (!path.empty()) { end_pos = path.back(); /* Generate updates. */ Faction::pointer faction = stack->owner; bool move = units.size() == stack->units.size() && target_id == 0; bool split = units.size() < stack->units.size() && target_id == 0; bool merge = units.size() == stack->units.size() && target_id != 0; UnitStack::pointer target = game->stacks.find(target_id); if (move) target_id = stack_id; if (split) target_id = game->get_free_stack_id(); // If the stack is splitting to a new empty position, create a stack there if (split) { emit(create_message(CreateStack, target_id, end_pos, faction->id)); } // Send the update emit(create_message(TransferUnits, stack_id, units, path, target_id)); // If the whole stack merged with an existing one, destroy it if (merge) { emit(create_message(DestroyStack, stack_id)); } } UnitStack::pointer attack_target = game->stacks.find(attack_target_id); bool attack = attack_target && (attack_target->owner != stack->owner); if (attack) { BOOST_LOG_TRIVIAL(debug) << "Attack!"; Point target_point = attack_target->position; Point attacking_point = end_pos; Battle battle(game, target_point, attacking_point); battle.run(); emit(create_message(DoBattle, end_stack_id, target_point, battle.moves)); } } break; case FactionReady: { boost::shared_ptr<FactionReadyMessage> cmd = boost::dynamic_pointer_cast<FactionReadyMessage>(command); int faction_id = cmd->data1; bool ready = cmd->data2; if (game->mark_faction_ready(faction_id, ready)) { emit(create_message(FactionReady, faction_id, ready)); } if (game->all_factions_ready()) { emit(create_message(TurnEnd)); // process turn end spawn_units(); game->turn_number++; emit(create_message(TurnBegin, game->turn_number)); } } break; case Chat: { boost::shared_ptr<WrapperMessage<std::string> > chat_msg = boost::dynamic_pointer_cast<WrapperMessage<std::string> >(command); emit(create_message(Chat, chat_msg->data)); } break; default: break; } } void GameArbiter::spawn_units() { for (int i = 0; i < game->level.height; i++) for (int j = 0; j < game->level.width; j++) { Point position(j, i); Tile& tile = game->level.tiles[position]; int spawn_group = tile.get_property<int>(SpawnGroup); if (!spawn_group) continue; std::vector<UnitStack::pointer> nearby_stacks; int num_nearby = game->get_nearby_stacks(position, 3, nearby_stacks); if (num_nearby > 0) continue; int random100 = rand() % 100; int spawn_chance = tile.get_property<int>(SpawnGroup); if (random100 > spawn_chance) continue; int stack_id = game->get_free_stack_id(); int faction_id = 1; // Independent int spawn_max = (rand() % 8) + 1; int spawn_count = 0; for (int k = 0; k < spawn_max; k++) { for (StrMap<UnitType>::const_iterator iter = game->unit_types.begin(); iter != game->unit_types.end(); iter++) { const UnitType::pointer type = iter->second; if (type->get_property<int>(SpawnGroup) != spawn_group) continue; random100 = rand() % 100; spawn_chance = type->get_property<int>(SpawnChance); if (random100 > spawn_chance) continue; if (spawn_count == 0) { emit(create_message(CreateStack, stack_id, position, faction_id)); } emit(create_message(CreateUnit, stack_id, type->name)); spawn_count++; } } if (spawn_count > 0) BOOST_LOG_TRIVIAL(debug) << boost::format("Spawned %d units from group %d at %s") % spawn_count % spawn_group % position; } } void GameArbiter::emit(boost::shared_ptr<Message> update) { publisher->receive(update); } <commit_msg>Fix crash when attacking an adjacent tile.<commit_after>#include "common.h" #include "hex/basics/error.h" #include "hex/game/game.h" #include "hex/game/game_arbiter.h" #include "hex/game/game_messages.h" #include "hex/game/combat/combat.h" #include "hex/game/movement/movement.h" GameArbiter::GameArbiter(Game *game, MessageReceiver *publisher): game(game), publisher(publisher) { } GameArbiter::~GameArbiter() { } void GameArbiter::receive(boost::shared_ptr<Message> command) { try { process_command(command); } catch (const DataError& err) { BOOST_LOG_TRIVIAL(error) << "Invalid command received; " << err.what(); } } void GameArbiter::process_command(boost::shared_ptr<Message> command) { switch (command->type) { case UnitMove: { boost::shared_ptr<UnitMoveMessage> cmd = boost::dynamic_pointer_cast<UnitMoveMessage>(command); int stack_id = cmd->data1; IntSet units = cmd->data2; Path& path = cmd->data3; int target_id = cmd->data4; UnitStack::pointer stack = game->stacks.get(stack_id); if (units.empty() || !stack->has_units(units) || path.empty()) { throw DataError() << "Invalid UnitMove message"; } /* Check that the move is allowed; shorten it if necessary */ Point end_pos = path.back(); UnitStack::pointer end_stack = game->level.tiles[end_pos].stack; int end_stack_id = end_stack ? end_stack->id : 0; if (end_stack_id != target_id) { path.pop_back(); target_id = 0; } MovementModel movement(&game->level); UnitStack::pointer selected_stack = stack->copy_subset(units); unsigned int allowed_steps = movement.check_path(*selected_stack, path); bool truncated = allowed_steps < path.size(); int attack_target_id = target_id; if (truncated) target_id = 0; path.resize(allowed_steps); if (!path.empty()) { end_pos = path.back(); /* Generate updates. */ Faction::pointer faction = stack->owner; bool move = units.size() == stack->units.size() && target_id == 0; bool split = units.size() < stack->units.size() && target_id == 0; bool merge = units.size() == stack->units.size() && target_id != 0; UnitStack::pointer target = game->stacks.find(target_id); if (move) target_id = stack_id; if (split) target_id = game->get_free_stack_id(); // If the stack is splitting to a new empty position, create a stack there if (split) { emit(create_message(CreateStack, target_id, end_pos, faction->id)); } // Send the update emit(create_message(TransferUnits, stack_id, units, path, target_id)); // If the whole stack merged with an existing one, destroy it if (merge) { emit(create_message(DestroyStack, stack_id)); } } else { end_pos = stack->position; } UnitStack::pointer attack_target = game->stacks.find(attack_target_id); bool attack = attack_target && (attack_target->owner != stack->owner); if (attack) { BOOST_LOG_TRIVIAL(debug) << "Attack!"; Point target_point = attack_target->position; Point attacking_point = end_pos; Battle battle(game, target_point, attacking_point); battle.run(); emit(create_message(DoBattle, end_stack_id, target_point, battle.moves)); } } break; case FactionReady: { boost::shared_ptr<FactionReadyMessage> cmd = boost::dynamic_pointer_cast<FactionReadyMessage>(command); int faction_id = cmd->data1; bool ready = cmd->data2; if (game->mark_faction_ready(faction_id, ready)) { emit(create_message(FactionReady, faction_id, ready)); } if (game->all_factions_ready()) { emit(create_message(TurnEnd)); // process turn end spawn_units(); game->turn_number++; emit(create_message(TurnBegin, game->turn_number)); } } break; case Chat: { boost::shared_ptr<WrapperMessage<std::string> > chat_msg = boost::dynamic_pointer_cast<WrapperMessage<std::string> >(command); emit(create_message(Chat, chat_msg->data)); } break; default: break; } } void GameArbiter::spawn_units() { for (int i = 0; i < game->level.height; i++) for (int j = 0; j < game->level.width; j++) { Point position(j, i); Tile& tile = game->level.tiles[position]; int spawn_group = tile.get_property<int>(SpawnGroup); if (!spawn_group) continue; std::vector<UnitStack::pointer> nearby_stacks; int num_nearby = game->get_nearby_stacks(position, 3, nearby_stacks); if (num_nearby > 0) continue; int random100 = rand() % 100; int spawn_chance = tile.get_property<int>(SpawnGroup); if (random100 > spawn_chance) continue; int stack_id = game->get_free_stack_id(); int faction_id = 1; // Independent int spawn_max = (rand() % 8) + 1; int spawn_count = 0; for (int k = 0; k < spawn_max; k++) { for (StrMap<UnitType>::const_iterator iter = game->unit_types.begin(); iter != game->unit_types.end(); iter++) { const UnitType::pointer type = iter->second; if (type->get_property<int>(SpawnGroup) != spawn_group) continue; random100 = rand() % 100; spawn_chance = type->get_property<int>(SpawnChance); if (random100 > spawn_chance) continue; if (spawn_count == 0) { emit(create_message(CreateStack, stack_id, position, faction_id)); } emit(create_message(CreateUnit, stack_id, type->name)); spawn_count++; } } if (spawn_count > 0) BOOST_LOG_TRIVIAL(debug) << boost::format("Spawned %d units from group %d at %s") % spawn_count % spawn_group % position; } } void GameArbiter::emit(boost::shared_ptr<Message> update) { publisher->receive(update); } <|endoftext|>
<commit_before>// Copyright (c) 2016-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bench/bench.h> #include <bench/data.h> #include <rpc/blockchain.h> #include <streams.h> #include <test/util/setup_common.h> #include <validation.h> #include <univalue.h> static void BlockToJsonVerbose(benchmark::Bench& bench) { TestingSetup test_setup{}; CDataStream stream(benchmark::data::block413567, SER_NETWORK, PROTOCOL_VERSION); char a = '\0'; stream.write(&a, 1); // Prevent compaction CBlock block; stream >> block; CBlockIndex blockindex; const uint256 blockHash = block.GetHash(); blockindex.phashBlock = &blockHash; blockindex.nBits = 403014710; bench.run([&] { (void)blockToJSON(block, &blockindex, &blockindex, /*verbose*/ true); }); } BENCHMARK(BlockToJsonVerbose); <commit_msg>Add benchmark to write JSON into a string<commit_after>// Copyright (c) 2016-2020 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bench/bench.h> #include <bench/data.h> #include <rpc/blockchain.h> #include <streams.h> #include <test/util/setup_common.h> #include <validation.h> #include <univalue.h> namespace { struct TestBlockAndIndex { TestingSetup test_setup{}; CBlock block{}; uint256 blockHash{}; CBlockIndex blockindex{}; TestBlockAndIndex() { CDataStream stream(benchmark::data::block413567, SER_NETWORK, PROTOCOL_VERSION); char a = '\0'; stream.write(&a, 1); // Prevent compaction stream >> block; blockHash = block.GetHash(); blockindex.phashBlock = &blockHash; blockindex.nBits = 403014710; } }; } // namespace static void BlockToJsonVerbose(benchmark::Bench& bench) { TestBlockAndIndex data; bench.run([&] { auto univalue = blockToJSON(data.block, &data.blockindex, &data.blockindex, /*verbose*/ true); ankerl::nanobench::doNotOptimizeAway(univalue); }); } BENCHMARK(BlockToJsonVerbose); static void BlockToJsonVerboseWrite(benchmark::Bench& bench) { TestBlockAndIndex data; auto univalue = blockToJSON(data.block, &data.blockindex, &data.blockindex, /*verbose*/ true); bench.run([&] { auto str = univalue.write(); ankerl::nanobench::doNotOptimizeAway(str); }); } BENCHMARK(BlockToJsonVerboseWrite); <|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS dba31a (1.8.4); FILE MERGED 2008/07/16 06:16:03 fs 1.8.4.2: RESYNC: (1.8-1.9); FILE MERGED 2008/07/10 06:36:08 oj 1.8.4.1: #i88727# new area prop for shapes<commit_after><|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include <numeric> #include <stdexcept> #include "fs.hpp" #include "utils.hpp" namespace { const std::size_t kMinimalArguments{2}; } int main(int argc, char *argv[]) { using std::cout; using std::endl; try { if (static_cast<std::size_t>(argc) < kMinimalArguments) { throw std::runtime_error("Incorrect number of arguments"); } const std::string searchedWord{argc == 2 ? "" : argv[2]}; const auto splitted = utils::split(fs::readFile(argv[1]), argc == 4 ? argv[3] : " "); const auto result = std::count_if(splitted.begin(), splitted.end(), [&](const auto &a) -> bool { if (searchedWord.empty()) { return true; } else { return searchedWord == a; } }); cout << result << endl; } catch (const std::exception &ex) { cout << ex.what() << endl; } } <commit_msg>Proper exit codes<commit_after>#include <algorithm> #include <iostream> #include <numeric> #include <stdexcept> #include "fs.hpp" #include "utils.hpp" namespace { const std::size_t kMinimalArguments{2}; } int main(int argc, char *argv[]) { using std::cout; using std::endl; try { if (static_cast<std::size_t>(argc) < kMinimalArguments) { throw std::runtime_error("Incorrect number of arguments"); } const std::string searchedWord{argc == 2 ? "" : argv[2]}; const auto splitted = utils::split(fs::readFile(argv[1]), argc == 4 ? argv[3] : " "); const auto result = std::count_if(splitted.begin(), splitted.end(), [&](const auto &a) -> bool { if (searchedWord.empty()) { return true; } else { return searchedWord == a; } }); cout << result << endl; return EXIT_SUCCESS; } catch (const std::exception &ex) { cout << ex.what() << endl; return EXIT_FAILURE; } } <|endoftext|>
<commit_before>#include "server.hpp" namespace po = boost::program_options; using std::cout; using std::cerr; using std::endl; int main(int argc, char* argv[]) { po::options_description desc("Bananagrams multiplayer dedicated server"); desc.add_options() ("help", "show options") ("dict", po::value<std::string>(), "dictionary file") ("port", po::value<unsigned int>()->default_value(default_port), "TCP/UDP listening port") ("bunch", po::value<std::string>()->default_value("1"), "bunch multiplier (0.5, inf, or an integer)") ; // TODO usage string // TODO print help on unrecognized options po::variables_map opts; po::store(po::parse_command_line(argc, argv, desc), opts); po::notify(opts); if (opts.count("help")) { cerr << desc << endl; return 1; } // check port option unsigned int port {opts["port"].as<unsigned int>()}; if (port == 0 || port > 65535) { cerr << "Invalid listening port: " << port << "!\n"; return 1; } // check bunch multiplier option std::stringstream multi_s; multi_s << opts["bunch"].as<std::string>(); unsigned int b_num {1}; unsigned int b_den {1}; if (multi_s.str() == "0.5") { b_den = 2; } else if (multi_s.str() == "inf") { // TODO } else { multi_s >> b_num; } // check dictionary option if (!opts.count("dict")) { cerr << "No dictionary file specified!\n"; return 1; } std::string dict = opts["dict"].as<std::string>(); std::map<std::string, std::string> dictionary; cout << "Loading dictionary... "; cout.flush(); std::ifstream words(dict); if (!words.is_open()) { std::cerr << "\nFailed to open " << dict << "!\n"; return 1; } // parse dictionary std::string line; while (std::getline(words, line)) { auto pos = line.find_first_of(' '); if (pos == std::string::npos) dictionary[line] = ""; else dictionary[line.substr(0, pos)] = line.substr(pos + 1, std::string::npos); } words.close(); cout << dictionary.size() << " words found\n"; // LET'S GO!!! std::list<char> bunch; for (char ch = 'A'; ch <= 'Z'; ++ch) for (unsigned int i = 0; i < ((letter_count[ch - 'A'] * b_num) / b_den); ++i) random_insert(bunch, ch); while (true) { } return 0; } <commit_msg>using std::string<commit_after>#include "server.hpp" namespace po = boost::program_options; using std::cout; using std::cerr; using std::endl; using std::string; int main(int argc, char* argv[]) { po::options_description desc("Bananagrams multiplayer dedicated server"); desc.add_options() ("help", "show options") ("dict", po::value<string>(), "dictionary file") ("port", po::value<unsigned int>()->default_value(default_port), "TCP/UDP listening port") ("bunch", po::value<string>()->default_value("1"), "bunch multiplier (0.5, inf, or a positive integer)") ; // TODO usage string // TODO print help on unrecognized options po::variables_map opts; po::store(po::parse_command_line(argc, argv, desc), opts); po::notify(opts); if (opts.count("help")) { cerr << desc << endl; return 1; } // check port option unsigned int port {opts["port"].as<unsigned int>()}; if (port == 0 || port > 65535) { cerr << "Invalid listening port: " << port << "!\n"; return 1; } // check bunch multiplier option std::stringstream multi_s; multi_s << opts["bunch"].as<string>(); unsigned int b_num {1}; unsigned int b_den {1}; if (multi_s.str() == "0.5") { b_den = 2; } else if (multi_s.str() == "inf") { // TODO } else { multi_s >> b_num; } // check dictionary option if (!opts.count("dict")) { cerr << "No dictionary file specified!\n"; return 1; } string dict = opts["dict"].as<string>(); std::map<string, string> dictionary; cout << "Loading dictionary... "; cout.flush(); std::ifstream words(dict); if (!words.is_open()) { std::cerr << "\nFailed to open " << dict << "!\n"; return 1; } // parse dictionary string line; while (std::getline(words, line)) { auto pos = line.find_first_of(' '); if (pos == string::npos) dictionary[line] = ""; else dictionary[line.substr(0, pos)] = line.substr(pos + 1, string::npos); } words.close(); cout << dictionary.size() << " words found\n"; // LET'S GO!!! std::list<char> bunch; for (char ch = 'A'; ch <= 'Z'; ++ch) for (unsigned int i = 0; i < ((letter_count[ch - 'A'] * b_num) / b_den); ++i) random_insert(bunch, ch); sf::UdpSocket socket; socket.bind(port); while (true) { } return 0; } <|endoftext|>
<commit_before>#include "occ_libstl.h" #include <cstring> #include <StlMesh_Mesh.hxx> #include <StlMesh_MeshTriangle.hxx> #include <StlMesh_SequenceOfMeshTriangle.hxx> #include <TColgp_SequenceOfXYZ.hxx> /* Common */ static void occ_mesh_stl_add_triangle(Handle_StlMesh_Mesh* mesh, const foug_stl_triangle_t* tri) { const int uId = (*mesh)->AddOnlyNewVertex(tri->v1.x, tri->v1.y, tri->v1.z); const int vId = (*mesh)->AddOnlyNewVertex(tri->v2.x, tri->v2.y, tri->v2.z); const int wId = (*mesh)->AddOnlyNewVertex(tri->v3.x, tri->v3.y, tri->v3.z); (*mesh)->AddTriangle(uId, vId, wId, tri->normal.x, tri->normal.y, tri->normal.z); } /* ASCII STL */ static void occ_mesh_stla_igeom_begin_solid(foug_stla_geom_input_t* geom, const char* /*name*/) { Handle_StlMesh_Mesh* mesh = static_cast<Handle_StlMesh_Mesh*>(geom->cookie); if (mesh->IsNull()) *mesh = new StlMesh_Mesh; (*mesh)->AddDomain(); } static void occ_mesh_stla_igeom_process_next_triangle(foug_stla_geom_input_t* geom, const foug_stl_triangle_t* tri) { Handle_StlMesh_Mesh* mesh = static_cast<Handle_StlMesh_Mesh*>(geom->cookie); occ_mesh_stl_add_triangle(mesh, tri); } void foug_stla_geom_input_set_occmesh(foug_stla_geom_input_t* input, Handle_StlMesh_Mesh* mesh) { input->cookie = mesh; input->begin_solid_func = occ_mesh_stla_igeom_begin_solid; input->process_next_triangle_func = occ_mesh_stla_igeom_process_next_triangle; input->end_solid_func = NULL; } /* Binary STL */ static void occ_mesh_stlb_igeom_begin_triangles(foug_stlb_geom_input_t* geom, uint32_t /*count*/) { Handle_StlMesh_Mesh* mesh = static_cast<Handle_StlMesh_Mesh*>(geom->cookie); *mesh = new StlMesh_Mesh; (*mesh)->AddDomain(); } static void occ_mesh_stlb_igeom_process_next_triangle(foug_stlb_geom_input_t* geom, const foug_stlb_triangle_t* face) { Handle_StlMesh_Mesh* mesh = static_cast<Handle_StlMesh_Mesh*>(geom->cookie); occ_mesh_stl_add_triangle(mesh, &(face->data)); } void foug_stlb_geom_input_set_occmesh(foug_stlb_geom_input_t* input, Handle_StlMesh_Mesh* mesh) { input->cookie = mesh; input->process_header_func = NULL; input->begin_triangles_func = occ_mesh_stlb_igeom_begin_triangles; input->process_next_triangle_func = occ_mesh_stlb_igeom_process_next_triangle; input->end_triangles_func = NULL; } static void occ_mesh_stlb_ogeom_get_header(const foug_stlb_geom_output_t* /*geom*/, uint8_t* header) { std::memcpy(header, "Generated by libfougdatax-c", FOUG_STLB_HEADER_SIZE); } static uint32_t occ_mesh_stlb_ogeom_get_triangle_count(const foug_stlb_geom_output_t* geom) { Handle_StlMesh_Mesh* mesh = static_cast<Handle_StlMesh_Mesh*>(geom->cookie); if ((*mesh)->NbDomains() >= 1) return (*mesh)->NbTriangles(1); return 0; } static void occ_mesh_stlb_ogeom_get_triangle(const foug_stlb_geom_output_t* geom, uint32_t index, foug_stlb_triangle_t* facet) { Handle_StlMesh_Mesh* mesh = static_cast<Handle_StlMesh_Mesh*>(geom->cookie); const StlMesh_SequenceOfMeshTriangle& meshTriangles = (*mesh)->Triangles(1); const Handle_StlMesh_MeshTriangle tri = meshTriangles.Value(index + 1); Standard_Integer v1; Standard_Integer v2; Standard_Integer v3; Standard_Real xN; Standard_Real yN; Standard_Real zN; tri->GetVertexAndOrientation(v1, v2, v3, xN, yN, zN); facet->data.normal.x = static_cast<foug_real32_t>(xN); facet->data.normal.y = static_cast<foug_real32_t>(yN); facet->data.normal.z = static_cast<foug_real32_t>(zN); const TColgp_SequenceOfXYZ& vertices = (*mesh)->Vertices(1); const gp_XYZ& coordsV1 = vertices.Value(v1); const gp_XYZ& coordsV2 = vertices.Value(v2); const gp_XYZ& coordsV3 = vertices.Value(v3); facet->data.v1.x = static_cast<foug_real32_t>(coordsV1.X()); facet->data.v2.x = static_cast<foug_real32_t>(coordsV2.X()); facet->data.v3.x = static_cast<foug_real32_t>(coordsV3.X()); facet->data.v1.y = static_cast<foug_real32_t>(coordsV1.Y()); facet->data.v2.y = static_cast<foug_real32_t>(coordsV2.Y()); facet->data.v3.y = static_cast<foug_real32_t>(coordsV3.Y()); facet->data.v1.z = static_cast<foug_real32_t>(coordsV1.Z()); facet->data.v2.z = static_cast<foug_real32_t>(coordsV2.Z()); facet->data.v3.z = static_cast<foug_real32_t>(coordsV3.Z()); facet->attribute_byte_count = 0; } void foug_stlb_geom_output_set_occmesh(foug_stlb_geom_output_t* output, Handle_StlMesh_Mesh* mesh) { output->cookie = mesh; output->get_header_func = occ_mesh_stlb_ogeom_get_header; output->get_triangle_count_func = occ_mesh_stlb_ogeom_get_triangle_count; output->get_triangle_func = occ_mesh_stlb_ogeom_get_triangle; } <commit_msg>occ_support: minor performance improvement<commit_after>#include "occ_libstl.h" #include <cstring> #include <StlMesh_Mesh.hxx> #include <StlMesh_MeshTriangle.hxx> #include <StlMesh_SequenceOfMeshTriangle.hxx> #include <TColgp_SequenceOfXYZ.hxx> /* Common */ static void occ_mesh_stl_add_triangle(Handle_StlMesh_Mesh* mesh, const foug_stl_triangle_t* tri) { const int uId = (*mesh)->AddOnlyNewVertex(tri->v1.x, tri->v1.y, tri->v1.z); const int vId = (*mesh)->AddOnlyNewVertex(tri->v2.x, tri->v2.y, tri->v2.z); const int wId = (*mesh)->AddOnlyNewVertex(tri->v3.x, tri->v3.y, tri->v3.z); (*mesh)->AddTriangle(uId, vId, wId, tri->normal.x, tri->normal.y, tri->normal.z); } /* ASCII STL */ static void occ_mesh_stla_igeom_begin_solid(foug_stla_geom_input_t* geom, const char* /*name*/) { Handle_StlMesh_Mesh* mesh = static_cast<Handle_StlMesh_Mesh*>(geom->cookie); if (mesh->IsNull()) *mesh = new StlMesh_Mesh; (*mesh)->AddDomain(); } static void occ_mesh_stla_igeom_process_next_triangle(foug_stla_geom_input_t* geom, const foug_stl_triangle_t* tri) { Handle_StlMesh_Mesh* mesh = static_cast<Handle_StlMesh_Mesh*>(geom->cookie); occ_mesh_stl_add_triangle(mesh, tri); } void foug_stla_geom_input_set_occmesh(foug_stla_geom_input_t* input, Handle_StlMesh_Mesh* mesh) { input->cookie = mesh; input->begin_solid_func = occ_mesh_stla_igeom_begin_solid; input->process_next_triangle_func = occ_mesh_stla_igeom_process_next_triangle; input->end_solid_func = NULL; } /* Binary STL */ static void occ_mesh_stlb_igeom_begin_triangles(foug_stlb_geom_input_t* geom, uint32_t /*count*/) { Handle_StlMesh_Mesh* mesh = static_cast<Handle_StlMesh_Mesh*>(geom->cookie); *mesh = new StlMesh_Mesh; (*mesh)->AddDomain(); } static void occ_mesh_stlb_igeom_process_next_triangle(foug_stlb_geom_input_t* geom, const foug_stlb_triangle_t* face) { Handle_StlMesh_Mesh* mesh = static_cast<Handle_StlMesh_Mesh*>(geom->cookie); occ_mesh_stl_add_triangle(mesh, &(face->data)); } void foug_stlb_geom_input_set_occmesh(foug_stlb_geom_input_t* input, Handle_StlMesh_Mesh* mesh) { input->cookie = mesh; input->process_header_func = NULL; input->begin_triangles_func = occ_mesh_stlb_igeom_begin_triangles; input->process_next_triangle_func = occ_mesh_stlb_igeom_process_next_triangle; input->end_triangles_func = NULL; } static void occ_mesh_stlb_ogeom_get_header(const foug_stlb_geom_output_t* /*geom*/, uint8_t* header) { std::memcpy(header, "Generated by libfougdatax-c", FOUG_STLB_HEADER_SIZE); } static uint32_t occ_mesh_stlb_ogeom_get_triangle_count(const foug_stlb_geom_output_t* geom) { Handle_StlMesh_Mesh* mesh = static_cast<Handle_StlMesh_Mesh*>(geom->cookie); if ((*mesh)->NbDomains() >= 1) return (*mesh)->NbTriangles(1); return 0; } static void occ_mesh_stlb_ogeom_get_triangle(const foug_stlb_geom_output_t* geom, uint32_t index, foug_stlb_triangle_t* facet) { Handle_StlMesh_Mesh* mesh = static_cast<Handle_StlMesh_Mesh*>(geom->cookie); const StlMesh_SequenceOfMeshTriangle& meshTriangles = (*mesh)->Triangles(1); const Handle_StlMesh_MeshTriangle& tri = meshTriangles.Value(index + 1); Standard_Integer v1; Standard_Integer v2; Standard_Integer v3; Standard_Real xN; Standard_Real yN; Standard_Real zN; tri->GetVertexAndOrientation(v1, v2, v3, xN, yN, zN); facet->data.normal.x = static_cast<foug_real32_t>(xN); facet->data.normal.y = static_cast<foug_real32_t>(yN); facet->data.normal.z = static_cast<foug_real32_t>(zN); const TColgp_SequenceOfXYZ& vertices = (*mesh)->Vertices(1); const gp_XYZ& coordsV1 = vertices.Value(v1); const gp_XYZ& coordsV2 = vertices.Value(v2); const gp_XYZ& coordsV3 = vertices.Value(v3); facet->data.v1.x = static_cast<foug_real32_t>(coordsV1.X()); facet->data.v2.x = static_cast<foug_real32_t>(coordsV2.X()); facet->data.v3.x = static_cast<foug_real32_t>(coordsV3.X()); facet->data.v1.y = static_cast<foug_real32_t>(coordsV1.Y()); facet->data.v2.y = static_cast<foug_real32_t>(coordsV2.Y()); facet->data.v3.y = static_cast<foug_real32_t>(coordsV3.Y()); facet->data.v1.z = static_cast<foug_real32_t>(coordsV1.Z()); facet->data.v2.z = static_cast<foug_real32_t>(coordsV2.Z()); facet->data.v3.z = static_cast<foug_real32_t>(coordsV3.Z()); facet->attribute_byte_count = 0; } void foug_stlb_geom_output_set_occmesh(foug_stlb_geom_output_t* output, Handle_StlMesh_Mesh* mesh) { output->cookie = mesh; output->get_header_func = occ_mesh_stlb_ogeom_get_header; output->get_triangle_count_func = occ_mesh_stlb_ogeom_get_triangle_count; output->get_triangle_func = occ_mesh_stlb_ogeom_get_triangle; } <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2018 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #ifndef MIOPEN_FUSION_HPP_ #define MIOPEN_FUSION_HPP_ #include <miopen/common.hpp> #include <miopen/errors.hpp> #include <miopen/handle.hpp> #include <miopen/miopen.h> #include <miopen/tensor.hpp> #include <miopen/activ.hpp> #include <miopen/convolution.hpp> #include <miopen/solver.hpp> #include <miopen/op_kernel_args.hpp> #include <miopen/fusion_ops.hpp> #include <set> #include <vector> #include <unordered_map> namespace miopen { enum FusionKernelSourceType { OpenclText, AsmText, Binary, }; struct OperatorArgs : miopenOperatorArgs { OperatorArgs(); void ins_arg(std::string name, OpKernelArg v); friend std::ostream& operator<<(std::ostream& stream, const OperatorArgs& x); std::vector<OpKernelArg> args_vec; std::unordered_map<std::string, OpKernelArg> args_map; }; struct FusionOpDescriptor : miopenFusionOpDescriptor { virtual ~FusionOpDescriptor() = default; FusionOpDescriptor(const FusionOpDescriptor&) = delete; FusionOpDescriptor() = default; FusionOpDescriptor& operator=(const FusionOpDescriptor&) = delete; void SetIdx(int _id) { plan_idx = _id; }; int GetIdx() const { return plan_idx; }; virtual FusionMDGraph_Edge_Map MDGraphKey() const { return {{"weight", {EdgeOp(0, true, OpAny)}}}; }; virtual miopenStatus_t GetOutputDesc(TensorDescriptor& output_desc) = 0; virtual miopenStatus_t GetNetworkConfig(std::string& network_config, Handle& handle); virtual miopenStatus_t GetCompileParms(std::string& compile_config, Handle& handle, FusionKernelSourceType source, const std::vector<solver::AnySolver>& solvers); friend std::ostream& operator<<(std::ostream& stream, const FusionOpDescriptor& x); virtual miopenFusionOp_t kind() const = 0; virtual std::vector<std::string> GetArgs() const = 0; virtual std::vector<size_t> GetLocalWGSz(Handle& handle, std::string algorithm_name); virtual std::vector<size_t> GetGlobalWGSz(Handle& handle, std::string algorithm_name); void SetInputDesc(TensorDescriptor i_desc) { input_desc = i_desc; }; TensorDescriptor input_desc; private: int plan_idx = 0; std::shared_ptr<OperatorArgs> args = nullptr; }; struct BiasFusionOpDescriptor : FusionOpDescriptor { BiasFusionOpDescriptor(TensorDescriptor& desc) : base_desc(desc){}; miopenStatus_t GetOutputDesc(TensorDescriptor& output_desc) override; miopenStatus_t GetNetworkConfig(std::string& network_config, Handle& handle) override; miopenStatus_t GetCompileParms(std::string& compile_config, Handle& handle, FusionKernelSourceType source, const std::vector<solver::AnySolver>& solvers) override; miopenStatus_t SetArgs(OperatorArgs& args, const void* alpha, const void* beta, ConstData_t bdata); std::vector<std::string> GetArgs() const override; miopenFusionOp_t kind() const override { return miopenFusionOpBiasForward; }; FusionMDGraph_Edge_Map MDGraphKey() const override; std::vector<size_t> GetLocalWGSz(Handle& handle, std::string algorithm_name) override; std::vector<size_t> GetGlobalWGSz(Handle& handle, std::string algorithm_name) override; TensorDescriptor& base_desc; }; struct ActivFusionOpDescriptor : FusionOpDescriptor { ActivFusionOpDescriptor(miopenActivationMode_t mode) : activMode(mode){}; miopenStatus_t GetOutputDesc(TensorDescriptor& output_desc) override; miopenStatus_t GetNetworkConfig(std::string& network_config, Handle& handle) override; miopenStatus_t GetCompileParms(std::string& compile_config, Handle& handle, FusionKernelSourceType source, const std::vector<solver::AnySolver>& solvers) override; miopenStatus_t SetArgs(OperatorArgs& args, const void* alpha, const void* beta, double activAlpha, double activBeta, double activGamma); std::vector<std::string> GetArgs() const override; miopenFusionOp_t kind() const override { return miopenFusionOpActivForward; }; FusionMDGraph_Edge_Map MDGraphKey() const override; static FusionMDGraph_Edge_Map MDGraphKey(miopenActivationMode_t mode); std::vector<size_t> GetLocalWGSz(Handle& handle, std::string algorithm_name) override; std::vector<size_t> GetGlobalWGSz(Handle& handle, std::string algorithm_name) override; miopenActivationMode_t activMode; }; struct BatchNormInferenceFusionOpDescriptor : FusionOpDescriptor { BatchNormInferenceFusionOpDescriptor(miopenBatchNormMode_t bn_mode, TensorDescriptor& desc) : mode(bn_mode), base_desc(desc){}; miopenStatus_t GetOutputDesc(TensorDescriptor& output_desc) override; miopenStatus_t GetNetworkConfig(std::string& network_config, Handle& handle) override; miopenStatus_t GetCompileParms(std::string& compile_config, Handle& handle, FusionKernelSourceType source, const std::vector<solver::AnySolver>& solvers) override; miopenStatus_t SetArgs(OperatorArgs& args, const void* alpha, const void* beta, ConstData_t bnScale, ConstData_t bnBias, ConstData_t estimatedMean, ConstData_t estimatedVariance, double epsilon); std::vector<std::string> GetArgs() const override; miopenFusionOp_t kind() const override { return miopenFusionOpBatchNormInference; }; FusionMDGraph_Edge_Map MDGraphKey() const override; static FusionMDGraph_Edge_Map MDGraphKey(miopenBatchNormMode_t bn_mode); std::vector<size_t> GetLocalWGSz(Handle& handle, std::string algorithm_name) override; std::vector<size_t> GetGlobalWGSz(Handle& handle, std::string algorithm_name) override; miopenBatchNormMode_t mode; TensorDescriptor& base_desc; }; struct ConvForwardOpDescriptor : FusionOpDescriptor { ConvForwardOpDescriptor(ConvolutionDescriptor& conv_descriptor, TensorDescriptor& filter_descriptor) : base_desc(conv_descriptor), filter_desc(filter_descriptor), kernel_info_valid(false), conv_compiler_options(""){}; miopenStatus_t GetOutputDesc(TensorDescriptor& output_desc) override; miopenStatus_t SetArgs(OperatorArgs& args, const void* alpha, const void* beta, ConstData_t w); std::vector<std::string> GetArgs() const override; miopenStatus_t GetNetworkConfig(std::string& network_config, Handle& handle) override; miopenStatus_t GetCompileParms(std::string& compile_config, Handle& handle, FusionKernelSourceType source, const std::vector<solver::AnySolver>& solvers) override; bool isASMApplicable(Handle& handle); miopenFusionOp_t kind() const override { return miopenFusionOpConvForward; }; FusionMDGraph_Edge_Map MDGraphKey() const override; static FusionMDGraph_Edge_Map MDGraphKey(miopenConvolutionMode_t conv_mode, miopenPaddingMode_t pad_mode, int pad_h, int pad_w, int u, int v, int dilation_h, int dilation_w, int k, int c, int x, int y); std::vector<size_t> GetLocalWGSz(Handle& handle, std::string algorithm_name) override; std::vector<size_t> GetGlobalWGSz(Handle& handle, std::string algorithm_name) override; ConvolutionDescriptor& base_desc; TensorDescriptor& filter_desc; solver::KernelInfo kernel_info; bool kernel_info_valid; std::string conv_compiler_options; private: mlo_construct_direct2D_fusion ConstructParams(Handle& handle); }; } // namespace miopen MIOPEN_DEFINE_OBJECT(miopenFusionOpDescriptor, miopen::FusionOpDescriptor); MIOPEN_DEFINE_OBJECT(miopenOperatorArgs, miopen::OperatorArgs); #endif // _MIOPEN_FUSION_HPP_ <commit_msg>Removes references in the fusion ops class members. (#1229)<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2018 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #ifndef MIOPEN_FUSION_HPP_ #define MIOPEN_FUSION_HPP_ #include <miopen/common.hpp> #include <miopen/errors.hpp> #include <miopen/handle.hpp> #include <miopen/miopen.h> #include <miopen/tensor.hpp> #include <miopen/activ.hpp> #include <miopen/convolution.hpp> #include <miopen/solver.hpp> #include <miopen/op_kernel_args.hpp> #include <miopen/fusion_ops.hpp> #include <set> #include <vector> #include <unordered_map> namespace miopen { enum FusionKernelSourceType { OpenclText, AsmText, Binary, }; struct OperatorArgs : miopenOperatorArgs { OperatorArgs(); void ins_arg(std::string name, OpKernelArg v); friend std::ostream& operator<<(std::ostream& stream, const OperatorArgs& x); std::vector<OpKernelArg> args_vec; std::unordered_map<std::string, OpKernelArg> args_map; }; struct FusionOpDescriptor : miopenFusionOpDescriptor { virtual ~FusionOpDescriptor() = default; FusionOpDescriptor(const FusionOpDescriptor&) = delete; FusionOpDescriptor() = default; FusionOpDescriptor& operator=(const FusionOpDescriptor&) = delete; void SetIdx(int _id) { plan_idx = _id; }; int GetIdx() const { return plan_idx; }; virtual FusionMDGraph_Edge_Map MDGraphKey() const { return {{"weight", {EdgeOp(0, true, OpAny)}}}; }; virtual miopenStatus_t GetOutputDesc(TensorDescriptor& output_desc) = 0; virtual miopenStatus_t GetNetworkConfig(std::string& network_config, Handle& handle); virtual miopenStatus_t GetCompileParms(std::string& compile_config, Handle& handle, FusionKernelSourceType source, const std::vector<solver::AnySolver>& solvers); friend std::ostream& operator<<(std::ostream& stream, const FusionOpDescriptor& x); virtual miopenFusionOp_t kind() const = 0; virtual std::vector<std::string> GetArgs() const = 0; virtual std::vector<size_t> GetLocalWGSz(Handle& handle, std::string algorithm_name); virtual std::vector<size_t> GetGlobalWGSz(Handle& handle, std::string algorithm_name); void SetInputDesc(TensorDescriptor i_desc) { input_desc = i_desc; }; TensorDescriptor input_desc; private: int plan_idx = 0; std::shared_ptr<OperatorArgs> args = nullptr; }; struct BiasFusionOpDescriptor : FusionOpDescriptor { BiasFusionOpDescriptor(TensorDescriptor& desc) : base_desc(desc){}; miopenStatus_t GetOutputDesc(TensorDescriptor& output_desc) override; miopenStatus_t GetNetworkConfig(std::string& network_config, Handle& handle) override; miopenStatus_t GetCompileParms(std::string& compile_config, Handle& handle, FusionKernelSourceType source, const std::vector<solver::AnySolver>& solvers) override; miopenStatus_t SetArgs(OperatorArgs& args, const void* alpha, const void* beta, ConstData_t bdata); std::vector<std::string> GetArgs() const override; miopenFusionOp_t kind() const override { return miopenFusionOpBiasForward; }; FusionMDGraph_Edge_Map MDGraphKey() const override; std::vector<size_t> GetLocalWGSz(Handle& handle, std::string algorithm_name) override; std::vector<size_t> GetGlobalWGSz(Handle& handle, std::string algorithm_name) override; TensorDescriptor base_desc; }; struct ActivFusionOpDescriptor : FusionOpDescriptor { ActivFusionOpDescriptor(miopenActivationMode_t mode) : activMode(mode){}; miopenStatus_t GetOutputDesc(TensorDescriptor& output_desc) override; miopenStatus_t GetNetworkConfig(std::string& network_config, Handle& handle) override; miopenStatus_t GetCompileParms(std::string& compile_config, Handle& handle, FusionKernelSourceType source, const std::vector<solver::AnySolver>& solvers) override; miopenStatus_t SetArgs(OperatorArgs& args, const void* alpha, const void* beta, double activAlpha, double activBeta, double activGamma); std::vector<std::string> GetArgs() const override; miopenFusionOp_t kind() const override { return miopenFusionOpActivForward; }; FusionMDGraph_Edge_Map MDGraphKey() const override; static FusionMDGraph_Edge_Map MDGraphKey(miopenActivationMode_t mode); std::vector<size_t> GetLocalWGSz(Handle& handle, std::string algorithm_name) override; std::vector<size_t> GetGlobalWGSz(Handle& handle, std::string algorithm_name) override; miopenActivationMode_t activMode; }; struct BatchNormInferenceFusionOpDescriptor : FusionOpDescriptor { BatchNormInferenceFusionOpDescriptor(miopenBatchNormMode_t bn_mode, TensorDescriptor& desc) : mode(bn_mode), base_desc(desc){}; miopenStatus_t GetOutputDesc(TensorDescriptor& output_desc) override; miopenStatus_t GetNetworkConfig(std::string& network_config, Handle& handle) override; miopenStatus_t GetCompileParms(std::string& compile_config, Handle& handle, FusionKernelSourceType source, const std::vector<solver::AnySolver>& solvers) override; miopenStatus_t SetArgs(OperatorArgs& args, const void* alpha, const void* beta, ConstData_t bnScale, ConstData_t bnBias, ConstData_t estimatedMean, ConstData_t estimatedVariance, double epsilon); std::vector<std::string> GetArgs() const override; miopenFusionOp_t kind() const override { return miopenFusionOpBatchNormInference; }; FusionMDGraph_Edge_Map MDGraphKey() const override; static FusionMDGraph_Edge_Map MDGraphKey(miopenBatchNormMode_t bn_mode); std::vector<size_t> GetLocalWGSz(Handle& handle, std::string algorithm_name) override; std::vector<size_t> GetGlobalWGSz(Handle& handle, std::string algorithm_name) override; miopenBatchNormMode_t mode; TensorDescriptor base_desc; }; struct ConvForwardOpDescriptor : FusionOpDescriptor { ConvForwardOpDescriptor(ConvolutionDescriptor& conv_descriptor, TensorDescriptor& filter_descriptor) : base_desc(conv_descriptor), filter_desc(filter_descriptor), kernel_info_valid(false), conv_compiler_options(""){}; miopenStatus_t GetOutputDesc(TensorDescriptor& output_desc) override; miopenStatus_t SetArgs(OperatorArgs& args, const void* alpha, const void* beta, ConstData_t w); std::vector<std::string> GetArgs() const override; miopenStatus_t GetNetworkConfig(std::string& network_config, Handle& handle) override; miopenStatus_t GetCompileParms(std::string& compile_config, Handle& handle, FusionKernelSourceType source, const std::vector<solver::AnySolver>& solvers) override; bool isASMApplicable(Handle& handle); miopenFusionOp_t kind() const override { return miopenFusionOpConvForward; }; FusionMDGraph_Edge_Map MDGraphKey() const override; static FusionMDGraph_Edge_Map MDGraphKey(miopenConvolutionMode_t conv_mode, miopenPaddingMode_t pad_mode, int pad_h, int pad_w, int u, int v, int dilation_h, int dilation_w, int k, int c, int x, int y); std::vector<size_t> GetLocalWGSz(Handle& handle, std::string algorithm_name) override; std::vector<size_t> GetGlobalWGSz(Handle& handle, std::string algorithm_name) override; ConvolutionDescriptor base_desc; TensorDescriptor filter_desc; solver::KernelInfo kernel_info; bool kernel_info_valid; std::string conv_compiler_options; private: mlo_construct_direct2D_fusion ConstructParams(Handle& handle); }; } // namespace miopen MIOPEN_DEFINE_OBJECT(miopenFusionOpDescriptor, miopen::FusionOpDescriptor); MIOPEN_DEFINE_OBJECT(miopenOperatorArgs, miopen::OperatorArgs); #endif // _MIOPEN_FUSION_HPP_ <|endoftext|>
<commit_before>// Copyright 2016 Chirstopher Torres (Raven), L3nn0x // // 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 "ccharserver.h" #include "ccharclient.h" #include "ccharisc.h" #include "epackettype.h" #include "platform_defines.h" #include "connection.h" #include <unordered_set> #include "isc_client_status.h" #include "logconsole.h" using namespace RoseCommon; void update_status(const Packet::IscClientStatus& packet, CCharServer& server, uint32_t charId) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); if (auto user = server.get_user(charId); user) { logger->debug("Char {} now has status {}", charId, packet.get_status()); const bool isSwitching = user.value()->get_status() == User::Status::SWITCHING ? true : false; user.value()->set_status(packet.get_status()); // we update the id every client on the map refers to when talking about this character. (this is different from the charId) user.value()->set_entityId(packet.get_entityMapId()); if (user.value()->get_status() == User::Status::CONNECTED && isSwitching) { // reload the map Core::CharacterTable characterTable{}; auto conn = Core::connectionPool.getConnection<Core::Osirose>(); auto charRes = conn(sqlpp::select(characterTable.map) .from(characterTable).where(characterTable.id == user.value()->get_charId())); if (charRes.empty()) { logger->error("Error while trying to access the updated map of {}", user.value()->get_charId()); return; } user.value()->set_mapId(charRes.front().map); } } else { logger->error("Error, got status packet for un-loaded {} client", packet.get_charId()); } } CCharServer::CCharServer(bool _isc, CCharServer *server) : CRoseServer(_isc), client_count_(0), server_count_(0), iscServer_(server) { register_dispatcher(std::function{update_status}); reactor_thread = std::thread([this]() { for (auto [res, task] = work_queue.pop_front(); res;) { { std::lock_guard<std::recursive_mutex> lock(access); std::invoke(std::move(task), *this); } auto [tmp_res, tmp_task] = work_queue.pop_front(); res = tmp_res; task = std::move(tmp_task); } }); } CCharServer::~CCharServer() { socket_[SocketType::Client]->shutdown(); work_queue.kill(); reactor_thread.join(); } void CCharServer::OnAccepted(std::unique_ptr<Core::INetwork> _sock) { //if (_sock->is_active()) { // Do Something? std::string _address = _sock->get_address(); if (IsISCServer() == false) { std::lock_guard<std::mutex> lock(client_list_mutex_); std::shared_ptr<CCharClient> nClient = std::make_shared<CCharClient>(this, std::move(_sock)); nClient->set_id(client_count_++); nClient->set_update_time( Core::Time::GetTickCount() ); nClient->set_active(true); nClient->start_recv(); logger_->info( "[{}] Client connected from: {}", nClient->get_id(), _address.c_str()); client_list_.push_front(std::move(nClient)); } else { std::lock_guard<std::mutex> lock(isc_list_mutex_); std::shared_ptr<CCharISC> nClient = std::make_shared<CCharISC>(this, std::move(_sock)); nClient->set_id(server_count_++); nClient->set_update_time( Core::Time::GetTickCount() ); nClient->set_active(true); nClient->start_recv(); logger_->info( "Server connected from: {}", _address.c_str() ); isc_list_.push_front(std::move(nClient)); } //} } void CCharServer::register_maps(CCharISC* isc, const std::vector<uint16_t>& maps) { std::shared_ptr<RoseCommon::CRoseClient> ptr; for (const auto& p : isc_list_) { if (p.get() == isc) { ptr = p; break; } } if (!ptr) { logger_->error("ISC server not found when registering maps!"); return; } for (const auto& m : maps) { this->maps[m] = ptr; } } void CCharServer::transfer(RoseCommon::Packet::IscTransfer&& P) { const auto& m = P.get_maps(); std::unordered_set<std::shared_ptr<CRoseClient>> set; if (m.empty()) { for (const auto& [m, p] : maps) { if (auto ptr = p.lock()) { set.insert(ptr); } } } else if (m.size() == 1 && m[0] == 0) { dispatch_packet(P.get_originatorId(), RoseCommon::fetchPacket<true>(static_cast<const uint8_t*>(P.get_blob().data()))); return; } else { for (const auto& mm : m) { if (auto ptr = maps[mm].lock()) { set.insert(ptr); } } } for (auto ptr : set) { ptr->send(P); } } void CCharServer::transfer_char(RoseCommon::Packet::IscTransferChar&& P) { std::vector<uint16_t> maps; for (auto name : P.get_names()) { if (const auto user = get_user(name); user) { maps.push_back(user.value()->get_mapId()); } } std::unordered_set<std::shared_ptr<CRoseClient>> set; for (auto map : maps) { if (auto ptr = this->maps[map].lock()) { set.insert(ptr); } } for (auto ptr : set) { ptr->send(P); } } void CCharServer::send_map(uint16_t map, const RoseCommon::CRosePacket& p) { auto packet = RoseCommon::Packet::IscTransfer::create({map}); std::vector<uint8_t> blob; p.write_to_vector(blob); packet.set_blob(blob); if (auto ptr = maps[map].lock()) { ptr->send(packet); } } void CCharServer::send_char(uint32_t character, const RoseCommon::CRosePacket& p) { const auto user = get_user(character); if (!user) { return; } auto packet = RoseCommon::Packet::IscTransferChar::create({user.value()->get_name()}); std::vector<uint8_t> blob; p.write_to_vector(blob); packet.set_blob(blob); if (auto ptr = maps[user.value()->get_mapId()].lock()) { ptr->send(packet); } } void CCharServer::send_char(const std::string& character, const RoseCommon::CRosePacket& p) { const auto user = get_user(character); if (!user) { return; } auto packet = RoseCommon::Packet::IscTransferChar::create({character}); std::vector<uint8_t> blob; p.write_to_vector(blob); packet.set_blob(blob); if (auto ptr = maps[user.value()->get_mapId()].lock()) { ptr->send(packet); } } bool CCharServer::dispatch_packet(uint32_t charId, std::unique_ptr<RoseCommon::CRosePacket>&& packet) { if (!packet) { return false; } if (!dispatcher.is_supported(*packet.get())) { return false; } work_queue.push_back([charId, packet = std::move(packet)](CCharServer& server) mutable { server.dispatcher.dispatch(std::move(packet), server, charId); }); return true; } std::optional<const User*const> CCharServer::get_user(const std::string& name) const { for (auto [k, v] : users) { if (v.get_name() == name) { return {&v}; } } return {}; } std::optional<const User*const> CCharServer::get_user(uint32_t id) const { if (auto it = users.find(id); it != users.end()) { return {&it->second}; } return {}; } std::optional<User*const> CCharServer::get_user(const std::string& name) { for (auto [k, v] : users) { if (v.get_name() == name) { return {&v}; } } return {}; } std::optional<User*const> CCharServer::get_user(uint32_t id) { if (auto it = users.find(id); it != users.end()) { return {&it->second}; } return {}; } void CCharServer::load_user(std::weak_ptr<CCharClient> client, uint32_t id) { Core::CharacterTable characterTable{}; auto conn = Core::connectionPool.getConnection<Core::Osirose>(); auto charRes = conn(sqlpp::select(characterTable.name, characterTable.map) .from(characterTable).where(characterTable.id == id)); if (charRes.empty()) { return; } User user(client, charRes.front().name, id, charRes.front().map); user.set_party(partys.get_party(id)); // we load the party if there is one for that character } void CCharServer::unload_user(uint32_t id) { users.erase(id); } <commit_msg>Update ccharserver.cpp<commit_after>// Copyright 2016 Chirstopher Torres (Raven), L3nn0x // // 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 "ccharserver.h" #include "ccharclient.h" #include "ccharisc.h" #include "epackettype.h" #include "platform_defines.h" #include "connection.h" #include <unordered_set> #include "isc_client_status.h" #include "logconsole.h" using namespace RoseCommon; void update_status(const Packet::IscClientStatus& packet, CCharServer& server, uint32_t charId) { auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock(); if (auto user = server.get_user(charId); user) { logger->debug("Char {} now has status {}", charId, packet.get_status()); const bool isSwitching = user.value()->get_status() == User::Status::SWITCHING ? true : false; user.value()->set_status(packet.get_status()); // we update the id every client on the map refers to when talking about this character. (this is different from the charId) user.value()->set_entityId(packet.get_entityMapId()); if (user.value()->get_status() == User::Status::CONNECTED && isSwitching) { // reload the map Core::CharacterTable characterTable{}; auto conn = Core::connectionPool.getConnection<Core::Osirose>(); auto charRes = conn(sqlpp::select(characterTable.map) .from(characterTable).where(characterTable.id == user.value()->get_charId())); if (charRes.empty()) { logger->error("Error while trying to access the updated map of {}", user.value()->get_charId()); return; } user.value()->set_mapId(charRes.front().map); } } else { logger->error("Error, got status packet for un-loaded {} client", packet.get_charId()); } } CCharServer::CCharServer(bool _isc, CCharServer *server) : CRoseServer(_isc), client_count_(0), server_count_(0), iscServer_(server) { register_dispatcher(std::function{update_status}); register_dispatcher(std::function{party_request}); reactor_thread = std::thread([this]() { for (auto [res, task] = work_queue.pop_front(); res;) { { std::lock_guard<std::recursive_mutex> lock(access); std::invoke(std::move(task), *this); } auto [tmp_res, tmp_task] = work_queue.pop_front(); res = tmp_res; task = std::move(tmp_task); } }); } CCharServer::~CCharServer() { socket_[SocketType::Client]->shutdown(); work_queue.kill(); reactor_thread.join(); } void CCharServer::OnAccepted(std::unique_ptr<Core::INetwork> _sock) { //if (_sock->is_active()) { // Do Something? std::string _address = _sock->get_address(); if (IsISCServer() == false) { std::lock_guard<std::mutex> lock(client_list_mutex_); std::shared_ptr<CCharClient> nClient = std::make_shared<CCharClient>(this, std::move(_sock)); nClient->set_id(client_count_++); nClient->set_update_time( Core::Time::GetTickCount() ); nClient->set_active(true); nClient->start_recv(); logger_->info( "[{}] Client connected from: {}", nClient->get_id(), _address.c_str()); client_list_.push_front(std::move(nClient)); } else { std::lock_guard<std::mutex> lock(isc_list_mutex_); std::shared_ptr<CCharISC> nClient = std::make_shared<CCharISC>(this, std::move(_sock)); nClient->set_id(server_count_++); nClient->set_update_time( Core::Time::GetTickCount() ); nClient->set_active(true); nClient->start_recv(); logger_->info( "Server connected from: {}", _address.c_str() ); isc_list_.push_front(std::move(nClient)); } //} } void CCharServer::register_maps(CCharISC* isc, const std::vector<uint16_t>& maps) { std::shared_ptr<RoseCommon::CRoseClient> ptr; for (const auto& p : isc_list_) { if (p.get() == isc) { ptr = p; break; } } if (!ptr) { logger_->error("ISC server not found when registering maps!"); return; } for (const auto& m : maps) { this->maps[m] = ptr; } } void CCharServer::transfer(RoseCommon::Packet::IscTransfer&& P) { const auto& m = P.get_maps(); std::unordered_set<std::shared_ptr<CRoseClient>> set; if (m.empty()) { for (const auto& [m, p] : maps) { if (auto ptr = p.lock()) { set.insert(ptr); } } } else if (m.size() == 1 && m[0] == 0) { dispatch_packet(P.get_originatorId(), RoseCommon::fetchPacket<true>(static_cast<const uint8_t*>(P.get_blob().data()))); return; } else { for (const auto& mm : m) { if (auto ptr = maps[mm].lock()) { set.insert(ptr); } } } for (auto ptr : set) { ptr->send(P); } } void CCharServer::transfer_char(RoseCommon::Packet::IscTransferChar&& P) { std::vector<uint16_t> maps; for (auto name : P.get_names()) { if (const auto user = get_user(name); user) { maps.push_back(user.value()->get_mapId()); } } std::unordered_set<std::shared_ptr<CRoseClient>> set; for (auto map : maps) { if (auto ptr = this->maps[map].lock()) { set.insert(ptr); } } for (auto ptr : set) { ptr->send(P); } } void CCharServer::send_map(uint16_t map, const RoseCommon::CRosePacket& p) { auto packet = RoseCommon::Packet::IscTransfer::create({map}); std::vector<uint8_t> blob; p.write_to_vector(blob); packet.set_blob(blob); if (auto ptr = maps[map].lock()) { ptr->send(packet); } } void CCharServer::send_char(uint32_t character, const RoseCommon::CRosePacket& p) { const auto user = get_user(character); if (!user) { return; } auto packet = RoseCommon::Packet::IscTransferChar::create({user.value()->get_name()}); std::vector<uint8_t> blob; p.write_to_vector(blob); packet.set_blob(blob); if (auto ptr = maps[user.value()->get_mapId()].lock()) { ptr->send(packet); } } void CCharServer::send_char(const std::string& character, const RoseCommon::CRosePacket& p) { const auto user = get_user(character); if (!user) { return; } auto packet = RoseCommon::Packet::IscTransferChar::create({character}); std::vector<uint8_t> blob; p.write_to_vector(blob); packet.set_blob(blob); if (auto ptr = maps[user.value()->get_mapId()].lock()) { ptr->send(packet); } } bool CCharServer::dispatch_packet(uint32_t charId, std::unique_ptr<RoseCommon::CRosePacket>&& packet) { if (!packet) { return false; } if (!dispatcher.is_supported(*packet.get())) { return false; } work_queue.push_back([charId, packet = std::move(packet)](CCharServer& server) mutable { server.dispatcher.dispatch(std::move(packet), server, charId); }); return true; } std::optional<const User*const> CCharServer::get_user(const std::string& name) const { for (auto [k, v] : users) { if (v.get_name() == name) { return {&v}; } } return {}; } std::optional<const User*const> CCharServer::get_user(uint32_t id) const { if (auto it = users.find(id); it != users.end()) { return {&it->second}; } return {}; } std::optional<User*const> CCharServer::get_user(const std::string& name) { for (auto [k, v] : users) { if (v.get_name() == name) { return {&v}; } } return {}; } std::optional<User*const> CCharServer::get_user(uint32_t id) { if (auto it = users.find(id); it != users.end()) { return {&it->second}; } return {}; } void CCharServer::load_user(std::weak_ptr<CCharClient> client, uint32_t id) { Core::CharacterTable characterTable{}; auto conn = Core::connectionPool.getConnection<Core::Osirose>(); auto charRes = conn(sqlpp::select(characterTable.name, characterTable.map) .from(characterTable).where(characterTable.id == id)); if (charRes.empty()) { return; } User user(client, charRes.front().name, id, charRes.front().map); user.set_party(partys.get_party(id)); // we load the party if there is one for that character } void CCharServer::unload_user(uint32_t id) { users.erase(id); } <|endoftext|>
<commit_before><commit_msg>Added missing derivative functions<commit_after><|endoftext|>
<commit_before><commit_msg>Fix in AT+CNUM command if there is no number<commit_after><|endoftext|>
<commit_before>/** \file add_oa_urls.cc * \brief Add additional urls for oa_access of items * \author Johannes Riedl */ /* Copyright (C) 2018, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <memory> #include <unordered_map> #include "Compiler.h" #include "FileUtil.h" #include "JSON.h" #include "MARC.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname \ << " doi_to_url_map.json marc_input marc_output\n"; std::exit(EXIT_FAILURE); } void CreateDoiToUrlMap(const std::string &map_filename, std::unordered_map<std::string, std::string> * const doi_to_url) { std::string json_document; if (not FileUtil::ReadString(map_filename, &json_document)) LOG_ERROR("Could not read in " + map_filename); JSON::Parser json_parser(json_document); std::shared_ptr<JSON::JSONNode> entries; if (not json_parser.parse(&entries)) LOG_ERROR("Could not properly parse \"" + map_filename + ": " + json_parser.getErrorMessage()); std::shared_ptr<JSON::ArrayNode> entry_array(JSON::JSONNode::CastToArrayNodeOrDie("", entries)); for (const auto &entry : *entry_array) { const std::string doi(LookupString("/doi", entry)); const std::string url(LookupString("/best_oa_location/url", entry)); if (not (doi.empty() or url.empty())) doi_to_url->emplace(doi, url); else LOG_ERROR("Either doi or url missing"); } } bool AlreadyHasIdenticalUrl(const MARC::Record &record, const std::string &url) { for (const auto &field : record.getTagRange("856")) { if (field.hasSubfieldWithValue('u', url)) return true; } return false; } void Augment856(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer, const std::unordered_map<std::string, std::string> &doi_to_url) { while (MARC::Record record = marc_reader->read()) { for (const auto &field : record.getTagRange("024")) { if (field.hasSubfieldWithValue('2', "doi")) { const std::string doi(field.getFirstSubfieldWithCode('a')); const auto doi_and_url(doi_to_url.find(doi)); if (doi_and_url != doi_to_url.cend()) { const std::string url(doi_and_url->second); if (not AlreadyHasIdenticalUrl(record, url)) record.insertField("856", { { 'u', url }, { 'z', "unpaywall" } }); } } } marc_writer->write(record); } } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 4) Usage(); std::unordered_map<std::string, std::string> doi_to_url; CreateDoiToUrlMap(argv[1], &doi_to_url); std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(argv[2])); std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(argv[3])); Augment856(marc_reader.get(), marc_writer.get(), doi_to_url); return EXIT_SUCCESS; } <commit_msg>Added missing empty line<commit_after>/** \file add_oa_urls.cc * \brief Add additional urls for oa_access of items * \author Johannes Riedl */ /* Copyright (C) 2018, Library of the University of Tübingen This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <memory> #include <unordered_map> #include "Compiler.h" #include "FileUtil.h" #include "JSON.h" #include "MARC.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname \ << " doi_to_url_map.json marc_input marc_output\n"; std::exit(EXIT_FAILURE); } void CreateDoiToUrlMap(const std::string &map_filename, std::unordered_map<std::string, std::string> * const doi_to_url) { std::string json_document; if (not FileUtil::ReadString(map_filename, &json_document)) LOG_ERROR("Could not read in " + map_filename); JSON::Parser json_parser(json_document); std::shared_ptr<JSON::JSONNode> entries; if (not json_parser.parse(&entries)) LOG_ERROR("Could not properly parse \"" + map_filename + ": " + json_parser.getErrorMessage()); std::shared_ptr<JSON::ArrayNode> entry_array(JSON::JSONNode::CastToArrayNodeOrDie("", entries)); for (const auto &entry : *entry_array) { const std::string doi(LookupString("/doi", entry)); const std::string url(LookupString("/best_oa_location/url", entry)); if (not (doi.empty() or url.empty())) doi_to_url->emplace(doi, url); else LOG_ERROR("Either doi or url missing"); } } bool AlreadyHasIdenticalUrl(const MARC::Record &record, const std::string &url) { for (const auto &field : record.getTagRange("856")) { if (field.hasSubfieldWithValue('u', url)) return true; } return false; } void Augment856(MARC::Reader * const marc_reader, MARC::Writer * const marc_writer, const std::unordered_map<std::string, std::string> &doi_to_url) { while (MARC::Record record = marc_reader->read()) { for (const auto &field : record.getTagRange("024")) { if (field.hasSubfieldWithValue('2', "doi")) { const std::string doi(field.getFirstSubfieldWithCode('a')); const auto doi_and_url(doi_to_url.find(doi)); if (doi_and_url != doi_to_url.cend()) { const std::string url(doi_and_url->second); if (not AlreadyHasIdenticalUrl(record, url)) record.insertField("856", { { 'u', url }, { 'z', "unpaywall" } }); } } } marc_writer->write(record); } } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 4) Usage(); std::unordered_map<std::string, std::string> doi_to_url; CreateDoiToUrlMap(argv[1], &doi_to_url); std::unique_ptr<MARC::Reader> marc_reader(MARC::Reader::Factory(argv[2])); std::unique_ptr<MARC::Writer> marc_writer(MARC::Writer::Factory(argv[3])); Augment856(marc_reader.get(), marc_writer.get(), doi_to_url); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*************************************************************************** addroomform.cpp - description ------------------- begin : Sun Jan 1 2004 copyright : (C) 2004 by Lalescu Liviu email : Please see https://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address) ***************************************************************************/ /*************************************************************************** * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * ***************************************************************************/ #include "addroomform.h" #include "longtextmessagebox.h" #include <QMessageBox> AddRoomForm::AddRoomForm(QWidget* parent): QDialog(parent) { setupUi(this); addRoomPushButton->setDefault(true); connect(closePushButton, SIGNAL(clicked()), this, SLOT(close())); connect(helpPushButton, SIGNAL(clicked()), this, SLOT(help())); connect(addRoomPushButton, SIGNAL(clicked()), this, SLOT(addRoom())); centerWidgetOnScreen(this); restoreFETDialogGeometry(this); QSize tmp5=buildingsComboBox->minimumSizeHint(); Q_UNUSED(tmp5); buildingsComboBox->clear(); buildingsComboBox->addItem(""); for(int i=0; i<gt.rules.buildingsList.size(); i++) buildingsComboBox->addItem(gt.rules.buildingsList.at(i)->name); capacitySpinBox->setMinimum(1); capacitySpinBox->setMaximum(MAX_ROOM_CAPACITY); capacitySpinBox->setValue(MAX_ROOM_CAPACITY); } AddRoomForm::~AddRoomForm() { saveFETDialogGeometry(this); } void AddRoomForm::addRoom() { if(nameLineEdit->text().isEmpty()){ QMessageBox::information(this, tr("FET information"), tr("Incorrect name")); return; } if(buildingsComboBox->currentIndex()<0){ QMessageBox::information(this, tr("FET information"), tr("Incorrect building")); return; } Room* rm=new Room(); rm->name=nameLineEdit->text(); rm->building=buildingsComboBox->currentText(); rm->capacity=capacitySpinBox->value(); if(!gt.rules.addRoom(rm)){ QMessageBox::information(this, tr("Room insertion dialog"), tr("Could not insert item. Must be a duplicate")); delete rm; } else{ QMessageBox::information(this, tr("Room insertion dialog"), tr("Room added")); } nameLineEdit->selectAll(); nameLineEdit->setFocus(); } void AddRoomForm::help() { QString s; s=tr("It is advisable to generate the timetable without the rooms (or without rooms' constraints), then, if a solution is possible, to add rooms or rooms' constraints"); s+="\n\n"; s+=tr("Please note that each room can hold a single activity at a specified period. If you" " have a very large room, which can hold more activities at one time, please add more rooms," " representing this larger room"); LongTextMessageBox::largeInformation(this, tr("FET - help on adding room(s)"), s); } <commit_msg>prefer foreach statements<commit_after>/*************************************************************************** addroomform.cpp - description ------------------- begin : Sun Jan 1 2004 copyright : (C) 2004 by Lalescu Liviu email : Please see https://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address) ***************************************************************************/ /*************************************************************************** * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU Affero General Public License as * * published by the Free Software Foundation, either version 3 of the * * License, or (at your option) any later version. * * * ***************************************************************************/ #include "addroomform.h" #include "longtextmessagebox.h" #include <QMessageBox> AddRoomForm::AddRoomForm(QWidget* parent): QDialog(parent) { setupUi(this); addRoomPushButton->setDefault(true); connect(closePushButton, SIGNAL(clicked()), this, SLOT(close())); connect(helpPushButton, SIGNAL(clicked()), this, SLOT(help())); connect(addRoomPushButton, SIGNAL(clicked()), this, SLOT(addRoom())); centerWidgetOnScreen(this); restoreFETDialogGeometry(this); QSize tmp5=buildingsComboBox->minimumSizeHint(); Q_UNUSED(tmp5); buildingsComboBox->clear(); buildingsComboBox->addItem(""); foreach (const Building *building, gt.rules.buildingsList) buildingsComboBox->addItem(building->name); capacitySpinBox->setMinimum(1); capacitySpinBox->setMaximum(MAX_ROOM_CAPACITY); capacitySpinBox->setValue(MAX_ROOM_CAPACITY); } AddRoomForm::~AddRoomForm() { saveFETDialogGeometry(this); } void AddRoomForm::addRoom() { if(nameLineEdit->text().isEmpty()){ QMessageBox::information(this, tr("FET information"), tr("Incorrect name")); return; } if(buildingsComboBox->currentIndex()<0){ QMessageBox::information(this, tr("FET information"), tr("Incorrect building")); return; } Room* rm=new Room(); rm->name=nameLineEdit->text(); rm->building=buildingsComboBox->currentText(); rm->capacity=capacitySpinBox->value(); if(!gt.rules.addRoom(rm)){ QMessageBox::information(this, tr("Room insertion dialog"), tr("Could not insert item. Must be a duplicate")); delete rm; } else{ QMessageBox::information(this, tr("Room insertion dialog"), tr("Room added")); } nameLineEdit->selectAll(); nameLineEdit->setFocus(); } void AddRoomForm::help() { QString s; s=tr("It is advisable to generate the timetable without the rooms (or without rooms' constraints), then, if a solution is possible, to add rooms or rooms' constraints"); s+="\n\n"; s+=tr("Please note that each room can hold a single activity at a specified period. If you" " have a very large room, which can hold more activities at one time, please add more rooms," " representing this larger room"); LongTextMessageBox::largeInformation(this, tr("FET - help on adding room(s)"), s); } <|endoftext|>
<commit_before>/// Useful conversion in visual studio const char* toConstChar(std:string strg) { return strg.c_str() } <commit_msg>Update stringopps.cpp<commit_after>/// Useful conversion in visual studio const char* toConstChar(std::string strg) { return strg.c_str() } <|endoftext|>
<commit_before>#pragma once #ifndef RAZ_STRUTILS_HPP #define RAZ_STRUTILS_HPP #include <algorithm> #include <cctype> #include <string> namespace Raz { namespace StrUtils { inline char toLowercase(char& character) { character = static_cast<char>(std::tolower(static_cast<unsigned char>(character))); return character; } inline std::string& toLowercase(std::string& text) { std::transform(text.begin(), text.end(), text.begin(), ::tolower); return text; } inline char toUppercase(char& character) { character = static_cast<char>(std::toupper(static_cast<unsigned char>(character))); return character; } inline std::string& toUppercase(std::string& text) { std::transform(text.begin(), text.end(), text.begin(), ::toupper); return text; } inline char toLowercaseCopy(char character) { toLowercase(character); return character; } inline std::string toLowercaseCopy(std::string text) { toLowercase(text); return text; } inline char toUppercaseCopy(char character) { toUppercase(character); return character; } inline std::string toUppercaseCopy(std::string text) { toUppercase(text); return text; } inline std::string& trimLeft(std::string& text) { text.erase(text.begin(), std::find_if(text.begin(), text.end(), [] (int c) { return !std::isspace(c); })); return text; } inline std::string& trimRight(std::string& text) { text.erase(std::find_if(text.rbegin(), text.rend(), [] (int c) { return !std::isspace(c); }).base(), text.end()); return text; } inline std::string& trim(std::string& text) { trimLeft(text); trimRight(text); return text; } inline std::string trimLeftCopy(std::string text) { trimLeft(text); return text; } inline std::string trimRightCopy(std::string text) { trimRight(text); return text; } inline std::string trimCopy(std::string text) { trim(text); return text; } } // namespace StrUtils } // namespace Raz #endif // RAZ_STRUTILS_HPP <commit_msg>[Update] Added a string splitting function to StrUtils<commit_after>#pragma once #ifndef RAZ_STRUTILS_HPP #define RAZ_STRUTILS_HPP #include <algorithm> #include <cctype> #include <string> namespace Raz { namespace StrUtils { inline char toLowercase(char& character) { character = static_cast<char>(std::tolower(static_cast<unsigned char>(character))); return character; } inline std::string& toLowercase(std::string& text) { std::transform(text.begin(), text.end(), text.begin(), ::tolower); return text; } inline char toUppercase(char& character) { character = static_cast<char>(std::toupper(static_cast<unsigned char>(character))); return character; } inline std::string& toUppercase(std::string& text) { std::transform(text.begin(), text.end(), text.begin(), ::toupper); return text; } inline char toLowercaseCopy(char character) { toLowercase(character); return character; } inline std::string toLowercaseCopy(std::string text) { toLowercase(text); return text; } inline char toUppercaseCopy(char character) { toUppercase(character); return character; } inline std::string toUppercaseCopy(std::string text) { toUppercase(text); return text; } inline std::string& trimLeft(std::string& text) { text.erase(text.begin(), std::find_if(text.begin(), text.end(), [] (int c) { return !std::isspace(c); })); return text; } inline std::string& trimRight(std::string& text) { text.erase(std::find_if(text.rbegin(), text.rend(), [] (int c) { return !std::isspace(c); }).base(), text.end()); return text; } inline std::string& trim(std::string& text) { trimLeft(text); trimRight(text); return text; } inline std::string trimLeftCopy(std::string text) { trimLeft(text); return text; } inline std::string trimRightCopy(std::string text) { trimRight(text); return text; } inline std::string trimCopy(std::string text) { trim(text); return text; } inline std::vector<std::string> split(std::string inputStr, char delimiter) { trimRight(inputStr); std::vector<std::string> parts {}; while (!inputStr.empty()) { const std::size_t delimPos = inputStr.find_first_of(delimiter); if (delimPos > inputStr.size()) { parts.push_back(inputStr); break; } parts.push_back(inputStr.substr(0, delimPos)); trimRight(parts.back()); inputStr.erase(0, delimPos + 1); trimLeft(inputStr); } return parts; } } // namespace StrUtils } // namespace Raz #endif // RAZ_STRUTILS_HPP <|endoftext|>
<commit_before>#pragma once #include "Head.h" #include <iostream> #include "maths.hpp" constexpr const int32_t BASE_MOD = 1000000007; template<typename T> inline T& add_mod(T& a, const T b, const T mod = BASE_MOD) { if ((a += b) >= mod) { a -= mod; } return a; } template<typename T> inline T& sub_mod(T& a, const T b, const T mod = BASE_MOD) { if ((a -= b) < 0) { a += mod; } return a; } template<typename T> inline T& mul_mod(T& a, const T b, const T mod = BASE_MOD) { a = static_cast<ll>(a) * b % mod; return a; } template<typename T, T MOD = BASE_MOD> class ModInt { public: constexpr ModInt() : ModInt(0) {} template<typename U> constexpr ModInt(const U value) : value_(normalize(value)) { static_assert(MOD > 0, "Modulo must be strictly positive."); // static_assert((std::equal<T, int32_t> && mod <= 0x3f3f3f3f) || (std::equal<T, int64_t> && mod <= 0x3f3f3f3f3f3f3f3fLL), "Modulo must be less than half of the max value for typename."); } constexpr T value() const { return value_; } constexpr bool operator ==(const ModInt rhs) const { return value_ == rhs.value_; } constexpr bool operator !=(const ModInt rhs) const { return !operator==(rhs); } constexpr bool operator <(const ModInt& rhs) const { return value_ < rhs.value_; } constexpr bool operator >(const ModInt& rhs) const { return value_ > rhs.value_; } constexpr ModInt operator +(const ModInt rhs) const { T x = value_; return{ add_mod(x, rhs.value_, MOD) }; } constexpr ModInt operator -(const ModInt rhs) const { T x = value_; return{ sub_mod(x, rhs.value_, MOD) }; } ModInt operator *(const ModInt rhs) const { T x = value_; return{ mul_mod(x, rhs.value_, MOD) }; } ModInt& operator +=(const ModInt rhs) { add_mod(value_, rhs.value_, MOD); return *this; } ModInt& operator -=(const ModInt rhs) { sub_mod(value_, rhs.value_, MOD); return *this; } ModInt& operator *=(const ModInt rhs) { mul_mod(value_, rhs.value_, MOD); return *this; } ModInt operator ++(int) { const ModInt ret(value_); add_mod(value_, 1, MOD); return ret; } ModInt operator --(int) { const ModInt ret(value_); sub_mod(value_, 1, MOD); return ret; } ModInt& operator ++() { add_mod(value_, 1, MOD); return *this; } ModInt& operator --() { sub_mod(value_, 1, MOD); return *this; } constexpr ModInt inverse() const { return{ inverseElement(static_cast<ll>(value_), MOD) }; } friend std::istream& operator >>(std::istream& in, ModInt& rhs) { T x; in >> x; rhs.value = rhs.normalize(x); return in; } friend std::ostream& operator <<(std::ostream& out, ModInt& rhs) { out << rhs.value_; return out; } private: T value_; template<typename U> T normalize(const U value) const { T ret = value % MOD; if (ret < 0) { return ret + MOD; } return ret; } };<commit_msg>Implemented std::is_integral for ModInt.<commit_after>#pragma once #include "Head.h" #include <iostream> #include "maths.hpp" constexpr const int32_t BASE_MOD = 1000000007; template<typename T> inline T& add_mod(T& a, const T b, const T mod = BASE_MOD) { if ((a += b) >= mod) { a -= mod; } return a; } template<typename T> inline T& sub_mod(T& a, const T b, const T mod = BASE_MOD) { if ((a -= b) < 0) { a += mod; } return a; } template<typename T> inline T& mul_mod(T& a, const T b, const T mod = BASE_MOD) { a = static_cast<ll>(a) * b % mod; return a; } template<typename T, T MOD = BASE_MOD> class ModInt { public: constexpr ModInt() : ModInt(0) {} template<typename U> constexpr ModInt(const U value) : value_(normalize(value)) { static_assert(MOD > 0, "Modulo must be strictly positive."); // static_assert((std::equal<T, int32_t> && mod <= 0x3f3f3f3f) || (std::equal<T, int64_t> && mod <= 0x3f3f3f3f3f3f3f3fLL), "Modulo must be less than half of the max value for typename."); } constexpr T value() const { return value_; } constexpr bool operator ==(const ModInt rhs) const { return value_ == rhs.value_; } constexpr bool operator !=(const ModInt rhs) const { return !operator==(rhs); } constexpr bool operator <(const ModInt& rhs) const { return value_ < rhs.value_; } constexpr bool operator >(const ModInt& rhs) const { return value_ > rhs.value_; } constexpr ModInt operator +(const ModInt rhs) const { T x = value_; return{ add_mod(x, rhs.value_, MOD) }; } constexpr ModInt operator -(const ModInt rhs) const { T x = value_; return{ sub_mod(x, rhs.value_, MOD) }; } ModInt operator *(const ModInt rhs) const { T x = value_; return{ mul_mod(x, rhs.value_, MOD) }; } ModInt& operator +=(const ModInt rhs) { add_mod(value_, rhs.value_, MOD); return *this; } ModInt& operator -=(const ModInt rhs) { sub_mod(value_, rhs.value_, MOD); return *this; } ModInt& operator *=(const ModInt rhs) { mul_mod(value_, rhs.value_, MOD); return *this; } ModInt operator ++(int) { const ModInt ret(value_); add_mod(value_, 1, MOD); return ret; } ModInt operator --(int) { const ModInt ret(value_); sub_mod(value_, 1, MOD); return ret; } ModInt& operator ++() { add_mod(value_, 1, MOD); return *this; } ModInt& operator --() { sub_mod(value_, 1, MOD); return *this; } constexpr ModInt inverse() const { return{ inverseElement(static_cast<ll>(value_), MOD) }; } friend std::istream& operator >>(std::istream& in, ModInt& rhs) { T x; in >> x; rhs.value = rhs.normalize(x); return in; } friend std::ostream& operator <<(std::ostream& out, ModInt& rhs) { out << rhs.value_; return out; } private: T value_; template<typename U> T normalize(const U value) const { T ret = value % MOD; if (ret < 0) { return ret + MOD; } return ret; } }; namespace std { template<typename T, T MOD> struct is_integral<ModInt<T, MOD>> : std::true_type {}; } <|endoftext|>
<commit_before>#include "qaesencryption.h" #include <QDebug> #define Multiply(x, y) \ ( ((y & 1) * x) ^ \ ((y>>1 & 1) * xTime(x)) ^ \ ((y>>2 & 1) * xTime(xTime(x))) ^ \ ((y>>3 & 1) * xTime(xTime(xTime(x)))) ^ \ ((y>>4 & 1) * xTime(xTime(xTime(xTime(x)))))) \ QAESEncryption::QAESEncryption(QAESEncryption::AES level, QAESEncryption::MODE mode) : m_level(level), m_mode(mode) { m_state = NULL; switch (level) { case AES_128: { AES128 aes; m_nk = aes.nk; m_keyLen = aes.keylen; m_nr = aes.nr; m_expandedKey = aes.expandedKey; qDebug() << "AES128"; } break; case AES_192: { AES192 aes; m_nk = aes.nk; m_keyLen = aes.keylen; m_nr = aes.nr; m_expandedKey = aes.expandedKey; } break; case AES_256: { AES256 aes; m_nk = aes.nk; m_keyLen = aes.keylen; m_nr = aes.nr; m_expandedKey = aes.expandedKey; } break; default: { AES128 aes; m_nk = aes.nk; m_keyLen = aes.keylen; m_nr = aes.nr; m_expandedKey = aes.expandedKey; } break; } } QByteArray QAESEncryption::expandKey(const QByteArray key) { int i, k; quint8 tempa[4]; // Used for the column/row operations QByteArray roundKey(key); qDebug() << "Key expansion before" << roundKey.size(); // The first round key is the key itself. /*for(i = 0; i < m_nk; ++i) { roundKey.replace((i * 4) + 0, (quint8) key.at((i * 4) + 0)); roundKey.replace((i * 4) + 1, (quint8) key.at((i * 4) + 1)); roundKey.replace((i * 4) + 2, (quint8) key.at((i * 4) + 2)); roundKey.replace((i * 4) + 3, (quint8) key.at((i * 4) + 3)); }*/ // All other round keys are found from the previous round keys. //i == Nk for(i = m_nk; i < m_nb * (m_nr + 1); i++) { { tempa[0] = (quint8) roundKey.at((i-1) * 4 + 0); tempa[1] = (quint8) roundKey.at((i-1) * 4 + 1); tempa[2] = (quint8) roundKey.at((i-1) * 4 + 2); tempa[3] = (quint8) roundKey.at((i-1) * 4 + 3); } if (i % m_nk == 0) { // This function shifts the 4 bytes in a word to the left once. // [a0,a1,a2,a3] becomes [a1,a2,a3,a0] // Function RotWord() { k = tempa[0]; tempa[0] = tempa[1]; tempa[1] = tempa[2]; tempa[2] = tempa[3]; tempa[3] = k; } // SubWord() is a function that takes a four-byte input word and // applies the S-box to each of the four bytes to produce an output word. // Function Subword() { tempa[0] = getSBoxValue(tempa[0]); tempa[1] = getSBoxValue(tempa[1]); tempa[2] = getSBoxValue(tempa[2]); tempa[3] = getSBoxValue(tempa[3]); } tempa[0] = tempa[0] ^ Rcon[i/m_nk]; } if (m_level == AES_256 && i % m_nk == 4) { // Function Subword() { tempa[0] = getSBoxValue(tempa[0]); tempa[1] = getSBoxValue(tempa[1]); tempa[2] = getSBoxValue(tempa[2]); tempa[3] = getSBoxValue(tempa[3]); } } roundKey.insert(i * 4 + 0, roundKey.at((i - m_nk) * 4 + 0) ^ tempa[0]); roundKey.insert(i * 4 + 1, roundKey.at((i - m_nk) * 4 + 1) ^ tempa[1]); roundKey.insert(i * 4 + 2, roundKey.at((i - m_nk) * 4 + 2) ^ tempa[2]); roundKey.insert(i * 4 + 3, roundKey.at((i - m_nk) * 4 + 3) ^ tempa[3]); } qDebug() << "Key expansion after" << roundKey.size(); return roundKey; } // This function adds the round key to state. // The round key is added to the state by an XOR function. void QAESEncryption::addRoundKey(quint8 round, const QByteArray expKey) { QByteArray::iterator it = m_state->begin(); for(int i=0; i < 16; i++) it[i] = (quint8)it[i] ^ (quint8)expKey.at(round * m_nb * 4 + (i/4) * m_nb + (i%4)); } // The SubBytes Function Substitutes the values in the // state matrix with values in an S-box. void QAESEncryption::subBytes() { QByteArray::iterator it = m_state->begin(); for(int i = 0; i < 16; i++) it[i] = getSBoxValue((quint8) it[i]); } // The ShiftRows() function shifts the rows in the state to the left. // Each row is shifted with different offset. // Offset = Row number. So the first row is not shifted. void QAESEncryption::shiftRows() { QByteArray::iterator it = m_state->begin(); quint8 temp; //Shift 1 temp = (quint8) it[4]; it[4] = it[4+1]; it[4+1] = it[4+2]; it[4+2] = it[4+3]; it[4+3] = temp; //Shift 2 temp = (quint8) it[8]; it[8] = it[8+2]; it[8+2] = temp; temp = it[8+1]; it[8+1] = it[8+3]; it[8+3] = temp; //Shift 3 temp = (quint8) it[12]; it[12] = it[12+3]; it[12+3] = it[12+2]; it[12+2] = it[12+1]; it[12+1] = temp; } // MixColumns function mixes the columns of the state matrix //optimized!! void QAESEncryption::mixColumns() { QByteArray::iterator it = m_state->begin(); quint8 Tmp,Tm,t; for(int i = 0; i < 16; i+=4) { t = (quint8) it[i]; Tmp = (quint8) it[i] ^ (quint8) it[i+1] ^ (quint8) it[i+2] ^ (quint8) it[i+3] ; Tm = (quint8) it[i] ^ (quint8) it[i+1]; Tm = xTime(Tm); it[i] = (quint8) it[i] ^ Tm ^ Tmp; Tm = (quint8) it[i+1] ^ (quint8) it[i+2]; Tm = xTime(Tm); it[i+1] = (quint8) it[i+1] ^ Tm ^ Tmp; Tm = (quint8) it[i+2] ^ (quint8) it[i+3]; Tm = xTime(Tm); it[i+2] = (quint8) it[i+2] ^ Tm ^ Tmp; Tm = (quint8) it[i+3] ^ t; Tm = xTime(Tm); it[i+3] = (quint8) it[i+3] ^ Tm ^ Tmp; } } // MixColumns function mixes the columns of the state matrix. // The method used to multiply may be difficult to understand for the inexperienced. // Please use the references to gain more information. void QAESEncryption::invMixColumns() { QByteArray::iterator it = m_state->begin(); quint8 a,b,c,d; for(int i = 0; i < 16; i+=4) { a = (quint8) it[i]; b = (quint8) it[i+1]; c = (quint8) it[i+2]; d = (quint8) it[i+3]; it[i] = (quint8) (Multiply(a, 0x0e) ^ Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09)); it[i+1] = (quint8) (Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d)); it[i+2] = (quint8) (Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b)); it[i+3] = (quint8) (Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e)); } } // The SubBytes Function Substitutes the values in the // state matrix with values in an S-box. void QAESEncryption::invSubBytes() { QByteArray::iterator it = m_state->begin(); for(int i = 0; i < 16; ++i) it[i] = getSBoxInvert(it[i]); } void QAESEncryption::invShiftRows() { QByteArray::iterator it = m_state->begin(); uint8_t temp; //Shift 1 to right temp = (quint8) it[4+3]; it[4+3] = it[4+2]; it[4+2] = it[4+1]; it[4+1] = it[4]; it[4] = temp; //Shift 2 temp = (quint8) it[8+2]; it[8+2] = it[8]; it[8] = temp; temp = (quint8) it[8+3]; it[8+3] = it[8+1]; it[8+1] = temp; //Shift 3 //PROBABLY WRONG!! temp = (quint8) it[12+3]; it[12+3] = it[12]; it[12] = it[12+1]; it[12+1] = it[12+2]; it[12+2] = temp; } // Cipher is the main function that encrypts the PlainText. QByteArray QAESEncryption::cipher(const QByteArray expKey, const QByteArray in) { //m_state is the input buffer.... handle it! QByteArray output(in); m_state = &output; quint8 round = 0; // Add the First round key to the state before starting the rounds. addRoundKey(0, expKey); qDebug() << print(output); // There will be Nr rounds. // The first Nr-1 rounds are identical. // These Nr-1 rounds are executed in the loop below. for(round = 1; round < m_nr; ++round) { subBytes(); shiftRows(); mixColumns(); addRoundKey(round, expKey); } // The last round is given below. // The MixColumns function is not here in the last round. subBytes(); shiftRows(); addRoundKey(m_nr, expKey); return output; } QByteArray QAESEncryption::invCipher(const QByteArray expKey, const QByteArray in) { //m_state is the input buffer.... handle it! QByteArray output(in); m_state = &output; uint8_t round = 0; // Add the First round key to the state before starting the rounds. addRoundKey(m_nr, expKey); // There will be Nr rounds. // The first Nr-1 rounds are identical. // These Nr-1 rounds are executed in the loop below. for(round=m_nr-1;round>0;round--) { invShiftRows(); invSubBytes(); addRoundKey(round, expKey); invMixColumns(); } // The last round is given below. // The MixColumns function is not here in the last round. invShiftRows(); invSubBytes(); addRoundKey(0, expKey); return output; } QByteArray QAESEncryption::encode(const QByteArray rawText, const QByteArray key, const QByteArray iv) { if (m_mode == CBC && iv == NULL) return NULL; //EMIT ERROR! //qDebug() << "key" << print(key); QByteArray expandedKey = expandKey(key); // The next function call encrypts the PlainText with the Key using AES algorithm. return cipher(expandedKey, rawText); } QString QAESEncryption::print(QByteArray in) { QString ret=""; for (int i=0; i < in.size();i++) ret.append(QString("0x%1 ").arg(QString::number((quint8)in.at(i), 16))); return ret; } QByteArray QAESEncryption::decode(const QByteArray rawText, const QByteArray key, const QByteArray iv) { if (m_mode == CBC && iv == NULL) return NULL; //EMIT ERROR! QByteArray expandedKey = expandKey(key); return invCipher(expandedKey, rawText); } <commit_msg>cleaning<commit_after>#include "qaesencryption.h" #include <QDebug> #define Multiply(x, y) \ ( ((y & 1) * x) ^ \ ((y>>1 & 1) * xTime(x)) ^ \ ((y>>2 & 1) * xTime(xTime(x))) ^ \ ((y>>3 & 1) * xTime(xTime(xTime(x)))) ^ \ ((y>>4 & 1) * xTime(xTime(xTime(xTime(x)))))) \ QAESEncryption::QAESEncryption(QAESEncryption::AES level, QAESEncryption::MODE mode) : m_level(level), m_mode(mode) { m_state = NULL; switch (level) { case AES_128: { AES128 aes; m_nk = aes.nk; m_keyLen = aes.keylen; m_nr = aes.nr; m_expandedKey = aes.expandedKey; qDebug() << "AES128"; } break; case AES_192: { AES192 aes; m_nk = aes.nk; m_keyLen = aes.keylen; m_nr = aes.nr; m_expandedKey = aes.expandedKey; qDebug() << "AES192"; } break; case AES_256: { AES256 aes; m_nk = aes.nk; m_keyLen = aes.keylen; m_nr = aes.nr; m_expandedKey = aes.expandedKey; qDebug() << "AES256"; } break; default: { AES128 aes; m_nk = aes.nk; m_keyLen = aes.keylen; m_nr = aes.nr; m_expandedKey = aes.expandedKey; qDebug() << "Defaulting to AES128"; } break; } } QByteArray QAESEncryption::expandKey(const QByteArray key) { int i, k; quint8 tempa[4]; // Used for the column/row operations QByteArray roundKey(key); qDebug() << "Key expansion before" << roundKey.size(); // The first round key is the key itself. // ... // All other round keys are found from the previous round keys. //i == Nk for(i = m_nk; i < m_nb * (m_nr + 1); i++) { { tempa[0] = (quint8) roundKey.at((i-1) * 4 + 0); tempa[1] = (quint8) roundKey.at((i-1) * 4 + 1); tempa[2] = (quint8) roundKey.at((i-1) * 4 + 2); tempa[3] = (quint8) roundKey.at((i-1) * 4 + 3); } if (i % m_nk == 0) { // This function shifts the 4 bytes in a word to the left once. // [a0,a1,a2,a3] becomes [a1,a2,a3,a0] // Function RotWord() { k = tempa[0]; tempa[0] = tempa[1]; tempa[1] = tempa[2]; tempa[2] = tempa[3]; tempa[3] = k; } // SubWord() is a function that takes a four-byte input word and // applies the S-box to each of the four bytes to produce an output word. // Function Subword() { tempa[0] = getSBoxValue(tempa[0]); tempa[1] = getSBoxValue(tempa[1]); tempa[2] = getSBoxValue(tempa[2]); tempa[3] = getSBoxValue(tempa[3]); } tempa[0] = tempa[0] ^ Rcon[i/m_nk]; } if (m_level == AES_256 && i % m_nk == 4) { // Function Subword() { qDebug() << "AES_256"; tempa[0] = getSBoxValue(tempa[0]); tempa[1] = getSBoxValue(tempa[1]); tempa[2] = getSBoxValue(tempa[2]); tempa[3] = getSBoxValue(tempa[3]); } } roundKey.insert(i * 4 + 0, roundKey.at((i - m_nk) * 4 + 0) ^ tempa[0]); roundKey.insert(i * 4 + 1, roundKey.at((i - m_nk) * 4 + 1) ^ tempa[1]); roundKey.insert(i * 4 + 2, roundKey.at((i - m_nk) * 4 + 2) ^ tempa[2]); roundKey.insert(i * 4 + 3, roundKey.at((i - m_nk) * 4 + 3) ^ tempa[3]); } //qDebug() << print(roundKey); return roundKey; } // This function adds the round key to state. // The round key is added to the state by an XOR function. void QAESEncryption::addRoundKey(quint8 round, const QByteArray expKey) { QByteArray::iterator it = m_state->begin(); for(int i=0; i < 16; i++) it[i] = (quint8)it[i] ^ (quint8)expKey.at(round * m_nb * 4 + (i/4) * m_nb + (i%4)); } // The SubBytes Function Substitutes the values in the // state matrix with values in an S-box. void QAESEncryption::subBytes() { QByteArray::iterator it = m_state->begin(); for(int i = 0; i < 16; i++) it[i] = getSBoxValue((quint8) it[i]); } // The ShiftRows() function shifts the rows in the state to the left. // Each row is shifted with different offset. // Offset = Row number. So the first row is not shifted. void QAESEncryption::shiftRows() { QByteArray::iterator it = m_state->begin(); quint8 temp; //Shift 1 to left temp = (quint8) it[4]; it[4] = it[4+1]; it[4+1] = it[4+2]; it[4+2] = it[4+3]; it[4+3] = temp; //Shift 2 to left temp = (quint8) it[8]; it[8] = it[8+2]; it[8+2] = temp; temp = it[8+1]; it[8+1] = it[8+3]; it[8+3] = temp; //Shift 3 to left temp = (quint8) it[12]; it[12] = it[12+3]; it[12+3] = it[12+2]; it[12+2] = it[12+1]; it[12+1] = temp; } // MixColumns function mixes the columns of the state matrix //optimized!! void QAESEncryption::mixColumns() { QByteArray::iterator it = m_state->begin(); quint8 Tmp,Tm,t; for(int i = 0; i < 16; i+=4) { t = (quint8) it[i]; Tmp = (quint8) it[i] ^ (quint8) it[i+1] ^ (quint8) it[i+2] ^ (quint8) it[i+3] ; Tm = (quint8) it[i] ^ (quint8) it[i+1]; Tm = xTime(Tm); it[i] = (quint8) it[i] ^ Tm ^ Tmp; Tm = (quint8) it[i+1] ^ (quint8) it[i+2]; Tm = xTime(Tm); it[i+1] = (quint8) it[i+1] ^ Tm ^ Tmp; Tm = (quint8) it[i+2] ^ (quint8) it[i+3]; Tm = xTime(Tm); it[i+2] = (quint8) it[i+2] ^ Tm ^ Tmp; Tm = (quint8) it[i+3] ^ t; Tm = xTime(Tm); it[i+3] = (quint8) it[i+3] ^ Tm ^ Tmp; } } // MixColumns function mixes the columns of the state matrix. // The method used to multiply may be difficult to understand for the inexperienced. // Please use the references to gain more information. void QAESEncryption::invMixColumns() { QByteArray::iterator it = m_state->begin(); quint8 a,b,c,d; for(int i = 0; i < 16; i+=4) { a = (quint8) it[i]; b = (quint8) it[i+1]; c = (quint8) it[i+2]; d = (quint8) it[i+3]; it[i] = (quint8) (Multiply(a, 0x0e) ^ Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09)); it[i+1] = (quint8) (Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d)); it[i+2] = (quint8) (Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b)); it[i+3] = (quint8) (Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e)); } } // The SubBytes Function Substitutes the values in the // state matrix with values in an S-box. void QAESEncryption::invSubBytes() { QByteArray::iterator it = m_state->begin(); for(int i = 0; i < 16; ++i) it[i] = getSBoxInvert(it[i]); } void QAESEncryption::invShiftRows() { QByteArray::iterator it = m_state->begin(); uint8_t temp; //Shift 1 to right temp = (quint8) it[4+3]; it[4+3] = it[4+2]; it[4+2] = it[4+1]; it[4+1] = it[4]; it[4] = temp; //Shift 2 temp = (quint8) it[8+2]; it[8+2] = it[8]; it[8] = temp; temp = (quint8) it[8+3]; it[8+3] = it[8+1]; it[8+1] = temp; //Shift 3 temp = (quint8) it[12+3]; it[12+3] = it[12]; it[12] = it[12+1]; it[12+1] = it[12+2]; it[12+2] = temp; } // Cipher is the main function that encrypts the PlainText. QByteArray QAESEncryption::cipher(const QByteArray expKey, const QByteArray in) { //m_state is the input buffer.... handle it! QByteArray output(in); m_state = &output; quint8 round = 0; // Add the First round key to the state before starting the rounds. addRoundKey(0, expKey); //qDebug() << print(output); // There will be Nr rounds. // The first Nr-1 rounds are identical. // These Nr-1 rounds are executed in the loop below. for(round = 1; round < m_nr; ++round) { subBytes(); shiftRows(); mixColumns(); addRoundKey(round, expKey); } // The last round is given below. // The MixColumns function is not here in the last round. subBytes(); shiftRows(); addRoundKey(m_nr, expKey); return output; } QByteArray QAESEncryption::invCipher(const QByteArray expKey, const QByteArray in) { //m_state is the input buffer.... handle it! QByteArray output(in); m_state = &output; uint8_t round = 0; // Add the First round key to the state before starting the rounds. addRoundKey(m_nr, expKey); // There will be Nr rounds. // The first Nr-1 rounds are identical. // These Nr-1 rounds are executed in the loop below. for(round=m_nr-1;round>0;round--) { invShiftRows(); invSubBytes(); addRoundKey(round, expKey); invMixColumns(); } // The last round is given below. // The MixColumns function is not here in the last round. invShiftRows(); invSubBytes(); addRoundKey(0, expKey); return output; } QByteArray QAESEncryption::encode(const QByteArray rawText, const QByteArray key, const QByteArray iv) { if (m_mode == CBC && iv.isNull()) return QByteArray(); //qDebug() << "key" << print(key); QByteArray expandedKey = expandKey(key); // The next function call encrypts the PlainText with the Key using AES algorithm. return cipher(expandedKey, rawText); } QString QAESEncryption::print(QByteArray in) { QString ret=""; for (int i=0; i < in.size();i++) ret.append(QString("0x%1 ").arg(QString::number((quint8)in.at(i), 16))); return ret; } QByteArray QAESEncryption::decode(const QByteArray rawText, const QByteArray key, const QByteArray iv) { if (m_mode == CBC && iv.isNull()) return QByteArray(); QByteArray expandedKey = expandKey(key); return invCipher(expandedKey, rawText); } <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details #include <boost/uuid/uuid_generators.hpp> #include "message.h" using namespace visionaray::async; //-------------------------------------------------------------------------------------------------- // message::header // message::header::header() : id_(boost::uuids::nil_uuid()) , type_(0) , size_(0) { } message::header::header(boost::uuids::uuid const& id, unsigned type, unsigned size) : id_(id) , type_(type) , size_(size) { } message::header::~header() { } //-------------------------------------------------------------------------------------------------- // message // message::message() { } message::message(unsigned type) : data_() , header_(boost::uuids::nil_uuid(), type, 0) { } message::~message() { } boost::uuids::uuid message::generate_id() { static boost::uuids::random_generator gen; return gen(); } <commit_msg>Compile fix as proposed by @woscho<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details #include <boost/version.hpp> #if BOOST_VERSION == 106900 #define BOOST_ALLOW_DEPRECATED_HEADERS #endif #include <boost/uuid/uuid_generators.hpp> #include "message.h" using namespace visionaray::async; //-------------------------------------------------------------------------------------------------- // message::header // message::header::header() : id_(boost::uuids::nil_uuid()) , type_(0) , size_(0) { } message::header::header(boost::uuids::uuid const& id, unsigned type, unsigned size) : id_(id) , type_(type) , size_(size) { } message::header::~header() { } //-------------------------------------------------------------------------------------------------- // message // message::message() { } message::message(unsigned type) : data_() , header_(boost::uuids::nil_uuid(), type, 0) { } message::~message() { } boost::uuids::uuid message::generate_id() { static boost::uuids::random_generator gen; return gen(); } <|endoftext|>
<commit_before><commit_msg>fix extend bug, works well.<commit_after><|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_MAKE_UNIQUE_HPP #define MAPNIK_MAKE_UNIQUE_HPP #include <memory> #if __cplusplus <= 201103L namespace std { // C++14 backfill from http://herbsutter.com/gotw/_102/ template<typename T, typename ...Args> inline std::unique_ptr<T> make_unique(Args&& ...args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } } #endif #endif // MAPNIK_MAKE_UNIQUE_HPP <commit_msg>don't trust __cplusplus - addresses issue 5 from #2396<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2014 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_MAKE_UNIQUE_HPP #define MAPNIK_MAKE_UNIQUE_HPP #include <memory> // http://stackoverflow.com/questions/14131454/visual-studio-2012-cplusplus-and-c-11 #if defined(_MSC_VER) && _MSC_VER < 1800 || !defined(_MSC_VER) && __cplusplus <= 201103L namespace std { // C++14 backfill from http://herbsutter.com/gotw/_102/ template<typename T, typename ...Args> inline std::unique_ptr<T> make_unique(Args&& ...args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } } #endif #endif // MAPNIK_MAKE_UNIQUE_HPP <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ /*========================================================================= Program: Tensor ToolKit - TTK Module: $URL: svn://scm.gforge.inria.fr/svn/ttk/trunk/Algorithms/itkElectrostaticRepulsionDiffusionGradientReductionFilter.txx $ Language: C++ Date: $Date: 2010-06-07 13:39:13 +0200 (Mo, 07 Jun 2010) $ Version: $Revision: 68 $ Copyright (c) INRIA 2010. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itk_MultiShellAdcAverageReconstructionImageFilter_cpp_ #define _itk_MultiShellAdcAverageReconstructionImageFilter_cpp_ #endif #define _USE_MATH_DEFINES #include "itkMultiShellAdcAverageReconstructionImageFilter.h" #include <math.h> #include <time.h> #include <itkImageRegionIterator.h> #include <itkImageRegion.h> #include "mitkDiffusionFunctionCollection.h" namespace itk { template <class TInputScalarType, class TOutputScalarType> MultiShellAdcAverageReconstructionImageFilter<TInputScalarType, TOutputScalarType> ::MultiShellAdcAverageReconstructionImageFilter(): m_Interpolation(false) { this->SetNumberOfRequiredInputs( 1 ); //this->SetNumberOfThreads(1); } template <class TInputScalarType, class TOutputScalarType> void MultiShellAdcAverageReconstructionImageFilter<TInputScalarType, TOutputScalarType> ::BeforeThreadedGenerateData() { // test whether BvalueMap contains all necessary information if(m_BValueMap.size() == 0) { itkWarningMacro(<< "No BValueMap given: create one using GradientDirectionContainer"); GradientDirectionContainerType::ConstIterator gdcit; for( gdcit = m_OriginalGradientDirections->Begin(); gdcit != m_OriginalGradientDirections->End(); ++gdcit) { double bValueKey = int(((m_BValue * gdcit.Value().two_norm() * gdcit.Value().two_norm())+7.5)/10)*10; m_BValueMap[bValueKey].push_back(gdcit.Index()); } } //# BValueMap contains no bZero --> itkException if(m_BValueMap.find(0.0) == m_BValueMap.end()) { MITK_INFO << "No ReferenceSignal (BZeroImages) found!"; itkExceptionMacro(<< "No ReferenceSignal (BZeroImages) found!"); } // test whether interpolation is necessary // - Gradeint directions on different shells are different m_Interpolation = mitk::gradients::CheckForDifferingShellDirections(m_BValueMap, m_OriginalGradientDirections.GetPointer()); // [allDirectionsContainer] Gradient DirectionContainer containing all unique directions m_allDirectionsIndicies = mitk::gradients::GetAllUniqueDirections(m_BValueMap, m_OriginalGradientDirections); // [sizeAllDirections] size of GradientContainer cointaining all unique directions m_allDirectionsSize = m_allDirectionsIndicies.size(); //MITK_INFO << m_allDirectionsSize; //exit(0); m_TargetGradientDirections = mitk::gradients::CreateNormalizedUniqueGradientDirectionContainer(m_BValueMap,m_OriginalGradientDirections); //MITK_INFO << m_allDirectionsSize; // if INTERPOLATION necessary if(m_Interpolation) { for(BValueMap::const_iterator it = m_BValueMap.begin();it != m_BValueMap.end(); it++) { if((*it).first == 0.0) continue; // if any #ShellDirection < 15 --> itkException (No interpolation possible) if((*it).second.size() < 15){ MITK_INFO << "Abort: No interpolation possible Shell-" << (*it).first << " has less than 15 directions."; itkExceptionMacro(<<"No interpolation possible"); } } m_ShellInterpolationMatrixVector.reserve(m_BValueMap.size()-1); // for Weightings // for each shell BValueMap::const_iterator it = m_BValueMap.begin(); it++; //skip bZeroIndices for(;it != m_BValueMap.end();it++) { //- calculate maxShOrder const IndicesVector currentShell = (*it).second; unsigned int SHMaxOrder = 12; while( ((SHMaxOrder+1)*(SHMaxOrder+2)/2) > currentShell.size()) SHMaxOrder -= 2 ; //- get TragetSHBasis using allDirectionsContainer vnl_matrix<double> sphericalCoordinates; sphericalCoordinates = mitk::gradients::ComputeSphericalFromCartesian(m_allDirectionsIndicies, m_OriginalGradientDirections); vnl_matrix<double> TargetSHBasis = mitk::gradients::ComputeSphericalHarmonicsBasis(sphericalCoordinates, SHMaxOrder); MITK_INFO << "TargetSHBasis " << TargetSHBasis.rows() << " x " << TargetSHBasis.cols(); //- get ShellSHBasis using currentShellDirections sphericalCoordinates = mitk::gradients::ComputeSphericalFromCartesian(currentShell, m_OriginalGradientDirections); vnl_matrix<double> ShellSHBasis = mitk::gradients::ComputeSphericalHarmonicsBasis(sphericalCoordinates, SHMaxOrder); MITK_INFO << "ShellSHBasis " << ShellSHBasis.rows() << " x " << ShellSHBasis.cols(); //- calculate interpolationSHBasis [TargetSHBasis * ShellSHBasis^-1] vnl_matrix_inverse<double> invShellSHBasis(ShellSHBasis); vnl_matrix<double> shellInterpolationMatrix = TargetSHBasis * invShellSHBasis.pinverse(); MITK_INFO << "shellInterpolationMatrix " << shellInterpolationMatrix.rows() << " x " << shellInterpolationMatrix.cols(); m_ShellInterpolationMatrixVector.push_back(shellInterpolationMatrix); //- save interpolationSHBasis } } m_WeightsVector.reserve(m_BValueMap.size()-1); BValueMap::const_iterator itt = m_BValueMap.begin(); itt++; // skip ReferenceImages //- calculate Weights [Weigthing = shell_size / max_shell_size] unsigned int maxShellSize = 0; for(;itt != m_BValueMap.end(); itt++){ if(itt->second.size() > maxShellSize) maxShellSize = itt->second.size(); } itt = m_BValueMap.begin(); itt++; // skip ReferenceImages for(;itt != m_BValueMap.end(); itt++){ m_WeightsVector.push_back(itt->second.size() / (double)maxShellSize); } // calculate average b-Value for target b-Value [bVal_t] // MITK_INFO << "overall referenceImage avareg"; // initialize output image typename OutputImageType::Pointer outImage = static_cast<OutputImageType * >(ProcessObject::GetOutput(0)); //outImage = OutputImageType::New(); outImage->SetSpacing( this->GetInput()->GetSpacing() ); outImage->SetOrigin( this->GetInput()->GetOrigin() ); outImage->SetDirection( this->GetInput()->GetDirection() ); // Set the image direction using bZeroDirection+AllDirectionsContainer outImage->SetLargestPossibleRegion( this->GetInput()->GetLargestPossibleRegion()); outImage->SetBufferedRegion( this->GetInput()->GetLargestPossibleRegion() ); outImage->SetRequestedRegion( this->GetInput()->GetLargestPossibleRegion() ); outImage->SetVectorLength( 1+m_allDirectionsSize ); // size of 1(bzeroValue) + AllDirectionsContainer outImage->Allocate(); BValueMap::iterator it = m_BValueMap.begin(); it++; // skip bZeroImages corresponding to 0-bValue m_TargetBValue = 0; while(it!=m_BValueMap.end()) { m_TargetBValue += it->first; it++; } m_TargetBValue /= (double)(m_BValueMap.size()-1); MITK_INFO << "Input:" << std::endl << std::endl << " GradientDirections: " << m_OriginalGradientDirections->Size() << std::endl << " Shells: " << (m_BValueMap.size() - 1) << std::endl << " ReferenceImages: " << m_BValueMap.at(0.0).size() << std::endl << " Interpolation: " << m_Interpolation << std::endl; MITK_INFO << "Output:" << std::endl << std::endl << " OutImageVectorLength: " << outImage->GetVectorLength() << std::endl << " TargetDirections: " << m_allDirectionsSize << std::endl << " TargetBValue: " << m_TargetBValue << std::endl << std::endl; } template <class TInputScalarType, class TOutputScalarType> void MultiShellAdcAverageReconstructionImageFilter<TInputScalarType, TOutputScalarType> ::ThreadedGenerateData(const OutputImageRegionType &outputRegionForThread, int /*threadId*/) { // Get input gradient image pointer typename InputImageType::Pointer inputImage = static_cast< InputImageType * >(ProcessObject::GetInput(0)); // ImageRegionIterator for the input image ImageRegionIterator< InputImageType > iit(inputImage, outputRegionForThread); iit.GoToBegin(); // Get output gradient image pointer typename OutputImageType::Pointer outputImage = static_cast< OutputImageType * >(ProcessObject::GetOutput(0)); // ImageRegionIterator for the output image ImageRegionIterator< OutputImageType > oit(outputImage, outputRegionForThread); oit.GoToBegin(); // calculate target bZero-Value [b0_t] const IndicesVector BZeroIndices = m_BValueMap[0.0]; double BZeroAverage = 0.0; // create empty nxm SignalMatrix containing n->signals/directions (in case of interpolation ~ sizeAllDirections otherwise the size of any shell) for m->shells vnl_matrix<double> SignalMatrix(m_allDirectionsSize, m_BValueMap.size()-1); // create nx1 targetSignalVector vnl_vector<double> SignalVector(m_allDirectionsSize); // ** walking over each Voxel while(!iit.IsAtEnd()) { InputPixelType b = iit.Get(); for(unsigned int i = 0 ; i < BZeroIndices.size(); i++) BZeroAverage += b[BZeroIndices[i]]; BZeroAverage /= (double)BZeroIndices.size(); OutputPixelType out = oit.Get(); out.Fill(0.0); out.SetElement(0,BZeroAverage); BValueMap::const_iterator shellIterator = m_BValueMap.begin(); shellIterator++; //skip bZeroImages unsigned int shellIndex = 0; while(shellIterator != m_BValueMap.end()) { // reset Data SignalVector.fill(0.0); // - get the RawSignal const IndicesVector currentShell = shellIterator->second; for(unsigned int i = 0 ; i < currentShell.size(); i++) SignalVector.put(i,b[currentShell[i]]); //MITK_INFO <<"RawSignal: "<< SignalVector; MITK_INFO << "möp" <<currentShell.size(); //- interpolate the Signal if necessary using corresponding interpolationSHBasis if(m_Interpolation) SignalVector = m_ShellInterpolationMatrixVector.at(shellIndex) * SignalVector; //- normalization of the raw Signal S_S0Normalization(SignalVector, BZeroAverage); //MITK_INFO <<"Normalized: "<< SignalVector; calculateAdcFromSignal(SignalVector, shellIterator->first); //MITK_INFO <<"ADC: "<< SignalVector; //- weight the signal if(m_Interpolation){ const double shellWeight = m_WeightsVector.at(shellIndex); SignalVector *= shellWeight; } //- save the (interpolated) ShellSignalVector as the ith column in the SignalMatrix SignalMatrix.set_column(shellIndex, SignalVector); shellIterator++; shellIndex++; //MITK_INFO << SignalMatrix; } // MITK_INFO <<"finalSignalMatrix: " << SignalMatrix; // ADC averaging Sum(ADC)/n for(unsigned int i = 0 ; i < SignalMatrix.rows(); i++) SignalVector.put(i,SignalMatrix.get_row(i).sum()); SignalVector/= (double)(m_BValueMap.size()-1); // MITK_INFO << "AveragedADC: " << SignalVector; // recalculate signal from ADC calculateSignalFromAdc(SignalVector, m_TargetBValue, BZeroAverage); for(unsigned int i = 1 ; i < out.Size(); i ++) out.SetElement(i,SignalVector.get(i-1)); //MITK_INFO << "ADCAveragedSignal: " << out; //MITK_INFO << "-------------"; oit.Set(out); ++oit; ++iit; } // outImageIterator set S_t // ** /* int vecLength; this->SetNumberOfRequiredOutputs (1); this->SetNthOutput (0, outImage); MITK_INFO << "...done"; */ } template <class TInputScalarType, class TOutputScalarType> void MultiShellAdcAverageReconstructionImageFilter<TInputScalarType, TOutputScalarType> ::S_S0Normalization( vnl_vector<double> & vec, const double & S0 ) { for(unsigned int i = 0; i < vec.size(); i++) vec[i] /= S0; } template <class TInputScalarType, class TOutputScalarType> void MultiShellAdcAverageReconstructionImageFilter<TInputScalarType, TOutputScalarType> ::calculateAdcFromSignal( vnl_vector<double> & vec, const double & bValue) { for(unsigned int i = 0; i < vec.size(); i++) vec[i] = log(vec[i])/-bValue; } template <class TInputScalarType, class TOutputScalarType> void MultiShellAdcAverageReconstructionImageFilter<TInputScalarType, TOutputScalarType> ::calculateSignalFromAdc(vnl_vector<double> & vec, const double & bValue, const double & referenceSignal) { for(unsigned int i = 0 ; i < vec.size(); i++){ //MITK_INFO << vec[i]; //MITK_INFO << bValue; //MITK_INFO << referenceSignal; vec[i] = referenceSignal * exp((-bValue) * vec[i]); } } } // end of namespace <commit_msg>bug fixes (2)<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ /*========================================================================= Program: Tensor ToolKit - TTK Module: $URL: svn://scm.gforge.inria.fr/svn/ttk/trunk/Algorithms/itkElectrostaticRepulsionDiffusionGradientReductionFilter.txx $ Language: C++ Date: $Date: 2010-06-07 13:39:13 +0200 (Mo, 07 Jun 2010) $ Version: $Revision: 68 $ Copyright (c) INRIA 2010. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef _itk_MultiShellAdcAverageReconstructionImageFilter_cpp_ #define _itk_MultiShellAdcAverageReconstructionImageFilter_cpp_ #endif #define _USE_MATH_DEFINES #include "itkMultiShellAdcAverageReconstructionImageFilter.h" #include <math.h> #include <time.h> #include <itkImageRegionIterator.h> #include <itkImageRegion.h> #include "mitkDiffusionFunctionCollection.h" namespace itk { template <class TInputScalarType, class TOutputScalarType> MultiShellAdcAverageReconstructionImageFilter<TInputScalarType, TOutputScalarType> ::MultiShellAdcAverageReconstructionImageFilter(): m_Interpolation(false) { this->SetNumberOfRequiredInputs( 1 ); this->SetNumberOfThreads(1); } template <class TInputScalarType, class TOutputScalarType> void MultiShellAdcAverageReconstructionImageFilter<TInputScalarType, TOutputScalarType> ::BeforeThreadedGenerateData() { // test whether BvalueMap contains all necessary information if(m_BValueMap.size() == 0) { itkWarningMacro(<< "No BValueMap given: create one using GradientDirectionContainer"); GradientDirectionContainerType::ConstIterator gdcit; for( gdcit = m_OriginalGradientDirections->Begin(); gdcit != m_OriginalGradientDirections->End(); ++gdcit) { double bValueKey = int(((m_BValue * gdcit.Value().two_norm() * gdcit.Value().two_norm())+7.5)/10)*10; m_BValueMap[bValueKey].push_back(gdcit.Index()); } } //# BValueMap contains no bZero --> itkException if(m_BValueMap.find(0.0) == m_BValueMap.end()) { MITK_INFO << "No ReferenceSignal (BZeroImages) found!"; itkExceptionMacro(<< "No ReferenceSignal (BZeroImages) found!"); } // test whether interpolation is necessary // - Gradeint directions on different shells are different m_Interpolation = mitk::gradients::CheckForDifferingShellDirections(m_BValueMap, m_OriginalGradientDirections.GetPointer()); // [allDirectionsContainer] Gradient DirectionContainer containing all unique directions m_allDirectionsIndicies = mitk::gradients::GetAllUniqueDirections(m_BValueMap, m_OriginalGradientDirections); // [sizeAllDirections] size of GradientContainer cointaining all unique directions m_allDirectionsSize = m_allDirectionsIndicies.size(); //MITK_INFO << m_allDirectionsSize; //exit(0); m_TargetGradientDirections = mitk::gradients::CreateNormalizedUniqueGradientDirectionContainer(m_BValueMap,m_OriginalGradientDirections); //MITK_INFO << m_allDirectionsSize; // if INTERPOLATION necessary if(m_Interpolation) { for(BValueMap::const_iterator it = m_BValueMap.begin();it != m_BValueMap.end(); it++) { if((*it).first == 0.0) continue; // if any #ShellDirection < 15 --> itkException (No interpolation possible) if((*it).second.size() < 15){ MITK_INFO << "Abort: No interpolation possible Shell-" << (*it).first << " has less than 15 directions."; itkExceptionMacro(<<"No interpolation possible"); } } m_ShellInterpolationMatrixVector.reserve(m_BValueMap.size()-1); // for Weightings // for each shell BValueMap::const_iterator it = m_BValueMap.begin(); it++; //skip bZeroIndices for(;it != m_BValueMap.end();it++) { //- calculate maxShOrder const IndicesVector currentShell = (*it).second; unsigned int SHMaxOrder = 12; while( ((SHMaxOrder+1)*(SHMaxOrder+2)/2) > currentShell.size()) SHMaxOrder -= 2 ; //- get TragetSHBasis using allDirectionsContainer vnl_matrix<double> sphericalCoordinates; sphericalCoordinates = mitk::gradients::ComputeSphericalFromCartesian(m_allDirectionsIndicies, m_OriginalGradientDirections); vnl_matrix<double> TargetSHBasis = mitk::gradients::ComputeSphericalHarmonicsBasis(sphericalCoordinates, SHMaxOrder); MITK_INFO << "TargetSHBasis " << TargetSHBasis.rows() << " x " << TargetSHBasis.cols(); //- get ShellSHBasis using currentShellDirections sphericalCoordinates = mitk::gradients::ComputeSphericalFromCartesian(currentShell, m_OriginalGradientDirections); vnl_matrix<double> ShellSHBasis = mitk::gradients::ComputeSphericalHarmonicsBasis(sphericalCoordinates, SHMaxOrder); MITK_INFO << "ShellSHBasis " << ShellSHBasis.rows() << " x " << ShellSHBasis.cols(); //- calculate interpolationSHBasis [TargetSHBasis * ShellSHBasis^-1] vnl_matrix_inverse<double> invShellSHBasis(ShellSHBasis); vnl_matrix<double> shellInterpolationMatrix = TargetSHBasis * invShellSHBasis.pinverse(); MITK_INFO << "shellInterpolationMatrix " << shellInterpolationMatrix.rows() << " x " << shellInterpolationMatrix.cols(); m_ShellInterpolationMatrixVector.push_back(shellInterpolationMatrix); //- save interpolationSHBasis } } m_WeightsVector.reserve(m_BValueMap.size()-1); BValueMap::const_iterator itt = m_BValueMap.begin(); itt++; // skip ReferenceImages //- calculate Weights [Weigthing = shell_size / max_shell_size] unsigned int maxShellSize = 0; for(;itt != m_BValueMap.end(); itt++){ if(itt->second.size() > maxShellSize) maxShellSize = itt->second.size(); } itt = m_BValueMap.begin(); itt++; // skip ReferenceImages for(;itt != m_BValueMap.end(); itt++){ m_WeightsVector.push_back(itt->second.size() / (double)maxShellSize); } // calculate average b-Value for target b-Value [bVal_t] // MITK_INFO << "overall referenceImage avareg"; // initialize output image typename OutputImageType::Pointer outImage = static_cast<OutputImageType * >(ProcessObject::GetOutput(0)); //outImage = OutputImageType::New(); outImage->SetSpacing( this->GetInput()->GetSpacing() ); outImage->SetOrigin( this->GetInput()->GetOrigin() ); outImage->SetDirection( this->GetInput()->GetDirection() ); // Set the image direction using bZeroDirection+AllDirectionsContainer outImage->SetLargestPossibleRegion( this->GetInput()->GetLargestPossibleRegion()); outImage->SetBufferedRegion( this->GetInput()->GetLargestPossibleRegion() ); outImage->SetRequestedRegion( this->GetInput()->GetLargestPossibleRegion() ); outImage->SetVectorLength( 1+m_allDirectionsSize ); // size of 1(bzeroValue) + AllDirectionsContainer outImage->Allocate(); BValueMap::iterator it = m_BValueMap.begin(); it++; // skip bZeroImages corresponding to 0-bValue m_TargetBValue = 0; while(it!=m_BValueMap.end()) { m_TargetBValue += it->first; it++; } m_TargetBValue /= (double)(m_BValueMap.size()-1); MITK_INFO << "Input:" << std::endl << std::endl << " GradientDirections: " << m_OriginalGradientDirections->Size() << std::endl << " Shells: " << (m_BValueMap.size() - 1) << std::endl << " ReferenceImages: " << m_BValueMap.at(0.0).size() << std::endl << " Interpolation: " << m_Interpolation << std::endl; MITK_INFO << "Output:" << std::endl << std::endl << " OutImageVectorLength: " << outImage->GetVectorLength() << std::endl << " TargetDirections: " << m_allDirectionsSize << std::endl << " TargetBValue: " << m_TargetBValue << std::endl << std::endl; } template <class TInputScalarType, class TOutputScalarType> void MultiShellAdcAverageReconstructionImageFilter<TInputScalarType, TOutputScalarType> ::ThreadedGenerateData(const OutputImageRegionType &outputRegionForThread, int /*threadId*/) { // Get input gradient image pointer typename InputImageType::Pointer inputImage = static_cast< InputImageType * >(ProcessObject::GetInput(0)); // ImageRegionIterator for the input image ImageRegionIterator< InputImageType > iit(inputImage, outputRegionForThread); iit.GoToBegin(); // Get output gradient image pointer typename OutputImageType::Pointer outputImage = static_cast< OutputImageType * >(ProcessObject::GetOutput(0)); // ImageRegionIterator for the output image ImageRegionIterator< OutputImageType > oit(outputImage, outputRegionForThread); oit.GoToBegin(); // calculate target bZero-Value [b0_t] const IndicesVector BZeroIndices = m_BValueMap[0.0]; double BZeroAverage = 0.0; // create empty nxm SignalMatrix containing n->signals/directions (in case of interpolation ~ sizeAllDirections otherwise the size of any shell) for m->shells vnl_matrix<double> SignalMatrix(m_allDirectionsSize, m_BValueMap.size()-1); // create nx1 targetSignalVector vnl_vector<double> SignalVector(m_allDirectionsSize); // ** walking over each Voxel while(!iit.IsAtEnd()) { InputPixelType b = iit.Get(); for(unsigned int i = 0 ; i < BZeroIndices.size(); i++) BZeroAverage += b[BZeroIndices[i]]; BZeroAverage /= (double)BZeroIndices.size(); OutputPixelType out = oit.Get(); out.Fill(0.0); out.SetElement(0,BZeroAverage); BValueMap::const_iterator shellIterator = m_BValueMap.begin(); shellIterator++; //skip bZeroImages unsigned int shellIndex = 0; while(shellIterator != m_BValueMap.end()) { // reset Data SignalVector.fill(0.0); // - get the RawSignal const IndicesVector currentShell = shellIterator->second; vnl_vector<double> InterpVector(currentShell.size()); // - get raw Signal for currente shell for(unsigned int i = 0 ; i < currentShell.size(); i++) InterpVector.put(i,b[currentShell[i]]); MITK_INFO <<"RawSignal: "<< InterpVector; //- normalization of the raw Signal S_S0Normalization(InterpVector, BZeroAverage); MITK_INFO <<"Normalized: "<< InterpVector; //- interpolate the Signal if necessary using corresponding interpolationSHBasis if(m_Interpolation) SignalVector = m_ShellInterpolationMatrixVector.at(shellIndex) * InterpVector; else SignalVector = InterpVector; MITK_INFO <<"Interpolated: "<< SignalVector; // - ADC calculation for the signalVector calculateAdcFromSignal(SignalVector, shellIterator->first); MITK_INFO << "ADCVector: " << SignalVector; //- weight the signal //if(m_Interpolation){ // const double shellWeight = m_WeightsVector.at(shellIndex); // SignalVector *= shellWeight; //} //- save the (interpolated) ShellSignalVector as the ith column in the SignalMatrix SignalMatrix.set_column(shellIndex, SignalVector); shellIterator++; shellIndex++; //MITK_INFO << SignalMatrix; } exit(0); // MITK_INFO <<"finalSignalMatrix: " << SignalMatrix; // ADC averaging Sum(ADC)/n for(unsigned int i = 0 ; i < SignalMatrix.rows(); i++) SignalVector.put(i,SignalMatrix.get_row(i).sum()); SignalVector/= (double)(m_BValueMap.size()-1); // MITK_INFO << "AveragedADC: " << SignalVector; // recalculate signal from ADC calculateSignalFromAdc(SignalVector, m_TargetBValue, BZeroAverage); for(unsigned int i = 1 ; i < out.Size(); i ++) out.SetElement(i,SignalVector.get(i-1)); //MITK_INFO << "ADCAveragedSignal: " << out; //MITK_INFO << "-------------"; oit.Set(out); ++oit; ++iit; } // outImageIterator set S_t // ** /* int vecLength; this->SetNumberOfRequiredOutputs (1); this->SetNthOutput (0, outImage); MITK_INFO << "...done"; */ } template <class TInputScalarType, class TOutputScalarType> void MultiShellAdcAverageReconstructionImageFilter<TInputScalarType, TOutputScalarType> ::S_S0Normalization( vnl_vector<double> & vec, const double & S0 ) { for(unsigned int i = 0; i < vec.size(); i++) vec[i] /= S0; } template <class TInputScalarType, class TOutputScalarType> void MultiShellAdcAverageReconstructionImageFilter<TInputScalarType, TOutputScalarType> ::calculateAdcFromSignal( vnl_vector<double> & vec, const double & bValue) { for(unsigned int i = 0; i < vec.size(); i++) vec[i] = log(vec[i])/-bValue; } template <class TInputScalarType, class TOutputScalarType> void MultiShellAdcAverageReconstructionImageFilter<TInputScalarType, TOutputScalarType> ::calculateSignalFromAdc(vnl_vector<double> & vec, const double & bValue, const double & referenceSignal) { for(unsigned int i = 0 ; i < vec.size(); i++){ //MITK_INFO << vec[i]; //MITK_INFO << bValue; //MITK_INFO << referenceSignal; vec[i] = referenceSignal * exp((-bValue) * vec[i]); } } } // end of namespace <|endoftext|>
<commit_before>/** @file Node/UnitBasic.hpp @brief Node basic unit class. @author Timothy Howard @copyright 2013-2014 Timothy Howard under the MIT license; see @ref index or the accompanying LICENSE file for full text. */ #ifndef HORD_NODE_UNITBASIC_HPP_ #define HORD_NODE_UNITBASIC_HPP_ #include <Hord/config.hpp> #include <Hord/Object/Defs.hpp> #include <Hord/Node/Defs.hpp> #include <Hord/Node/Unit.hpp> namespace Hord { namespace Node { // Forward declarations class UnitBasic; /** @addtogroup object @{ */ /** @addtogroup node @{ */ /** Basic node unit class. */ class UnitBasic final : public Node::Unit { private: using base = Node::Unit; static Object::UPtr construct( Object::ID const id, Object::ID const parent ) noexcept; public: /** Type info. */ static constexpr Object::type_info const info{ "Hive.UnitBasic", Node::Type{Node::UnitType::basic}, {Node::SUPPLIED_PROPS}, UnitBasic::construct }; private: UnitBasic() = delete; UnitBasic(UnitBasic const&) = delete; UnitBasic& operator=(UnitBasic const&) = delete; public: /** @name Special member functions */ /// @{ /** Destructor. */ ~UnitBasic() noexcept override; /** Move constructor. */ UnitBasic(UnitBasic&&); /** Move assignment operator. */ UnitBasic& operator=(UnitBasic&&); private: UnitBasic( Node::ID const id, Object::ID const parent ) noexcept; /// @} }; /** @} */ // end of doc-group node /** @} */ // end of doc-group object } // namespace Node template struct Node::Unit::ensure_traits<Node::UnitBasic>; } // namespace Hord #endif // HORD_NODE_UNITBASIC_HPP_ <commit_msg>Node::UnitBasic: corrected unit name in info.<commit_after>/** @file Node/UnitBasic.hpp @brief Node basic unit class. @author Timothy Howard @copyright 2013-2014 Timothy Howard under the MIT license; see @ref index or the accompanying LICENSE file for full text. */ #ifndef HORD_NODE_UNITBASIC_HPP_ #define HORD_NODE_UNITBASIC_HPP_ #include <Hord/config.hpp> #include <Hord/Object/Defs.hpp> #include <Hord/Node/Defs.hpp> #include <Hord/Node/Unit.hpp> namespace Hord { namespace Node { // Forward declarations class UnitBasic; /** @addtogroup object @{ */ /** @addtogroup node @{ */ /** Basic node unit class. */ class UnitBasic final : public Node::Unit { private: using base = Node::Unit; static Object::UPtr construct( Object::ID const id, Object::ID const parent ) noexcept; public: /** Type info. */ static constexpr Object::type_info const info{ "Hord.UnitBasic", Node::Type{Node::UnitType::basic}, {Node::SUPPLIED_PROPS}, UnitBasic::construct }; private: UnitBasic() = delete; UnitBasic(UnitBasic const&) = delete; UnitBasic& operator=(UnitBasic const&) = delete; public: /** @name Special member functions */ /// @{ /** Destructor. */ ~UnitBasic() noexcept override; /** Move constructor. */ UnitBasic(UnitBasic&&); /** Move assignment operator. */ UnitBasic& operator=(UnitBasic&&); private: UnitBasic( Node::ID const id, Object::ID const parent ) noexcept; /// @} }; /** @} */ // end of doc-group node /** @} */ // end of doc-group object } // namespace Node template struct Node::Unit::ensure_traits<Node::UnitBasic>; } // namespace Hord #endif // HORD_NODE_UNITBASIC_HPP_ <|endoftext|>
<commit_before>#include "draw_widget.hpp" #include "proxystyle.hpp" #include "slider_ctrl.hpp" #include "../map/framework_factory.hpp" #include "../map/render_policy.hpp" #include "../yg/internal/opengl.hpp" #include "../platform/settings.hpp" #include <QtGui/QMouseEvent> #include <QtGui/QMenu> using namespace storage; namespace qt { bool s_isExiting = false; QtVideoTimer::QtVideoTimer(DrawWidget * w, TFrameFn frameFn) : ::VideoTimer(frameFn), m_widget(w) {} void QtVideoTimer::start() { m_timer = new QTimer(); m_widget->connect(m_timer, SIGNAL(timeout()), m_widget, SLOT(AnimTimerElapsed())); resume(); } void QtVideoTimer::pause() { m_timer->stop(); m_state = EPaused; } void QtVideoTimer::resume() { m_timer->start(1000 / 60); m_state = ERunning; } void QtVideoTimer::stop() { pause(); delete m_timer; m_timer = 0; m_state = EStopped; } DrawWidget::DrawWidget(QWidget * pParent) : QGLWidget(pParent), m_isInitialized(false), m_isTimerStarted(false), m_framework(FrameworkFactory::CreateFramework()), m_isDrag(false), m_isRotate(false), m_redrawInterval(100), m_pScale(0) { m_timer = new QTimer(this); connect(m_timer, SIGNAL(timeout()), this, SLOT(ScaleTimerElapsed())); } DrawWidget::~DrawWidget() { m_framework.reset(); } void DrawWidget::PrepareShutdown() { s_isExiting = true; m_framework->PrepareToShutdown(); m_videoTimer.reset(); } void DrawWidget::SetScaleControl(QScaleSlider * pScale) { m_pScale = pScale; connect(m_pScale, SIGNAL(actionTriggered(int)), this, SLOT(ScaleChanged(int))); } void DrawWidget::UpdateNow() { update(); } void DrawWidget::UpdateAfterSettingsChanged() { m_framework->SetupMeasurementSystem(); } bool DrawWidget::LoadState() { pair<int, int> widthAndHeight; if (!Settings::Get("DrawWidgetSize", widthAndHeight)) return false; m_framework->OnSize(widthAndHeight.first, widthAndHeight.second); if (!m_framework->LoadState()) return false; //m_framework.UpdateNow(); UpdateScaleControl(); return true; } void DrawWidget::SaveState() { pair<int, int> widthAndHeight(width(), height()); Settings::Set("DrawWidgetSize", widthAndHeight); m_framework->SaveState(); } void DrawWidget::MoveLeft() { m_framework->Move(math::pi, 0.5); emit ViewportChanged(); } void DrawWidget::MoveRight() { m_framework->Move(0.0, 0.5); emit ViewportChanged(); } void DrawWidget::MoveUp() { m_framework->Move(math::pi/2.0, 0.5); emit ViewportChanged(); } void DrawWidget::MoveDown() { m_framework->Move(-math::pi/2.0, 0.5); emit ViewportChanged(); } void DrawWidget::ScalePlus() { m_framework->Scale(2.0); UpdateScaleControl(); emit ViewportChanged(); } void DrawWidget::ScaleMinus() { m_framework->Scale(0.5); UpdateScaleControl(); emit ViewportChanged(); } void DrawWidget::ScalePlusLight() { m_framework->Scale(1.5); UpdateScaleControl(); emit ViewportChanged(); } void DrawWidget::ScaleMinusLight() { m_framework->Scale(2.0/3.0); UpdateScaleControl(); emit ViewportChanged(); } void DrawWidget::ShowAll() { m_framework->ShowAll(); UpdateScaleControl(); emit ViewportChanged(); } void DrawWidget::Repaint() { m_framework->Invalidate(); } VideoTimer * DrawWidget::CreateVideoTimer() { #ifdef OMIM_OS_MAC return CreateAppleVideoTimer(bind(&DrawWidget::DrawFrame, this)); #else return new QtVideoTimer(this, bind(&DrawWidget::DrawFrame, this)); #endif } void DrawWidget::ScaleChanged(int action) { if (action != QAbstractSlider::SliderNoAction) { double const factor = m_pScale->GetScaleFactor(); if (factor != 1.0) { m_framework->Scale(factor); emit ViewportChanged(); } } } void DrawWidget::initializeGL() { /// we'll perform swap by ourselves, see issue #333 setAutoBufferSwap(false); if (!m_isInitialized) { m_videoTimer.reset(CreateVideoTimer()); shared_ptr<qt::gl::RenderContext> primaryRC(new qt::gl::RenderContext(this)); yg::ResourceManager::Params rmParams; rmParams.m_rtFormat = yg::Data8Bpp; rmParams.m_texFormat = yg::Data8Bpp; rmParams.m_texRtFormat = yg::Data8Bpp; rmParams.m_videoMemoryLimit = GetPlatform().VideoMemoryLimit(); try { m_framework->SetRenderPolicy(CreateRenderPolicy(m_videoTimer.get(), true, rmParams, primaryRC)); } catch (yg::gl::platform_unsupported const & e) { LOG(LERROR, ("OpenGL platform is unsupported, reason: ", e.what())); /// TODO: Show "Please Update Drivers" dialog and close the program. } m_isInitialized = true; } } void DrawWidget::resizeGL(int w, int h) { m_framework->OnSize(w, h); m_framework->Invalidate(); if (m_isInitialized && m_isTimerStarted) DrawFrame(); UpdateScaleControl(); emit ViewportChanged(); } void DrawWidget::paintGL() { if ((m_isInitialized) && (!m_isTimerStarted)) { /// timer should be started upon the first repaint /// request to fully initialized GLWidget. m_isTimerStarted = true; m_framework->SetUpdatesEnabled(true); } m_framework->Invalidate(); } void DrawWidget::DrawFrame() { if (s_isExiting) return; if (m_framework->NeedRedraw()) { makeCurrent(); m_framework->SetNeedRedraw(false); shared_ptr<PaintEvent> paintEvent(new PaintEvent(m_framework->GetRenderPolicy()->GetDrawer().get())); m_framework->BeginPaint(paintEvent); m_framework->DoPaint(paintEvent); /// swapping buffers before ending the frame, see issue #333 swapBuffers(); m_framework->EndPaint(paintEvent); doneCurrent(); } } namespace { DragEvent get_drag_event(QMouseEvent * e) { QPoint const p = e->pos(); return DragEvent(p.x(), p.y()); } RotateEvent get_rotate_event(QPoint const & pt, QPoint const & centerPt) { return RotateEvent(centerPt.x(), centerPt.y(), pt.x(), pt.y()); } } void DrawWidget::mousePressEvent(QMouseEvent * e) { QGLWidget::mousePressEvent(e); if (e->button() == Qt::LeftButton) { if (e->modifiers() & Qt::ControlModifier) { // starting rotation m_framework->StartRotate(get_rotate_event(e->pos(), this->rect().center())); setCursor(Qt::CrossCursor); m_isRotate = true; } else { // starting drag m_framework->StartDrag(get_drag_event(e)); setCursor(Qt::CrossCursor); m_isDrag = true; } } else if (e->button() == Qt::RightButton) { // show feature types QPoint const & pt = e->pos(); vector<string> types; m_framework->GetFeatureTypes(m2::PointD(pt.x(), pt.y()), types); QMenu menu; for (size_t i = 0; i < types.size(); ++i) menu.addAction(QString::fromAscii(types[i].c_str())); menu.exec(pt); } } void DrawWidget::mouseDoubleClickEvent(QMouseEvent * e) { QGLWidget::mouseDoubleClickEvent(e); if (e->button() == Qt::LeftButton) { StopDragging(e); m_framework->ScaleToPoint(ScaleToPointEvent(e->pos().x(), e->pos().y(), 1.5)); UpdateScaleControl(); emit ViewportChanged(); } } void DrawWidget::mouseMoveEvent(QMouseEvent * e) { QGLWidget::mouseMoveEvent(e); if (m_isDrag) m_framework->DoDrag(get_drag_event(e)); if (m_isRotate) m_framework->DoRotate(get_rotate_event(e->pos(), this->rect().center())); } void DrawWidget::mouseReleaseEvent(QMouseEvent * e) { QGLWidget::mouseReleaseEvent(e); StopDragging(e); StopRotating(e); emit ViewportChanged(); } void DrawWidget::keyReleaseEvent(QKeyEvent * e) { QGLWidget::keyReleaseEvent(e); StopRotating(e); emit ViewportChanged(); } void DrawWidget::StopRotating(QMouseEvent * e) { if (m_isRotate && (e->button() == Qt::LeftButton)) { m_framework->StopRotate(get_rotate_event(e->pos(), this->rect().center())); setCursor(Qt::ArrowCursor); m_isRotate = false; } } void DrawWidget::StopRotating(QKeyEvent * e) { if (m_isRotate && (e->key() == Qt::Key_Control)) { m_framework->StopRotate(get_rotate_event(this->mapFromGlobal(QCursor::pos()), this->rect().center())); } } void DrawWidget::StopDragging(QMouseEvent * e) { if (m_isDrag && e->button() == Qt::LeftButton) { m_framework->StopDrag(get_drag_event(e)); setCursor(Qt::ArrowCursor); m_isDrag = false; } } void DrawWidget::ScaleTimerElapsed() { m_timer->stop(); } void DrawWidget::AnimTimerElapsed() { DrawFrame(); } void DrawWidget::wheelEvent(QWheelEvent * e) { if (!m_isDrag && !m_isRotate) { // if we are inside the timer, cancel it if (m_timer->isActive()) m_timer->stop(); m_timer->start(m_redrawInterval); //m_framework->Scale(exp(e->delta() / 360.0)); m_framework->ScaleToPoint(ScaleToPointEvent(e->pos().x(), e->pos().y(), exp(e->delta() / 360.0))); UpdateScaleControl(); emit ViewportChanged(); } } void DrawWidget::UpdateScaleControl() { if (m_pScale) { // don't send ScaleChanged m_pScale->SetPosWithBlockedSignals(m_framework->GetDrawScale()); } } void DrawWidget::Search(search::SearchParams params) { if (m_framework->GetCurrentPosition(params.m_lat, params.m_lon)) { params.SetNearMeMode(true); params.m_validPos = true; } m_framework->Search(params); } void DrawWidget::ShowFeature(m2::RectD const & rect) { m_framework->ShowRect(rect); UpdateScaleControl(); } void DrawWidget::QueryMaxScaleMode() { m_framework->XorQueryMaxScaleMode(); } } <commit_msg>[desktop] more compact memory format for tile textures<commit_after>#include "draw_widget.hpp" #include "proxystyle.hpp" #include "slider_ctrl.hpp" #include "../map/framework_factory.hpp" #include "../map/render_policy.hpp" #include "../yg/internal/opengl.hpp" #include "../platform/settings.hpp" #include <QtGui/QMouseEvent> #include <QtGui/QMenu> using namespace storage; namespace qt { bool s_isExiting = false; QtVideoTimer::QtVideoTimer(DrawWidget * w, TFrameFn frameFn) : ::VideoTimer(frameFn), m_widget(w) {} void QtVideoTimer::start() { m_timer = new QTimer(); m_widget->connect(m_timer, SIGNAL(timeout()), m_widget, SLOT(AnimTimerElapsed())); resume(); } void QtVideoTimer::pause() { m_timer->stop(); m_state = EPaused; } void QtVideoTimer::resume() { m_timer->start(1000 / 60); m_state = ERunning; } void QtVideoTimer::stop() { pause(); delete m_timer; m_timer = 0; m_state = EStopped; } DrawWidget::DrawWidget(QWidget * pParent) : QGLWidget(pParent), m_isInitialized(false), m_isTimerStarted(false), m_framework(FrameworkFactory::CreateFramework()), m_isDrag(false), m_isRotate(false), m_redrawInterval(100), m_pScale(0) { m_timer = new QTimer(this); connect(m_timer, SIGNAL(timeout()), this, SLOT(ScaleTimerElapsed())); } DrawWidget::~DrawWidget() { m_framework.reset(); } void DrawWidget::PrepareShutdown() { s_isExiting = true; m_framework->PrepareToShutdown(); m_videoTimer.reset(); } void DrawWidget::SetScaleControl(QScaleSlider * pScale) { m_pScale = pScale; connect(m_pScale, SIGNAL(actionTriggered(int)), this, SLOT(ScaleChanged(int))); } void DrawWidget::UpdateNow() { update(); } void DrawWidget::UpdateAfterSettingsChanged() { m_framework->SetupMeasurementSystem(); } bool DrawWidget::LoadState() { pair<int, int> widthAndHeight; if (!Settings::Get("DrawWidgetSize", widthAndHeight)) return false; m_framework->OnSize(widthAndHeight.first, widthAndHeight.second); if (!m_framework->LoadState()) return false; //m_framework.UpdateNow(); UpdateScaleControl(); return true; } void DrawWidget::SaveState() { pair<int, int> widthAndHeight(width(), height()); Settings::Set("DrawWidgetSize", widthAndHeight); m_framework->SaveState(); } void DrawWidget::MoveLeft() { m_framework->Move(math::pi, 0.5); emit ViewportChanged(); } void DrawWidget::MoveRight() { m_framework->Move(0.0, 0.5); emit ViewportChanged(); } void DrawWidget::MoveUp() { m_framework->Move(math::pi/2.0, 0.5); emit ViewportChanged(); } void DrawWidget::MoveDown() { m_framework->Move(-math::pi/2.0, 0.5); emit ViewportChanged(); } void DrawWidget::ScalePlus() { m_framework->Scale(2.0); UpdateScaleControl(); emit ViewportChanged(); } void DrawWidget::ScaleMinus() { m_framework->Scale(0.5); UpdateScaleControl(); emit ViewportChanged(); } void DrawWidget::ScalePlusLight() { m_framework->Scale(1.5); UpdateScaleControl(); emit ViewportChanged(); } void DrawWidget::ScaleMinusLight() { m_framework->Scale(2.0/3.0); UpdateScaleControl(); emit ViewportChanged(); } void DrawWidget::ShowAll() { m_framework->ShowAll(); UpdateScaleControl(); emit ViewportChanged(); } void DrawWidget::Repaint() { m_framework->Invalidate(); } VideoTimer * DrawWidget::CreateVideoTimer() { #ifdef OMIM_OS_MAC return CreateAppleVideoTimer(bind(&DrawWidget::DrawFrame, this)); #else return new QtVideoTimer(this, bind(&DrawWidget::DrawFrame, this)); #endif } void DrawWidget::ScaleChanged(int action) { if (action != QAbstractSlider::SliderNoAction) { double const factor = m_pScale->GetScaleFactor(); if (factor != 1.0) { m_framework->Scale(factor); emit ViewportChanged(); } } } void DrawWidget::initializeGL() { /// we'll perform swap by ourselves, see issue #333 setAutoBufferSwap(false); if (!m_isInitialized) { m_videoTimer.reset(CreateVideoTimer()); shared_ptr<qt::gl::RenderContext> primaryRC(new qt::gl::RenderContext(this)); yg::ResourceManager::Params rmParams; rmParams.m_rtFormat = yg::Data8Bpp; rmParams.m_texFormat = yg::Data8Bpp; rmParams.m_texRtFormat = yg::Data4Bpp; rmParams.m_videoMemoryLimit = GetPlatform().VideoMemoryLimit(); try { m_framework->SetRenderPolicy(CreateRenderPolicy(m_videoTimer.get(), true, rmParams, primaryRC)); } catch (yg::gl::platform_unsupported const & e) { LOG(LERROR, ("OpenGL platform is unsupported, reason: ", e.what())); /// TODO: Show "Please Update Drivers" dialog and close the program. } m_isInitialized = true; } } void DrawWidget::resizeGL(int w, int h) { m_framework->OnSize(w, h); m_framework->Invalidate(); if (m_isInitialized && m_isTimerStarted) DrawFrame(); UpdateScaleControl(); emit ViewportChanged(); } void DrawWidget::paintGL() { if ((m_isInitialized) && (!m_isTimerStarted)) { /// timer should be started upon the first repaint /// request to fully initialized GLWidget. m_isTimerStarted = true; m_framework->SetUpdatesEnabled(true); } m_framework->Invalidate(); } void DrawWidget::DrawFrame() { if (s_isExiting) return; if (m_framework->NeedRedraw()) { makeCurrent(); m_framework->SetNeedRedraw(false); shared_ptr<PaintEvent> paintEvent(new PaintEvent(m_framework->GetRenderPolicy()->GetDrawer().get())); m_framework->BeginPaint(paintEvent); m_framework->DoPaint(paintEvent); /// swapping buffers before ending the frame, see issue #333 swapBuffers(); m_framework->EndPaint(paintEvent); doneCurrent(); } } namespace { DragEvent get_drag_event(QMouseEvent * e) { QPoint const p = e->pos(); return DragEvent(p.x(), p.y()); } RotateEvent get_rotate_event(QPoint const & pt, QPoint const & centerPt) { return RotateEvent(centerPt.x(), centerPt.y(), pt.x(), pt.y()); } } void DrawWidget::mousePressEvent(QMouseEvent * e) { QGLWidget::mousePressEvent(e); if (e->button() == Qt::LeftButton) { if (e->modifiers() & Qt::ControlModifier) { // starting rotation m_framework->StartRotate(get_rotate_event(e->pos(), this->rect().center())); setCursor(Qt::CrossCursor); m_isRotate = true; } else { // starting drag m_framework->StartDrag(get_drag_event(e)); setCursor(Qt::CrossCursor); m_isDrag = true; } } else if (e->button() == Qt::RightButton) { // show feature types QPoint const & pt = e->pos(); vector<string> types; m_framework->GetFeatureTypes(m2::PointD(pt.x(), pt.y()), types); QMenu menu; for (size_t i = 0; i < types.size(); ++i) menu.addAction(QString::fromAscii(types[i].c_str())); menu.exec(pt); } } void DrawWidget::mouseDoubleClickEvent(QMouseEvent * e) { QGLWidget::mouseDoubleClickEvent(e); if (e->button() == Qt::LeftButton) { StopDragging(e); m_framework->ScaleToPoint(ScaleToPointEvent(e->pos().x(), e->pos().y(), 1.5)); UpdateScaleControl(); emit ViewportChanged(); } } void DrawWidget::mouseMoveEvent(QMouseEvent * e) { QGLWidget::mouseMoveEvent(e); if (m_isDrag) m_framework->DoDrag(get_drag_event(e)); if (m_isRotate) m_framework->DoRotate(get_rotate_event(e->pos(), this->rect().center())); } void DrawWidget::mouseReleaseEvent(QMouseEvent * e) { QGLWidget::mouseReleaseEvent(e); StopDragging(e); StopRotating(e); emit ViewportChanged(); } void DrawWidget::keyReleaseEvent(QKeyEvent * e) { QGLWidget::keyReleaseEvent(e); StopRotating(e); emit ViewportChanged(); } void DrawWidget::StopRotating(QMouseEvent * e) { if (m_isRotate && (e->button() == Qt::LeftButton)) { m_framework->StopRotate(get_rotate_event(e->pos(), this->rect().center())); setCursor(Qt::ArrowCursor); m_isRotate = false; } } void DrawWidget::StopRotating(QKeyEvent * e) { if (m_isRotate && (e->key() == Qt::Key_Control)) { m_framework->StopRotate(get_rotate_event(this->mapFromGlobal(QCursor::pos()), this->rect().center())); } } void DrawWidget::StopDragging(QMouseEvent * e) { if (m_isDrag && e->button() == Qt::LeftButton) { m_framework->StopDrag(get_drag_event(e)); setCursor(Qt::ArrowCursor); m_isDrag = false; } } void DrawWidget::ScaleTimerElapsed() { m_timer->stop(); } void DrawWidget::AnimTimerElapsed() { DrawFrame(); } void DrawWidget::wheelEvent(QWheelEvent * e) { if (!m_isDrag && !m_isRotate) { // if we are inside the timer, cancel it if (m_timer->isActive()) m_timer->stop(); m_timer->start(m_redrawInterval); //m_framework->Scale(exp(e->delta() / 360.0)); m_framework->ScaleToPoint(ScaleToPointEvent(e->pos().x(), e->pos().y(), exp(e->delta() / 360.0))); UpdateScaleControl(); emit ViewportChanged(); } } void DrawWidget::UpdateScaleControl() { if (m_pScale) { // don't send ScaleChanged m_pScale->SetPosWithBlockedSignals(m_framework->GetDrawScale()); } } void DrawWidget::Search(search::SearchParams params) { if (m_framework->GetCurrentPosition(params.m_lat, params.m_lon)) { params.SetNearMeMode(true); params.m_validPos = true; } m_framework->Search(params); } void DrawWidget::ShowFeature(m2::RectD const & rect) { m_framework->ShowRect(rect); UpdateScaleControl(); } void DrawWidget::QueryMaxScaleMode() { m_framework->XorQueryMaxScaleMode(); } } <|endoftext|>
<commit_before>/* * creaturesImage.cpp * openc2e * * Created by Alyssa Milburn on Sun Jun 06 2004. * Copyright (c) 2004 Alyssa Milburn. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "creaturesImage.h" #include "c16Image.h" #include "blkImage.h" #include "openc2e.h" #include "fileSwapper.h" #include "PathResolver.h" #include <iostream> #include <fstream> #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #include <sys/types.h> // passwd* #include <pwd.h> // getpwuid using namespace boost::filesystem; imageGallery gallery; enum filetype { blk, s16, c16 }; path homeDirectory() { path p; char *envhome = getenv("HOME"); if (envhome) p = path(envhome, native); if ((!envhome) || (!is_directory(p))) p = path(getpwuid(getuid())->pw_dir, native); if (!is_directory(p)) { std::cerr << "Can't work out what your home directory is, giving up and using /tmp for now." << std::endl; p = path("/tmp", native); // sigh } return p; } path cacheDirectory() { path p = path(homeDirectory().native_directory_string() + "/.openc2e", native); if (!exists(p)) create_directory(p); else if (!is_directory(p)) throw creaturesException("Your .openc2e is a file, not a directory. That's bad."); return p; } bool tryOpen(mmapifstream *in, creaturesImage *&img, std::string fname, filetype ft) { path cachefile, realfile; std::string cachename; std::string basename = fname; basename.erase(basename.end() - 4, basename.end()); // work out where the real file should be switch (ft) { case blk: realfile = path(datapath + "/Backgrounds/" + fname, native); break; case c16: case s16: realfile = path(datapath + "/Images/" + fname, native); break; } // if it doesn't exist, too bad, give up. if (!resolveFile(realfile)) return false; // work out where the cached file should be cachename = cacheDirectory().native_directory_string() + "/" + fname; if (ft == c16) { // TODO: we should really stop the caller from appending .s16/.c16 cachename.erase(cachename.end() - 4, cachename.end()); cachename.append(".s16"); } #ifdef __C2E_BIGENDIAN cachename = cachename + ".big"; #endif cachefile = path(cachename, native); if (resolveFile(cachefile)) { // TODO: check for up-to-date-ness in->clear(); in->mmapopen(cachefile.native_file_string()); if (ft == c16) ft = s16; goto done; } std::cout << "couldn't find cached version: " << cachefile.native_file_string() << std::endl; in->clear(); in->mmapopen(realfile.native_file_string()); #ifdef __C2E_BIGENDIAN if (in->is_open()) { fileSwapper f; switch (ft) { case blk: f.convertblk(realfile.native_file_string(), cachefile.native_file_string()); break; case s16: f.converts16(realfile.native_file_string(), cachefile.native_file_string()); break; case c16: //cachefile = change_extension(cachefile, ""); //cachefile = change_extension(cachefile, ".s16.big"); f.convertc16(realfile.native_file_string(), cachefile.native_file_string()); ft = s16; break; default: return true; // TODO: exception? } in->close(); // TODO: close the mmap too! how? if (!exists(cachefile)) return false; // TODO: exception? in->mmapopen(cachefile.native_file_string()); } #endif done: if (in->is_open()) { switch (ft) { case blk: img = new blkImage(in); break; case c16: img = new c16Image(in); break; // this should never happen, actually, once we're done case s16: img = new s16Image(in); break; } img->name = basename; } return in->is_open(); } /* * Retrieve an image for rendering use. To retrieve a sprite, pass the name without * extension. To retrieve a background, pass the full filename (ie, with .blk). */ creaturesImage *imageGallery::getImage(std::string name) { // step one: see if the image is already in the gallery std::map<std::string, creaturesImage *>::iterator i = gallery.find(name); if (i != gallery.end()) { creaturesImage *img = i->second; img->addRef(); return img; } // step two: try opening it in .c16 form first, then try .s16 form mmapifstream *in = new mmapifstream(); creaturesImage *img; if (!tryOpen(in, img, name + ".s16", s16)) { if (!tryOpen(in, img, name + ".c16", c16)) { bool lasttry = tryOpen(in, img, name, blk); if (!lasttry) { std::cerr << "imageGallery couldn't find the sprite '" << name << "'" << std::endl; return 0; } gallery[name] = img; } else { gallery[name] = img; } } else { gallery[name] = img; } in->close(); // doesn't close the mmap, which we still need :) return gallery[name]; } void imageGallery::delImage(creaturesImage *in) { in->delRef(); if (in->refCount() == 0) { delete in; for (std::map<std::string, creaturesImage *>::iterator i = gallery.begin(); i != gallery.end(); i++) { if (i->second == in) { gallery.erase(i); return; } } std::cerr << "imageGallery warning: delImage got a newly unreferenced image but it isn't in the gallery\n"; } } /* vim: set noet: */ <commit_msg>add win32 homeDirectory() implementation<commit_after>/* * creaturesImage.cpp * openc2e * * Created by Alyssa Milburn on Sun Jun 06 2004. * Copyright (c) 2004 Alyssa Milburn. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "creaturesImage.h" #include "c16Image.h" #include "blkImage.h" #include "openc2e.h" #include "fileSwapper.h" #include "PathResolver.h" #include <iostream> #include <fstream> #include <boost/filesystem/path.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #ifndef _WIN32 #include <sys/types.h> // passwd* #include <pwd.h> // getpwuid #endif using namespace boost::filesystem; imageGallery gallery; enum filetype { blk, s16, c16 }; #ifndef _WIN32 path homeDirectory() { path p; char *envhome = getenv("HOME"); if (envhome) p = path(envhome, native); if ((!envhome) || (!is_directory(p))) p = path(getpwuid(getuid())->pw_dir, native); if (!is_directory(p)) { std::cerr << "Can't work out what your home directory is, giving up and using /tmp for now." << std::endl; p = path("/tmp", native); // sigh } return p; } #else path homeDirectory() { path p = path("./temp", native); if (!exists(p)) create_directory(p); return p; } #endif path cacheDirectory() { path p = path(homeDirectory().native_directory_string() + "/.openc2e", native); if (!exists(p)) create_directory(p); else if (!is_directory(p)) throw creaturesException("Your .openc2e is a file, not a directory. That's bad."); return p; } bool tryOpen(mmapifstream *in, creaturesImage *&img, std::string fname, filetype ft) { path cachefile, realfile; std::string cachename; std::string basename = fname; basename.erase(basename.end() - 4, basename.end()); // work out where the real file should be switch (ft) { case blk: realfile = path(datapath + "/Backgrounds/" + fname, native); break; case c16: case s16: realfile = path(datapath + "/Images/" + fname, native); break; } // if it doesn't exist, too bad, give up. if (!resolveFile(realfile)) return false; // work out where the cached file should be cachename = cacheDirectory().native_directory_string() + "/" + fname; if (ft == c16) { // TODO: we should really stop the caller from appending .s16/.c16 cachename.erase(cachename.end() - 4, cachename.end()); cachename.append(".s16"); } #ifdef __C2E_BIGENDIAN cachename = cachename + ".big"; #endif cachefile = path(cachename, native); if (resolveFile(cachefile)) { // TODO: check for up-to-date-ness in->clear(); in->mmapopen(cachefile.native_file_string()); if (ft == c16) ft = s16; goto done; } std::cout << "couldn't find cached version: " << cachefile.native_file_string() << std::endl; in->clear(); in->mmapopen(realfile.native_file_string()); #ifdef __C2E_BIGENDIAN if (in->is_open()) { fileSwapper f; switch (ft) { case blk: f.convertblk(realfile.native_file_string(), cachefile.native_file_string()); break; case s16: f.converts16(realfile.native_file_string(), cachefile.native_file_string()); break; case c16: //cachefile = change_extension(cachefile, ""); //cachefile = change_extension(cachefile, ".s16.big"); f.convertc16(realfile.native_file_string(), cachefile.native_file_string()); ft = s16; break; default: return true; // TODO: exception? } in->close(); // TODO: close the mmap too! how? if (!exists(cachefile)) return false; // TODO: exception? in->mmapopen(cachefile.native_file_string()); } #endif done: if (in->is_open()) { switch (ft) { case blk: img = new blkImage(in); break; case c16: img = new c16Image(in); break; // this should never happen, actually, once we're done case s16: img = new s16Image(in); break; } img->name = basename; } return in->is_open(); } /* * Retrieve an image for rendering use. To retrieve a sprite, pass the name without * extension. To retrieve a background, pass the full filename (ie, with .blk). */ creaturesImage *imageGallery::getImage(std::string name) { // step one: see if the image is already in the gallery std::map<std::string, creaturesImage *>::iterator i = gallery.find(name); if (i != gallery.end()) { creaturesImage *img = i->second; img->addRef(); return img; } // step two: try opening it in .c16 form first, then try .s16 form mmapifstream *in = new mmapifstream(); creaturesImage *img; if (!tryOpen(in, img, name + ".s16", s16)) { if (!tryOpen(in, img, name + ".c16", c16)) { bool lasttry = tryOpen(in, img, name, blk); if (!lasttry) { std::cerr << "imageGallery couldn't find the sprite '" << name << "'" << std::endl; return 0; } gallery[name] = img; } else { gallery[name] = img; } } else { gallery[name] = img; } in->close(); // doesn't close the mmap, which we still need :) return gallery[name]; } void imageGallery::delImage(creaturesImage *in) { in->delRef(); if (in->refCount() == 0) { delete in; for (std::map<std::string, creaturesImage *>::iterator i = gallery.begin(); i != gallery.end(); i++) { if (i->second == in) { gallery.erase(i); return; } } std::cerr << "imageGallery warning: delImage got a newly unreferenced image but it isn't in the gallery\n"; } } /* vim: set noet: */ <|endoftext|>
<commit_before>#ifndef V_SMC_CORE_PARTICLE_HPP #define V_SMC_CORE_PARTICLE_HPP #include <algorithm> #include <limits> #include <cstddef> #include <mkl_cblas.h> #include <mkl_vml.h> #include <boost/function.hpp> #include <boost/math/special_functions/log1p.hpp> #include <Random123/aes.h> #include <Random123/ars.h> #include <Random123/philox.h> #include <Random123/threefry.h> #include <vDist/rng/gsl.hpp> #include <vDist/tool/buffer.hpp> #include <vDist/tool/constants.hpp> #include <vDist/tool/eblas.hpp> /// The Parallel RNG (based on Rand123) seed #ifndef V_SMC_PRNG_SEED #define V_SMC_PRNG_SEED 0xdeadbeefL #endif // V_SMC_PRNG_SEED /// The Parallel RNG (based on Rand123) type, philox or threefry #ifndef V_SMC_PRNG_TYPE #define V_SMC_PRNG_TYPE Threefry4x64 #endif // V_SMC_PRNG_TYPE /// The type used to extract random bits #ifndef V_SMC_PRNG_UINT_TYPE #define V_SMC_PRNG_UINT_TYPE unsigned #endif // V_SMC_PRNG_UINT_TYPE #define V_SMC_PRNG_IDX_MAX \ (sizeof(rng_type::ctr_type) / sizeof(V_SMC_PRNG_UINT_TYPE)) namespace vSMC { /// Resample scheme enum ResampleScheme {MULTINOMIAL, RESIDUAL, STRATIFIED, SYSTEMATIC}; /// \brief Particle class /// /// Particle class store the particle set and arrays of weights and log /// weights. It provides access to particle values as well as weights. It /// computes and manages resources for ESS, resampling, etc, tasks unique to /// each iteration. template <typename T> class Particle { public : /// \brief Type of of the internal RNG, one of the 64 bit Rand123 type typedef r123::V_SMC_PRNG_TYPE rng_type; /// \brief Construct a Particle object with given number of particles /// /// \param N The number of particles Particle (std::size_t N) : size_(N), value_(N), weight_(N), log_weight_(N), inc_weight_(N), replication_(N), ess_(0), resampled_(false), zconst_(0), estimate_zconst_(false), rbase_(0), rbit_(N), ridx_(N), rctr_(N), rkey_(N) { int shift = sizeof(V_SMC_PRNG_UINT_TYPE) * 8 - 1; rbase_ = 0.5 / (1U<<shift); for (std::size_t i = 0; i != N; ++i) { rng_type::ctr_type c = {{}}; rng_type::key_type k = {{}}; c[0] = i; k[0] = V_SMC_PRNG_SEED + i; rctr_[i] = c; rkey_[i] = k; ridx_[i] = 0; rbit_[i].c = crng_(rctr_[i], rkey_[i]); } for (std::size_t i = 0; i != size_; ++i) { weight_[i] = 1; log_weight_[i] = 0; } } /// \brief Size of the particle set /// /// \return The number of particles std::size_t size () const { return size_; } /// \brief Read and write access to particle values /// /// \return A reference to the particle values, type (T &) /// /// \note The Particle class guarantee that during the life type of the /// object, the reference returned by this member will no be a dangle /// handler. T &value () { return value_; } /// \brief Read only access to particle values /// /// \return A const reference to the particle values const T &value () const { return value_; } /// \brief Read only access to the weights /// /// \return A const pointer to the weights /// /// \note The Particle class guarantee that during the life type of the /// object, the pointer returned by this always valid and point to the /// same address const double *weight_ptr () const { return weight_.get(); } /// \brief Read only access to the log weights /// /// \return A const pointer to the log weights const double *log_weight_ptr () const { return log_weight_.get(); } /// \brief Set the log weights /// /// \param [in] new_weight New log weights void set_log_weight (const double *new_weight) { cblas_dcopy(size_, new_weight, 1, log_weight_, 1); set_weight(); } /// \brief Add to the log weights /// /// \param [in] inc_weight Incremental log weights void add_log_weight (const double *inc_weight) { if (estimate_zconst_) { vdExp(size_, inc_weight, inc_weight_); zconst_ += std::log(cblas_ddot(size_, weight_, 1, inc_weight_, 1)); } vdAdd(size_, log_weight_, inc_weight, log_weight_); set_weight(); } /// \brief The ESS (Effective Sample Size) /// /// \return The value of ESS for current particle set double ess () const { return ess_; } /// \brief Get indicator of resampling /// /// \return A bool value, \b true if the current iteration was resampled bool resampled () const { return resampled_; } /// \brief Set indicator of resampling /// /// \param resampled \b true if the current iteration was resampled void resampled (bool resampled) { resampled_ = resampled; } /// \brief Get the value of SMC normalizing constant /// /// \return SMC normalizng constant estimate double zconst () const { return zconst_; } /// \brief Toggle whether or not record SMC normalizing constant /// /// \param estimate_zconst Start estimating normalzing constant if true void zconst (bool estimate_zconst) { estimate_zconst_ = estimate_zconst; } /// \brief Reset the value of SMC normalizing constant void reset_zconst () { zconst_ = 0; } /// \brief Perform resampling /// /// \param scheme The resampling scheme, see ResamplingScheme /// \param [in] rng A gsl rng object pointer void resample (ResampleScheme scheme, const gsl_rng *rng) { switch (scheme) { case MULTINOMIAL : resample_multinomial(rng); break; case RESIDUAL : resample_residual(rng); break; case STRATIFIED : resample_stratified(rng); break; case SYSTEMATIC : resample_systematic(rng); break; default : throw std::runtime_error( "ERROR: vSMC::Particle::resample: " "Unknown Resample Scheme"); } } /// \brief Generate an uniform random integer V_SMC_PRNG_UINT_TYPE ruint (std::size_t id) { if (ridx_[id] == V_SMC_PRNG_IDX_MAX) { ridx_[id] = 0; rctr_[id][0] += size_; rbit_[id].c = crng_(rctr_[id], rkey_[id]); } return rbit_[id].n[ridx_[id]++]; } /// \brief Generate an [0,1] uniform random variate double runif (std::size_t id) { return ruint(id) * rbase_; } double runif (std::size_t id, double min, double max) { return runif(id) * (max - min) + min; } double rnorm (std::size_t id, double mean, double sd) { double u1 = runif(id); double u2 = runif(id); return std::sqrt(-2 * std::log(u1)) * std::sin(vDist::constants::pi2() * u2) * sd + mean; } double rlnorm (std::size_t id, double meanlog, double sdlog) { return std::exp(rnorm(id, meanlog, sdlog)); } double rcauchy (std::size_t id, double location, double scale) { return scale * std::tan(vDist::constants::pi() * (runif(id) - 0.5)) + location; } double rexp (std::size_t id, double scale) { return -scale * boost::math::log1p(-runif(id)); } double rlaplace (std::size_t id, double location, double scale) { double u = runif(id) - 0.5; return u > 0 ? location - scale * boost::math::log1p(-2 * u): location + scale * boost::math::log1p(2 * u); } double rweibull (std::size_t id, double shape, double scale) { return scale * std::pow( -boost::math::log1p(-runif(id)), 1 / shape); } // TODO GAMMA double rgamma (std::size_t id, double shape, double scale) { return 0; } double rchisq (std::size_t id, double df) { return rgamma(id, 0.5 * df, 2); } double rf (std::size_t id, double df1, double df2) { return rchisq(id, df1) / rchisq(id, df2) * df2 / df1; } double rt (std::size_t id, double df) { return rnorm(id, 0, 1) / std::sqrt(rchisq(id, df) / df); } // TODO BETA double rbeta (std::size_t id, double shape1, double shape2) { return 0; } private : std::size_t size_; T value_; vDist::tool::Buffer<double> weight_; vDist::tool::Buffer<double> log_weight_; vDist::tool::Buffer<double> inc_weight_; vDist::tool::Buffer<unsigned> replication_; double ess_; bool resampled_; double zconst_; bool estimate_zconst_; union uni { rng_type::ctr_type c; V_SMC_PRNG_UINT_TYPE n[V_SMC_PRNG_IDX_MAX];}; double rbase_; rng_type crng_; vDist::tool::Buffer<uni> rbit_; vDist::tool::Buffer<int> ridx_; vDist::tool::Buffer<rng_type::ctr_type> rctr_; vDist::tool::Buffer<rng_type::key_type> rkey_; void set_weight () { double max_weight = -std::numeric_limits<double>::infinity(); for (std::size_t i = 0; i != size_; ++i) max_weight = std::max(max_weight, log_weight_[i]); for (std::size_t i = 0; i != size_; ++i) log_weight_[i] -= max_weight; vdExp(size_, log_weight_, weight_); double sum = cblas_dasum(size_, weight_, 1); cblas_dscal(size_, 1 / sum, weight_, 1); ess_ = 1 / cblas_ddot(size_, weight_, 1, weight_, 1); } void resample_multinomial (const gsl_rng *rng) { gsl_ran_multinomial(rng, size_, size_, weight_, replication_); resample_do(); } void resample_residual (const gsl_rng *rng) { /// \internal Reuse weight and log_weight. /// weight: act as the fractional part of N * weight. /// log_weight: act as the integral part of N * weight. /// They all will be reset to equal weights after resampling. /// So it is safe to modify them here. vDist::tool::dyatx(size_, size_, weight_, 1, log_weight_, 1); vdModf(size_, log_weight_, log_weight_, weight_); std::size_t size = size_; size -= cblas_dasum(size_, log_weight_, 1); gsl_ran_multinomial(rng, size_, size, weight_, replication_); for (std::size_t i = 0; i != size_; ++i) replication_[i] += log_weight_[i]; resample_do(); } void resample_stratified (const gsl_rng *rng) {} void resample_systematic (const gsl_rng *rng) {} void resample_do () { std::size_t from = 0; std::size_t time = 0; for (std::size_t to = 0; to != size_; ++to) { if (!replication_[to]) { // replication_[to] has zero child, copy from elsewhere if (replication_[from] - time <= 1) { // only 1 child left on replication_[from] time = 0; do // move from to some position with at least 2 children ++from; while (replication_[from] < 2); } value_.copy(from, to); ++time; } } vDist::tool::dfill(size_, 1.0 / size_, weight_, 1); vDist::tool::dfill(size_, 0, log_weight_, 1); ess_ = size_; } }; // class Particle } // namespace vSMC #endif // V_SMC_CORE_PARTICLE_HPP <commit_msg>cleanup<commit_after>#ifndef V_SMC_CORE_PARTICLE_HPP #define V_SMC_CORE_PARTICLE_HPP #include <algorithm> #include <limits> #include <cstddef> #include <mkl_cblas.h> #include <mkl_vml.h> #include <boost/function.hpp> #include <boost/math/special_functions/log1p.hpp> #include <Random123/aes.h> #include <Random123/ars.h> #include <Random123/philox.h> #include <Random123/threefry.h> #include <vDist/rng/gsl.hpp> #include <vDist/tool/buffer.hpp> #include <vDist/tool/constants.hpp> #include <vDist/tool/eblas.hpp> /// The Parallel RNG (based on Rand123) seed #ifndef V_SMC_PRNG_SEED #define V_SMC_PRNG_SEED 0xdeadbeefL #endif // V_SMC_PRNG_SEED /// The Parallel RNG (based on Rand123) type, philox or threefry #ifndef V_SMC_PRNG_TYPE #define V_SMC_PRNG_TYPE Threefry4x64 #endif // V_SMC_PRNG_TYPE /// The type used to extract random bits #ifndef V_SMC_PRNG_UINT_TYPE #define V_SMC_PRNG_UINT_TYPE unsigned #endif // V_SMC_PRNG_UINT_TYPE #define V_SMC_PRNG_IDX_MAX \ (sizeof(rng_type::ctr_type) / sizeof(V_SMC_PRNG_UINT_TYPE)) namespace vSMC { /// Resample scheme enum ResampleScheme {MULTINOMIAL, RESIDUAL, STRATIFIED, SYSTEMATIC}; /// \brief Particle class /// /// Particle class store the particle set and arrays of weights and log /// weights. It provides access to particle values as well as weights. It /// computes and manages resources for ESS, resampling, etc, tasks unique to /// each iteration. template <typename T> class Particle { public : /// \brief Type of of the internal RNG, one of the 64 bit Rand123 type typedef r123::V_SMC_PRNG_TYPE rng_type; /// \brief Construct a Particle object with given number of particles /// /// \param N The number of particles Particle (std::size_t N) : size_(N), value_(N), weight_(N), log_weight_(N), inc_weight_(N), replication_(N), ess_(0), resampled_(false), zconst_(0), estimate_zconst_(false), rbase_(0), rbit_(N), ridx_(N), rctr_(N), rkey_(N) { int shift = sizeof(V_SMC_PRNG_UINT_TYPE) * 8 - 1; rbase_ = 0.5 / (1U<<shift); for (std::size_t i = 0; i != N; ++i) { rng_type::ctr_type c = {{}}; rng_type::key_type k = {{}}; c[0] = i; k[0] = V_SMC_PRNG_SEED + i; rctr_[i] = c; rkey_[i] = k; ridx_[i] = 0; rbit_[i].c = crng_(rctr_[i], rkey_[i]); } vDist::tool::dfill(size_, 1.0 / size_, weight_, 1); vDist::tool::dfill(size_, 0, log_weight_, 1); } /// \brief Size of the particle set /// /// \return The number of particles std::size_t size () const { return size_; } /// \brief Read and write access to particle values /// /// \return A reference to the particle values, type (T &) /// /// \note The Particle class guarantee that during the life type of the /// object, the reference returned by this member will no be a dangle /// handler. T &value () { return value_; } /// \brief Read only access to particle values /// /// \return A const reference to the particle values const T &value () const { return value_; } /// \brief Read only access to the weights /// /// \return A const pointer to the weights /// /// \note The Particle class guarantee that during the life type of the /// object, the pointer returned by this always valid and point to the /// same address const double *weight_ptr () const { return weight_.get(); } /// \brief Read only access to the log weights /// /// \return A const pointer to the log weights const double *log_weight_ptr () const { return log_weight_.get(); } /// \brief Set the log weights /// /// \param [in] new_weight New log weights void set_log_weight (const double *new_weight) { cblas_dcopy(size_, new_weight, 1, log_weight_, 1); set_weight(); } /// \brief Add to the log weights /// /// \param [in] inc_weight Incremental log weights void add_log_weight (const double *inc_weight) { if (estimate_zconst_) { vdExp(size_, inc_weight, inc_weight_); zconst_ += std::log(cblas_ddot(size_, weight_, 1, inc_weight_, 1)); } vdAdd(size_, log_weight_, inc_weight, log_weight_); set_weight(); } /// \brief The ESS (Effective Sample Size) /// /// \return The value of ESS for current particle set double ess () const { return ess_; } /// \brief Get indicator of resampling /// /// \return A bool value, \b true if the current iteration was resampled bool resampled () const { return resampled_; } /// \brief Set indicator of resampling /// /// \param resampled \b true if the current iteration was resampled void resampled (bool resampled) { resampled_ = resampled; } /// \brief Get the value of SMC normalizing constant /// /// \return SMC normalizng constant estimate double zconst () const { return zconst_; } /// \brief Toggle whether or not record SMC normalizing constant /// /// \param estimate_zconst Start estimating normalzing constant if true void zconst (bool estimate_zconst) { estimate_zconst_ = estimate_zconst; } /// \brief Reset the value of SMC normalizing constant void reset_zconst () { zconst_ = 0; } /// \brief Perform resampling /// /// \param scheme The resampling scheme, see ResamplingScheme /// \param [in] rng A gsl rng object pointer void resample (ResampleScheme scheme, const gsl_rng *rng) { switch (scheme) { case MULTINOMIAL : resample_multinomial(rng); break; case RESIDUAL : resample_residual(rng); break; case STRATIFIED : resample_stratified(rng); break; case SYSTEMATIC : resample_systematic(rng); break; default : throw std::runtime_error( "ERROR: vSMC::Particle::resample: " "Unknown Resample Scheme"); } } /// \brief Generate an uniform random integer V_SMC_PRNG_UINT_TYPE ruint (std::size_t id) { if (ridx_[id] == V_SMC_PRNG_IDX_MAX) { ridx_[id] = 0; rctr_[id][0] += size_; rbit_[id].c = crng_(rctr_[id], rkey_[id]); } return rbit_[id].n[ridx_[id]++]; } /// \brief Generate an [0,1] uniform random variate double runif (std::size_t id) { return ruint(id) * rbase_; } double runif (std::size_t id, double min, double max) { return runif(id) * (max - min) + min; } double rnorm (std::size_t id, double mean, double sd) { double u1 = runif(id); double u2 = runif(id); return std::sqrt(-2 * std::log(u1)) * std::sin(vDist::constants::pi2() * u2) * sd + mean; } double rlnorm (std::size_t id, double meanlog, double sdlog) { return std::exp(rnorm(id, meanlog, sdlog)); } double rcauchy (std::size_t id, double location, double scale) { return scale * std::tan(vDist::constants::pi() * (runif(id) - 0.5)) + location; } double rexp (std::size_t id, double scale) { return -scale * boost::math::log1p(-runif(id)); } double rlaplace (std::size_t id, double location, double scale) { double u = runif(id) - 0.5; return u > 0 ? location - scale * boost::math::log1p(-2 * u): location + scale * boost::math::log1p(2 * u); } double rweibull (std::size_t id, double shape, double scale) { return scale * std::pow( -boost::math::log1p(-runif(id)), 1 / shape); } // TODO GAMMA double rgamma (std::size_t id, double shape, double scale) { return 0; } double rchisq (std::size_t id, double df) { return rgamma(id, 0.5 * df, 2); } double rf (std::size_t id, double df1, double df2) { return rchisq(id, df1) / rchisq(id, df2) * df2 / df1; } double rt (std::size_t id, double df) { return rnorm(id, 0, 1) / std::sqrt(rchisq(id, df) / df); } // TODO BETA double rbeta (std::size_t id, double shape1, double shape2) { return 0; } private : std::size_t size_; T value_; vDist::tool::Buffer<double> weight_; vDist::tool::Buffer<double> log_weight_; vDist::tool::Buffer<double> inc_weight_; vDist::tool::Buffer<unsigned> replication_; double ess_; bool resampled_; double zconst_; bool estimate_zconst_; union uni { rng_type::ctr_type c; V_SMC_PRNG_UINT_TYPE n[V_SMC_PRNG_IDX_MAX];}; double rbase_; rng_type crng_; vDist::tool::Buffer<uni> rbit_; vDist::tool::Buffer<int> ridx_; vDist::tool::Buffer<rng_type::ctr_type> rctr_; vDist::tool::Buffer<rng_type::key_type> rkey_; void set_weight () { double max_weight = -std::numeric_limits<double>::infinity(); for (std::size_t i = 0; i != size_; ++i) max_weight = std::max(max_weight, log_weight_[i]); for (std::size_t i = 0; i != size_; ++i) log_weight_[i] -= max_weight; vdExp(size_, log_weight_, weight_); double sum = cblas_dasum(size_, weight_, 1); cblas_dscal(size_, 1 / sum, weight_, 1); ess_ = 1 / cblas_ddot(size_, weight_, 1, weight_, 1); } void resample_multinomial (const gsl_rng *rng) { gsl_ran_multinomial(rng, size_, size_, weight_, replication_); resample_do(); } void resample_residual (const gsl_rng *rng) { // Reuse weight and log_weight. weight: act as the fractional part of // N * weight. log_weight: act as the integral part of N * weight. // They all will be reset to equal weights after resampling. So it is // safe to modify them here. vDist::tool::dyatx(size_, size_, weight_, 1, log_weight_, 1); vdModf(size_, log_weight_, log_weight_, weight_); std::size_t size = size_; size -= cblas_dasum(size_, log_weight_, 1); gsl_ran_multinomial(rng, size_, size, weight_, replication_); for (std::size_t i = 0; i != size_; ++i) replication_[i] += log_weight_[i]; resample_do(); } void resample_stratified (const gsl_rng *rng) {} void resample_systematic (const gsl_rng *rng) {} void resample_do () { std::size_t from = 0; std::size_t time = 0; for (std::size_t to = 0; to != size_; ++to) { if (!replication_[to]) { // replication_[to] has zero child, copy from elsewhere if (replication_[from] - time <= 1) { // only 1 child left on replication_[from] time = 0; do // move from to some position with at least 2 children ++from; while (replication_[from] < 2); } value_.copy(from, to); ++time; } } vDist::tool::dfill(size_, 1.0 / size_, weight_, 1); vDist::tool::dfill(size_, 0, log_weight_, 1); ess_ = size_; } }; // class Particle } // namespace vSMC #endif // V_SMC_CORE_PARTICLE_HPP <|endoftext|>
<commit_before>#ifndef INCLUDE_AL_FILE_HPP #define INCLUDE_AL_FILE_HPP #include <unistd.h> #include <stdio.h> #include <string> #include <sys/stat.h> #include <list> #include "allocore/system/al_Config.h" #ifdef AL_WIN32 #define AL_FILE_DELIMITER '\\' #else #define AL_FILE_DELIMITER '/' #endif #define AL_PATH_MAX (4096) namespace al{ /// Strips a qualified path to a file (src) into a path to the containing folder (dst) //void path2dir(char* dst, const char* src); /// a pair of path (folder/directory) and filename class FilePath { public: FilePath() {}; FilePath(std::string file, std::string path) : mPath(path), mFile(file) {} ///! this constructor takes a path to a file: FilePath(std::string fullpath); const std::string& file() const { return mFile; } const std::string& path() const { return mPath; } std::string filepath() const { return path()+file(); } FilePath& file(const std::string& v) { mFile=v; return *this; } FilePath& path(const std::string& v) { mPath=v; return *this; } protected: std::string mPath; std::string mFile; }; /// A handy way to manage several possible search paths class SearchPaths { public: SearchPaths() {} SearchPaths(int argc, char * const argv[], bool recursive=true) { addAppPaths(argc,argv,recursive); } ~SearchPaths() {} /// find a file in the searchpaths /// returns true if file found, and fills result with corresponding path & filename /// returns false if file not found FilePath find(const std::string& filename); /// add a path to search in; recursive searching is optional void addSearchPath(const std::string& path, bool recursive = true); /// adds best estimate of application launch paths (cwd etc.) /// can pass in argv from the main() function if desired. void addAppPaths(int argc, char * const argv[], bool recursive = true); void addAppPaths(bool recursive = true); const std::string& appPath() const { return mAppPath; } /// todo? //void addResourcePath(); // strips trailing filename from a path; e.g. /usr/bin/man -> /usr/bin/ static std::string stripFileName(const std::string& src); // ensure path ends with the proper delimiter static std::string conformPath(const std::string& src); // does a file at the given filepath exist? static bool fileExists(const std::string& name, const std::string& path); protected: typedef std::pair<std::string, bool> searchpath; std::list<searchpath> mSearchPaths; std::string mAppPath; }; /// File class File{ public: /// @param[in] path path of file /// @param[in] mode i/o mode w, r, wb, rb /// @param[in] open whether to open the file File(const std::string& path, const std::string& mode="r", bool open=false); File(const FilePath& path, const std::string& mode="r", bool open=false); ~File(); void close(); ///< Close file bool open(); ///< Open file with specified i/o mode File& mode(const std::string& v){ mMode=v; return *this; } File& path(const std::string& v){ mPath=v; return *this; } /// Write memory elements to file int write(const std::string& v){ return write(v.data(), 1, v.length()); } int write(const void * v, int itemSizeInBytes, int items=1){ int itemsWritten = fwrite(v, itemSizeInBytes, items, mFP); mSizeBytes += itemsWritten * itemSizeInBytes; return itemsWritten; } /// Read memory elements from file int read(void * v, int size, int items=1){ return fread(v, size, items, mFP); } /// Quick and dirty write memory to file static int write(const std::string& path, const void * v, int size, int items=1); /// Returns character string of file contents (read mode only) const char * readAll(); /// Returns whether file is open bool opened() const { return 0 != mFP; } /// Returns file i/o mode string const std::string& mode() const { return mMode; } /// Returns path string const std::string& path() const { return mPath; } /// Returns size, in bytes, of file contents int size() const { return mSizeBytes; } /// Returns whether file exists static bool exists(const std::string& path); /// Return modification time of file (or 0 on failure) \ as number of seconds since 00:00:00 january 1, 1970 UTC al_sec modified() const; /// Return last access time of file (or 0 on failure) \ as number of seconds since 00:00:00 january 1, 1970 UTC al_sec accessed() const; /// Return creation time of file (or 0 on failure) \ as number of seconds since 00:00:00 january 1, 1970 UTC al_sec created() const; /// Return size file (or 0 on failure) size_t sizeFile() const; /// Return space used on disk of file (or 0 on failure) size_t storage() const; FILE * filePointer() { return mFP; } static al_sec modified(std::string path) { File f(path); return f.modified(); } static al_sec accessed(std::string path) { File f(path); return f.accessed(); } static al_sec created(std::string path) { File f(path); return f.created(); } static size_t sizeFile(std::string path) { File f(path); return f.sizeFile(); } static size_t storage(std::string path) { File f(path); return f.storage(); } protected: class Impl; Impl * mImpl; std::string mPath; std::string mMode; char * mContent; int mSizeBytes; FILE * mFP; void freeContent(); void allocContent(int n); void getSize(); }; //// INLINE IMPLEMENTATION //// inline std::string SearchPaths::stripFileName(const std::string& src) { std::string filepath(src); size_t pos = filepath.find_last_of(AL_FILE_DELIMITER); if (pos !=std::string::npos) { filepath.erase(pos+1); } return filepath; } inline std::string SearchPaths::conformPath(const std::string& src) { std::string path(src); // paths should end with a delimiter: if (path[path.size()-1] != AL_FILE_DELIMITER) { path += AL_FILE_DELIMITER; } return path; } inline void SearchPaths::addAppPaths(int argc, char * const argv[], bool recursive) { addAppPaths(recursive); if (argc > 0) { //char path[4096]; std::string filepath = stripFileName(argv[0]); mAppPath = filepath; addSearchPath(filepath, recursive); } } inline void SearchPaths::addAppPaths(bool recursive) { char cwd[4096]; if(getcwd(cwd, sizeof(cwd))){ mAppPath = std::string(cwd) + "/"; addSearchPath(mAppPath, recursive); } } inline void SearchPaths::addSearchPath(const std::string& src, bool recursive) { std::string path=conformPath(src); // check for duplicates std::list<searchpath>::iterator iter = mSearchPaths.begin(); while (iter != mSearchPaths.end()) { //printf("path %s\n", iter->first.c_str()); if (path == iter->first) { return; } iter++; } // printf("adding path %s\n", path.data()); mSearchPaths.push_front(searchpath(path, recursive)); } inline bool SearchPaths::fileExists(const std::string& path, const std::string& name) { struct stat stFileInfo; std::string filename(path+name); return (stat((path + name).c_str(),&stFileInfo) == 0); } } // al:: #endif <commit_msg>File: removed multi-line comments<commit_after>#ifndef INCLUDE_AL_FILE_HPP #define INCLUDE_AL_FILE_HPP #include <unistd.h> #include <stdio.h> #include <string> #include <sys/stat.h> #include <list> #include "allocore/system/al_Config.h" #ifdef AL_WIN32 #define AL_FILE_DELIMITER '\\' #else #define AL_FILE_DELIMITER '/' #endif #define AL_PATH_MAX (4096) namespace al{ /// Strips a qualified path to a file (src) into a path to the containing folder (dst) //void path2dir(char* dst, const char* src); /// a pair of path (folder/directory) and filename class FilePath { public: FilePath() {}; FilePath(std::string file, std::string path) : mPath(path), mFile(file) {} ///! this constructor takes a path to a file: FilePath(std::string fullpath); const std::string& file() const { return mFile; } const std::string& path() const { return mPath; } std::string filepath() const { return path()+file(); } FilePath& file(const std::string& v) { mFile=v; return *this; } FilePath& path(const std::string& v) { mPath=v; return *this; } protected: std::string mPath; std::string mFile; }; /// A handy way to manage several possible search paths class SearchPaths { public: SearchPaths() {} SearchPaths(int argc, char * const argv[], bool recursive=true) { addAppPaths(argc,argv,recursive); } ~SearchPaths() {} /// find a file in the searchpaths /// returns true if file found, and fills result with corresponding path & filename /// returns false if file not found FilePath find(const std::string& filename); /// add a path to search in; recursive searching is optional void addSearchPath(const std::string& path, bool recursive = true); /// adds best estimate of application launch paths (cwd etc.) /// can pass in argv from the main() function if desired. void addAppPaths(int argc, char * const argv[], bool recursive = true); void addAppPaths(bool recursive = true); const std::string& appPath() const { return mAppPath; } /// todo? //void addResourcePath(); // strips trailing filename from a path; e.g. /usr/bin/man -> /usr/bin/ static std::string stripFileName(const std::string& src); // ensure path ends with the proper delimiter static std::string conformPath(const std::string& src); // does a file at the given filepath exist? static bool fileExists(const std::string& name, const std::string& path); protected: typedef std::pair<std::string, bool> searchpath; std::list<searchpath> mSearchPaths; std::string mAppPath; }; /// File class File{ public: /// @param[in] path path of file /// @param[in] mode i/o mode w, r, wb, rb /// @param[in] open whether to open the file File(const std::string& path, const std::string& mode="r", bool open=false); File(const FilePath& path, const std::string& mode="r", bool open=false); ~File(); void close(); ///< Close file bool open(); ///< Open file with specified i/o mode File& mode(const std::string& v){ mMode=v; return *this; } File& path(const std::string& v){ mPath=v; return *this; } /// Write memory elements to file int write(const std::string& v){ return write(v.data(), 1, v.length()); } int write(const void * v, int itemSizeInBytes, int items=1){ int itemsWritten = fwrite(v, itemSizeInBytes, items, mFP); mSizeBytes += itemsWritten * itemSizeInBytes; return itemsWritten; } /// Read memory elements from file int read(void * v, int size, int items=1){ return fread(v, size, items, mFP); } /// Quick and dirty write memory to file static int write(const std::string& path, const void * v, int size, int items=1); /// Returns character string of file contents (read mode only) const char * readAll(); /// Returns whether file is open bool opened() const { return 0 != mFP; } /// Returns file i/o mode string const std::string& mode() const { return mMode; } /// Returns path string const std::string& path() const { return mPath; } /// Returns size, in bytes, of file contents int size() const { return mSizeBytes; } /// Returns whether file exists static bool exists(const std::string& path); /// Return modification time of file (or 0 on failure) as number of seconds since 00:00:00 january 1, 1970 UTC al_sec modified() const; /// Return last access time of file (or 0 on failure) as number of seconds since 00:00:00 january 1, 1970 UTC al_sec accessed() const; /// Return creation time of file (or 0 on failure) as number of seconds since 00:00:00 january 1, 1970 UTC al_sec created() const; /// Return size file (or 0 on failure) size_t sizeFile() const; /// Return space used on disk of file (or 0 on failure) size_t storage() const; FILE * filePointer() { return mFP; } static al_sec modified(std::string path) { File f(path); return f.modified(); } static al_sec accessed(std::string path) { File f(path); return f.accessed(); } static al_sec created(std::string path) { File f(path); return f.created(); } static size_t sizeFile(std::string path) { File f(path); return f.sizeFile(); } static size_t storage(std::string path) { File f(path); return f.storage(); } protected: class Impl; Impl * mImpl; std::string mPath; std::string mMode; char * mContent; int mSizeBytes; FILE * mFP; void freeContent(); void allocContent(int n); void getSize(); }; //// INLINE IMPLEMENTATION //// inline std::string SearchPaths::stripFileName(const std::string& src) { std::string filepath(src); size_t pos = filepath.find_last_of(AL_FILE_DELIMITER); if (pos !=std::string::npos) { filepath.erase(pos+1); } return filepath; } inline std::string SearchPaths::conformPath(const std::string& src) { std::string path(src); // paths should end with a delimiter: if (path[path.size()-1] != AL_FILE_DELIMITER) { path += AL_FILE_DELIMITER; } return path; } inline void SearchPaths::addAppPaths(int argc, char * const argv[], bool recursive) { addAppPaths(recursive); if (argc > 0) { //char path[4096]; std::string filepath = stripFileName(argv[0]); mAppPath = filepath; addSearchPath(filepath, recursive); } } inline void SearchPaths::addAppPaths(bool recursive) { char cwd[4096]; if(getcwd(cwd, sizeof(cwd))){ mAppPath = std::string(cwd) + "/"; addSearchPath(mAppPath, recursive); } } inline void SearchPaths::addSearchPath(const std::string& src, bool recursive) { std::string path=conformPath(src); // check for duplicates std::list<searchpath>::iterator iter = mSearchPaths.begin(); while (iter != mSearchPaths.end()) { //printf("path %s\n", iter->first.c_str()); if (path == iter->first) { return; } iter++; } // printf("adding path %s\n", path.data()); mSearchPaths.push_front(searchpath(path, recursive)); } inline bool SearchPaths::fileExists(const std::string& path, const std::string& name) { struct stat stFileInfo; std::string filename(path+name); return (stat((path + name).c_str(),&stFileInfo) == 0); } } // al:: #endif <|endoftext|>
<commit_before>#include "stdafx.h" #include "GameTile.h" #include "lodepng.h" #include "VoxelDrawSystem.h" #include "GL3DProgram.h" #include "GLTerrainProgram.h" #include "TerrainChunk.h" #include "TerrainChunkRenderer.h" #include "BaseFrame.h" #define CHUNK_COUNT ((TILE_SIZE/CHUNK_SIZE)*(TILE_SIZE/CHUNK_SIZE)) GameTile::GameTile() { Cells = new TileCell[TILE_SIZE*TILE_SIZE]; chunks = new TerrainChunk*[CHUNK_COUNT]; memset(chunks,0,CHUNK_COUNT*sizeof(TerrainChunk*)); UseByDate = numeric_limits<double>::max(); } GameTile::~GameTile() { delete [] Cells; delete [] chunks; } GameTile * GameTile::CreateGameTile(int x, int y) { GameTile * newTile = new GameTile(); newTile->tile_x = x; newTile->tile_y = y; return newTile; } GameTile * GameTile::CreatePlaceholderTile(int x, int y) { GameTile * newTile = new GameTile(); //Because you are a placeholder tiles you must prematurely trash the internal arrays delete [] newTile->Cells; //Clean up the pointers because delete[] NULL is safe newTile->Cells = NULL; newTile->tile_x = x; newTile->tile_y = y; return newTile; } //Load a game tile from disk GameTile * GameTile::LoadTileFromDisk(string tileImagePath) { unsigned int width; unsigned int height; vector<unsigned char> tileData; cout << "Starting load of tile \"" << tileImagePath << "\"\n"; //First load the tile map data from the image if (lodepng::decode(tileData,width,height,tileImagePath)) { cout << "\tImage load failed.\n"; //Error return NULL; } _ASSERTE(width==TILE_SIZE); _ASSERTE(height==TILE_SIZE); cout << "\tLoaded image file, now converting to game tile data.\n"; GameTile * tile = new GameTile(); tile->readImageData(tileData); return tile; } //Patch edge heights to be realistic values void GameTile::PatchStackEdges(TileCell * cellList, int cellWidth) { //Patch edge stack heights to be 2 (3 height) to cover most holes for (int i = 0; i < cellWidth; i++) { cellList[i].stackHeight = 1; cellList[i+(cellWidth-1)*cellWidth].stackHeight = 1; } for (int i = 0; i < cellWidth; i++) { cellList[i*cellWidth + 0].stackHeight = 1; cellList[i*cellWidth + cellWidth - 1].stackHeight = 1; } } void GameTile::readImageData(const vector<unsigned char> & imageData) { _ASSERTE(imageData.size() == (TILE_SIZE*TILE_SIZE*4)); for (unsigned int i = 0; i < imageData.size(); i+= 4) { //Load every RGBA pixel into a tile cell Cells[i/4].height = imageData[i+0]; Cells[i/4].materialId = imageData[i+1]; //Stack height must be calculated separately Cells[i/4].stackHeight = 0; Cells[i/4].cellHealth = imageData[i+2]; Cells[i/4].cellMaxHealth = Cells[i/4].cellHealth; } UpdateTileSection(0,0,TILE_SIZE,TILE_SIZE); } //Load a game tile from memory //pending GameTile * GameTile::LoadCompressedTileFromMemory(const vector<unsigned char> & tileData) { unsigned int width; unsigned int height; vector<unsigned char> imageData; cout << "Starting load of tile from memory\n"; //First load the tile map data from the image if (lodepng::decode(imageData,width,height,tileData)) { cout << "\tImage load failed.\n"; //Error return NULL; } _ASSERTE(width==TILE_SIZE); _ASSERTE(height==TILE_SIZE); cout << "\tLoaded image file, now converting to game tile data.\n"; GameTile * tile = new GameTile(); tile->readImageData(imageData); return tile; } void GameTile::LoadTileFromMemoryIntoExisting(const vector<unsigned char> & tileData, GameTile * newTile) { newTile->readImageData(tileData); } //Recalculate stack heights for the given region of tile cells void GameTile::CalculateStackSizes(TileCell * cells, unsigned int width, unsigned int rx, unsigned int ry, unsigned int tox, unsigned int toy) { for (unsigned int y = ry; y < toy; y++) { for (unsigned int x = rx; x < tox; x++) { unsigned char lowestHeight; unsigned char checkHeight; //Your stack size is the stack necessary to //cover up the hole between you and your lowest neighboring voxel //so first find the lowest neighboring voxel lowestHeight = cells[y*(int)width + (x + 1)].height; if ((checkHeight = cells[y*(int)width + (x - 1)].height) < lowestHeight) lowestHeight = checkHeight; if ((checkHeight = cells[(y + 1)*(int)width + x].height) < lowestHeight) lowestHeight = checkHeight; if ((checkHeight = cells[(y - 1)*(int)width + x].height) < lowestHeight) lowestHeight = checkHeight; //Now determine the stack height based off of the lowest height around you unsigned char myHeight = cells[y*(int)width+x].height; if (lowestHeight < myHeight) cells[y*(int)width+x].stackHeight = myHeight-lowestHeight; else cells[y*(int)width+x].stackHeight = 0; } } } //Recalculate stack heights for the given region of tile cells void GameTile::UpdateTileSection(unsigned int rx, unsigned int ry, unsigned int tox, unsigned int toy) { bool doCalc = false; //If the full tile is being updated apply stack edge patching if ((rx == 0) && (ry == 0) && (tox == TILE_SIZE) && (toy == TILE_SIZE)) { PatchStackEdges(Cells,TILE_SIZE); doCalc = true; } //Calculate the finest grain stack sizes CalculateStackSizes(Cells,TILE_SIZE,rx+1,ry+1,tox-1,toy-1); if (chunks[0] == NULL) { //Generate all the chunks for this tile for (int y = 0; y < TILE_SIZE; y+= CHUNK_SIZE) for (int x = 0; x < TILE_SIZE; x+= CHUNK_SIZE) { int chunkx = x/CHUNK_SIZE; int chunky = y/CHUNK_SIZE; chunks[chunky*(TILE_SIZE/CHUNK_SIZE)+chunkx] = new TerrainChunk(this,x,y); } } else { //Reconstruct the chunks which are in the region specified //Chunk-align the tox,toy rx -= rx % CHUNK_SIZE; ry -= ry % CHUNK_SIZE; for (int y = ry; y < toy; y+= CHUNK_SIZE) { for (int x = rx;x < tox; x+= CHUNK_SIZE) { //Find the chunk the given x,y is in int chunkx = x/CHUNK_SIZE; int chunky = y/CHUNK_SIZE; //Rebuild that chunk chunks[chunky*(TILE_SIZE/CHUNK_SIZE)+chunkx]->Reconstruct(); } } } } TileCell * GameTile::GetTileCell(vec2 pos) { _ASSERTE((pos.x >= 0) && (pos.y >= 0)); _ASSERTE((pos.x < (float)TILE_SIZE) && (pos.y < (float)TILE_SIZE)); //First lookup which tile the position is in int tileX = (int)floor(pos.x); int tileY = (int)floor(pos.y); return &Cells[tileY*TILE_SIZE+tileX]; } //Carves a square crater from fx,fy to tox,toy to depth "depth" and adds all removed voxels //to the removedVoxels value void GameTile::Crater(IntRect craterRegion, int craterBottomZ, float damageDone, vec3 epicenter, vector<vec4> & removedVoxels) { _ASSERTE((craterRegion.StartX >= 0) && (craterRegion.StartY >= 0)); _ASSERTE((craterRegion.StartX < (float)TILE_SIZE) && (craterRegion.StartY < (float)TILE_SIZE)); _ASSERTE((craterRegion.StartX <= craterRegion.EndX) && (craterRegion.StartY <= craterRegion.EndY)); _ASSERTE(craterBottomZ > 0); for (int x = craterRegion.StartX; x <= craterRegion.EndX; x++) { for (int y = craterRegion.StartY; y <= craterRegion.EndY; y++) { TileCell& cell = Cells[y*TILE_SIZE+x]; int height = cell.height; int heightDiff = height-craterBottomZ+1; //Skip where the terrain does not intersect the crater if (heightDiff < 0) continue; //Damage the voxel //determine damage scaled with distance from the epicenter float damageScaler = ((craterRegion.EndX - craterRegion.StartX)*1.5 - glm::distance(vec2(x,y),vec2(epicenter))); damageScaler = max(0.0f,min(damageScaler,1.0f)); float damage = damageDone*damageScaler; float originalLife = cell.cellHealth; float newLife = floor(originalLife-damage); //Only do partial destruction if the voxel isn't dead if (newLife > 0) { cell.cellHealth = (int)newLife; continue; } //Keep track of all removed voxels while (heightDiff >= 0) { removedVoxels.push_back(vec4(x+(tile_x*TILE_SIZE),y+(tile_y*TILE_SIZE),height,cell.materialId)); heightDiff--; height--; } //Expose a half health surface cell.cellHealth = (int)cell.cellMaxHealth/2; //Alter the height to create the crater Cells[y*TILE_SIZE+x].height = craterBottomZ-1; } } //Alter the values to be large enough for stack calculation craterRegion.StartX-=2; craterRegion.StartY-=2; craterRegion.EndX+=4; craterRegion.EndY+=4; //Limit the values to valid ranges if (craterRegion.StartX < 0) craterRegion.StartX = 0; if (craterRegion.StartY < 0) craterRegion.StartY = 0; if (craterRegion.EndX > TILE_SIZE-1) craterRegion.EndX = TILE_SIZE-1; if (craterRegion.EndY > TILE_SIZE-1) craterRegion.EndY = TILE_SIZE-1; //Rebuild the stack heights in this region UpdateTileSection(craterRegion.StartX,craterRegion.StartY,craterRegion.EndX,craterRegion.EndY); } //Recode the tile to uncompressed png data vector<unsigned char> GameTile::recode() { //Convert the tile to RGBA pixel data vector<unsigned char> rawTileData(TILE_SIZE*TILE_SIZE*4); for (int y = 0; y < TILE_SIZE; y++) { for (int x = 0; x < TILE_SIZE; x++) { int cellIndex = (x+y*TILE_SIZE); rawTileData[cellIndex*4+0] = Cells[cellIndex].height; rawTileData[cellIndex*4+1] = Cells[cellIndex].materialId; rawTileData[cellIndex*4+2] = 0; rawTileData[cellIndex*4+3] = 0; } } return rawTileData; } //Save the tile to disk void GameTile::SaveTile(string saveName) { vector<unsigned char> input(recode()); unsigned int error = lodepng::encode(saveName.c_str(),input,TILE_SIZE,TILE_SIZE); if (error) { cout << "Failed to save tile. Lodepng error " << error << ": "<< lodepng_error_text(error) << "\n"; } } //Save the tile to memory vector<unsigned char> GameTile::SaveTileToMemory() { vector<unsigned char> input(recode()); vector<unsigned char> output; unsigned int error = lodepng::encode(output,input,TILE_SIZE,TILE_SIZE); if (error) { cout << "Failed to save tile. Lodepng error " << error << ": "<< lodepng_error_text(error) << "\n"; return vector<unsigned char>(); } return output; } //Render the given region using the specified detail level //the rect should be tile-relative coordinates void GameTile::Render(GL3DProgram * voxelShader, GLTerrainProgram * terrainShader, TerrainChunkRenderer * terrainRenderer, VoxelDrawSystem * cellDrawSystem, IntRect drawRegion, int & voxelCount) { TileCell * cells; _ASSERTE(TILE_SIZE >= drawRegion.EndX); _ASSERTE(TILE_SIZE >= drawRegion.EndY); terrainShader->UseProgram(); //offset rendering for tile location terrainShader->Model.PushMatrix(); terrainShader->Model.Translate(vec3(tile_x * TILE_SIZE, tile_y * TILE_SIZE, 0)); //Scale for level of detail requested terrainShader->Model.Apply(); //Draw the tiles in the region specified for (int ry = drawRegion.StartY; ry < drawRegion.EndY; ry+= CHUNK_SIZE) { for (int rx = drawRegion.StartX;rx < drawRegion.EndX; rx+= CHUNK_SIZE) { //Find the chunk the given x,y is in int chunkx = rx/CHUNK_SIZE; int chunky = ry/CHUNK_SIZE; //Draw that chunk TerrainChunk * chunk = chunks[chunky*(TILE_SIZE/CHUNK_SIZE)+chunkx]; terrainRenderer->RenderTerrainChunk(vec2(tile_x,tile_y)*(float)TILE_SIZE,chunk,terrainShader); voxelCount += chunk->VoxelCount; } } voxelShader->UseProgram(); voxelShader->Model.PushMatrix(); voxelShader->Model.Translate(vec3(tile_x * TILE_SIZE, tile_y * TILE_SIZE, 0)); //Next check for any structures on this tile which intersect the view rectangle for (auto structure : Structures) { int structx = (int)structure.Position.x; int structy = (int)structure.Position.y; int structex = structx + (int)structure.Extents.x; int structey = structy + (int)structure.Extents.y; //Now see if the struct rectangle intersects the draw rectangle if (((drawRegion.StartX < structx) && (drawRegion.EndX > structex)) && ((drawRegion.StartY < structy) && (drawRegion.EndY > structey))) { //Time to draw the structure //Push the structure's position if (structure.Cells.size() > 0){ voxelShader->Model.PushMatrix(); voxelShader->Model.Translate(structure.Position); voxelShader->Model.Apply(); //Track voxels drawn for debug //Todo: fix broken voxel count //voxelCount += structure.Cells.size(); //Start the draw cycle cellDrawSystem->startDraw(voxelShader); StructureCell * celliterator = &structure.Cells.front(); unsigned int endCount = structure.Cells.size(); //Push all the cells for (unsigned int i = 0; i < endCount; i++, celliterator++) cellDrawSystem->pushVoxel(voxelShader, celliterator->pos, celliterator->material); //Finish drawing and remove the structure matrix cellDrawSystem->finishDraw(voxelShader); voxelShader->Model.PopMatrix(); } } } voxelShader->Model.PopMatrix(); //Undo tile translation terrainShader->Model.PopMatrix(); }<commit_msg>Made some optimizations to crater and removed unused building drawing code<commit_after>#include "stdafx.h" #include "GameTile.h" #include "lodepng.h" #include "VoxelDrawSystem.h" #include "GL3DProgram.h" #include "GLTerrainProgram.h" #include "TerrainChunk.h" #include "TerrainChunkRenderer.h" #include "BaseFrame.h" #define CHUNK_COUNT ((TILE_SIZE/CHUNK_SIZE)*(TILE_SIZE/CHUNK_SIZE)) GameTile::GameTile() { Cells = new TileCell[TILE_SIZE*TILE_SIZE]; chunks = new TerrainChunk*[CHUNK_COUNT]; memset(chunks,0,CHUNK_COUNT*sizeof(TerrainChunk*)); UseByDate = numeric_limits<double>::max(); } GameTile::~GameTile() { delete [] Cells; delete [] chunks; } GameTile * GameTile::CreateGameTile(int x, int y) { GameTile * newTile = new GameTile(); newTile->tile_x = x; newTile->tile_y = y; return newTile; } GameTile * GameTile::CreatePlaceholderTile(int x, int y) { GameTile * newTile = new GameTile(); //Because you are a placeholder tiles you must prematurely trash the internal arrays delete [] newTile->Cells; //Clean up the pointers because delete[] NULL is safe newTile->Cells = NULL; newTile->tile_x = x; newTile->tile_y = y; return newTile; } //Load a game tile from disk GameTile * GameTile::LoadTileFromDisk(string tileImagePath) { unsigned int width; unsigned int height; vector<unsigned char> tileData; cout << "Starting load of tile \"" << tileImagePath << "\"\n"; //First load the tile map data from the image if (lodepng::decode(tileData,width,height,tileImagePath)) { cout << "\tImage load failed.\n"; //Error return NULL; } _ASSERTE(width==TILE_SIZE); _ASSERTE(height==TILE_SIZE); cout << "\tLoaded image file, now converting to game tile data.\n"; GameTile * tile = new GameTile(); tile->readImageData(tileData); return tile; } //Patch edge heights to be realistic values void GameTile::PatchStackEdges(TileCell * cellList, int cellWidth) { //Patch edge stack heights to be 2 (3 height) to cover most holes for (int i = 0; i < cellWidth; i++) { cellList[i].stackHeight = 1; cellList[i+(cellWidth-1)*cellWidth].stackHeight = 1; } for (int i = 0; i < cellWidth; i++) { cellList[i*cellWidth + 0].stackHeight = 1; cellList[i*cellWidth + cellWidth - 1].stackHeight = 1; } } void GameTile::readImageData(const vector<unsigned char> & imageData) { _ASSERTE(imageData.size() == (TILE_SIZE*TILE_SIZE*4)); for (unsigned int i = 0; i < imageData.size(); i+= 4) { //Load every RGBA pixel into a tile cell Cells[i/4].height = imageData[i+0]; Cells[i/4].materialId = imageData[i+1]; //Stack height must be calculated separately Cells[i/4].stackHeight = 0; Cells[i/4].cellHealth = imageData[i+2]; Cells[i/4].cellMaxHealth = Cells[i/4].cellHealth; } UpdateTileSection(0,0,TILE_SIZE,TILE_SIZE); } //Load a game tile from memory //pending GameTile * GameTile::LoadCompressedTileFromMemory(const vector<unsigned char> & tileData) { unsigned int width; unsigned int height; vector<unsigned char> imageData; cout << "Starting load of tile from memory\n"; //First load the tile map data from the image if (lodepng::decode(imageData,width,height,tileData)) { cout << "\tImage load failed.\n"; //Error return NULL; } _ASSERTE(width==TILE_SIZE); _ASSERTE(height==TILE_SIZE); cout << "\tLoaded image file, now converting to game tile data.\n"; GameTile * tile = new GameTile(); tile->readImageData(imageData); return tile; } void GameTile::LoadTileFromMemoryIntoExisting(const vector<unsigned char> & tileData, GameTile * newTile) { newTile->readImageData(tileData); } //Recalculate stack heights for the given region of tile cells void GameTile::CalculateStackSizes(TileCell * cells, unsigned int width, unsigned int rx, unsigned int ry, unsigned int tox, unsigned int toy) { for (unsigned int y = ry; y < toy; y++) { for (unsigned int x = rx; x < tox; x++) { unsigned char lowestHeight; unsigned char checkHeight; //Your stack size is the stack necessary to //cover up the hole between you and your lowest neighboring voxel //so first find the lowest neighboring voxel lowestHeight = cells[y*(int)width + (x + 1)].height; if ((checkHeight = cells[y*(int)width + (x - 1)].height) < lowestHeight) lowestHeight = checkHeight; if ((checkHeight = cells[(y + 1)*(int)width + x].height) < lowestHeight) lowestHeight = checkHeight; if ((checkHeight = cells[(y - 1)*(int)width + x].height) < lowestHeight) lowestHeight = checkHeight; //Now determine the stack height based off of the lowest height around you unsigned char myHeight = cells[y*(int)width+x].height; if (lowestHeight < myHeight) cells[y*(int)width+x].stackHeight = myHeight-lowestHeight; else cells[y*(int)width+x].stackHeight = 0; } } } //Recalculate stack heights for the given region of tile cells void GameTile::UpdateTileSection(unsigned int rx, unsigned int ry, unsigned int tox, unsigned int toy) { bool doCalc = false; //If the full tile is being updated apply stack edge patching if ((rx == 0) && (ry == 0) && (tox == TILE_SIZE) && (toy == TILE_SIZE)) { PatchStackEdges(Cells,TILE_SIZE); doCalc = true; } //Calculate the finest grain stack sizes CalculateStackSizes(Cells,TILE_SIZE,rx+1,ry+1,tox-1,toy-1); if (chunks[0] == NULL) { //Generate all the chunks for this tile for (int y = 0; y < TILE_SIZE; y+= CHUNK_SIZE) for (int x = 0; x < TILE_SIZE; x+= CHUNK_SIZE) { int chunkx = x/CHUNK_SIZE; int chunky = y/CHUNK_SIZE; chunks[chunky*(TILE_SIZE/CHUNK_SIZE)+chunkx] = new TerrainChunk(this,x,y); } } else { //Reconstruct the chunks which are in the region specified //Chunk-align the tox,toy rx -= rx % CHUNK_SIZE; ry -= ry % CHUNK_SIZE; for (int y = ry; y < toy; y+= CHUNK_SIZE) { for (int x = rx;x < tox; x+= CHUNK_SIZE) { //Find the chunk the given x,y is in int chunkx = x/CHUNK_SIZE; int chunky = y/CHUNK_SIZE; //Rebuild that chunk chunks[chunky*(TILE_SIZE/CHUNK_SIZE)+chunkx]->Reconstruct(); } } } } TileCell * GameTile::GetTileCell(vec2 pos) { _ASSERTE((pos.x >= 0) && (pos.y >= 0)); _ASSERTE((pos.x < (float)TILE_SIZE) && (pos.y < (float)TILE_SIZE)); //First lookup which tile the position is in int tileX = (int)floor(pos.x); int tileY = (int)floor(pos.y); return &Cells[tileY*TILE_SIZE+tileX]; } //Carves a square crater from fx,fy to tox,toy to depth "depth" and adds all removed voxels //to the removedVoxels value void GameTile::Crater(IntRect craterRegion, int craterBottomZ, float damageDone, vec3 epicenter, vector<vec4> & removedVoxels) { _ASSERTE((craterRegion.StartX >= 0) && (craterRegion.StartY >= 0)); _ASSERTE((craterRegion.StartX < (float)TILE_SIZE) && (craterRegion.StartY < (float)TILE_SIZE)); _ASSERTE((craterRegion.StartX <= craterRegion.EndX) && (craterRegion.StartY <= craterRegion.EndY)); _ASSERTE(craterBottomZ > 0); int cellsRemoved = 0; for (int x = craterRegion.StartX; x <= craterRegion.EndX; x++) { for (int y = craterRegion.StartY; y <= craterRegion.EndY; y++) { TileCell& cell = Cells[y*TILE_SIZE+x]; int height = cell.height; int heightDiff = height-craterBottomZ+1; //Skip where the terrain does not intersect the crater if (heightDiff < 0) continue; //Damage the voxel //determine damage scaled with distance from the epicenter float damageScaler = ((craterRegion.EndX - craterRegion.StartX)*1.5 - glm::distance(vec2(x,y),vec2(epicenter))); damageScaler = max(0.0f,min(damageScaler,1.0f)); float damage = damageDone*damageScaler; float originalLife = cell.cellHealth; float newLife = floor(originalLife-damage); //Only do partial destruction if the voxel isn't dead if (newLife > 0) { cell.cellHealth = (int)newLife; continue; } //Keep track of all removed voxels while (heightDiff >= 0) { removedVoxels.push_back(vec4(x+(tile_x*TILE_SIZE),y+(tile_y*TILE_SIZE),height,cell.materialId)); cellsRemoved++; heightDiff--; height--; } //Expose a half health surface cell.cellHealth = (int)cell.cellMaxHealth/2; //Alter the height to create the crater Cells[y*TILE_SIZE+x].height = craterBottomZ-1; } } //Update nothing if no cells changed if (cellsRemoved <= 0) return; //Alter the values to be large enough for stack calculation craterRegion.StartX-=2; craterRegion.StartY-=2; craterRegion.EndX+=4; craterRegion.EndY+=4; //Limit the values to valid ranges if (craterRegion.StartX < 0) craterRegion.StartX = 0; if (craterRegion.StartY < 0) craterRegion.StartY = 0; if (craterRegion.EndX > TILE_SIZE-1) craterRegion.EndX = TILE_SIZE-1; if (craterRegion.EndY > TILE_SIZE-1) craterRegion.EndY = TILE_SIZE-1; //Rebuild the stack heights in this region UpdateTileSection(craterRegion.StartX,craterRegion.StartY,craterRegion.EndX,craterRegion.EndY); } //Recode the tile to uncompressed png data vector<unsigned char> GameTile::recode() { //Convert the tile to RGBA pixel data vector<unsigned char> rawTileData(TILE_SIZE*TILE_SIZE*4); for (int y = 0; y < TILE_SIZE; y++) { for (int x = 0; x < TILE_SIZE; x++) { int cellIndex = (x+y*TILE_SIZE); rawTileData[cellIndex*4+0] = Cells[cellIndex].height; rawTileData[cellIndex*4+1] = Cells[cellIndex].materialId; rawTileData[cellIndex*4+2] = 0; rawTileData[cellIndex*4+3] = 0; } } return rawTileData; } //Save the tile to disk void GameTile::SaveTile(string saveName) { vector<unsigned char> input(recode()); unsigned int error = lodepng::encode(saveName.c_str(),input,TILE_SIZE,TILE_SIZE); if (error) { cout << "Failed to save tile. Lodepng error " << error << ": "<< lodepng_error_text(error) << "\n"; } } //Save the tile to memory vector<unsigned char> GameTile::SaveTileToMemory() { vector<unsigned char> input(recode()); vector<unsigned char> output; unsigned int error = lodepng::encode(output,input,TILE_SIZE,TILE_SIZE); if (error) { cout << "Failed to save tile. Lodepng error " << error << ": "<< lodepng_error_text(error) << "\n"; return vector<unsigned char>(); } return output; } //Render the given region using the specified detail level //the rect should be tile-relative coordinates void GameTile::Render(GL3DProgram * voxelShader, GLTerrainProgram * terrainShader, TerrainChunkRenderer * terrainRenderer, VoxelDrawSystem * cellDrawSystem, IntRect drawRegion, int & voxelCount) { TileCell * cells; _ASSERTE(TILE_SIZE >= drawRegion.EndX); _ASSERTE(TILE_SIZE >= drawRegion.EndY); terrainShader->UseProgram(); //offset rendering for tile location terrainShader->Model.PushMatrix(); terrainShader->Model.Translate(vec3(tile_x * TILE_SIZE, tile_y * TILE_SIZE, 0)); //Scale for level of detail requested terrainShader->Model.Apply(); //Draw the tiles in the region specified for (int ry = drawRegion.StartY; ry < drawRegion.EndY; ry+= CHUNK_SIZE) { for (int rx = drawRegion.StartX;rx < drawRegion.EndX; rx+= CHUNK_SIZE) { //Find the chunk the given x,y is in int chunkx = rx/CHUNK_SIZE; int chunky = ry/CHUNK_SIZE; //Draw that chunk TerrainChunk * chunk = chunks[chunky*(TILE_SIZE/CHUNK_SIZE)+chunkx]; terrainRenderer->RenderTerrainChunk(vec2(tile_x,tile_y)*(float)TILE_SIZE,chunk,terrainShader); voxelCount += chunk->VoxelCount; } } //Undo tile translation terrainShader->Model.PopMatrix(); }<|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ THIS_CLASS::THIS_CLASS(DocumentImpl *ownerDoc) : PARENT_CLASS(ownerDoc) { this->ownerDocument = ownerDoc; this->firstChild = null; fChanges = 0; }; // This only makes a shallow copy, cloneChildren must also be called for a // deep clone THIS_CLASS::THIS_CLASS(const THIS_CLASS &other) : PARENT_CLASS(other) { this->ownerDocument = other.ownerDocument; // Need to break the association w/ original kids this->firstChild = null; fChanges = 0; }; void THIS_CLASS::cloneChildren(const NodeImpl &other) { // for (NodeImpl *mykid = other.getFirstChild(); for (NodeImpl *mykid = ((NodeImpl&)other).getFirstChild(); mykid != null; mykid = mykid->getNextSibling()) { this->appendChild(mykid->cloneNode(true)); } } DocumentImpl * THIS_CLASS::getOwnerDocument() { return ownerDocument; } // unlike getOwnerDocument this is not overriden by DocumentImpl to return null DocumentImpl * THIS_CLASS::getDocument() { return ownerDocument; } void THIS_CLASS::setOwnerDocument(DocumentImpl *doc) { ownerDocument = doc; for (NodeImpl *child = firstChild; child != null; child = child->getNextSibling()) { child->setOwnerDocument(doc); } } void THIS_CLASS::changed() { ++fChanges; NodeImpl *parentNode = getParentNode(); if (parentNode != null) { parentNode->changed(); } }; int THIS_CLASS::changes() { return fChanges; }; NodeListImpl *THIS_CLASS::getChildNodes() { return this; }; NodeImpl * THIS_CLASS::getFirstChild() { return firstChild; }; NodeImpl * THIS_CLASS::getLastChild() { return lastChild(); }; ChildNode * THIS_CLASS::lastChild() { // last child is stored as the previous sibling of first child return firstChild != null ? firstChild->previousSibling : null; }; void THIS_CLASS::lastChild(ChildNode *node) { // store lastChild as previous sibling of first child if (firstChild != null) { firstChild->previousSibling = node; } } unsigned int THIS_CLASS::getLength() { unsigned int count = 0; ChildNode *node = firstChild; while(node != null) { ++count; node = node->nextSibling; } return count; }; bool THIS_CLASS::hasChildNodes() { return firstChild!=null; }; NodeImpl *THIS_CLASS::insertBefore(NodeImpl *newChild, NodeImpl *refChild) { if (readOnly()) throw DOM_DOMException( DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null); if (newChild->getOwnerDocument() != ownerDocument) throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR, null); // Convert to internal type, to avoid repeated casting ChildNode * newInternal= (ChildNode *)newChild; // Prevent cycles in the tree bool treeSafe=true; for(NodeImpl *a=this->getParentNode(); treeSafe && a!=null; a=a->getParentNode()) treeSafe=(newInternal!=a); if(!treeSafe) throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,null); // refChild must in fact be a child of this node (or null) if (refChild!=null && refChild->getParentNode() != this) throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR,null); if (newInternal->isDocumentFragmentImpl()) { // SLOW BUT SAFE: We could insert the whole subtree without // juggling so many next/previous pointers. (Wipe out the // parent's child-list, patch the parent pointers, set the // ends of the list.) But we know some subclasses have special- // case behavior they add to insertBefore(), so we don't risk it. // This approch also takes fewer bytecodes. // NOTE: If one of the children is not a legal child of this // node, throw HIERARCHY_REQUEST_ERR before _any_ of the children // have been transferred. (Alternative behaviors would be to // reparent up to the first failure point or reparent all those // which are acceptable to the target node, neither of which is // as robust. PR-DOM-0818 isn't entirely clear on which it // recommends????? // No need to check kids for right-document; if they weren't, // they wouldn't be kids of that DocFrag. for(NodeImpl *kid=newInternal->getFirstChild(); // Prescan kid!=null; kid=kid->getNextSibling()) { if (!DocumentImpl::isKidOK(this, kid)) throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,null); } while(newInternal->hasChildNodes()) // Move insertBefore(newInternal->getFirstChild(),refChild); } else if (!DocumentImpl::isKidOK(this, newInternal)) throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,null); else { // Convert to internal type, to avoid repeated casting ChildNode *refInternal = (ChildNode *)refChild; NodeImpl *oldparent=newInternal->getParentNode(); if(oldparent!=null) oldparent->removeChild(newInternal); ChildNode *prev; // Find the node we're inserting after, if any (null if // inserting to head of list) prev = (refInternal == null) ? lastChild() : refInternal->previousSibling; // Attach up newInternal->ownerNode = this; newInternal->owned(true); // Attach after newInternal->previousSibling=prev; if (refInternal == firstChild) { firstChild = newInternal; newInternal->firstChild(true); } else { prev->nextSibling = newInternal; } // Attach before newInternal->nextSibling = refInternal; if(refInternal == null) { // store lastChild as previous sibling of first child firstChild->previousSibling = newInternal; } else { refInternal->previousSibling = newInternal; refInternal->firstChild(true); } } changed(); return newInternal; }; NodeImpl *THIS_CLASS::item(unsigned int index) { ChildNode *node = firstChild; for(unsigned int i=0; i<index && node!=null; ++i) node = node->nextSibling; return node; }; NodeImpl *THIS_CLASS::removeChild(NodeImpl *oldChild) { if (readOnly()) throw DOM_DOMException( DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null); if (oldChild != null && oldChild->getParentNode() != this) throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null); ChildNode * oldInternal = (ChildNode *) oldChild; // Patch tree past oldChild ChildNode *prev = oldInternal->previousSibling; ChildNode *next = oldInternal->nextSibling; if (oldInternal != firstChild) prev->nextSibling = next; else { oldInternal->firstChild(false); firstChild = next; if (next != null) { next->firstChild(true); } } if (next != null) // oldInternal != lastChild next->previousSibling = prev; else { if (firstChild != null) { // store lastChild as previous sibling of first child firstChild->previousSibling = prev; } } // Remove oldChild's references to tree oldInternal->ownerNode = ownerDocument; oldInternal->owned(false); oldInternal->nextSibling = null; oldInternal->previousSibling = null; changed(); return oldInternal; }; NodeImpl *THIS_CLASS::replaceChild(NodeImpl *newChild, NodeImpl *oldChild) { insertBefore(newChild, oldChild); // changed() already done. return removeChild(oldChild); }; void THIS_CLASS::setReadOnly(bool readOnl, bool deep) { NodeImpl::setReadOnly(readOnl, deep); if (deep) // Recursively set kids for (ChildNode *mykid = firstChild; mykid != null; mykid = mykid->nextSibling) if(! (mykid->isEntityReference())) mykid->setReadOnly(readOnl,true); }; //Introduced in DOM Level 2 void THIS_CLASS::normalize() { ChildNode *kid, *next; for (kid = firstChild; kid != null; kid = next) { next = kid->nextSibling; // If kid and next are both Text nodes (but _not_ CDATASection, // which is a subclass of Text), they can be merged. if (next != null && kid->isTextImpl() && !(kid->isCDATASectionImpl()) && next->isTextImpl() && !(next->isCDATASectionImpl()) ) { ((TextImpl *) kid)->appendData(((TextImpl *) next)->getData()); removeChild(next); if (next->nodeRefCount == 0) deleteIf(next); next = kid; // Don't advance; there might be another. } // Otherwise it might be an Element, which is handled recursively else if (kid->isElementImpl()) kid->normalize(); }; // changed() will have occurred when the removeChild() was done, // so does not have to be reissued. }; <commit_msg>Fixed insertNode for assigning correct link to previous siblings and marking the correct head for first sibling.<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 1999-2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Id$ */ THIS_CLASS::THIS_CLASS(DocumentImpl *ownerDoc) : PARENT_CLASS(ownerDoc) { this->ownerDocument = ownerDoc; this->firstChild = null; fChanges = 0; }; // This only makes a shallow copy, cloneChildren must also be called for a // deep clone THIS_CLASS::THIS_CLASS(const THIS_CLASS &other) : PARENT_CLASS(other) { this->ownerDocument = other.ownerDocument; // Need to break the association w/ original kids this->firstChild = null; fChanges = 0; }; void THIS_CLASS::cloneChildren(const NodeImpl &other) { // for (NodeImpl *mykid = other.getFirstChild(); for (NodeImpl *mykid = ((NodeImpl&)other).getFirstChild(); mykid != null; mykid = mykid->getNextSibling()) { this->appendChild(mykid->cloneNode(true)); } } DocumentImpl * THIS_CLASS::getOwnerDocument() { return ownerDocument; } // unlike getOwnerDocument this is not overriden by DocumentImpl to return null DocumentImpl * THIS_CLASS::getDocument() { return ownerDocument; } void THIS_CLASS::setOwnerDocument(DocumentImpl *doc) { ownerDocument = doc; for (NodeImpl *child = firstChild; child != null; child = child->getNextSibling()) { child->setOwnerDocument(doc); } } void THIS_CLASS::changed() { ++fChanges; NodeImpl *parentNode = getParentNode(); if (parentNode != null) { parentNode->changed(); } }; int THIS_CLASS::changes() { return fChanges; }; NodeListImpl *THIS_CLASS::getChildNodes() { return this; }; NodeImpl * THIS_CLASS::getFirstChild() { return firstChild; }; NodeImpl * THIS_CLASS::getLastChild() { return lastChild(); }; ChildNode * THIS_CLASS::lastChild() { // last child is stored as the previous sibling of first child return firstChild != null ? firstChild->previousSibling : null; }; void THIS_CLASS::lastChild(ChildNode *node) { // store lastChild as previous sibling of first child if (firstChild != null) { firstChild->previousSibling = node; } } unsigned int THIS_CLASS::getLength() { unsigned int count = 0; ChildNode *node = firstChild; while(node != null) { ++count; node = node->nextSibling; } return count; }; bool THIS_CLASS::hasChildNodes() { return firstChild!=null; }; NodeImpl *THIS_CLASS::insertBefore(NodeImpl *newChild, NodeImpl *refChild) { if (readOnly()) throw DOM_DOMException( DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null); if (newChild->getOwnerDocument() != ownerDocument) throw DOM_DOMException(DOM_DOMException::WRONG_DOCUMENT_ERR, null); // Convert to internal type, to avoid repeated casting ChildNode * newInternal= (ChildNode *)newChild; // Prevent cycles in the tree bool treeSafe=true; for(NodeImpl *a=this->getParentNode(); treeSafe && a!=null; a=a->getParentNode()) treeSafe=(newInternal!=a); if(!treeSafe) throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,null); // refChild must in fact be a child of this node (or null) if (refChild!=null && refChild->getParentNode() != this) throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR,null); if (newInternal->isDocumentFragmentImpl()) { // SLOW BUT SAFE: We could insert the whole subtree without // juggling so many next/previous pointers. (Wipe out the // parent's child-list, patch the parent pointers, set the // ends of the list.) But we know some subclasses have special- // case behavior they add to insertBefore(), so we don't risk it. // This approch also takes fewer bytecodes. // NOTE: If one of the children is not a legal child of this // node, throw HIERARCHY_REQUEST_ERR before _any_ of the children // have been transferred. (Alternative behaviors would be to // reparent up to the first failure point or reparent all those // which are acceptable to the target node, neither of which is // as robust. PR-DOM-0818 isn't entirely clear on which it // recommends????? // No need to check kids for right-document; if they weren't, // they wouldn't be kids of that DocFrag. for(NodeImpl *kid=newInternal->getFirstChild(); // Prescan kid!=null; kid=kid->getNextSibling()) { if (!DocumentImpl::isKidOK(this, kid)) throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,null); } while(newInternal->hasChildNodes()) // Move insertBefore(newInternal->getFirstChild(),refChild); } else if (!DocumentImpl::isKidOK(this, newInternal)) throw DOM_DOMException(DOM_DOMException::HIERARCHY_REQUEST_ERR,null); else { // Convert to internal type, to avoid repeated casting ChildNode *refInternal = (ChildNode *)refChild; NodeImpl *oldparent=newInternal->getParentNode(); if(oldparent!=null) oldparent->removeChild(newInternal); ChildNode *prev; // Find the node we're inserting after, if any (null if // inserting to head of list) prev = (refInternal == null) ? lastChild() : refInternal->previousSibling; // Attach up newInternal->ownerNode = this; newInternal->owned(true); // Attach after newInternal->previousSibling=prev; if (refInternal == firstChild) { firstChild = newInternal; if (refInternal != null) refInternal->firstChild(false); newInternal->firstChild(true); } else { prev->nextSibling = newInternal; } // Attach before newInternal->nextSibling = refInternal; if(refInternal == null) { // store lastChild as previous sibling of first child firstChild->previousSibling = newInternal; } else { refInternal->previousSibling = newInternal; } } changed(); return newInternal; }; NodeImpl *THIS_CLASS::item(unsigned int index) { ChildNode *node = firstChild; for(unsigned int i=0; i<index && node!=null; ++i) node = node->nextSibling; return node; }; NodeImpl *THIS_CLASS::removeChild(NodeImpl *oldChild) { if (readOnly()) throw DOM_DOMException( DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR, null); if (oldChild != null && oldChild->getParentNode() != this) throw DOM_DOMException(DOM_DOMException::NOT_FOUND_ERR, null); ChildNode * oldInternal = (ChildNode *) oldChild; // Patch tree past oldChild ChildNode *prev = oldInternal->previousSibling; ChildNode *next = oldInternal->nextSibling; if (oldInternal != firstChild) prev->nextSibling = next; else { oldInternal->firstChild(false); firstChild = next; if (next != null) { next->firstChild(true); } } if (next != null) // oldInternal != lastChild next->previousSibling = prev; else { if (firstChild != null) { // store lastChild as previous sibling of first child firstChild->previousSibling = prev; } } // Remove oldChild's references to tree oldInternal->ownerNode = ownerDocument; oldInternal->owned(false); oldInternal->nextSibling = null; oldInternal->previousSibling = null; changed(); return oldInternal; }; NodeImpl *THIS_CLASS::replaceChild(NodeImpl *newChild, NodeImpl *oldChild) { insertBefore(newChild, oldChild); // changed() already done. return removeChild(oldChild); }; void THIS_CLASS::setReadOnly(bool readOnl, bool deep) { NodeImpl::setReadOnly(readOnl, deep); if (deep) // Recursively set kids for (ChildNode *mykid = firstChild; mykid != null; mykid = mykid->nextSibling) if(! (mykid->isEntityReference())) mykid->setReadOnly(readOnl,true); }; //Introduced in DOM Level 2 void THIS_CLASS::normalize() { ChildNode *kid, *next; for (kid = firstChild; kid != null; kid = next) { next = kid->nextSibling; // If kid and next are both Text nodes (but _not_ CDATASection, // which is a subclass of Text), they can be merged. if (next != null && kid->isTextImpl() && !(kid->isCDATASectionImpl()) && next->isTextImpl() && !(next->isCDATASectionImpl()) ) { ((TextImpl *) kid)->appendData(((TextImpl *) next)->getData()); removeChild(next); if (next->nodeRefCount == 0) deleteIf(next); next = kid; // Don't advance; there might be another. } // Otherwise it might be an Element, which is handled recursively else if (kid->isElementImpl()) kid->normalize(); }; // changed() will have occurred when the removeChild() was done, // so does not have to be reissued. }; <|endoftext|>
<commit_before>#ifndef SKSAT_WINDOW_HPP #define SKSAT_WINDOW_HPP #include <sksat/common.hpp> #include <sksat/platform.hpp> #include <sksat/color.hpp> namespace sksat { class window_base { public: window_base() : opend(false), xsize(default_xsize), ysize(default_ysize), xpos(default_xpos), ypos(default_ypos) {} window_base(size_t x, size_t y) : opend(false), xsize(x), ysize(y), xpos(default_xpos), ypos(default_ypos) {} window_base(sksat::string &t, size_t x, size_t y) : opend(false), title(t), xsize(x), ysize(y), xpos(default_xpos), ypos(default_ypos) {} void open(){ opend = api_open(); } void open(size_t x, size_t y){ open(); set_size(x,y); } void open(sksat::string &t){ set_title(t); open(); } void open(sksat::string &t, size_t x, size_t y){ set_title(t); open(x,y); } void close(){ if(opend) api_close(); opend=false; } void show(){ if(opend) api_show(); } void set_title(sksat::string &t){ title = t; set_title(t.c_str()); } void set_title(const char *t){ title = t; api_set_title(t); } sksat::string get_title() const { return title; } virtual void set_size(size_t x, size_t y){ xsize=x; ysize=y; if(opend) api_set_size(x,y); } void set_xsize(size_t x){ set_size(x, ysize); } void set_ysize(size_t y){ set_size(xsize, y); } size_t get_xsize() const { return xsize; } size_t get_ysize() const { return ysize; } void move(size_t x, size_t y){ xpos=x; ypos=y; api_move(x,y); } void set_pos(size_t x, size_t y){ move(x,y); } void set_xpos(size_t x){ move(x,ypos); } void set_ypos(size_t y){ move(xpos,y); } operator bool () const { return opend; } // 描画関数 inline void draw_point(sksat::color &col, size_t x, size_t y){ api_draw_point(col, x, y); } // void draw_line(sksat::color &col, size_t x0, size_t y0, size_t x1, size_t y1); // void draw_rect(sksat::color &col, size_t x0, size_t y0, size_t x1, size_t y1, bool fill); // set_color()でセットした色 // void draw_point(size_t x, size_t y); // void draw_line(size_t x0, size_t y0, size_t x1, size_t y1); // void draw_rect(size_t x0, size_t y0, size_t x1, size_t y1, bool fill); // void fill_rect(size_t x0, size_t y0, size_t x1, size_t y1){ draw_rect(x0,y0,x1,y1,true); } inline void flush(){ if(opend) api_flush(); } inline bool step_loop(){ if(opend) return api_step_loop(); } inline void loop(){ while(api_step_loop()); } protected: // 環境依存部(純粋仮想関数) virtual void init() = 0; virtual bool api_open() = 0; virtual void api_close() = 0; virtual void api_show() = 0; virtual void api_set_title(const char *t) = 0; virtual void api_set_size(size_t x, size_t y) = 0; virtual void api_flush() = 0; virtual void api_move(size_t x, size_t y) = 0; // 描画 virtual void api_draw_point(sksat::color &col, size_t x, size_t y) = 0; virtual bool api_step_loop() = 0; public: static size_t default_xsize, default_ysize; static size_t default_xpos, default_ypos; protected: bool opend; size_t xsize, ysize; size_t xpos, ypos; sksat::string title; }; size_t window_base::default_xsize = 100; size_t window_base::default_ysize = 100; size_t window_base::default_xpos = 0; size_t window_base::default_ypos = 0; } #if defined(OS_WIN32) #include <sksat/win32/window.hpp> namespace sksat{ using sksat::win32::window; } #elif defined(OS_LINUX) #include <sksat/linux/window.hpp> namespace sksat{ using sksat::linux::window; } #else #error not implemented. #endif #endif <commit_msg>[FIX] remove init func (pure virtual)<commit_after>#ifndef SKSAT_WINDOW_HPP #define SKSAT_WINDOW_HPP #include <sksat/common.hpp> #include <sksat/platform.hpp> #include <sksat/color.hpp> namespace sksat { class window_base { public: window_base() : opend(false), xsize(default_xsize), ysize(default_ysize), xpos(default_xpos), ypos(default_ypos) {} window_base(size_t x, size_t y) : opend(false), xsize(x), ysize(y), xpos(default_xpos), ypos(default_ypos) {} window_base(sksat::string &t, size_t x, size_t y) : opend(false), title(t), xsize(x), ysize(y), xpos(default_xpos), ypos(default_ypos) {} void open(){ opend = api_open(); } void open(size_t x, size_t y){ open(); set_size(x,y); } void open(sksat::string &t){ set_title(t); open(); } void open(sksat::string &t, size_t x, size_t y){ set_title(t); open(x,y); } void close(){ if(opend) api_close(); opend=false; } void show(){ if(opend) api_show(); } void set_title(sksat::string &t){ title = t; set_title(t.c_str()); } void set_title(const char *t){ title = t; api_set_title(t); } sksat::string get_title() const { return title; } virtual void set_size(size_t x, size_t y){ xsize=x; ysize=y; if(opend) api_set_size(x,y); } void set_xsize(size_t x){ set_size(x, ysize); } void set_ysize(size_t y){ set_size(xsize, y); } size_t get_xsize() const { return xsize; } size_t get_ysize() const { return ysize; } void move(size_t x, size_t y){ xpos=x; ypos=y; api_move(x,y); } void set_pos(size_t x, size_t y){ move(x,y); } void set_xpos(size_t x){ move(x,ypos); } void set_ypos(size_t y){ move(xpos,y); } operator bool () const { return opend; } // 描画関数 inline void draw_point(sksat::color &col, size_t x, size_t y){ api_draw_point(col, x, y); } // void draw_line(sksat::color &col, size_t x0, size_t y0, size_t x1, size_t y1); // void draw_rect(sksat::color &col, size_t x0, size_t y0, size_t x1, size_t y1, bool fill); // set_color()でセットした色 // void draw_point(size_t x, size_t y); // void draw_line(size_t x0, size_t y0, size_t x1, size_t y1); // void draw_rect(size_t x0, size_t y0, size_t x1, size_t y1, bool fill); // void fill_rect(size_t x0, size_t y0, size_t x1, size_t y1){ draw_rect(x0,y0,x1,y1,true); } inline void flush(){ if(opend) api_flush(); } inline bool step_loop(){ if(opend) return api_step_loop(); } inline void loop(){ while(api_step_loop()); } protected: // 環境依存部(純粋仮想関数) virtual bool api_open() = 0; virtual void api_close() = 0; virtual void api_show() = 0; virtual void api_set_title(const char *t) = 0; virtual void api_set_size(size_t x, size_t y) = 0; virtual void api_flush() = 0; virtual void api_move(size_t x, size_t y) = 0; // 描画 virtual void api_draw_point(sksat::color &col, size_t x, size_t y) = 0; virtual bool api_step_loop() = 0; public: static size_t default_xsize, default_ysize; static size_t default_xpos, default_ypos; protected: bool opend; size_t xsize, ysize; size_t xpos, ypos; sksat::string title; }; size_t window_base::default_xsize = 100; size_t window_base::default_ysize = 100; size_t window_base::default_xpos = 0; size_t window_base::default_ypos = 0; } #if defined(OS_WIN32) #include <sksat/win32/window.hpp> namespace sksat{ using sksat::win32::window; } #elif defined(OS_LINUX) #include <sksat/linux/window.hpp> namespace sksat{ using sksat::linux::window; } #else #error not implemented. #endif #endif <|endoftext|>
<commit_before>// // GameModel.cpp // CatchiOS // // Created by John Barbero Unenge on 10/7/12. // Copyright (c) 2012 John Barbero Unenge. All rights reserved. // #include "GameModel.hpp" #include "../EventHandling/EventBus.hpp" #include "../Helper/Logger.hpp" #include "Physics/PBody.hpp" #include "../Helper/Constants.hpp" GameModel::GameModel() { m_physicsManager = new PhysicsManager(); m_gameMap = new GameMap(); m_player = new Player(); m_chainsaw = 0; } GameModel::~GameModel() { } void GameModel::update(float dt) { if (m_chainsaw != 0){ if (m_chainsaw->targetReached()){ m_chainsaw->setTarget(m_player->getPosition()); Log(LOG_INFO, "Chainsaw", "The Chainsaw has reached its target!! ****"); } m_chainsaw->update(dt); } m_physicsManager->update(dt); m_player->update(); // m_gameMap->update(); } Vector2d* GameModel::getCenterPoint() { return new Vector2d(m_player->getPosition().x, m_player->getPosition().y); } void GameModel::playerJump() { m_player->jump(); } void GameModel::playerThrowAt(int x, int y) { double convertedX = x * Constants::getGameWidth(); double convertedY = y * Constants::getGameHeight(); b2Vec2 target = b2Vec2( convertedX + m_player->getPosition().x, convertedY + m_player->getPosition().y); b2Vec2 spawn = b2Vec2(m_player->getPosition().x + 3, m_player->getPosition().y + 3); m_chainsaw = new Chainsaw(b2Vec2(1.0, 1.0 ),spawn , target, false, true, PB_PLAYER); Log(LOG_INFO, "GameModel", generateCString("Player threw his chainsaw at: %i,%i", x, y)); }<commit_msg>GameModel now keeps a reference to a Chainsaw<commit_after>// // GameModel.cpp // CatchiOS // // Created by John Barbero Unenge on 10/7/12. // Copyright (c) 2012 John Barbero Unenge. All rights reserved. // #include "GameModel.hpp" #include "../EventHandling/EventBus.hpp" #include "../Helper/Logger.hpp" #include "Physics/PBody.hpp" #include "../Helper/Constants.hpp" GameModel::GameModel() { m_physicsManager = new PhysicsManager(); m_gameMap = new GameMap(); m_player = new Player(); m_player = new Player(); m_chainsaw = 0; } GameModel::~GameModel() { } void GameModel::update(float dt) { if (m_chainsaw != 0){ if (m_chainsaw->targetReached()){ m_chainsaw->setTarget(m_player->getPosition()); Log(LOG_INFO, "Chainsaw", "The Chainsaw has reached its target!! ****"); } m_chainsaw->update(dt); } m_physicsManager->update(dt); m_player->update(); // m_gameMap->update(); } Vector2d* GameModel::getCenterPoint() { return new Vector2d(m_player->getPosition().x, m_player->getPosition().y); } void GameModel::playerJump() { m_player->jump(); } void GameModel::playerThrowAt(int x, int y) { double convertedX = x * Constants::getGameWidth(); double convertedY = y * Constants::getGameHeight(); b2Vec2 target = b2Vec2( convertedX + m_player->getPosition().x, convertedY + m_player->getPosition().y); b2Vec2 spawn = b2Vec2(m_player->getPosition().x + 3, m_player->getPosition().y + 3); m_chainsaw = new Chainsaw(b2Vec2(1.0, 1.0 ),spawn , target, false, true, PB_PLAYER); Log(LOG_INFO, "GameModel", generateCString("Player threw his chainsaw at: %i,%i", x, y)); }<|endoftext|>
<commit_before>#ifndef ORG_EEROS_CONTROL_SUM_HPP_ #define ORG_EEROS_CONTROL_SUM_HPP_ #include <vector> #include <eeros/control/Block.hpp> #include <eeros/control/Input.hpp> #include <eeros/control/Output.hpp> namespace eeros { namespace control { template < uint8_t N = 2, typename T = double > class Sum : public Block { public: Sum() { // TODO set bool-array to false } virtual void run() { T sum = 0; for(uint8_t i = 0; i < N; i++) { if(negated[i]) sum -= in[i].getSignal().getValue(); else sum += in[i].getSignal().getValue(); } out.getSignal().setValue(sum); out.getSignal().setTimestamp(in[0].getSignal().getTimestamp()); } virtual Input<T>& getIn(uint8_t index) { return in[index]; } virtual Output<T>& getOut() { return out; } virtual void negateInput(uint8_t index) { negated[index] = true; } protected: Input<T> in[N]; Output<T> out; bool negated[N]; }; }; }; #endif /* ORG_EEROS_CONTROL_SUM_HPP_ */ <commit_msg>[Framework] Sum-Block: Bug fixed in initialization<commit_after>#ifndef ORG_EEROS_CONTROL_SUM_HPP_ #define ORG_EEROS_CONTROL_SUM_HPP_ #include <vector> #include <eeros/control/Block.hpp> #include <eeros/control/Input.hpp> #include <eeros/control/Output.hpp> namespace eeros { namespace control { template < uint8_t N = 2, typename T = double > class Sum : public Block { public: Sum() { for(uint8_t i = 0; i < N; i++) { negated[i] = false; } } virtual void run() { T sum = 0; for(uint8_t i = 0; i < N; i++) { if(negated[i]) sum -= in[i].getSignal().getValue(); else sum += in[i].getSignal().getValue(); } out.getSignal().setValue(sum); out.getSignal().setTimestamp(in[0].getSignal().getTimestamp()); } virtual Input<T>& getIn(uint8_t index) { return in[index]; } virtual Output<T>& getOut() { return out; } virtual void negateInput(uint8_t index) { negated[index] = true; } protected: Input<T> in[N]; Output<T> out; bool negated[N]; }; }; }; #endif /* ORG_EEROS_CONTROL_SUM_HPP_ */ <|endoftext|>