text
stringlengths
54
60.6k
<commit_before>//============================================================================ // I B E X // File : ctc01.cpp // Author : Gilles Chabert // Copyright : Ecole des Mines de Nantes (France) // License : See the LICENSE file // Created : Jun 3, 2012 // Last Update : Jun 3, 2012 //============================================================================ #include "./ibex.h" #include <cmath> #include <iostream> using std::sqrt; using std::cout; using std::endl; int main() { { // Example #13 // ------------------------------------------------ // Contractor // // > Create the function (x,y)->( ||(x,y)||-d, ||(x,y)-(1,1)||-d ) // > Create the contractor "projection of f=0" // (i.e., contraction of the input box w.r.t. f=0) // > Embed this contractor in a generic fix-point loop // ------------------------------------------------ ibex::Variable x("x"), y("y"); const double d = 0.5 * sqrt(2); ibex::Function f( x, y, ibex::Return(ibex::sqrt(ibex::sqr(x) + ibex::sqr(y)) - d, ibex::sqrt(ibex::sqr(x - 1.0) + ibex::sqr(y - 1.0)) - d)); cout << f << endl; double init_box[][2] = {{-10, 10}, {-10, 10}}; ibex::IntervalVector box(2, init_box); ibex::CtcFwdBwd c(f); c.contract(box); cout << "box after proj=" << box << endl; ibex::CtcFixPoint fp(c, 1e-03); fp.contract(box); cout << "box after fixpoint=" << box << endl; } { // Example #14 // ------------------------------------------------ // Combining FwdBwdection and Newton Contractor // // > Create the projection contractor on the same function // as in the last example // > Contract the initial box x to x' // > Create the Newton iteration contractor // > Contract the box x' // ------------------------------------------------ ibex::Variable x("x"), y("y"); const double d = 1.0; ibex::Function f(x, y, ibex::Return(sqrt(sqr(x) + sqr(y)) - d, sqrt(sqr(x - 1.0) + sqr(y - 1.0)) - d)); cout << f << endl; double init_box[][2] = {{0.9, 1.1}, {-0.1, 0.1}}; ibex::IntervalVector box(2, init_box); ibex::CtcFwdBwd c(f); c.contract(box); cout << "box after proj=" << box << endl; ibex::CtcNewton newton(f); newton.contract(box); cout << "box after newton=" << box << endl; } } <commit_msg>test(ibex_test.cc): Fix memory-leak<commit_after>//============================================================================ // I B E X // File : ctc01.cpp // Author : Gilles Chabert // Copyright : Ecole des Mines de Nantes (France) // License : See the LICENSE file // Created : Jun 3, 2012 // Last Update : Jun 3, 2012 //============================================================================ #include "./ibex.h" #include <cmath> #include <iostream> using std::cout; using std::endl; using std::sqrt; int main() { { // Example #13 // ------------------------------------------------ // Contractor // // > Create the function (x,y)->( ||(x,y)||-d, ||(x,y)-(1,1)||-d ) // > Create the contractor "projection of f=0" // (i.e., contraction of the input box w.r.t. f=0) // > Embed this contractor in a generic fix-point loop // ------------------------------------------------ // We do the following to avoid memory leak. See // https://github.com/ibex-team/ibex-lib/issues/137#issuecomment-104536311 const auto& x = ibex::ExprSymbol::new_(); const auto& y = ibex::ExprSymbol::new_(); const double d = 0.5 * sqrt(2); ibex::Function f( x, y, ibex::Return(ibex::sqrt(ibex::sqr(x) + ibex::sqr(y)) - d, ibex::sqrt(ibex::sqr(x - 1.0) + ibex::sqr(y - 1.0)) - d)); cout << f << endl; double init_box[][2] = {{-10, 10}, {-10, 10}}; ibex::IntervalVector box(2, init_box); ibex::CtcFwdBwd c(f); c.contract(box); cout << "box after proj=" << box << endl; ibex::CtcFixPoint fp(c, 1e-03); fp.contract(box); cout << "box after fixpoint=" << box << endl; } { // Example #14 // ------------------------------------------------ // Combining FwdBwdection and Newton Contractor // // > Create the projection contractor on the same function // as in the last example // > Contract the initial box x to x' // > Create the Newton iteration contractor // > Contract the box x' // ------------------------------------------------ const auto& x = ibex::ExprSymbol::new_(); const auto& y = ibex::ExprSymbol::new_(); const double d = 1.0; ibex::Function f(x, y, ibex::Return(sqrt(sqr(x) + sqr(y)) - d, sqrt(sqr(x - 1.0) + sqr(y - 1.0)) - d)); cout << f << endl; double init_box[][2] = {{0.9, 1.1}, {-0.1, 0.1}}; ibex::IntervalVector box(2, init_box); ibex::CtcFwdBwd c(f); c.contract(box); cout << "box after proj=" << box << endl; ibex::CtcNewton newton(f); newton.contract(box); cout << "box after newton=" << box << endl; } } <|endoftext|>
<commit_before>//.............................................................................. // // This file is part of the AXL library. // // AXL is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/axl/license.txt // //.............................................................................. #include "pch.h" #include "axl_io_Serial.h" #include "axl_sys_Event.h" namespace axl { namespace io { //.............................................................................. #if (_AXL_OS_WIN) bool Serial::open ( const sl::StringRef& name, uint_t flags ) { uint_t accessMode = (flags & FileFlag_ReadOnly) ? GENERIC_READ : (flags & FileFlag_WriteOnly) ? GENERIC_WRITE : GENERIC_READ | GENERIC_WRITE; uint_t flagsAttributes = (flags & FileFlag_Asynchronous) ? FILE_FLAG_OVERLAPPED : 0; return m_serial.open (name, accessMode, flagsAttributes); } bool Serial::setSettings ( const SerialSettings* settings, uint_t mask ) { DCB dcb; dcb.DCBlength = sizeof (dcb); bool result = m_serial.getSettings (&dcb); if (!result) return false; dcb.fBinary = TRUE; dcb.fDsrSensitivity = FALSE; dcb.fDtrControl = DTR_CONTROL_DISABLE; if (mask & SerialSettingId_BaudRate) dcb.BaudRate = settings->m_baudRate; if (mask & SerialSettingId_DataBits) dcb.ByteSize = settings->m_dataBits; if (mask & SerialSettingId_StopBits) dcb.StopBits = settings->m_stopBits; if (mask & SerialSettingId_Parity) { dcb.fParity = settings->m_parity != SerialParity_None; dcb.Parity = settings->m_parity; } if (mask & SerialSettingId_FlowControl) switch (settings->m_flowControl) { case SerialFlowControl_None: dcb.fOutxCtsFlow = FALSE; dcb.fRtsControl = RTS_CONTROL_DISABLE; break; case SerialFlowControl_RtsCts: dcb.fOutxCtsFlow = TRUE; dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; break; case SerialFlowControl_XonXoff: dcb.fOutX = TRUE; dcb.fInX = TRUE; break; } if (!(mask & SerialSettingId_ReadInterval)) return m_serial.setSettings (&dcb); COMMTIMEOUTS timeouts = { 0 }; timeouts.ReadIntervalTimeout = settings->m_readInterval == 0 ? -1 : settings->m_readInterval == -1 ? 0 : settings->m_readInterval; return m_serial.setSettings (&dcb) && m_serial.setTimeouts (&timeouts); } bool Serial::getSettings (SerialSettings* settings) { DCB dcb; dcb.DCBlength = sizeof (dcb); bool result = m_serial.getSettings (&dcb); if (!result) return false; settings->setDcb (&dcb); return true; } uint_t Serial::getStatusLines () { uint_t lines = m_serial.getStatusLines (); return lines != -1 ? (lines & 0xf0) >> 4 : -1; } #elif (_AXL_OS_POSIX) bool Serial::open ( const sl::StringRef& name, uint_t flags ) { uint_t posixFlags = (flags & FileFlag_ReadOnly) ? O_RDONLY : (flags & FileFlag_WriteOnly) ? O_WRONLY : O_RDWR; if (flags & FileFlag_Asynchronous) posixFlags |= O_NONBLOCK; posixFlags |= O_NOCTTY; return m_serial.open (name, posixFlags); } bool Serial::setSettings ( const SerialSettings* settings, uint_t mask ) { termios attr; bool result = m_serial.getAttr (&attr); if (!result) return false; if (mask & SerialSettingId_BaudRate) { speed_t speed; switch (settings->m_baudRate) { case 110: speed = B110; break; case 300: speed = B300; break; case 600: speed = B600; break; case 1200: speed = B1200; break; case 2400: speed = B2400; break; case 4800: speed = B4800; break; case 9600: speed = B9600; break; case 19200: speed = B19200; break; case 38400: speed = B38400; break; case 57600: speed = B57600; break; case 115200: speed = B115200; break; default: // TODO: custom baud rate (currently fall back to 38400) speed = B38400; } cfsetispeed (&attr, speed); cfsetospeed (&attr, speed); } if (mask & SerialSettingId_DataBits) { attr.c_cflag &= ~CSIZE; switch (settings->m_dataBits) { case 5: attr.c_cflag |= CS5; break; case 6: attr.c_cflag |= CS6; break; case 7: attr.c_cflag |= CS7; break; case 8: default: attr.c_cflag |= CS8; break; } } if (mask & SerialSettingId_StopBits) { if (settings->m_stopBits == SerialStopBits_2) attr.c_cflag |= CSTOPB; else attr.c_cflag &= ~CSTOPB; } if (mask & SerialSettingId_Parity) { attr.c_iflag &= ~(PARMRK | INPCK); attr.c_iflag |= IGNPAR; switch (settings->m_parity) { case SerialParity_None: attr.c_cflag &= ~PARENB; break; case SerialParity_Odd: attr.c_cflag |= PARENB | PARODD; break; case SerialParity_Even: attr.c_cflag &= ~PARODD; attr.c_cflag |= PARENB; break; #ifdef CMSPAR case SerialParity_Mark: attr.c_cflag |= PARENB | CMSPAR | PARODD; break; case SerialParity_Space: attr.c_cflag &= ~PARODD; attr.c_cflag |= PARENB | CMSPAR; break; #endif default: attr.c_cflag |= PARENB; attr.c_iflag |= PARMRK | INPCK; attr.c_iflag &= ~IGNPAR; } } if (mask & SerialSettingId_FlowControl) switch (settings->m_flowControl) { case SerialFlowControl_RtsCts: attr.c_cflag |= CRTSCTS; attr.c_iflag &= ~(IXON | IXOFF | IXANY); break; case SerialFlowControl_XonXoff: attr.c_cflag &= ~CRTSCTS; attr.c_iflag |= IXON | IXOFF | IXANY; break; case SerialFlowControl_None: default: attr.c_cflag &= ~CRTSCTS; attr.c_iflag &= ~(IXON | IXOFF | IXANY); } // ensure some extra default flags attr.c_iflag |= IGNBRK; attr.c_iflag &= ~(BRKINT | IGNCR | INLCR | ICRNL | ISTRIP); attr.c_oflag = 0; attr.c_cflag |= CREAD | CLOCAL; attr.c_lflag = 0; for (size_t i = 0; i < countof (attr.c_cc); i++) attr.c_cc [i] = _POSIX_VDISABLE; attr.c_cc [VTIME] = settings->m_readInterval / 100; // milliseconds -> deciseconds attr.c_cc [VMIN] = 1; return m_serial.setAttr (&attr); } bool Serial::getSettings (SerialSettings* settings) { termios attr; bool result = m_serial.getAttr (&attr); if (!result) return false; settings->setAttr (&attr); return true; } uint_t Serial::getStatusLines () { uint_t result = m_serial.getStatusLines (); if (result == -1) return -1; uint_t lines = 0; if (result & TIOCM_CTS) lines |= SerialStatusLine_Cts; if (result & TIOCM_DSR) lines |= SerialStatusLine_Dsr; if (result & TIOCM_RNG) lines |= SerialStatusLine_Ring; if (result & TIOCM_CAR) lines |= SerialStatusLine_Dcd; return lines; } #endif //.............................................................................. } // namespace io } // namespace axl <commit_msg>[axl_io] clear flow control fields in the DCB prior to setting the new value<commit_after>//.............................................................................. // // This file is part of the AXL library. // // AXL is distributed under the MIT license. // For details see accompanying license.txt file, // the public copy of which is also available at: // http://tibbo.com/downloads/archive/axl/license.txt // //.............................................................................. #include "pch.h" #include "axl_io_Serial.h" #include "axl_sys_Event.h" namespace axl { namespace io { //.............................................................................. #if (_AXL_OS_WIN) bool Serial::open ( const sl::StringRef& name, uint_t flags ) { uint_t accessMode = (flags & FileFlag_ReadOnly) ? GENERIC_READ : (flags & FileFlag_WriteOnly) ? GENERIC_WRITE : GENERIC_READ | GENERIC_WRITE; uint_t flagsAttributes = (flags & FileFlag_Asynchronous) ? FILE_FLAG_OVERLAPPED : 0; return m_serial.open (name, accessMode, flagsAttributes); } bool Serial::setSettings ( const SerialSettings* settings, uint_t mask ) { DCB dcb; dcb.DCBlength = sizeof (dcb); bool result = m_serial.getSettings (&dcb); if (!result) return false; dcb.fBinary = TRUE; dcb.fDsrSensitivity = FALSE; dcb.fDtrControl = DTR_CONTROL_DISABLE; if (mask & SerialSettingId_BaudRate) dcb.BaudRate = settings->m_baudRate; if (mask & SerialSettingId_DataBits) dcb.ByteSize = settings->m_dataBits; if (mask & SerialSettingId_StopBits) dcb.StopBits = settings->m_stopBits; if (mask & SerialSettingId_Parity) { dcb.fParity = settings->m_parity != SerialParity_None; dcb.Parity = settings->m_parity; } if (mask & SerialSettingId_FlowControl) { dcb.fOutxCtsFlow = FALSE; dcb.fOutX = FALSE; dcb.fInX = FALSE; if (dcb.fRtsControl == RTS_CONTROL_HANDSHAKE) dcb.fRtsControl = RTS_CONTROL_DISABLE; switch (settings->m_flowControl) { case SerialFlowControl_RtsCts: dcb.fOutxCtsFlow = TRUE; dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; break; case SerialFlowControl_XonXoff: dcb.fOutX = TRUE; dcb.fInX = TRUE; break; } } if (!(mask & SerialSettingId_ReadInterval)) return m_serial.setSettings (&dcb); COMMTIMEOUTS timeouts = { 0 }; timeouts.ReadIntervalTimeout = settings->m_readInterval == 0 ? -1 : settings->m_readInterval == -1 ? 0 : settings->m_readInterval; return m_serial.setSettings (&dcb) && m_serial.setTimeouts (&timeouts); } bool Serial::getSettings (SerialSettings* settings) { DCB dcb; dcb.DCBlength = sizeof (dcb); bool result = m_serial.getSettings (&dcb); if (!result) return false; settings->setDcb (&dcb); return true; } uint_t Serial::getStatusLines () { uint_t lines = m_serial.getStatusLines (); return lines != -1 ? (lines & 0xf0) >> 4 : -1; } #elif (_AXL_OS_POSIX) bool Serial::open ( const sl::StringRef& name, uint_t flags ) { uint_t posixFlags = (flags & FileFlag_ReadOnly) ? O_RDONLY : (flags & FileFlag_WriteOnly) ? O_WRONLY : O_RDWR; if (flags & FileFlag_Asynchronous) posixFlags |= O_NONBLOCK; posixFlags |= O_NOCTTY; return m_serial.open (name, posixFlags); } bool Serial::setSettings ( const SerialSettings* settings, uint_t mask ) { termios attr; bool result = m_serial.getAttr (&attr); if (!result) return false; if (mask & SerialSettingId_BaudRate) { speed_t speed; switch (settings->m_baudRate) { case 110: speed = B110; break; case 300: speed = B300; break; case 600: speed = B600; break; case 1200: speed = B1200; break; case 2400: speed = B2400; break; case 4800: speed = B4800; break; case 9600: speed = B9600; break; case 19200: speed = B19200; break; case 38400: speed = B38400; break; case 57600: speed = B57600; break; case 115200: speed = B115200; break; default: // TODO: custom baud rate (currently fall back to 38400) speed = B38400; } cfsetispeed (&attr, speed); cfsetospeed (&attr, speed); } if (mask & SerialSettingId_DataBits) { attr.c_cflag &= ~CSIZE; switch (settings->m_dataBits) { case 5: attr.c_cflag |= CS5; break; case 6: attr.c_cflag |= CS6; break; case 7: attr.c_cflag |= CS7; break; case 8: default: attr.c_cflag |= CS8; break; } } if (mask & SerialSettingId_StopBits) { if (settings->m_stopBits == SerialStopBits_2) attr.c_cflag |= CSTOPB; else attr.c_cflag &= ~CSTOPB; } if (mask & SerialSettingId_Parity) { attr.c_iflag &= ~(PARMRK | INPCK); attr.c_iflag |= IGNPAR; switch (settings->m_parity) { case SerialParity_None: attr.c_cflag &= ~PARENB; break; case SerialParity_Odd: attr.c_cflag |= PARENB | PARODD; break; case SerialParity_Even: attr.c_cflag &= ~PARODD; attr.c_cflag |= PARENB; break; #ifdef CMSPAR case SerialParity_Mark: attr.c_cflag |= PARENB | CMSPAR | PARODD; break; case SerialParity_Space: attr.c_cflag &= ~PARODD; attr.c_cflag |= PARENB | CMSPAR; break; #endif default: attr.c_cflag |= PARENB; attr.c_iflag |= PARMRK | INPCK; attr.c_iflag &= ~IGNPAR; } } if (mask & SerialSettingId_FlowControl) switch (settings->m_flowControl) { case SerialFlowControl_RtsCts: attr.c_cflag |= CRTSCTS; attr.c_iflag &= ~(IXON | IXOFF | IXANY); break; case SerialFlowControl_XonXoff: attr.c_cflag &= ~CRTSCTS; attr.c_iflag |= IXON | IXOFF | IXANY; break; case SerialFlowControl_None: default: attr.c_cflag &= ~CRTSCTS; attr.c_iflag &= ~(IXON | IXOFF | IXANY); } // ensure some extra default flags attr.c_iflag |= IGNBRK; attr.c_iflag &= ~(BRKINT | IGNCR | INLCR | ICRNL | ISTRIP); attr.c_oflag = 0; attr.c_cflag |= CREAD | CLOCAL; attr.c_lflag = 0; for (size_t i = 0; i < countof (attr.c_cc); i++) attr.c_cc [i] = _POSIX_VDISABLE; attr.c_cc [VTIME] = settings->m_readInterval / 100; // milliseconds -> deciseconds attr.c_cc [VMIN] = 1; return m_serial.setAttr (&attr); } bool Serial::getSettings (SerialSettings* settings) { termios attr; bool result = m_serial.getAttr (&attr); if (!result) return false; settings->setAttr (&attr); return true; } uint_t Serial::getStatusLines () { uint_t result = m_serial.getStatusLines (); if (result == -1) return -1; uint_t lines = 0; if (result & TIOCM_CTS) lines |= SerialStatusLine_Cts; if (result & TIOCM_DSR) lines |= SerialStatusLine_Dsr; if (result & TIOCM_RNG) lines |= SerialStatusLine_Ring; if (result & TIOCM_CAR) lines |= SerialStatusLine_Dcd; return lines; } #endif //.............................................................................. } // namespace io } // namespace axl <|endoftext|>
<commit_before>#include <iostream> #include <limits> #include <algorithm> #include "../segment_tree/segment_tree.hpp" template <typename T> struct rmq_specification { static inline const T& get_identity() { static const T IDENTITY = std::numeric_limits<T>::min(); return IDENTITY; } static inline const T& fn(const T & a, const T & b) { return std::min(a, b); } }; typedef fx::segment_tree<int, rmq_specification<int> > segment_tree_rmq; int main() { size_t array_size = 10; int array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; segment_tree_rmq st(array, array+array_size); std::cout << (st.query(0, 10) == 0) << std::endl; return 0; } <commit_msg>Identity for min should be max<commit_after>#include <iostream> #include <limits> #include <algorithm> #include "../segment_tree/segment_tree.hpp" template <typename T> struct rmq_specification { static inline const T& get_identity() { static const T IDENTITY = std::numeric_limits<T>::max(); return IDENTITY; } static inline const T& fn(const T & a, const T & b) { return std::min(a, b); } }; typedef fx::segment_tree<int, rmq_specification<int> > segment_tree_rmq; int main() { size_t array_size = 10; int array[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; segment_tree_rmq st(array, array+array_size); std::cout << (st.query(0, 10) == 0) << std::endl; return 0; } <|endoftext|>
<commit_before>#pragma once #include "../data/math.hpp" #include "../data/data_set.hpp" #include <QObject> #include <QPainter> #include <QPointF> #include <vector> namespace datavis { using std::vector; class Selector; class PlotView; class Plot : public QObject { Q_OBJECT public: struct Range { Range() {} Range(double min, double max): min(min), max(max) {} double min = 0; double max = 0; double extent() { return max - min; } }; Plot(QObject * parent = 0): QObject(parent) {} PlotView * view() { return m_view; } virtual DataSetPtr dataSet() = 0; virtual bool isEmpty() const = 0; virtual Range xRange() = 0; virtual Range yRange() = 0; virtual void plot(QPainter *, const Mapping2d &, const QRectF & region) = 0; virtual vector<double> dataLocation(const QPointF & point) = 0; signals: void xRangeChanged(); void yRangeChanged(); void contentChanged(); private: friend class PlotView; void setView(PlotView *view) { m_view = view; } PlotView * m_view; }; inline QPointF operator* (const Mapping2d & m, const QPointF & v) { return QPointF(v.x() * m.x_scale + m.x_offset, v.y() * m.y_scale + m.y_offset); } } <commit_msg>Plot: Fix uninitialized variable<commit_after>#pragma once #include "../data/math.hpp" #include "../data/data_set.hpp" #include <QObject> #include <QPainter> #include <QPointF> #include <vector> namespace datavis { using std::vector; class Selector; class PlotView; class Plot : public QObject { Q_OBJECT public: struct Range { Range() {} Range(double min, double max): min(min), max(max) {} double min = 0; double max = 0; double extent() { return max - min; } }; Plot(QObject * parent = 0): QObject(parent) {} PlotView * view() { return m_view; } virtual DataSetPtr dataSet() = 0; virtual bool isEmpty() const = 0; virtual Range xRange() = 0; virtual Range yRange() = 0; virtual void plot(QPainter *, const Mapping2d &, const QRectF & region) = 0; virtual vector<double> dataLocation(const QPointF & point) = 0; signals: void xRangeChanged(); void yRangeChanged(); void contentChanged(); private: friend class PlotView; void setView(PlotView *view) { m_view = view; } PlotView * m_view = nullptr; }; inline QPointF operator* (const Mapping2d & m, const QPointF & v) { return QPointF(v.x() * m.x_scale + m.x_offset, v.y() * m.y_scale + m.y_offset); } } <|endoftext|>
<commit_before>// Copyright (c) 2015 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-CHROMIUM file. #include "brightray/browser/platform_notification_service.h" #include "base/strings/utf_string_conversions.h" #include "brightray/browser/browser_client.h" #include "brightray/browser/notification.h" #include "brightray/browser/notification_delegate.h" #include "brightray/browser/notification_presenter.h" #include "content/public/browser/notification_event_dispatcher.h" #include "content/public/common/notification_resources.h" #include "content/public/common/platform_notification_data.h" #include "third_party/skia/include/core/SkBitmap.h" namespace brightray { namespace { void OnWebNotificationAllowed(base::WeakPtr<Notification> notification, const SkBitmap& icon, const content::PlatformNotificationData& data, bool audio_muted, bool allowed) { if (!notification) return; if (allowed) { brightray::NotificationOptions options; options.title = data.title; options.msg = data.body; options.tag = data.tag; options.icon_url = data.icon; options.icon = icon; options.silent = audio_muted ? true : data.silent; options.has_reply = false; notification->Show(options); } else { notification->Destroy(); } } class NotificationDelegateImpl final : public brightray::NotificationDelegate { public: explicit NotificationDelegateImpl(const std::string& notification_id) : notification_id_(notification_id) {} void NotificationDestroyed() override { delete this; } void NotificationClick() override { content::NotificationEventDispatcher::GetInstance() ->DispatchNonPersistentClickEvent(notification_id_); } void NotificationClosed() override { content::NotificationEventDispatcher::GetInstance() ->DispatchNonPersistentCloseEvent(notification_id_); } void NotificationDisplayed() override { content::NotificationEventDispatcher::GetInstance() ->DispatchNonPersistentShowEvent(notification_id_); } private: std::string notification_id_; DISALLOW_COPY_AND_ASSIGN(NotificationDelegateImpl); }; } // namespace PlatformNotificationService::PlatformNotificationService( BrowserClient* browser_client) : browser_client_(browser_client), render_process_id_(-1) {} PlatformNotificationService::~PlatformNotificationService() {} blink::mojom::PermissionStatus PlatformNotificationService::CheckPermissionOnUIThread( content::BrowserContext* browser_context, const GURL& origin, int render_process_id) { render_process_id_ = render_process_id; return blink::mojom::PermissionStatus::GRANTED; } blink::mojom::PermissionStatus PlatformNotificationService::CheckPermissionOnIOThread( content::ResourceContext* resource_context, const GURL& origin, int render_process_id) { return blink::mojom::PermissionStatus::GRANTED; } void PlatformNotificationService::DisplayNotification( content::BrowserContext* browser_context, const std::string& notification_id, const GURL& origin, const content::PlatformNotificationData& notification_data, const content::NotificationResources& notification_resources) { auto* presenter = browser_client_->GetNotificationPresenter(); if (!presenter) return; NotificationDelegateImpl* delegate = new NotificationDelegateImpl(notification_id); auto notification = presenter->CreateNotification(delegate, notification_id); if (notification) { browser_client_->WebNotificationAllowed( render_process_id_, base::Bind(&OnWebNotificationAllowed, notification, notification_resources.notification_icon, notification_data)); } } void PlatformNotificationService::DisplayPersistentNotification( content::BrowserContext* browser_context, const std::string& notification_id, const GURL& service_worker_scope, const GURL& origin, const content::PlatformNotificationData& notification_data, const content::NotificationResources& notification_resources) {} void PlatformNotificationService::ClosePersistentNotification( content::BrowserContext* browser_context, const std::string& notification_id) {} void PlatformNotificationService::CloseNotification( content::BrowserContext* browser_context, const std::string& notification_id) { auto* presenter = browser_client_->GetNotificationPresenter(); if (!presenter) return; presenter->CloseNotificationWithId(notification_id); } void PlatformNotificationService::GetDisplayedNotifications( content::BrowserContext* browser_context, const DisplayedNotificationsCallback& callback) {} } // namespace brightray <commit_msg>fix: remember the render_process_id when permission requests occur on the IO thread (#13621)<commit_after>// Copyright (c) 2015 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-CHROMIUM file. #include "brightray/browser/platform_notification_service.h" #include "base/strings/utf_string_conversions.h" #include "brightray/browser/browser_client.h" #include "brightray/browser/notification.h" #include "brightray/browser/notification_delegate.h" #include "brightray/browser/notification_presenter.h" #include "content/public/browser/notification_event_dispatcher.h" #include "content/public/common/notification_resources.h" #include "content/public/common/platform_notification_data.h" #include "third_party/skia/include/core/SkBitmap.h" namespace brightray { namespace { void OnWebNotificationAllowed(base::WeakPtr<Notification> notification, const SkBitmap& icon, const content::PlatformNotificationData& data, bool audio_muted, bool allowed) { if (!notification) return; if (allowed) { brightray::NotificationOptions options; options.title = data.title; options.msg = data.body; options.tag = data.tag; options.icon_url = data.icon; options.icon = icon; options.silent = audio_muted ? true : data.silent; options.has_reply = false; notification->Show(options); } else { notification->Destroy(); } } class NotificationDelegateImpl final : public brightray::NotificationDelegate { public: explicit NotificationDelegateImpl(const std::string& notification_id) : notification_id_(notification_id) {} void NotificationDestroyed() override { delete this; } void NotificationClick() override { content::NotificationEventDispatcher::GetInstance() ->DispatchNonPersistentClickEvent(notification_id_); } void NotificationClosed() override { content::NotificationEventDispatcher::GetInstance() ->DispatchNonPersistentCloseEvent(notification_id_); } void NotificationDisplayed() override { content::NotificationEventDispatcher::GetInstance() ->DispatchNonPersistentShowEvent(notification_id_); } private: std::string notification_id_; DISALLOW_COPY_AND_ASSIGN(NotificationDelegateImpl); }; } // namespace PlatformNotificationService::PlatformNotificationService( BrowserClient* browser_client) : browser_client_(browser_client), render_process_id_(-1) {} PlatformNotificationService::~PlatformNotificationService() {} blink::mojom::PermissionStatus PlatformNotificationService::CheckPermissionOnUIThread( content::BrowserContext* browser_context, const GURL& origin, int render_process_id) { render_process_id_ = render_process_id; return blink::mojom::PermissionStatus::GRANTED; } blink::mojom::PermissionStatus PlatformNotificationService::CheckPermissionOnIOThread( content::ResourceContext* resource_context, const GURL& origin, int render_process_id) { render_process_id_ = render_process_id; return blink::mojom::PermissionStatus::GRANTED; } void PlatformNotificationService::DisplayNotification( content::BrowserContext* browser_context, const std::string& notification_id, const GURL& origin, const content::PlatformNotificationData& notification_data, const content::NotificationResources& notification_resources) { auto* presenter = browser_client_->GetNotificationPresenter(); if (!presenter) return; NotificationDelegateImpl* delegate = new NotificationDelegateImpl(notification_id); auto notification = presenter->CreateNotification(delegate, notification_id); if (notification) { browser_client_->WebNotificationAllowed( render_process_id_, base::Bind(&OnWebNotificationAllowed, notification, notification_resources.notification_icon, notification_data)); } } void PlatformNotificationService::DisplayPersistentNotification( content::BrowserContext* browser_context, const std::string& notification_id, const GURL& service_worker_scope, const GURL& origin, const content::PlatformNotificationData& notification_data, const content::NotificationResources& notification_resources) {} void PlatformNotificationService::ClosePersistentNotification( content::BrowserContext* browser_context, const std::string& notification_id) {} void PlatformNotificationService::CloseNotification( content::BrowserContext* browser_context, const std::string& notification_id) { auto* presenter = browser_client_->GetNotificationPresenter(); if (!presenter) return; presenter->CloseNotificationWithId(notification_id); } void PlatformNotificationService::GetDisplayedNotifications( content::BrowserContext* browser_context, const DisplayedNotificationsCallback& callback) {} } // namespace brightray <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "findplugin.h" #include "textfindconstants.h" #include "currentdocumentfind.h" #include "findtoolwindow.h" #include "searchresultwindow.h" #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/actionmanager/command.h> #include <coreplugin/coreconstants.h> #include <coreplugin/icore.h> #include <extensionsystem/pluginmanager.h> #include <utils/qtcassert.h> #include <QtCore/QtPlugin> #include <QtCore/QSettings> /*! \namespace Find The Find namespace provides everything that has to do with search term based searches. */ /*! \namespace Find::Internal \internal */ /*! \namespace Find::Internal::ItemDataRoles \internal */ Q_DECLARE_METATYPE(Find::IFindFilter*) namespace { const int MAX_COMPLETIONS = 50; } using namespace Find; using namespace Find::Internal; FindPlugin::FindPlugin() : m_currentDocumentFind(0), m_findToolBar(0), m_findDialog(0), m_findCompletionModel(new QStringListModel(this)), m_replaceCompletionModel(new QStringListModel(this)) { } FindPlugin::~FindPlugin() { delete m_currentDocumentFind; delete m_findToolBar; delete m_findDialog; } bool FindPlugin::initialize(const QStringList &, QString *) { setupMenu(); m_currentDocumentFind = new CurrentDocumentFind; m_findToolBar = new FindToolBar(this, m_currentDocumentFind); m_findDialog = new FindToolWindow(this); SearchResultWindow *searchResultWindow = new SearchResultWindow; addAutoReleasedObject(searchResultWindow); return true; } void FindPlugin::extensionsInitialized() { setupFilterMenuItems(); readSettings(); } void FindPlugin::shutdown() { m_findToolBar->setVisible(false); m_findToolBar->setParent(0); m_currentDocumentFind->removeConnections(); writeSettings(); } void FindPlugin::filterChanged() { IFindFilter *changedFilter = qobject_cast<IFindFilter *>(sender()); QAction *action = m_filterActions.value(changedFilter); QTC_ASSERT(changedFilter, return); QTC_ASSERT(action, return); action->setEnabled(changedFilter->isEnabled()); bool haveEnabledFilters = false; foreach (IFindFilter *filter, m_filterActions.keys()) { if (filter->isEnabled()) { haveEnabledFilters = true; break; } } m_openFindDialog->setEnabled(haveEnabledFilters); } void FindPlugin::openFindFilter() { QAction *action = qobject_cast<QAction*>(sender()); QTC_ASSERT(action, return); IFindFilter *filter = action->data().value<IFindFilter *>(); if (m_currentDocumentFind->candidateIsEnabled()) m_currentDocumentFind->acceptCandidate(); QString currentFindString = (m_currentDocumentFind->isEnabled() ? m_currentDocumentFind->currentFindString() : ""); if (!currentFindString.isEmpty()) m_findDialog->setFindText(currentFindString); m_findDialog->open(filter); } void FindPlugin::setupMenu() { Core::ActionManager *am = Core::ICore::instance()->actionManager(); Core::ActionContainer *medit = am->actionContainer(Core::Constants::M_EDIT); Core::ActionContainer *mfind = am->createMenu(Constants::M_FIND); medit->addMenu(mfind, Core::Constants::G_EDIT_FIND); mfind->menu()->setTitle(tr("&Find/Replace")); mfind->appendGroup(Constants::G_FIND_CURRENTDOCUMENT); mfind->appendGroup(Constants::G_FIND_FILTERS); mfind->appendGroup(Constants::G_FIND_FLAGS); mfind->appendGroup(Constants::G_FIND_ACTIONS); QList<int> globalcontext = QList<int>() << Core::Constants::C_GLOBAL_ID; Core::Command *cmd; QAction *separator; separator = new QAction(this); separator->setSeparator(true); cmd = am->registerAction(separator, QLatin1String("Find.Sep.Flags"), globalcontext); mfind->addAction(cmd, Constants::G_FIND_FLAGS); separator = new QAction(this); separator->setSeparator(true); cmd = am->registerAction(separator, QLatin1String("Find.Sep.Actions"), globalcontext); mfind->addAction(cmd, Constants::G_FIND_ACTIONS); Core::ActionContainer *mfindadvanced = am->createMenu(Constants::M_FIND_ADVANCED); mfindadvanced->menu()->setTitle(tr("Advanced Find")); mfind->addMenu(mfindadvanced, Constants::G_FIND_FILTERS); m_openFindDialog = new QAction(tr("Open Advanced Find..."), this); cmd = am->registerAction(m_openFindDialog, QLatin1String("Find.Dialog"), globalcontext); cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+F"))); mfindadvanced->addAction(cmd); connect(m_openFindDialog, SIGNAL(triggered()), this, SLOT(openFindFilter())); } void FindPlugin::setupFilterMenuItems() { Core::ActionManager *am = Core::ICore::instance()->actionManager(); QList<IFindFilter*> findInterfaces = ExtensionSystem::PluginManager::instance()->getObjects<IFindFilter>(); Core::Command *cmd; QList<int> globalcontext = QList<int>() << Core::Constants::C_GLOBAL_ID; Core::ActionContainer *mfindadvanced = am->actionContainer(Constants::M_FIND_ADVANCED); m_filterActions.clear(); bool haveEnabledFilters = false; foreach (IFindFilter *filter, findInterfaces) { QAction *action = new QAction(QString(" %1").arg(filter->name()), this); bool isEnabled = filter->isEnabled(); if (isEnabled) haveEnabledFilters = true; action->setEnabled(isEnabled); action->setData(qVariantFromValue(filter)); cmd = am->registerAction(action, QLatin1String("FindFilter.")+filter->id(), globalcontext); cmd->setDefaultKeySequence(filter->defaultShortcut()); mfindadvanced->addAction(cmd, Constants::G_FIND_FILTERS); m_filterActions.insert(filter, action); connect(action, SIGNAL(triggered(bool)), this, SLOT(openFindFilter())); connect(filter, SIGNAL(changed()), this, SLOT(filterChanged())); } m_findDialog->setFindFilters(findInterfaces); m_openFindDialog->setEnabled(haveEnabledFilters); } QTextDocument::FindFlags FindPlugin::findFlags() const { return m_findFlags; } void FindPlugin::setCaseSensitive(bool sensitive) { setFindFlag(QTextDocument::FindCaseSensitively, sensitive); } void FindPlugin::setWholeWord(bool wholeOnly) { setFindFlag(QTextDocument::FindWholeWords, wholeOnly); } void FindPlugin::setBackward(bool backward) { setFindFlag(QTextDocument::FindBackward, backward); } void FindPlugin::setFindFlag(QTextDocument::FindFlag flag, bool enabled) { bool hasFlag = hasFindFlag(flag); if ((hasFlag && enabled) || (!hasFlag && !enabled)) return; if (enabled) m_findFlags |= flag; else m_findFlags &= ~flag; if (flag != QTextDocument::FindBackward) emit findFlagsChanged(); } bool FindPlugin::hasFindFlag(QTextDocument::FindFlag flag) { return m_findFlags & flag; } void FindPlugin::writeSettings() { QSettings *settings = Core::ICore::instance()->settings(); settings->beginGroup("Find"); settings->setValue("Backward", QVariant((m_findFlags & QTextDocument::FindBackward) != 0)); settings->setValue("CaseSensitively", QVariant((m_findFlags & QTextDocument::FindCaseSensitively) != 0)); settings->setValue("WholeWords", QVariant((m_findFlags & QTextDocument::FindWholeWords) != 0)); settings->setValue("FindStrings", m_findCompletions); settings->setValue("ReplaceStrings", m_replaceCompletions); settings->endGroup(); m_findToolBar->writeSettings(); m_findDialog->writeSettings(); } void FindPlugin::readSettings() { QSettings *settings = Core::ICore::instance()->settings(); settings->beginGroup("Find"); bool block = blockSignals(true); setBackward(settings->value("Backward", false).toBool()); setCaseSensitive(settings->value("CaseSensitively", false).toBool()); setWholeWord(settings->value("WholeWords", false).toBool()); blockSignals(block); m_findCompletions = settings->value("FindStrings").toStringList(); m_replaceCompletions = settings->value("ReplaceStrings").toStringList(); m_findCompletionModel->setStringList(m_findCompletions); m_replaceCompletionModel->setStringList(m_replaceCompletions); settings->endGroup(); m_findToolBar->readSettings(); m_findDialog->readSettings(); emit findFlagsChanged(); // would have been done in the setXXX methods above } void FindPlugin::updateFindCompletion(const QString &text) { updateCompletion(text, m_findCompletions, m_findCompletionModel); } void FindPlugin::updateReplaceCompletion(const QString &text) { updateCompletion(text, m_replaceCompletions, m_replaceCompletionModel); } void FindPlugin::updateCompletion(const QString &text, QStringList &completions, QStringListModel *model) { if (text.isEmpty()) return; completions.removeAll(text); completions.prepend(text); while (completions.size() > MAX_COMPLETIONS) completions.removeLast(); model->setStringList(completions); } Q_EXPORT_PLUGIN(FindPlugin) <commit_msg>Don't try to add actions to non-existing group.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "findplugin.h" #include "textfindconstants.h" #include "currentdocumentfind.h" #include "findtoolwindow.h" #include "searchresultwindow.h" #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/actionmanager/command.h> #include <coreplugin/coreconstants.h> #include <coreplugin/icore.h> #include <extensionsystem/pluginmanager.h> #include <utils/qtcassert.h> #include <QtCore/QtPlugin> #include <QtCore/QSettings> /*! \namespace Find The Find namespace provides everything that has to do with search term based searches. */ /*! \namespace Find::Internal \internal */ /*! \namespace Find::Internal::ItemDataRoles \internal */ Q_DECLARE_METATYPE(Find::IFindFilter*) namespace { const int MAX_COMPLETIONS = 50; } using namespace Find; using namespace Find::Internal; FindPlugin::FindPlugin() : m_currentDocumentFind(0), m_findToolBar(0), m_findDialog(0), m_findCompletionModel(new QStringListModel(this)), m_replaceCompletionModel(new QStringListModel(this)) { } FindPlugin::~FindPlugin() { delete m_currentDocumentFind; delete m_findToolBar; delete m_findDialog; } bool FindPlugin::initialize(const QStringList &, QString *) { setupMenu(); m_currentDocumentFind = new CurrentDocumentFind; m_findToolBar = new FindToolBar(this, m_currentDocumentFind); m_findDialog = new FindToolWindow(this); SearchResultWindow *searchResultWindow = new SearchResultWindow; addAutoReleasedObject(searchResultWindow); return true; } void FindPlugin::extensionsInitialized() { setupFilterMenuItems(); readSettings(); } void FindPlugin::shutdown() { m_findToolBar->setVisible(false); m_findToolBar->setParent(0); m_currentDocumentFind->removeConnections(); writeSettings(); } void FindPlugin::filterChanged() { IFindFilter *changedFilter = qobject_cast<IFindFilter *>(sender()); QAction *action = m_filterActions.value(changedFilter); QTC_ASSERT(changedFilter, return); QTC_ASSERT(action, return); action->setEnabled(changedFilter->isEnabled()); bool haveEnabledFilters = false; foreach (IFindFilter *filter, m_filterActions.keys()) { if (filter->isEnabled()) { haveEnabledFilters = true; break; } } m_openFindDialog->setEnabled(haveEnabledFilters); } void FindPlugin::openFindFilter() { QAction *action = qobject_cast<QAction*>(sender()); QTC_ASSERT(action, return); IFindFilter *filter = action->data().value<IFindFilter *>(); if (m_currentDocumentFind->candidateIsEnabled()) m_currentDocumentFind->acceptCandidate(); QString currentFindString = (m_currentDocumentFind->isEnabled() ? m_currentDocumentFind->currentFindString() : ""); if (!currentFindString.isEmpty()) m_findDialog->setFindText(currentFindString); m_findDialog->open(filter); } void FindPlugin::setupMenu() { Core::ActionManager *am = Core::ICore::instance()->actionManager(); Core::ActionContainer *medit = am->actionContainer(Core::Constants::M_EDIT); Core::ActionContainer *mfind = am->createMenu(Constants::M_FIND); medit->addMenu(mfind, Core::Constants::G_EDIT_FIND); mfind->menu()->setTitle(tr("&Find/Replace")); mfind->appendGroup(Constants::G_FIND_CURRENTDOCUMENT); mfind->appendGroup(Constants::G_FIND_FILTERS); mfind->appendGroup(Constants::G_FIND_FLAGS); mfind->appendGroup(Constants::G_FIND_ACTIONS); QList<int> globalcontext = QList<int>() << Core::Constants::C_GLOBAL_ID; Core::Command *cmd; QAction *separator; separator = new QAction(this); separator->setSeparator(true); cmd = am->registerAction(separator, QLatin1String("Find.Sep.Flags"), globalcontext); mfind->addAction(cmd, Constants::G_FIND_FLAGS); separator = new QAction(this); separator->setSeparator(true); cmd = am->registerAction(separator, QLatin1String("Find.Sep.Actions"), globalcontext); mfind->addAction(cmd, Constants::G_FIND_ACTIONS); Core::ActionContainer *mfindadvanced = am->createMenu(Constants::M_FIND_ADVANCED); mfindadvanced->menu()->setTitle(tr("Advanced Find")); mfind->addMenu(mfindadvanced, Constants::G_FIND_FILTERS); m_openFindDialog = new QAction(tr("Open Advanced Find..."), this); cmd = am->registerAction(m_openFindDialog, QLatin1String("Find.Dialog"), globalcontext); cmd->setDefaultKeySequence(QKeySequence(tr("Ctrl+Shift+F"))); mfindadvanced->addAction(cmd); connect(m_openFindDialog, SIGNAL(triggered()), this, SLOT(openFindFilter())); } void FindPlugin::setupFilterMenuItems() { Core::ActionManager *am = Core::ICore::instance()->actionManager(); QList<IFindFilter*> findInterfaces = ExtensionSystem::PluginManager::instance()->getObjects<IFindFilter>(); Core::Command *cmd; QList<int> globalcontext = QList<int>() << Core::Constants::C_GLOBAL_ID; Core::ActionContainer *mfindadvanced = am->actionContainer(Constants::M_FIND_ADVANCED); m_filterActions.clear(); bool haveEnabledFilters = false; foreach (IFindFilter *filter, findInterfaces) { QAction *action = new QAction(QString(" %1").arg(filter->name()), this); bool isEnabled = filter->isEnabled(); if (isEnabled) haveEnabledFilters = true; action->setEnabled(isEnabled); action->setData(qVariantFromValue(filter)); cmd = am->registerAction(action, QLatin1String("FindFilter.")+filter->id(), globalcontext); cmd->setDefaultKeySequence(filter->defaultShortcut()); mfindadvanced->addAction(cmd); m_filterActions.insert(filter, action); connect(action, SIGNAL(triggered(bool)), this, SLOT(openFindFilter())); connect(filter, SIGNAL(changed()), this, SLOT(filterChanged())); } m_findDialog->setFindFilters(findInterfaces); m_openFindDialog->setEnabled(haveEnabledFilters); } QTextDocument::FindFlags FindPlugin::findFlags() const { return m_findFlags; } void FindPlugin::setCaseSensitive(bool sensitive) { setFindFlag(QTextDocument::FindCaseSensitively, sensitive); } void FindPlugin::setWholeWord(bool wholeOnly) { setFindFlag(QTextDocument::FindWholeWords, wholeOnly); } void FindPlugin::setBackward(bool backward) { setFindFlag(QTextDocument::FindBackward, backward); } void FindPlugin::setFindFlag(QTextDocument::FindFlag flag, bool enabled) { bool hasFlag = hasFindFlag(flag); if ((hasFlag && enabled) || (!hasFlag && !enabled)) return; if (enabled) m_findFlags |= flag; else m_findFlags &= ~flag; if (flag != QTextDocument::FindBackward) emit findFlagsChanged(); } bool FindPlugin::hasFindFlag(QTextDocument::FindFlag flag) { return m_findFlags & flag; } void FindPlugin::writeSettings() { QSettings *settings = Core::ICore::instance()->settings(); settings->beginGroup("Find"); settings->setValue("Backward", QVariant((m_findFlags & QTextDocument::FindBackward) != 0)); settings->setValue("CaseSensitively", QVariant((m_findFlags & QTextDocument::FindCaseSensitively) != 0)); settings->setValue("WholeWords", QVariant((m_findFlags & QTextDocument::FindWholeWords) != 0)); settings->setValue("FindStrings", m_findCompletions); settings->setValue("ReplaceStrings", m_replaceCompletions); settings->endGroup(); m_findToolBar->writeSettings(); m_findDialog->writeSettings(); } void FindPlugin::readSettings() { QSettings *settings = Core::ICore::instance()->settings(); settings->beginGroup("Find"); bool block = blockSignals(true); setBackward(settings->value("Backward", false).toBool()); setCaseSensitive(settings->value("CaseSensitively", false).toBool()); setWholeWord(settings->value("WholeWords", false).toBool()); blockSignals(block); m_findCompletions = settings->value("FindStrings").toStringList(); m_replaceCompletions = settings->value("ReplaceStrings").toStringList(); m_findCompletionModel->setStringList(m_findCompletions); m_replaceCompletionModel->setStringList(m_replaceCompletions); settings->endGroup(); m_findToolBar->readSettings(); m_findDialog->readSettings(); emit findFlagsChanged(); // would have been done in the setXXX methods above } void FindPlugin::updateFindCompletion(const QString &text) { updateCompletion(text, m_findCompletions, m_findCompletionModel); } void FindPlugin::updateReplaceCompletion(const QString &text) { updateCompletion(text, m_replaceCompletions, m_replaceCompletionModel); } void FindPlugin::updateCompletion(const QString &text, QStringList &completions, QStringListModel *model) { if (text.isEmpty()) return; completions.removeAll(text); completions.prepend(text); while (completions.size() > MAX_COMPLETIONS) completions.removeLast(); model->setStringList(completions); } Q_EXPORT_PLUGIN(FindPlugin) <|endoftext|>
<commit_before>// Formatting library for C++ - scanning API proof of concept // // Copyright (c) 2012 - present, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. #include <array> #include <climits> #include "fmt/format.h" #include "gmock.h" #include "gtest-extra.h" FMT_BEGIN_NAMESPACE namespace internal { struct scan_arg { type arg_type; union { int* int_value; unsigned* uint_value; long long* long_long_value; unsigned long long* ulong_long_value; std::string* string; // TODO: more types }; scan_arg() : arg_type(none_type) {} scan_arg(int& value) : arg_type(int_type), int_value(&value) {} scan_arg(unsigned& value) : arg_type(uint_type), uint_value(&value) {} scan_arg(long long& value) : arg_type(long_long_type), long_long_value(&value) {} scan_arg(unsigned long long& value) : arg_type(ulong_long_type), ulong_long_value(&value) {} scan_arg(std::string& value) : arg_type(string_type), string(&value) {} }; } // namespace internal struct scan_args { int size; const internal::scan_arg* data; template <size_t N> scan_args(const std::array<internal::scan_arg, N>& store) : size(N), data(store.data()) { static_assert(N < INT_MAX, "too many arguments"); } }; namespace internal { struct scan_handler : error_handler { private: const char* begin_; const char* end_; scan_args args_; int next_arg_id_; scan_arg arg_; template <typename T = unsigned> T read_uint() { T value = 0; while (begin_ != end_) { char c = *begin_++; if (c < '0' || c > '9') on_error("invalid input"); // TODO: check overflow value = value * 10 + (c - '0'); } return value; } template <typename T = int> T read_int() { T value = 0; bool negative = begin_ != end_ && *begin_ == '-'; if (negative) ++begin_; value = read_uint<typename std::make_unsigned<T>::type>(); if (negative) value = -value; return value; } public: scan_handler(string_view input, scan_args args) : begin_(input.data()), end_(begin_ + input.size()), args_(args), next_arg_id_(0) {} const char* pos() const { return begin_; } void on_text(const char* begin, const char* end) { auto size = end - begin; if (begin_ + size > end_ || !std::equal(begin, end, begin_)) on_error("invalid input"); begin_ += size; } void on_arg_id() { if (next_arg_id_ >= args_.size) on_error("argument index out of range"); arg_ = args_.data[next_arg_id_++]; } void on_arg_id(unsigned) { on_error("invalid format"); } void on_arg_id(string_view) { on_error("invalid format"); } void on_replacement_field(const char*) { switch (arg_.arg_type) { case int_type: *arg_.int_value = read_int(); break; case uint_type: *arg_.uint_value = read_uint(); break; case long_long_type: *arg_.long_long_value = read_int<long long>(); break; case ulong_long_type: *arg_.ulong_long_value = read_uint<unsigned long long>(); break; case string_type: { while (begin_ != end_ && *begin_ != ' ') arg_.string->push_back(*begin_++); break; } default: assert(false); } } const char* on_format_specs(const char* begin, const char*) { return begin; } }; } // namespace internal template <typename... Args> std::array<internal::scan_arg, sizeof...(Args)> make_scan_args(Args&... args) { return std::array<internal::scan_arg, sizeof...(Args)>{args...}; } string_view::iterator vscan(string_view input, string_view format_str, scan_args args) { internal::scan_handler h(input, args); internal::parse_format_string<false>(format_str, h); return input.begin() + (h.pos() - &*input.begin()); } template <typename... Args> string_view::iterator scan(string_view input, string_view format_str, Args&... args) { return vscan(input, format_str, make_scan_args(args...)); } FMT_END_NAMESPACE TEST(ScanTest, ReadText) { fmt::string_view s = "foo"; auto end = fmt::scan(s, "foo"); EXPECT_EQ(end, s.end()); EXPECT_THROW_MSG(fmt::scan("fob", "foo"), fmt::format_error, "invalid input"); } TEST(ScanTest, ReadInt) { int n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); fmt::scan("-42", "{}", n); EXPECT_EQ(n, -42); } TEST(ScanTest, ReadLongLong) { long long n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); fmt::scan("-42", "{}", n); EXPECT_EQ(n, -42); } TEST(ScanTest, ReadUInt) { unsigned n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error, "invalid input"); } TEST(ScanTest, ReadULongLong) { unsigned long long n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error, "invalid input"); } TEST(ScanTest, ReadString) { std::string s; fmt::scan("foo", "{}", s); EXPECT_EQ(s, "foo"); } TEST(ScanTest, InvalidFormat) { EXPECT_THROW_MSG(fmt::scan("", "{}"), fmt::format_error, "argument index out of range"); EXPECT_THROW_MSG(fmt::scan("", "{"), fmt::format_error, "invalid format string"); } TEST(ScanTest, Example) { std::string key; int value; fmt::scan("answer = 42", "{} = {}", key, value); EXPECT_EQ(key, "answer"); EXPECT_EQ(value, 42); } <commit_msg>Implement parsing of string_views<commit_after>// Formatting library for C++ - scanning API proof of concept // // Copyright (c) 2012 - present, Victor Zverovich // All rights reserved. // // For the license information refer to format.h. #include <array> #include <climits> #include "fmt/format.h" #include "gmock.h" #include "gtest-extra.h" FMT_BEGIN_NAMESPACE namespace internal { enum class scan_type { none_type, int_type, uint_type, long_long_type, ulong_long_type, string_type, string_view_type }; struct scan_arg { scan_type arg_type; union { int* int_value; unsigned* uint_value; long long* long_long_value; unsigned long long* ulong_long_value; std::string* string; fmt::string_view* string_view; // TODO: more types }; scan_arg() : arg_type(scan_type::none_type) {} scan_arg(int& value) : arg_type(scan_type::int_type), int_value(&value) {} scan_arg(unsigned& value) : arg_type(scan_type::uint_type), uint_value(&value) {} scan_arg(long long& value) : arg_type(scan_type::long_long_type), long_long_value(&value) {} scan_arg(unsigned long long& value) : arg_type(scan_type::ulong_long_type), ulong_long_value(&value) {} scan_arg(std::string& value) : arg_type(scan_type::string_type), string(&value) {} scan_arg(fmt::string_view& value) : arg_type(scan_type::string_view_type), string_view(&value) {} }; } // namespace internal struct scan_args { int size; const internal::scan_arg* data; template <size_t N> scan_args(const std::array<internal::scan_arg, N>& store) : size(N), data(store.data()) { static_assert(N < INT_MAX, "too many arguments"); } }; namespace internal { struct scan_handler : error_handler { private: const char* begin_; const char* end_; scan_args args_; int next_arg_id_; scan_arg arg_; template <typename T = unsigned> T read_uint() { T value = 0; while (begin_ != end_) { char c = *begin_++; if (c < '0' || c > '9') on_error("invalid input"); // TODO: check overflow value = value * 10 + (c - '0'); } return value; } template <typename T = int> T read_int() { T value = 0; bool negative = begin_ != end_ && *begin_ == '-'; if (negative) ++begin_; value = read_uint<typename std::make_unsigned<T>::type>(); if (negative) value = -value; return value; } public: scan_handler(string_view input, scan_args args) : begin_(input.data()), end_(begin_ + input.size()), args_(args), next_arg_id_(0) {} const char* pos() const { return begin_; } void on_text(const char* begin, const char* end) { auto size = end - begin; if (begin_ + size > end_ || !std::equal(begin, end, begin_)) on_error("invalid input"); begin_ += size; } void on_arg_id() { if (next_arg_id_ >= args_.size) on_error("argument index out of range"); arg_ = args_.data[next_arg_id_++]; } void on_arg_id(unsigned) { on_error("invalid format"); } void on_arg_id(string_view) { on_error("invalid format"); } void on_replacement_field(const char*) { switch (arg_.arg_type) { case scan_type::int_type: *arg_.int_value = read_int(); break; case scan_type::uint_type: *arg_.uint_value = read_uint(); break; case scan_type::long_long_type: *arg_.long_long_value = read_int<long long>(); break; case scan_type::ulong_long_type: *arg_.ulong_long_value = read_uint<unsigned long long>(); break; case scan_type::string_type: while (begin_ != end_ && *begin_ != ' ') arg_.string->push_back(*begin_++); break; case scan_type::string_view_type: { auto s = begin_; while (begin_ != end_ && *begin_ != ' ') ++begin_; *arg_.string_view = fmt::string_view(s, begin_ - s); break; } default: assert(false); } } const char* on_format_specs(const char* begin, const char*) { return begin; } }; } // namespace internal template <typename... Args> std::array<internal::scan_arg, sizeof...(Args)> make_scan_args(Args&... args) { return std::array<internal::scan_arg, sizeof...(Args)>{args...}; } string_view::iterator vscan(string_view input, string_view format_str, scan_args args) { internal::scan_handler h(input, args); internal::parse_format_string<false>(format_str, h); return input.begin() + (h.pos() - &*input.begin()); } template <typename... Args> string_view::iterator scan(string_view input, string_view format_str, Args&... args) { return vscan(input, format_str, make_scan_args(args...)); } FMT_END_NAMESPACE TEST(ScanTest, ReadText) { fmt::string_view s = "foo"; auto end = fmt::scan(s, "foo"); EXPECT_EQ(end, s.end()); EXPECT_THROW_MSG(fmt::scan("fob", "foo"), fmt::format_error, "invalid input"); } TEST(ScanTest, ReadInt) { int n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); fmt::scan("-42", "{}", n); EXPECT_EQ(n, -42); } TEST(ScanTest, ReadLongLong) { long long n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); fmt::scan("-42", "{}", n); EXPECT_EQ(n, -42); } TEST(ScanTest, ReadUInt) { unsigned n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error, "invalid input"); } TEST(ScanTest, ReadULongLong) { unsigned long long n = 0; fmt::scan("42", "{}", n); EXPECT_EQ(n, 42); EXPECT_THROW_MSG(fmt::scan("-42", "{}", n), fmt::format_error, "invalid input"); } TEST(ScanTest, ReadString) { std::string s; fmt::scan("foo", "{}", s); EXPECT_EQ(s, "foo"); } TEST(ScanTest, ReadStringView) { fmt::string_view s; fmt::scan("foo", "{}", s); EXPECT_EQ(s, "foo"); } TEST(ScanTest, InvalidFormat) { EXPECT_THROW_MSG(fmt::scan("", "{}"), fmt::format_error, "argument index out of range"); EXPECT_THROW_MSG(fmt::scan("", "{"), fmt::format_error, "invalid format string"); } TEST(ScanTest, Example) { std::string key; int value; fmt::scan("answer = 42", "{} = {}", key, value); EXPECT_EQ(key, "answer"); EXPECT_EQ(value, 42); } <|endoftext|>
<commit_before>#include <string> #include <utility> #include <vector> #include "boost/chrono.hpp" #include "boost/thread.hpp" #include "boost/thread/latch.hpp" #include "gtest/gtest.h" #include "dsb/comm/proxy.hpp" #include "dsb/comm/util.hpp" #include "dsb/execution/variable_io.hpp" #include "dsb/util.hpp" namespace { std::pair<std::string, std::string> EndpointPair() { const auto base = std::string("inproc://") + ::testing::UnitTest::GetInstance()->current_test_info()->test_case_name() + '_' + ::testing::UnitTest::GetInstance()->current_test_info()->name(); return std::make_pair(base + "1", base + "2"); } } TEST(dsb_execution, VariablePublishSubscribe) { const auto ep = EndpointPair(); auto proxy = dsb::comm::SpawnProxy(ZMQ_XSUB, ep.first, ZMQ_XPUB, ep.second); auto stopProxy = dsb::util::OnScopeExit([&]() { proxy.Stop(); }); const dsb::model::SlaveID slaveID = 1; const dsb::model::VariableID varXID = 100; const dsb::model::VariableID varYID = 200; const auto varX = dsb::model::Variable(slaveID, varXID); const auto varY = dsb::model::Variable(slaveID, varYID); auto pub = dsb::execution::VariablePublisher(); pub.Connect(ep.first, slaveID); auto sub = dsb::execution::VariableSubscriber(); sub.Connect(ep.second); sub.Subscribe(varX); boost::this_thread::sleep_for(boost::chrono::milliseconds(100)); dsb::model::StepID t = 0; // Verify that Update() times out if it doesn't receive data EXPECT_THROW(sub.Update(t, boost::chrono::milliseconds(1)), std::runtime_error); // Test transferring one variable pub.Publish(t, varXID, 123); sub.Update(t, boost::chrono::seconds(1)); EXPECT_EQ(123, boost::get<int>(sub.Value(varX))); // Verify that Value() throws on a variable which is not subscribed to EXPECT_THROW(sub.Value(varY), std::logic_error); // Verify that the current value is used, old values are discarded, and // future values are queued. ++t; pub.Publish(t-1, varXID, 123); pub.Publish(t, varXID, 456); pub.Publish(t+1, varXID, 789); sub.Update(t, boost::chrono::seconds(1)); EXPECT_EQ(456, boost::get<int>(sub.Value(varX))); // Multiple variables sub.Subscribe(varY); boost::this_thread::sleep_for(boost::chrono::milliseconds(100)); ++t; pub.Publish(t, varYID, std::string("Hello World")); sub.Update(t, boost::chrono::seconds(1)); EXPECT_EQ(789, boost::get<int>(sub.Value(varX))); EXPECT_EQ("Hello World", boost::get<std::string>(sub.Value(varY))); pub.Publish(t, varXID, 1.0); ++t; pub.Publish(t, varYID, true); EXPECT_THROW(sub.Update(t, boost::chrono::milliseconds(1)), std::runtime_error); pub.Publish(t, varXID, 2.0); sub.Update(t, boost::chrono::seconds(1)); EXPECT_EQ(2.0, boost::get<double>(sub.Value(varX))); EXPECT_TRUE(boost::get<bool>(sub.Value(varY))); // Unsubscribe to one variable ++t; sub.Unsubscribe(varX); pub.Publish(t, varXID, 100); pub.Publish(t, varYID, false); sub.Update(t, boost::chrono::seconds(1)); EXPECT_THROW(sub.Value(varX), std::logic_error); EXPECT_FALSE(boost::get<bool>(sub.Value(varY))); } TEST(dsb_execution, VariablePublishSubscribePerformance) { const int VAR_COUNT = 5000; const int STEP_COUNT = 50; // Fire up the proxy auto proxySocket1 = zmq::socket_t(dsb::comm::GlobalContext(), ZMQ_XSUB); auto proxySocket2 = zmq::socket_t(dsb::comm::GlobalContext(), ZMQ_XPUB); int zero = 0; proxySocket1.setsockopt(ZMQ_SNDHWM, &zero, sizeof(zero)); proxySocket1.setsockopt(ZMQ_RCVHWM, &zero, sizeof(zero)); proxySocket2.setsockopt(ZMQ_SNDHWM, &zero, sizeof(zero)); proxySocket2.setsockopt(ZMQ_RCVHWM, &zero, sizeof(zero)); const auto proxyPort1 = dsb::comm::BindToEphemeralPort(proxySocket1); const auto proxyPort2 = dsb::comm::BindToEphemeralPort(proxySocket2); const auto proxyEndpoint1 = "tcp://localhost:" + std::to_string(proxyPort1); const auto proxyEndpoint2 = "tcp://localhost:" + std::to_string(proxyPort2); auto proxy = dsb::comm::SpawnProxy(std::move(proxySocket1), std::move(proxySocket2)); // Prepare the list of variables const dsb::model::SlaveID publisherID = 1; std::vector<dsb::model::Variable> vars; for (int i = 1; i <= VAR_COUNT; ++i) { vars.emplace_back(publisherID, i); } boost::latch primeLatch(1); boost::barrier stepBarrier(2); auto pubThread = boost::thread( [STEP_COUNT, proxyEndpoint1, publisherID, &vars, &primeLatch, &stepBarrier] () { auto pub = dsb::execution::VariablePublisher(); pub.Connect(proxyEndpoint1, publisherID); do { for (size_t i = 0; i < vars.size(); ++i) { pub.Publish(0, vars[i].ID(), i*1.0); } } while (primeLatch.wait_for(boost::chrono::milliseconds(100)) == boost::cv_status::timeout); for (int stepID = 1; stepID <= STEP_COUNT; ++stepID) { for (size_t i = 0; i < vars.size(); ++i) { pub.Publish(stepID, vars[i].ID(), i*1.0*stepID); } stepBarrier.wait(); } }); auto sub = dsb::execution::VariableSubscriber(); sub.Connect(proxyEndpoint2); //const auto tSub = boost::chrono::steady_clock::now(); for (const auto& var : vars) sub.Subscribe(var); //const auto tPrime = boost::chrono::steady_clock::now(); for (;;) { try { sub.Update(0, boost::chrono::milliseconds(10000)); break; } catch (const std::runtime_error&) { } } primeLatch.count_down(); const auto tSim = boost::chrono::steady_clock::now(); const auto stepTimeout = boost::chrono::milliseconds(std::max(100, VAR_COUNT*10)); for (int stepID = 1; stepID <= STEP_COUNT; ++stepID) { // NOTE: If an exeption is thrown here (typically due to timeout), // stepBarrier will be destroyed while the other thread is still waiting // for it, triggering an assertion failure in the barrier destructor: // // boost::condition_variable::~condition_variable(): Assertion `!ret' failed. // // The solution is to increase the timeout -- or improve performance. ;) sub.Update(stepID, stepTimeout); for (size_t i = 0; i < vars.size(); ++i) { ASSERT_EQ(i*1.0*stepID, boost::get<double>(sub.Value(vars[i]))); } stepBarrier.wait(); } const auto tStop = boost::chrono::steady_clock::now(); pubThread.join(); proxy.Stop(true); // Throughput = average number of variable values transferred per second const auto throughput = STEP_COUNT * VAR_COUNT * (1e9 / boost::chrono::duration_cast<boost::chrono::nanoseconds>(tStop-tSim).count());(STEP_COUNT*VAR_COUNT*1e9/boost::chrono::duration_cast<boost::chrono::nanoseconds>(tStop-tSim).count()); EXPECT_GT(throughput, 10000.0); /* std::cout << "\nSubscription time: " << boost::chrono::duration_cast<boost::chrono::milliseconds>(tPrime-tSub) << "\nPriming time : " << boost::chrono::duration_cast<boost::chrono::milliseconds>(tSim-tPrime) << "\nTotal sim time : " << boost::chrono::duration_cast<boost::chrono::milliseconds>(tStop-tSim) << "\nStep time : " << (boost::chrono::duration_cast<boost::chrono::microseconds>(tStop-tSim)/STEP_COUNT) << " (" << STEP_COUNT << " steps)" << "\nPer-var time : " << (boost::chrono::duration_cast<boost::chrono::nanoseconds>(tStop-tSim)/(STEP_COUNT*VAR_COUNT)) << " (" << VAR_COUNT << " vars)" << "\nThroughput : " << throughput << " vars/second" << std::endl; */ } <commit_msg>Fix performance test for Windows and raise the bar<commit_after>#ifdef _WIN32 # define NOMINMAX #endif #include <algorithm> #include <string> #include <utility> #include <vector> #include "boost/chrono.hpp" #include "boost/thread.hpp" #include "boost/thread/latch.hpp" #include "gtest/gtest.h" #include "dsb/comm/proxy.hpp" #include "dsb/comm/util.hpp" #include "dsb/execution/variable_io.hpp" #include "dsb/util.hpp" namespace { std::pair<std::string, std::string> EndpointPair() { const auto base = std::string("inproc://") + ::testing::UnitTest::GetInstance()->current_test_info()->test_case_name() + '_' + ::testing::UnitTest::GetInstance()->current_test_info()->name(); return std::make_pair(base + "1", base + "2"); } } TEST(dsb_execution, VariablePublishSubscribe) { const auto ep = EndpointPair(); auto proxy = dsb::comm::SpawnProxy(ZMQ_XSUB, ep.first, ZMQ_XPUB, ep.second); auto stopProxy = dsb::util::OnScopeExit([&]() { proxy.Stop(); }); const dsb::model::SlaveID slaveID = 1; const dsb::model::VariableID varXID = 100; const dsb::model::VariableID varYID = 200; const auto varX = dsb::model::Variable(slaveID, varXID); const auto varY = dsb::model::Variable(slaveID, varYID); auto pub = dsb::execution::VariablePublisher(); pub.Connect(ep.first, slaveID); auto sub = dsb::execution::VariableSubscriber(); sub.Connect(ep.second); sub.Subscribe(varX); boost::this_thread::sleep_for(boost::chrono::milliseconds(100)); dsb::model::StepID t = 0; // Verify that Update() times out if it doesn't receive data EXPECT_THROW(sub.Update(t, boost::chrono::milliseconds(1)), std::runtime_error); // Test transferring one variable pub.Publish(t, varXID, 123); sub.Update(t, boost::chrono::seconds(1)); EXPECT_EQ(123, boost::get<int>(sub.Value(varX))); // Verify that Value() throws on a variable which is not subscribed to EXPECT_THROW(sub.Value(varY), std::logic_error); // Verify that the current value is used, old values are discarded, and // future values are queued. ++t; pub.Publish(t-1, varXID, 123); pub.Publish(t, varXID, 456); pub.Publish(t+1, varXID, 789); sub.Update(t, boost::chrono::seconds(1)); EXPECT_EQ(456, boost::get<int>(sub.Value(varX))); // Multiple variables sub.Subscribe(varY); boost::this_thread::sleep_for(boost::chrono::milliseconds(100)); ++t; pub.Publish(t, varYID, std::string("Hello World")); sub.Update(t, boost::chrono::seconds(1)); EXPECT_EQ(789, boost::get<int>(sub.Value(varX))); EXPECT_EQ("Hello World", boost::get<std::string>(sub.Value(varY))); pub.Publish(t, varXID, 1.0); ++t; pub.Publish(t, varYID, true); EXPECT_THROW(sub.Update(t, boost::chrono::milliseconds(1)), std::runtime_error); pub.Publish(t, varXID, 2.0); sub.Update(t, boost::chrono::seconds(1)); EXPECT_EQ(2.0, boost::get<double>(sub.Value(varX))); EXPECT_TRUE(boost::get<bool>(sub.Value(varY))); // Unsubscribe to one variable ++t; sub.Unsubscribe(varX); pub.Publish(t, varXID, 100); pub.Publish(t, varYID, false); sub.Update(t, boost::chrono::seconds(1)); EXPECT_THROW(sub.Value(varX), std::logic_error); EXPECT_FALSE(boost::get<bool>(sub.Value(varY))); } TEST(dsb_execution, VariablePublishSubscribePerformance) { const int VAR_COUNT = 5000; const int STEP_COUNT = 50; // Fire up the proxy auto proxySocket1 = zmq::socket_t(dsb::comm::GlobalContext(), ZMQ_XSUB); auto proxySocket2 = zmq::socket_t(dsb::comm::GlobalContext(), ZMQ_XPUB); int zero = 0; proxySocket1.setsockopt(ZMQ_SNDHWM, &zero, sizeof(zero)); proxySocket1.setsockopt(ZMQ_RCVHWM, &zero, sizeof(zero)); proxySocket2.setsockopt(ZMQ_SNDHWM, &zero, sizeof(zero)); proxySocket2.setsockopt(ZMQ_RCVHWM, &zero, sizeof(zero)); const auto proxyPort1 = dsb::comm::BindToEphemeralPort(proxySocket1); const auto proxyPort2 = dsb::comm::BindToEphemeralPort(proxySocket2); const auto proxyEndpoint1 = "tcp://localhost:" + std::to_string(proxyPort1); const auto proxyEndpoint2 = "tcp://localhost:" + std::to_string(proxyPort2); auto proxy = dsb::comm::SpawnProxy(std::move(proxySocket1), std::move(proxySocket2)); // Prepare the list of variables const dsb::model::SlaveID publisherID = 1; std::vector<dsb::model::Variable> vars; for (int i = 1; i <= VAR_COUNT; ++i) { vars.emplace_back(publisherID, i); } boost::latch primeLatch(1); boost::barrier stepBarrier(2); auto pubThread = boost::thread( [STEP_COUNT, proxyEndpoint1, publisherID, &vars, &primeLatch, &stepBarrier] () { dsb::execution::VariablePublisher pub; pub.Connect(proxyEndpoint1, publisherID); do { for (size_t i = 0; i < vars.size(); ++i) { pub.Publish(0, vars[i].ID(), i*1.0); } } while (primeLatch.wait_for(boost::chrono::milliseconds(100)) == boost::cv_status::timeout); for (int stepID = 1; stepID <= STEP_COUNT; ++stepID) { for (size_t i = 0; i < vars.size(); ++i) { pub.Publish(stepID, vars[i].ID(), i*1.0*stepID); } stepBarrier.wait(); } }); dsb::execution::VariableSubscriber sub; sub.Connect(proxyEndpoint2); //const auto tSub = boost::chrono::steady_clock::now(); for (const auto& var : vars) sub.Subscribe(var); //const auto tPrime = boost::chrono::steady_clock::now(); for (;;) { try { sub.Update(0, boost::chrono::milliseconds(10000)); break; } catch (const std::runtime_error&) { } } primeLatch.count_down(); const auto tSim = boost::chrono::steady_clock::now(); const auto stepTimeout = boost::chrono::milliseconds(std::max(100, VAR_COUNT*10)); for (int stepID = 1; stepID <= STEP_COUNT; ++stepID) { // NOTE: If an exeption is thrown here (typically due to timeout), // stepBarrier will be destroyed while the other thread is still waiting // for it, triggering an assertion failure in the barrier destructor: // // boost::condition_variable::~condition_variable(): Assertion `!ret' failed. // // The solution is to increase the timeout -- or improve performance. ;) sub.Update(stepID, stepTimeout); for (size_t i = 0; i < vars.size(); ++i) { ASSERT_EQ(i*1.0*stepID, boost::get<double>(sub.Value(vars[i]))); } stepBarrier.wait(); } const auto tStop = boost::chrono::steady_clock::now(); pubThread.join(); proxy.Stop(true); // Throughput = average number of variable values transferred per second const auto throughput = STEP_COUNT * VAR_COUNT * (1e9 / boost::chrono::duration_cast<boost::chrono::nanoseconds>(tStop-tSim).count());(STEP_COUNT*VAR_COUNT*1e9/boost::chrono::duration_cast<boost::chrono::nanoseconds>(tStop-tSim).count()); EXPECT_GT(throughput, 50000.0); /* std::cout << "\nSubscription time: " << boost::chrono::duration_cast<boost::chrono::milliseconds>(tPrime-tSub) << "\nPriming time : " << boost::chrono::duration_cast<boost::chrono::milliseconds>(tSim-tPrime) << "\nTotal sim time : " << boost::chrono::duration_cast<boost::chrono::milliseconds>(tStop-tSim) << "\nStep time : " << (boost::chrono::duration_cast<boost::chrono::microseconds>(tStop-tSim)/STEP_COUNT) << " (" << STEP_COUNT << " steps)" << "\nPer-var time : " << (boost::chrono::duration_cast<boost::chrono::nanoseconds>(tStop-tSim)/(STEP_COUNT*VAR_COUNT)) << " (" << VAR_COUNT << " vars)" << "\nThroughput : " << throughput << " vars/second" << std::endl; */ } <|endoftext|>
<commit_before>// // (c) 2019 Eduardo Doria. // #include "KeyframeTrack.h" #include "Log.h" using namespace Supernova; KeyframeTrack::KeyframeTrack(): TimeAction(){ this->index = 0; this->progress = 0; } KeyframeTrack::KeyframeTrack(std::vector<float> times): TimeAction(){ setTimes(times); this->index = 0; this->progress = 0; } void KeyframeTrack::setTimes(std::vector<float> times){ this->times = times; } std::vector<float> KeyframeTrack::getTimes(){ return times; } bool KeyframeTrack::stop(){ if (!Action::stop()) return false; index = 0; progress = 0; return true; } bool KeyframeTrack::update(float interval){ if (!TimeAction::update(interval)) return false; if (times.size() == 0) return false; float actualTime = duration * value; if (actualTime < times[0]) { index = 0; progress = 0; return true; } index = 0; while ((index+1) < times.size() && times[index+1] < actualTime){ index++; } return true; } <commit_msg>Fixed Keyframe bug when loop animation<commit_after>// // (c) 2019 Eduardo Doria. // #include "KeyframeTrack.h" #include "Log.h" using namespace Supernova; KeyframeTrack::KeyframeTrack(): TimeAction(){ this->index = 0; this->progress = 0; } KeyframeTrack::KeyframeTrack(std::vector<float> times): TimeAction(){ setTimes(times); this->index = 0; this->progress = 0; } void KeyframeTrack::setTimes(std::vector<float> times){ this->times = times; } std::vector<float> KeyframeTrack::getTimes(){ return times; } bool KeyframeTrack::stop(){ if (!TimeAction::stop()) return false; index = 0; progress = 0; return true; } bool KeyframeTrack::update(float interval){ if (!TimeAction::update(interval)) return false; if (times.size() == 0) return false; float actualTime = duration * value; if (actualTime < times[0]) { index = 0; progress = 0; return true; } index = 0; while ((index+1) < times.size() && times[index+1] < actualTime){ index++; } return true; } <|endoftext|>
<commit_before>#ifndef DEVICEFILTER_HPP #define DEVICEFILTER_HPP #include "bridge.h" #include "CommonData.hpp" #include "DeviceFilter.hpp" #include "IOLogWrapper.hpp" #include "RemapFilterBase.hpp" namespace org_pqrs_Karabiner { namespace RemapFilter { class DeviceFilter : public RemapFilterBase { public: DeviceFilter(unsigned int type) : RemapFilterBase(type) {}; void initialize(const unsigned int* vec, size_t length) { for (size_t i = 0; i < length - 2; i += 3) { targets_.push_back(DeviceIdentifier(DeviceVendor(vec[i]), DeviceProduct(vec[i + 1]), DeviceLocation(vec[i + 2]))); } if (length % 3 > 0) { IOLOG_WARN("Invalid length(%d) in BRIDGE_FILTERTYPE_DEVICE_*\n", static_cast<int>(length)); } } bool isblocked(void) { if (get_type() == BRIDGE_FILTERTYPE_DEVICE_NOT || get_type() == BRIDGE_FILTERTYPE_DEVICE_ONLY) { bool isnot = (get_type() == BRIDGE_FILTERTYPE_DEVICE_NOT); for (size_t i = 0; i < targets_.size(); ++i) { DeviceIdentifier& v = targets_[i]; if (CommonData::getcurrent_deviceIdentifier().isEqual(v)) { return isnot ? true : false; } } return isnot ? false : true; } IOLOG_ERROR("DeviceFilter::isblocked unknown type(%d)\n", get_type()); return false; } private: Vector_DeviceIdentifier targets_; }; } } #endif <commit_msg>addLine<commit_after>#ifndef DEVICEFILTER_HPP #define DEVICEFILTER_HPP #include "bridge.h" #include "CommonData.hpp" #include "DeviceFilter.hpp" #include "IOLogWrapper.hpp" #include "RemapFilterBase.hpp" namespace org_pqrs_Karabiner { namespace RemapFilter { class DeviceFilter : public RemapFilterBase { public: DeviceFilter(unsigned int type) : RemapFilterBase(type) {}; void initialize(const unsigned int* vec, size_t length) { for (size_t i = 0; i < length - 2; i += 3) { targets_.push_back(DeviceIdentifier(DeviceVendor(vec[i]), DeviceProduct(vec[i + 1]), DeviceLocation(vec[i + 2]))); } if (length % 3 > 0) { IOLOG_WARN("Invalid length(%d) in BRIDGE_FILTERTYPE_DEVICE_*\n", static_cast<int>(length)); } } bool isblocked(void) { if (get_type() == BRIDGE_FILTERTYPE_DEVICE_NOT || get_type() == BRIDGE_FILTERTYPE_DEVICE_ONLY) { bool isnot = (get_type() == BRIDGE_FILTERTYPE_DEVICE_NOT); for (size_t i = 0; i < targets_.size(); ++i) { DeviceIdentifier& v = targets_[i]; if (CommonData::getcurrent_deviceIdentifier().isEqual(v)) { return isnot ? true : false; } } return isnot ? false : true; } IOLOG_ERROR("DeviceFilter::isblocked unknown type(%d)\n", get_type()); return false; } private: Vector_DeviceIdentifier targets_; }; } } #endif <|endoftext|>
<commit_before>/** @copyright * Copyright (c) 2017 Stuart W Baker * 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 MCP2515Can.cxx * This file implements the CAN driver for the MCP2515 CAN Controller. * * @author Stuart W. Baker * @date 3 January 2017 */ #include "MCP2515Can.hxx" #include <fcntl.h> #include <compiler.h> const MCP2515Can::MCP2515Baud MCP2515Can::BAUD_TABLE[] = { /* 20 MHz clock source * TQ = (2 * BRP) / freq = (2 * 5) / 20 MHz = 500 nsec * Baud = 125 kHz * bit time = 1 / 125 kHz = 8 usec = 16 TQ * SyncSeg = 1 TQ * PropSeg = 7 TQ * PS1 = 4 TQ * PS2 = 4 TQ * sample time = (1 TQ + 7 TQ + 4 TQ) / 16 TQ = 75% * SJW = PS2 - 1 = 4 - 1 = 3 * SJW = 3 * 500 nsec = 1.5 usec * * Oscillator Tolerance: * 4 / (2 * ((13 * 16) - 4)) = 0.980% * 3 / (20 * 16) = 0.938% * = 0.938% */ {20000000, 125000, {(5 - 1), (3 - 1)}, {(7 - 1), (4 - 1), 0, 1}, {(4 - 1), 0, 0}}, /* 8 MHz clock source * TQ = (2 * BRP) / freq = (2 * 2) / 8 MHz = 500 nsec * Baud = 125 kHz * bit time = 1 / 125 kHz = 8 usec = 16 TQ * SyncSeg = 1 TQ * PropSeg = 7 TQ * PS1 = 4 TQ * PS2 = 4 TQ * sample time = (1 TQ + 7 TQ + 4 TQ) / 16 TQ = 75% * SJW = PS2 - 1 = 4 - 1 = 3 * SJW = 3 * 500 nsec = 1.5 usec * * Oscillator Tolerance: * 4 / (2 * ((13 * 16) - 4)) = 0.980% * 3 / (20 * 16) = 0.938% * = 0.938% */ {8000000, 125000, {(2 - 1), (3 - 1)}, {(7 - 1), (4 - 1), 0, 1}, {(4 - 1), 0, 0}} }; /* * init() */ void MCP2515Can::init(const char *spi_name, uint32_t freq, uint32_t baud) { spiFd_ = ::open(spi_name, O_RDWR); HASSERT(spiFd_ >= 0); ::ioctl(spiFd_, SPI_IOC_GET_OBJECT_REFERENCE, &spi_); HASSERT(spi_); /* configure SPI bus settings */ uint8_t spi_mode = SPI_MODE_0; uint8_t spi_bpw = 8; uint32_t spi_max_speed_hz = freq / 2; if (spi_max_speed_hz > SPI_MAX_SPEED_HZ) { spi_max_speed_hz = SPI_MAX_SPEED_HZ; } ::ioctl(spiFd_, SPI_IOC_WR_MODE, &spi_mode); ::ioctl(spiFd_, SPI_IOC_WR_BITS_PER_WORD, &spi_bpw); ::ioctl(spiFd_, SPI_IOC_WR_MAX_SPEED_HZ, &spi_max_speed_hz); /* reset device */ reset(); /* wait until device is in configuration mode */ while ((register_read(CANSTAT) & 0xE0) != 0x80); /* find valid timing settings for the requested frequency and buad rates */ for (size_t i = 0; i < ARRAYSIZE(BAUD_TABLE); ++i) { if (BAUD_TABLE[i].freq_ == freq && BAUD_TABLE[i].baud_ == baud) { register_write(CNF1, BAUD_TABLE[i].cnf1_.data_); register_write(CNF2, BAUD_TABLE[i].cnf2_.data_); register_write(CNF3, BAUD_TABLE[i].cnf3_.data_); /* setup RX Buf 0 to receive any message, and if RX Buf 0 is full, * the new message will roll over into RX Buf 1 */ register_write(RXB0CTRL, 0x64); register_write(RXB1CTRL, 0x60); /* setup TXnRTS and RXnBF pins as inputs and outputs respectively */ register_write(BFPCTRL, 0x0C | (gpoData_ << 4)); register_write(TXRTSCTRL, 0x00); gpiData_ = (register_read(TXRTSCTRL) >> 3) & 0x7; /* put the device into normal operation mode */ register_write(CANCTRL, 0x00); /* wait until device is in normal mode */ while ((register_read(CANSTAT) & 0xE0) != 0x00); return; } } /* unsupported frequency */ HASSERT(0); } /* * enable() */ void MCP2515Can::enable() { /* there is a mutex lock above us, so the following sequence is atomic */ if (!is_created()) { /* start the thread at the highest priority in the system */ start(name, get_priority_max(), 2048); } /* clear interrupt flags */ register_write(CANINTF, 0); /* enable error and receive interrupts */ register_write(CANINTE, MERR | ERRI | RX1I | RX0I); interruptEnable_(); } /* * disable() */ void MCP2515Can::disable() { interruptDisable_(); /* disable all interrupt sources */ register_write(CANINTE, 0); register_write(TXB0CTRL, 0x00); register_write(TXB1CTRL, 0x00); portENTER_CRITICAL(); /* flush out any transmit data in the pipleline */ txBuf->flush(); txPending_ = 0; portEXIT_CRITICAL(); } /* * tx_msg_locked() */ __attribute__((optimize("-O3"))) void MCP2515Can::tx_msg_locked() { #if MCP2515_NULL_TX /* throw away the CAN frames after consuming them */ struct can_frame *can_frame; portENTER_CRITICAL(); if (txBuf->data_read_pointer(&can_frame)) { txBuf->consume(1); txBuf->signal_condition(); } portEXIT_CRITICAL(); #else /* the node lock_ will be locked by the caller */ if (txPending_ < 3) { struct can_frame *can_frame; /* find an empty buffer */ int index = (txPending_ & 0x1) ? 1 : 0; portENTER_CRITICAL(); if (txBuf->data_read_pointer(&can_frame)) { /* build up a transmit BufferWrite structure */ BufferWrite buffer(index, can_frame); txBuf->consume(1); portEXIT_CRITICAL(); /* bump up priority of the other buffer so it will * transmit first if it is pending */ bit_modify(index == 0 ? TXB1CTRL : TXB0CTRL, 0x01, 0x03); /* load the tranmit buffer */ buffer_write(&buffer, index, can_frame); txPending_ |= (0x1 << index); /* request to send at lowest priority */ bit_modify(index == 0 ? TXB0CTRL : TXB1CTRL, 0x08, 0x0B); bit_modify(CANINTE, TX0I << index, TX0I << index); txBuf->signal_condition(); } else { portEXIT_CRITICAL(); } } #endif } /* * entry() */ __attribute__((optimize("-O3"))) void *MCP2515Can::entry() { for ( ; /* forever */ ; ) { #if MCP2515_DEBUG int result = sem.timedwait(SEC_TO_NSEC(1)); if (result != 0) { lock_.lock(); spi_ioc_transfer xfer[2]; memset(xfer, 0, sizeof(xfer)); uint8_t wr_data[2] = {READ, 0}; xfer[0].tx_buf = (unsigned long)wr_data; xfer[0].len = sizeof(wr_data); xfer[1].rx_buf = (unsigned long)regs; xfer[1].len = sizeof(regs); xfer[1].cs_change = 1; ::ioctl(spiFd_, SPI_IOC_MESSAGE(2), xfer); lock_.unlock(); continue; } #else sem_.wait(); #endif lock_.lock(); spi_->csDeassert(); /* read status flags */ uint8_t canintf = register_read(CANINTF); if (UNLIKELY((canintf & ERRI)) || UNLIKELY((canintf & MERR))) { /* error handling, read error flag register */ uint8_t eflg = register_read(EFLG); /* clear error status flag */ bit_modify(CANINTF, 0, ERRI | MERR); if (eflg & (RX0OVR | RX1OVR)) { /* receive overrun */ ++overrunCount; /* clear error flag */ bit_modify(EFLG, 0, (RX0OVR | RX1OVR)); } if (eflg & TXBO) { /* bus off */ ++busOffCount; } if ((eflg & TXEP) || (eflg & RXEP)) { /* error passive state */ ++softErrorCount; /* flush out any transmit data in the pipleline */ register_write(TXB0CTRL, 0x00); register_write(TXB1CTRL, 0x00); bit_modify(CANINTE, 0, TX0I | TX1I); bit_modify(CANINTF, 0, TX0I | TX1I); portENTER_CRITICAL(); txBuf->flush(); portEXIT_CRITICAL(); txBuf->signal_condition(); txPending_ = 0; } } if (canintf & RX0I) { { /* receive interrupt active */ BufferRead buffer(0); buffer_read(&buffer, 0); struct can_frame *can_frame; portENTER_CRITICAL(); if (LIKELY(rxBuf->data_write_pointer(&can_frame))) { buffer.build_struct_can_frame(can_frame); rxBuf->advance(1); spi_->csAssert(); rxBuf->signal_condition(); spi_->csDeassert(); ++numReceivedPackets_; } else { /* receive overrun occured */ ++overrunCount; } portEXIT_CRITICAL(); } /* RX Buf 1 can only be full if RX Buf 0 was also previously full. * It is extremely unlikely that RX Buf 1 will ever be full. */ if (UNLIKELY(canintf & RX1I)) { /* receive interrupt active */ BufferRead buffer(1); buffer_read(&buffer, 1); struct can_frame *can_frame; portENTER_CRITICAL(); if (LIKELY(rxBuf->data_write_pointer(&can_frame))) { buffer.build_struct_can_frame(can_frame); rxBuf->advance(1); spi_->csAssert(); rxBuf->signal_condition(); spi_->csDeassert(); ++numReceivedPackets_; } else { /* receive overrun occured */ ++overrunCount; } portEXIT_CRITICAL(); } } if (txPending_) { /* transmit interrupt active and transmission complete */ if (canintf & TX0I) { txPending_ &= ~0x1; bit_modify(CANINTE, 0, TX0I); bit_modify(CANINTF, 0, TX0I); ++numTransmittedPackets_; } if (canintf & TX1I) { txPending_ &= ~0x2; bit_modify(CANINTE, 0, TX1I); bit_modify(CANINTF, 0, TX1I); ++numTransmittedPackets_; } while (txPending_ < 3) { struct can_frame *can_frame; /* find an empty buffer */ int index = (txPending_ & 0x1) ? 1 : 0; portENTER_CRITICAL(); if (txBuf->data_read_pointer(&can_frame)) { /* build up a transmit BufferWrite structure */ BufferWrite buffer(index, can_frame); txBuf->consume(1); portEXIT_CRITICAL(); /* bump up priority of the other buffer so it will * transmit first if it is pending */ bit_modify(index == 0 ? TXB1CTRL : TXB0CTRL, 0x01, 0x03); /* load the tranmit buffer */ buffer_write(&buffer, index, can_frame); txPending_ |= (0x1 << index); /* request to send at lowest priority */ bit_modify(index == 0 ? TXB0CTRL : TXB1CTRL, 0x08, 0x0B); bit_modify(CANINTE, TX0I << index, TX0I << index); txBuf->signal_condition(); } else { portEXIT_CRITICAL(); break; } } } if (UNLIKELY(ioPending_)) { ioPending_ = false; /* write the latest GPO data */ register_write(BFPCTRL, 0x0C | (gpoData_ << 4)); /* get the latest GPI data */ gpiData_ = (register_read(TXRTSCTRL) >> 3) & 0x7; } spi_->csAssert(); lock_.unlock(); spi_->csDeassert(); interruptEnable_(); } return NULL; } /* * interrupt_handler() */ __attribute__((optimize("-O3"))) void MCP2515Can::interrupt_handler() { spi_->csAssert(); int woken = false; interruptDisable_(); sem_.post_from_isr(&woken); os_isr_exit_yield_test(woken); } <commit_msg>Fix instrumentation<commit_after>/** @copyright * Copyright (c) 2017 Stuart W Baker * 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 MCP2515Can.cxx * This file implements the CAN driver for the MCP2515 CAN Controller. * * @author Stuart W. Baker * @date 3 January 2017 */ #include "MCP2515Can.hxx" #include <fcntl.h> #include <compiler.h> const MCP2515Can::MCP2515Baud MCP2515Can::BAUD_TABLE[] = { /* 20 MHz clock source * TQ = (2 * BRP) / freq = (2 * 5) / 20 MHz = 500 nsec * Baud = 125 kHz * bit time = 1 / 125 kHz = 8 usec = 16 TQ * SyncSeg = 1 TQ * PropSeg = 7 TQ * PS1 = 4 TQ * PS2 = 4 TQ * sample time = (1 TQ + 7 TQ + 4 TQ) / 16 TQ = 75% * SJW = PS2 - 1 = 4 - 1 = 3 * SJW = 3 * 500 nsec = 1.5 usec * * Oscillator Tolerance: * 4 / (2 * ((13 * 16) - 4)) = 0.980% * 3 / (20 * 16) = 0.938% * = 0.938% */ {20000000, 125000, {(5 - 1), (3 - 1)}, {(7 - 1), (4 - 1), 0, 1}, {(4 - 1), 0, 0}}, /* 8 MHz clock source * TQ = (2 * BRP) / freq = (2 * 2) / 8 MHz = 500 nsec * Baud = 125 kHz * bit time = 1 / 125 kHz = 8 usec = 16 TQ * SyncSeg = 1 TQ * PropSeg = 7 TQ * PS1 = 4 TQ * PS2 = 4 TQ * sample time = (1 TQ + 7 TQ + 4 TQ) / 16 TQ = 75% * SJW = PS2 - 1 = 4 - 1 = 3 * SJW = 3 * 500 nsec = 1.5 usec * * Oscillator Tolerance: * 4 / (2 * ((13 * 16) - 4)) = 0.980% * 3 / (20 * 16) = 0.938% * = 0.938% */ {8000000, 125000, {(2 - 1), (3 - 1)}, {(7 - 1), (4 - 1), 0, 1}, {(4 - 1), 0, 0}} }; /* * init() */ void MCP2515Can::init(const char *spi_name, uint32_t freq, uint32_t baud) { spiFd_ = ::open(spi_name, O_RDWR); HASSERT(spiFd_ >= 0); ::ioctl(spiFd_, SPI_IOC_GET_OBJECT_REFERENCE, &spi_); HASSERT(spi_); /* configure SPI bus settings */ uint8_t spi_mode = SPI_MODE_0; uint8_t spi_bpw = 8; uint32_t spi_max_speed_hz = freq / 2; if (spi_max_speed_hz > SPI_MAX_SPEED_HZ) { spi_max_speed_hz = SPI_MAX_SPEED_HZ; } ::ioctl(spiFd_, SPI_IOC_WR_MODE, &spi_mode); ::ioctl(spiFd_, SPI_IOC_WR_BITS_PER_WORD, &spi_bpw); ::ioctl(spiFd_, SPI_IOC_WR_MAX_SPEED_HZ, &spi_max_speed_hz); /* reset device */ reset(); /* wait until device is in configuration mode */ while ((register_read(CANSTAT) & 0xE0) != 0x80); /* find valid timing settings for the requested frequency and buad rates */ for (size_t i = 0; i < ARRAYSIZE(BAUD_TABLE); ++i) { if (BAUD_TABLE[i].freq_ == freq && BAUD_TABLE[i].baud_ == baud) { register_write(CNF1, BAUD_TABLE[i].cnf1_.data_); register_write(CNF2, BAUD_TABLE[i].cnf2_.data_); register_write(CNF3, BAUD_TABLE[i].cnf3_.data_); /* setup RX Buf 0 to receive any message, and if RX Buf 0 is full, * the new message will roll over into RX Buf 1 */ register_write(RXB0CTRL, 0x64); register_write(RXB1CTRL, 0x60); /* setup TXnRTS and RXnBF pins as inputs and outputs respectively */ register_write(BFPCTRL, 0x0C | (gpoData_ << 4)); register_write(TXRTSCTRL, 0x00); gpiData_ = (register_read(TXRTSCTRL) >> 3) & 0x7; /* put the device into normal operation mode */ register_write(CANCTRL, 0x00); /* wait until device is in normal mode */ while ((register_read(CANSTAT) & 0xE0) != 0x00); return; } } /* unsupported frequency */ HASSERT(0); } /* * enable() */ void MCP2515Can::enable() { /* there is a mutex lock above us, so the following sequence is atomic */ if (!is_created()) { /* start the thread at the highest priority in the system */ start(name, get_priority_max(), 2048); } /* clear interrupt flags */ register_write(CANINTF, 0); /* enable error and receive interrupts */ register_write(CANINTE, MERR | ERRI | RX1I | RX0I); interruptEnable_(); } /* * disable() */ void MCP2515Can::disable() { interruptDisable_(); /* disable all interrupt sources */ register_write(CANINTE, 0); register_write(TXB0CTRL, 0x00); register_write(TXB1CTRL, 0x00); portENTER_CRITICAL(); /* flush out any transmit data in the pipleline */ txBuf->flush(); txPending_ = 0; portEXIT_CRITICAL(); } /* * tx_msg_locked() */ __attribute__((optimize("-O3"))) void MCP2515Can::tx_msg_locked() { #if MCP2515_NULL_TX /* throw away the CAN frames after consuming them */ struct can_frame *can_frame; portENTER_CRITICAL(); if (txBuf->data_read_pointer(&can_frame)) { txBuf->consume(1); txBuf->signal_condition(); } portEXIT_CRITICAL(); #else /* the node lock_ will be locked by the caller */ if (txPending_ < 3) { struct can_frame *can_frame; /* find an empty buffer */ int index = (txPending_ & 0x1) ? 1 : 0; portENTER_CRITICAL(); if (txBuf->data_read_pointer(&can_frame)) { /* build up a transmit BufferWrite structure */ BufferWrite buffer(index, can_frame); txBuf->consume(1); portEXIT_CRITICAL(); /* bump up priority of the other buffer so it will * transmit first if it is pending */ bit_modify(index == 0 ? TXB1CTRL : TXB0CTRL, 0x01, 0x03); /* load the tranmit buffer */ buffer_write(&buffer, index, can_frame); txPending_ |= (0x1 << index); /* request to send at lowest priority */ bit_modify(index == 0 ? TXB0CTRL : TXB1CTRL, 0x08, 0x0B); bit_modify(CANINTE, TX0I << index, TX0I << index); txBuf->signal_condition(); } else { portEXIT_CRITICAL(); } } #endif } /* * entry() */ __attribute__((optimize("-O3"))) void *MCP2515Can::entry() { for ( ; /* forever */ ; ) { #if MCP2515_DEBUG int result = sem_.timedwait(SEC_TO_NSEC(1)); if (result != 0) { lock_.lock(); spi_ioc_transfer xfer[2]; memset(xfer, 0, sizeof(xfer)); uint8_t wr_data[2] = {READ, 0}; xfer[0].tx_buf = (unsigned long)wr_data; xfer[0].len = sizeof(wr_data); xfer[1].rx_buf = (unsigned long)regs_; xfer[1].len = sizeof(regs_); xfer[1].cs_change = 1; ::ioctl(spiFd_, SPI_IOC_MESSAGE(2), xfer); lock_.unlock(); continue; } #else sem_.wait(); #endif lock_.lock(); spi_->csDeassert(); /* read status flags */ uint8_t canintf = register_read(CANINTF); if (UNLIKELY((canintf & ERRI)) || UNLIKELY((canintf & MERR))) { /* error handling, read error flag register */ uint8_t eflg = register_read(EFLG); /* clear error status flag */ bit_modify(CANINTF, 0, ERRI | MERR); if (eflg & (RX0OVR | RX1OVR)) { /* receive overrun */ ++overrunCount; /* clear error flag */ bit_modify(EFLG, 0, (RX0OVR | RX1OVR)); } if (eflg & TXBO) { /* bus off */ ++busOffCount; } if ((eflg & TXEP) || (eflg & RXEP)) { /* error passive state */ ++softErrorCount; /* flush out any transmit data in the pipleline */ register_write(TXB0CTRL, 0x00); register_write(TXB1CTRL, 0x00); bit_modify(CANINTE, 0, TX0I | TX1I); bit_modify(CANINTF, 0, TX0I | TX1I); portENTER_CRITICAL(); txBuf->flush(); portEXIT_CRITICAL(); txBuf->signal_condition(); txPending_ = 0; } } if (canintf & RX0I) { { /* receive interrupt active */ BufferRead buffer(0); buffer_read(&buffer, 0); struct can_frame *can_frame; portENTER_CRITICAL(); if (LIKELY(rxBuf->data_write_pointer(&can_frame))) { buffer.build_struct_can_frame(can_frame); rxBuf->advance(1); spi_->csAssert(); rxBuf->signal_condition(); spi_->csDeassert(); ++numReceivedPackets_; } else { /* receive overrun occured */ ++overrunCount; } portEXIT_CRITICAL(); } /* RX Buf 1 can only be full if RX Buf 0 was also previously full. * It is extremely unlikely that RX Buf 1 will ever be full. */ if (UNLIKELY(canintf & RX1I)) { /* receive interrupt active */ BufferRead buffer(1); buffer_read(&buffer, 1); struct can_frame *can_frame; portENTER_CRITICAL(); if (LIKELY(rxBuf->data_write_pointer(&can_frame))) { buffer.build_struct_can_frame(can_frame); rxBuf->advance(1); spi_->csAssert(); rxBuf->signal_condition(); spi_->csDeassert(); ++numReceivedPackets_; } else { /* receive overrun occured */ ++overrunCount; } portEXIT_CRITICAL(); } } if (txPending_) { /* transmit interrupt active and transmission complete */ if (canintf & TX0I) { txPending_ &= ~0x1; bit_modify(CANINTE, 0, TX0I); bit_modify(CANINTF, 0, TX0I); ++numTransmittedPackets_; } if (canintf & TX1I) { txPending_ &= ~0x2; bit_modify(CANINTE, 0, TX1I); bit_modify(CANINTF, 0, TX1I); ++numTransmittedPackets_; } while (txPending_ < 3) { struct can_frame *can_frame; /* find an empty buffer */ int index = (txPending_ & 0x1) ? 1 : 0; portENTER_CRITICAL(); if (txBuf->data_read_pointer(&can_frame)) { /* build up a transmit BufferWrite structure */ BufferWrite buffer(index, can_frame); txBuf->consume(1); portEXIT_CRITICAL(); /* bump up priority of the other buffer so it will * transmit first if it is pending */ bit_modify(index == 0 ? TXB1CTRL : TXB0CTRL, 0x01, 0x03); /* load the tranmit buffer */ buffer_write(&buffer, index, can_frame); txPending_ |= (0x1 << index); /* request to send at lowest priority */ bit_modify(index == 0 ? TXB0CTRL : TXB1CTRL, 0x08, 0x0B); bit_modify(CANINTE, TX0I << index, TX0I << index); txBuf->signal_condition(); } else { portEXIT_CRITICAL(); break; } } } if (UNLIKELY(ioPending_)) { ioPending_ = false; /* write the latest GPO data */ register_write(BFPCTRL, 0x0C | (gpoData_ << 4)); /* get the latest GPI data */ gpiData_ = (register_read(TXRTSCTRL) >> 3) & 0x7; } spi_->csAssert(); lock_.unlock(); spi_->csDeassert(); interruptEnable_(); } return NULL; } /* * interrupt_handler() */ __attribute__((optimize("-O3"))) void MCP2515Can::interrupt_handler() { spi_->csAssert(); int woken = false; interruptDisable_(); sem_.post_from_isr(&woken); os_isr_exit_yield_test(woken); } <|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 TivaNRZ.hxx * * Device driver for TivaWare to decode DCC track signal. * * @author Balazs Racz * @date 29 Nov 2014 */ #include "TivaDCC.hxx" // for FixedQueue #include "TivaGPIO.hxx" // for pin definitions #include "RailcomDriver.hxx" // for debug pins #include "dcc/Receiver.hxx" typedef DummyPin PIN_RailcomCutout; #define SIGNAL_LEVEL_ONE 0x80000000UL /* */ /** Device driver for decoding a DCC signal on a TI Tiva class microcontroller. This driver exports a filesystem device node, but that file node is not usable for reading or writing anything at the moment. The only feature supported by this device driver right now is that it is able to tell a RailcomDriver when the railcom cutout is supposed to start, when we're in the middle and when it is over. This is necessary for the correct functionality of the railcom driver. @TODO: implement actual packet decoding and sending back to the application layer. Usage: Define a structure declaring your hardware information. See below for what you need to define in there. Instantiate the device driver and pass the pointer to the railcom driver to the constructor. There is no need to touch the device from the application layer. Example hardware definitions: struct DCCDecode { static const auto TIMER_BASE = WTIMER4_BASE; static const auto TIMER_PERIPH = SYSCTL_PERIPH_WTIMER4; static const auto TIMER_INTERRUPT = INT_WTIMER4A; static const auto TIMER = TIMER_A; static const auto CFG_CAP_TIME_UP = TIMER_CFG_SPLIT_PAIR | TIMER_CFG_A_CAP_TIME_UP | TIMER_CFG_B_ONE_SHOT; // Interrupt bits. static const auto TIMER_CAP_EVENT = TIMER_CAPA_EVENT; static const auto TIMER_TIM_TIMEOUT = TIMER_TIMA_TIMEOUT; static const auto OS_INTERRUPT = INT_WTIMER4B; DECL_PIN(NRZPIN, D, 4); static const auto NRZPIN_CONFIG = GPIO_PD4_WT4CCP0; static const uint32_t TIMER_MAX_VALUE = 0x8000000UL; static const int Q_SIZE = 16; }; */ template <class HW> class TivaDccDecoder : public Node { public: TivaDccDecoder(const char *name, RailcomDriver *railcom_driver); ~TivaDccDecoder() { } /** Handles a raw interrupt. */ inline void interrupt_handler() __attribute__((always_inline)); /** Handles a software interrupt to FreeRTOS. */ inline void os_interrupt_handler() __attribute__((always_inline)); private: /** Read from a file or device. * @param file file reference for this device * @param buf location to place read data * @param count number of bytes to read * @return number of bytes read upon success, -1 upon failure with errno * containing the cause */ ssize_t read(File *file, void *buf, size_t count) OVERRIDE; /** Write to a file or device. * @param file file reference for this device * @param buf location to find write data * @param count number of bytes to write * @return number of bytes written upon success, -1 upon failure with errno * containing the cause */ ssize_t write(File *file, const void *buf, size_t count) OVERRIDE { return -EINVAL; } /** Request an ioctl transaction * @param file file reference for this device * @param node node reference for this device * @param key ioctl key * @param data key data */ int ioctl(File *file, unsigned long int key, unsigned long data) OVERRIDE; void enable() override; /**< function to enable device */ void disable() override; /**< function to disable device */ /** Discards all pending buffers. Called after disable(). */ void flush_buffers() override { while (!inputData_.empty()) { inputData_.increment_front(); } }; FixedQueue<uint32_t, HW::Q_SIZE> inputData_; uint32_t lastTimerValue_; uint32_t reloadCount_; unsigned lastLevel_; bool overflowed_ = false; bool inCutout_ = false; bool prepCutout_ = false; Notifiable *readableNotifiable_ = nullptr; RailcomDriver *railcomDriver_; //< notified for cutout events. dcc::DccDecoder decoder_; DISALLOW_COPY_AND_ASSIGN(TivaDccDecoder); }; template <class HW> TivaDccDecoder<HW>::TivaDccDecoder(const char *name, RailcomDriver *railcom_driver) : Node(name) , railcomDriver_(railcom_driver) { MAP_SysCtlPeripheralEnable(HW::TIMER_PERIPH); HW::NRZ_Pin::hw_init(); disable(); } template <class HW> void TivaDccDecoder<HW>::enable() { disable(); MAP_TimerClockSourceSet(HW::TIMER_BASE, TIMER_CLOCK_SYSTEM); MAP_TimerConfigure(HW::TIMER_BASE, HW::CFG_CAP_TIME_UP); MAP_TimerControlStall(HW::TIMER_BASE, HW::TIMER, true); MAP_TimerControlEvent(HW::TIMER_BASE, HW::TIMER, TIMER_EVENT_BOTH_EDGES); MAP_TimerLoadSet(HW::TIMER_BASE, HW::TIMER, HW::TIMER_MAX_VALUE); MAP_TimerPrescaleSet(HW::TIMER_BASE, HW::TIMER, HW::PS_MAX); reloadCount_ = 0; lastTimerValue_ = 0; MAP_TimerIntEnable(HW::TIMER_BASE, HW::TIMER_CAP_EVENT); MAP_TimerIntEnable(HW::TIMER_BASE, HW::TIMER_TIM_TIMEOUT); MAP_TimerLoadSet( HW::TIMER_BASE, HW::SAMPLE_TIMER, HW::SAMPLE_PERIOD_CLOCKS & 0xffffU); MAP_TimerPrescaleSet( HW::TIMER_BASE, HW::SAMPLE_TIMER, HW::SAMPLE_PERIOD_CLOCKS >> 16); MAP_TimerEnable(HW::TIMER_BASE, HW::SAMPLE_TIMER); MAP_IntPrioritySet(HW::TIMER_INTERRUPT, 0); MAP_IntPrioritySet(HW::OS_INTERRUPT, configKERNEL_INTERRUPT_PRIORITY); MAP_IntEnable(HW::OS_INTERRUPT); MAP_IntEnable(HW::TIMER_INTERRUPT); MAP_TimerEnable(HW::TIMER_BASE, HW::TIMER); } template <class HW> void TivaDccDecoder<HW>::disable() { MAP_IntDisable(HW::TIMER_INTERRUPT); MAP_IntDisable(HW::OS_INTERRUPT); MAP_TimerDisable(HW::TIMER_BASE, HW::TIMER); } template <class HW> __attribute__((optimize("-O3"))) void TivaDccDecoder<HW>::interrupt_handler() { Debug::DccDecodeInterrupts::set(true); // get masked interrupt status auto status = MAP_TimerIntStatus(HW::TIMER_BASE, false); if (status & HW::TIMER_TIM_TIMEOUT) { // The timer got reloaded. reloadCount_++; MAP_TimerIntClear(HW::TIMER_BASE, HW::TIMER_TIM_TIMEOUT); } // TODO(balazs.racz): Technically it is possible that the timer reload // happens between the event match and the interrupt entry. In this case we // will incorrectly add a full cycle to the event length. if (status & HW::TIMER_CAP_EVENT) { //Debug::DccDecodeInterrupts::toggle(); MAP_TimerIntClear(HW::TIMER_BASE, HW::TIMER_CAP_EVENT); static uint32_t raw_new_value; raw_new_value = MAP_TimerValueGet(HW::TIMER_BASE, HW::TIMER); static uint32_t new_value; new_value = raw_new_value; while (reloadCount_ > 0) { new_value += HW::TIMER_MAX_VALUE; reloadCount_--; } // HASSERT(new_value > lastTimerValue_); new_value -= lastTimerValue_; /*if (!inputData_.full()) { inputData_.back() = overflowed_ ? 3 : new_value; overflowed_ = false; inputData_.increment_back(); } else { overflowed_ = true; }*/ decoder_.process_data(new_value); if ((status & HW::SAMPLE_TIMER_TIMEOUT) && HW::NRZ_Pin::get() && !prepCutout_) { // The first positive edge after the sample timer expired (but // outside of the cutout). MAP_TimerIntClear(HW::TIMER_BASE, HW::SAMPLE_TIMER_TIMEOUT); railcomDriver_->feedback_sample(); HW::after_feedback_hook(); } if (decoder_.before_dcc_cutout()) { prepCutout_ = true; HW::dcc_before_cutout_hook(); } else if (decoder_.state() == dcc::DccDecoder::DCC_CUTOUT) { railcomDriver_->start_cutout(); inCutout_ = true; } /// TODO(balazs.racz) recognize middle cutout. else if (decoder_.state() == dcc::DccDecoder::DCC_PACKET_FINISHED) { if (inCutout_) { railcomDriver_->end_cutout(); inCutout_ = false; } HW::dcc_packet_finished_hook(); prepCutout_ = false; } lastTimerValue_ = raw_new_value; // We are not currently writing anything to the inputData_ queue, thus // we don't need to send our OS interrupt either. Once we fix to start // emitting the actual packets, we need to reenable this interrupt. // MAP_IntPendSet(HW::OS_INTERRUPT); } Debug::DccDecodeInterrupts::set(false); } template <class HW> __attribute__((optimize("-O3"))) void TivaDccDecoder<HW>::os_interrupt_handler() { if (!inputData_.empty()) { Notifiable *n = readableNotifiable_; readableNotifiable_ = nullptr; if (n) { n->notify_from_isr(); os_isr_exit_yield_test(true); } } } template <class HW> int TivaDccDecoder<HW>::ioctl(File *file, unsigned long int key, unsigned long data) { if (IOC_TYPE(key) == CAN_IOC_MAGIC && IOC_SIZE(key) == NOTIFIABLE_TYPE && key == CAN_IOC_READ_ACTIVE) { Notifiable *n = reinterpret_cast<Notifiable *>(data); HASSERT(n); // If there is no data for reading, we put the incoming notification // into the holder. Otherwise we notify it immediately. if (inputData_.empty()) { portENTER_CRITICAL(); if (inputData_.empty()) { // We are in a critical section now. If we got into this // branch, then the buffer was full at the beginning of the // critical section. If the hardware interrupt kicks in now, // and sets the os_interrupt to pending, the os interrupt will // not happen until we leave the critical section, and thus the // swap will be in effect by then. std::swap(n, readableNotifiable_); } portEXIT_CRITICAL(); } if (n) { n->notify(); } return 0; } errno = EINVAL; return -1; } /** Read from a file or device. * @param file file reference for this device * @param buf location to place read data * @param count number of bytes to read * @return number of bytes read upon success, -1 upon failure with errno * containing the cause */ template <class HW> ssize_t TivaDccDecoder<HW>::read(File *file, void *buf, size_t count) { if (count != 4) { return -EINVAL; } // We only need this critical section to prevent concurrent threads from // reading at the same time. portENTER_CRITICAL(); if (inputData_.empty()) { portEXIT_CRITICAL(); return -EAGAIN; } uint32_t v = reinterpret_cast<uint32_t>(buf); HASSERT((v & 3) == 0); // alignment check. uint32_t *pv = static_cast<uint32_t *>(buf); *pv = inputData_.front(); inputData_.increment_front(); portEXIT_CRITICAL(); return count; } <commit_msg>Fixes an issue where the railcom cutout would not be detected if the polarity of the inbound DCC signal was reversed. WIth reversed polarity it is not possible to detect the partial one bit at the beginning of the railcom cutout.<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 TivaNRZ.hxx * * Device driver for TivaWare to decode DCC track signal. * * @author Balazs Racz * @date 29 Nov 2014 */ #include "TivaDCC.hxx" // for FixedQueue #include "TivaGPIO.hxx" // for pin definitions #include "RailcomDriver.hxx" // for debug pins #include "dcc/Receiver.hxx" typedef DummyPin PIN_RailcomCutout; #define SIGNAL_LEVEL_ONE 0x80000000UL /* */ /** Device driver for decoding a DCC signal on a TI Tiva class microcontroller. This driver exports a filesystem device node, but that file node is not usable for reading or writing anything at the moment. The only feature supported by this device driver right now is that it is able to tell a RailcomDriver when the railcom cutout is supposed to start, when we're in the middle and when it is over. This is necessary for the correct functionality of the railcom driver. @TODO: implement actual packet decoding and sending back to the application layer. Usage: Define a structure declaring your hardware information. See below for what you need to define in there. Instantiate the device driver and pass the pointer to the railcom driver to the constructor. There is no need to touch the device from the application layer. Example hardware definitions: struct DCCDecode { static const auto TIMER_BASE = WTIMER4_BASE; static const auto TIMER_PERIPH = SYSCTL_PERIPH_WTIMER4; static const auto TIMER_INTERRUPT = INT_WTIMER4A; static const auto TIMER = TIMER_A; static const auto CFG_CAP_TIME_UP = TIMER_CFG_SPLIT_PAIR | TIMER_CFG_A_CAP_TIME_UP | TIMER_CFG_B_ONE_SHOT; // Interrupt bits. static const auto TIMER_CAP_EVENT = TIMER_CAPA_EVENT; static const auto TIMER_TIM_TIMEOUT = TIMER_TIMA_TIMEOUT; static const auto OS_INTERRUPT = INT_WTIMER4B; DECL_PIN(NRZPIN, D, 4); static const auto NRZPIN_CONFIG = GPIO_PD4_WT4CCP0; static const uint32_t TIMER_MAX_VALUE = 0x8000000UL; static const int Q_SIZE = 16; }; */ template <class HW> class TivaDccDecoder : public Node { public: TivaDccDecoder(const char *name, RailcomDriver *railcom_driver); ~TivaDccDecoder() { } /** Handles a raw interrupt. */ inline void interrupt_handler() __attribute__((always_inline)); /** Handles a software interrupt to FreeRTOS. */ inline void os_interrupt_handler() __attribute__((always_inline)); private: /** Read from a file or device. * @param file file reference for this device * @param buf location to place read data * @param count number of bytes to read * @return number of bytes read upon success, -1 upon failure with errno * containing the cause */ ssize_t read(File *file, void *buf, size_t count) OVERRIDE; /** Write to a file or device. * @param file file reference for this device * @param buf location to find write data * @param count number of bytes to write * @return number of bytes written upon success, -1 upon failure with errno * containing the cause */ ssize_t write(File *file, const void *buf, size_t count) OVERRIDE { return -EINVAL; } /** Request an ioctl transaction * @param file file reference for this device * @param node node reference for this device * @param key ioctl key * @param data key data */ int ioctl(File *file, unsigned long int key, unsigned long data) OVERRIDE; void enable() override; /**< function to enable device */ void disable() override; /**< function to disable device */ /** Discards all pending buffers. Called after disable(). */ void flush_buffers() override { while (!inputData_.empty()) { inputData_.increment_front(); } }; FixedQueue<uint32_t, HW::Q_SIZE> inputData_; uint32_t lastTimerValue_; uint32_t reloadCount_; unsigned lastLevel_; bool overflowed_ = false; bool inCutout_ = false; bool prepCutout_ = false; Notifiable *readableNotifiable_ = nullptr; RailcomDriver *railcomDriver_; //< notified for cutout events. dcc::DccDecoder decoder_; DISALLOW_COPY_AND_ASSIGN(TivaDccDecoder); }; template <class HW> TivaDccDecoder<HW>::TivaDccDecoder(const char *name, RailcomDriver *railcom_driver) : Node(name) , railcomDriver_(railcom_driver) { MAP_SysCtlPeripheralEnable(HW::TIMER_PERIPH); HW::NRZ_Pin::hw_init(); disable(); } template <class HW> void TivaDccDecoder<HW>::enable() { disable(); MAP_TimerClockSourceSet(HW::TIMER_BASE, TIMER_CLOCK_SYSTEM); MAP_TimerConfigure(HW::TIMER_BASE, HW::CFG_CAP_TIME_UP); MAP_TimerControlStall(HW::TIMER_BASE, HW::TIMER, true); MAP_TimerControlEvent(HW::TIMER_BASE, HW::TIMER, TIMER_EVENT_BOTH_EDGES); MAP_TimerLoadSet(HW::TIMER_BASE, HW::TIMER, HW::TIMER_MAX_VALUE); MAP_TimerPrescaleSet(HW::TIMER_BASE, HW::TIMER, HW::PS_MAX); reloadCount_ = 0; lastTimerValue_ = 0; MAP_TimerIntEnable(HW::TIMER_BASE, HW::TIMER_CAP_EVENT); MAP_TimerIntEnable(HW::TIMER_BASE, HW::TIMER_TIM_TIMEOUT); MAP_TimerLoadSet( HW::TIMER_BASE, HW::SAMPLE_TIMER, HW::SAMPLE_PERIOD_CLOCKS & 0xffffU); MAP_TimerPrescaleSet( HW::TIMER_BASE, HW::SAMPLE_TIMER, HW::SAMPLE_PERIOD_CLOCKS >> 16); MAP_TimerEnable(HW::TIMER_BASE, HW::SAMPLE_TIMER); MAP_IntPrioritySet(HW::TIMER_INTERRUPT, 0); MAP_IntPrioritySet(HW::OS_INTERRUPT, configKERNEL_INTERRUPT_PRIORITY); MAP_IntEnable(HW::OS_INTERRUPT); MAP_IntEnable(HW::TIMER_INTERRUPT); MAP_TimerEnable(HW::TIMER_BASE, HW::TIMER); } template <class HW> void TivaDccDecoder<HW>::disable() { MAP_IntDisable(HW::TIMER_INTERRUPT); MAP_IntDisable(HW::OS_INTERRUPT); MAP_TimerDisable(HW::TIMER_BASE, HW::TIMER); } template <class HW> __attribute__((optimize("-O3"))) void TivaDccDecoder<HW>::interrupt_handler() { Debug::DccDecodeInterrupts::set(true); // get masked interrupt status auto status = MAP_TimerIntStatus(HW::TIMER_BASE, false); if (status & HW::TIMER_TIM_TIMEOUT) { // The timer got reloaded. reloadCount_++; MAP_TimerIntClear(HW::TIMER_BASE, HW::TIMER_TIM_TIMEOUT); } // TODO(balazs.racz): Technically it is possible that the timer reload // happens between the event match and the interrupt entry. In this case we // will incorrectly add a full cycle to the event length. if (status & HW::TIMER_CAP_EVENT) { //Debug::DccDecodeInterrupts::toggle(); MAP_TimerIntClear(HW::TIMER_BASE, HW::TIMER_CAP_EVENT); static uint32_t raw_new_value; raw_new_value = MAP_TimerValueGet(HW::TIMER_BASE, HW::TIMER); static uint32_t new_value; new_value = raw_new_value; while (reloadCount_ > 0) { new_value += HW::TIMER_MAX_VALUE; reloadCount_--; } // HASSERT(new_value > lastTimerValue_); new_value -= lastTimerValue_; /*if (!inputData_.full()) { inputData_.back() = overflowed_ ? 3 : new_value; overflowed_ = false; inputData_.increment_back(); } else { overflowed_ = true; }*/ bool cutout_just_finished = false; decoder_.process_data(new_value); if (decoder_.before_dcc_cutout()) { prepCutout_ = true; HW::dcc_before_cutout_hook(); } // If we are at the second half of the last 1 bit and the // value of the input pin is 1, then we cannot recognize when // the first half of the cutout bit disappears thus we'll // never get the DCC cutout signal. We will therefore start // the cutout by hand with a bit of delay. else if (decoder_.state() == dcc::DccDecoder::DCC_MAYBE_CUTOUT && true) //HW::NRZ_Pin::get()) { SysCtlDelay(180); railcomDriver_->start_cutout(); inCutout_ = true; } else if (decoder_.state() == dcc::DccDecoder::DCC_CUTOUT) { railcomDriver_->start_cutout(); inCutout_ = true; } /// TODO(balazs.racz) recognize middle cutout. else if (decoder_.state() == dcc::DccDecoder::DCC_PACKET_FINISHED) { if (inCutout_) { railcomDriver_->end_cutout(); inCutout_ = false; } HW::dcc_packet_finished_hook(); prepCutout_ = false; cutout_just_finished = true; } lastTimerValue_ = raw_new_value; if ((status & HW::SAMPLE_TIMER_TIMEOUT) && HW::NRZ_Pin::get() && !prepCutout_ && !cutout_just_finished) { // The first positive edge after the sample timer expired (but // outside of the cutout). MAP_TimerIntClear(HW::TIMER_BASE, HW::SAMPLE_TIMER_TIMEOUT); railcomDriver_->feedback_sample(); HW::after_feedback_hook(); } // We are not currently writing anything to the inputData_ queue, thus // we don't need to send our OS interrupt either. Once we fix to start // emitting the actual packets, we need to reenable this interrupt. // MAP_IntPendSet(HW::OS_INTERRUPT); } Debug::DccDecodeInterrupts::set(false); } template <class HW> __attribute__((optimize("-O3"))) void TivaDccDecoder<HW>::os_interrupt_handler() { if (!inputData_.empty()) { Notifiable *n = readableNotifiable_; readableNotifiable_ = nullptr; if (n) { n->notify_from_isr(); os_isr_exit_yield_test(true); } } } template <class HW> int TivaDccDecoder<HW>::ioctl(File *file, unsigned long int key, unsigned long data) { if (IOC_TYPE(key) == CAN_IOC_MAGIC && IOC_SIZE(key) == NOTIFIABLE_TYPE && key == CAN_IOC_READ_ACTIVE) { Notifiable *n = reinterpret_cast<Notifiable *>(data); HASSERT(n); // If there is no data for reading, we put the incoming notification // into the holder. Otherwise we notify it immediately. if (inputData_.empty()) { portENTER_CRITICAL(); if (inputData_.empty()) { // We are in a critical section now. If we got into this // branch, then the buffer was full at the beginning of the // critical section. If the hardware interrupt kicks in now, // and sets the os_interrupt to pending, the os interrupt will // not happen until we leave the critical section, and thus the // swap will be in effect by then. std::swap(n, readableNotifiable_); } portEXIT_CRITICAL(); } if (n) { n->notify(); } return 0; } errno = EINVAL; return -1; } /** Read from a file or device. * @param file file reference for this device * @param buf location to place read data * @param count number of bytes to read * @return number of bytes read upon success, -1 upon failure with errno * containing the cause */ template <class HW> ssize_t TivaDccDecoder<HW>::read(File *file, void *buf, size_t count) { if (count != 4) { return -EINVAL; } // We only need this critical section to prevent concurrent threads from // reading at the same time. portENTER_CRITICAL(); if (inputData_.empty()) { portEXIT_CRITICAL(); return -EAGAIN; } uint32_t v = reinterpret_cast<uint32_t>(buf); HASSERT((v & 3) == 0); // alignment check. uint32_t *pv = static_cast<uint32_t *>(buf); *pv = inputData_.front(); inputData_.increment_front(); portEXIT_CRITICAL(); return count; } <|endoftext|>
<commit_before>//===- Target.cpp ---------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Machine-specific things, such as applying relocations, creation of // GOT or PLT entries, etc., are handled in this file. // // Refer the ELF spec for the single letter variables, S, A or P, used // in this file. // // Some functions defined in this file has "relaxTls" as part of their names. // They do peephole optimization for TLS variables by rewriting instructions. // They are not part of the ABI but optional optimization, so you can skip // them if you are not interested in how TLS variables are optimized. // See the following paper for the details. // // Ulrich Drepper, ELF Handling For Thread-Local Storage // http://www.akkadia.org/drepper/tls.pdf // //===----------------------------------------------------------------------===// #include "Target.h" #include "InputFiles.h" #include "OutputSections.h" #include "SymbolTable.h" #include "Symbols.h" #include "lld/Common/ErrorHandler.h" #include "llvm/Object/ELF.h" using namespace llvm; using namespace llvm::object; using namespace llvm::ELF; namespace lld { std::string toString(elf::RelType type) { StringRef s = getELFRelocationTypeName(elf::config->emachine, type); if (s == "Unknown") return ("Unknown (" + Twine(type) + ")").str(); return s; } namespace elf { const TargetInfo *target; TargetInfo *getTarget() { switch (config->emachine) { case EM_386: case EM_IAMCU: return getX86TargetInfo(); case EM_AARCH64: return getAArch64TargetInfo(); case EM_AMDGPU: return getAMDGPUTargetInfo(); case EM_ARM: return getARMTargetInfo(); case EM_AVR: return getAVRTargetInfo(); case EM_HEXAGON: return getHexagonTargetInfo(); case EM_MIPS: switch (config->ekind) { case ELF32LEKind: return getMipsTargetInfo<ELF32LE>(); case ELF32BEKind: return getMipsTargetInfo<ELF32BE>(); case ELF64LEKind: return getMipsTargetInfo<ELF64LE>(); case ELF64BEKind: return getMipsTargetInfo<ELF64BE>(); default: llvm_unreachable("unsupported MIPS target"); } case EM_MSP430: return getMSP430TargetInfo(); case EM_PPC: return getPPCTargetInfo(); case EM_PPC64: return getPPC64TargetInfo(); case EM_RISCV: return getRISCVTargetInfo(); case EM_SPARCV9: return getSPARCV9TargetInfo(); case EM_X86_64: return getX86_64TargetInfo(); } llvm_unreachable("unknown target machine"); } template <class ELFT> static ErrorPlace getErrPlace(const uint8_t *loc) { for (InputSectionBase *d : inputSections) { auto *isec = cast<InputSection>(d); if (!isec->getParent()) continue; uint8_t *isecLoc = Out::bufferStart + isec->getParent()->offset + isec->outSecOff; if (isecLoc > loc) continue; // isecLoc might be nullptr here, with isec->getSize() being non-zero. // Adding these two together is not defined in C++. if (loc < reinterpret_cast<uint8_t *>( reinterpret_cast<std::uintptr_t>(isecLoc) + isec->getSize())) return {isec, isec->template getLocation<ELFT>(loc - isecLoc) + ": "}; } return {}; } ErrorPlace getErrorPlace(const uint8_t *loc) { switch (config->ekind) { case ELF32LEKind: return getErrPlace<ELF32LE>(loc); case ELF32BEKind: return getErrPlace<ELF32BE>(loc); case ELF64LEKind: return getErrPlace<ELF64LE>(loc); case ELF64BEKind: return getErrPlace<ELF64BE>(loc); default: llvm_unreachable("unknown ELF type"); } } TargetInfo::~TargetInfo() {} int64_t TargetInfo::getImplicitAddend(const uint8_t *buf, RelType type) const { return 0; } bool TargetInfo::usesOnlyLowPageBits(RelType type) const { return false; } bool TargetInfo::needsThunk(RelExpr expr, RelType type, const InputFile *file, uint64_t branchAddr, const Symbol &s) const { return false; } bool TargetInfo::adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end, uint8_t stOther) const { llvm_unreachable("Target doesn't support split stacks."); } bool TargetInfo::inBranchRange(RelType type, uint64_t src, uint64_t dst) const { return true; } void TargetInfo::writeIgotPlt(uint8_t *buf, const Symbol &s) const { writeGotPlt(buf, s); } RelExpr TargetInfo::adjustRelaxExpr(RelType type, const uint8_t *data, RelExpr expr) const { return expr; } void TargetInfo::relaxGot(uint8_t *loc, RelType type, uint64_t val) const { llvm_unreachable("Should not have claimed to be relaxable"); } void TargetInfo::relaxTlsGdToLe(uint8_t *loc, RelType type, uint64_t val) const { llvm_unreachable("Should not have claimed to be relaxable"); } void TargetInfo::relaxTlsGdToIe(uint8_t *loc, RelType type, uint64_t val) const { llvm_unreachable("Should not have claimed to be relaxable"); } void TargetInfo::relaxTlsIeToLe(uint8_t *loc, RelType type, uint64_t val) const { llvm_unreachable("Should not have claimed to be relaxable"); } void TargetInfo::relaxTlsLdToLe(uint8_t *loc, RelType type, uint64_t val) const { llvm_unreachable("Should not have claimed to be relaxable"); } uint64_t TargetInfo::getImageBase() const { // Use -image-base if set. Fall back to the target default if not. if (config->imageBase) return *config->imageBase; return config->isPic ? 0 : defaultImageBase; } } // namespace elf } // namespace lld <commit_msg>Make nullptr check more robust<commit_after>//===- Target.cpp ---------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Machine-specific things, such as applying relocations, creation of // GOT or PLT entries, etc., are handled in this file. // // Refer the ELF spec for the single letter variables, S, A or P, used // in this file. // // Some functions defined in this file has "relaxTls" as part of their names. // They do peephole optimization for TLS variables by rewriting instructions. // They are not part of the ABI but optional optimization, so you can skip // them if you are not interested in how TLS variables are optimized. // See the following paper for the details. // // Ulrich Drepper, ELF Handling For Thread-Local Storage // http://www.akkadia.org/drepper/tls.pdf // //===----------------------------------------------------------------------===// #include "Target.h" #include "InputFiles.h" #include "OutputSections.h" #include "SymbolTable.h" #include "Symbols.h" #include "lld/Common/ErrorHandler.h" #include "llvm/Object/ELF.h" using namespace llvm; using namespace llvm::object; using namespace llvm::ELF; namespace lld { std::string toString(elf::RelType type) { StringRef s = getELFRelocationTypeName(elf::config->emachine, type); if (s == "Unknown") return ("Unknown (" + Twine(type) + ")").str(); return s; } namespace elf { const TargetInfo *target; TargetInfo *getTarget() { switch (config->emachine) { case EM_386: case EM_IAMCU: return getX86TargetInfo(); case EM_AARCH64: return getAArch64TargetInfo(); case EM_AMDGPU: return getAMDGPUTargetInfo(); case EM_ARM: return getARMTargetInfo(); case EM_AVR: return getAVRTargetInfo(); case EM_HEXAGON: return getHexagonTargetInfo(); case EM_MIPS: switch (config->ekind) { case ELF32LEKind: return getMipsTargetInfo<ELF32LE>(); case ELF32BEKind: return getMipsTargetInfo<ELF32BE>(); case ELF64LEKind: return getMipsTargetInfo<ELF64LE>(); case ELF64BEKind: return getMipsTargetInfo<ELF64BE>(); default: llvm_unreachable("unsupported MIPS target"); } case EM_MSP430: return getMSP430TargetInfo(); case EM_PPC: return getPPCTargetInfo(); case EM_PPC64: return getPPC64TargetInfo(); case EM_RISCV: return getRISCVTargetInfo(); case EM_SPARCV9: return getSPARCV9TargetInfo(); case EM_X86_64: return getX86_64TargetInfo(); } llvm_unreachable("unknown target machine"); } template <class ELFT> static ErrorPlace getErrPlace(const uint8_t *loc) { if (!Out::bufferStart) return {}; for (InputSectionBase *d : inputSections) { auto *isec = cast<InputSection>(d); if (!isec->getParent()) continue; uint8_t *isecLoc = Out::bufferStart + isec->getParent()->offset + isec->outSecOff; if (isecLoc <= loc && loc < isecLoc + isec->getSize()) return {isec, isec->template getLocation<ELFT>(loc - isecLoc) + ": "}; } return {}; } ErrorPlace getErrorPlace(const uint8_t *loc) { switch (config->ekind) { case ELF32LEKind: return getErrPlace<ELF32LE>(loc); case ELF32BEKind: return getErrPlace<ELF32BE>(loc); case ELF64LEKind: return getErrPlace<ELF64LE>(loc); case ELF64BEKind: return getErrPlace<ELF64BE>(loc); default: llvm_unreachable("unknown ELF type"); } } TargetInfo::~TargetInfo() {} int64_t TargetInfo::getImplicitAddend(const uint8_t *buf, RelType type) const { return 0; } bool TargetInfo::usesOnlyLowPageBits(RelType type) const { return false; } bool TargetInfo::needsThunk(RelExpr expr, RelType type, const InputFile *file, uint64_t branchAddr, const Symbol &s) const { return false; } bool TargetInfo::adjustPrologueForCrossSplitStack(uint8_t *loc, uint8_t *end, uint8_t stOther) const { llvm_unreachable("Target doesn't support split stacks."); } bool TargetInfo::inBranchRange(RelType type, uint64_t src, uint64_t dst) const { return true; } void TargetInfo::writeIgotPlt(uint8_t *buf, const Symbol &s) const { writeGotPlt(buf, s); } RelExpr TargetInfo::adjustRelaxExpr(RelType type, const uint8_t *data, RelExpr expr) const { return expr; } void TargetInfo::relaxGot(uint8_t *loc, RelType type, uint64_t val) const { llvm_unreachable("Should not have claimed to be relaxable"); } void TargetInfo::relaxTlsGdToLe(uint8_t *loc, RelType type, uint64_t val) const { llvm_unreachable("Should not have claimed to be relaxable"); } void TargetInfo::relaxTlsGdToIe(uint8_t *loc, RelType type, uint64_t val) const { llvm_unreachable("Should not have claimed to be relaxable"); } void TargetInfo::relaxTlsIeToLe(uint8_t *loc, RelType type, uint64_t val) const { llvm_unreachable("Should not have claimed to be relaxable"); } void TargetInfo::relaxTlsLdToLe(uint8_t *loc, RelType type, uint64_t val) const { llvm_unreachable("Should not have claimed to be relaxable"); } uint64_t TargetInfo::getImageBase() const { // Use -image-base if set. Fall back to the target default if not. if (config->imageBase) return *config->imageBase; return config->isPic ? 0 : defaultImageBase; } } // namespace elf } // namespace lld <|endoftext|>
<commit_before>/* * Copyright (c) [2004-2015] Novell, Inc. * Copyright (c) 2016 SUSE LLC * * All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, contact Novell, Inc. * * To contact Novell about this file by physical or electronic mail, you may * find current contact information at www.novell.com. */ #include <fstream> #include "storage/Utils/AppUtil.h" #include "storage/Utils/SystemCmd.h" #include "storage/Utils/StorageDefines.h" #include "storage/SystemInfo/CmdParted.h" #include "storage/Utils/Enum.h" #include "storage/Devices/PartitionImpl.h" #include "storage/Utils/StorageTypes.h" #include "storage/Devices/PartitionTableImpl.h" namespace storage { using namespace std; Parted::Parted(const string& device) : device(device), label(PtType::PT_UNKNOWN), region(), implicit(false), gpt_enlarge(false), gpt_pmbr_boot(false) { SystemCmd cmd(PARTEDBIN " --script " + quote(device) + " unit s print", SystemCmd::DoThrow); // No check for exit status since parted 3.1 exits with 1 if no // partition table is found. if ( !cmd.stderr().empty() ) { this->stderr = cmd.stderr(); // Save stderr output if ( boost::starts_with( cmd.stderr().front(), "Error: Could not stat device" ) ) ST_THROW( SystemCmdException( &cmd, "parted complains: " + cmd.stderr().front() ) ); else { // Intentionally NOT throwing an exception here for just any kind // of stderr output because it's quite common for the parted // command to write messages to stderr in certain situations that // may not necessarily be fatal. // // See also bsc#938572, bsc#938561 for ( const string& line: stderr ) { y2war( "parted stderr> " + line ); } } } parse(cmd.stdout(), cmd.stderr()); } void Parted::parse(const vector<string>& stdout, const vector<string>& stderr) { implicit = false; gpt_enlarge = false; gpt_fix_backup = false; gpt_pmbr_boot = false; entries.clear(); vector<string>::const_iterator pos; pos = find_if(stdout, string_starts_with("Partition Table:")); if (pos != stdout.end()) { string label_str = extractNthWord(2, *pos); if (label_str == "msdos") label = PtType::MSDOS; else if (label_str == "gpt" || label_str == "gpt_sync_mbr") label = PtType::GPT; else if (label_str == "dasd") label = PtType::DASD; else if (label_str == "loop") label = PtType::PT_LOOP; else if (label_str == "unknown") label = PtType::PT_UNKNOWN; else throw runtime_error("unknown partition table type"); } else y2war("could not find partition table"); pos = find_if(stdout, string_starts_with("Disk " + device + ":")); if (pos != stdout.end()) scanDiskSize(*pos); else y2war("could not find disk size"); // not present for unrecognised disk label pos = find_if(stdout, string_starts_with("Sector size (logical/physical):")); if (pos != stdout.end()) scanSectorSizeLine(*pos); else y2war("could not find sector size"); pos = find_if(stdout, string_starts_with("Disk Flags:")); if (pos != stdout.end()) scanDiskFlags(*pos); else y2war("could not find disk flags"); gpt_enlarge = find_if(stderr, string_contains("fix the GPT to use all")) != stderr.end(); gpt_fix_backup = find_if(stderr, string_contains("backup GPT table is corrupt, but the " "primary appears OK")) != stderr.end(); if (label != PtType::PT_UNKNOWN && label != PtType::PT_LOOP) { int n = 0; // Parse partition tables: One with cylinder sizes, one with sector sizes for (const string& line : stdout) { if (boost::starts_with(line, "Number")) n++; string tmp = extractNthWord(0, line); if (!tmp.empty() && isdigit(tmp[0])) { if (n == 1) scanSectorEntryLine(line); else ST_THROW( ParseException( string( "Unexpected partition table #" ) + std::to_string(n), "", "" ) ); } } } y2mil(*this); } bool Parted::getEntry(unsigned num, Entry& entry) const { for (const_iterator it = entries.begin(); it != entries.end(); ++it) { if (it->num == num) { entry = *it; return true; } } return false; } std::ostream& operator<<(std::ostream& s, const Parted& parted) { s << "device:" << parted.device << " label:" << toString(parted.label) << " region:" << parted.region; if (parted.implicit) s << " implicit"; if (parted.gpt_enlarge) s << " gpt-enlarge"; if (parted.gpt_fix_backup) s << " gpt-fix-backup"; if (parted.gpt_pmbr_boot) s << " gpt-pmbr-boot"; s << '\n'; for (Parted::const_iterator it = parted.entries.begin(); it != parted.entries.end(); ++it) s << *it << '\n'; return s; } std::ostream& operator<<(std::ostream& s, const Parted::Entry& entry) { s << "num:" << entry.num << " region:" << entry.region << " type:" << toString(entry.type) << " id:" << entry.id; if (entry.boot) s << " boot"; if (entry.legacy_boot) s << " legacy-boot"; return s; } void Parted::scanDiskSize(const string& line) { string tmp(line); tmp.erase(0, tmp.find(':') + 1); int num_sectors = 0; tmp >> num_sectors; region.set_length(num_sectors); } void Parted::scanDiskFlags(const string& line) { implicit = boost::contains(line, "implicit_partition_table"); gpt_pmbr_boot = boost::contains(line, "pmbr_boot"); } void Parted::scanSectorSizeLine(const string& line) { // FIXME: This parser is too minimalistic and allows too much illegal input. // It turned out to be near impossible to come up with any test case that // actually made it throw an exception and not just silently do something random. // -- shundhammer 2015-05-13 string tmp(line); tmp.erase(0, tmp.find(':') + 1); tmp = extractNthWord(0, tmp); list<string> l = splitString(extractNthWord(0, tmp), "/"); if (l.size() == 2) { list<string>::const_iterator i = l.begin(); int logical_sector_size = 0; *i >> logical_sector_size; region.set_block_size(logical_sector_size); } else { ST_THROW( ParseException( "Bad sector size line", line, "Sector size (logical/physical): 512B/4096B" ) ); } } void Parted::scanSectorEntryLine(const string& line) { // Sample input: // // 1 2048s 4208639s 4206592s primary linux-swap(v1) type=82 // 2 4208640s 88100863s 83892224s primary btrfs boot, type=83 // 3 88100864s 171991039s 83890176s primary btrfs type=83 // 4 171991040s 3907028991s 3735037952s extended lba, type=0f // 5 171993088s 3907008511s 3735015424s logical xfs type=83 // // (Number) (Start) (End) (Size) (Type) (File system) (Flags) Entry entry; std::istringstream Data(line); classic(Data); unsigned long start_sector = 0; unsigned long end_sector = 0; unsigned long size_sector = 0; string PartitionTypeStr; string skip; if (label == PtType::MSDOS) { Data >> entry.num >> start_sector >> skip >> end_sector >> skip >> size_sector >> skip >> PartitionTypeStr; } else { Data >> entry.num >> start_sector >> skip >> end_sector >> skip >> size_sector >> skip; } if ( Data.fail() ) // parse error? { ST_THROW(ParseException("Bad sector-based partition entry", line, "2 4208640s 88100863s 83892224s primary btrfs boot, type=83")); } y2mil("num:" << entry.num << " start-sector:" << start_sector << " end-sector:" << end_sector << " size-sector:" << size_sector); if (entry.num == 0) ST_THROW(ParseException("Illegal partition number 0", line, "")); entry.region = Region(start_sector, size_sector, region.get_block_size()); char c; string TInfo; Data.unsetf(ifstream::skipws); Data >> c; char last_char = ','; while( Data.good() && !Data.eof() ) { if ( !isspace(c) ) { TInfo += c; last_char = c; } else { if ( last_char != ',' ) { TInfo += ","; last_char = ','; } } Data >> c; } boost::to_lower(TInfo, locale::classic()); list<string> flags = splitString(TInfo, ","); y2mil("TInfo:" << TInfo << " flags:" << flags); // TODO parted has a strange interface to represent partition type // ids. E.g. swap is not displayed based on the id but the partition // content. On GPT it is also not possible to distinguish whether the // id is linux or unknown. Work with upsteam parted to improve the // interface. The line below should then be entry.id = ID_UNKNOWN. entry.id = ID_LINUX; if (label == PtType::MSDOS) { if (PartitionTypeStr == "extended") { entry.type = PartitionType::EXTENDED; entry.id = ID_EXTENDED; } else if (entry.num >= 5) { entry.type = PartitionType::LOGICAL; } } else if (contains_if(flags, string_starts_with("fat"))) { entry.id = ID_DOS32; } else if (contains(flags, "ntfs")) { entry.id = ID_NTFS; } else if (contains_if(flags, string_contains("swap"))) { entry.id = ID_SWAP; } else if (contains(flags, "raid")) { entry.id = ID_RAID; } else if (contains(flags, "lvm")) { entry.id = ID_LVM; } else if (contains(flags, "prep")) { entry.id = ID_PREP; } else if (contains(flags, "esp")) { entry.id = ID_ESP; } if (label == PtType::MSDOS) { entry.boot = contains(flags, "boot"); list<string>::const_iterator it1 = find_if(flags.begin(), flags.end(), string_starts_with("type=")); if (it1 != flags.end()) { string val = string(*it1, 5); int tmp_id = 0; std::istringstream Data2(val); classic(Data2); Data2 >> std::hex >> tmp_id; if (tmp_id > 0) { entry.id = tmp_id; } } } if (label == PtType::GPT) { entry.legacy_boot = contains(flags, "legacy_boot"); if (contains(flags, "bios_grub")) { entry.id = ID_BIOS_BOOT; } else if (contains(flags, "msftdata")) { entry.id = ID_WINDOWS_BASIC_DATA; } else if (contains(flags, "msftres")) { entry.id = ID_MICROSOFT_RESERVED; } } y2mil("num:" << entry.num << " region:" << entry.region << " id:" << entry.id << " type:" << toString(entry.type)); entries.push_back(entry); } } <commit_msg>- improved parser<commit_after>/* * Copyright (c) [2004-2015] Novell, Inc. * Copyright (c) 2016 SUSE LLC * * All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, contact Novell, Inc. * * To contact Novell about this file by physical or electronic mail, you may * find current contact information at www.novell.com. */ #include <fstream> #include "storage/Utils/AppUtil.h" #include "storage/Utils/SystemCmd.h" #include "storage/Utils/StorageDefines.h" #include "storage/SystemInfo/CmdParted.h" #include "storage/Utils/Enum.h" #include "storage/Devices/PartitionImpl.h" #include "storage/Utils/StorageTypes.h" #include "storage/Devices/PartitionTableImpl.h" namespace storage { using namespace std; Parted::Parted(const string& device) : device(device), label(PtType::PT_UNKNOWN), region(), implicit(false), gpt_enlarge(false), gpt_pmbr_boot(false) { SystemCmd cmd(PARTEDBIN " --script " + quote(device) + " unit s print", SystemCmd::DoThrow); // No check for exit status since parted 3.1 exits with 1 if no // partition table is found. if ( !cmd.stderr().empty() ) { this->stderr = cmd.stderr(); // Save stderr output if ( boost::starts_with( cmd.stderr().front(), "Error: Could not stat device" ) ) ST_THROW( SystemCmdException( &cmd, "parted complains: " + cmd.stderr().front() ) ); else { // Intentionally NOT throwing an exception here for just any kind // of stderr output because it's quite common for the parted // command to write messages to stderr in certain situations that // may not necessarily be fatal. // // See also bsc#938572, bsc#938561 for ( const string& line: stderr ) { y2war( "parted stderr> " + line ); } } } parse(cmd.stdout(), cmd.stderr()); } void Parted::parse(const vector<string>& stdout, const vector<string>& stderr) { implicit = false; gpt_enlarge = false; gpt_fix_backup = false; gpt_pmbr_boot = false; entries.clear(); vector<string>::const_iterator pos; pos = find_if(stdout, string_starts_with("Partition Table:")); if (pos != stdout.end()) { string label_str = extractNthWord(2, *pos); if (label_str == "msdos") label = PtType::MSDOS; else if (label_str == "gpt" || label_str == "gpt_sync_mbr") label = PtType::GPT; else if (label_str == "dasd") label = PtType::DASD; else if (label_str == "loop") label = PtType::PT_LOOP; else if (label_str == "unknown") label = PtType::PT_UNKNOWN; else throw runtime_error("unknown partition table type"); } else y2war("could not find partition table"); pos = find_if(stdout, string_starts_with("Disk " + device + ":")); if (pos != stdout.end()) scanDiskSize(*pos); else y2war("could not find disk size"); // not present for unrecognised disk label pos = find_if(stdout, string_starts_with("Sector size (logical/physical):")); if (pos != stdout.end()) scanSectorSizeLine(*pos); else y2war("could not find sector size"); pos = find_if(stdout, string_starts_with("Disk Flags:")); if (pos != stdout.end()) scanDiskFlags(*pos); else y2war("could not find disk flags"); gpt_enlarge = find_if(stderr, string_contains("fix the GPT to use all")) != stderr.end(); gpt_fix_backup = find_if(stderr, string_contains("backup GPT table is corrupt, but the " "primary appears OK")) != stderr.end(); if (label != PtType::PT_UNKNOWN && label != PtType::PT_LOOP) { int n = 0; // Parse partition tables: One with cylinder sizes, one with sector sizes for (const string& line : stdout) { if (boost::starts_with(line, "Number")) n++; string tmp = extractNthWord(0, line); if (!tmp.empty() && isdigit(tmp[0])) { if (n == 1) scanSectorEntryLine(line); else ST_THROW( ParseException( string( "Unexpected partition table #" ) + std::to_string(n), "", "" ) ); } } } y2mil(*this); } bool Parted::getEntry(unsigned num, Entry& entry) const { for (const_iterator it = entries.begin(); it != entries.end(); ++it) { if (it->num == num) { entry = *it; return true; } } return false; } std::ostream& operator<<(std::ostream& s, const Parted& parted) { s << "device:" << parted.device << " label:" << toString(parted.label) << " region:" << parted.region; if (parted.implicit) s << " implicit"; if (parted.gpt_enlarge) s << " gpt-enlarge"; if (parted.gpt_fix_backup) s << " gpt-fix-backup"; if (parted.gpt_pmbr_boot) s << " gpt-pmbr-boot"; s << '\n'; for (Parted::const_iterator it = parted.entries.begin(); it != parted.entries.end(); ++it) s << *it << '\n'; return s; } std::ostream& operator<<(std::ostream& s, const Parted::Entry& entry) { s << "num:" << entry.num << " region:" << entry.region << " type:" << toString(entry.type) << " id:" << entry.id; if (entry.boot) s << " boot"; if (entry.legacy_boot) s << " legacy-boot"; return s; } void Parted::scanDiskSize(const string& line) { string tmp(line); tmp.erase(0, tmp.find(':') + 1); int num_sectors = 0; tmp >> num_sectors; region.set_length(num_sectors); } void Parted::scanDiskFlags(const string& line) { implicit = boost::contains(line, "implicit_partition_table"); gpt_pmbr_boot = boost::contains(line, "pmbr_boot"); } void Parted::scanSectorSizeLine(const string& line) { // FIXME: This parser is too minimalistic and allows too much illegal input. // It turned out to be near impossible to come up with any test case that // actually made it throw an exception and not just silently do something random. // -- shundhammer 2015-05-13 string tmp(line); tmp.erase(0, tmp.find(':') + 1); tmp = extractNthWord(0, tmp); list<string> l = splitString(extractNthWord(0, tmp), "/"); if (l.size() == 2) { list<string>::const_iterator i = l.begin(); int logical_sector_size = 0; *i >> logical_sector_size; region.set_block_size(logical_sector_size); } else { ST_THROW( ParseException( "Bad sector size line", line, "Sector size (logical/physical): 512B/4096B" ) ); } } void Parted::scanSectorEntryLine(const string& line) { // Sample input: // // 1 2048s 4208639s 4206592s primary linux-swap(v1) type=82 // 2 4208640s 88100863s 83892224s primary btrfs boot, type=83 // 3 88100864s 171991039s 83890176s primary btrfs type=83 // 4 171991040s 3907028991s 3735037952s extended lba, type=0f // 5 171993088s 3907008511s 3735015424s logical xfs type=83 // // (Number) (Start) (End) (Size) (Type) (File system) (Flags) Entry entry; std::istringstream Data(line); classic(Data); unsigned long start_sector = 0; unsigned long end_sector = 0; unsigned long size_sector = 0; string PartitionTypeStr; string skip; if (label == PtType::MSDOS) { Data >> entry.num >> start_sector >> skip >> end_sector >> skip >> size_sector >> skip >> PartitionTypeStr; } else { Data >> entry.num >> start_sector >> skip >> end_sector >> skip >> size_sector >> skip; } if ( Data.fail() ) // parse error? { ST_THROW(ParseException("Bad sector-based partition entry", line, "2 4208640s 88100863s 83892224s primary btrfs boot, type=83")); } y2mil("num:" << entry.num << " start-sector:" << start_sector << " end-sector:" << end_sector << " size-sector:" << size_sector); if (entry.num == 0) ST_THROW(ParseException("Illegal partition number 0", line, "")); entry.region = Region(start_sector, size_sector, region.get_block_size()); // TODO the parser simply adds the filesystem, name and flags to one // list and then does string matching. This cannot work reliable, just // think of a partition named "esp" containing swap. Use 'parted // --machine'. char c; string TInfo; Data.unsetf(ifstream::skipws); Data >> c; char last_char = ','; while( Data.good() && !Data.eof() ) { if ( !isspace(c) ) { TInfo += c; last_char = c; } else { if ( last_char != ',' ) { TInfo += ","; last_char = ','; } } Data >> c; } boost::to_lower(TInfo, locale::classic()); list<string> flags = splitString(TInfo, ","); y2mil("TInfo:" << TInfo << " flags:" << flags); // TODO parted has a strange interface to represent partition type // ids. E.g. swap is not displayed based on the id but the partition // content. On GPT it is also not possible to distinguish whether the // id is linux or unknown. Work with upsteam parted to improve the // interface. The line below should then be entry.id = ID_UNKNOWN. entry.id = ID_LINUX; if (label == PtType::MSDOS) { if (PartitionTypeStr == "extended") { entry.type = PartitionType::EXTENDED; entry.id = ID_EXTENDED; } else if (entry.num >= 5) { entry.type = PartitionType::LOGICAL; } } else if (contains_if(flags, string_starts_with("fat"))) { entry.id = ID_DOS32; } else if (contains(flags, "ntfs")) { entry.id = ID_NTFS; } else if (contains_if(flags, string_contains("swap"))) { entry.id = ID_SWAP; } else if (contains(flags, "raid")) { entry.id = ID_RAID; } else if (contains(flags, "lvm")) { entry.id = ID_LVM; } else if (contains(flags, "prep")) { entry.id = ID_PREP; } if (contains(flags, "esp")) { entry.id = ID_ESP; } if (label == PtType::MSDOS) { entry.boot = contains(flags, "boot"); list<string>::const_iterator it1 = find_if(flags.begin(), flags.end(), string_starts_with("type=")); if (it1 != flags.end()) { string val = string(*it1, 5); int tmp_id = 0; std::istringstream Data2(val); classic(Data2); Data2 >> std::hex >> tmp_id; if (tmp_id > 0) { entry.id = tmp_id; } } } if (label == PtType::GPT) { entry.legacy_boot = contains(flags, "legacy_boot"); if (contains(flags, "bios_grub")) { entry.id = ID_BIOS_BOOT; } else if (contains(flags, "msftdata")) { entry.id = ID_WINDOWS_BASIC_DATA; } else if (contains(flags, "msftres")) { entry.id = ID_MICROSOFT_RESERVED; } } y2mil("num:" << entry.num << " region:" << entry.region << " id:" << entry.id << " type:" << toString(entry.type)); entries.push_back(entry); } } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/operators/recurrent_op.h" #include <glog/logging.h> #include <gtest/gtest.h> #include "paddle/framework/ddim.h" #include "paddle/framework/op_registry.h" #include "paddle/framework/operator.h" #include "paddle/framework/tensor.h" #include "paddle/operators/net_op.h" namespace paddle { namespace operators { using framework::make_ddim; using framework::DDim; class RecurrentOpTest : public ::testing::Test { protected: virtual void SetUp() override { CreateGlobalVariables(); CreateStepNet(); CreateRNNOp(); } virtual void TearDown() override {} void CreateGlobalVariables() { // create input, and init content LOG(INFO) << "create global variable x"; for (auto inlink : std::vector<std::string>{"x", "x0", "x1", "h"}) { Variable* x = scope_.NewVar(inlink); DDim dims = make_ddim(std::vector<int>{ 10 /*sent size*/, 20 /*batch size*/, 30 /*input dim*/}); x->GetMutable<Tensor>()->mutable_data<float>(dims, platform::CPUPlace()); } // create output alias just for test for (auto inlink : std::vector<std::string>{"h@alias"}) { Variable* x = scope_.NewVar(inlink); DDim dims = make_ddim(std::vector<int>{20 /*batch size*/, 30 /*input dim*/}); x->GetMutable<Tensor>()->mutable_data<float>(dims, platform::CPUPlace()); } LOG(INFO) << "create global variable w"; Variable* w = scope_.NewVar("rnn/w"); w->GetMutable<Tensor>()->mutable_data<float>( make_ddim(std::vector<int>{30, 30}), platform::CPUPlace()); for (auto boot : std::vector<std::string>{"h_boot"}) { LOG(INFO) << "create global variable " << boot; Variable* h_boot = scope_.NewVar(boot); h_boot->GetMutable<Tensor>()->mutable_data<float>( make_ddim(std::vector<int>{20 /*batch size*/, 30 /*input dim*/}), platform::CPUPlace()); } LOG(INFO) << "create variable step_scopes"; scope_.NewVar("step_scopes"); LOG(INFO) << "create variable h"; scope_.NewVar("h"); } void CreateRNNOp() { framework::OpDesc op_desc; op_desc.set_type("recurrent_op"); // inlinks 0 op_desc.add_inputs("x"); op_desc.add_inputs("x0"); op_desc.add_inputs("x1"); // boot_memories 3 op_desc.add_inputs("h_boot"); // step net 5 op_desc.add_inputs("step_net"); // outlinks 6 op_desc.add_outputs("h"); // step scopes 7 op_desc.add_outputs("step_scopes"); auto _input_format = std::vector<int>{ 0, // in_link 3, // memories 4 // step_net }; auto input_format = op_desc.add_attrs(); input_format->set_name("input_format"); input_format->set_type(paddle::framework::AttrType::INTS); for (auto i : _input_format) { input_format->add_ints(i); } auto output_format = op_desc.add_attrs(); output_format->set_name("output_format"); output_format->set_type(paddle::framework::AttrType::INTS); for (auto i : std::vector<int>{0, 1, 2}) { output_format->add_ints(i); } auto inlink_alias = op_desc.add_attrs(); inlink_alias->set_name("inlink_alias"); inlink_alias->set_type(paddle::framework::AttrType::STRINGS); auto outlink_alias = op_desc.add_attrs(); outlink_alias->set_name("outlink_alias"); outlink_alias->set_type(paddle::framework::AttrType::STRINGS); auto pre_memories = op_desc.add_attrs(); pre_memories->set_name("pre_memories"); pre_memories->set_type(paddle::framework::AttrType::STRINGS); auto memories = op_desc.add_attrs(); memories->set_name("memories"); memories->set_type(paddle::framework::AttrType::STRINGS); // create inlink_alias for (const auto& item : std::vector<std::string>{"x@alias", "x0@alias", "x1@alias"}) { inlink_alias->add_strings(item); } // pre memories for (const auto& item : std::vector<std::string>{"rnn/h@pre"}) { pre_memories->add_strings(item); } // memories for (const auto& item : std::vector<std::string>{"rnn/h"}) { memories->add_strings(item); } // output alias for (const auto& item : std::vector<std::string>{"h@alias"}) { outlink_alias->add_strings(item); } rnn_op_ = OpRegistry::CreateOp(op_desc); LOG(INFO) << "rnn_op finish init"; } void CreateStepNet() { LOG(INFO) << "create variable step_net"; Variable* var = scope_.NewVar("step_net"); auto net = var->GetMutable<NetOp>(); net->AddOp( OpRegistry::CreateOp("mul", {"rnn/h@pre", "rnn/w"}, {"rnn/s"}, {})); net->AddOp( OpRegistry::CreateOp("add_two", {"x@alias", "rnn/s"}, {"rnn/h"}, {})); net->CompleteAddOp(); } // father scope Scope scope_; std::shared_ptr<OperatorBase> rnn_op_; }; TEST_F(RecurrentOpTest, Run) { platform::CPUDeviceContext ctx; rnn_op_->InferShape(scope_); rnn_op_->Run(scope_, ctx); } class RecurrentGradientAlgorithmTest : public ::testing::Test { protected: virtual void SetUp() override { CreateGlobalVariables(); CreateStepScopes(); CreateStepNet(); CreateRNNGradientAlgorithm(); // segment inputs SegmentInputs(); // link forward memories LinkeMemories(); } virtual void TearDown() override {} void CreateGlobalVariables() { // inputs: x LOG(INFO) << "create global variable x"; Variable* x = scope_.NewVar("x"); DDim dims = make_ddim({10 /*sent size*/, 20 /*batch size*/, 30 /*input dim*/}); x->GetMutable<Tensor>()->mutable_data<float>(dims, platform::CPUPlace()); // inputs: h_boot LOG(INFO) << "create global variable h_boot"; Variable* h_boot = scope_.NewVar("h_boot"); h_boot->GetMutable<Tensor>()->mutable_data<float>( make_ddim({20 /*batch size*/, 30 /*input dim*/}), platform::CPUPlace()); // inputs: w LOG(INFO) << "create global variable w"; Variable* w = scope_.NewVar("rnn/w"); w->GetMutable<Tensor>()->mutable_data<float>(make_ddim({30, 30}), platform::CPUPlace()); // inputs: h_grad LOG(INFO) << "create variable h_grad"; Variable* dh = scope_.NewVar("h_grad"); dh->GetMutable<Tensor>()->mutable_data<float>(make_ddim({10, 20, 30}), platform::CPUPlace()); // inputs: step_scopes LOG(INFO) << "create variable step_scopes"; scope_.NewVar("step_scopes"); // inputs: step_net LOG(INFO) << "create variable step_net"; scope_.NewVar("step_net"); // outputs: w_grad LOG(INFO) << "create global variable w_grad"; scope_.NewVar("rnn/w_grad"); // outputs: x_grad LOG(INFO) << "create global variable x_grad"; scope_.NewVar("x_grad"); // outputs: h_boot_grad LOG(INFO) << "create global variable h_boot_grad"; scope_.NewVar("h_boot_grad"); } void CreateStepScopes() { auto step_scopes = scope_.FindVar("step_scopes")->GetMutable<std::vector<Scope*>>(); for (int i = 0; i < 10; ++i) { auto& scope = scope_.NewScope(); auto pre_t = scope.NewVar("rnn/pre_h")->GetMutable<Tensor>(); pre_t->mutable_data<float>({20, 30}, platform::CPUPlace()); auto tensor = scope.NewVar("rnn/h")->GetMutable<Tensor>(); tensor->mutable_data<float>({20, 30}, platform::CPUPlace()); // for unit test of ConcatOutputs auto xg = scope.NewVar("rnn/x_grad")->GetMutable<Tensor>(); xg->mutable_data<float>({20, 30}, platform::CPUPlace()); step_scopes->emplace_back(&scope); } // last time step auto g = (*step_scopes)[9]->NewVar("rnn/h_pre_grad")->GetMutable<Tensor>(); g->mutable_data<float>({20, 30}, platform::CPUPlace()); } void CreateRNNGradientAlgorithm() { std::unique_ptr<rnn::Argument> arg(new rnn::Argument()); arg->step_net = "step_net"; arg->step_scopes = "step_scopes"; rnn::Link inlink; inlink.external = "h_grad"; inlink.internal = "rnn/h_grad"; arg->inlinks = std::vector<rnn::Link>{inlink}; rnn::Link outlink; outlink.external = "x_grad"; outlink.internal = "rnn/x_grad"; arg->outlinks = std::vector<rnn::Link>{outlink}; rnn::MemoryAttr mem_attr; mem_attr.pre_var = "rnn/h_pre_grad"; mem_attr.var = "rnn/h_grad"; mem_attr.boot_var = "h_boot_grad"; arg->memories = std::vector<rnn::MemoryAttr>{mem_attr}; rnn_grad_algo_.Init(std::move(arg)); } void CreateStepNet() { LOG(INFO) << "create variable step_net"; Variable* var = scope_.NewVar("step_net"); auto net = var->GetMutable<NetOp>(); net->AddOp(OpRegistry::CreateOp("mul", {"rnn/h_pre", "rnn/w", "rnn/s_grad"}, {"rnn/h_pre_grad", "rnn/w_grad"}, {})); net->AddOp(OpRegistry::CreateOp("add_two", {"rnn/h_grad"}, {"rnn/x_grad", "rnn/s_grad"}, {})); net->CompleteAddOp(); } void SegmentInputs() { LOG(INFO) << "segment inputs"; std::vector<std::string> inlinks = {"x"}; std::vector<std::string> inlinks_alias = {"rnn/x"}; rnn::Link inlink; inlink.external = "x"; inlink.internal = "rnn/x"; auto step_scopes = scope_.FindVar("step_scopes")->GetMutable<std::vector<Scope*>>(); rnn::SegmentInputs(*step_scopes, std::vector<rnn::Link>{inlink}, 10, true /*infer_shape_mode*/); } void LinkeMemories() { LOG(INFO) << "link memories"; rnn::MemoryAttr mem_attr; mem_attr.pre_var = "rnn/h_pre"; mem_attr.var = "rnn/h"; mem_attr.boot_var = "boot_h"; std::vector<rnn::MemoryAttr> memories; memories.push_back(mem_attr); auto step_scopes = scope_.FindVar("step_scopes")->GetMutable<std::vector<Scope*>>(); for (int i = 1; i < 10; ++i) { rnn::LinkMemories(*step_scopes, memories, i, -1, true /*infer_shape_mode*/); } } Scope scope_; RecurrentGradientAlgorithm rnn_grad_algo_; }; // TEST_F(RecurrentGradientAlgorithmTest, Run) { // platform::CPUDeviceContext ctx; // rnn_grad_algo_.Run(scope_, ctx); // } } // namespace operators } // namespace paddle TEST(RecurrentOp, LinkMemories) { using namespace paddle::framework; using namespace paddle::platform; using namespace paddle::operators; // create and init step scopes size_t len = 10; std::vector<Scope*> step_scopes; for (size_t i = 0; i < len; ++i) { auto scope = new Scope(); scope->NewVar("pre_h"); auto tensor = scope->NewVar("h")->GetMutable<Tensor>(); float* data = tensor->mutable_data<float>({15, 20}, CPUPlace()); for (size_t j = 0; j < 15 * 20; ++j) { data[j] = rand() * (1. / (double)RAND_MAX); } step_scopes.push_back(scope); } // create MemoryAttr rnn::MemoryAttr mem_attr; mem_attr.pre_var = "pre_h"; mem_attr.var = "h"; mem_attr.boot_var = "boot_h"; std::vector<rnn::MemoryAttr> memories; memories.push_back(mem_attr); for (size_t i = 1; i < len; ++i) { rnn::LinkMemories(step_scopes, memories, i, -1, false /*infer_shape_mode*/); } // check for (size_t i = 0; i < len - 1; ++i) { const float* a = step_scopes[i]->FindVar("h")->GetMutable<Tensor>()->data<float>(); const float* b = step_scopes[i + 1] ->FindVar("pre_h") ->GetMutable<Tensor>() ->data<float>(); for (size_t j = 0; j < 15 * 20; ++j) { ASSERT_FLOAT_EQ(a[j], b[j]); } } for (int i = len - 2; i >= 0; --i) { rnn::LinkMemories(step_scopes, memories, i, 1, false /*infer_shape_mode*/); } // check for (int i = len - 2; i >= 0; --i) { const float* a = step_scopes[i]->FindVar("pre_h")->GetMutable<Tensor>()->data<float>(); const float* b = step_scopes[i + 1]->FindVar("h")->GetMutable<Tensor>()->data<float>(); for (size_t j = 0; j < 15 * 20; ++j) { ASSERT_FLOAT_EQ(a[j], b[j]); } } for (auto s : step_scopes) { delete s; } } USE_OP(add_two); USE_OP(mul); USE_OP_WITHOUT_KERNEL(recurrent_op); <commit_msg>"fix recurrent op test"<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve. 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 "paddle/operators/recurrent_op.h" #include <glog/logging.h> #include <gtest/gtest.h> #include "paddle/framework/ddim.h" #include "paddle/framework/op_registry.h" #include "paddle/framework/operator.h" #include "paddle/framework/tensor.h" #include "paddle/operators/net_op.h" namespace paddle { namespace operators { using framework::make_ddim; using framework::DDim; using framework::Tensor; using framework::Variable; using framework::Scope; using framework::OpRegistry; class RecurrentOpTest : public ::testing::Test { protected: virtual void SetUp() override { CreateGlobalVariables(); CreateStepNet(); CreateRNNOp(); } virtual void TearDown() override {} void CreateGlobalVariables() { // create input, and init content LOG(INFO) << "create global variable x"; for (auto inlink : std::vector<std::string>{"x", "x0", "x1", "h"}) { Variable* x = scope_.NewVar(inlink); DDim dims = make_ddim(std::vector<int>{ 10 /*sent size*/, 20 /*batch size*/, 30 /*input dim*/}); x->GetMutable<Tensor>()->mutable_data<float>(dims, platform::CPUPlace()); } // create output alias just for test for (auto inlink : std::vector<std::string>{"h@alias"}) { Variable* x = scope_.NewVar(inlink); DDim dims = make_ddim(std::vector<int>{20 /*batch size*/, 30 /*input dim*/}); x->GetMutable<Tensor>()->mutable_data<float>(dims, platform::CPUPlace()); } LOG(INFO) << "create global variable w"; Variable* w = scope_.NewVar("rnn/w"); w->GetMutable<Tensor>()->mutable_data<float>( make_ddim(std::vector<int>{30, 30}), platform::CPUPlace()); for (auto boot : std::vector<std::string>{"h_boot"}) { LOG(INFO) << "create global variable " << boot; Variable* h_boot = scope_.NewVar(boot); h_boot->GetMutable<Tensor>()->mutable_data<float>( make_ddim(std::vector<int>{20 /*batch size*/, 30 /*input dim*/}), platform::CPUPlace()); } LOG(INFO) << "create variable step_scopes"; scope_.NewVar("step_scopes"); LOG(INFO) << "create variable h"; scope_.NewVar("h"); } void CreateRNNOp() { framework::OpDesc op_desc; op_desc.set_type("recurrent_op"); // inlinks 0 op_desc.add_inputs("x"); op_desc.add_inputs("x0"); op_desc.add_inputs("x1"); // boot_memories 3 op_desc.add_inputs("h_boot"); // step net 5 op_desc.add_inputs("step_net"); // outlinks 6 op_desc.add_outputs("h"); // step scopes 7 op_desc.add_outputs("step_scopes"); auto _input_format = std::vector<int>{ 0, // in_link 3, // memories 4 // step_net }; auto input_format = op_desc.add_attrs(); input_format->set_name("input_format"); input_format->set_type(paddle::framework::AttrType::INTS); for (auto i : _input_format) { input_format->add_ints(i); } auto output_format = op_desc.add_attrs(); output_format->set_name("output_format"); output_format->set_type(paddle::framework::AttrType::INTS); for (auto i : std::vector<int>{0, 1, 2}) { output_format->add_ints(i); } auto inlink_alias = op_desc.add_attrs(); inlink_alias->set_name("inlink_alias"); inlink_alias->set_type(paddle::framework::AttrType::STRINGS); auto outlink_alias = op_desc.add_attrs(); outlink_alias->set_name("outlink_alias"); outlink_alias->set_type(paddle::framework::AttrType::STRINGS); auto pre_memories = op_desc.add_attrs(); pre_memories->set_name("pre_memories"); pre_memories->set_type(paddle::framework::AttrType::STRINGS); auto memories = op_desc.add_attrs(); memories->set_name("memories"); memories->set_type(paddle::framework::AttrType::STRINGS); // create inlink_alias for (const auto& item : std::vector<std::string>{"x@alias", "x0@alias", "x1@alias"}) { inlink_alias->add_strings(item); } // pre memories for (const auto& item : std::vector<std::string>{"rnn/h@pre"}) { pre_memories->add_strings(item); } // memories for (const auto& item : std::vector<std::string>{"rnn/h"}) { memories->add_strings(item); } // output alias for (const auto& item : std::vector<std::string>{"h@alias"}) { outlink_alias->add_strings(item); } rnn_op_ = OpRegistry::CreateOp(op_desc); LOG(INFO) << "rnn_op finish init"; } void CreateStepNet() { LOG(INFO) << "create variable step_net"; Variable* var = scope_.NewVar("step_net"); auto net = var->GetMutable<NetOp>(); net->AddOp( OpRegistry::CreateOp("mul", {"rnn/h@pre", "rnn/w"}, {"rnn/s"}, {})); net->AddOp( OpRegistry::CreateOp("add_two", {"x@alias", "rnn/s"}, {"rnn/h"}, {})); net->CompleteAddOp(); } // father scope Scope scope_; std::shared_ptr<framework::OperatorBase> rnn_op_; }; TEST_F(RecurrentOpTest, Run) { platform::CPUDeviceContext ctx; rnn_op_->InferShape(scope_); rnn_op_->Run(scope_, ctx); } class RecurrentGradientAlgorithmTest : public ::testing::Test { protected: virtual void SetUp() override { CreateGlobalVariables(); CreateStepScopes(); CreateStepNet(); CreateRNNGradientAlgorithm(); // segment inputs SegmentInputs(); // link forward memories LinkeMemories(); } virtual void TearDown() override {} void CreateGlobalVariables() { // inputs: x LOG(INFO) << "create global variable x"; Variable* x = scope_.NewVar("x"); DDim dims = make_ddim({10 /*sent size*/, 20 /*batch size*/, 30 /*input dim*/}); x->GetMutable<Tensor>()->mutable_data<float>(dims, platform::CPUPlace()); // inputs: h_boot LOG(INFO) << "create global variable h_boot"; Variable* h_boot = scope_.NewVar("h_boot"); h_boot->GetMutable<Tensor>()->mutable_data<float>( make_ddim({20 /*batch size*/, 30 /*input dim*/}), platform::CPUPlace()); // inputs: w LOG(INFO) << "create global variable w"; Variable* w = scope_.NewVar("rnn/w"); w->GetMutable<Tensor>()->mutable_data<float>(make_ddim({30, 30}), platform::CPUPlace()); // inputs: h_grad LOG(INFO) << "create variable h_grad"; Variable* dh = scope_.NewVar("h_grad"); dh->GetMutable<Tensor>()->mutable_data<float>(make_ddim({10, 20, 30}), platform::CPUPlace()); // inputs: step_scopes LOG(INFO) << "create variable step_scopes"; scope_.NewVar("step_scopes"); // inputs: step_net LOG(INFO) << "create variable step_net"; scope_.NewVar("step_net"); // outputs: w_grad LOG(INFO) << "create global variable w_grad"; scope_.NewVar("rnn/w_grad"); // outputs: x_grad LOG(INFO) << "create global variable x_grad"; scope_.NewVar("x_grad"); // outputs: h_boot_grad LOG(INFO) << "create global variable h_boot_grad"; scope_.NewVar("h_boot_grad"); } void CreateStepScopes() { auto step_scopes = scope_.FindVar("step_scopes")->GetMutable<std::vector<Scope*>>(); for (int i = 0; i < 10; ++i) { auto& scope = scope_.NewScope(); auto pre_t = scope.NewVar("rnn/pre_h")->GetMutable<Tensor>(); pre_t->mutable_data<float>({20, 30}, platform::CPUPlace()); auto tensor = scope.NewVar("rnn/h")->GetMutable<Tensor>(); tensor->mutable_data<float>({20, 30}, platform::CPUPlace()); // for unit test of ConcatOutputs auto xg = scope.NewVar("rnn/x_grad")->GetMutable<Tensor>(); xg->mutable_data<float>({20, 30}, platform::CPUPlace()); step_scopes->emplace_back(&scope); } // last time step auto g = (*step_scopes)[9]->NewVar("rnn/h_pre_grad")->GetMutable<Tensor>(); g->mutable_data<float>({20, 30}, platform::CPUPlace()); } void CreateRNNGradientAlgorithm() { std::unique_ptr<rnn::Argument> arg(new rnn::Argument()); arg->step_net = "step_net"; arg->step_scopes = "step_scopes"; rnn::Link inlink; inlink.external = "h_grad"; inlink.internal = "rnn/h_grad"; arg->inlinks = std::vector<rnn::Link>{inlink}; rnn::Link outlink; outlink.external = "x_grad"; outlink.internal = "rnn/x_grad"; arg->outlinks = std::vector<rnn::Link>{outlink}; rnn::MemoryAttr mem_attr; mem_attr.pre_var = "rnn/h_pre_grad"; mem_attr.var = "rnn/h_grad"; mem_attr.boot_var = "h_boot_grad"; arg->memories = std::vector<rnn::MemoryAttr>{mem_attr}; rnn_grad_algo_.Init(std::move(arg)); } void CreateStepNet() { LOG(INFO) << "create variable step_net"; Variable* var = scope_.NewVar("step_net"); auto net = var->GetMutable<NetOp>(); net->AddOp(OpRegistry::CreateOp("mul", {"rnn/h_pre", "rnn/w", "rnn/s_grad"}, {"rnn/h_pre_grad", "rnn/w_grad"}, {})); net->AddOp(OpRegistry::CreateOp("add_two", {"rnn/h_grad"}, {"rnn/x_grad", "rnn/s_grad"}, {})); net->CompleteAddOp(); } void SegmentInputs() { LOG(INFO) << "segment inputs"; std::vector<std::string> inlinks = {"x"}; std::vector<std::string> inlinks_alias = {"rnn/x"}; rnn::Link inlink; inlink.external = "x"; inlink.internal = "rnn/x"; auto step_scopes = scope_.FindVar("step_scopes")->GetMutable<std::vector<Scope*>>(); rnn::SegmentInputs(*step_scopes, std::vector<rnn::Link>{inlink}, 10, true /*infer_shape_mode*/); } void LinkeMemories() { LOG(INFO) << "link memories"; rnn::MemoryAttr mem_attr; mem_attr.pre_var = "rnn/h_pre"; mem_attr.var = "rnn/h"; mem_attr.boot_var = "boot_h"; std::vector<rnn::MemoryAttr> memories; memories.push_back(mem_attr); auto step_scopes = scope_.FindVar("step_scopes")->GetMutable<std::vector<Scope*>>(); for (int i = 1; i < 10; ++i) { rnn::LinkMemories(*step_scopes, memories, i, -1, true /*infer_shape_mode*/); } } Scope scope_; RecurrentGradientAlgorithm rnn_grad_algo_; }; // TEST_F(RecurrentGradientAlgorithmTest, Run) { // platform::CPUDeviceContext ctx; // rnn_grad_algo_.Run(scope_, ctx); // } } // namespace operators } // namespace paddle TEST(RecurrentOp, LinkMemories) { using namespace paddle::framework; using namespace paddle::platform; using namespace paddle::operators; // create and init step scopes size_t len = 10; std::vector<Scope*> step_scopes; for (size_t i = 0; i < len; ++i) { auto scope = new Scope(); scope->NewVar("pre_h"); auto tensor = scope->NewVar("h")->GetMutable<Tensor>(); float* data = tensor->mutable_data<float>({15, 20}, CPUPlace()); for (size_t j = 0; j < 15 * 20; ++j) { data[j] = rand() * (1. / (double)RAND_MAX); } step_scopes.push_back(scope); } // create MemoryAttr rnn::MemoryAttr mem_attr; mem_attr.pre_var = "pre_h"; mem_attr.var = "h"; mem_attr.boot_var = "boot_h"; std::vector<rnn::MemoryAttr> memories; memories.push_back(mem_attr); for (size_t i = 1; i < len; ++i) { rnn::LinkMemories(step_scopes, memories, i, -1, false /*infer_shape_mode*/); } // check for (size_t i = 0; i < len - 1; ++i) { const float* a = step_scopes[i]->FindVar("h")->GetMutable<Tensor>()->data<float>(); const float* b = step_scopes[i + 1] ->FindVar("pre_h") ->GetMutable<Tensor>() ->data<float>(); for (size_t j = 0; j < 15 * 20; ++j) { ASSERT_FLOAT_EQ(a[j], b[j]); } } for (int i = len - 2; i >= 0; --i) { rnn::LinkMemories(step_scopes, memories, i, 1, false /*infer_shape_mode*/); } // check for (int i = len - 2; i >= 0; --i) { const float* a = step_scopes[i]->FindVar("pre_h")->GetMutable<Tensor>()->data<float>(); const float* b = step_scopes[i + 1]->FindVar("h")->GetMutable<Tensor>()->data<float>(); for (size_t j = 0; j < 15 * 20; ++j) { ASSERT_FLOAT_EQ(a[j], b[j]); } } for (auto s : step_scopes) { delete s; } } USE_OP(add_two); USE_OP(mul); USE_OP_WITHOUT_KERNEL(recurrent_op); <|endoftext|>
<commit_before>#include "gauss_convol.h" #include <cassert> #include <cmath> /* Gaussian convolution kernels are truncated at this many sigmas from the center. While it is more efficient to keep this value small, experiments show that for consistent scale-space analysis it needs a value of about 3.0, at which point the Gaussian has fallen to only 1% of its central value. A value of 2.0 greatly reduces keypoint consistency, and a value of 4.0 is better than 3.0. */ static const flnum GaussTruncate = 4.0; /* --------------------------- Blur image --------------------------- */ /* Same as ConvBuffer, but implemented with loop unrolling for increased speed. This is the most time intensive routine in keypoint detection, so deserves careful attention to efficiency. Loop unrolling simply sums 5 multiplications at a time to allow the compiler to schedule operations better and avoid loop overhead. This almost triples speed of previous version on a Pentium with gcc. */ static void ConvBufferFast(flnum *buffer, flnum *kernel, int rsize, int ksize) { int i; flnum sum, *bp, *kp, *endkp; for (i = 0; i < rsize; i++) { sum = 0.0; bp = &buffer[i]; kp = &kernel[0]; endkp = &kernel[ksize]; /* Loop unrolling: do 5 multiplications at a time. */ while (kp + 4 < endkp) { sum += bp[0] * kp[0] + bp[1] * kp[1] + bp[2] * kp[2] + bp[3] * kp[3] + bp[4] * kp[4]; bp += 5; kp += 5; } /* Do 2 multiplications at a time on remaining items. */ while (kp + 1 < endkp) { sum += bp[0] * kp[0] + bp[1] * kp[1]; bp += 2; kp += 2; } /* Finish last one if needed. */ if (kp < endkp) sum += *bp * *kp; buffer[i] = sum; } } /* Convolve image with the 1-D kernel vector along image rows. This is designed to be as efficient as possible. Pixels outside the image are set to the value of the closest image pixel. */ static void ConvHorizontal(LWImage<flnum>& image, flnum *kernel, int ksize) { flnum buffer[8000]; const int rows = image.h; const int cols = image.w; const int halfsize = ksize / 2; assert(cols + ksize < 8000); /*TANG: this will give a limit of image size*/ for(int comp = 0; comp < image.comps; comp++) { const int deltaComp = comp*image.stepComp(); for (int r = 0; r < rows; r++) { /* Copy the row into buffer with pixels at ends replicated for half the mask size. This avoids need to check for ends within inner loop. */ for (int i = 0; i < halfsize; i++) buffer[i] = image.pixel(0,r)[deltaComp]; for (int i = 0; i < cols; i++) buffer[halfsize + i] = image.pixel(i,r)[deltaComp]; for (int i = 0; i < halfsize; i++) buffer[halfsize + cols + i] = image.pixel(cols-1,r)[deltaComp]; ConvBufferFast(buffer, kernel, cols, ksize); for (int c = 0; c < cols; c++) image.pixel(c,r)[deltaComp] = buffer[c]; } } } /* Same as ConvHorizontal, but apply to vertical columns of image. */ static void ConvVertical(LWImage<flnum>& image, flnum *kernel, int ksize) { flnum buffer[8000]; const int rows = image.h; const int cols = image.w; const int halfsize = ksize / 2; assert(rows + ksize < 8000); /*TANG: this will give a limit of image size*/ for(int comp = 0; comp < image.comps; comp++) { const int deltaComp = comp*image.stepComp(); for (int c = 0; c < cols; c++) { for (int i = 0; i < halfsize; i++) buffer[i] = image.pixel(c,0)[deltaComp]; for (int i = 0; i < rows; i++) buffer[halfsize + i] = image.pixel(c,i)[deltaComp]; for (int i = 0; i < halfsize; i++) buffer[halfsize + rows + i] = image.pixel(c,rows-1)[deltaComp]; ConvBufferFast(buffer, kernel, rows, ksize); for (int r = 0; r < rows; r++) image.pixel(c,r)[deltaComp] = buffer[r]; } } } /* Convolve image with a Gaussian of width sigma and store result back in image. This routine creates the Gaussian kernel, and then applies it sequentially in horizontal and vertical directions. */ void gauss_convol(LWImage<flnum>& image, flnum sigma) { /*float x, kernel[100], sum = 0.0;*/ flnum x, kernel[1000], sum = 0.0; /*TANG*/ int ksize, i; /* The Gaussian kernel is truncated at GaussTruncate sigmas from center. The kernel size should be odd. */ ksize = (int)(2.0 * GaussTruncate * sigma + 1.0); /*ksize = MAX(3, ksize);*/ /* Kernel must be at least 3. */ ksize = ksize > 3 ? ksize : 3; if (ksize % 2 == 0) /* Make kernel size odd. */ ksize++; /*assert(ksize < 100);*/ assert(ksize < 1000); /*TANG*/ /* Fill in kernel values. */ for (i = 0; i <= ksize; i++) { x = static_cast<flnum>(i - ksize/2); kernel[i] = exp(- x * x / (2 * sigma * sigma)); sum += kernel[i]; } /* Normalize kernel values to sum to 1.0. */ for (i = 0; i < ksize; i++) kernel[i] /= sum; ConvHorizontal(image, kernel, ksize); ConvVertical(image, kernel, ksize); } <commit_msg>FIX homography: increase static buffer size: 200000 elements<commit_after>#include "gauss_convol.h" #include <cassert> #include <cmath> /* Gaussian convolution kernels are truncated at this many sigmas from the center. While it is more efficient to keep this value small, experiments show that for consistent scale-space analysis it needs a value of about 3.0, at which point the Gaussian has fallen to only 1% of its central value. A value of 2.0 greatly reduces keypoint consistency, and a value of 4.0 is better than 3.0. */ static const flnum GaussTruncate = 4.0; /* --------------------------- Blur image --------------------------- */ /* Same as ConvBuffer, but implemented with loop unrolling for increased speed. This is the most time intensive routine in keypoint detection, so deserves careful attention to efficiency. Loop unrolling simply sums 5 multiplications at a time to allow the compiler to schedule operations better and avoid loop overhead. This almost triples speed of previous version on a Pentium with gcc. */ static void ConvBufferFast(flnum *buffer, flnum *kernel, int rsize, int ksize) { int i; flnum sum, *bp, *kp, *endkp; for (i = 0; i < rsize; i++) { sum = 0.0; bp = &buffer[i]; kp = &kernel[0]; endkp = &kernel[ksize]; /* Loop unrolling: do 5 multiplications at a time. */ while (kp + 4 < endkp) { sum += bp[0] * kp[0] + bp[1] * kp[1] + bp[2] * kp[2] + bp[3] * kp[3] + bp[4] * kp[4]; bp += 5; kp += 5; } /* Do 2 multiplications at a time on remaining items. */ while (kp + 1 < endkp) { sum += bp[0] * kp[0] + bp[1] * kp[1]; bp += 2; kp += 2; } /* Finish last one if needed. */ if (kp < endkp) sum += *bp * *kp; buffer[i] = sum; } } /* Convolve image with the 1-D kernel vector along image rows. This is designed to be as efficient as possible. Pixels outside the image are set to the value of the closest image pixel. */ static void ConvHorizontal(LWImage<flnum>& image, flnum *kernel, int ksize) { flnum buffer[200000]; const int rows = image.h; const int cols = image.w; const int halfsize = ksize / 2; assert(cols + ksize < 200000); /*TANG: this will give a limit of image size*/ for(int comp = 0; comp < image.comps; comp++) { const int deltaComp = comp*image.stepComp(); for (int r = 0; r < rows; r++) { /* Copy the row into buffer with pixels at ends replicated for half the mask size. This avoids need to check for ends within inner loop. */ for (int i = 0; i < halfsize; i++) buffer[i] = image.pixel(0,r)[deltaComp]; for (int i = 0; i < cols; i++) buffer[halfsize + i] = image.pixel(i,r)[deltaComp]; for (int i = 0; i < halfsize; i++) buffer[halfsize + cols + i] = image.pixel(cols-1,r)[deltaComp]; ConvBufferFast(buffer, kernel, cols, ksize); for (int c = 0; c < cols; c++) image.pixel(c,r)[deltaComp] = buffer[c]; } } } /* Same as ConvHorizontal, but apply to vertical columns of image. */ static void ConvVertical(LWImage<flnum>& image, flnum *kernel, int ksize) { flnum buffer[200000]; const int rows = image.h; const int cols = image.w; const int halfsize = ksize / 2; assert(rows + ksize < 200000); /*TANG: this will give a limit of image size*/ for(int comp = 0; comp < image.comps; comp++) { const int deltaComp = comp*image.stepComp(); for (int c = 0; c < cols; c++) { for (int i = 0; i < halfsize; i++) buffer[i] = image.pixel(c,0)[deltaComp]; for (int i = 0; i < rows; i++) buffer[halfsize + i] = image.pixel(c,i)[deltaComp]; for (int i = 0; i < halfsize; i++) buffer[halfsize + rows + i] = image.pixel(c,rows-1)[deltaComp]; ConvBufferFast(buffer, kernel, rows, ksize); for (int r = 0; r < rows; r++) image.pixel(c,r)[deltaComp] = buffer[r]; } } } /* Convolve image with a Gaussian of width sigma and store result back in image. This routine creates the Gaussian kernel, and then applies it sequentially in horizontal and vertical directions. */ void gauss_convol(LWImage<flnum>& image, flnum sigma) { /*float x, kernel[100], sum = 0.0;*/ flnum x, kernel[200000], sum = 0.0; /*TANG*/ int ksize, i; /* The Gaussian kernel is truncated at GaussTruncate sigmas from center. The kernel size should be odd. */ ksize = (int)(2.0 * GaussTruncate * sigma + 1.0); /*ksize = MAX(3, ksize);*/ /* Kernel must be at least 3. */ ksize = ksize > 3 ? ksize : 3; if (ksize % 2 == 0) /* Make kernel size odd. */ ksize++; /*assert(ksize < 100);*/ assert(ksize < 200000); /*TANG*/ /* Fill in kernel values. */ for (i = 0; i <= ksize; i++) { x = static_cast<flnum>(i - ksize/2); kernel[i] = exp(- x * x / (2 * sigma * sigma)); sum += kernel[i]; } /* Normalize kernel values to sum to 1.0. */ for (i = 0; i < ksize; i++) kernel[i] /= sum; ConvHorizontal(image, kernel, ksize); ConvVertical(image, kernel, ksize); } <|endoftext|>
<commit_before>/* * Author: Brendan Le Foll <brendan.le.foll@intel.com> * Copyright (c) 2014 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "gpio.h" #include "types.hpp" #include <stdexcept> #if defined(SWIGJAVASCRIPT) #if NODE_MODULE_VERSION >= 0x000D #include <uv.h> #endif #endif namespace mraa { // These enums must match the enums in gpio.h /** * Gpio Output modes */ typedef enum { MODE_STRONG = 0, /**< Default. Strong High and Low */ MODE_PULLUP = 1, /**< Interupt on rising & falling */ MODE_PULLDOWN = 2, /**< Interupt on rising only */ MODE_HIZ = 3 /**< Interupt on falling only */ } Mode; /** * Gpio Direction options */ typedef enum { DIR_OUT = 0, /**< Output. A Mode can also be set */ DIR_IN = 1, /**< Input */ DIR_OUT_HIGH = 2, /**< Output. Init High */ DIR_OUT_LOW = 3 /**< Output. Init Low */ } Dir; /** * Gpio Edge types for interupts */ typedef enum { EDGE_NONE = 0, /**< No interrupt on Gpio */ EDGE_BOTH = 1, /**< Interupt on rising & falling */ EDGE_RISING = 2, /**< Interupt on rising only */ EDGE_FALLING = 3 /**< Interupt on falling only */ } Edge; /** * @brief API to General Purpose IO * * This file defines the gpio interface for libmraa * * @snippet Blink-IO.cpp Interesting */ class Gpio { public: /** * Instanciates a Gpio object * * @param pin pin number to use * @param owner (optional) Set pin owner, default behaviour is to 'own' * the pin if we exported it. This means we will close it on destruct. * Otherwise it will get left open. This is only valid in sysfs use * cases * @param raw (optional) Raw pins will use gpiolibs pin numbering from * the kernel module. Note that you will not get any muxers set up for * you so this may not always work as expected. */ Gpio(int pin, bool owner = true, bool raw = false) { if (raw) { m_gpio = mraa_gpio_init_raw(pin); } else { m_gpio = mraa_gpio_init(pin); } if (m_gpio == NULL) { throw std::invalid_argument("Invalid GPIO pin specified"); } if (!owner) { mraa_gpio_owner(m_gpio, 0); } } /** * Gpio object destructor, this will only unexport the gpio if we where * the owner */ ~Gpio() { mraa_gpio_close(m_gpio); } /** * Set the edge mode for ISR * * @param mode The edge mode to set * @return Result of operation */ Result edge(Edge mode) { return (Result) mraa_gpio_edge_mode(m_gpio, (mraa_gpio_edge_t) mode); } #if defined(SWIGPYTHON) Result isr(Edge mode, PyObject* pyfunc, PyObject* args) { return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, (void (*) (void*)) pyfunc, (void*) args); } #elif defined(SWIGJAVASCRIPT) static void v8isr(uv_work_t* req, int status) { mraa::Gpio* This = (mraa::Gpio*) req->data; int argc = 1; v8::Local<v8::Value> argv[] = { SWIGV8_INTEGER_NEW(-1) }; #if NODE_MODULE_VERSION >= 0x000D v8::Local<v8::Function> f = v8::Local<v8::Function>::New(v8::Isolate::GetCurrent(), This->m_v8isr); f->Call(SWIGV8_CURRENT_CONTEXT()->Global(), argc, argv); #else This->m_v8isr->Call(SWIGV8_CURRENT_CONTEXT()->Global(), argc, argv); #endif delete req; } static void nop(uv_work_t* req) { // Do nothing. } static void uvwork(void* ctx) { uv_work_t* req = new uv_work_t; req->data = ctx; uv_queue_work(uv_default_loop(), req, nop, v8isr); } Result isr(Edge mode, v8::Handle<v8::Function> func) { #if NODE_MODULE_VERSION >= 0x000D m_v8isr.Reset(v8::Isolate::GetCurrent(), func); #else m_v8isr = v8::Persistent<v8::Function>::New(func); #endif return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, &uvwork, this); } #elif defined(SWIGJAVA) || defined(JAVACALLBACK) Result isr(Edge mode, jobject runnable) { return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, mraa_java_isr_callback, runnable); } #endif /** * Sets a callback to be called when pin value changes * * @param mode The edge mode to set * @param fptr Function pointer to function to be called when interupt is * triggered * @param args Arguments passed to the interrupt handler (fptr) * @return Result of operation */ Result isr(Edge mode, void (*fptr)(void*), void* args) { return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, fptr, args); } /** * Exits callback - this call will not kill the isr thread immediatly * but only when it is out of it's critical section * * @return Result of operation */ Result isrExit() { #if defined(SWIGJAVASCRIPT) #if NODE_MODULE_VERSION >= 0x000D m_v8isr.Reset(); #else m_v8isr.Dispose(); m_v8isr.Clear(); #endif #endif return (Result) mraa_gpio_isr_exit(m_gpio); } /** * Change Gpio mode * * @param mode The mode to change the gpio into * @return Result of operation */ Result mode(Mode mode) { return (Result )mraa_gpio_mode(m_gpio, (mraa_gpio_mode_t) mode); } /** * Change Gpio direction * * @param dir The direction to change the gpio into * @return Result of operation */ Result dir(Dir dir) { return (Result )mraa_gpio_dir(m_gpio, (mraa_gpio_dir_t) dir); } /** * Read value from Gpio * * @return Gpio value */ int read() { return mraa_gpio_read(m_gpio); } /** * Write value to Gpio * * @param value Value to write to Gpio * @return Result of operation */ Result write(int value) { return (Result) mraa_gpio_write(m_gpio, value); } /** * Enable use of mmap i/o if available. * * @param enable true to use mmap * @return Result of operation */ Result useMmap(bool enable) { return (Result) mraa_gpio_use_mmaped(m_gpio, (mraa_boolean_t) enable); } /** * Get pin number of Gpio. If raw param is True will return the * number as used within sysfs. Invalid will return -1. * * @param raw (optional) get the raw gpio number. * @return Pin number */ int getPin(bool raw = false) { if (raw) { return mraa_gpio_get_pin_raw(m_gpio); } return mraa_gpio_get_pin(m_gpio); } private: mraa_gpio_context m_gpio; #if defined(SWIGJAVASCRIPT) v8::Persistent<v8::Function> m_v8isr; #endif }; } <commit_msg>gpio.hpp: Add direction read call for C++ & SWIG APIs<commit_after>/* * Author: Brendan Le Foll <brendan.le.foll@intel.com> * Copyright (c) 2014 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "gpio.h" #include "types.hpp" #include <stdexcept> #if defined(SWIGJAVASCRIPT) #if NODE_MODULE_VERSION >= 0x000D #include <uv.h> #endif #endif namespace mraa { // These enums must match the enums in gpio.h /** * Gpio Output modes */ typedef enum { MODE_STRONG = 0, /**< Default. Strong High and Low */ MODE_PULLUP = 1, /**< Interupt on rising & falling */ MODE_PULLDOWN = 2, /**< Interupt on rising only */ MODE_HIZ = 3 /**< Interupt on falling only */ } Mode; /** * Gpio Direction options */ typedef enum { DIR_OUT = 0, /**< Output. A Mode can also be set */ DIR_IN = 1, /**< Input */ DIR_OUT_HIGH = 2, /**< Output. Init High */ DIR_OUT_LOW = 3 /**< Output. Init Low */ } Dir; /** * Gpio Edge types for interupts */ typedef enum { EDGE_NONE = 0, /**< No interrupt on Gpio */ EDGE_BOTH = 1, /**< Interupt on rising & falling */ EDGE_RISING = 2, /**< Interupt on rising only */ EDGE_FALLING = 3 /**< Interupt on falling only */ } Edge; /** * @brief API to General Purpose IO * * This file defines the gpio interface for libmraa * * @snippet Blink-IO.cpp Interesting */ class Gpio { public: /** * Instanciates a Gpio object * * @param pin pin number to use * @param owner (optional) Set pin owner, default behaviour is to 'own' * the pin if we exported it. This means we will close it on destruct. * Otherwise it will get left open. This is only valid in sysfs use * cases * @param raw (optional) Raw pins will use gpiolibs pin numbering from * the kernel module. Note that you will not get any muxers set up for * you so this may not always work as expected. */ Gpio(int pin, bool owner = true, bool raw = false) { if (raw) { m_gpio = mraa_gpio_init_raw(pin); } else { m_gpio = mraa_gpio_init(pin); } if (m_gpio == NULL) { throw std::invalid_argument("Invalid GPIO pin specified"); } if (!owner) { mraa_gpio_owner(m_gpio, 0); } } /** * Gpio object destructor, this will only unexport the gpio if we where * the owner */ ~Gpio() { mraa_gpio_close(m_gpio); } /** * Set the edge mode for ISR * * @param mode The edge mode to set * @return Result of operation */ Result edge(Edge mode) { return (Result) mraa_gpio_edge_mode(m_gpio, (mraa_gpio_edge_t) mode); } #if defined(SWIGPYTHON) Result isr(Edge mode, PyObject* pyfunc, PyObject* args) { return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, (void (*) (void*)) pyfunc, (void*) args); } #elif defined(SWIGJAVASCRIPT) static void v8isr(uv_work_t* req, int status) { mraa::Gpio* This = (mraa::Gpio*) req->data; int argc = 1; v8::Local<v8::Value> argv[] = { SWIGV8_INTEGER_NEW(-1) }; #if NODE_MODULE_VERSION >= 0x000D v8::Local<v8::Function> f = v8::Local<v8::Function>::New(v8::Isolate::GetCurrent(), This->m_v8isr); f->Call(SWIGV8_CURRENT_CONTEXT()->Global(), argc, argv); #else This->m_v8isr->Call(SWIGV8_CURRENT_CONTEXT()->Global(), argc, argv); #endif delete req; } static void nop(uv_work_t* req) { // Do nothing. } static void uvwork(void* ctx) { uv_work_t* req = new uv_work_t; req->data = ctx; uv_queue_work(uv_default_loop(), req, nop, v8isr); } Result isr(Edge mode, v8::Handle<v8::Function> func) { #if NODE_MODULE_VERSION >= 0x000D m_v8isr.Reset(v8::Isolate::GetCurrent(), func); #else m_v8isr = v8::Persistent<v8::Function>::New(func); #endif return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, &uvwork, this); } #elif defined(SWIGJAVA) || defined(JAVACALLBACK) Result isr(Edge mode, jobject runnable) { return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, mraa_java_isr_callback, runnable); } #endif /** * Sets a callback to be called when pin value changes * * @param mode The edge mode to set * @param fptr Function pointer to function to be called when interupt is * triggered * @param args Arguments passed to the interrupt handler (fptr) * @return Result of operation */ Result isr(Edge mode, void (*fptr)(void*), void* args) { return (Result) mraa_gpio_isr(m_gpio, (mraa_gpio_edge_t) mode, fptr, args); } /** * Exits callback - this call will not kill the isr thread immediatly * but only when it is out of it's critical section * * @return Result of operation */ Result isrExit() { #if defined(SWIGJAVASCRIPT) #if NODE_MODULE_VERSION >= 0x000D m_v8isr.Reset(); #else m_v8isr.Dispose(); m_v8isr.Clear(); #endif #endif return (Result) mraa_gpio_isr_exit(m_gpio); } /** * Change Gpio mode * * @param mode The mode to change the gpio into * @return Result of operation */ Result mode(Mode mode) { return (Result )mraa_gpio_mode(m_gpio, (mraa_gpio_mode_t) mode); } /** * Change Gpio direction * * @param dir The direction to change the gpio into * @return Result of operation */ Result dir(Dir dir) { return (Result )mraa_gpio_dir(m_gpio, (mraa_gpio_dir_t) dir); } /** * Read Gpio direction * * @throw std::runtime_error in case of failure * @return Result of operation */ Dir readDir() { mraa_gpio_dir_t dir; if (mraa_gpio_read_dir(m_gpio, &dir) != MRAA_SUCCESS) { throw std::runtime_error("Failed to read direction"); } return (Dir) dir; } /** * Read value from Gpio * * @return Gpio value */ int read() { return mraa_gpio_read(m_gpio); } /** * Write value to Gpio * * @param value Value to write to Gpio * @return Result of operation */ Result write(int value) { return (Result) mraa_gpio_write(m_gpio, value); } /** * Enable use of mmap i/o if available. * * @param enable true to use mmap * @return Result of operation */ Result useMmap(bool enable) { return (Result) mraa_gpio_use_mmaped(m_gpio, (mraa_boolean_t) enable); } /** * Get pin number of Gpio. If raw param is True will return the * number as used within sysfs. Invalid will return -1. * * @param raw (optional) get the raw gpio number. * @return Pin number */ int getPin(bool raw = false) { if (raw) { return mraa_gpio_get_pin_raw(m_gpio); } return mraa_gpio_get_pin(m_gpio); } private: mraa_gpio_context m_gpio; #if defined(SWIGJAVASCRIPT) v8::Persistent<v8::Function> m_v8isr; #endif }; } <|endoftext|>
<commit_before>#include <ciri/wnd/Window.hpp> #include <ciri/gfx/GraphicsDeviceFactory.hpp> #include <ciri/gfx/IShader.hpp> #include <ciri/gfx/IVertexBuffer.hpp> #include <ciri/gfx/IIndexBuffer.hpp> #include <ciri/gfx/IConstantBuffer.hpp> #include <ciri/gfx/Camera.hpp> #include <cc/Vec3.hpp> #include <cc/Mat4.hpp> #include <cc/MatrixFunc.hpp> #if defined(_DEBUG) #include <crtdbg.h> #endif struct SimpleVertex { cc::Vec3f position; cc::Vec3f color; SimpleVertex() { } SimpleVertex( const cc::Vec3f& pos, const cc::Vec3f& col ) : position(pos), color(col) { } }; __declspec(align(16)) struct ShaderData { //cc::Mat4f xform; float xform[16]; }; void createCube( float size, SimpleVertex* vb, int* ib ) { vb[0] = SimpleVertex(cc::Vec3f(-1.0f, -1.0f, 1.0f), cc::Vec3f(1.0f, 0.0f, 0.0f)); vb[1] = SimpleVertex(cc::Vec3f( 1.0f, -1.0f, 1.0f), cc::Vec3f(0.0f, 1.0f, 0.0f)); vb[2] = SimpleVertex(cc::Vec3f( 1.0, 1.0, 1.0), cc::Vec3f(0.0f, 0.0f, 1.0f)); vb[3] = SimpleVertex(cc::Vec3f(-1.0, 1.0, 1.0), cc::Vec3f(1.0f, 1.0f, 1.0f)); vb[4] = SimpleVertex(cc::Vec3f(-1.0, -1.0, -1.0), cc::Vec3f(1.0f, 0.0f, 0.0f)); vb[5] = SimpleVertex(cc::Vec3f( 1.0, -1.0, -1.0), cc::Vec3f(0.0f, 1.0f, 0.0f)); vb[6] = SimpleVertex(cc::Vec3f( 1.0, 1.0, -1.0), cc::Vec3f(0.0f, 0.0f, 1.0f)); vb[7] = SimpleVertex(cc::Vec3f(-1.0, 1.0, -1.0), cc::Vec3f(1.0f, 1.0f, 1.0f)); ib[0]=0; ib[1]=1; ib[2]=2; ib[3]=2; ib[4]=3; ib[5]=0; ib[6]=3; ib[7]=2; ib[8]=6; ib[9]=6; ib[10]=7; ib[11]=3; ib[12]=7; ib[13]=6; ib[14]=5; ib[15]=5; ib[16]=4; ib[17]=7; ib[18]=4; ib[19]=5; ib[20]=1; ib[21]=1; ib[22]=0; ib[23]=4; ib[24]=4; ib[25]=0; ib[26]=3; ib[27]=3; ib[28]=7; ib[29]=4; ib[30]=1; ib[31]=5; ib[32]=6; ib[33]=6; ib[34]=2; ib[35]=1; } int main() { #if defined(_DEBUG) int debugFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); debugFlag|= _CRTDBG_LEAK_CHECK_DF; debugFlag |= _CRTDBG_CHECK_ALWAYS_DF; _CrtSetDbgFlag(debugFlag); #endif ciri::Camera camera; camera.setAspect(1280.0f / 720.0f); camera.setPosition(cc::Vec3f(0.0f, 2.0f, 0.0f)); camera.setTarget(cc::Vec3f(0.0f, 0.0f, -4.0f)); ciri::Window window; window.create(1280, 720); ciri::IGraphicsDevice* device = ciri::GraphicsDeviceFactory::create(ciri::GraphicsDeviceFactory::OpenGL); if( !device->create(&window) ) { printf("Failed to initialize graphics device.\n"); return -1; } else { printf("Graphics device initialized.\n"); } ciri::IShader* shader = device->createShader(); shader->addVertexShader("data/simple_vs.glsl"); shader->addPixelShader("data/simple_ps.glsl"); shader->addInputElement(ciri::VertexElement(ciri::VertexFormat::Float3, ciri::VertexUsage::Position, 0)); shader->addInputElement(ciri::VertexElement(ciri::VertexFormat::Float3, ciri::VertexUsage::Color, 0)); if( ciri::err::failed(shader->build()) ) { printf("Failed to build shader: %s.\n", shader->getLastError()); } else { printf("Shader built.\n"); } SimpleVertex vertices[8]; int indices[36]; createCube(1.0f, vertices, indices); ciri::IVertexBuffer* vertexBuffer = device->createVertexBuffer(); if( !vertexBuffer->set(vertices, sizeof(SimpleVertex), 8, false) ) { printf("Failed to create vertex buffer.\n"); } else { printf("Created vertex buffer.\n"); } ciri::IIndexBuffer* indexBuffer = device->createIndexBuffer(); if( !indexBuffer->set(indices, 36, false) ) { printf("Failed to create index buffer.\n"); } else { printf("Created index buffer.\n"); } ShaderData shaderData; cc::Mat4f viewProj = (camera.getProj() * camera.getView()); cc::Mat4f world = cc::math::translate(cc::Vec3f(0.0f, 0.0f, -4.0f)); cc::Mat4f xform = viewProj * world; memcpy(shaderData.xform, &xform[0][0], sizeof(float) * 16); ciri::IConstantBuffer* constantBuffer = device->createConstantBuffer(); if( ciri::err::failed(constantBuffer->setData(sizeof(shaderData), &shaderData)) ) { printf("Failed to create constant buffer.\n"); } else { printf("Created constant buffer.\n"); } if( ciri::err::failed(shader->addConstants(constantBuffer, "TestConstants", ciri::ShaderType::Vertex)) ) { printf("Failed to assign constant buffer to shader.\n"); } else { printf("Assigned constant buffer to shader.\n"); } while( window.isOpen() ) { ciri::WindowEvent evt; while( window.pollEvent(evt) ) { if( evt.type == ciri::WindowEvent::Closed ) { window.destroy(); } } static float time = 0.0f; time += 0.0001f; static float angle = 0.0f; angle += 0.1f; if( angle > 360.0f ) { angle = (360.0f - angle); } viewProj = (camera.getProj() * camera.getView()); world = cc::math::translate(cc::Vec3f(0.0f, 0.0f, -4.0f)) * cc::math::rotate(angle, cc::Vec3f(0.0f, 1.0f, 0.0f)); cc::Mat4f xform = viewProj * world; memcpy(shaderData.xform, &xform[0][0], sizeof(float) * 16); if( ciri::err::failed(constantBuffer->setData(sizeof(shaderData), &shaderData)) ) { printf("Failed to update constant buffer.\n"); } device->clear(); device->applyShader(shader); device->setVertexBuffer(vertexBuffer); device->setIndexBuffer(indexBuffer); device->drawIndexed(ciri::PrimitiveTopology::TriangleList, indexBuffer->getIndexCount()); device->present(); } device->destroy(); delete device; device = nullptr; return 0; }<commit_msg>Changed hardcoded array and memcpy in test constants to an actual matrix.<commit_after>#include <ciri/wnd/Window.hpp> #include <ciri/gfx/GraphicsDeviceFactory.hpp> #include <ciri/gfx/IShader.hpp> #include <ciri/gfx/IVertexBuffer.hpp> #include <ciri/gfx/IIndexBuffer.hpp> #include <ciri/gfx/IConstantBuffer.hpp> #include <ciri/gfx/Camera.hpp> #include <cc/Vec3.hpp> #include <cc/Mat4.hpp> #include <cc/MatrixFunc.hpp> #if defined(_DEBUG) #include <crtdbg.h> #endif struct SimpleVertex { cc::Vec3f position; cc::Vec3f color; SimpleVertex() { } SimpleVertex( const cc::Vec3f& pos, const cc::Vec3f& col ) : position(pos), color(col) { } }; __declspec(align(16)) struct ShaderData { cc::Mat4f xform; }; void createCube( float size, SimpleVertex* vb, int* ib ) { vb[0] = SimpleVertex(cc::Vec3f(-1.0f, -1.0f, 1.0f), cc::Vec3f(1.0f, 0.0f, 0.0f)); vb[1] = SimpleVertex(cc::Vec3f( 1.0f, -1.0f, 1.0f), cc::Vec3f(0.0f, 1.0f, 0.0f)); vb[2] = SimpleVertex(cc::Vec3f( 1.0, 1.0, 1.0), cc::Vec3f(0.0f, 0.0f, 1.0f)); vb[3] = SimpleVertex(cc::Vec3f(-1.0, 1.0, 1.0), cc::Vec3f(1.0f, 1.0f, 1.0f)); vb[4] = SimpleVertex(cc::Vec3f(-1.0, -1.0, -1.0), cc::Vec3f(1.0f, 0.0f, 0.0f)); vb[5] = SimpleVertex(cc::Vec3f( 1.0, -1.0, -1.0), cc::Vec3f(0.0f, 1.0f, 0.0f)); vb[6] = SimpleVertex(cc::Vec3f( 1.0, 1.0, -1.0), cc::Vec3f(0.0f, 0.0f, 1.0f)); vb[7] = SimpleVertex(cc::Vec3f(-1.0, 1.0, -1.0), cc::Vec3f(1.0f, 1.0f, 1.0f)); ib[0]=0; ib[1]=1; ib[2]=2; ib[3]=2; ib[4]=3; ib[5]=0; ib[6]=3; ib[7]=2; ib[8]=6; ib[9]=6; ib[10]=7; ib[11]=3; ib[12]=7; ib[13]=6; ib[14]=5; ib[15]=5; ib[16]=4; ib[17]=7; ib[18]=4; ib[19]=5; ib[20]=1; ib[21]=1; ib[22]=0; ib[23]=4; ib[24]=4; ib[25]=0; ib[26]=3; ib[27]=3; ib[28]=7; ib[29]=4; ib[30]=1; ib[31]=5; ib[32]=6; ib[33]=6; ib[34]=2; ib[35]=1; } int main() { #if defined(_DEBUG) int debugFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); debugFlag|= _CRTDBG_LEAK_CHECK_DF; debugFlag |= _CRTDBG_CHECK_ALWAYS_DF; _CrtSetDbgFlag(debugFlag); #endif ciri::Camera camera; camera.setAspect(1280.0f / 720.0f); camera.setPosition(cc::Vec3f(0.0f, 2.0f, 0.0f)); camera.setTarget(cc::Vec3f(0.0f, 0.0f, -4.0f)); ciri::Window window; window.create(1280, 720); ciri::IGraphicsDevice* device = ciri::GraphicsDeviceFactory::create(ciri::GraphicsDeviceFactory::OpenGL); if( !device->create(&window) ) { printf("Failed to initialize graphics device.\n"); return -1; } else { printf("Graphics device initialized.\n"); } ciri::IShader* shader = device->createShader(); shader->addVertexShader("data/simple_vs.glsl"); shader->addPixelShader("data/simple_ps.glsl"); shader->addInputElement(ciri::VertexElement(ciri::VertexFormat::Float3, ciri::VertexUsage::Position, 0)); shader->addInputElement(ciri::VertexElement(ciri::VertexFormat::Float3, ciri::VertexUsage::Color, 0)); if( ciri::err::failed(shader->build()) ) { printf("Failed to build shader: %s.\n", shader->getLastError()); } else { printf("Shader built.\n"); } SimpleVertex vertices[8]; int indices[36]; createCube(1.0f, vertices, indices); ciri::IVertexBuffer* vertexBuffer = device->createVertexBuffer(); if( !vertexBuffer->set(vertices, sizeof(SimpleVertex), 8, false) ) { printf("Failed to create vertex buffer.\n"); } else { printf("Created vertex buffer.\n"); } ciri::IIndexBuffer* indexBuffer = device->createIndexBuffer(); if( !indexBuffer->set(indices, 36, false) ) { printf("Failed to create index buffer.\n"); } else { printf("Created index buffer.\n"); } ShaderData shaderData; cc::Mat4f viewProj = (camera.getProj() * camera.getView()); cc::Mat4f world = cc::math::translate(cc::Vec3f(0.0f, 0.0f, -4.0f)); cc::Mat4f xform = viewProj * world; shaderData.xform = xform; ciri::IConstantBuffer* constantBuffer = device->createConstantBuffer(); if( ciri::err::failed(constantBuffer->setData(sizeof(shaderData), &shaderData)) ) { printf("Failed to create constant buffer.\n"); } else { printf("Created constant buffer.\n"); } if( ciri::err::failed(shader->addConstants(constantBuffer, "TestConstants", ciri::ShaderType::Vertex)) ) { printf("Failed to assign constant buffer to shader.\n"); } else { printf("Assigned constant buffer to shader.\n"); } while( window.isOpen() ) { ciri::WindowEvent evt; while( window.pollEvent(evt) ) { if( evt.type == ciri::WindowEvent::Closed ) { window.destroy(); } } static float time = 0.0f; time += 0.0001f; static float angle = 0.0f; angle += 0.1f; if( angle > 360.0f ) { angle = (360.0f - angle); } viewProj = (camera.getProj() * camera.getView()); world = cc::math::translate(cc::Vec3f(0.0f, 0.0f, -4.0f)) * cc::math::rotate(angle, cc::Vec3f(0.0f, 1.0f, 0.0f)); cc::Mat4f xform = viewProj * world; shaderData.xform = xform; if( ciri::err::failed(constantBuffer->setData(sizeof(shaderData), &shaderData)) ) { printf("Failed to update constant buffer.\n"); } device->clear(); device->applyShader(shader); device->setVertexBuffer(vertexBuffer); device->setIndexBuffer(indexBuffer); device->drawIndexed(ciri::PrimitiveTopology::TriangleList, indexBuffer->getIndexCount()); device->present(); } device->destroy(); delete device; device = nullptr; return 0; }<|endoftext|>
<commit_before>#include <Python.h> #include "ptex_util.hpp" static PyObject* Py_merge_ptex(PyObject *, PyObject* args){ PyObject *input_list = 0, *seq, *item, *result = 0; const char **input_files = 0; const char *output = 0; int *offsets; Ptex::String err_msg; if(!PyArg_ParseTuple(args, "Os:merge_ptex", &input_list, &output)) return 0; if (!PySequence_Check(input_list)) { PyErr_SetString(PyExc_ValueError, "first argument should be sequence of filepaths"); return 0; } seq = PySequence_Fast(input_list, "first argument should be sequence of filepaths"); if (seq == 0) return 0; Py_ssize_t input_len = PySequence_Length(seq); if (input_len < 2) { PyErr_SetString(PyExc_ValueError, "at least 2 input files required"); Py_DECREF(seq); return 0; } input_files = (const char**) malloc(sizeof(char*)*input_len); offsets = (int*) malloc(sizeof(int)*input_len); for (int i = 0; i < input_len; ++i){ //borrowing, do not decref item = PySequence_Fast_GET_ITEM(seq, i); if(!PyString_Check(item)){ PyErr_Format(PyExc_ValueError, "Input list element %i is not a string", i); goto exit; } //internal ptr input_files[i] = PyString_AsString(item); } if (ptex_merge((int) input_len, input_files, output, offsets, err_msg)){ PyErr_SetString(PyExc_RuntimeError, err_msg.c_str()); goto exit; } //now build result; result = PyList_New(input_len); for (int i = 0; i < input_len; ++i){ item = PySequence_Fast_GET_ITEM(seq, i); item = Py_BuildValue("Oi", item, offsets[i]); //increfs item PyList_SetItem(result, i, item); //steals item } exit: free(input_files); free(offsets); Py_DECREF(seq); return result; } static PyMethodDef ptexutils_methods [] = { { "merge_ptex", Py_merge_ptex, METH_VARARGS, "merge ptex files"}, { NULL, NULL, 0, NULL } }; extern "C" { PyMODINIT_FUNC initcptexutils(void){ PyObject *m; m = Py_InitModule3("cptexutils", ptexutils_methods, ""); if (m == NULL) return; } } <commit_msg>add ptex_reverse to python module<commit_after>#include <Python.h> #include "ptex_util.hpp" static PyObject* Py_merge_ptex(PyObject *, PyObject* args){ PyObject *input_list = 0, *seq, *item, *result = 0; const char **input_files = 0; const char *output = 0; int *offsets; Ptex::String err_msg; if(!PyArg_ParseTuple(args, "Os:merge_ptex", &input_list, &output)) return 0; if (!PySequence_Check(input_list)) { PyErr_SetString(PyExc_ValueError, "first argument should be sequence of filepaths"); return 0; } seq = PySequence_Fast(input_list, "first argument should be sequence of filepaths"); if (seq == 0) return 0; Py_ssize_t input_len = PySequence_Length(seq); if (input_len < 2) { PyErr_SetString(PyExc_ValueError, "at least 2 input files required"); Py_DECREF(seq); return 0; } input_files = (const char**) malloc(sizeof(char*)*input_len); offsets = (int*) malloc(sizeof(int)*input_len); for (int i = 0; i < input_len; ++i){ //borrowing, do not decref item = PySequence_Fast_GET_ITEM(seq, i); if(!PyString_Check(item)){ PyErr_Format(PyExc_ValueError, "Input list element %i is not a string", i); goto exit; } //internal ptr input_files[i] = PyString_AsString(item); } if (ptex_merge((int) input_len, input_files, output, offsets, err_msg)){ PyErr_SetString(PyExc_RuntimeError, err_msg.c_str()); goto exit; } //now build result; result = PyList_New(input_len); for (int i = 0; i < input_len; ++i){ item = PySequence_Fast_GET_ITEM(seq, i); item = Py_BuildValue("Oi", item, offsets[i]); //increfs item PyList_SetItem(result, i, item); //steals item } exit: free(input_files); free(offsets); Py_DECREF(seq); return result; } static PyObject* Py_reverse_ptex(PyObject *, PyObject* args){ const char *input = 0; const char *output = 0; Ptex::String err_msg; if(!PyArg_ParseTuple(args, "ss:reverse_ptex", &input, &output)) return 0; if (ptex_reverse(input, output, err_msg)){ PyErr_SetString(PyExc_RuntimeError, err_msg.c_str()); return 0; } Py_RETURN_NONE; } static PyMethodDef ptexutils_methods [] = { { "merge_ptex", Py_merge_ptex, METH_VARARGS, "merge ptex files"}, { "reverse_ptex", Py_reverse_ptex, METH_VARARGS, "reverse faces in ptex file"}, { NULL, NULL, 0, NULL } }; extern "C" { PyMODINIT_FUNC initcptexutils(void){ PyObject *m; m = Py_InitModule3("cptexutils", ptexutils_methods, ""); if (m == NULL) return; } } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2003 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _WIN32 #pragma warning(4:4786) #endif #include <iostream> #include <config.h> #include "ActionBinding.h" #include "CommandManager.h" #include "KeyManager.h" ActionBinding::ActionBinding() { wayToBindActions.insert(std::make_pair(std::string("quit"), press)); wayToBindActions.insert(std::make_pair(std::string("fire"), both)); wayToBindActions.insert(std::make_pair(std::string("drop"), press)); wayToBindActions.insert(std::make_pair(std::string("identify"), press)); wayToBindActions.insert(std::make_pair(std::string("jump"), press)); wayToBindActions.insert(std::make_pair(std::string("send all"), press)); wayToBindActions.insert(std::make_pair(std::string("send team"), press)); wayToBindActions.insert(std::make_pair(std::string("send nemesis"), press)); wayToBindActions.insert(std::make_pair(std::string("send recipient"), press)); wayToBindActions.insert(std::make_pair(std::string("toggle displayScore"), press)); wayToBindActions.insert(std::make_pair(std::string("toggle displayBinoculars"), press)); wayToBindActions.insert(std::make_pair(std::string("pause"), press)); #ifdef SNAPPING wayToBindActions.insert(std::make_pair(std::string("screenshot"), press)); #endif wayToBindActions.insert(std::make_pair(std::string("time backward"), press)); wayToBindActions.insert(std::make_pair(std::string("time forward"), press)); wayToBindActions.insert(std::make_pair(std::string("toggle displayRadarFlags"), press)); wayToBindActions.insert(std::make_pair(std::string("toggle displayMainFlags"), press)); wayToBindActions.insert(std::make_pair(std::string("silence"), press)); wayToBindActions.insert(std::make_pair(std::string("toggle displayLabels"), press)); wayToBindActions.insert(std::make_pair(std::string("destruct"), press)); wayToBindActions.insert(std::make_pair(std::string("roam rotate stop"), release)); wayToBindActions.insert(std::make_pair(std::string("roam rotate left"), both)); wayToBindActions.insert(std::make_pair(std::string("roam rotate right"), both)); wayToBindActions.insert(std::make_pair(std::string("roam rotate up"), both)); wayToBindActions.insert(std::make_pair(std::string("roam rotate down"), both)); wayToBindActions.insert(std::make_pair(std::string("roam translate left"), both)); wayToBindActions.insert(std::make_pair(std::string("roam translate right"), both)); wayToBindActions.insert(std::make_pair(std::string("roam translate forward"), both)); wayToBindActions.insert(std::make_pair(std::string("roam translate backward"), both)); wayToBindActions.insert(std::make_pair(std::string("roam translate up"), both)); wayToBindActions.insert(std::make_pair(std::string("roam translate down"), both)); wayToBindActions.insert(std::make_pair(std::string("roam cycle subject backward"), press)); wayToBindActions.insert(std::make_pair(std::string("roam cycle subject forward"), press)); wayToBindActions.insert(std::make_pair(std::string("roam cycle type forward"), press)); wayToBindActions.insert(std::make_pair(std::string("roam zoom in"), both)); wayToBindActions.insert(std::make_pair(std::string("roam zoom out"), both)); wayToBindActions.insert(std::make_pair(std::string("roam zoom normal"), both)); wayToBindActions.insert(std::make_pair(std::string("servercommand"), press)); wayToBindActions.insert(std::make_pair(std::string("toggle displayFlagHelp"), press)); wayToBindActions.insert(std::make_pair(std::string("scrollpanel up"), press)); wayToBindActions.insert(std::make_pair(std::string("scrollpanel down"), press)); wayToBindActions.insert(std::make_pair(std::string("set displayRadarRange 0.25"), press)); wayToBindActions.insert(std::make_pair(std::string("set displayRadarRange 0.5"), press)); wayToBindActions.insert(std::make_pair(std::string("set displayRadarRange 1.0"), press)); wayToBindActions.insert(std::make_pair(std::string("toggle slowKeyboard"), press)); wayToBindActions.insert(std::make_pair(std::string("hunt"), press)); wayToBindActions.insert(std::make_pair(std::string("restart"), release)); wayToBindActions.insert(std::make_pair(std::string("autopilot"), press)); defaultBinding.insert(std::make_pair(std::string("F12"), std::string("quit"))); defaultBinding.insert(std::make_pair(std::string("Left Mouse"), std::string("fire"))); defaultBinding.insert(std::make_pair(std::string("Enter"), std::string("fire"))); defaultBinding.insert(std::make_pair(std::string("Middle Mouse"), std::string("drop"))); defaultBinding.insert(std::make_pair(std::string("Space"), std::string("drop"))); defaultBinding.insert(std::make_pair(std::string("Right Mouse"), std::string("identify"))); defaultBinding.insert(std::make_pair(std::string("I"), std::string("identify"))); defaultBinding.insert(std::make_pair(std::string("Tab"), std::string("jump"))); defaultBinding.insert(std::make_pair(std::string("N"), std::string("send all"))); defaultBinding.insert(std::make_pair(std::string("M"), std::string("send team"))); defaultBinding.insert(std::make_pair(std::string(","), std::string("send nemesis"))); defaultBinding.insert(std::make_pair(std::string("."), std::string("send recipient"))); defaultBinding.insert(std::make_pair(std::string("S"), std::string("toggle displayScore"))); defaultBinding.insert(std::make_pair(std::string("B"), std::string("toggle displayBinoculars"))); defaultBinding.insert(std::make_pair(std::string("Pause"), std::string("pause"))); defaultBinding.insert(std::make_pair(std::string("P"), std::string("pause"))); #ifdef SNAPPING defaultBinding.insert(std::make_pair(std::string("F5"), std::string("screenshot"))); #endif defaultBinding.insert(std::make_pair(std::string("-"), std::string("time backward"))); defaultBinding.insert(std::make_pair(std::string("="), std::string("time forward"))); defaultBinding.insert(std::make_pair(std::string("H"), std::string("toggle displayRadarFlags"))); defaultBinding.insert(std::make_pair(std::string("J"), std::string("toggle displayMainFlags"))); defaultBinding.insert(std::make_pair(std::string("K"), std::string("silence"))); defaultBinding.insert(std::make_pair(std::string("L"), std::string("toggle displayLabels"))); defaultBinding.insert(std::make_pair(std::string("Delete"), std::string("destruct"))); defaultBinding.insert(std::make_pair(std::string("Left Arrow"), std::string("roam rotate stop"))); defaultBinding.insert(std::make_pair(std::string("Right Arrow"), std::string("roam rotate stop"))); defaultBinding.insert(std::make_pair(std::string("Up Arrow"), std::string("roam rotate stop"))); defaultBinding.insert(std::make_pair(std::string("Down Arrow"), std::string("roam rotate stop"))); defaultBinding.insert(std::make_pair(std::string("Ctrl+Left Arrow"), std::string("roam rotate left"))); defaultBinding.insert(std::make_pair(std::string("Ctrl+Right Arrow"), std::string("roam rotate right"))); defaultBinding.insert(std::make_pair(std::string("Ctrl+Up Arrow"), std::string("roam rotate up"))); defaultBinding.insert(std::make_pair(std::string("Ctrl+Down Arrow"), std::string("roam rotate down"))); defaultBinding.insert(std::make_pair(std::string("Shift+Left Arrow"), std::string("roam translate left"))); defaultBinding.insert(std::make_pair(std::string("Shift+Right Arrow"), std::string("roam translate right"))); defaultBinding.insert(std::make_pair(std::string("Shift+Up Arrow"), std::string("roam translate forward"))); defaultBinding.insert(std::make_pair(std::string("Shift+Down Arrow"), std::string("roam translate backward"))); defaultBinding.insert(std::make_pair(std::string("Alt+Up Arrow"), std::string("roam translate up"))); defaultBinding.insert(std::make_pair(std::string("Alt+Down Arrow"), std::string("roam translate down"))); defaultBinding.insert(std::make_pair(std::string("F6"), std::string("roam cycle subject backward"))); defaultBinding.insert(std::make_pair(std::string("F7"), std::string("roam cycle subject forward"))); defaultBinding.insert(std::make_pair(std::string("F8"), std::string("roam cycle type forward"))); defaultBinding.insert(std::make_pair(std::string("F9"), std::string("roam zoom in"))); defaultBinding.insert(std::make_pair(std::string("F10"), std::string("roam zoom out"))); defaultBinding.insert(std::make_pair(std::string("F11"), std::string("roam zoom normal"))); defaultBinding.insert(std::make_pair(std::string("O"), std::string("servercommand"))); defaultBinding.insert(std::make_pair(std::string("F"), std::string("toggle displayFlagHelp"))); defaultBinding.insert(std::make_pair(std::string("Page Up"), std::string("scrollpanel up"))); defaultBinding.insert(std::make_pair(std::string("Page Down"), std::string("scrollpanel down"))); defaultBinding.insert(std::make_pair(std::string("1"), std::string("set displayRadarRange 0.25"))); defaultBinding.insert(std::make_pair(std::string("2"), std::string("set displayRadarRange 0.5"))); defaultBinding.insert(std::make_pair(std::string("3"), std::string("set displayRadarRange 1.0"))); defaultBinding.insert(std::make_pair(std::string("A"), std::string("toggle slowKeyboard"))); defaultBinding.insert(std::make_pair(std::string("U"), std::string("hunt"))); defaultBinding.insert(std::make_pair(std::string("Right Mouse"), std::string("restart"))); defaultBinding.insert(std::make_pair(std::string("I"), std::string("restart"))); defaultBinding.insert(std::make_pair(std::string("9"), std::string("autopilot"))); } void ActionBinding::resetBindings() { BindingTable::const_iterator index; for (index = bindingTable.begin(); index != bindingTable.end(); ++index) unbind(index->second, index->first); bindingTable = defaultBinding; for (index = bindingTable.begin(); index != bindingTable.end(); ++index) bind(index->second, index->first); } void ActionBinding::getFromBindings() { bindingTable.clear(); KEYMGR.iterate(&onScanCB, this); } void ActionBinding::onScanCB(const std::string& name, bool, const std::string& cmd, void*) { ActionBinding::instance().associate(name, cmd, false); } void ActionBinding::associate(std::string key, std::string action, bool keyBind) { BindingTable::iterator index; if (!wayToBindActions.count(action)) return; PressStatusBind newStatusBind = wayToBindActions[action]; for (index = bindingTable.lower_bound( key ); index != bindingTable.upper_bound( key ); ++index) { if (newStatusBind == both) { if (keyBind) unbind(index->second, key); bindingTable.erase(index); } else if (newStatusBind == press) { if (wayToBindActions[index->second] != release) { if (keyBind) unbind(index->second, key); bindingTable.erase(index); } } else { if (wayToBindActions[index->second] != press) { if (keyBind) unbind(index->second, key); bindingTable.erase(index); } } } bindingTable.insert(std::make_pair(key, action)); if (keyBind) bind(action, key); }; void ActionBinding::deassociate(std::string action) { BindingTable::iterator index; for (index = bindingTable.begin(); index != bindingTable.end(); index++) { if (index->second == action) { unbind(action, index->first); bindingTable.erase(index); } } }; void ActionBinding::bind(std::string action, std::string key) { PressStatusBind statusBind = wayToBindActions[action]; std::string command; if (statusBind == press || statusBind == both) { command = "bind \"" + key + "\" down \"" + action + "\""; CMDMGR.run(command); }; if (statusBind == release || statusBind == both) { command = "bind \"" + key + "\" up \"" + action + "\""; CMDMGR.run(command); }; } void ActionBinding::unbind(std::string action, std::string key) { PressStatusBind statusBind = wayToBindActions[action]; std::string command; if (statusBind == press || statusBind == both) { command = "unbind \"" + key + "\" down"; CMDMGR.run(command); }; if (statusBind == release || statusBind == both) { command = "unbind \"" + key + "\" up"; CMDMGR.run(command); }; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>be careful when deleting elements when using a forward iterator - boom<commit_after>/* bzflag * Copyright (c) 1993 - 2003 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #ifdef _WIN32 #pragma warning(4:4786) #endif #include <iostream> #include <config.h> #include "ActionBinding.h" #include "CommandManager.h" #include "KeyManager.h" ActionBinding::ActionBinding() { wayToBindActions.insert(std::make_pair(std::string("quit"), press)); wayToBindActions.insert(std::make_pair(std::string("fire"), both)); wayToBindActions.insert(std::make_pair(std::string("drop"), press)); wayToBindActions.insert(std::make_pair(std::string("identify"), press)); wayToBindActions.insert(std::make_pair(std::string("jump"), press)); wayToBindActions.insert(std::make_pair(std::string("send all"), press)); wayToBindActions.insert(std::make_pair(std::string("send team"), press)); wayToBindActions.insert(std::make_pair(std::string("send nemesis"), press)); wayToBindActions.insert(std::make_pair(std::string("send recipient"), press)); wayToBindActions.insert(std::make_pair(std::string("toggle displayScore"), press)); wayToBindActions.insert(std::make_pair(std::string("toggle displayBinoculars"), press)); wayToBindActions.insert(std::make_pair(std::string("pause"), press)); #ifdef SNAPPING wayToBindActions.insert(std::make_pair(std::string("screenshot"), press)); #endif wayToBindActions.insert(std::make_pair(std::string("time backward"), press)); wayToBindActions.insert(std::make_pair(std::string("time forward"), press)); wayToBindActions.insert(std::make_pair(std::string("toggle displayRadarFlags"), press)); wayToBindActions.insert(std::make_pair(std::string("toggle displayMainFlags"), press)); wayToBindActions.insert(std::make_pair(std::string("silence"), press)); wayToBindActions.insert(std::make_pair(std::string("toggle displayLabels"), press)); wayToBindActions.insert(std::make_pair(std::string("destruct"), press)); wayToBindActions.insert(std::make_pair(std::string("roam rotate stop"), release)); wayToBindActions.insert(std::make_pair(std::string("roam rotate left"), both)); wayToBindActions.insert(std::make_pair(std::string("roam rotate right"), both)); wayToBindActions.insert(std::make_pair(std::string("roam rotate up"), both)); wayToBindActions.insert(std::make_pair(std::string("roam rotate down"), both)); wayToBindActions.insert(std::make_pair(std::string("roam translate left"), both)); wayToBindActions.insert(std::make_pair(std::string("roam translate right"), both)); wayToBindActions.insert(std::make_pair(std::string("roam translate forward"), both)); wayToBindActions.insert(std::make_pair(std::string("roam translate backward"), both)); wayToBindActions.insert(std::make_pair(std::string("roam translate up"), both)); wayToBindActions.insert(std::make_pair(std::string("roam translate down"), both)); wayToBindActions.insert(std::make_pair(std::string("roam cycle subject backward"), press)); wayToBindActions.insert(std::make_pair(std::string("roam cycle subject forward"), press)); wayToBindActions.insert(std::make_pair(std::string("roam cycle type forward"), press)); wayToBindActions.insert(std::make_pair(std::string("roam zoom in"), both)); wayToBindActions.insert(std::make_pair(std::string("roam zoom out"), both)); wayToBindActions.insert(std::make_pair(std::string("roam zoom normal"), both)); wayToBindActions.insert(std::make_pair(std::string("servercommand"), press)); wayToBindActions.insert(std::make_pair(std::string("toggle displayFlagHelp"), press)); wayToBindActions.insert(std::make_pair(std::string("scrollpanel up"), press)); wayToBindActions.insert(std::make_pair(std::string("scrollpanel down"), press)); wayToBindActions.insert(std::make_pair(std::string("set displayRadarRange 0.25"), press)); wayToBindActions.insert(std::make_pair(std::string("set displayRadarRange 0.5"), press)); wayToBindActions.insert(std::make_pair(std::string("set displayRadarRange 1.0"), press)); wayToBindActions.insert(std::make_pair(std::string("toggle slowKeyboard"), press)); wayToBindActions.insert(std::make_pair(std::string("hunt"), press)); wayToBindActions.insert(std::make_pair(std::string("restart"), release)); wayToBindActions.insert(std::make_pair(std::string("autopilot"), press)); defaultBinding.insert(std::make_pair(std::string("F12"), std::string("quit"))); defaultBinding.insert(std::make_pair(std::string("Left Mouse"), std::string("fire"))); defaultBinding.insert(std::make_pair(std::string("Enter"), std::string("fire"))); defaultBinding.insert(std::make_pair(std::string("Middle Mouse"), std::string("drop"))); defaultBinding.insert(std::make_pair(std::string("Space"), std::string("drop"))); defaultBinding.insert(std::make_pair(std::string("Right Mouse"), std::string("identify"))); defaultBinding.insert(std::make_pair(std::string("I"), std::string("identify"))); defaultBinding.insert(std::make_pair(std::string("Tab"), std::string("jump"))); defaultBinding.insert(std::make_pair(std::string("N"), std::string("send all"))); defaultBinding.insert(std::make_pair(std::string("M"), std::string("send team"))); defaultBinding.insert(std::make_pair(std::string(","), std::string("send nemesis"))); defaultBinding.insert(std::make_pair(std::string("."), std::string("send recipient"))); defaultBinding.insert(std::make_pair(std::string("S"), std::string("toggle displayScore"))); defaultBinding.insert(std::make_pair(std::string("B"), std::string("toggle displayBinoculars"))); defaultBinding.insert(std::make_pair(std::string("Pause"), std::string("pause"))); defaultBinding.insert(std::make_pair(std::string("P"), std::string("pause"))); #ifdef SNAPPING defaultBinding.insert(std::make_pair(std::string("F5"), std::string("screenshot"))); #endif defaultBinding.insert(std::make_pair(std::string("-"), std::string("time backward"))); defaultBinding.insert(std::make_pair(std::string("="), std::string("time forward"))); defaultBinding.insert(std::make_pair(std::string("H"), std::string("toggle displayRadarFlags"))); defaultBinding.insert(std::make_pair(std::string("J"), std::string("toggle displayMainFlags"))); defaultBinding.insert(std::make_pair(std::string("K"), std::string("silence"))); defaultBinding.insert(std::make_pair(std::string("L"), std::string("toggle displayLabels"))); defaultBinding.insert(std::make_pair(std::string("Delete"), std::string("destruct"))); defaultBinding.insert(std::make_pair(std::string("Left Arrow"), std::string("roam rotate stop"))); defaultBinding.insert(std::make_pair(std::string("Right Arrow"), std::string("roam rotate stop"))); defaultBinding.insert(std::make_pair(std::string("Up Arrow"), std::string("roam rotate stop"))); defaultBinding.insert(std::make_pair(std::string("Down Arrow"), std::string("roam rotate stop"))); defaultBinding.insert(std::make_pair(std::string("Ctrl+Left Arrow"), std::string("roam rotate left"))); defaultBinding.insert(std::make_pair(std::string("Ctrl+Right Arrow"), std::string("roam rotate right"))); defaultBinding.insert(std::make_pair(std::string("Ctrl+Up Arrow"), std::string("roam rotate up"))); defaultBinding.insert(std::make_pair(std::string("Ctrl+Down Arrow"), std::string("roam rotate down"))); defaultBinding.insert(std::make_pair(std::string("Shift+Left Arrow"), std::string("roam translate left"))); defaultBinding.insert(std::make_pair(std::string("Shift+Right Arrow"), std::string("roam translate right"))); defaultBinding.insert(std::make_pair(std::string("Shift+Up Arrow"), std::string("roam translate forward"))); defaultBinding.insert(std::make_pair(std::string("Shift+Down Arrow"), std::string("roam translate backward"))); defaultBinding.insert(std::make_pair(std::string("Alt+Up Arrow"), std::string("roam translate up"))); defaultBinding.insert(std::make_pair(std::string("Alt+Down Arrow"), std::string("roam translate down"))); defaultBinding.insert(std::make_pair(std::string("F6"), std::string("roam cycle subject backward"))); defaultBinding.insert(std::make_pair(std::string("F7"), std::string("roam cycle subject forward"))); defaultBinding.insert(std::make_pair(std::string("F8"), std::string("roam cycle type forward"))); defaultBinding.insert(std::make_pair(std::string("F9"), std::string("roam zoom in"))); defaultBinding.insert(std::make_pair(std::string("F10"), std::string("roam zoom out"))); defaultBinding.insert(std::make_pair(std::string("F11"), std::string("roam zoom normal"))); defaultBinding.insert(std::make_pair(std::string("O"), std::string("servercommand"))); defaultBinding.insert(std::make_pair(std::string("F"), std::string("toggle displayFlagHelp"))); defaultBinding.insert(std::make_pair(std::string("Page Up"), std::string("scrollpanel up"))); defaultBinding.insert(std::make_pair(std::string("Page Down"), std::string("scrollpanel down"))); defaultBinding.insert(std::make_pair(std::string("1"), std::string("set displayRadarRange 0.25"))); defaultBinding.insert(std::make_pair(std::string("2"), std::string("set displayRadarRange 0.5"))); defaultBinding.insert(std::make_pair(std::string("3"), std::string("set displayRadarRange 1.0"))); defaultBinding.insert(std::make_pair(std::string("A"), std::string("toggle slowKeyboard"))); defaultBinding.insert(std::make_pair(std::string("U"), std::string("hunt"))); defaultBinding.insert(std::make_pair(std::string("Right Mouse"), std::string("restart"))); defaultBinding.insert(std::make_pair(std::string("I"), std::string("restart"))); defaultBinding.insert(std::make_pair(std::string("9"), std::string("autopilot"))); } void ActionBinding::resetBindings() { BindingTable::const_iterator index; for (index = bindingTable.begin(); index != bindingTable.end(); ++index) unbind(index->second, index->first); bindingTable = defaultBinding; for (index = bindingTable.begin(); index != bindingTable.end(); ++index) bind(index->second, index->first); } void ActionBinding::getFromBindings() { bindingTable.clear(); KEYMGR.iterate(&onScanCB, this); } void ActionBinding::onScanCB(const std::string& name, bool, const std::string& cmd, void*) { ActionBinding::instance().associate(name, cmd, false); } void ActionBinding::associate(std::string key, std::string action, bool keyBind) { BindingTable::iterator index, next; if (!wayToBindActions.count(action)) return; PressStatusBind newStatusBind = wayToBindActions[action]; for (index = bindingTable.lower_bound( key ); index != bindingTable.upper_bound( key ); index = next) { next = index; ++next; if (newStatusBind == both) { if (keyBind) unbind(index->second, key); bindingTable.erase(index); } else if (newStatusBind == press) { if (wayToBindActions[index->second] != release) { if (keyBind) unbind(index->second, key); bindingTable.erase(index); } } else { if (wayToBindActions[index->second] != press) { if (keyBind) unbind(index->second, key); bindingTable.erase(index); } } } bindingTable.insert(std::make_pair(key, action)); if (keyBind) bind(action, key); }; void ActionBinding::deassociate(std::string action) { BindingTable::iterator index; for (index = bindingTable.begin(); index != bindingTable.end(); index++) { if (index->second == action) { unbind(action, index->first); bindingTable.erase(index); } } }; void ActionBinding::bind(std::string action, std::string key) { PressStatusBind statusBind = wayToBindActions[action]; std::string command; if (statusBind == press || statusBind == both) { command = "bind \"" + key + "\" down \"" + action + "\""; CMDMGR.run(command); }; if (statusBind == release || statusBind == both) { command = "bind \"" + key + "\" up \"" + action + "\""; CMDMGR.run(command); }; } void ActionBinding::unbind(std::string action, std::string key) { PressStatusBind statusBind = wayToBindActions[action]; std::string command; if (statusBind == press || statusBind == both) { command = "unbind \"" + key + "\" down"; CMDMGR.run(command); }; if (statusBind == release || statusBind == both) { command = "unbind \"" + key + "\" up"; CMDMGR.run(command); }; } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // Copyright (c) 2014 Michael G. Brehm // // 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 "stdafx.h" #include "ElfArguments.h" #pragma warning(push, 4) // Explicit Instantiations // template ElfArguments::StackImage ElfArguments::GenerateStackImage<ElfClass::x86>(HANDLE); #ifdef _M_X64 template ElfArguments::StackImage ElfArguments::GenerateStackImage<ElfClass::x86_64>(HANDLE); #endif //----------------------------------------------------------------------------- // ::BufferWrite // // Helper function for ElfArguments::GenerateStackImage, writes a value of // a specific data type into a buffer and returns an updated pointer // // Arguments: // // dest - Destination buffer pointer // source - Source value template <typename _type> inline uint8_t* BufferWrite(uint8_t* dest, const _type& source) { *reinterpret_cast<_type*>(dest) = source; return dest + sizeof(_type); } //--------------------------------------------------------------------------- // ElfArguments Constructor // // Arguments: // // argc - Pointer to the initial set of command line arguments // envp - Pointer to the initial set of environment variables ElfArguments::ElfArguments(const uapi::char_t** argv, const uapi::char_t** envp) { // Iterate over any provided arguments/variables and append them while(argv) { if(*argv) AppendArgument(*argv); ++argv; } while(envp) { if(*envp) AppendEnvironmentVariable(*envp); ++envp; } } //--------------------------------------------------------------------------- // ElfArguments::AlignUp (private, static) // // Aligns an offset up to the specified alignment // // Arguments: // // offset - Offset to be aligned // alignment - Alignment inline size_t ElfArguments::AlignUp(size_t offset, size_t alignment) { if(alignment < 1) throw Exception(E_ARGUMENTOUTOFRANGE, _T("alignment")); if(offset == 0) return 0; else return offset + ((alignment - (offset % alignment)) % alignment); } //----------------------------------------------------------------------------- // ElfArguments::AppendArgument // // Appends an argument to the contained argument list // // Arguments: // // value - Command-line argument to be added void ElfArguments::AppendArgument(const uapi::char_t* value) { if(!value) throw Exception(E_ARGUMENTNULL, "value"); m_argv.push_back(AppendInfo(value, strlen(value) + 1)); } //----------------------------------------------------------------------------- // ElfArguments::AppendAuxiliaryVector // // Appends an auxiliary vector to the contained list // // Arguments: // // type - Auxiliary vector type code // value - Auxiliary vector value void ElfArguments::AppendAuxiliaryVector(int type, uintptr_t value) { if(type < 0) throw Exception(E_ARGUMENTOUTOFRANGE, "type"); m_auxv.push_back(auxvec_t(type, value)); } //----------------------------------------------------------------------------- // ElfArguments::AppendAuxiliaryVector // // Appends an auxiliary vector to the contained list // // Arguments: // // type - Auxiliary vector type code // value - Auxiliary vector value void ElfArguments::AppendAuxiliaryVector(int type, const uapi::char_t* value) { if(type < 0) throw Exception(E_ARGUMENTOUTOFRANGE, "type"); // If the value will be pushed into the info block, indicate that with a // negative type, this will be removed during generation if(value) m_auxv.push_back(auxvec_t(-type, AppendInfo(value, strlen(value) + 1))); else m_auxv.push_back(auxvec_t(type)); } //----------------------------------------------------------------------------- // ElfArguments::AppendAuxiliaryVector // // Appends an auxiliary vector to the contained list // // Arguments: // // type - Auxiliary vector type code // buffer - Buffer holding binary auxiliary vector data // length - Length of the input buffer void ElfArguments::AppendAuxiliaryVector(int type, const void* buffer, size_t length) { if(type < 0) throw Exception(E_ARGUMENTOUTOFRANGE, "type"); // If the value will be pushed into the info block, indicate that with a // negative type, this will be removed during generation if(buffer && length) m_auxv.push_back(auxvec_t(-type, AppendInfo(buffer, length))); else m_auxv.push_back(auxvec_t(type)); } //----------------------------------------------------------------------------- // ElfArguments::AppendEnvironmentVariable // // Appends a preformatted environment variable to the contained list // // Arguments: // // variable - Preformatted environment variable in KEY=VALUE format void ElfArguments::AppendEnvironmentVariable(const uapi::char_t* keyandvalue) { if(!keyandvalue) throw Exception(E_ARGUMENTNULL, "keyandvalue"); m_envp.push_back(AppendInfo(keyandvalue, strlen(keyandvalue) + 1)); } //----------------------------------------------------------------------------- // ElfArguments::AppendEnvironmentVariable // // Appends an environment variable to the contained list // // Arguments: // // key - Environment variable key // value - Environment variable value void ElfArguments::AppendEnvironmentVariable(const uapi::char_t* key, const uapi::char_t* value) { if(!key) throw Exception(E_ARGUMENTNULL, "key"); if(!value) value = "\0"; // Append the key, an equal sign and the value to the information block uint32_t offset = AppendInfo(key, strlen(key)); AppendInfo("=", 1); AppendInfo(value, strlen(value) + 1); m_envp.push_back(offset); } //----------------------------------------------------------------------------- // ElfArguments::AppendInfo (private) // // Appends data to the information block // // Arguments: // // buffer - Buffer with data to be appended or NULL to reserve // length - Length of the data to be appended uint32_t ElfArguments::AppendInfo(const void* buffer, size_t length) { // Offsets are cast into unsigned 32-bit integers, the max must be smaller static_assert(MAX_INFO_BUFFER < UINT32_MAX, "ElfArguments::MAX_INFO_BUFFER must not be >= UINT32_MAX"); size_t offset = m_info.size(); // Get current end as the offset // Use a const byte pointer and the range-insert method to copy const uint8_t* pointer = reinterpret_cast<const uint8_t*>(buffer); m_info.insert(m_info.end(), pointer, pointer + length); // There is a limit to how big this buffer can be if(m_info.size() > MAX_INFO_BUFFER) throw Exception(E_ELFARGUMENTSTOOBIG, static_cast<uint32_t>(m_info.size()), MAX_INFO_BUFFER); return static_cast<uint32_t>(offset); } //----------------------------------------------------------------------------- // ElfArguments::GenerateStackImage // // Generates the memory image for the collected ELF arguments // // Arguments: // // process - Handle to the target process template <ElfClass _elfclass> ElfArguments::StackImage ElfArguments::GenerateStackImage(HANDLE process) { using elf = elf_traits<_elfclass>; size_t imagelen; // Length of the entire image size_t stackoffset; // Offset to the stack image // Align the information block to 16 bytes; this becomes the start of the stack image imagelen = stackoffset = AlignUp(m_info.size(), 16); // Calculate the additional size required to hold the vectors imagelen += sizeof(typename elf::addr_t); // argc imagelen += sizeof(typename elf::addr_t) * (m_argv.size() + 1); // argv + NULL imagelen += sizeof(typename elf::addr_t) * (m_envp.size() + 1); // envp + NULL imagelen += sizeof(typename elf::auxv_t) * (m_auxv.size() + 1); // auxv + AT_NULL imagelen += sizeof(typename elf::addr_t); // NULL imagelen = AlignUp(imagelen, 16); // alignment // Allocate the memory to hold the arguments in the hosted process std::unique_ptr<MemoryRegion> allocation = MemoryRegion::Reserve(process, imagelen, MEM_COMMIT | MEM_TOP_DOWN); // If there is any data in the information block, write that into the hosted process try { if(m_info.data() && !WriteProcessMemory(process, allocation->Pointer, m_info.data(), m_info.size(), nullptr)) throw Win32Exception(); } catch(Exception& ex) { throw Exception(E_ELFWRITEARGUMENTS, ex); } // Use a local heap buffer to collect all of the stack image data locally before writing it HeapBuffer<uint8_t> stackimage(imagelen - stackoffset); memset(&stackimage, 0, stackimage.Size); // Cast the allocation pointer into an elf::addr_t for simpler arithmetic typename elf::addr_t allocptr = reinterpret_cast<typename elf::addr_t>(allocation->Pointer); // ARGC uint8_t* next = BufferWrite<typename elf::addr_t>(stackimage, static_cast<typename elf::addr_t>(m_argv.size())); // ARGV + NULL for_each(m_argv.begin(), m_argv.end(), [&](uint32_t& offset) { next = BufferWrite<typename elf::addr_t>(next, allocptr + offset); }); next = BufferWrite<typename elf::addr_t>(next, 0); // ENVP + NULL for_each(m_envp.begin(), m_envp.end(), [&](uint32_t& offset) { next = BufferWrite<typename elf::addr_t>(next, allocptr + offset); }); next = BufferWrite<typename elf::addr_t>(next, 0); // AUXV for_each(m_auxv.begin(), m_auxv.end(), [&](auxvec_t auxv) { // Cast the stored AT_ type code back into a non-negative addr_t typename elf::addr_t type = static_cast<typename elf::addr_t>(abs(auxv.a_type)); // If a_type is positive, this is a straight value, otherwise it's an offset into the information block if(auxv.a_type >= 0) next = BufferWrite<typename elf::auxv_t>(next, { type, static_cast<typename elf::addr_t>(auxv.a_val) }); else next = BufferWrite<typename elf::auxv_t>(next, { type, allocptr + static_cast<typename elf::addr_t>(auxv.a_val) }); }); // AT_NULL + TERMINATOR next = BufferWrite<typename elf::auxv_t>(next, { LINUX_AT_NULL, 0 }); next = BufferWrite<typename elf::addr_t>(next, 0); // Write the stack image portion of the arguments into the host process address space void* pv = reinterpret_cast<uint8_t*>(allocation->Pointer) + stackoffset; try { if(!WriteProcessMemory(process, pv, &stackimage, stackimage.Size, nullptr)) throw Win32Exception(); } catch(Exception& ex) { throw Exception(E_ELFWRITEARGUMENTS, ex); } // Detach the MemoryRegion allocation and return the metadata to the caller return StackImage { reinterpret_cast<uint8_t*>(allocation->Detach()) + stackoffset, stackimage.Size }; } //----------------------------------------------------------------------------- #pragma warning(pop) <commit_msg>ElfArguments bug<commit_after>//----------------------------------------------------------------------------- // Copyright (c) 2014 Michael G. Brehm // // 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 "stdafx.h" #include "ElfArguments.h" #pragma warning(push, 4) // Explicit Instantiations // template ElfArguments::StackImage ElfArguments::GenerateStackImage<ElfClass::x86>(HANDLE); #ifdef _M_X64 template ElfArguments::StackImage ElfArguments::GenerateStackImage<ElfClass::x86_64>(HANDLE); #endif //----------------------------------------------------------------------------- // ::BufferWrite // // Helper function for ElfArguments::GenerateStackImage, writes a value of // a specific data type into a buffer and returns an updated pointer // // Arguments: // // dest - Destination buffer pointer // source - Source value template <typename _type> inline uint8_t* BufferWrite(uint8_t* dest, const _type& source) { *reinterpret_cast<_type*>(dest) = source; return dest + sizeof(_type); } //--------------------------------------------------------------------------- // ElfArguments Constructor // // Arguments: // // argc - Pointer to the initial set of command line arguments // envp - Pointer to the initial set of environment variables ElfArguments::ElfArguments(const uapi::char_t** argv, const uapi::char_t** envp) { // Iterate over any provided arguments/variables and append them while(argv && *argv) { AppendArgument(*argv); ++argv; } while(envp && *envp) { AppendEnvironmentVariable(*envp); ++envp; } } //--------------------------------------------------------------------------- // ElfArguments::AlignUp (private, static) // // Aligns an offset up to the specified alignment // // Arguments: // // offset - Offset to be aligned // alignment - Alignment inline size_t ElfArguments::AlignUp(size_t offset, size_t alignment) { if(alignment < 1) throw Exception(E_ARGUMENTOUTOFRANGE, _T("alignment")); if(offset == 0) return 0; else return offset + ((alignment - (offset % alignment)) % alignment); } //----------------------------------------------------------------------------- // ElfArguments::AppendArgument // // Appends an argument to the contained argument list // // Arguments: // // value - Command-line argument to be added void ElfArguments::AppendArgument(const uapi::char_t* value) { if(!value) throw Exception(E_ARGUMENTNULL, "value"); m_argv.push_back(AppendInfo(value, strlen(value) + 1)); } //----------------------------------------------------------------------------- // ElfArguments::AppendAuxiliaryVector // // Appends an auxiliary vector to the contained list // // Arguments: // // type - Auxiliary vector type code // value - Auxiliary vector value void ElfArguments::AppendAuxiliaryVector(int type, uintptr_t value) { if(type < 0) throw Exception(E_ARGUMENTOUTOFRANGE, "type"); m_auxv.push_back(auxvec_t(type, value)); } //----------------------------------------------------------------------------- // ElfArguments::AppendAuxiliaryVector // // Appends an auxiliary vector to the contained list // // Arguments: // // type - Auxiliary vector type code // value - Auxiliary vector value void ElfArguments::AppendAuxiliaryVector(int type, const uapi::char_t* value) { if(type < 0) throw Exception(E_ARGUMENTOUTOFRANGE, "type"); // If the value will be pushed into the info block, indicate that with a // negative type, this will be removed during generation if(value) m_auxv.push_back(auxvec_t(-type, AppendInfo(value, strlen(value) + 1))); else m_auxv.push_back(auxvec_t(type)); } //----------------------------------------------------------------------------- // ElfArguments::AppendAuxiliaryVector // // Appends an auxiliary vector to the contained list // // Arguments: // // type - Auxiliary vector type code // buffer - Buffer holding binary auxiliary vector data // length - Length of the input buffer void ElfArguments::AppendAuxiliaryVector(int type, const void* buffer, size_t length) { if(type < 0) throw Exception(E_ARGUMENTOUTOFRANGE, "type"); // If the value will be pushed into the info block, indicate that with a // negative type, this will be removed during generation if(buffer && length) m_auxv.push_back(auxvec_t(-type, AppendInfo(buffer, length))); else m_auxv.push_back(auxvec_t(type)); } //----------------------------------------------------------------------------- // ElfArguments::AppendEnvironmentVariable // // Appends a preformatted environment variable to the contained list // // Arguments: // // variable - Preformatted environment variable in KEY=VALUE format void ElfArguments::AppendEnvironmentVariable(const uapi::char_t* keyandvalue) { if(!keyandvalue) throw Exception(E_ARGUMENTNULL, "keyandvalue"); m_envp.push_back(AppendInfo(keyandvalue, strlen(keyandvalue) + 1)); } //----------------------------------------------------------------------------- // ElfArguments::AppendEnvironmentVariable // // Appends an environment variable to the contained list // // Arguments: // // key - Environment variable key // value - Environment variable value void ElfArguments::AppendEnvironmentVariable(const uapi::char_t* key, const uapi::char_t* value) { if(!key) throw Exception(E_ARGUMENTNULL, "key"); if(!value) value = "\0"; // Append the key, an equal sign and the value to the information block uint32_t offset = AppendInfo(key, strlen(key)); AppendInfo("=", 1); AppendInfo(value, strlen(value) + 1); m_envp.push_back(offset); } //----------------------------------------------------------------------------- // ElfArguments::AppendInfo (private) // // Appends data to the information block // // Arguments: // // buffer - Buffer with data to be appended or NULL to reserve // length - Length of the data to be appended uint32_t ElfArguments::AppendInfo(const void* buffer, size_t length) { // Offsets are cast into unsigned 32-bit integers, the max must be smaller static_assert(MAX_INFO_BUFFER < UINT32_MAX, "ElfArguments::MAX_INFO_BUFFER must not be >= UINT32_MAX"); size_t offset = m_info.size(); // Get current end as the offset // Use a const byte pointer and the range-insert method to copy const uint8_t* pointer = reinterpret_cast<const uint8_t*>(buffer); m_info.insert(m_info.end(), pointer, pointer + length); // There is a limit to how big this buffer can be if(m_info.size() > MAX_INFO_BUFFER) throw Exception(E_ELFARGUMENTSTOOBIG, static_cast<uint32_t>(m_info.size()), MAX_INFO_BUFFER); return static_cast<uint32_t>(offset); } //----------------------------------------------------------------------------- // ElfArguments::GenerateStackImage // // Generates the memory image for the collected ELF arguments // // Arguments: // // process - Handle to the target process template <ElfClass _elfclass> ElfArguments::StackImage ElfArguments::GenerateStackImage(HANDLE process) { using elf = elf_traits<_elfclass>; size_t imagelen; // Length of the entire image size_t stackoffset; // Offset to the stack image // Align the information block to 16 bytes; this becomes the start of the stack image imagelen = stackoffset = AlignUp(m_info.size(), 16); // Calculate the additional size required to hold the vectors imagelen += sizeof(typename elf::addr_t); // argc imagelen += sizeof(typename elf::addr_t) * (m_argv.size() + 1); // argv + NULL imagelen += sizeof(typename elf::addr_t) * (m_envp.size() + 1); // envp + NULL imagelen += sizeof(typename elf::auxv_t) * (m_auxv.size() + 1); // auxv + AT_NULL imagelen += sizeof(typename elf::addr_t); // NULL imagelen = AlignUp(imagelen, 16); // alignment // Allocate the memory to hold the arguments in the hosted process std::unique_ptr<MemoryRegion> allocation = MemoryRegion::Reserve(process, imagelen, MEM_COMMIT | MEM_TOP_DOWN); // If there is any data in the information block, write that into the hosted process try { if(m_info.data() && !WriteProcessMemory(process, allocation->Pointer, m_info.data(), m_info.size(), nullptr)) throw Win32Exception(); } catch(Exception& ex) { throw Exception(E_ELFWRITEARGUMENTS, ex); } // Use a local heap buffer to collect all of the stack image data locally before writing it HeapBuffer<uint8_t> stackimage(imagelen - stackoffset); memset(&stackimage, 0, stackimage.Size); // Cast the allocation pointer into an elf::addr_t for simpler arithmetic typename elf::addr_t allocptr = reinterpret_cast<typename elf::addr_t>(allocation->Pointer); // ARGC uint8_t* next = BufferWrite<typename elf::addr_t>(stackimage, static_cast<typename elf::addr_t>(m_argv.size())); // ARGV + NULL for_each(m_argv.begin(), m_argv.end(), [&](uint32_t& offset) { next = BufferWrite<typename elf::addr_t>(next, allocptr + offset); }); next = BufferWrite<typename elf::addr_t>(next, 0); // ENVP + NULL for_each(m_envp.begin(), m_envp.end(), [&](uint32_t& offset) { next = BufferWrite<typename elf::addr_t>(next, allocptr + offset); }); next = BufferWrite<typename elf::addr_t>(next, 0); // AUXV for_each(m_auxv.begin(), m_auxv.end(), [&](auxvec_t auxv) { // Cast the stored AT_ type code back into a non-negative addr_t typename elf::addr_t type = static_cast<typename elf::addr_t>(abs(auxv.a_type)); // If a_type is positive, this is a straight value, otherwise it's an offset into the information block if(auxv.a_type >= 0) next = BufferWrite<typename elf::auxv_t>(next, { type, static_cast<typename elf::addr_t>(auxv.a_val) }); else next = BufferWrite<typename elf::auxv_t>(next, { type, allocptr + static_cast<typename elf::addr_t>(auxv.a_val) }); }); // AT_NULL + TERMINATOR next = BufferWrite<typename elf::auxv_t>(next, { LINUX_AT_NULL, 0 }); next = BufferWrite<typename elf::addr_t>(next, 0); // Write the stack image portion of the arguments into the host process address space void* pv = reinterpret_cast<uint8_t*>(allocation->Pointer) + stackoffset; try { if(!WriteProcessMemory(process, pv, &stackimage, stackimage.Size, nullptr)) throw Win32Exception(); } catch(Exception& ex) { throw Exception(E_ELFWRITEARGUMENTS, ex); } // Detach the MemoryRegion allocation and return the metadata to the caller return StackImage { reinterpret_cast<uint8_t*>(allocation->Detach()) + stackoffset, stackimage.Size }; } //----------------------------------------------------------------------------- #pragma warning(pop) <|endoftext|>
<commit_before>// // This file is part of the Marble Project. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <tackat@kde.org> // Copyright 2007 Inge Wallin <ingwa@kde.org> // Copyright 2008 Simon Hausmann <hausmann@kde.org> // // Self #include "TinyWebBrowser.h" // Qt #include <QtCore/QFileInfo> #include <QtCore/QPointer> #include <QtCore/QRegExp> #include <QtGui/QAction> #include <QtGui/QDesktopServices> #include <QtGui/QPainter> #include <QtGui/QPrintDialog> #include <QtGui/QPrinter> #include <QtGui/QTextFrame> // Marble #include "MarbleGlobal.h" #include "MarbleDebug.h" #include "MarbleDirs.h" #include "MarbleLocale.h" namespace Marble { class TinyWebBrowserPrivate { }; static QString guessWikipediaDomain() { const QString code = MarbleLocale::languageCode(); return QString ( "http://%1.wikipedia.org/" ).arg ( code ); } TinyWebBrowser::TinyWebBrowser( QWidget* parent ) : QWebView( parent ), d( 0 ) { connect( this, SIGNAL( statusBarMessage( QString ) ), this, SIGNAL( statusMessage( QString ) ) ); page()->setLinkDelegationPolicy( QWebPage::DelegateAllLinks ); connect( this, SIGNAL( linkClicked( QUrl ) ), this, SLOT( openExternalLink( QUrl ) ) ); connect( this, SIGNAL( titleChanged( QString ) ), this, SLOT( setWindowTitle( QString ) ) ); pageAction( QWebPage::OpenLinkInNewWindow )->setEnabled( false ); pageAction( QWebPage::OpenLinkInNewWindow )->setVisible( false ); } TinyWebBrowser::~TinyWebBrowser() { // not yet needed //delete d; } void TinyWebBrowser::setWikipediaPath( const QString& relativeUrl ) { QUrl url = relativeUrl; if ( url.isRelative() ) url = QUrl( guessWikipediaDomain() ).resolved( url ); load( url ); } void TinyWebBrowser::print() { #ifndef QT_NO_PRINTER QPrinter printer; QPointer<QPrintDialog> dlg = new QPrintDialog( &printer, this ); if ( dlg->exec() ) QWebView::print( &printer ); delete dlg; #endif } QWebView *TinyWebBrowser::createWindow( QWebPage::WebWindowType type ) { TinyWebBrowser *view = new TinyWebBrowser( this ); if ( type == QWebPage::WebModalDialog ) { view->setWindowModality( Qt::WindowModal ); } return view; } void TinyWebBrowser::openExternalLink( QUrl url ) { QDesktopServices::openUrl( url ); } QByteArray TinyWebBrowser::userAgent(const QString &platform, const QString &component) { QString result( "Mozilla/5.0 (compatible; Marble/%1; %2; %3)" ); result = result.arg( MARBLE_VERSION_STRING, platform, component); return result.toAscii(); } } // namespace Marble #include "TinyWebBrowser.moc" <commit_msg>Use the mobile wikipedia version. It's a tiny browser after all.<commit_after>// // This file is part of the Marble Project. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2006-2007 Torsten Rahn <tackat@kde.org> // Copyright 2007 Inge Wallin <ingwa@kde.org> // Copyright 2008 Simon Hausmann <hausmann@kde.org> // // Self #include "TinyWebBrowser.h" // Qt #include <QtCore/QFileInfo> #include <QtCore/QPointer> #include <QtCore/QRegExp> #include <QtGui/QAction> #include <QtGui/QDesktopServices> #include <QtGui/QPainter> #include <QtGui/QPrintDialog> #include <QtGui/QPrinter> #include <QtGui/QTextFrame> // Marble #include "MarbleGlobal.h" #include "MarbleDebug.h" #include "MarbleDirs.h" #include "MarbleLocale.h" namespace Marble { class TinyWebBrowserPrivate { }; static QString guessWikipediaDomain() { const QString code = MarbleLocale::languageCode(); return QString ( "http://%1.m.wikipedia.org/" ).arg ( code ); } TinyWebBrowser::TinyWebBrowser( QWidget* parent ) : QWebView( parent ), d( 0 ) { connect( this, SIGNAL( statusBarMessage( QString ) ), this, SIGNAL( statusMessage( QString ) ) ); page()->setLinkDelegationPolicy( QWebPage::DelegateAllLinks ); connect( this, SIGNAL( linkClicked( QUrl ) ), this, SLOT( openExternalLink( QUrl ) ) ); connect( this, SIGNAL( titleChanged( QString ) ), this, SLOT( setWindowTitle( QString ) ) ); pageAction( QWebPage::OpenLinkInNewWindow )->setEnabled( false ); pageAction( QWebPage::OpenLinkInNewWindow )->setVisible( false ); } TinyWebBrowser::~TinyWebBrowser() { // not yet needed //delete d; } void TinyWebBrowser::setWikipediaPath( const QString& relativeUrl ) { QUrl url = relativeUrl; if ( url.isRelative() ) url = QUrl( guessWikipediaDomain() ).resolved( url ); load( url ); } void TinyWebBrowser::print() { #ifndef QT_NO_PRINTER QPrinter printer; QPointer<QPrintDialog> dlg = new QPrintDialog( &printer, this ); if ( dlg->exec() ) QWebView::print( &printer ); delete dlg; #endif } QWebView *TinyWebBrowser::createWindow( QWebPage::WebWindowType type ) { TinyWebBrowser *view = new TinyWebBrowser( this ); if ( type == QWebPage::WebModalDialog ) { view->setWindowModality( Qt::WindowModal ); } return view; } void TinyWebBrowser::openExternalLink( QUrl url ) { QDesktopServices::openUrl( url ); } QByteArray TinyWebBrowser::userAgent(const QString &platform, const QString &component) { QString result( "Mozilla/5.0 (compatible; Marble/%1; %2; %3)" ); result = result.arg( MARBLE_VERSION_STRING, platform, component); return result.toAscii(); } } // namespace Marble #include "TinyWebBrowser.moc" <|endoftext|>
<commit_before>#pragma once //=====================================================================// /*! @file @brief RX64M, RX65x, RX71M グループ・CMTW 定義 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2018 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/device.hpp" /// cmtw モジュールが無いデバイスでエラーとする #if defined(SIG_RX24T) || defined(SIG_RX66T) # error "cmtw.hpp: This module does not exist" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンペアマッチタイマ W クラス @param[in] base ベース・アドレス @param[in] per ペリフェラル @param[in] ivec 割り込みベクター */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t base, peripheral per, ICU::VECTOR ivec> struct cmtw_t { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマスタートレジスタ(CMWSTR) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct cmwstr_t : public rw16_t<base + 0x00> { typedef rw16_t<base + 0x00> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bit_rw_t <io_, bitpos::B0> STR; }; static cmwstr_t CMWSTR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマコントロールレジスタ(CMWCR) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct cmwcr_t : public rw16_t<base + 0x04> { typedef rw16_t<base + 0x04> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bits_rw_t<io_, bitpos::B0, 2> CKS; bit_rw_t <io_, bitpos::B3> CMWIE; bit_rw_t <io_, bitpos::B4> IC0IE; bit_rw_t <io_, bitpos::B5> IC1IE; bit_rw_t <io_, bitpos::B6> OC0IE; bit_rw_t <io_, bitpos::B7> OC1IE; bit_rw_t <io_, bitpos::B9> CMS; bits_rw_t<io_, bitpos::B13, 3> CCLR; }; static cmwcr_t CMWCR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマ I/O コントロールレジスタ(CMWIOR) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct cmwior_t : public rw16_t<base + 0x08> { typedef rw16_t<base + 0x08> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bits_rw_t<io_, bitpos::B0, 2> IC0; bits_rw_t<io_, bitpos::B2, 2> IC1; bit_rw_t <io_, bitpos::B4> IC0E; bit_rw_t <io_, bitpos::B5> IC1E; bits_rw_t<io_, bitpos::B8, 2> OC0; bits_rw_t<io_, bitpos::B10, 2> OC1; bit_rw_t <io_, bitpos::B12> OC0E; bit_rw_t <io_, bitpos::B13> OC1E; bit_rw_t <io_, bitpos::B15> CMWE; }; static cmwior_t CMWIOR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマカウンタ(CMWCNT) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x10> CMWCNT; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンペアマッチコンスタントレジスタ(CMWCOR) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x14> CMWCOR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief インプットキャプチャレジスタ 0(CMWICR0) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x18> CMWICR0; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief インプットキャプチャレジスタ 1(CMWICR1) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x1C> CMWICR1; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief アウトプットコンペアレジスタ 0(CMWOCR0) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x20> CMWOCR0; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief アウトプットコンペアレジスタ 1(CMWOCR1) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x24> CMWOCR1; //-----------------------------------------------------------------// /*! @brief ペリフェラル型を返す @return ペリフェラル型 */ //-----------------------------------------------------------------// static peripheral get_peripheral() noexcept { return per; } //-----------------------------------------------------------------// /*! @brief 割り込みベクターを返す @return ベクター型 */ //-----------------------------------------------------------------// static ICU::VECTOR get_ivec() noexcept { return ivec; } }; typedef cmtw_t<0x00094200, peripheral::CMTW0, ICU::VECTOR::CMWI0> CMTW0; typedef cmtw_t<0x00094280, peripheral::CMTW1, ICU::VECTOR::CMWI1> CMTW1; } <commit_msg>Update: interrup vector<commit_after>#pragma once //=====================================================================// /*! @file @brief RX64M, RX65x, RX71M, RX72M グループ・CMTW 定義 @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2018, 2020 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/device.hpp" /// cmtw モジュールが無いデバイスでエラーとする #if defined(SIG_RX24T) || defined(SIG_RX66T) || defined(SIG_RX72T) # error "cmtw.hpp: This module does not exist" #endif namespace device { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンペアマッチタイマ W クラス @param[in] base ベース・アドレス @param[in] per ペリフェラル @param[in] ivec 割り込みベクター */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// template <uint32_t base, peripheral per, ICU::VECTOR ivec> struct cmtw_t { //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマスタートレジスタ(CMWSTR) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct cmwstr_t : public rw16_t<base + 0x00> { typedef rw16_t<base + 0x00> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bit_rw_t <io_, bitpos::B0> STR; }; static cmwstr_t CMWSTR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマコントロールレジスタ(CMWCR) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct cmwcr_t : public rw16_t<base + 0x04> { typedef rw16_t<base + 0x04> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bits_rw_t<io_, bitpos::B0, 2> CKS; bit_rw_t <io_, bitpos::B3> CMWIE; bit_rw_t <io_, bitpos::B4> IC0IE; bit_rw_t <io_, bitpos::B5> IC1IE; bit_rw_t <io_, bitpos::B6> OC0IE; bit_rw_t <io_, bitpos::B7> OC1IE; bit_rw_t <io_, bitpos::B9> CMS; bits_rw_t<io_, bitpos::B13, 3> CCLR; }; static cmwcr_t CMWCR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマ I/O コントロールレジスタ(CMWIOR) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// struct cmwior_t : public rw16_t<base + 0x08> { typedef rw16_t<base + 0x08> io_; using io_::operator =; using io_::operator (); using io_::operator |=; using io_::operator &=; bits_rw_t<io_, bitpos::B0, 2> IC0; bits_rw_t<io_, bitpos::B2, 2> IC1; bit_rw_t <io_, bitpos::B4> IC0E; bit_rw_t <io_, bitpos::B5> IC1E; bits_rw_t<io_, bitpos::B8, 2> OC0; bits_rw_t<io_, bitpos::B10, 2> OC1; bit_rw_t <io_, bitpos::B12> OC0E; bit_rw_t <io_, bitpos::B13> OC1E; bit_rw_t <io_, bitpos::B15> CMWE; }; static cmwior_t CMWIOR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief タイマカウンタ(CMWCNT) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x10> CMWCNT; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief コンペアマッチコンスタントレジスタ(CMWCOR) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x14> CMWCOR; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief インプットキャプチャレジスタ 0(CMWICR0) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x18> CMWICR0; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief インプットキャプチャレジスタ 1(CMWICR1) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x1C> CMWICR1; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief アウトプットコンペアレジスタ 0(CMWOCR0) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x20> CMWOCR0; //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// /*! @brief アウトプットコンペアレジスタ 1(CMWOCR1) */ //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// static rw32_t<base + 0x24> CMWOCR1; //-----------------------------------------------------------------// /*! @brief ペリフェラル型を返す @return ペリフェラル型 */ //-----------------------------------------------------------------// static peripheral get_peripheral() noexcept { return per; } //-----------------------------------------------------------------// /*! @brief 割り込みベクターを返す @return ベクター型 */ //-----------------------------------------------------------------// static ICU::VECTOR get_ivec() noexcept { return ivec; } }; typedef cmtw_t<0x00094200, peripheral::CMTW0, ICU::VECTOR::CMWI0> CMTW0; typedef cmtw_t<0x00094280, peripheral::CMTW1, ICU::VECTOR::CMWI1> CMTW1; } <|endoftext|>
<commit_before>#include <stdio.h> #include "xbyak/xbyak.h" using namespace Xbyak; #ifdef _MSC_VER #pragma warning(disable : 4245) #endif class Sample : public CodeGenerator { void operator=(const Sample&); public: #include "nm.cpp" }; #define _STR(x) #x #define TEST(syntax) err = true; try { syntax; err = false; } catch (Xbyak::Error) { } catch (...) { } if (!err) printf("should be err:%s;\n", _STR(syntax)) class ErrorSample : public CodeGenerator { void operator=(const ErrorSample&); public: void gen() { bool err; TEST(mov(ptr[eax],1)); TEST(test(ptr[eax],1)); TEST(adc(ptr[eax],1)); TEST(setz(eax)); } }; int main() { try { Sample s; s.gen(); } catch (std::exception& e) { printf("ERR:%s\n", e.what()); } catch (...) { printf("unknown error\n"); } ErrorSample es; es.gen(); } <commit_msg>add try catch<commit_after>#include <stdio.h> #include "xbyak/xbyak.h" using namespace Xbyak; #ifdef _MSC_VER #pragma warning(disable : 4245) #endif class Sample : public CodeGenerator { void operator=(const Sample&); public: #include "nm.cpp" }; #define _STR(x) #x #define TEST(syntax) err = true; try { syntax; err = false; } catch (Xbyak::Error) { } catch (...) { } if (!err) printf("should be err:%s;\n", _STR(syntax)) class ErrorSample : public CodeGenerator { void operator=(const ErrorSample&); public: void gen() { bool err; TEST(mov(ptr[eax],1)); TEST(test(ptr[eax],1)); TEST(adc(ptr[eax],1)); TEST(setz(eax)); } }; int main() try { try { Sample s; s.gen(); } catch (std::exception& e) { printf("ERR:%s\n", e.what()); } catch (...) { printf("unknown error\n"); } ErrorSample es; es.gen(); } catch (std::exception& e) { printf("err %s\n", e.what()); return 1; } <|endoftext|>
<commit_before>#include "debug_render.h" #include "file_system.h" #include "input.h" #include "loader.h" #include "memory.h" #include "pen.h" #include "pen_string.h" #include "renderer.h" #include "str/Str.h" #include "threads.h" #include "timer.h" using namespace pen; using namespace put; namespace { void* user_setup(void* params); loop_t user_update(); void user_shutdown(); } // namespace namespace pen { pen_creation_params pen_entry(int argc, char** argv) { pen::pen_creation_params p; p.window_width = 1280; p.window_height = 720; p.window_title = "input_example"; p.window_sample_count = 4; p.user_thread_function = user_setup; p.flags = pen::e_pen_create_flags::renderer; return p; } } // namespace pen namespace { struct vertex { float x, y, z, w; }; struct textured_vertex { float x, y, z, w; float u, v; }; pen::job_thread_params* s_job_params = nullptr; pen::job* s_thread_info = nullptr; u32 s_clear_state = 0; u32 s_raster_state = 0; u32 s_cb_2d_view = 0; void* user_setup(void* params) { // unpack the params passed to the thread and signal to the engine it ok to proceed s_job_params = (pen::job_thread_params*)params; s_thread_info = s_job_params->job_info; pen::semaphore_post(s_thread_info->p_sem_continue, 1); // initialise the debug render system put::dbg::init(); // create 2 clear states one for the render target and one for the main screen, so we can see the difference static pen::clear_state cs = { 0.5f, 0.5f, 0.5f, 0.5f, 1.0f, 0x00, PEN_CLEAR_COLOUR_BUFFER | PEN_CLEAR_DEPTH_BUFFER, }; s_clear_state = pen::renderer_create_clear_state(cs); // raster state pen::raster_state_creation_params rcp; pen::memory_zero(&rcp, sizeof(raster_state_creation_params)); rcp.fill_mode = PEN_FILL_SOLID; rcp.cull_mode = PEN_CULL_BACK; rcp.depth_bias_clamp = 0.0f; rcp.sloped_scale_depth_bias = 0.0f; rcp.depth_clip_enable = true; s_raster_state = pen::renderer_create_raster_state(rcp); // cb pen::buffer_creation_params bcp; bcp.usage_flags = PEN_USAGE_DYNAMIC; bcp.bind_flags = PEN_BIND_CONSTANT_BUFFER; bcp.cpu_access_flags = PEN_CPU_ACCESS_WRITE; bcp.buffer_size = sizeof(float) * 20; bcp.data = (void*)nullptr; s_cb_2d_view = pen::renderer_create_buffer(bcp); pen_main_loop(user_update); return PEN_THREAD_OK; } void user_shutdown() { dbg::shutdown(); pen::renderer_new_frame(); pen::renderer_release_clear_state(s_clear_state); pen::renderer_release_buffer(s_cb_2d_view); pen::renderer_release_raster_state(s_raster_state); pen::renderer_present(); pen::renderer_consume_cmd_buffer(); pen::semaphore_post(s_thread_info->p_sem_terminated, 1); } loop_t user_update() { // setup renderer pen::renderer_new_frame(); pen::viewport vp = {0.0f, 0.0f, PEN_BACK_BUFFER_RATIO, 1.0f, 0.0f, 1.0f}; s32 iw, ih; pen::window_get_size(iw, ih); pen::viewport vvp = {0.0f, 0.0f, (f32)iw, (f32)ih, 0.0f, 1.0f}; pen::renderer_set_targets(PEN_BACK_BUFFER_COLOUR, PEN_BACK_BUFFER_DEPTH); pen::renderer_set_raster_state(s_raster_state); pen::renderer_set_viewport(vp); pen::renderer_set_scissor_rect(rect{vp.x, vp.y, vp.width, vp.height}); pen::renderer_clear(s_clear_state); put::dbg::add_text_2f(10.0f, 10.0f, vvp, vec4f(0.0f, 1.0f, 0.0f, 1.0f), "%s", "Input Test"); const pen::mouse_state& ms = pen::input_get_mouse_state(); // mouse vec2f mouse_pos = vec2f((f32)ms.x, vvp.height - (f32)ms.y); vec2f mouse_quad_size = vec2f(5.0f, 5.0f); put::dbg::add_quad_2f(mouse_pos, mouse_quad_size, vec4f::cyan()); put::dbg::add_text_2f(10.0f, 20.0f, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "mouse down : left %i, middle %i, right %i: mouse_wheel %i", ms.buttons[PEN_MOUSE_L], ms.buttons[PEN_MOUSE_M], ms.buttons[PEN_MOUSE_R], ms.wheel); // key down Str key_msg = "key down: "; for (s32 key = 0; key < PK_COUNT; ++key) { if (pen::input_key(key)) { key_msg.append("["); key_msg.append(pen::input_get_key_str(key)); key_msg.append("]"); } } key_msg.append("\n"); put::dbg::add_text_2f(10.0f, 30.0f, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "%s", key_msg.c_str()); Str ascii_msg = "character down: "; for (s32 key = 0; key < PK_COUNT; ++key) { if (pen::input_get_unicode_key(key)) { ascii_msg.append("["); ascii_msg.append(key); ascii_msg.append("]"); } } ascii_msg.append("\n"); Str unicode = pen::input_get_unicode_input(); static Str text_buffer; if (unicode[0] == 8) { text_buffer[text_buffer.length() - 1] = '\0'; } else { text_buffer.append(unicode.c_str()); } put::dbg::add_text_2f(10.0f, 40.0f, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "input text: %s", text_buffer.c_str()); // raw gamepad u32 num_gamepads = input_get_num_gamepads(); put::dbg::add_text_2f(10.0f, 60.0f, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "Gamepads: %i", num_gamepads); f32 ypos = 70.0f; for (u32 i = 0; i < num_gamepads; ++i) { f32 start_y = ypos; raw_gamepad_state gs; pen::input_get_raw_gamepad_state(i, gs); put::dbg::add_text_2f(10.0f, ypos, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "Vendor ID: [%i] : Product ID [%i]", gs.vendor_id, gs.product_id); ypos += 10.0f; for (u32 b = 0; b < 16; ++b) { put::dbg::add_text_2f(10.0f, ypos, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "Button: %i : [%i]", b, gs.button[b]); ypos += 10.0f; } f32 xpos = 150.0f; for (u32 r = 0; r < 4; ++r) { ypos = start_y + 10.0f; for (u32 a = 0; a < 16; ++a) { u32 ai = r * 16 + a; put::dbg::add_text_2f(xpos, ypos, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "Axis: %i : [%f]", ai, gs.axis[ai]); ypos += 10.0f; } xpos += 150.0f; } } static const c8* mappings[] = {"No Mapping", "DS4", "xbox 360", "DS4 XInput", "xbox 360 XInput"}; ypos += 10.0f; for (u32 i = 0; i < num_gamepads; ++i) { raw_gamepad_state rgs; pen::input_get_raw_gamepad_state(i, rgs); if (rgs.mapping == PEN_INVALID_HANDLE) { put::dbg::add_text_2f(10.0f, ypos, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "Initialising Mapping..."); continue; } gamepad_state gs; pen::input_get_gamepad_state(i, gs); put::dbg::add_text_2f(10.0f, ypos, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "Mapped Gamepad: %s", mappings[rgs.mapping]); ypos += 10.0f; f32 start_y = ypos; static const c8* button_names[] = {"A / CROSS", "B / CIRCLE", "X / SQUARE", "Y / TRIANGLE", "L1", "R1", "BACK / SHARE", "START / OPTIONS", "L3", "R3", "DPAD LEFT", "DPAD RIGHT", "DPAD UP", "DPAD DOWN", "TOUCH PAD", "PLATFORM"}; static_assert(PEN_ARRAY_SIZE(button_names) == PGP_BUTTON_COUNT, "mismatched array size"); for (u32 b = 0; b < PGP_BUTTON_COUNT; ++b) { put::dbg::add_text_2f(10.0f, ypos, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "%s: %i", button_names[b], gs.button[b]); ypos += 10.0f; } static const c8* axis_names[] = {"Left Stick X", "Left Stick Y", "Right Stick X", "Right Stick Y", "L TRIGGER", "R TRIGGER"}; static_assert(PEN_ARRAY_SIZE(axis_names) == PGP_AXIS_COUNT, "mismatched array size"); ypos = start_y; f32 xpos = 150.0f; for (u32 a = 0; a < PGP_BUTTON_COUNT; ++a) { put::dbg::add_text_2f(xpos, ypos, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "%s: %f", axis_names[a], gs.axis[a]); ypos += 10.0f; } } // create 2d view proj matrix float W = 2.0f / vvp.width; float H = 2.0f / vvp.height; float mvp[4][4] = {{W, 0.0, 0.0, 0.0}, {0.0, H, 0.0, 0.0}, {0.0, 0.0, 1.0, 0.0}, {-1.0, -1.0, 0.0, 1.0}}; pen::renderer_update_buffer(s_cb_2d_view, mvp, sizeof(mvp), 0); // render dbg put::dbg::render_2d(s_cb_2d_view); // present pen::renderer_present(); pen::renderer_consume_cmd_buffer(); // msg from the engine we want to terminate if (pen::semaphore_try_wait(s_thread_info->p_sem_exit)) { user_shutdown(); pen_main_loop_exit(); } pen_main_loop_continue(); } } // namespace <commit_msg>- add mouse pos to sample<commit_after>#include "debug_render.h" #include "file_system.h" #include "input.h" #include "loader.h" #include "memory.h" #include "pen.h" #include "pen_string.h" #include "renderer.h" #include "str/Str.h" #include "threads.h" #include "timer.h" using namespace pen; using namespace put; namespace { void* user_setup(void* params); loop_t user_update(); void user_shutdown(); } // namespace namespace pen { pen_creation_params pen_entry(int argc, char** argv) { pen::pen_creation_params p; p.window_width = 1280; p.window_height = 720; p.window_title = "input_example"; p.window_sample_count = 4; p.user_thread_function = user_setup; p.flags = pen::e_pen_create_flags::renderer; return p; } } // namespace pen namespace { struct vertex { float x, y, z, w; }; struct textured_vertex { float x, y, z, w; float u, v; }; pen::job_thread_params* s_job_params = nullptr; pen::job* s_thread_info = nullptr; u32 s_clear_state = 0; u32 s_raster_state = 0; u32 s_cb_2d_view = 0; void* user_setup(void* params) { // unpack the params passed to the thread and signal to the engine it ok to proceed s_job_params = (pen::job_thread_params*)params; s_thread_info = s_job_params->job_info; pen::semaphore_post(s_thread_info->p_sem_continue, 1); // initialise the debug render system put::dbg::init(); // create 2 clear states one for the render target and one for the main screen, so we can see the difference static pen::clear_state cs = { 0.5f, 0.5f, 0.5f, 0.5f, 1.0f, 0x00, PEN_CLEAR_COLOUR_BUFFER | PEN_CLEAR_DEPTH_BUFFER, }; s_clear_state = pen::renderer_create_clear_state(cs); // raster state pen::raster_state_creation_params rcp; pen::memory_zero(&rcp, sizeof(raster_state_creation_params)); rcp.fill_mode = PEN_FILL_SOLID; rcp.cull_mode = PEN_CULL_BACK; rcp.depth_bias_clamp = 0.0f; rcp.sloped_scale_depth_bias = 0.0f; rcp.depth_clip_enable = true; s_raster_state = pen::renderer_create_raster_state(rcp); // cb pen::buffer_creation_params bcp; bcp.usage_flags = PEN_USAGE_DYNAMIC; bcp.bind_flags = PEN_BIND_CONSTANT_BUFFER; bcp.cpu_access_flags = PEN_CPU_ACCESS_WRITE; bcp.buffer_size = sizeof(float) * 20; bcp.data = (void*)nullptr; s_cb_2d_view = pen::renderer_create_buffer(bcp); pen_main_loop(user_update); return PEN_THREAD_OK; } void user_shutdown() { dbg::shutdown(); pen::renderer_new_frame(); pen::renderer_release_clear_state(s_clear_state); pen::renderer_release_buffer(s_cb_2d_view); pen::renderer_release_raster_state(s_raster_state); pen::renderer_present(); pen::renderer_consume_cmd_buffer(); pen::semaphore_post(s_thread_info->p_sem_terminated, 1); } loop_t user_update() { // setup renderer pen::renderer_new_frame(); pen::viewport vp = {0.0f, 0.0f, PEN_BACK_BUFFER_RATIO, 1.0f, 0.0f, 1.0f}; s32 iw, ih; pen::window_get_size(iw, ih); pen::viewport vvp = {0.0f, 0.0f, (f32)iw, (f32)ih, 0.0f, 1.0f}; pen::renderer_set_targets(PEN_BACK_BUFFER_COLOUR, PEN_BACK_BUFFER_DEPTH); pen::renderer_set_raster_state(s_raster_state); pen::renderer_set_viewport(vp); pen::renderer_set_scissor_rect(rect{vp.x, vp.y, vp.width, vp.height}); pen::renderer_clear(s_clear_state); put::dbg::add_text_2f(10.0f, 10.0f, vvp, vec4f(0.0f, 1.0f, 0.0f, 1.0f), "%s", "Input Test"); const pen::mouse_state& ms = pen::input_get_mouse_state(); // mouse vec2f mouse_pos = vec2f((f32)ms.x, vvp.height - (f32)ms.y); vec2f mouse_quad_size = vec2f(5.0f, 5.0f); put::dbg::add_quad_2f(mouse_pos, mouse_quad_size, vec4f::cyan()); put::dbg::add_text_2f(10.0f, 20.0f, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "mouse (%f,%f) | down : left %i, middle %i, right %i: mouse_wheel %i", mouse_pos.x, mouse_pos.y, ms.buttons[PEN_MOUSE_L], ms.buttons[PEN_MOUSE_M], ms.buttons[PEN_MOUSE_R], ms.wheel); // key down Str key_msg = "key down: "; for (s32 key = 0; key < PK_COUNT; ++key) { if (pen::input_key(key)) { key_msg.append("["); key_msg.append(pen::input_get_key_str(key)); key_msg.append("]"); } } key_msg.append("\n"); put::dbg::add_text_2f(10.0f, 30.0f, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "%s", key_msg.c_str()); Str ascii_msg = "character down: "; for (s32 key = 0; key < PK_COUNT; ++key) { if (pen::input_get_unicode_key(key)) { ascii_msg.append("["); ascii_msg.append(key); ascii_msg.append("]"); } } ascii_msg.append("\n"); Str unicode = pen::input_get_unicode_input(); static Str text_buffer; if (unicode[0] == 8) { text_buffer[text_buffer.length() - 1] = '\0'; } else { text_buffer.append(unicode.c_str()); } put::dbg::add_text_2f(10.0f, 40.0f, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "input text: %s", text_buffer.c_str()); // raw gamepad u32 num_gamepads = input_get_num_gamepads(); put::dbg::add_text_2f(10.0f, 60.0f, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "Gamepads: %i", num_gamepads); f32 ypos = 70.0f; for (u32 i = 0; i < num_gamepads; ++i) { f32 start_y = ypos; raw_gamepad_state gs; pen::input_get_raw_gamepad_state(i, gs); put::dbg::add_text_2f(10.0f, ypos, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "Vendor ID: [%i] : Product ID [%i]", gs.vendor_id, gs.product_id); ypos += 10.0f; for (u32 b = 0; b < 16; ++b) { put::dbg::add_text_2f(10.0f, ypos, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "Button: %i : [%i]", b, gs.button[b]); ypos += 10.0f; } f32 xpos = 150.0f; for (u32 r = 0; r < 4; ++r) { ypos = start_y + 10.0f; for (u32 a = 0; a < 16; ++a) { u32 ai = r * 16 + a; put::dbg::add_text_2f(xpos, ypos, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "Axis: %i : [%f]", ai, gs.axis[ai]); ypos += 10.0f; } xpos += 150.0f; } } static const c8* mappings[] = {"No Mapping", "DS4", "xbox 360", "DS4 XInput", "xbox 360 XInput"}; ypos += 10.0f; for (u32 i = 0; i < num_gamepads; ++i) { raw_gamepad_state rgs; pen::input_get_raw_gamepad_state(i, rgs); if (rgs.mapping == PEN_INVALID_HANDLE) { put::dbg::add_text_2f(10.0f, ypos, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "Initialising Mapping..."); continue; } gamepad_state gs; pen::input_get_gamepad_state(i, gs); put::dbg::add_text_2f(10.0f, ypos, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "Mapped Gamepad: %s", mappings[rgs.mapping]); ypos += 10.0f; f32 start_y = ypos; static const c8* button_names[] = {"A / CROSS", "B / CIRCLE", "X / SQUARE", "Y / TRIANGLE", "L1", "R1", "BACK / SHARE", "START / OPTIONS", "L3", "R3", "DPAD LEFT", "DPAD RIGHT", "DPAD UP", "DPAD DOWN", "TOUCH PAD", "PLATFORM"}; static_assert(PEN_ARRAY_SIZE(button_names) == PGP_BUTTON_COUNT, "mismatched array size"); for (u32 b = 0; b < PGP_BUTTON_COUNT; ++b) { put::dbg::add_text_2f(10.0f, ypos, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "%s: %i", button_names[b], gs.button[b]); ypos += 10.0f; } static const c8* axis_names[] = {"Left Stick X", "Left Stick Y", "Right Stick X", "Right Stick Y", "L TRIGGER", "R TRIGGER"}; static_assert(PEN_ARRAY_SIZE(axis_names) == PGP_AXIS_COUNT, "mismatched array size"); ypos = start_y; f32 xpos = 150.0f; for (u32 a = 0; a < PGP_BUTTON_COUNT; ++a) { put::dbg::add_text_2f(xpos, ypos, vvp, vec4f(1.0f, 1.0f, 1.0f, 1.0f), "%s: %f", axis_names[a], gs.axis[a]); ypos += 10.0f; } } // create 2d view proj matrix float W = 2.0f / vvp.width; float H = 2.0f / vvp.height; float mvp[4][4] = {{W, 0.0, 0.0, 0.0}, {0.0, H, 0.0, 0.0}, {0.0, 0.0, 1.0, 0.0}, {-1.0, -1.0, 0.0, 1.0}}; pen::renderer_update_buffer(s_cb_2d_view, mvp, sizeof(mvp), 0); // render dbg put::dbg::render_2d(s_cb_2d_view); // present pen::renderer_present(); pen::renderer_consume_cmd_buffer(); // msg from the engine we want to terminate if (pen::semaphore_try_wait(s_thread_info->p_sem_exit)) { user_shutdown(); pen_main_loop_exit(); } pen_main_loop_continue(); } } // namespace <|endoftext|>
<commit_before>#include "greedy_solver.h" #include <algorithm> #include <functional> #include <vector> #include "cyc_limits.h" #include "logger.h" namespace cyclus { //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - GreedySolver::~GreedySolver() { if (conditioner_ != NULL) delete conditioner_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void GreedySolver::Solve() { if (conditioner_ != NULL) { conditioner_->Condition(graph_); } std::for_each(graph_->request_groups().begin(), graph_->request_groups().end(), std::bind1st( std::mem_fun(&GreedySolver::GreedilySatisfySet_), this)); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void GreedySolver::GreedilySatisfySet_(RequestGroup::Ptr prs) { double target = prs->qty(); double match = 0; const std::vector<ExchangeNode::Ptr>& nodes = prs->nodes(); std::vector<ExchangeNode::Ptr>::const_iterator req_it = nodes.begin(); std::vector<Arc>::const_iterator arc_it; CLOG(LEV_DEBUG1) << "Greedy Solving for " << target << " amount of a resource."; while( (match <= target) && (req_it != nodes.end()) ) { // this if statement is needed because map.at() will throw if the key does // not exist, which is a corner case for when there is a request with no bid // arcs associated with it if (graph_->node_arc_map().count(*req_it) > 0) { const std::vector<Arc>& arcs = graph_->node_arc_map().at(*req_it); std::vector<Arc> sorted(arcs); // make a copy for now std::sort(sorted.begin(), sorted.end(), ReqPrefComp); arc_it = sorted.begin(); while( (match <= target) && (arc_it != sorted.end()) ) { double remain = target - match; double tomatch = std::min(remain, Capacity(*arc_it)); // this implementat-ion is for requester-specific exclusivity tomatch = (arc_it->exclusive && tomatch < arc_it->excl_val) ? 0 : tomatch; if (tomatch > eps()) { CLOG(LEV_DEBUG1) << "Greedy Solver is matching " << tomatch << " amount of a resource."; graph_->AddMatch(*arc_it, tomatch); match += tomatch; } ++arc_it; } // while( (match =< target) && (arc_it != arcs.end()) ) } // if(graph_->node_arc_map().count(*req_it) > 0) ++req_it; } // while( (match =< target) && (req_it != nodes.end()) ) } } // namespace cyclus <commit_msg>updated exclusivity adjustment. this bug wasn't evident (or testable) because capacity-constraints will cause tomatch < remain which then will by definition be tomatch < excl_val of arc. all tests pass and alls well.<commit_after>#include "greedy_solver.h" #include <algorithm> #include <functional> #include <vector> #include "cyc_limits.h" #include "logger.h" namespace cyclus { //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - GreedySolver::~GreedySolver() { if (conditioner_ != NULL) delete conditioner_; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void GreedySolver::Solve() { if (conditioner_ != NULL) { conditioner_->Condition(graph_); } std::for_each(graph_->request_groups().begin(), graph_->request_groups().end(), std::bind1st( std::mem_fun(&GreedySolver::GreedilySatisfySet_), this)); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void GreedySolver::GreedilySatisfySet_(RequestGroup::Ptr prs) { double target = prs->qty(); double match = 0; const std::vector<ExchangeNode::Ptr>& nodes = prs->nodes(); std::vector<ExchangeNode::Ptr>::const_iterator req_it = nodes.begin(); std::vector<Arc>::const_iterator arc_it; CLOG(LEV_DEBUG1) << "Greedy Solving for " << target << " amount of a resource."; while( (match <= target) && (req_it != nodes.end()) ) { // this if statement is needed because map.at() will throw if the key does // not exist, which is a corner case for when there is a request with no bid // arcs associated with it if (graph_->node_arc_map().count(*req_it) > 0) { const std::vector<Arc>& arcs = graph_->node_arc_map().at(*req_it); std::vector<Arc> sorted(arcs); // make a copy for now std::sort(sorted.begin(), sorted.end(), ReqPrefComp); arc_it = sorted.begin(); while( (match <= target) && (arc_it != sorted.end()) ) { double remain = target - match; // capacity adjustment double tomatch = std::min(remain, Capacity(*arc_it)); // exclusivity adjustment if (arc_it->exclusive) { double excl_val = arc_it->excl_val; tomatch = (tomatch < excl_val) ? 0 : excl_val; } if (tomatch > eps()) { CLOG(LEV_DEBUG1) << "Greedy Solver is matching " << tomatch << " amount of a resource."; graph_->AddMatch(*arc_it, tomatch); match += tomatch; } ++arc_it; } // while( (match =< target) && (arc_it != arcs.end()) ) } // if(graph_->node_arc_map().count(*req_it) > 0) ++req_it; } // while( (match =< target) && (req_it != nodes.end()) ) } } // namespace cyclus <|endoftext|>
<commit_before>#include "stdafx.h" #include "DBManager.h" #include "ODBCInterface.h" #include "TimeManager.h" DBManager *g_pDBManager = NULL; DBManager::DBManager() { mCharDBInterface = new ODBCInterface(); m_Active = TRUE; } DBManager::~DBManager() { SAFE_DELETE(mCharDBInterface); } BOOL DBManager::Init() { __ENTER_FUNCTION //从Config 读取Login DB 相关的数据 CHAR Host[HOST_STR_LEN]; strncpy(Host,g_Config.m_ShareMemInfo.m_DBIP,HOST_STR_LEN); //连接对端IP Host[HOST_STR_LEN-1] = '\0'; UINT Port = g_Config.m_ShareMemInfo.m_DBPort; //连接对端端口 CHAR Database[DATABASE_STR_LEN]; strncpy(Database,g_Config.m_ShareMemInfo.m_DBName,DATABASE_STR_LEN); //数据库名称 Database[DATABASE_STR_LEN-1] = '\0'; CHAR User[DB_USE_STR_LEN]; //用户名称 strncpy(User,g_Config.m_ShareMemInfo.m_DBUser,DB_USE_STR_LEN); User[DB_USE_STR_LEN-1] = '\0'; CHAR Password[DB_PASSWORD_STR_LEN]; //密码 strncpy(Password,g_Config.m_ShareMemInfo.m_DBPassword,DB_PASSWORD_STR_LEN); Password[DB_PASSWORD_STR_LEN-1] = '\0'; Assert(mCharDBInterface); mCharDBInterface->Connect(Database, User, Password); if(!mCharDBInterface->IsConnected()) { Log::SaveLog(LOGIN_LOGFILE,"mCharDBInterface->Connect()... Get Errors: %s ",mCharDBInterface->GetErrorMsg()); } // mCharDBInterface->IsConnected(); return TRUE; __LEAVE_FUNCTION return FALSE; } VOID DBManager::run() { __ENTER_FUNCTION /* UINT uTime = g_pTimeManager->CurrentTime(); g_DBLogicManager.m_ThreadID = getTID(); while (IsActive()) { MySleep(100); if(!mCharDBInterface->IsConnected()) { mCharDBInterface->Connect(); } g_DBLogicManager.HeartBeat(uTime); }*/ __LEAVE_FUNCTION } ODBCInterface* DBManager::GetInterface(DB_NAMES name) { __ENTER_FUNCTION switch(name) { case CHARACTER_DATABASE: return mCharDBInterface; break; default: return NULL; } __LEAVE_FUNCTION } <commit_msg>optimize the common db manager<commit_after>/** * PAP Server Engine ( https://github.com/viticm/web-pap ) * $Id DBManager.cpp * @link https://github.com/viticm/web-pap/tree/master/server for the canonical source repository * @copyright Copyright (c) 2013-2013 viticm( viticm@126.com ) * @license * @user viticm<viticm@126.com> * @date 2013-8-9 15:25:01 * @uses the database manager */ #include "stdafx.h" #include "DBManager.h" #include "ODBCInterface.h" #include "TimeManager.h" DBManager *g_pDBManager = NULL; DBManager::DBManager() { mCharDBInterface = new ODBCInterface(); m_Active = TRUE; } DBManager::~DBManager() { SAFE_DELETE(mCharDBInterface); } BOOL DBManager::Init() { __ENTER_FUNCTION //从Config 读取 Char DB 相关的数据 CHAR szDBCharHost[ HOST_STR_LEN ] ; strncpy( szDBCharHost, g_Config.m_ShareMemInfo.m_DBIP,HOST_STR_LEN ) ; //连接对端IP szDBCharHost[ HOST_STR_LEN - 1 ] = '\0' ; UINT uDBCharPort = g_Config.m_ShareMemInfo.m_DBPort ; //连接对端端口 CHAR szDBCharDatabase[ DATABASE_STR_LEN ] ; strncpy( szDBCharDatabase, g_Config.m_ShareMemInfo.m_DBName, DATABASE_STR_LEN ) ; //数据库名称 szDBCharDatabase[ DATABASE_STR_LEN - 1 ] = '\0' ; CHAR szDBCharUser[ DB_USE_STR_LEN ] ; //用户名称 strncpy( szDBCharUser, g_Config.m_ShareMemInfo.m_DBUser, DB_USE_STR_LEN ) ; szDBCharUser[ DB_USE_STR_LEN - 1 ] = '\0' ; CHAR szDBCharPassword[ DB_PASSWORD_STR_LEN ] ; //密码 strncpy( szDBCharPassword, g_Config.m_ShareMemInfo.m_DBPassword, DB_PASSWORD_STR_LEN ) ; szDBCharPassword[ DB_PASSWORD_STR_LEN - 1 ] = '\0' ; Assert( mCharDBInterface ); mCharDBInterface->Connect( szDBCharDatabase, szDBCharUser, szDBCharPassword ) ; if( !mCharDBInterface->IsConnected() ) { Log::SaveLog( LOGIN_LOGFILE,"mCharDBInterface->Connect()... Get Errors: %s ", mCharDBInterface->GetErrorMsg() ); } return TRUE; __LEAVE_FUNCTION return FALSE; } VOID DBManager::run() { __ENTER_FUNCTION /* UINT uTime = g_pTimeManager->CurrentTime(); g_DBLogicManager.m_ThreadID = getTID(); while (IsActive()) { MySleep(100); if(!mCharDBInterface->IsConnected()) { mCharDBInterface->Connect(); } g_DBLogicManager.HeartBeat(uTime); }*/ __LEAVE_FUNCTION } ODBCInterface* DBManager::GetInterface(DB_NAMES name) { __ENTER_FUNCTION switch(name) { case CHARACTER_DATABASE: return mCharDBInterface; break; default: return NULL; } __LEAVE_FUNCTION } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLTextMarkImportContext.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: hr $ $Date: 2006-06-19 18:46: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 * ************************************************************************/ #include "XMLTextMarkImportContext.hxx" #ifndef _RTL_USTRING #include <rtl/ustring.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_ #include <com/sun/star/xml/sax/XAttributeList.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XTEXTCONTENT_HPP_ #include <com/sun/star/text/XTextContent.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif using namespace ::rtl; using namespace ::com::sun::star::text; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::container; using namespace ::com::sun::star::xml::sax; using namespace ::xmloff::token; TYPEINIT1( XMLTextMarkImportContext, SvXMLImportContext); XMLTextMarkImportContext::XMLTextMarkImportContext( SvXMLImport& rImport, XMLTextImportHelper& rHlp, sal_uInt16 nPrefix, const OUString& rLocalName ) : SvXMLImportContext(rImport, nPrefix, rLocalName), rHelper(rHlp) { } enum lcl_MarkType { TypeReference, TypeReferenceStart, TypeReferenceEnd, TypeBookmark, TypeBookmarkStart, TypeBookmarkEnd }; static SvXMLEnumMapEntry __READONLY_DATA lcl_aMarkTypeMap[] = { { XML_REFERENCE_MARK, TypeReference }, { XML_REFERENCE_MARK_START, TypeReferenceStart }, { XML_REFERENCE_MARK_END, TypeReferenceEnd }, { XML_BOOKMARK, TypeBookmark }, { XML_BOOKMARK_START, TypeBookmarkStart }, { XML_BOOKMARK_END, TypeBookmarkEnd }, { XML_TOKEN_INVALID, 0 }, }; void XMLTextMarkImportContext::StartElement( const Reference<XAttributeList> & xAttrList) { const OUString sAPI_reference_mark( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.text.ReferenceMark")); const OUString sAPI_bookmark( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.text.Bookmark")); OUString sName; if (FindName(GetImport(), xAttrList, sName)) { sal_uInt16 nTmp; if (SvXMLUnitConverter::convertEnum(nTmp, GetLocalName(), lcl_aMarkTypeMap)) { switch ((lcl_MarkType)nTmp) { case TypeReference: // export point reference mark CreateAndInsertMark(GetImport(), sAPI_reference_mark, sName, rHelper.GetCursorAsRange()->getStart()); break; case TypeBookmark: // export point bookmark CreateAndInsertMark(GetImport(), sAPI_bookmark, sName, rHelper.GetCursorAsRange()->getStart()); break; case TypeBookmarkStart: // save XTextRange for later construction of bookmark rHelper.InsertBookmarkStartRange( sName, rHelper.GetCursorAsRange()->getStart()); break; case TypeBookmarkEnd: { // get old range, and construct Reference<XTextRange> xStartRange; if (rHelper.FindAndRemoveBookmarkStartRange(xStartRange, sName)) { Reference<XTextRange> xEndRange( rHelper.GetCursorAsRange()->getStart()); // check if beginning and end are in same XText if (xStartRange->getText() == xEndRange->getText()) { // create range for insertion Reference<XTextCursor> xInsertionCursor = rHelper.GetText()->createTextCursorByRange( xEndRange); xInsertionCursor->gotoRange(xStartRange, sal_True); //DBG_ASSERT(! xInsertionCursor->isCollapsed(), // "we want no point mark"); // can't assert, because someone could // create a file with subsequence // start/end elements Reference<XTextRange> xInsertionRange( xInsertionCursor, UNO_QUERY); // insert reference CreateAndInsertMark(GetImport(), sAPI_bookmark, sName, xInsertionRange); } // else: beginning/end in different XText -> ignore! } // else: no start found -> ignore! break; } case TypeReferenceStart: case TypeReferenceEnd: DBG_ERROR("reference start/end are handled in txtparai !"); break; default: DBG_ERROR("unknown mark type"); break; } } } } void XMLTextMarkImportContext::CreateAndInsertMark( SvXMLImport& rImport, const OUString& sServiceName, const OUString& sMarkName, const Reference<XTextRange> & rRange) { // create mark Reference<XMultiServiceFactory> xFactory(rImport.GetModel(),UNO_QUERY); if( xFactory.is() ) { Reference<XInterface> xIfc = xFactory->createInstance(sServiceName); // set name Reference<XNamed> xNamed(xIfc, UNO_QUERY); if (xNamed.is()) { xNamed->setName(sMarkName); // cast to XTextContent and attach to document Reference<XTextContent> xTextContent(xIfc, UNO_QUERY); if (xTextContent.is()) { // if inserting marks, bAbsorb==sal_False will cause // collapsing of the given XTextRange. rImport.GetTextImport()->GetText()->insertTextContent(rRange, xTextContent, sal_True); } } } } sal_Bool XMLTextMarkImportContext::FindName( SvXMLImport& rImport, const Reference<XAttributeList> & xAttrList, OUString& sName) { sal_Bool bNameOK = sal_False; // find name attribute first sal_Int16 nLength = xAttrList->getLength(); for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++) { OUString sLocalName; sal_uInt16 nPrefix = rImport.GetNamespaceMap(). GetKeyByAttrName( xAttrList->getNameByIndex(nAttr), &sLocalName ); if ( (XML_NAMESPACE_TEXT == nPrefix) && IsXMLToken(sLocalName, XML_NAME) ) { sName = xAttrList->getValueByIndex(nAttr); bNameOK = sal_True; } } return bNameOK; } <commit_msg>INTEGRATION: CWS pchfix02 (1.8.34); FILE MERGED 2006/09/01 18:00:08 kaib 1.8.34.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLTextMarkImportContext.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2006-09-17 11:14: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_xmloff.hxx" #include "XMLTextMarkImportContext.hxx" #ifndef _RTL_USTRING #include <rtl/ustring.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _XMLOFF_XMLTOKEN_HXX #include "xmltoken.hxx" #endif #ifndef _XMLOFF_XMLIMP_HXX #include "xmlimp.hxx" #endif #ifndef _XMLOFF_NMSPMAP_HXX #include "nmspmap.hxx" #endif #ifndef _XMLOFF_XMLNMSPE_HXX #include "xmlnmspe.hxx" #endif #ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_ #include <com/sun/star/xml/sax/XAttributeList.hpp> #endif #ifndef _COM_SUN_STAR_TEXT_XTEXTCONTENT_HPP_ #include <com/sun/star/text/XTextContent.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_ #include <com/sun/star/container/XNamed.hpp> #endif using namespace ::rtl; using namespace ::com::sun::star::text; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::container; using namespace ::com::sun::star::xml::sax; using namespace ::xmloff::token; TYPEINIT1( XMLTextMarkImportContext, SvXMLImportContext); XMLTextMarkImportContext::XMLTextMarkImportContext( SvXMLImport& rImport, XMLTextImportHelper& rHlp, sal_uInt16 nPrefix, const OUString& rLocalName ) : SvXMLImportContext(rImport, nPrefix, rLocalName), rHelper(rHlp) { } enum lcl_MarkType { TypeReference, TypeReferenceStart, TypeReferenceEnd, TypeBookmark, TypeBookmarkStart, TypeBookmarkEnd }; static SvXMLEnumMapEntry __READONLY_DATA lcl_aMarkTypeMap[] = { { XML_REFERENCE_MARK, TypeReference }, { XML_REFERENCE_MARK_START, TypeReferenceStart }, { XML_REFERENCE_MARK_END, TypeReferenceEnd }, { XML_BOOKMARK, TypeBookmark }, { XML_BOOKMARK_START, TypeBookmarkStart }, { XML_BOOKMARK_END, TypeBookmarkEnd }, { XML_TOKEN_INVALID, 0 }, }; void XMLTextMarkImportContext::StartElement( const Reference<XAttributeList> & xAttrList) { const OUString sAPI_reference_mark( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.text.ReferenceMark")); const OUString sAPI_bookmark( RTL_CONSTASCII_USTRINGPARAM("com.sun.star.text.Bookmark")); OUString sName; if (FindName(GetImport(), xAttrList, sName)) { sal_uInt16 nTmp; if (SvXMLUnitConverter::convertEnum(nTmp, GetLocalName(), lcl_aMarkTypeMap)) { switch ((lcl_MarkType)nTmp) { case TypeReference: // export point reference mark CreateAndInsertMark(GetImport(), sAPI_reference_mark, sName, rHelper.GetCursorAsRange()->getStart()); break; case TypeBookmark: // export point bookmark CreateAndInsertMark(GetImport(), sAPI_bookmark, sName, rHelper.GetCursorAsRange()->getStart()); break; case TypeBookmarkStart: // save XTextRange for later construction of bookmark rHelper.InsertBookmarkStartRange( sName, rHelper.GetCursorAsRange()->getStart()); break; case TypeBookmarkEnd: { // get old range, and construct Reference<XTextRange> xStartRange; if (rHelper.FindAndRemoveBookmarkStartRange(xStartRange, sName)) { Reference<XTextRange> xEndRange( rHelper.GetCursorAsRange()->getStart()); // check if beginning and end are in same XText if (xStartRange->getText() == xEndRange->getText()) { // create range for insertion Reference<XTextCursor> xInsertionCursor = rHelper.GetText()->createTextCursorByRange( xEndRange); xInsertionCursor->gotoRange(xStartRange, sal_True); //DBG_ASSERT(! xInsertionCursor->isCollapsed(), // "we want no point mark"); // can't assert, because someone could // create a file with subsequence // start/end elements Reference<XTextRange> xInsertionRange( xInsertionCursor, UNO_QUERY); // insert reference CreateAndInsertMark(GetImport(), sAPI_bookmark, sName, xInsertionRange); } // else: beginning/end in different XText -> ignore! } // else: no start found -> ignore! break; } case TypeReferenceStart: case TypeReferenceEnd: DBG_ERROR("reference start/end are handled in txtparai !"); break; default: DBG_ERROR("unknown mark type"); break; } } } } void XMLTextMarkImportContext::CreateAndInsertMark( SvXMLImport& rImport, const OUString& sServiceName, const OUString& sMarkName, const Reference<XTextRange> & rRange) { // create mark Reference<XMultiServiceFactory> xFactory(rImport.GetModel(),UNO_QUERY); if( xFactory.is() ) { Reference<XInterface> xIfc = xFactory->createInstance(sServiceName); // set name Reference<XNamed> xNamed(xIfc, UNO_QUERY); if (xNamed.is()) { xNamed->setName(sMarkName); // cast to XTextContent and attach to document Reference<XTextContent> xTextContent(xIfc, UNO_QUERY); if (xTextContent.is()) { // if inserting marks, bAbsorb==sal_False will cause // collapsing of the given XTextRange. rImport.GetTextImport()->GetText()->insertTextContent(rRange, xTextContent, sal_True); } } } } sal_Bool XMLTextMarkImportContext::FindName( SvXMLImport& rImport, const Reference<XAttributeList> & xAttrList, OUString& sName) { sal_Bool bNameOK = sal_False; // find name attribute first sal_Int16 nLength = xAttrList->getLength(); for(sal_Int16 nAttr = 0; nAttr < nLength; nAttr++) { OUString sLocalName; sal_uInt16 nPrefix = rImport.GetNamespaceMap(). GetKeyByAttrName( xAttrList->getNameByIndex(nAttr), &sLocalName ); if ( (XML_NAMESPACE_TEXT == nPrefix) && IsXMLToken(sLocalName, XML_NAME) ) { sName = xAttrList->getValueByIndex(nAttr); bNameOK = sal_True; } } return bNameOK; } <|endoftext|>
<commit_before><commit_msg>Add .tmp suffix to downloading files<commit_after><|endoftext|>
<commit_before>/*---------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have purchased from * Numenta, Inc. a separate commercial license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * ---------------------------------------------------------------------- */ /** @file * Definitions for the Spatial Pooler */ #ifndef NTA_spatial_pooler_HPP #define NTA_spatial_pooler_HPP #include <cstring> #include <iostream> #include <nta/math/SparseBinaryMatrix.hpp> #include <nta/math/SparseMatrix.hpp> #include <nta/types/types.hpp> #include <string> #include <vector> using namespace std; namespace nta { namespace algorithms { namespace spatial_pooler { ///////////////////////////////////////////////////////////////////////// /// CLA spatial pooler implementation in C++. /// /// @b Responsibility /// The Spatial Pooler is responsible for creating a sparse distributed /// representation of the input. It computes the set of active columns. /// It maintains the state of the proximal dendrites between the columns /// and the inputs bits and keeps track of the activity and overlap /// duty cycles /// /// @b Description /// Todo. /// ///////////////////////////////////////////////////////////////////////// class SpatialPooler { public: SpatialPooler(); ~SpatialPooler() {} virtual UInt version() const { return version_; }; virtual void compute(UInt inputVector[], bool learn, UInt activeVector[]); virtual void save(ostream& outStream); virtual void load(istream& inStream); UInt persistentSize(); UInt getNumColumns(); UInt getNumInputs(); UInt getPotentialRadius(); void setPotentialRadius(UInt potentialRadius); Real getPotentialPct(); void setPotentialPct(Real potentialPct); bool getGlobalInhibition(); void setGlobalInhibition(bool globalInhibition); Int getNumActiveColumnsPerInhArea(); void setNumActiveColumnsPerInhArea(UInt numActiveColumnsPerInhArea); Real getLocalAreaDensity(); void setLocalAreaDensity(Real localAreaDensity); UInt getStimulusThreshold(); void setStimulusThreshold(UInt stimulusThreshold); UInt getInhibitionRadius(); void setInhibitionRadius(UInt inhibitionRadius); UInt getDutyCyclePeriod(); void setDutyCyclePeriod(UInt dutyCyclePeriod); Real getMaxBoost(); void setMaxBoost(Real maxBoost); UInt getIterationNum(); void setIterationNum(UInt iterationNum); UInt getIterationLearnNum(); void setIterationLearnNum(UInt iterationLearnNum); UInt getSpVerbosity(); void setSpVerbosity(UInt spVerbosity); UInt getUpdatePeriod(); void setUpdatePeriod(UInt updatePeriod); Real getSynPermTrimThreshold(); void setSynPermTrimThreshold(Real synPermTrimThreshold); Real getSynPermActiveInc(); void setSynPermActiveInc(Real synPermActiveInc); Real getSynPermInactiveDec(); void setSynPermInactiveDec(Real synPermInactiveDec); Real getSynPermBelowStimulusInc(); void setSynPermBelowStimulusInc(Real synPermBelowStimulusInc); Real getSynPermConnected(); void setSynPermConnected(Real setSynPermConnected); Real getMinPctOverlapDutyCycles(); void setMinPctOverlapDutyCycles(Real minPctOverlapDutyCycles); Real getMinPctActiveDutyCycles(); void setMinPctActiveDutyCycles(Real minPctActiveDutyCycles); void getBoostFactors(Real boostFactors[]); void setBoostFactors(Real boostFactors[]); void getOverlapDutyCycles(Real overlapDutyCycles[]); void setOverlapDutyCycles(Real overlapDutyCycles[]); void getActiveDutyCycles(Real activeDutyCycles[]); void setActiveDutyCycles(Real activeDutyCycles[]); void getMinOverlapDutyCycles(Real minOverlapDutyCycles[]); void setMinOverlapDutyCycles(Real minOverlapDutyCycles[]); void getMinActiveDutyCycles(Real minActiveDutyCycles[]); void setMinActiveDutyCycles(Real minActiveDutyCycles[]); void getPotential(UInt column, UInt potential[]); void setPotential(UInt column, UInt potential[]); void getPermanence(UInt column, Real permanence[]); void setPermanence(UInt column, Real permanence[]); void getConnectedSynapses(UInt column, UInt connectedSynapses[]); void getConnectedCounts(UInt connectedCounts[]); // Implementation methods. all methods below this line are // NOT part of the public API void stripNeverLearned_(UInt activeArray[]); void toDense_(vector<UInt>& sparse, UInt dense[], UInt n); void boostOverlaps_(vector<UInt>& overlaps, vector<Real>& boostedOverlaps); void range_(Int start, Int end, UInt ubound, bool wrapAround, vector<UInt>& rangeVector); vector<UInt> mapPotential1D_(UInt column, bool wrapAround); Real initPermConnected_(); Real initPermNonConnected_(); vector<Real> initPermanence_(vector<UInt>& potential, Real connectedPct); void clip_(vector<Real>& perm, bool trim); void updatePermanencesForColumn_(vector<Real>& perm, UInt column, bool raisePerm=true); UInt countConnected_(vector<Real>& perm); UInt raisePermanencesToThreshold_(vector<Real>& perm, vector<UInt>& potential); void calculateOverlap_(UInt inputVector[], vector<UInt>& overlap); void calculateOverlapPct_(vector<UInt>& overlaps, vector<Real>& overlapPct); bool isWinner_(Real score, vector<pair<UInt, Real> >& winners, UInt numWinners); void addToWinners_(UInt index, Real score, vector<pair<UInt, Real> >& winners); void inhibitColumns_(vector<Real>& overlaps, vector<UInt>& activeColumns); void inhibitColumnsGlobal_(vector<Real>& overlaps, Real density, vector<UInt>& activeColumns); void inhibitColumnsLocal_(vector<Real>& overlaps, Real density, vector<UInt>& activeColumns); void getNeighbors1D_(UInt column, vector<UInt>& dimensions, UInt radius, bool wrapAround, vector<UInt>& neighbors); void getNeighbors2D_(UInt column, vector<UInt>& dimensions, UInt radius, bool wrapAround, vector<UInt>& neighbors); void cartesianProduct_(vector<vector<UInt> >& vecs, vector<vector<UInt> >& product); void getNeighborsND_(UInt column, vector<UInt>& dimensions, UInt radius, bool wrapAround, vector<UInt>& neighbors); void adaptSynapses_(UInt inputVector[], vector<UInt>& activeColumns); void bumpUpWeakColumns_(); void updateInhibitionRadius_(); Real avgColumnsPerInput_(); Real avgConnectedSpanForColumn1D_(UInt column); Real avgConnectedSpanForColumn2D_(UInt column); Real avgConnectedSpanForColumnND_(UInt column); void updateMinDutyCycles_(); void updateMinDutyCyclesGlobal_(); void updateMinDutyCyclesLocal_(); static void updateDutyCyclesHelper_(vector<Real>& dutyCycles, vector<UInt>& newValues, UInt period); void updateDutyCycles_(vector<UInt>& overlaps, UInt activeArray[]); void updateBoostFactors_(); void updateBookeepingVars_(bool learn); bool isUpdateRound_(); virtual void initialize(vector<UInt> inputDimensions, vector<UInt> columnDimensions, UInt potentialRadius=16, Real potentialPct=0.5, bool globalInhibition=true, Real localAreaDensity=-1.0, UInt numActiveColumnsPerInhArea=10, UInt stimulusThreshold=0, Real synPermInactiveDec=0.01, Real synPermActiveInc=0.1, Real synPermConnected=0.1, Real minPctOverlapDutyCycles=0.001, Real minPctActiveDutyCycles=0.001, UInt dutyCyclePeriod=1000, Real maxBoost=10.0, Int seed=1, UInt spVerbosity=0); void seed_(UInt64 seed); protected: UInt numInputs_; UInt numColumns_; vector<UInt> columnDimensions_; vector<UInt> inputDimensions_; UInt potentialRadius_; Real potentialPct_; Real initConnectedPct_; bool globalInhibition_; Int numActiveColumnsPerInhArea_; Real localAreaDensity_; UInt stimulusThreshold_; UInt inhibitionRadius_; UInt dutyCyclePeriod_; Real maxBoost_; UInt iterationNum_; UInt iterationLearnNum_; UInt spVerbosity_; UInt updatePeriod_; Real synPermMin_; Real synPermMax_; Real synPermTrimThreshold_; Real synPermInactiveDec_; Real synPermActiveInc_; Real synPermBelowStimulusInc_; Real synPermConnected_; vector<Real> boostFactors_; vector<Real> overlapDutyCycles_; vector<Real> activeDutyCycles_; vector<Real> minOverlapDutyCycles_; vector<Real> minActiveDutyCycles_; Real minPctOverlapDutyCycles_; Real minPctActiveDutyCycles_; SparseMatrix<UInt,Real,Int,Real64> permanences_; SparseBinaryMatrix<UInt,UInt> potentialPools_; SparseBinaryMatrix<UInt, UInt> connectedSynapses_; vector<UInt> connectedCounts_; vector<UInt> overlaps_; vector<Real> overlapsPct_; vector<Real> boostedOverlaps_; vector<UInt> activeColumns_; private: UInt version_; Random rng_; }; } // end namespace spatial_pooler } // end namespace algorithms } // end namespace nta #endif // NTA_spatial_pooler_HPP <commit_msg>added more tests whether randomized learn parameter<commit_after>/*---------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have purchased from * Numenta, Inc. a separate commercial license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * ---------------------------------------------------------------------- */ /** @file * Definitions for the Spatial Pooler */ #ifndef NTA_spatial_pooler_HPP #define NTA_spatial_pooler_HPP #include <cstring> #include <iostream> #include <nta/math/SparseBinaryMatrix.hpp> #include <nta/math/SparseMatrix.hpp> #include <nta/types/types.hpp> #include <string> #include <vector> using namespace std; namespace nta { namespace algorithms { namespace spatial_pooler { ///////////////////////////////////////////////////////////////////////// /// CLA spatial pooler implementation in C++. /// /// @b Responsibility /// The Spatial Pooler is responsible for creating a sparse distributed /// representation of the input. It computes the set of active columns. /// It maintains the state of the proximal dendrites between the columns /// and the inputs bits and keeps track of the activity and overlap /// duty cycles /// /// @b Description /// Todo. /// ///////////////////////////////////////////////////////////////////////// class SpatialPooler { public: SpatialPooler(); ~SpatialPooler() {} virtual UInt version() const { return version_; }; virtual void compute(UInt inputVector[], bool learn, UInt activeVector[]); virtual void save(ostream& outStream); virtual void load(istream& inStream); virtual UInt persistentSize(); UInt getNumColumns(); UInt getNumInputs(); UInt getPotentialRadius(); void setPotentialRadius(UInt potentialRadius); Real getPotentialPct(); void setPotentialPct(Real potentialPct); bool getGlobalInhibition(); void setGlobalInhibition(bool globalInhibition); Int getNumActiveColumnsPerInhArea(); void setNumActiveColumnsPerInhArea(UInt numActiveColumnsPerInhArea); Real getLocalAreaDensity(); void setLocalAreaDensity(Real localAreaDensity); UInt getStimulusThreshold(); void setStimulusThreshold(UInt stimulusThreshold); UInt getInhibitionRadius(); void setInhibitionRadius(UInt inhibitionRadius); UInt getDutyCyclePeriod(); void setDutyCyclePeriod(UInt dutyCyclePeriod); Real getMaxBoost(); void setMaxBoost(Real maxBoost); UInt getIterationNum(); void setIterationNum(UInt iterationNum); UInt getIterationLearnNum(); void setIterationLearnNum(UInt iterationLearnNum); UInt getSpVerbosity(); void setSpVerbosity(UInt spVerbosity); UInt getUpdatePeriod(); void setUpdatePeriod(UInt updatePeriod); Real getSynPermTrimThreshold(); void setSynPermTrimThreshold(Real synPermTrimThreshold); Real getSynPermActiveInc(); void setSynPermActiveInc(Real synPermActiveInc); Real getSynPermInactiveDec(); void setSynPermInactiveDec(Real synPermInactiveDec); Real getSynPermBelowStimulusInc(); void setSynPermBelowStimulusInc(Real synPermBelowStimulusInc); Real getSynPermConnected(); void setSynPermConnected(Real setSynPermConnected); Real getMinPctOverlapDutyCycles(); void setMinPctOverlapDutyCycles(Real minPctOverlapDutyCycles); Real getMinPctActiveDutyCycles(); void setMinPctActiveDutyCycles(Real minPctActiveDutyCycles); void getBoostFactors(Real boostFactors[]); void setBoostFactors(Real boostFactors[]); void getOverlapDutyCycles(Real overlapDutyCycles[]); void setOverlapDutyCycles(Real overlapDutyCycles[]); void getActiveDutyCycles(Real activeDutyCycles[]); void setActiveDutyCycles(Real activeDutyCycles[]); void getMinOverlapDutyCycles(Real minOverlapDutyCycles[]); void setMinOverlapDutyCycles(Real minOverlapDutyCycles[]); void getMinActiveDutyCycles(Real minActiveDutyCycles[]); void setMinActiveDutyCycles(Real minActiveDutyCycles[]); void getPotential(UInt column, UInt potential[]); void setPotential(UInt column, UInt potential[]); void getPermanence(UInt column, Real permanence[]); void setPermanence(UInt column, Real permanence[]); void getConnectedSynapses(UInt column, UInt connectedSynapses[]); void getConnectedCounts(UInt connectedCounts[]); // Implementation methods. all methods below this line are // NOT part of the public API void stripNeverLearned_(UInt activeArray[]); void toDense_(vector<UInt>& sparse, UInt dense[], UInt n); void boostOverlaps_(vector<UInt>& overlaps, vector<Real>& boostedOverlaps); void range_(Int start, Int end, UInt ubound, bool wrapAround, vector<UInt>& rangeVector); vector<UInt> mapPotential1D_(UInt column, bool wrapAround); Real initPermConnected_(); Real initPermNonConnected_(); vector<Real> initPermanence_(vector<UInt>& potential, Real connectedPct); void clip_(vector<Real>& perm, bool trim); void updatePermanencesForColumn_(vector<Real>& perm, UInt column, bool raisePerm=true); UInt countConnected_(vector<Real>& perm); UInt raisePermanencesToThreshold_(vector<Real>& perm, vector<UInt>& potential); void calculateOverlap_(UInt inputVector[], vector<UInt>& overlap); void calculateOverlapPct_(vector<UInt>& overlaps, vector<Real>& overlapPct); bool isWinner_(Real score, vector<pair<UInt, Real> >& winners, UInt numWinners); void addToWinners_(UInt index, Real score, vector<pair<UInt, Real> >& winners); void inhibitColumns_(vector<Real>& overlaps, vector<UInt>& activeColumns); void inhibitColumnsGlobal_(vector<Real>& overlaps, Real density, vector<UInt>& activeColumns); void inhibitColumnsLocal_(vector<Real>& overlaps, Real density, vector<UInt>& activeColumns); void getNeighbors1D_(UInt column, vector<UInt>& dimensions, UInt radius, bool wrapAround, vector<UInt>& neighbors); void getNeighbors2D_(UInt column, vector<UInt>& dimensions, UInt radius, bool wrapAround, vector<UInt>& neighbors); void cartesianProduct_(vector<vector<UInt> >& vecs, vector<vector<UInt> >& product); void getNeighborsND_(UInt column, vector<UInt>& dimensions, UInt radius, bool wrapAround, vector<UInt>& neighbors); void adaptSynapses_(UInt inputVector[], vector<UInt>& activeColumns); void bumpUpWeakColumns_(); void updateInhibitionRadius_(); Real avgColumnsPerInput_(); Real avgConnectedSpanForColumn1D_(UInt column); Real avgConnectedSpanForColumn2D_(UInt column); Real avgConnectedSpanForColumnND_(UInt column); void updateMinDutyCycles_(); void updateMinDutyCyclesGlobal_(); void updateMinDutyCyclesLocal_(); static void updateDutyCyclesHelper_(vector<Real>& dutyCycles, vector<UInt>& newValues, UInt period); void updateDutyCycles_(vector<UInt>& overlaps, UInt activeArray[]); void updateBoostFactors_(); void updateBookeepingVars_(bool learn); bool isUpdateRound_(); virtual void initialize(vector<UInt> inputDimensions, vector<UInt> columnDimensions, UInt potentialRadius=16, Real potentialPct=0.5, bool globalInhibition=true, Real localAreaDensity=-1.0, UInt numActiveColumnsPerInhArea=10, UInt stimulusThreshold=0, Real synPermInactiveDec=0.01, Real synPermActiveInc=0.1, Real synPermConnected=0.1, Real minPctOverlapDutyCycles=0.001, Real minPctActiveDutyCycles=0.001, UInt dutyCyclePeriod=1000, Real maxBoost=10.0, Int seed=1, UInt spVerbosity=0); void seed_(UInt64 seed); protected: UInt numInputs_; UInt numColumns_; vector<UInt> columnDimensions_; vector<UInt> inputDimensions_; UInt potentialRadius_; Real potentialPct_; Real initConnectedPct_; bool globalInhibition_; Int numActiveColumnsPerInhArea_; Real localAreaDensity_; UInt stimulusThreshold_; UInt inhibitionRadius_; UInt dutyCyclePeriod_; Real maxBoost_; UInt iterationNum_; UInt iterationLearnNum_; UInt spVerbosity_; UInt updatePeriod_; Real synPermMin_; Real synPermMax_; Real synPermTrimThreshold_; Real synPermInactiveDec_; Real synPermActiveInc_; Real synPermBelowStimulusInc_; Real synPermConnected_; vector<Real> boostFactors_; vector<Real> overlapDutyCycles_; vector<Real> activeDutyCycles_; vector<Real> minOverlapDutyCycles_; vector<Real> minActiveDutyCycles_; Real minPctOverlapDutyCycles_; Real minPctActiveDutyCycles_; SparseMatrix<UInt,Real,Int,Real64> permanences_; SparseBinaryMatrix<UInt,UInt> potentialPools_; SparseBinaryMatrix<UInt, UInt> connectedSynapses_; vector<UInt> connectedCounts_; vector<UInt> overlaps_; vector<Real> overlapsPct_; vector<Real> boostedOverlaps_; vector<UInt> activeColumns_; private: UInt version_; Random rng_; }; } // end namespace spatial_pooler } // end namespace algorithms } // end namespace nta #endif // NTA_spatial_pooler_HPP <|endoftext|>
<commit_before>TCanvas *pAll=0; AliRunLoader *gAL=0; AliLoader *gHL=0; AliESD *gEsd=0; TTree *gEsdTr=0; AliHMPID *gH=0; Int_t gEvt=0; Int_t gMaxEvt=0; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void Hdisp() {//display events from files if any in current directory or simulated events pAll=new TCanvas("all","",1000,900); pAll->Divide(3,3,0,0);pAll->ToggleEditor(); pAll->Connect("ProcessedEvent(Int_t,Int_t,Int_t,TObject*)",0,"","DoZoom(Int_t,Int_t,Int_t,TObject*)"); if(gSystem->IsFileInIncludePath("galice.root")){// tries to open session if(gAlice) delete gAlice; //in case we execute this in aliroot delete default AliRun object gAL=AliRunLoader::Open(); //try to open galice.root from current dir gAL->LoadgAlice(); //take new AliRun object from galice.root gHL=gAL->GetDetectorLoader("HMPID"); gH=(AliHMPID*)gAL->GetAliRun()->GetDetector("HMPID"); //get HMPID object from galice.root gMaxEvt=gAL->GetNumberOfEvents()-1; gHL->LoadHits(); gHL->LoadDigits(); gHL->LoadRecPoints(); TFile *pEsdFl=TFile::Open("AliESDs.root"); gEsdTr=(TTree*) pEsdFl->Get("esdTree"); gEsdTr->SetBranchAddress("ESD", &gEsd); pAll->cd(7); TButton *pBtn=new TButton("Next","ReadEvt()",0,0,0.2,0.1); pBtn->Draw(); ReadEvt(); }else{ pAll->cd(7); TButton *pBtn=new TButton("Next","SimEvt()",0,0,0.2,0.1); pBtn->Draw(); SimEvt(); } } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void ReadEvt() {// Read curent event and display it assumes that session is alredy opened TClonesArray hits("AliHMPIDHit"); if(gEvt>gMaxEvt) gEvt=0; if(gEvt<0) gEvt=gMaxEvt; gEsdTr->GetEntry(gEvt); gAL->GetEvent(gEvt); ReadHits(&hits); gHL->TreeD()->GetEntry(0); gHL->TreeR()->GetEntry(0); pAll->cd(3); gPad->Clear(); TLatex txt;txt.DrawLatex(0.2,0.2,Form("Event %i (total %i)",gEvt,gMaxEvt)); DrawEvt(&hits,gH->DigLst(),gH->CluLst(),gEsd); gEvt++; } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void SimEvt() { TClonesArray hits("AliHMPIDHit"); TClonesArray sdig("AliHMPIDDigit"); TObjArray digs(7); for(Int_t i=0;i<7;i++) digs.AddAt(new TClonesArray("AliHMPIDDigit"),i); TObjArray clus(7); for(Int_t i=0;i<7;i++) clus.AddAt(new TClonesArray("AliHMPIDCluster"),i); AliESD esd; SimEsd(&esd); SimHits(&esd,&hits); AliHMPIDv1::Hit2Sdi(&hits,&sdig); AliHMPIDDigitizer::Sdi2Dig(&sdig,&digs); AliHMPIDReconstructor::Dig2Clu(&digs,&clus); AliHMPIDTracker::Recon(&esd,&clus); pAll->cd(3); gPad->Clear(); TLatex txt;txt.DrawLatex(0.2,0.2,Form("Simulated event %i",gEvt)); DrawEvt(&hits,&digs,&clus,&esd); gEvt++; }//SimEvt() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void SimEsd(AliESD *pEsd) { TParticle part; TLorentzVector mom; for(Int_t iTrk=0;iTrk<25;iTrk++){//stack loop part.SetPdgCode(kProton); part.SetProductionVertex(0,0,0,0); Double_t eta= -0.4+gRandom->Rndm()*0.8; //rapidity is random [-0.4,+0.4] Double_t phi= gRandom->Rndm()*1.4; //phi is random [ 0 , 80 ] degrees mom.SetPtEtaPhiM(2,eta,phi,part.GetMass()); part.SetMomentum(mom); AliESDtrack trk(&part); pEsd->AddTrack(&trk); }//stack loop }//EsdFromStack() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void SimHits(AliESD *pEsd, TClonesArray *pHits) { AliHMPIDRecon rec; const Int_t kCerenkov=50000050,kFeedback=50000051; Int_t hc=0; TVector2 pos; for(Int_t iTrk=0;iTrk<pEsd->GetNumberOfTracks();iTrk++){//tracks loop AliESDtrack *pTrk=pEsd->GetTrack(iTrk); Float_t xRa,yRa; Int_t ch=AliHMPIDTracker::IntTrkCha(pTrk,xRa,yRa); if(ch<0) continue; //this track does not hit HMPID Float_t ckov=0.63; Float_t th,ph,xPc,yPc,; pTrk->GetHMPIDtrk(xPc,yPc,th,ph); rec.SetTrack(xRa,yRa,th,ph); if(!AliHMPIDDigit::IsInDead(xPc,yPc)) new((*pHits)[hc++]) AliHMPIDHit(ch,200e-9,kProton ,iTrk,xPc,yPc); //mip hit for(int i=0;i<4;i++) new((*pHits)[hc++]) AliHMPIDHit(ch,7.5e-9,kFeedback,iTrk,gRandom->Rndm()*130,gRandom->Rndm()*126); //bkg hits 4 per track for(int i=0;i<16;i++){ rec.TracePhot(ckov,gRandom->Rndm()*TMath::TwoPi(),pos); new((*pHits)[hc++]) AliHMPIDHit(ch,7.5e-9,kCerenkov,iTrk,pos.X(),pos.Y()); } //photon hits }//tracks loop }//SimHits() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void ReadHits(TClonesArray *pHitLst) { pHitLst->Delete(); Int_t cnt=0; for(Int_t iEnt=0;iEnt<gHL->TreeH()->GetEntries();iEnt++){ //TreeH loop gHL->TreeH()->GetEntry(iEnt); //get current entry (prim) for(Int_t iHit=0;iHit<gH->Hits()->GetEntries();iHit++){ //hits loop AliHMPIDHit *pHit = (AliHMPIDHit*)gH->Hits()->At(iHit); //get current hit new((*pHitLst)[cnt++]) AliHMPIDHit(*pHit); }//hits loop for this entry }//tree entries loop }//ReadHits() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void DrawCh(Int_t iCh) { gPad->Range(-10,-10,AliHMPIDDigit::SizeAllX()+5,AliHMPIDDigit::SizeAllY()+5); TLatex txt; txt.SetTextSize(0.1); txt.DrawLatex(-5,-5,Form("%i",iCh)); for(Int_t iPc=AliHMPIDDigit::kMinPc;iPc<=AliHMPIDDigit::kMaxPc;iPc++){ TBox *pBox=new TBox(AliHMPIDDigit::fMinPcX[iPc],AliHMPIDDigit::fMinPcY[iPc], AliHMPIDDigit::fMaxPcX[iPc],AliHMPIDDigit::fMaxPcY[iPc]); pBox->SetFillStyle(0); pBox->Draw(); }//PC loop }//DrawCh() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void DrawEvt(TClonesArray *pHitLst,TObjArray *pDigLst,TObjArray *pCluLst,AliESD *pEsd) {//draws all the objects of current event in given canvas AliHMPIDRecon rec; TPolyMarker *pTxC[7]; TPolyMarker *pRin[7]; //intesections and rings for(Int_t ch=0;ch<7;ch++){ pTxC[ch]=new TPolyMarker; pTxC[ch]->SetMarkerStyle(2); pTxC[ch]->SetMarkerColor(kRed); pTxC[ch]->SetMarkerSize(3); pRin[ch]=new TPolyMarker; pRin[ch]->SetMarkerStyle(6); pRin[ch]->SetMarkerColor(kMagenta); } for(Int_t iTrk=0;iTrk<pEsd->GetNumberOfTracks();iTrk++){//tracks loop to collect cerenkov rings and intersection points AliESDtrack *pTrk=pEsd->GetTrack(iTrk); Int_t ch=pTrk->GetHMPIDcluIdx(); if(ch<0) continue; //this track does not hit HMPID ch/=1000000; Float_t th,ph,xPc,yPc; pTrk->GetHMPIDtrk(xPc,yPc,th,ph); //get info on current track pTxC[ch]->SetNextPoint(xPc,yPc); //add new intersection point Float_t ckov=pTrk->GetHMPIDsignal(); Float_t err=TMath::Sqrt(pTrk->GetHMPIDchi2()); if(ckov>0){ rec.SetTrack(xPc,yPc,th,ph); TVector2 pos; for(int j=0;j<100;j++){rec.TracePhot(ckov,j*0.0628,pos); pRin[ch]->SetNextPoint(pos.X(),pos.Y());} } }//tracks loop for(Int_t iCh=0;iCh<7;iCh++){//chambers loop switch(iCh){ case 6: pAll->cd(1); break; case 5: pAll->cd(2); break; case 4: pAll->cd(4); break; case 3: pAll->cd(5); break; case 2: pAll->cd(6); break; case 1: pAll->cd(8); break; case 0: pAll->cd(9); break; } gPad->SetEditable(kTRUE); gPad->Clear(); DrawCh(iCh); for(Int_t iHit=0;iHit<pHitLst->GetEntries();iHit++){ AliHMPIDHit *pHit=(AliHMPIDHit*)pHitLst->At(iHit); if(pHit->Ch()==iCh) pHit->Draw(); //draw hits } ((TClonesArray*)pDigLst->At(iCh))->Draw(); //draw digits ((TClonesArray*)pCluLst->At(iCh))->Draw(); //draw clusters pTxC[iCh]->Draw(); //draw intersections pRin[iCh]->Draw(); //draw rings gPad->SetEditable(kFALSE); }//chambers loop }//DrawEvt() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void DoZoom(Int_t evt, Int_t px, Int_t py, TObject *obj) { if(evt!=5 && evt!=6) return; //5- zoom in 6-zoom out const Int_t minZoom=64; const Int_t maxZoom=2; static Int_t zoom=minZoom; //zoom level if(evt==5&&zoom==maxZoom) return; if(evt==6&&zoom==minZoom) return; if(!obj->IsA()->InheritsFrom("TPad")) return; //current object is not pad TPad *pPad=(TPad*)obj; if(pPad->GetNumber()==3 || pPad->GetNumber()==7) return; //current pad is wrong // Printf("evt=%i (%i,%i) %s",evt,px,py,obj->GetName()); Float_t x=pPad->AbsPixeltoX(px); Float_t y=pPad->AbsPixeltoY(py); if(evt==5){ zoom=zoom/2; pPad->Range(x-zoom*2,y-zoom*2,x+zoom*2,y+zoom*2);} //zoom in else { zoom=zoom*2; pPad->Range(x-zoom*2,y-zoom*2,x+zoom*2,y+zoom*2);} //zoom out if(zoom==minZoom) pPad->Range(-10,-10,AliHMPIDDigit::SizeAllX()+5,AliHMPIDDigit::SizeAllY()+5); ((TCanvas *)gTQSender)->SetTitle(Form("zoom x%i",minZoom/zoom)); pPad->Modified(); pPad->Update(); } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ <commit_msg>add legend to display + printing facilities<commit_after>TCanvas *pAll=0; AliRunLoader *gAL=0; AliLoader *gHL=0; AliESD *gEsd=0; TTree *gEsdTr=0; AliHMPID *gH=0; Int_t gEvt=0; Int_t gMaxEvt=0; //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void Hdisp() {//display events from files if any in current directory or simulated events pAll=new TCanvas("all","",1000,900); pAll->Divide(3,3,0,0);pAll->ToggleEditor(); pAll->Connect("ProcessedEvent(Int_t,Int_t,Int_t,TObject*)",0,"","DoZoom(Int_t,Int_t,Int_t,TObject*)"); if(gSystem->IsFileInIncludePath("galice.root")){// tries to open session if(gAlice) delete gAlice; //in case we execute this in aliroot delete default AliRun object gAL=AliRunLoader::Open(); //try to open galice.root from current dir gAL->LoadgAlice(); //take new AliRun object from galice.root gHL=gAL->GetDetectorLoader("HMPID"); gH=(AliHMPID*)gAL->GetAliRun()->GetDetector("HMPID"); //get HMPID object from galice.root gMaxEvt=gAL->GetNumberOfEvents()-1; gHL->LoadHits(); gHL->LoadSDigits(); gHL->LoadDigits(); gHL->LoadRecPoints(); TFile *pEsdFl=TFile::Open("AliESDs.root"); gEsdTr=(TTree*) pEsdFl->Get("esdTree"); gEsdTr->SetBranchAddress("ESD", &gEsd); pAll->cd(7); TButton *pBtn=new TButton("Next","ReadEvt()",0,0,0.2,0.1); pBtn->Draw(); TButton *pHitBtn=new TButton("Print hits","PrintHits()",0,0.2,0.3,0.3); pHitBtn->Draw(); TButton *pSdiBtn=new TButton("Print sdis","PrintSdis()",0,0.4,0.3,0.5); pSdiBtn->Draw(); TButton *pDigBtn=new TButton("Print digs","PrintDigs()",0,0.6,0.3,0.7); pDigBtn->Draw(); TButton *pCluBtn=new TButton("Print clus","PrintClus()",0,0.8,0.3,0.9); pCluBtn->Draw(); ReadEvt(); }else{ pAll->cd(7); TButton *pBtn=new TButton("Next","SimEvt()",0,0,0.2,0.1); pBtn->Draw(); SimEvt(); } } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void ReadEvt() {// Read curent event and display it assumes that session is alredy opened TClonesArray hits("AliHMPIDHit"); if(gEvt>gMaxEvt) gEvt=0; if(gEvt<0) gEvt=gMaxEvt; gEsdTr->GetEntry(gEvt); gAL->GetEvent(gEvt); ReadHits(&hits); gHL->TreeS()->GetEntry(0); gHL->TreeD()->GetEntry(0); gHL->TreeR()->GetEntry(0); DrawEvt(&hits,gH->DigLst(),gH->CluLst(),gEsd); gEvt++; } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void SimEvt() { TClonesArray hits("AliHMPIDHit"); TClonesArray sdig("AliHMPIDDigit"); TObjArray digs(7); for(Int_t i=0;i<7;i++) digs.AddAt(new TClonesArray("AliHMPIDDigit"),i); TObjArray clus(7); for(Int_t i=0;i<7;i++) clus.AddAt(new TClonesArray("AliHMPIDCluster"),i); AliESD esd; SimEsd(&esd); SimHits(&esd,&hits); AliHMPIDv1::Hit2Sdi(&hits,&sdig); AliHMPIDDigitizer::Sdi2Dig(&sdig,&digs); AliHMPIDReconstructor::Dig2Clu(&digs,&clus); AliHMPIDTracker::Recon(&esd,&clus); pAll->cd(3); gPad->Clear(); TLatex txt;txt.DrawLatex(0.2,0.2,Form("Simulated event %i",gEvt)); DrawEvt(&hits,&digs,&clus,&esd); gEvt++; }//SimEvt() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void SimEsd(AliESD *pEsd) { TParticle part; TLorentzVector mom; for(Int_t iTrk=0;iTrk<25;iTrk++){//stack loop part.SetPdgCode(kProton); part.SetProductionVertex(0,0,0,0); Double_t eta= -0.4+gRandom->Rndm()*0.8; //rapidity is random [-0.4,+0.4] Double_t phi= gRandom->Rndm()*1.4; //phi is random [ 0 , 80 ] degrees mom.SetPtEtaPhiM(2,eta,phi,part.GetMass()); part.SetMomentum(mom); AliESDtrack trk(&part); pEsd->AddTrack(&trk); }//stack loop }//EsdFromStack() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void SimHits(AliESD *pEsd, TClonesArray *pHits) { AliHMPIDRecon rec; const Int_t kCerenkov=50000050,kFeedback=50000051; Int_t hc=0; TVector2 pos; for(Int_t iTrk=0;iTrk<pEsd->GetNumberOfTracks();iTrk++){//tracks loop AliESDtrack *pTrk=pEsd->GetTrack(iTrk); Float_t xRa,yRa; Int_t ch=AliHMPIDTracker::IntTrkCha(pTrk,xRa,yRa); if(ch<0) continue; //this track does not hit HMPID Float_t ckov=0.63; Float_t th,ph,xPc,yPc,; pTrk->GetHMPIDtrk(xPc,yPc,th,ph); rec.SetTrack(xRa,yRa,th,ph); if(!AliHMPIDDigit::IsInDead(xPc,yPc)) new((*pHits)[hc++]) AliHMPIDHit(ch,200e-9,kProton ,iTrk,xPc,yPc); //mip hit for(int i=0;i<4;i++) new((*pHits)[hc++]) AliHMPIDHit(ch,7.5e-9,kFeedback,iTrk,gRandom->Rndm()*130,gRandom->Rndm()*126); //bkg hits 4 per track for(int i=0;i<16;i++){ rec.TracePhot(ckov,gRandom->Rndm()*TMath::TwoPi(),pos); new((*pHits)[hc++]) AliHMPIDHit(ch,7.5e-9,kCerenkov,iTrk,pos.X(),pos.Y()); } //photon hits }//tracks loop }//SimHits() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void ReadHits(TClonesArray *pHitLst) { pHitLst->Delete(); Int_t cnt=0; for(Int_t iEnt=0;iEnt<gHL->TreeH()->GetEntries();iEnt++){ //TreeH loop gHL->TreeH()->GetEntry(iEnt); //get current entry (prim) for(Int_t iHit=0;iHit<gH->Hits()->GetEntries();iHit++){ //hits loop AliHMPIDHit *pHit = (AliHMPIDHit*)gH->Hits()->At(iHit); //get current hit new((*pHitLst)[cnt++]) AliHMPIDHit(*pHit); }//hits loop for this entry }//tree entries loop }//ReadHits() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void DrawCh(Int_t iCh) { gPad->Range(-10,-10,AliHMPIDDigit::SizeAllX()+5,AliHMPIDDigit::SizeAllY()+5); TLatex txt; txt.SetTextSize(0.1); txt.DrawLatex(-5,-5,Form("%i",iCh)); for(Int_t iPc=AliHMPIDDigit::kMinPc;iPc<=AliHMPIDDigit::kMaxPc;iPc++){ TBox *pBox=new TBox(AliHMPIDDigit::fMinPcX[iPc],AliHMPIDDigit::fMinPcY[iPc], AliHMPIDDigit::fMaxPcX[iPc],AliHMPIDDigit::fMaxPcY[iPc]); pBox->SetFillStyle(0); pBox->Draw(); }//PC loop }//DrawCh() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void DrawEvt(TClonesArray *pHitLst,TObjArray *pDigLst,TObjArray *pCluLst,AliESD *pEsd) {//draws all the objects of current event in given canvas AliHMPIDRecon rec; TPolyMarker *pTxC[7], *pRin[7]; TMarker *pMip,*pCko,*pFee,*pDig,*pClu; pMip=new TMarker; pMip->SetMarkerColor(kRed); pMip->SetMarkerStyle(kOpenTriangleUp); pCko=new TMarker; pCko->SetMarkerColor(kRed); pCko->SetMarkerStyle(kOpenCircle); pFee=new TMarker; pFee->SetMarkerColor(kRed); pFee->SetMarkerStyle(kOpenDiamond); pDig=new TMarker; pDig->SetMarkerColor(kGreen);pDig->SetMarkerStyle(kOpenSquare); pClu=new TMarker; pClu->SetMarkerColor(kBlue); pClu->SetMarkerStyle(kStar); for(Int_t ch=0;ch<7;ch++){ pTxC[ch]=new TPolyMarker; pTxC[ch]->SetMarkerStyle(2); pTxC[ch]->SetMarkerColor(kRed); pTxC[ch]->SetMarkerSize(3); pRin[ch]=new TPolyMarker; pRin[ch]->SetMarkerStyle(6); pRin[ch]->SetMarkerColor(kMagenta); } for(Int_t iTrk=0;iTrk<pEsd->GetNumberOfTracks();iTrk++){//tracks loop to collect cerenkov rings and intersection points AliESDtrack *pTrk=pEsd->GetTrack(iTrk); Int_t ch=pTrk->GetHMPIDcluIdx(); if(ch<0) continue; //this track does not hit HMPID ch/=1000000; Float_t th,ph,xPc,yPc; pTrk->GetHMPIDtrk(xPc,yPc,th,ph); //get info on current track pTxC[ch]->SetNextPoint(xPc,yPc); //add new intersection point Float_t ckov=pTrk->GetHMPIDsignal(); Float_t err=TMath::Sqrt(pTrk->GetHMPIDchi2()); if(ckov>0){ rec.SetTrack(xPc,yPc,th,ph); TVector2 pos; for(int j=0;j<100;j++){rec.TracePhot(ckov,j*0.0628,pos); pRin[ch]->SetNextPoint(pos.X(),pos.Y());} } }//tracks loop Int_t totHit=pHitLst->GetEntriesFast(),totDig=0,totClu=0,totTxC=0; for(Int_t iCh=0;iCh<7;iCh++){//chambers loop totTxC+=pTxC[iCh]->GetN(); totDig+=((TClonesArray*)pDigLst->At(iCh))->GetEntriesFast(); totClu+=((TClonesArray*)pCluLst->At(iCh))->GetEntriesFast(); switch(iCh){ case 6: pAll->cd(1); break; case 5: pAll->cd(2); break; case 4: pAll->cd(4); break; case 3: pAll->cd(5); break; case 2: pAll->cd(6); break; case 1: pAll->cd(8); break; case 0: pAll->cd(9); break; } gPad->SetEditable(kTRUE); gPad->Clear(); DrawCh(iCh); for(Int_t iHit=0;iHit<pHitLst->GetEntriesFast();iHit++){ AliHMPIDHit *pHit=(AliHMPIDHit*)pHitLst->At(iHit); if(pHit->Ch()==iCh) pHit->Draw(); } ((TClonesArray*)pDigLst->At(iCh))->Draw(); //draw digits ((TClonesArray*)pCluLst->At(iCh))->Draw(); //draw clusters pTxC[iCh]->Draw(); //draw intersections pRin[iCh]->Draw(); //draw rings gPad->SetEditable(kFALSE); }//chambers loop pAll->cd(3); gPad->Clear(); TLegend *pLeg=new TLegend(0.2,0.2,0.8,0.8); pLeg->SetHeader(Form("Event %i Total %i",gEvt,gMaxEvt+1)); pLeg->AddEntry(pTxC[0],Form("TRKxPC %i" ,totTxC),"p"); pLeg->AddEntry(pMip ,Form("Mip hits %i" ,totHit),"p"); pLeg->AddEntry(pCko ,Form("Ckov hits %i" ,totHit),"p"); pLeg->AddEntry(pFee ,Form("Feed hits %i" ,totHit),"p"); pLeg->AddEntry(pDig ,Form("Digs %i" ,totDig),"p"); pLeg->AddEntry(pClu ,Form("Clus %i" ,totClu),"p"); pLeg->Draw(); }//DrawEvt() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void DoZoom(Int_t evt, Int_t px, Int_t py, TObject *obj) { if(evt!=5 && evt!=6) return; //5- zoom in 6-zoom out const Int_t minZoom=64; const Int_t maxZoom=2; static Int_t zoom=minZoom; //zoom level if(evt==5&&zoom==maxZoom) return; if(evt==6&&zoom==minZoom) return; // if(!obj->IsA()->InheritsFrom("TPad")) return; //current object is not pad TVirtualPad *pPad=gROOT->GetSelectedPad(); if(pPad->GetNumber()==3 || pPad->GetNumber()==7) return; //current pad is wrong // Printf("evt=%i (%i,%i) %s",evt,px,py,obj->GetName()); Float_t x=pPad->AbsPixeltoX(px); Float_t y=pPad->AbsPixeltoY(py); if(evt==5){ zoom=zoom/2; pPad->Range(x-zoom*2,y-zoom*2,x+zoom*2,y+zoom*2);} //zoom in else { zoom=zoom*2; pPad->Range(x-zoom*2,y-zoom*2,x+zoom*2,y+zoom*2);} //zoom out if(zoom==minZoom) pPad->Range(-10,-10,AliHMPIDDigit::SizeAllX()+5,AliHMPIDDigit::SizeAllY()+5); ((TCanvas *)gTQSender)->SetTitle(Form("zoom x%i",minZoom/zoom)); pPad->Modified(); pPad->Update(); } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void PrintHits() { //Prints a list of HMPID hits for a given event. Default is event number 0. Printf("List of HMPID hits for event %i",gEvt); Int_t iTotHits=0; for(Int_t iPrim=0;iPrim<gHL->TreeH()->GetEntries();iPrim++){//prims loop gHL->TreeH()->GetEntry(iPrim); gH->Hits()->Print(); iTotHits+=gH->Hits()->GetEntries(); } Printf("totally %i hits for event %i",iTotHits,gEvt); } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void PrintSdis() { //prints a list of HMPID sdigits for a given event Printf("List of HMPID sdigits for event %i",gEvt); gH->SdiLst()->Print(); Printf("totally %i sdigits for event %i",gH->SdiLst()->GetEntries(),gEvt); } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void PrintDigs() { //prints a list of HMPID digits Printf("List of HMPID digits for event %i",gEvt); gH->DigLst()->Print(); Int_t totDigs=0; for(Int_t i=0;i<7;i++) {totDigs+=gH->DigLst(i)->GetEntries();} Printf("totally %i digits for event %i",totDigs,gEvt); } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void PrintClus() {//prints a list of HMPID clusters for a given event Printf("List of HMPID clusters for event %i",gEvt); gH->CluLst()->Print(); Int_t iCluCnt=0; for(Int_t iCh=0;iCh<7;iCh++) iCluCnt+=gH->CluLst(iCh)->GetEntries(); Printf("totally %i clusters for event %i",iCluCnt,gEvt); } <|endoftext|>
<commit_before>#include "./JPetRecoImageTools.h" #include <vector> #include <utility> #include <cmath> #include <functional> #include <cassert> #include <memory> JPetRecoImageTools::JPetRecoImageTools() { } JPetRecoImageTools::~JPetRecoImageTools() { } double JPetRecoImageTools::nearestNeighbour(std::vector<std::vector<int>> & emissionMatrix, double a, double b, int center, int x, int y, bool sang) { if(sang) { y = (int) std::round(a*x + b) + center; if (y >= 0 && y < emissionMatrix[0].size()) return emissionMatrix[x+center][y]; else return 0; } else { x = (int) std::round(a*y + b) + center; if (x >= 0 && x < emissionMatrix.size()) return emissionMatrix[x][y+center]; else return 0; } } double JPetRecoImageTools::linear(std::vector<std::vector<int>> & emissionMatrix, double a, double b, int center, int x, int y, bool sang) { if(sang) { y = (int) std::round(a*x + b) + center; double weight = std::abs((a*x + b) - std::ceil(a*x + b)); if (y >= 0 && y < emissionMatrix[0].size()) return (1-weight) * emissionMatrix[x+center][y] + weight * emissionMatrix[x+center][y+1]; else return 0; } else { x = (int) std::round(a*y + b) + center; double weight = std::abs((a*y + b) - std::ceil(a*y + b)); if (x >= 0 && x + 1 < emissionMatrix.size()) return (1-weight) * emissionMatrix[x][y+center] + weight * emissionMatrix[x+1][y+center]; else return 0; } } /*! \brief Function returning vector of vectors with value of sinogram * \param emissionMatrix matrix, need to be NxN * \param views number of views on object, degree step is calculated as (ang2 - ang1) / views * \param scans number of scans on object, step is calculated as emissionMatrix[0].size() / scans * \param interpolationFunction function to interpolate values (Optional, default linear) * \param ang1 start angle for projection (Optional, default 0) * \param ang2 end angle for projection (Optional, default 180) * \param scaleResult if set to true, scale result to <min, max> (Optional, default false) * \param min minimum value in returned sinogram (Optional, default 0) * \param max maximum value in returned sinogram (Optional, default 255) */ std::vector<std::vector<double>> JPetRecoImageTools::sinogram(std::vector<std::vector<int>>& emissionMatrix, int views, int scans, std::function<double(std::vector<std::vector<int>> &, double, double, int, int, int, bool)> interpolationFunction, float ang1, float ang2, bool scaleResult, int min, int max) { assert(emissionMatrix.size() > 0); assert(emissionMatrix.size() == emissionMatrix[0].size()); assert(views > 0); assert(scans > 0); assert(min < max); assert(ang1 < ang2); //create vector of size views, initialize it with vector of size scans std::vector<std::vector<double>> proj(views, std::vector<double>(scans)); std::unique_ptr<double[]> sintab(new double[views]); std::unique_ptr<double[]> costab(new double[views]); float phi = 0.; float stepsize = (ang2 - ang1) / views; assert(stepsize > 0); //maybe != 0 ? int i = 0; for (phi = ang1; phi < ang2; phi = phi + stepsize) { sintab[i] = std::sin((double) phi * M_PI / 180 - M_PI/2); costab[i] = std::cos((double) phi * M_PI / 180 - M_PI/2); i++; } i=0; int scanNumber=0; const int inputMatrixSize = emissionMatrix.size(); const int center = inputMatrixSize / 2; //if no. scans is greater than the image width, then scale will be <1 double scale = inputMatrixSize*1.42/scans; const double sang = std::sqrt(2)/2; int N=0; for (phi=ang1;phi<ang2;phi=phi+stepsize){ double a = -costab[i]/sintab[i]; double aa = 1/a; for(scanNumber=0;scanNumber<scans;scanNumber++) { N = scanNumber - scans/2; proj[i][scanNumber] = JPetRecoImageTools::calculateValue(emissionMatrix, std::abs(sintab[i]) > sang, N, costab[i], sintab[i], scale, center, interpolationFunction, a, aa ); } i++; } i=0; if(scaleResult) { JPetRecoImageTools::scale(proj, min, max); } return proj; } double JPetRecoImageTools::calculateValue(std::vector<std::vector<int>>& emissionMatrix, bool sang, int N, double cos, double sin, double scale, int center, std::function<double(std::vector<std::vector<int>>&, double, double, int, int, int, bool)>& interpolationFunction, double a, double aa) { double b = 0.; if(sang) b = (N - cos - sin) / sin; else b = (N - cos - sin) / cos; b *= scale; double value = 0.; int x = 0; int y = 0; if(sang) { for (x = -center; x < center; x++){ value += interpolationFunction(emissionMatrix, a, b, center, x, y, sang); } value /= std::abs(sin); } else { for (y = -center; y < center; y++){ value += interpolationFunction(emissionMatrix, aa, b, center, x, y, sang); } value /= std::abs(cos); } return value; } void JPetRecoImageTools::scale(std::vector<std::vector<double>>& v, int min, int max) { double datamax = v[0][0]; double datamin = v[0][0]; for (unsigned int k = 0; k < v.size(); k++ ) { for (unsigned int j = 0; j < v[0].size(); j++ ) { if(v[k][j] < min) v[k][j] = min; if(v[k][j] > datamax) datamax = v[k][j]; if(v[k][j] < datamin) datamin = v[k][j]; } } if(datamax == 0.) // if max value is 0, no need to scale return; for (unsigned int k = 0; k < v.size(); k++ ) { for (unsigned int j = 0; j < v[0].size(); j++ ) { v[k][j] = (double) ((v[k][j]-datamin) * max/datamax); } } }<commit_msg>Remove warnings<commit_after>#include "./JPetRecoImageTools.h" #include <vector> #include <utility> #include <cmath> #include <functional> #include <cassert> #include <memory> JPetRecoImageTools::JPetRecoImageTools() { } JPetRecoImageTools::~JPetRecoImageTools() { } double JPetRecoImageTools::nearestNeighbour(std::vector<std::vector<int>> & emissionMatrix, double a, double b, int center, int x, int y, bool sang) { if(sang) { y = (int) std::round(a*x + b) + center; if (y >= 0 && y < (int) emissionMatrix[0].size()) return emissionMatrix[x+center][y]; else return 0; } else { x = (int) std::round(a*y + b) + center; if (x >= 0 && x < (int) emissionMatrix.size()) return emissionMatrix[x][y+center]; else return 0; } } double JPetRecoImageTools::linear(std::vector<std::vector<int>> & emissionMatrix, double a, double b, int center, int x, int y, bool sang) { if(sang) { y = (int) std::round(a*x + b) + center; double weight = std::abs((a*x + b) - std::ceil(a*x + b)); if (y >= 0 && y < (int) emissionMatrix[0].size()) return (1-weight) * emissionMatrix[x+center][y] + weight * emissionMatrix[x+center][y+1]; else return 0; } else { x = (int) std::round(a*y + b) + center; double weight = std::abs((a*y + b) - std::ceil(a*y + b)); if (x >= 0 && x + 1 < (int) emissionMatrix.size()) return (1-weight) * emissionMatrix[x][y+center] + weight * emissionMatrix[x+1][y+center]; else return 0; } } /*! \brief Function returning vector of vectors with value of sinogram * \param emissionMatrix matrix, need to be NxN * \param views number of views on object, degree step is calculated as (ang2 - ang1) / views * \param scans number of scans on object, step is calculated as emissionMatrix[0].size() / scans * \param interpolationFunction function to interpolate values (Optional, default linear) * \param ang1 start angle for projection (Optional, default 0) * \param ang2 end angle for projection (Optional, default 180) * \param scaleResult if set to true, scale result to <min, max> (Optional, default false) * \param min minimum value in returned sinogram (Optional, default 0) * \param max maximum value in returned sinogram (Optional, default 255) */ std::vector<std::vector<double>> JPetRecoImageTools::sinogram(std::vector<std::vector<int>>& emissionMatrix, int views, int scans, std::function<double(std::vector<std::vector<int>> &, double, double, int, int, int, bool)> interpolationFunction, float ang1, float ang2, bool scaleResult, int min, int max) { assert(emissionMatrix.size() > 0); assert(emissionMatrix.size() == emissionMatrix[0].size()); assert(views > 0); assert(scans > 0); assert(min < max); assert(ang1 < ang2); //create vector of size views, initialize it with vector of size scans std::vector<std::vector<double>> proj(views, std::vector<double>(scans)); std::unique_ptr<double[]> sintab(new double[views]); std::unique_ptr<double[]> costab(new double[views]); float phi = 0.; float stepsize = (ang2 - ang1) / views; assert(stepsize > 0); //maybe != 0 ? int i = 0; for (phi = ang1; phi < ang2; phi = phi + stepsize) { sintab[i] = std::sin((double) phi * M_PI / 180 - M_PI/2); costab[i] = std::cos((double) phi * M_PI / 180 - M_PI/2); i++; } i=0; int scanNumber=0; const int inputMatrixSize = emissionMatrix.size(); const int center = inputMatrixSize / 2; //if no. scans is greater than the image width, then scale will be <1 double scale = inputMatrixSize*1.42/scans; const double sang = std::sqrt(2)/2; int N=0; for (phi=ang1;phi<ang2;phi=phi+stepsize){ double a = -costab[i]/sintab[i]; double aa = 1/a; for(scanNumber=0;scanNumber<scans;scanNumber++) { N = scanNumber - scans/2; proj[i][scanNumber] = JPetRecoImageTools::calculateValue(emissionMatrix, std::abs(sintab[i]) > sang, N, costab[i], sintab[i], scale, center, interpolationFunction, a, aa ); } i++; } i=0; if(scaleResult) { JPetRecoImageTools::scale(proj, min, max); } return proj; } double JPetRecoImageTools::calculateValue(std::vector<std::vector<int>>& emissionMatrix, bool sang, int N, double cos, double sin, double scale, int center, std::function<double(std::vector<std::vector<int>>&, double, double, int, int, int, bool)>& interpolationFunction, double a, double aa) { double b = 0.; if(sang) b = (N - cos - sin) / sin; else b = (N - cos - sin) / cos; b *= scale; double value = 0.; int x = 0; int y = 0; if(sang) { for (x = -center; x < center; x++){ value += interpolationFunction(emissionMatrix, a, b, center, x, y, sang); } value /= std::abs(sin); } else { for (y = -center; y < center; y++){ value += interpolationFunction(emissionMatrix, aa, b, center, x, y, sang); } value /= std::abs(cos); } return value; } void JPetRecoImageTools::scale(std::vector<std::vector<double>>& v, int min, int max) { double datamax = v[0][0]; double datamin = v[0][0]; for (unsigned int k = 0; k < v.size(); k++ ) { for (unsigned int j = 0; j < v[0].size(); j++ ) { if(v[k][j] < min) v[k][j] = min; if(v[k][j] > datamax) datamax = v[k][j]; if(v[k][j] < datamin) datamin = v[k][j]; } } if(datamax == 0.) // if max value is 0, no need to scale return; for (unsigned int k = 0; k < v.size(); k++ ) { for (unsigned int j = 0; j < v[0].size(); j++ ) { v[k][j] = (double) ((v[k][j]-datamin) * max/datamax); } } }<|endoftext|>
<commit_before>#ifndef GQ_CHARACTERIZE_H #define GQ_CHARACTERIZE_H #include <eigen3/Eigen/Eigen> #include <cfloat> #include <iostream> class GQ_Characterize{ protected: // coefficients of the GQ double A_,B_,C_,D_,E_,F_,G_,H_,J_,K_; // the cannonical GQ type int type; // translation from the canoncial GQ to final GQ Vector3d translation; // tolerance used to determine // if matrix determinant should be considered zero const double gq_tol; const double equivalence_tol; enum GQ_TYPE {UNKNOWN = 0, ELLIPSOID, ONE_SHEET_HYPERBOLOID, TWO_SHEET_HYPERBOLOID, ELLIPTIC_CONE, ELLIPTIC_PARABOLOID, HYPERBOLIC_PARABOLOID, ELLIPTIC_CYL, HYPERBOLIC_CYL, PARABOLIC_CYL}; public: //Constructor GQ_Characterize(double A, double B, double C, double D, double E, double F, double G, double H, double J, double K); protected: void make_canonical(); // this method reduces a complex GQ to a geometrically equivalent // and more CAD-friendly form if appropriate void reduce_type(); GQ_TYPE find_type(int rt, int rf, int del, int s, int d); } #endif <commit_msg>Added missing semicolon to GQ_char definition<commit_after>#ifndef GQ_CHARACTERIZE_H #define GQ_CHARACTERIZE_H #include <eigen3/Eigen/Eigen> #include <cfloat> #include <iostream> class GQ_Characterize{ protected: // coefficients of the GQ double A_,B_,C_,D_,E_,F_,G_,H_,J_,K_; // the cannonical GQ type int type; // translation from the canoncial GQ to final GQ Vector3d translation; // tolerance used to determine // if matrix determinant should be considered zero const double gq_tol; const double equivalence_tol; enum GQ_TYPE {UNKNOWN = 0, ELLIPSOID, ONE_SHEET_HYPERBOLOID, TWO_SHEET_HYPERBOLOID, ELLIPTIC_CONE, ELLIPTIC_PARABOLOID, HYPERBOLIC_PARABOLOID, ELLIPTIC_CYL, HYPERBOLIC_CYL, PARABOLIC_CYL}; public: //Constructor GQ_Characterize(double A, double B, double C, double D, double E, double F, double G, double H, double J, double K); protected: void make_canonical(); // this method reduces a complex GQ to a geometrically equivalent // and more CAD-friendly form if appropriate void reduce_type(); GQ_TYPE find_type(int rt, int rf, int del, int s, int d); }; #endif <|endoftext|>
<commit_before>// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <cmath> #include "SoundResource.hpp" #include "AudioDevice.hpp" #include "SoundData.hpp" #include "Stream.hpp" #include "math/MathUtils.hpp" static void resampleLerp(const std::vector<float>& src, uint32_t srcFrames, std::vector<float>& dst, uint32_t dstFrames, uint32_t channels) { if (dstFrames > 0) // do resampling only if setination is not empty { if (srcFrames == 0) // source is empty { dst.resize(dstFrames * channels); std::fill(dst.begin(), dst.end(), 0.0f); } else { float srcIncrement = static_cast<float>(srcFrames - 1) / static_cast<float>(dstFrames - 1); float srcPosition = 0.0f; dst.resize(dstFrames * channels); for (uint32_t frame = 0; frame < dstFrames - 1; ++frame) { uint32_t srcCurrentFrame = static_cast<uint32_t>(srcPosition); float frac = srcPosition - srcCurrentFrame; srcPosition += srcIncrement; uint32_t srcNextFrame = srcCurrentFrame + 1; for (uint32_t channel = 0; channel < channels; ++channel) { uint32_t srcCurrentPosition = srcCurrentFrame * channels + channel; uint32_t srcNextPosition = srcNextFrame * channels + channel; dst[frame * channels + channel] = ouzel::lerp(src[srcCurrentPosition], src[srcNextPosition], frac); } } // fill the last frame of the destination with the last frame of the source for (uint32_t channel = 0; channel < channels; ++channel) { dst[(dstFrames - 1) * channels + channel] = src[(srcFrames - 1) * channels + channel]; } } } } namespace ouzel { namespace audio { SoundResource::SoundResource(AudioDevice* aAudioDevice): audioDevice(aAudioDevice) { } SoundResource::~SoundResource() { } bool SoundResource::init(const std::shared_ptr<SoundData>& newSoundData, bool newRelativePosition) { soundData = newSoundData; relativePosition = newRelativePosition; if (soundData) { stream = soundData->createStream(); } return true; } void SoundResource::setPosition(const Vector3& newPosition) { position = newPosition; } void SoundResource::setPitch(float newPitch) { pitch = newPitch; } void SoundResource::setGain(float newGain) { gain = newGain; } void SoundResource::setRolloffFactor(float newRolloffFactor) { rolloffFactor = newRolloffFactor; } void SoundResource::setMinDistance(float newMinDistance) { minDistance = newMinDistance; } void SoundResource::setMaxDistance(float newMaxDistance) { maxDistance = newMaxDistance; } bool SoundResource::play(bool repeatSound) { playing = true; repeat = repeatSound; return true; } bool SoundResource::pause() { playing = false; return true; } bool SoundResource::stop() { playing = false; reset = true; return true; } bool SoundResource::getData(uint32_t frames, uint16_t channels, uint32_t sampleRate, std::vector<float>& result) { if (!playing) { result.clear(); } else if (soundData && soundData->getChannels() > 0 && stream) { float finalPitch = pitch * soundData->getSampleRate() / sampleRate; uint32_t neededFrames = static_cast<uint32_t>(frames * finalPitch); uint32_t resetCount; if (!soundData->getData(stream.get(), neededFrames, repeat, resetCount, data)) { return false; } if (!repeat && resetCount > 0) playing = false; if (finalPitch != 1.0f) { uint32_t srcFrames = static_cast<uint32_t>(data.size()) / soundData->getChannels(); uint32_t dstFrames = static_cast<uint32_t>(frames * (static_cast<float>(srcFrames) / neededFrames)); //Log() << "sample rate: " << soundData->getSampleRate() << ", frames: " << frames << ", needed frames: " << neededFrames << ", got frames: " << srcFrames << ", dest frames: " << dstFrames << ", final pitch: " << finalPitch; resampleLerp(data, srcFrames, resampledData, dstFrames, soundData->getChannels()); } else { resampledData = data; } if (channels != soundData->getChannels()) { uint32_t srcFrames = static_cast<uint32_t>(resampledData.size()) / soundData->getChannels(); result.resize(srcFrames * channels); // front left channel if (channels >= 1) { uint32_t destination = 0; if (soundData->getChannels() >= 1) { uint32_t source = 0; for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination] = resampledData[source]; destination += channels; source += soundData->getChannels(); } } else { // fill the front left channel with zeros for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination] = 0.0f; destination += channels; } } } // front right channel if (channels >= 2) { uint32_t destination = 0; // sound data has front right channel if (soundData->getChannels() >= 2) { uint32_t source = 0; for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 1] = resampledData[source + 1]; destination += channels; source += soundData->getChannels(); } } else { // copy the front left channel in to the front right one for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 1] = result[destination]; destination += channels; } } } // center channel if (channels >= 3) { uint32_t destination = 0; if (soundData->getChannels() >= 3) { uint32_t source = 0; for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 2] = resampledData[source + 2]; destination += channels; source += soundData->getChannels(); } } else if (channels >= 2) { // calculate the average of the front left and the front right channel for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 2] = (result[destination] + result[destination + 1]) / 2.0f; destination += channels; } } else { // copy the front left channel in to the center one for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 2] = result[destination]; destination += channels; } } } // LFE channel if (channels >= 4) { uint32_t destination = 0; if (soundData->getChannels() >= 4) { uint32_t source = 0; for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 3] = resampledData[source + 3]; destination += channels; source += soundData->getChannels(); } } else { // fill the LFE channel with zeros for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 3] = 0; destination += channels; } } } // back left channel if (channels >= 5) { uint32_t destination = 0; // sound data has back left channel if (soundData->getChannels() >= 5) { uint32_t source = 0; for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 4] = resampledData[source + 4]; destination += channels; source += soundData->getChannels(); } } else { // copy the front left channel in to the back left one for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 4] = result[destination]; destination += channels; } } } // back right channel if (channels >= 6) { uint32_t destination = 0; // sound data has back right channel if (soundData->getChannels() >= 6) { uint32_t source = 0; for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 5] = resampledData[source + 5]; destination += channels; source += soundData->getChannels(); } } else { // copy the front right channel in to the back right one for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 5] = result[destination + 1]; destination += channels; } } } } else { result = resampledData; } Vector3 offset = relativePosition ? position : position - audioDevice->getListenerPosition(); float distance = clamp(offset.length(), minDistance, maxDistance); float attenuation = minDistance / (minDistance + rolloffFactor * (distance - minDistance)); // inverse distance std::vector<float> channelVolume(channels, gain * attenuation); if (channelVolume.size() > 1) { Quaternion inverseRotation = -audioDevice->getListenerRotation(); Vector3 relative = inverseRotation * offset; relative.normalize(); float angle = atan2f(relative.x, relative.z); // constant power panning channelVolume[0] = SQRT2 / 2.0f * (cosf(angle) - sinf(angle)); channelVolume[1] = SQRT2 / 2.0f * (cosf(angle) + sinf(angle)); } for (uint32_t frame = 0; frame < result.size() / channels; ++frame) { for (uint32_t channel = 0; channel < channels; ++channel) { result[frame * channels + channel] *= channelVolume[channel]; } } } return true; } } // namespace audio } // namespace ouzel <commit_msg>Remove the debug log<commit_after>// Copyright (C) 2017 Elviss Strazdins // This file is part of the Ouzel engine. #include <cmath> #include "SoundResource.hpp" #include "AudioDevice.hpp" #include "SoundData.hpp" #include "Stream.hpp" #include "math/MathUtils.hpp" static void resampleLerp(const std::vector<float>& src, uint32_t srcFrames, std::vector<float>& dst, uint32_t dstFrames, uint32_t channels) { if (dstFrames > 0) // do resampling only if setination is not empty { if (srcFrames == 0) // source is empty { dst.resize(dstFrames * channels); std::fill(dst.begin(), dst.end(), 0.0f); } else { float srcIncrement = static_cast<float>(srcFrames - 1) / static_cast<float>(dstFrames - 1); float srcPosition = 0.0f; dst.resize(dstFrames * channels); for (uint32_t frame = 0; frame < dstFrames - 1; ++frame) { uint32_t srcCurrentFrame = static_cast<uint32_t>(srcPosition); float frac = srcPosition - srcCurrentFrame; srcPosition += srcIncrement; uint32_t srcNextFrame = srcCurrentFrame + 1; for (uint32_t channel = 0; channel < channels; ++channel) { uint32_t srcCurrentPosition = srcCurrentFrame * channels + channel; uint32_t srcNextPosition = srcNextFrame * channels + channel; dst[frame * channels + channel] = ouzel::lerp(src[srcCurrentPosition], src[srcNextPosition], frac); } } // fill the last frame of the destination with the last frame of the source for (uint32_t channel = 0; channel < channels; ++channel) { dst[(dstFrames - 1) * channels + channel] = src[(srcFrames - 1) * channels + channel]; } } } } namespace ouzel { namespace audio { SoundResource::SoundResource(AudioDevice* aAudioDevice): audioDevice(aAudioDevice) { } SoundResource::~SoundResource() { } bool SoundResource::init(const std::shared_ptr<SoundData>& newSoundData, bool newRelativePosition) { soundData = newSoundData; relativePosition = newRelativePosition; if (soundData) { stream = soundData->createStream(); } return true; } void SoundResource::setPosition(const Vector3& newPosition) { position = newPosition; } void SoundResource::setPitch(float newPitch) { pitch = newPitch; } void SoundResource::setGain(float newGain) { gain = newGain; } void SoundResource::setRolloffFactor(float newRolloffFactor) { rolloffFactor = newRolloffFactor; } void SoundResource::setMinDistance(float newMinDistance) { minDistance = newMinDistance; } void SoundResource::setMaxDistance(float newMaxDistance) { maxDistance = newMaxDistance; } bool SoundResource::play(bool repeatSound) { playing = true; repeat = repeatSound; return true; } bool SoundResource::pause() { playing = false; return true; } bool SoundResource::stop() { playing = false; reset = true; return true; } bool SoundResource::getData(uint32_t frames, uint16_t channels, uint32_t sampleRate, std::vector<float>& result) { if (!playing) { result.clear(); } else if (soundData && soundData->getChannels() > 0 && stream) { float finalPitch = pitch * soundData->getSampleRate() / sampleRate; uint32_t neededFrames = static_cast<uint32_t>(frames * finalPitch); uint32_t resetCount; if (!soundData->getData(stream.get(), neededFrames, repeat, resetCount, data)) { return false; } if (!repeat && resetCount > 0) playing = false; if (finalPitch != 1.0f) { uint32_t srcFrames = static_cast<uint32_t>(data.size()) / soundData->getChannels(); uint32_t dstFrames = static_cast<uint32_t>(frames * (static_cast<float>(srcFrames) / neededFrames)); resampleLerp(data, srcFrames, resampledData, dstFrames, soundData->getChannels()); } else { resampledData = data; } if (channels != soundData->getChannels()) { uint32_t srcFrames = static_cast<uint32_t>(resampledData.size()) / soundData->getChannels(); result.resize(srcFrames * channels); // front left channel if (channels >= 1) { uint32_t destination = 0; if (soundData->getChannels() >= 1) { uint32_t source = 0; for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination] = resampledData[source]; destination += channels; source += soundData->getChannels(); } } else { // fill the front left channel with zeros for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination] = 0.0f; destination += channels; } } } // front right channel if (channels >= 2) { uint32_t destination = 0; // sound data has front right channel if (soundData->getChannels() >= 2) { uint32_t source = 0; for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 1] = resampledData[source + 1]; destination += channels; source += soundData->getChannels(); } } else { // copy the front left channel in to the front right one for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 1] = result[destination]; destination += channels; } } } // center channel if (channels >= 3) { uint32_t destination = 0; if (soundData->getChannels() >= 3) { uint32_t source = 0; for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 2] = resampledData[source + 2]; destination += channels; source += soundData->getChannels(); } } else if (channels >= 2) { // calculate the average of the front left and the front right channel for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 2] = (result[destination] + result[destination + 1]) / 2.0f; destination += channels; } } else { // copy the front left channel in to the center one for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 2] = result[destination]; destination += channels; } } } // LFE channel if (channels >= 4) { uint32_t destination = 0; if (soundData->getChannels() >= 4) { uint32_t source = 0; for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 3] = resampledData[source + 3]; destination += channels; source += soundData->getChannels(); } } else { // fill the LFE channel with zeros for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 3] = 0; destination += channels; } } } // back left channel if (channels >= 5) { uint32_t destination = 0; // sound data has back left channel if (soundData->getChannels() >= 5) { uint32_t source = 0; for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 4] = resampledData[source + 4]; destination += channels; source += soundData->getChannels(); } } else { // copy the front left channel in to the back left one for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 4] = result[destination]; destination += channels; } } } // back right channel if (channels >= 6) { uint32_t destination = 0; // sound data has back right channel if (soundData->getChannels() >= 6) { uint32_t source = 0; for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 5] = resampledData[source + 5]; destination += channels; source += soundData->getChannels(); } } else { // copy the front right channel in to the back right one for (uint32_t frame = 0; frame < srcFrames; ++frame) { result[destination + 5] = result[destination + 1]; destination += channels; } } } } else { result = resampledData; } Vector3 offset = relativePosition ? position : position - audioDevice->getListenerPosition(); float distance = clamp(offset.length(), minDistance, maxDistance); float attenuation = minDistance / (minDistance + rolloffFactor * (distance - minDistance)); // inverse distance std::vector<float> channelVolume(channels, gain * attenuation); if (channelVolume.size() > 1) { Quaternion inverseRotation = -audioDevice->getListenerRotation(); Vector3 relative = inverseRotation * offset; relative.normalize(); float angle = atan2f(relative.x, relative.z); // constant power panning channelVolume[0] = SQRT2 / 2.0f * (cosf(angle) - sinf(angle)); channelVolume[1] = SQRT2 / 2.0f * (cosf(angle) + sinf(angle)); } for (uint32_t frame = 0; frame < result.size() / channels; ++frame) { for (uint32_t channel = 0; channel < channels; ++channel) { result[frame * channels + channel] *= channelVolume[channel]; } } } return true; } } // namespace audio } // namespace ouzel <|endoftext|>
<commit_before>#ifndef CONTROL_H #define CONTROL_H #include "SPECTYPES.H" // guessed, some may be wrong on PSX enum input_buttons { IN_NONE = 0, // 0x000000 IN_UP = (1 << 0), // 0x000001 IN_DOWN = (1 << 1), // 0x000002 IN_LEFT = (1 << 2), // 0x000004 IN_RIGHT = (1 << 3), // 0x000008 IN_JUMP = (1 << 4), // 0x000010 IN_DRAW = (1 << 5), // Space / Triangle // 0x000020 IN_ACTION = (1 << 6), // Ctrl / X // 0x000040 IN_WALK = (1 << 7), // Shift / R1 // 0x000080 IN_OPTION = (1 << 8), // 0x000100 IN_LOOK = (1 << 9), // 0x000200 IN_LSTEP = (1 << 10), // 0x000400 IN_RSTEP = (1 << 11), // 0x000800 IN_ROLL = (1 << 12), // End / O // 0x001000 IN_PAUSE = (1 << 13), // 0x002000 IN_SAVE = (1 << 22), // F5 // 0x400000 IN_LOAD = (1 << 23) // F6 // 0x800000 }; extern int flipeffect; extern int fliptimer; extern unsigned char ShatterSounds[18][10]; extern unsigned char WeaponDelay; extern unsigned char KeyTriggerActive; extern unsigned short GlobalCounter; extern char TriggerTimer; extern int reset_flag; extern short SlowMotion; extern short SlowMoFrameCount; extern unsigned char InItemControlLoop; extern short ItemNewRoomNo; extern short SmashedMeshCount; extern char richcutfrigflag; extern int nRope; extern char GetLaraOnLOS; extern int NoInput; extern int number_los_rooms; extern long rand_1; extern int framecount; extern long rand_2; extern struct ITEM_INFO* items; extern int flip_status; extern int flipmap[10]; extern int flip_stats[10]; extern int height_type; extern int tiltxoff; extern int tiltyoff; extern unsigned long _CutSceneTriggered1; extern unsigned long _CutSceneTriggered2; extern unsigned long FmvSceneTriggered; extern unsigned char CurrentAtmosphere; extern unsigned char IsAtmospherePlaying; extern char* OutsideRoomTable; extern short* OutsideRoomOffsets; extern short IsRoomOutsideNo; extern short FXType; extern int OnObject; extern short* trigger_index; extern char cd_flags[136]; extern unsigned char InGameCnt; extern struct RAT_STRUCT* Rats; extern struct BAT_STRUCT* Bats; extern struct SPIDER_STRUCT* Spiders; extern struct TWOGUN_INFO twogun[4]; extern int SetDebounce; extern short WB_room; extern struct ITEM_INFO* WB_item; extern unsigned char HeavyTriggered; extern struct MESH_INFO* SmashedMesh[16]; extern short SmashedMeshRoom[16]; extern struct PENDULUM CurrentPendulum; extern char LaraDrawType; extern char WeatherType; extern char RoomDrawType; extern struct PHD_VECTOR ClosestCoord; extern int ClosestItem; extern int ClosestDist; extern short XSoff1; extern short YSoff1; extern short ZSoff1; extern short XSoff2; extern short YSoff2; extern short ZSoff2; extern short los_rooms[20]; extern char globoncuttrig; extern short ItemNewRooms[256][2]; extern struct CHARDEF CharDef[106]; extern long ControlPhase(long nframes, int demo_mode); extern long GetRandomControl(); extern long GetRandomDraw(); extern void AddRoomFlipItems(struct room_info* r); extern void KillMoveItems(); extern void KillMoveEffects(); extern void TestTriggers(short* data, int heavy, int HeavyFlags); extern void ClearFires(); extern int is_object_in_room(int roomnumber, int objnumber); extern void NeatAndTidyTriggerCutscene(int value, int timer); extern int CheckCutPlayed(int num); extern void SetCutNotPlayed(int num); extern void SetCutPlayed(int num); extern void InitCutPlayed(); extern void ResetGuards(); extern void InterpolateAngle(short dest, short *src, short *diff, short speed); extern int CheckGuardOnTrigger(); extern int ExplodeItemNode(struct ITEM_INFO *item, int Node, int NoXZVel, long bits); extern int GetTargetOnLOS(struct GAME_VECTOR *src, struct GAME_VECTOR *dest, int DrawTarget, int firing); extern void FireCrossBowFromLaserSight(struct GAME_VECTOR *src, struct GAME_VECTOR *target); extern void TriggerNormalCDTrack(short value, short flags, short type); extern void TriggerCDTrack(short value, short flags, short type); extern void RemoveRoomFlipItems(struct room_info *r); extern void FlipMap(int FlipNumber); extern void _TestTriggers(short *data, int heavy, int HeavyFlags); extern void RefreshCamera(short type, short *data); extern long GetWaterHeight(long x, long y, long z, short room_number); extern void AlterFloorHeight(struct ITEM_INFO *item, int height); extern short GetHeight(struct FLOOR_INFO *floor, int x, int y, int z); extern struct FLOOR_INFO *GetFloor(int x, int y, int z, short *room_number); extern short GetCeiling(struct FLOOR_INFO *floor, int x, int y, int z); #endif<commit_msg>added flipeffects<commit_after>#ifndef CONTROL_H #define CONTROL_H #include "SPECTYPES.H" // guessed, some may be wrong on PSX enum input_buttons { IN_NONE = 0, // 0x000000 IN_UP = (1 << 0), // 0x000001 IN_DOWN = (1 << 1), // 0x000002 IN_LEFT = (1 << 2), // 0x000004 IN_RIGHT = (1 << 3), // 0x000008 IN_JUMP = (1 << 4), // 0x000010 IN_DRAW = (1 << 5), // Space / Triangle // 0x000020 IN_ACTION = (1 << 6), // Ctrl / X // 0x000040 IN_WALK = (1 << 7), // Shift / R1 // 0x000080 IN_OPTION = (1 << 8), // 0x000100 IN_LOOK = (1 << 9), // 0x000200 IN_LSTEP = (1 << 10), // 0x000400 IN_RSTEP = (1 << 11), // 0x000800 IN_ROLL = (1 << 12), // End / O // 0x001000 IN_PAUSE = (1 << 13), // 0x002000 IN_SAVE = (1 << 22), // F5 // 0x400000 IN_LOAD = (1 << 23) // F6 // 0x800000 }; enum flipeffects { FE_ROTATE_180 = 0, FE_FLOOR_SHAKE = 1, FE_FLOOD_FX = 2, FE_LARA_BUBBLES = 3, FE_FINISH_LEVEL = 4, FE_ACTIVATE_CAMERA = 5, FE_ACTIVATE_KEY = 6, FE_RUBBLE_FX = 7, FE_SWAP_CROWBAR = 8, FE_TIMER_FIELD_FX = 10, FE_EXPLOSION_FX = 11, FE_LARA_HANDSFREE = 12, FE_SHOOT_RIGHTGUN = 16, FE_SHOOT_LEFTGUN = 17, FE_INV_ON = 21, FE_INV_OFF = 22, FE_RESET_HAIR = 26, FE_SETFOG = 28, FE_LARALOCATION = 30, FE_RESET_TEST = 31, FE_FOOTPRINT_FX = 32, FE_CLEAR_SPIDERS_PATCH = 33, FE_LARALOCATIONPAD = 45, FE_KILLACTIVEBADDIES = 46, FE_TUT_HINT_1 = 47, FE_TUT_HINT_2 = 48, FE_TUT_HINT_3 = 49, FE_TUT_HINT_4 = 50, FE_TUT_HINT_5 = 51, FE_TUT_HINT_6 = 52, FE_TUT_HINT_7 = 53, FE_TUT_HINT_8 = 54, FE_TUT_HINT_9 = 55, FE_TUT_HINT_10 = 56, FE_TUT_HINT_11 = 57, FE_TUT_HINT_12 = 58 }; extern int flipeffect; extern int fliptimer; extern unsigned char ShatterSounds[18][10]; extern unsigned char WeaponDelay; extern unsigned char KeyTriggerActive; extern unsigned short GlobalCounter; extern char TriggerTimer; extern int reset_flag; extern short SlowMotion; extern short SlowMoFrameCount; extern unsigned char InItemControlLoop; extern short ItemNewRoomNo; extern short SmashedMeshCount; extern char richcutfrigflag; extern int nRope; extern char GetLaraOnLOS; extern int NoInput; extern int number_los_rooms; extern long rand_1; extern int framecount; extern long rand_2; extern struct ITEM_INFO* items; extern int flip_status; extern int flipmap[10]; extern int flip_stats[10]; extern int height_type; extern int tiltxoff; extern int tiltyoff; extern unsigned long _CutSceneTriggered1; extern unsigned long _CutSceneTriggered2; extern unsigned long FmvSceneTriggered; extern unsigned char CurrentAtmosphere; extern unsigned char IsAtmospherePlaying; extern char* OutsideRoomTable; extern short* OutsideRoomOffsets; extern short IsRoomOutsideNo; extern short FXType; extern int OnObject; extern short* trigger_index; extern char cd_flags[136]; extern unsigned char InGameCnt; extern struct RAT_STRUCT* Rats; extern struct BAT_STRUCT* Bats; extern struct SPIDER_STRUCT* Spiders; extern struct TWOGUN_INFO twogun[4]; extern int SetDebounce; extern short WB_room; extern struct ITEM_INFO* WB_item; extern unsigned char HeavyTriggered; extern struct MESH_INFO* SmashedMesh[16]; extern short SmashedMeshRoom[16]; extern struct PENDULUM CurrentPendulum; extern char LaraDrawType; extern char WeatherType; extern char RoomDrawType; extern struct PHD_VECTOR ClosestCoord; extern int ClosestItem; extern int ClosestDist; extern short XSoff1; extern short YSoff1; extern short ZSoff1; extern short XSoff2; extern short YSoff2; extern short ZSoff2; extern short los_rooms[20]; extern char globoncuttrig; extern short ItemNewRooms[256][2]; extern struct CHARDEF CharDef[106]; extern long ControlPhase(long nframes, int demo_mode); extern long GetRandomControl(); extern long GetRandomDraw(); extern void AddRoomFlipItems(struct room_info* r); extern void KillMoveItems(); extern void KillMoveEffects(); extern void TestTriggers(short* data, int heavy, int HeavyFlags); extern void ClearFires(); extern int is_object_in_room(int roomnumber, int objnumber); extern void NeatAndTidyTriggerCutscene(int value, int timer); extern int CheckCutPlayed(int num); extern void SetCutNotPlayed(int num); extern void SetCutPlayed(int num); extern void InitCutPlayed(); extern void ResetGuards(); extern void InterpolateAngle(short dest, short *src, short *diff, short speed); extern int CheckGuardOnTrigger(); extern int ExplodeItemNode(struct ITEM_INFO *item, int Node, int NoXZVel, long bits); extern int GetTargetOnLOS(struct GAME_VECTOR *src, struct GAME_VECTOR *dest, int DrawTarget, int firing); extern void FireCrossBowFromLaserSight(struct GAME_VECTOR *src, struct GAME_VECTOR *target); extern void TriggerNormalCDTrack(short value, short flags, short type); extern void TriggerCDTrack(short value, short flags, short type); extern void RemoveRoomFlipItems(struct room_info *r); extern void FlipMap(int FlipNumber); extern void _TestTriggers(short *data, int heavy, int HeavyFlags); extern void RefreshCamera(short type, short *data); extern long GetWaterHeight(long x, long y, long z, short room_number); extern void AlterFloorHeight(struct ITEM_INFO *item, int height); extern short GetHeight(struct FLOOR_INFO *floor, int x, int y, int z); extern struct FLOOR_INFO *GetFloor(int x, int y, int z, short *room_number); extern short GetCeiling(struct FLOOR_INFO *floor, int x, int y, int z); #endif<|endoftext|>
<commit_before>#include "types.h" #include "amd64.h" #include "mmu.h" #include "cpu.hh" #include "kernel.hh" #include "bits.hh" #include "spinlock.h" #include "kalloc.hh" #include "queue.h" #include "condvar.h" #include "proc.hh" #include "vm.hh" #include "gc.hh" #include "crange.hh" #include "cpputil.hh" enum { vm_debug = 0 }; /* * vmnode */ vmnode::vmnode(u64 npg, vmntype ntype, inode *i, u64 off, u64 s) : npages(npg), ref(0), type(ntype), ip(i), offset(off), sz(s) { if (npg > NELEM(page)) panic("vmnode too big\n"); memset(page, 0, sizeof(page)); if (type == EAGER) { assert(allocpg() == 0); if (ip) assert(demand_load() == 0); } } vmnode::~vmnode() { for(u64 i = 0; i < npages; i++) { if (page[i]) { kfree(page[i]); page[i] = 0; } } if (ip) iput(ip); } void vmnode::decref() { if(--ref == 0) delete this; } int vmnode::allocpg() { for(u64 i = 0; i < npages; i++) { if (page[i]) continue; char *p = kalloc(); if (!p) { cprintf("allocpg: out of memory, leaving half-filled vmnode\n"); return -1; } memset(p, 0, PGSIZE); if(!cmpxch(&page[i], (char*) 0, p)) kfree(p); } return 0; } vmnode * vmnode::copy() { vmnode *c = new vmnode(npages, type, (type==ONDEMAND) ? idup(ip) : 0, offset, sz); if(c == 0) return 0; if (!page[0]) // If first page is absent, all pages are absent return c; if (c->allocpg() < 0) { cprintf("vmn_copy: out of memory\n"); delete c; return 0; } for(u64 i = 0; i < npages; i++) if (page[i]) memmove(c->page[i], page[i], PGSIZE); return c; } int vmnode::demand_load() { for (u64 i = 0; i < sz; i += PGSIZE) { char *p = page[i / PGSIZE]; s64 n; if (sz - i < PGSIZE) n = sz - i; else n = PGSIZE; /* * Possible race condition with concurrent demand_load() calls, * if the underlying inode's contents change.. */ if (readi(ip, p, offset+i, n) != n) return -1; } return 0; } /* * vma */ vma::vma(vmap *vmap, uptr start, uptr end, enum vmatype vtype, vmnode *vmn) : range(&vmap->cr, start, end-start), vma_start(start), vma_end(end), va_type(vtype), n(vmn) { if (n) n->ref++; } vma::~vma() { if (n) n->decref(); } /* * vmap */ vmap::vmap() : cr(10), ref(1), pml4(setupkvm()), kshared((char*) ksalloc(slab_kshared)) { if (pml4 == 0) { cprintf("vmap_alloc: setupkvm out of memory\n"); goto err; } if (kshared == NULL) { cprintf("vmap::vmap: kshared out of memory\n"); goto err; } if (setupkshared(pml4, kshared)) { cprintf("vmap::vmap: setupkshared out of memory\n"); goto err; } return; err: if (kshared) ksfree(slab_kshared, kshared); if (pml4) freevm(pml4); } vmap::~vmap() { if (kshared) ksfree(slab_kshared, kshared); if (pml4) freevm(pml4); } void vmap::decref() { if (--ref == 0) delete this; } bool vmap::replace_vma(vma *a, vma *b) { auto span = cr.search_lock(a->vma_start, a->vma_end - a->vma_start); if (a->deleted()) return false; for (auto e: span) assert(a == e); span.replace(b); return true; } vmap* vmap::copy(int share) { vmap *nm = new vmap(); if(nm == 0) return 0; for (range *r: cr) { vma *e = (vma *) r; struct vma *ne; if (share) { ne = new vma(nm, e->vma_start, e->vma_end, COW, e->n); // if the original vma wasn't COW, replace it with a COW vma if (e->va_type != COW) { vma *repl = new vma(this, e->vma_start, e->vma_end, COW, e->n); replace_vma(e, repl); updatepages(pml4, e->vma_start, e->vma_end, [](atomic<pme_t>* p) { for (;;) { pme_t v = p->load(); if (v & PTE_LOCK) continue; if (!(v & PTE_P) || !(v & PTE_U) || !(v & PTE_W) || cmpxch(p, v, PTE_ADDR(v) | PTE_P | PTE_U | PTE_COW)) break; } }); } } else { ne = new vma(nm, e->vma_start, e->vma_end, PRIVATE, e->n->copy()); } if (ne == 0) goto err; if (ne->n == 0) { delete ne; goto err; } auto span = nm->cr.search_lock(ne->vma_start, ne->vma_end - ne->vma_start); for (auto x __attribute__((unused)): span) assert(0); /* span must be empty */ span.replace(ne); } if (share) tlbflush(); // Reload hardware page table return nm; err: delete nm; return 0; } // Does any vma overlap start..start+len? // If yes, return the vma pointer. // If no, return 0. // This code can't handle regions at the very end // of the address space, e.g. 0xffffffff..0x0 // We key vma's by their end address. vma * vmap::lookup(uptr start, uptr len) { if (start + len < start) panic("vmap::lookup bad len"); range *r = cr.search(start, len); if (r != 0) { vma *e = (vma *) r; if (e->vma_end <= e->vma_start) panic("malformed va"); if (e->vma_start < start+len && e->vma_end > start) return e; } return 0; } int vmap::insert(vmnode *n, uptr vma_start, int dotlb) { vma *e; { // new scope to release the search lock before tlbflush u64 len = n->npages * PGSIZE; auto span = cr.search_lock(vma_start, len); for (auto r: span) { vma *rvma = (vma*) r; cprintf("vmap::insert: overlap with 0x%lx--0x%lx\n", rvma->vma_start, rvma->vma_end); return -1; } // XXX handle overlaps e = new vma(this, vma_start, vma_start+len, PRIVATE, n); if (e == 0) { cprintf("vmap::insert: out of vmas\n"); return -1; } span.replace(e); } bool needtlb = false; updatepages(pml4, e->vma_start, e->vma_end, [&needtlb](atomic<pme_t> *p) { for (;;) { pme_t v = p->load(); if (v & PTE_LOCK) continue; if (cmpxch(p, v, (pme_t) 0)) break; if (v != 0) needtlb = true; } }); if (needtlb && dotlb) tlbflush(); return 0; } int vmap::remove(uptr vma_start, uptr len) { { // new scope to release the search lock before tlbflush uptr vma_end = vma_start + len; auto span = cr.search_lock(vma_start, len); for (auto r: span) { vma *rvma = (vma*) r; if (rvma->vma_start < vma_start || rvma->vma_end > vma_end) { cprintf("vmap::remove: partial unmap not supported\n"); return -1; } } // XXX handle partial unmap span.replace(0); } bool needtlb = false; updatepages(pml4, vma_start, vma_start + len, [&needtlb](atomic<pme_t> *p) { for (;;) { pme_t v = p->load(); if (v & PTE_LOCK) continue; if (cmpxch(p, v, (pme_t) 0)) break; if (v != 0) needtlb = true; } }); if (needtlb) tlbflush(); return 0; } /* * pagefault handling code on vmap */ int vmap::pagefault_wcow(vma *m) { // Always make a copy of n, even if this process has the only ref, // because other processes may change ref count while this process // is handling wcow. struct vmnode *nodecopy = m->n->copy(); if (nodecopy == 0) { cprintf("pagefault_wcow: out of mem\n"); return -1; } vma *repl = new vma(this, m->vma_start, m->vma_end, PRIVATE, nodecopy); replace_vma(m, repl); updatepages(pml4, m->vma_start, m->vma_end, [](atomic<pme_t> *p) { for (;;) { pme_t v = p->load(); if (v & PTE_LOCK) continue; if (cmpxch(p, v, (pme_t) 0)) break; } }); return 0; } int vmap::pagefault(uptr va, u32 err) { if (va >= USERTOP) return -1; atomic<pme_t> *pte = walkpgdir(pml4, va, 1); retry: pme_t ptev = pte->load(); // optimize checks of args to syscals if ((ptev & (PTE_P|PTE_U|PTE_W)) == (PTE_P|PTE_U|PTE_W)) { // XXX using pagefault() as a security check in syscalls is prone to races return 0; } if (ptev & PTE_LOCK) { // locked, might as well wait for the other pagefaulting core.. goto retry; } scoped_gc_epoch gc; vma *m = lookup(va, 1); if (m == 0) return -1; u64 npg = (PGROUNDDOWN(va) - m->vma_start) / PGSIZE; if (vm_debug) cprintf("pagefault: err 0x%x va 0x%lx type %d ref %lu pid %d\n", err, va, m->va_type, m->n->ref.load(), myproc()->pid); if (m->n && m->n->type == ONDEMAND && m->n->page[npg] == 0) { if (m->n->allocpg() < 0) panic("pagefault: couldn't allocate pages"); if (m->n->demand_load() < 0) panic("pagefault: couldn't load"); } if (m->va_type == COW && (err & FEC_WR)) { if (pagefault_wcow(m) < 0) return -1; tlbflush(); goto retry; } if (!cmpxch(pte, ptev, ptev | PTE_LOCK)) goto retry; if (m->deleted()) { *pte = ptev; goto retry; } if (m->va_type == COW) { *pte = v2p(m->n->page[npg]) | PTE_P | PTE_U | PTE_COW; } else { assert(m->n->ref == 1); *pte = v2p(m->n->page[npg]) | PTE_P | PTE_U | PTE_W; } return 1; } int pagefault(struct vmap *vmap, uptr va, u32 err) { return vmap->pagefault(va, err); } // Copy len bytes from p to user address va in vmap. // Most useful when vmap is not the current page table. int vmap::copyout(uptr va, void *p, u64 len) { char *buf = (char*)p; while(len > 0){ uptr va0 = (uptr)PGROUNDDOWN(va); scoped_gc_epoch gc; vma *vma = lookup(va, 1); if(vma == 0) return -1; uptr pn = (va0 - vma->vma_start) / PGSIZE; char *p0 = vma->n->page[pn]; if(p0 == 0) panic("copyout: missing page"); uptr n = PGSIZE - (va - va0); if(n > len) n = len; memmove(p0 + (va - va0), buf, n); len -= n; buf += n; va = va0 + PGSIZE; } return 0; } <commit_msg>minor speedup<commit_after>#include "types.h" #include "amd64.h" #include "mmu.h" #include "cpu.hh" #include "kernel.hh" #include "bits.hh" #include "spinlock.h" #include "kalloc.hh" #include "queue.h" #include "condvar.h" #include "proc.hh" #include "vm.hh" #include "gc.hh" #include "crange.hh" #include "cpputil.hh" enum { vm_debug = 0 }; /* * vmnode */ vmnode::vmnode(u64 npg, vmntype ntype, inode *i, u64 off, u64 s) : npages(npg), ref(0), type(ntype), ip(i), offset(off), sz(s) { if (npg > NELEM(page)) panic("vmnode too big\n"); memset(page, 0, npg * sizeof(page[0])); if (type == EAGER) { assert(allocpg() == 0); if (ip) assert(demand_load() == 0); } } vmnode::~vmnode() { for(u64 i = 0; i < npages; i++) if (page[i]) kfree(page[i]); if (ip) iput(ip); } void vmnode::decref() { if(--ref == 0) delete this; } int vmnode::allocpg() { for(u64 i = 0; i < npages; i++) { if (page[i]) continue; char *p = kalloc(); if (!p) { cprintf("allocpg: out of memory, leaving half-filled vmnode\n"); return -1; } memset(p, 0, PGSIZE); if(!cmpxch(&page[i], (char*) 0, p)) kfree(p); } return 0; } vmnode * vmnode::copy() { vmnode *c = new vmnode(npages, type, (type==ONDEMAND) ? idup(ip) : 0, offset, sz); if(c == 0) return 0; if (!page[0]) // If first page is absent, all pages are absent return c; if (c->allocpg() < 0) { cprintf("vmn_copy: out of memory\n"); delete c; return 0; } for(u64 i = 0; i < npages; i++) if (page[i]) memmove(c->page[i], page[i], PGSIZE); return c; } int vmnode::demand_load() { for (u64 i = 0; i < sz; i += PGSIZE) { char *p = page[i / PGSIZE]; s64 n; if (sz - i < PGSIZE) n = sz - i; else n = PGSIZE; /* * Possible race condition with concurrent demand_load() calls, * if the underlying inode's contents change.. */ if (readi(ip, p, offset+i, n) != n) return -1; } return 0; } /* * vma */ vma::vma(vmap *vmap, uptr start, uptr end, enum vmatype vtype, vmnode *vmn) : range(&vmap->cr, start, end-start), vma_start(start), vma_end(end), va_type(vtype), n(vmn) { if (n) n->ref++; } vma::~vma() { if (n) n->decref(); } /* * vmap */ vmap::vmap() : cr(10), ref(1), pml4(setupkvm()), kshared((char*) ksalloc(slab_kshared)) { if (pml4 == 0) { cprintf("vmap_alloc: setupkvm out of memory\n"); goto err; } if (kshared == NULL) { cprintf("vmap::vmap: kshared out of memory\n"); goto err; } if (setupkshared(pml4, kshared)) { cprintf("vmap::vmap: setupkshared out of memory\n"); goto err; } return; err: if (kshared) ksfree(slab_kshared, kshared); if (pml4) freevm(pml4); } vmap::~vmap() { if (kshared) ksfree(slab_kshared, kshared); if (pml4) freevm(pml4); } void vmap::decref() { if (--ref == 0) delete this; } bool vmap::replace_vma(vma *a, vma *b) { auto span = cr.search_lock(a->vma_start, a->vma_end - a->vma_start); if (a->deleted()) return false; for (auto e: span) assert(a == e); span.replace(b); return true; } vmap* vmap::copy(int share) { vmap *nm = new vmap(); if(nm == 0) return 0; for (range *r: cr) { vma *e = (vma *) r; struct vma *ne; if (share) { ne = new vma(nm, e->vma_start, e->vma_end, COW, e->n); // if the original vma wasn't COW, replace it with a COW vma if (e->va_type != COW) { vma *repl = new vma(this, e->vma_start, e->vma_end, COW, e->n); replace_vma(e, repl); updatepages(pml4, e->vma_start, e->vma_end, [](atomic<pme_t>* p) { for (;;) { pme_t v = p->load(); if (v & PTE_LOCK) continue; if (!(v & PTE_P) || !(v & PTE_U) || !(v & PTE_W) || cmpxch(p, v, PTE_ADDR(v) | PTE_P | PTE_U | PTE_COW)) break; } }); } } else { ne = new vma(nm, e->vma_start, e->vma_end, PRIVATE, e->n->copy()); } if (ne == 0) goto err; if (ne->n == 0) { delete ne; goto err; } auto span = nm->cr.search_lock(ne->vma_start, ne->vma_end - ne->vma_start); for (auto x __attribute__((unused)): span) assert(0); /* span must be empty */ span.replace(ne); } if (share) tlbflush(); // Reload hardware page table return nm; err: delete nm; return 0; } // Does any vma overlap start..start+len? // If yes, return the vma pointer. // If no, return 0. // This code can't handle regions at the very end // of the address space, e.g. 0xffffffff..0x0 // We key vma's by their end address. vma * vmap::lookup(uptr start, uptr len) { if (start + len < start) panic("vmap::lookup bad len"); range *r = cr.search(start, len); if (r != 0) { vma *e = (vma *) r; if (e->vma_end <= e->vma_start) panic("malformed va"); if (e->vma_start < start+len && e->vma_end > start) return e; } return 0; } int vmap::insert(vmnode *n, uptr vma_start, int dotlb) { vma *e; { // new scope to release the search lock before tlbflush u64 len = n->npages * PGSIZE; auto span = cr.search_lock(vma_start, len); for (auto r: span) { vma *rvma = (vma*) r; cprintf("vmap::insert: overlap with 0x%lx--0x%lx\n", rvma->vma_start, rvma->vma_end); return -1; } // XXX handle overlaps e = new vma(this, vma_start, vma_start+len, PRIVATE, n); if (e == 0) { cprintf("vmap::insert: out of vmas\n"); return -1; } span.replace(e); } bool needtlb = false; updatepages(pml4, e->vma_start, e->vma_end, [&needtlb](atomic<pme_t> *p) { for (;;) { pme_t v = p->load(); if (v & PTE_LOCK) continue; if (cmpxch(p, v, (pme_t) 0)) break; if (v != 0) needtlb = true; } }); if (needtlb && dotlb) tlbflush(); return 0; } int vmap::remove(uptr vma_start, uptr len) { { // new scope to release the search lock before tlbflush uptr vma_end = vma_start + len; auto span = cr.search_lock(vma_start, len); for (auto r: span) { vma *rvma = (vma*) r; if (rvma->vma_start < vma_start || rvma->vma_end > vma_end) { cprintf("vmap::remove: partial unmap not supported\n"); return -1; } } // XXX handle partial unmap span.replace(0); } bool needtlb = false; updatepages(pml4, vma_start, vma_start + len, [&needtlb](atomic<pme_t> *p) { for (;;) { pme_t v = p->load(); if (v & PTE_LOCK) continue; if (cmpxch(p, v, (pme_t) 0)) break; if (v != 0) needtlb = true; } }); if (needtlb) tlbflush(); return 0; } /* * pagefault handling code on vmap */ int vmap::pagefault_wcow(vma *m) { // Always make a copy of n, even if this process has the only ref, // because other processes may change ref count while this process // is handling wcow. struct vmnode *nodecopy = m->n->copy(); if (nodecopy == 0) { cprintf("pagefault_wcow: out of mem\n"); return -1; } vma *repl = new vma(this, m->vma_start, m->vma_end, PRIVATE, nodecopy); replace_vma(m, repl); updatepages(pml4, m->vma_start, m->vma_end, [](atomic<pme_t> *p) { for (;;) { pme_t v = p->load(); if (v & PTE_LOCK) continue; if (cmpxch(p, v, (pme_t) 0)) break; } }); return 0; } int vmap::pagefault(uptr va, u32 err) { if (va >= USERTOP) return -1; atomic<pme_t> *pte = walkpgdir(pml4, va, 1); retry: pme_t ptev = pte->load(); // optimize checks of args to syscals if ((ptev & (PTE_P|PTE_U|PTE_W)) == (PTE_P|PTE_U|PTE_W)) { // XXX using pagefault() as a security check in syscalls is prone to races return 0; } if (ptev & PTE_LOCK) { // locked, might as well wait for the other pagefaulting core.. goto retry; } scoped_gc_epoch gc; vma *m = lookup(va, 1); if (m == 0) return -1; u64 npg = (PGROUNDDOWN(va) - m->vma_start) / PGSIZE; if (vm_debug) cprintf("pagefault: err 0x%x va 0x%lx type %d ref %lu pid %d\n", err, va, m->va_type, m->n->ref.load(), myproc()->pid); if (m->n && m->n->type == ONDEMAND && m->n->page[npg] == 0) { if (m->n->allocpg() < 0) panic("pagefault: couldn't allocate pages"); if (m->n->demand_load() < 0) panic("pagefault: couldn't load"); } if (m->va_type == COW && (err & FEC_WR)) { if (pagefault_wcow(m) < 0) return -1; tlbflush(); goto retry; } if (!cmpxch(pte, ptev, ptev | PTE_LOCK)) goto retry; if (m->deleted()) { *pte = ptev; goto retry; } if (m->va_type == COW) { *pte = v2p(m->n->page[npg]) | PTE_P | PTE_U | PTE_COW; } else { assert(m->n->ref == 1); *pte = v2p(m->n->page[npg]) | PTE_P | PTE_U | PTE_W; } return 1; } int pagefault(struct vmap *vmap, uptr va, u32 err) { return vmap->pagefault(va, err); } // Copy len bytes from p to user address va in vmap. // Most useful when vmap is not the current page table. int vmap::copyout(uptr va, void *p, u64 len) { char *buf = (char*)p; while(len > 0){ uptr va0 = (uptr)PGROUNDDOWN(va); scoped_gc_epoch gc; vma *vma = lookup(va, 1); if(vma == 0) return -1; uptr pn = (va0 - vma->vma_start) / PGSIZE; char *p0 = vma->n->page[pn]; if(p0 == 0) panic("copyout: missing page"); uptr n = PGSIZE - (va - va0); if(n > len) n = len; memmove(p0 + (va - va0), buf, n); len -= n; buf += n; va = va0 + PGSIZE; } return 0; } <|endoftext|>
<commit_before>/* main.cpp * localcall main file - locally loads a shared library, instantiates a module and calls a function from that module */ #include <iostream> #include <cstdlib> #include <boost/shared_ptr.hpp> #include <qi/os.hpp> #include <qi/path.hpp> #include <qi/log.hpp> #include <alcommon/almodule.h> #include <alcommon/alproxy.h> #include <alcommon/albroker.h> #include <alcommon/albrokermanager.h> // Turn bold text on std::ostream& bold_on(std::ostream& os) { return os << "\e[1m"; } // Turn bold text off std::ostream& bold_off(std::ostream& os) { return os << "\e[0m"; } int main(int argc, char* argv[]) { // Name of desired library std::string libName = "libmoduletest.so"; // Name of desired module in library std::string moduleName = "ModuleTest"; // Name of void(void) function to call in class std::string funcName = "printHello"; // Set broker name, ip and port, finding first available port from 54000 const std::string brokerName = "localCallBroker"; int brokerPort = qi::os::findAvailablePort(54000); const std::string brokerIp = "0.0.0.0"; // Default parent port and ip int pport = 9559; std::string pip = "127.0.0.1"; // Check number of command line arguments if (argc != 1 && argc != 3 && argc != 5) { std::cerr << "Wrong number of arguments!" << std::endl; std::cerr << "Usage: localcall [--pip robot_ip] [--pport port]" << std::endl; exit(2); } // If there is only one argument it should be the IP or PORT if (argc == 3) { if (std::string(argv[1]) == "--pip") { pip = argv[2]; } else if (std::string(argv[1]) == "--pport") { pport = atoi(argv[2]); } else { std::cerr << "Wrong number of arguments!" << std::endl; std::cerr << "Usage: localcall [--pip robot_ip] [--pport port]" << std::endl; exit(2); } } // Specified IP or PORT for the connection if (argc == 5) { if (std::string(argv[1]) == "--pport" && std::string(argv[3]) == "--pip") { pport = atoi(argv[2]); pip = argv[4]; } else if (std::string(argv[3]) == "--pport" && std::string(argv[1]) == "--pip") { pport = atoi(argv[4]); pip = argv[2]; } else { std::cerr << "Wrong number of arguments!" << std::endl; std::cerr << "Usage: localcall [--pip robot_ip] [--pport port]" << std::endl; exit(2); } } // Need this for SOAP serialisation of floats to work setlocale(LC_NUMERIC, "C"); // Create a broker boost::shared_ptr<AL::ALBroker> broker; try { broker = AL::ALBroker::createBroker( brokerName, brokerIp, brokerPort, pip, pport, 0); } // Throw error and quit if a broker could not be created catch(...) { std::cerr << "Failed to connect broker to: " << pip << ":" << pport << std::endl; AL::ALBrokerManager::getInstance()->killAllBroker(); AL::ALBrokerManager::kill(); return 1; } // Add the broker to NAOqi AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock()); AL::ALBrokerManager::getInstance()->addBroker(broker); // Find the desired library std::cout << bold_on << "Finding " << libName << "..." << bold_off << std::endl; std::string library = qi::path::findLib(libName.c_str()); // Open the library std::cout << bold_on << "Loading " << library << "..." << bold_off << std::endl; void* handle = qi::os::dlopen(library.c_str()); if (!handle) { qiLogWarning(moduleName.c_str()) << "Could not load library:" << qi::os::dlerror() << std::endl; return -1; } // Load the create symbol std::cout << bold_on << "Loading _createModule symbol..." << bold_off << std::endl; int(*createModule)(boost::shared_ptr<AL::ALBroker>) = (int(*)(boost::shared_ptr<AL::ALBroker>))(qi::os::dlsym(handle, "_createModule")); if (!createModule) { qiLogWarning(moduleName.c_str()) << "Could not load symbol _createModule: " << qi::os::dlerror() << std::endl; return -1; } // Check if module is already present std::cout << bold_on << "Module " << moduleName << " is "; if (!(broker->isModulePresent(moduleName))) { std::cout << "not "; } std::cout << "present" << bold_off << std::endl; // Create an instance of the desired module std::cout << bold_on << "Creating " << moduleName << " instance..." << bold_off << std::endl; createModule(broker); // Check for module creation std::cout << bold_on << "Module " << moduleName.c_str() << " is "; if (!(broker->isModulePresent(moduleName))) { std::cout << "not "; } std::cout << "present" << bold_off << std::endl; // Create a proxy to the module std::cout << bold_on << "Creating proxy to module..." << bold_off << std::endl; AL::ALProxy testProxy(moduleName, pip, pport); // Call a generic function from the module with no arguments std::cout << bold_on << "Calling function " << funcName << "..." << bold_off << std::endl; testProxy.callVoid(funcName); // Get a handle to the module and close it { boost::shared_ptr<AL::ALModuleCore> module = broker->getModuleByName(moduleName); std::cout << bold_on << "Closing module " << moduleName << "..." << bold_off << std::endl; module->exit(); } // Check module has closed std::cout << bold_on << "Module " << moduleName << " is "; if (!(broker->isModulePresent(moduleName))) { std::cout << "not "; } std::cout << "present" << bold_off << std::endl; // Close the broker std::cout << bold_on << "Closing broker..." << bold_off << std::endl; broker->shutdown(); // Exit program std::cout << bold_on << "Exiting..." << bold_off << std::endl; return 0; } <commit_msg>Improved localcall command-line options<commit_after>/* main.cpp * localcall main file - locally loads a shared library, instantiates a module and calls a function from that module */ #include <iostream> #include <cstdlib> #include <unistd.h> #include <getopt.h> #include <boost/shared_ptr.hpp> #include <qi/os.hpp> #include <qi/path.hpp> #include <qi/log.hpp> #include <alcommon/almodule.h> #include <alcommon/alproxy.h> #include <alcommon/albroker.h> #include <alcommon/albrokermanager.h> // Turn bold text on std::ostream& bold_on(std::ostream& os) { return os << "\e[1m"; } // Turn bold text off std::ostream& bold_off(std::ostream& os) { return os << "\e[0m"; } // Wrong number of arguments void argErr(void) { // Standard usage message std::string usage = "Usage: localcall [--pip robot_ip] [--pport port] [--lib library] [--mod module] [--fun function]"; std::cerr << "Wrong number of arguments!" << std::endl; std::cerr << usage << std::endl; exit(2); } int main(int argc, char* argv[]) { // Default name of desired library std::string libName = "libmoduletest.so"; // Default name of desired module in library std::string moduleName = "ModuleTest"; // Default name of void(void) function to call in module std::string funcName = "printHello"; // Set broker name, ip and port, finding first available port from 54000 const std::string brokerName = "localCallBroker"; int brokerPort = qi::os::findAvailablePort(54000); const std::string brokerIp = "0.0.0.0"; // Default parent port and ip int pport = 9559; std::string pip = "127.0.0.1"; // Check for odd number of command line arguments (in this case) if (argc % 2 != 1) { argErr(); } // Get any arguments while (true) { static int index = 0; // Struct of options static const struct option longopts[] = { {"pip", 1, 0, 'p'}, {"pport", 1, 0, 'o'}, {"lib", 1, 0, 'l'}, {"mod", 1, 0, 'm'}, {"fun", 1, 0, 'f'}, {0, 0, 0, 0 } }; switch(index = getopt_long(argc, argv, "", longopts, &index)) { case 'p': if (optarg) pip = std::string(optarg); else argErr(); break; case 'o': if (optarg) pport = atoi(optarg); else argErr(); break; case 'l': if (optarg) libName = std::string(optarg); else argErr(); break; case 'm': if (optarg) moduleName = std::string(optarg); else argErr(); break; case 'f': if (optarg) funcName = std::string(optarg); else argErr(); break; } if (index == -1) break; } // Need this for SOAP serialisation of floats to work setlocale(LC_NUMERIC, "C"); // Create a broker boost::shared_ptr<AL::ALBroker> broker; try { broker = AL::ALBroker::createBroker( brokerName, brokerIp, brokerPort, pip, pport, 0); } // Throw error and quit if a broker could not be created catch(...) { std::cerr << "Failed to connect broker to: " << pip << ":" << pport << std::endl; AL::ALBrokerManager::getInstance()->killAllBroker(); AL::ALBrokerManager::kill(); return 1; } // Add the broker to NAOqi AL::ALBrokerManager::setInstance(broker->fBrokerManager.lock()); AL::ALBrokerManager::getInstance()->addBroker(broker); // Find the desired library std::cout << bold_on << "Finding " << libName << "..." << bold_off << std::endl; std::string library = qi::path::findLib(libName.c_str()); // Open the library std::cout << bold_on << "Loading " << library << "..." << bold_off << std::endl; void* handle = qi::os::dlopen(library.c_str()); if (!handle) { qiLogWarning(moduleName.c_str()) << "Could not load library:" << qi::os::dlerror() << std::endl; return -1; } // Load the create symbol std::cout << bold_on << "Loading _createModule symbol..." << bold_off << std::endl; int(*createModule)(boost::shared_ptr<AL::ALBroker>) = (int(*)(boost::shared_ptr<AL::ALBroker>))(qi::os::dlsym(handle, "_createModule")); if (!createModule) { qiLogWarning(moduleName.c_str()) << "Could not load symbol _createModule: " << qi::os::dlerror() << std::endl; return -1; } // Check if module is already present std::cout << bold_on << "Module " << moduleName << " is "; if (!(broker->isModulePresent(moduleName))) { std::cout << "not "; } std::cout << "present" << bold_off << std::endl; // Create an instance of the desired module std::cout << bold_on << "Creating " << moduleName << " instance..." << bold_off << std::endl; createModule(broker); // Check for module creation std::cout << bold_on << "Module " << moduleName.c_str() << " is "; if (!(broker->isModulePresent(moduleName))) { std::cout << "not "; } std::cout << "present" << bold_off << std::endl; // Create a proxy to the module std::cout << bold_on << "Creating proxy to module..." << bold_off << std::endl; AL::ALProxy testProxy(moduleName, pip, pport); // Call a generic function from the module with no arguments std::cout << bold_on << "Calling function " << funcName << "..." << bold_off << std::endl; testProxy.callVoid(funcName); // Get a handle to the module and close it { boost::shared_ptr<AL::ALModuleCore> module = broker->getModuleByName(moduleName); std::cout << bold_on << "Closing module " << moduleName << "..." << bold_off << std::endl; module->exit(); } // Check module has closed std::cout << bold_on << "Module " << moduleName << " is "; if (!(broker->isModulePresent(moduleName))) { std::cout << "not "; } std::cout << "present" << bold_off << std::endl; // Close the broker std::cout << bold_on << "Closing broker..." << bold_off << std::endl; broker->shutdown(); // Exit program std::cout << bold_on << "Exiting..." << bold_off << std::endl; return 0; } <|endoftext|>
<commit_before>/* * DSA * (C) 1999-2010,2014,2016 Jack Lloyd * (C) 2016 René Korthaus * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/dsa.h> #include <botan/internal/keypair.h> #include <botan/reducer.h> #include <botan/rng.h> #include <botan/internal/divide.h> #include <botan/internal/pk_ops_impl.h> #if defined(BOTAN_HAS_RFC6979_GENERATOR) #include <botan/internal/emsa.h> #include <botan/internal/rfc6979.h> #endif namespace Botan { /* * DSA_PublicKey Constructor */ DSA_PublicKey::DSA_PublicKey(const AlgorithmIdentifier& alg_id, const std::vector<uint8_t>& key_bits) : DL_Scheme_PublicKey(alg_id, key_bits, DL_Group_Format::ANSI_X9_57) { BOTAN_ARG_CHECK(group_q().bytes() > 0, "Q parameter must be set for DSA"); } DSA_PublicKey::DSA_PublicKey(const DL_Group& grp, const BigInt& y1) { m_group = grp; m_y = y1; BOTAN_ARG_CHECK(grp.q_bytes() > 0, "Q parameter must be set for DSA"); } /* * Create a DSA private key */ DSA_PrivateKey::DSA_PrivateKey(RandomNumberGenerator& rng, const DL_Group& grp, const BigInt& x_arg) { m_group = grp; if(x_arg == 0) m_x = BigInt::random_integer(rng, 2, group_q()); else m_x = x_arg; m_y = m_group.power_g_p(m_x, m_group.q_bits()); } DSA_PrivateKey::DSA_PrivateKey(const AlgorithmIdentifier& alg_id, const secure_vector<uint8_t>& key_bits) : DL_Scheme_PrivateKey(alg_id, key_bits, DL_Group_Format::ANSI_X9_57) { m_y = m_group.power_g_p(m_x, m_group.q_bits()); } /* * Check Private DSA Parameters */ bool DSA_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const { if(!DL_Scheme_PrivateKey::check_key(rng, strong) || m_x >= group_q()) return false; if(!strong) return true; return KeyPair::signature_consistency_check(rng, *this, "EMSA1(SHA-256)"); } std::unique_ptr<Public_Key> DSA_PrivateKey::public_key() const { return std::make_unique<DSA_PublicKey>(get_group(), get_y()); } namespace { /** * Object that can create a DSA signature */ class DSA_Signature_Operation final : public PK_Ops::Signature_with_EMSA { public: DSA_Signature_Operation(const DSA_PrivateKey& dsa, const std::string& emsa, RandomNumberGenerator& rng) : PK_Ops::Signature_with_EMSA(emsa), m_group(dsa.get_group()), m_x(dsa.get_x()) { m_b = BigInt::random_integer(rng, 2, dsa.group_q()); m_b_inv = m_group.inverse_mod_q(m_b); } size_t signature_length() const override { return 2*m_group.q_bytes(); } size_t max_input_bits() const override { return m_group.q_bits(); } secure_vector<uint8_t> raw_sign(const uint8_t msg[], size_t msg_len, RandomNumberGenerator& rng) override; private: const DL_Group m_group; const BigInt& m_x; BigInt m_b, m_b_inv; }; secure_vector<uint8_t> DSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len, RandomNumberGenerator& rng) { const BigInt& q = m_group.get_q(); BigInt m = BigInt::from_bytes_with_max_bits(msg, msg_len, m_group.q_bits()); while(m >= q) m -= q; #if defined(BOTAN_HAS_RFC6979_GENERATOR) BOTAN_UNUSED(rng); const BigInt k = generate_rfc6979_nonce(m_x, q, m, this->hash_for_signature()); #else const BigInt k = BigInt::random_integer(rng, 1, q); #endif const BigInt k_inv = m_group.inverse_mod_q(k); /* * It may not be strictly necessary for the reduction (g^k mod p) mod q to be * const time, since r is published as part of the signature, and deriving * anything useful about k from g^k mod p would seem to require computing a * discrete logarithm. * * However it only increases the cost of signatures by about 7-10%, and DSA is * only for legacy use anyway so we don't care about the performance so much. */ const BigInt r = ct_modulo(m_group.power_g_p(k, m_group.q_bits()), m_group.get_q()); /* * Blind the input message and compute x*r+m as (x*r*b + m*b)/b */ m_b = m_group.square_mod_q(m_b); m_b_inv = m_group.square_mod_q(m_b_inv); m = m_group.multiply_mod_q(m_b, m); const BigInt xr = m_group.multiply_mod_q(m_b, m_x, r); const BigInt s = m_group.multiply_mod_q(m_b_inv, k_inv, m_group.mod_q(xr+m)); // With overwhelming probability, a bug rather than actual zero r/s if(r.is_zero() || s.is_zero()) throw Internal_Error("Computed zero r/s during DSA signature"); return BigInt::encode_fixed_length_int_pair(r, s, q.bytes()); } /** * Object that can verify a DSA signature */ class DSA_Verification_Operation final : public PK_Ops::Verification_with_EMSA { public: DSA_Verification_Operation(const DSA_PublicKey& dsa, const std::string& emsa) : PK_Ops::Verification_with_EMSA(emsa), m_group(dsa.get_group()), m_y(dsa.get_y()) { } size_t max_input_bits() const override { return m_group.q_bits(); } bool with_recovery() const override { return false; } bool verify(const uint8_t msg[], size_t msg_len, const uint8_t sig[], size_t sig_len) override; private: const DL_Group m_group; const BigInt& m_y; }; bool DSA_Verification_Operation::verify(const uint8_t msg[], size_t msg_len, const uint8_t sig[], size_t sig_len) { const BigInt& q = m_group.get_q(); const size_t q_bytes = q.bytes(); if(sig_len != 2*q_bytes || msg_len > q_bytes) return false; BigInt r(sig, q_bytes); BigInt s(sig + q_bytes, q_bytes); BigInt i = BigInt::from_bytes_with_max_bits(msg, msg_len, m_group.q_bits()); if(r <= 0 || r >= q || s <= 0 || s >= q) return false; s = inverse_mod(s, q); const BigInt sr = m_group.multiply_mod_q(s, r); const BigInt si = m_group.multiply_mod_q(s, i); s = m_group.multi_exponentiate(si, m_y, sr); // s is too big for Barrett, and verification doesn't need to be const-time return (s % m_group.get_q() == r); } } std::unique_ptr<PK_Ops::Verification> DSA_PublicKey::create_verification_op(const std::string& params, const std::string& provider) const { if(provider == "base" || provider.empty()) return std::make_unique<DSA_Verification_Operation>(*this, params); throw Provider_Not_Found(algo_name(), provider); } std::unique_ptr<PK_Ops::Signature> DSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng, const std::string& params, const std::string& provider) const { if(provider == "base" || provider.empty()) return std::make_unique<DSA_Signature_Operation>(*this, params, rng); throw Provider_Not_Found(algo_name(), provider); } } <commit_msg>FIX: validate X <= Q before exponentiation<commit_after>/* * DSA * (C) 1999-2010,2014,2016 Jack Lloyd * (C) 2016 René Korthaus * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/dsa.h> #include <botan/internal/keypair.h> #include <botan/reducer.h> #include <botan/rng.h> #include <botan/internal/divide.h> #include <botan/internal/pk_ops_impl.h> #if defined(BOTAN_HAS_RFC6979_GENERATOR) #include <botan/internal/emsa.h> #include <botan/internal/rfc6979.h> #endif namespace Botan { /* * DSA_PublicKey Constructor */ DSA_PublicKey::DSA_PublicKey(const AlgorithmIdentifier& alg_id, const std::vector<uint8_t>& key_bits) : DL_Scheme_PublicKey(alg_id, key_bits, DL_Group_Format::ANSI_X9_57) { BOTAN_ARG_CHECK(group_q().bytes() > 0, "Q parameter must be set for DSA"); } DSA_PublicKey::DSA_PublicKey(const DL_Group& grp, const BigInt& y1) { m_group = grp; m_y = y1; BOTAN_ARG_CHECK(grp.q_bytes() > 0, "Q parameter must be set for DSA"); } /* * Create a DSA private key */ DSA_PrivateKey::DSA_PrivateKey(RandomNumberGenerator& rng, const DL_Group& grp, const BigInt& x_arg) { m_group = grp; if(x_arg == 0) m_x = BigInt::random_integer(rng, 2, group_q()); else { BOTAN_ARG_CHECK(m_x.bits() <= m_group.q_bits(), "x must not be larger than q"); m_x = x_arg; } m_y = m_group.power_g_p(m_x, m_group.q_bits()); } DSA_PrivateKey::DSA_PrivateKey(const AlgorithmIdentifier& alg_id, const secure_vector<uint8_t>& key_bits) : DL_Scheme_PrivateKey(alg_id, key_bits, DL_Group_Format::ANSI_X9_57) { BOTAN_ARG_CHECK(m_x.bits() <= m_group.q_bits(), "x must not be larger than q"); m_y = m_group.power_g_p(m_x, m_group.q_bits()); } /* * Check Private DSA Parameters */ bool DSA_PrivateKey::check_key(RandomNumberGenerator& rng, bool strong) const { if(!DL_Scheme_PrivateKey::check_key(rng, strong) || m_x >= group_q()) return false; if(!strong) return true; return KeyPair::signature_consistency_check(rng, *this, "EMSA1(SHA-256)"); } std::unique_ptr<Public_Key> DSA_PrivateKey::public_key() const { return std::make_unique<DSA_PublicKey>(get_group(), get_y()); } namespace { /** * Object that can create a DSA signature */ class DSA_Signature_Operation final : public PK_Ops::Signature_with_EMSA { public: DSA_Signature_Operation(const DSA_PrivateKey& dsa, const std::string& emsa, RandomNumberGenerator& rng) : PK_Ops::Signature_with_EMSA(emsa), m_group(dsa.get_group()), m_x(dsa.get_x()) { m_b = BigInt::random_integer(rng, 2, dsa.group_q()); m_b_inv = m_group.inverse_mod_q(m_b); } size_t signature_length() const override { return 2*m_group.q_bytes(); } size_t max_input_bits() const override { return m_group.q_bits(); } secure_vector<uint8_t> raw_sign(const uint8_t msg[], size_t msg_len, RandomNumberGenerator& rng) override; private: const DL_Group m_group; const BigInt& m_x; BigInt m_b, m_b_inv; }; secure_vector<uint8_t> DSA_Signature_Operation::raw_sign(const uint8_t msg[], size_t msg_len, RandomNumberGenerator& rng) { const BigInt& q = m_group.get_q(); BigInt m = BigInt::from_bytes_with_max_bits(msg, msg_len, m_group.q_bits()); while(m >= q) m -= q; #if defined(BOTAN_HAS_RFC6979_GENERATOR) BOTAN_UNUSED(rng); const BigInt k = generate_rfc6979_nonce(m_x, q, m, this->hash_for_signature()); #else const BigInt k = BigInt::random_integer(rng, 1, q); #endif const BigInt k_inv = m_group.inverse_mod_q(k); /* * It may not be strictly necessary for the reduction (g^k mod p) mod q to be * const time, since r is published as part of the signature, and deriving * anything useful about k from g^k mod p would seem to require computing a * discrete logarithm. * * However it only increases the cost of signatures by about 7-10%, and DSA is * only for legacy use anyway so we don't care about the performance so much. */ const BigInt r = ct_modulo(m_group.power_g_p(k, m_group.q_bits()), m_group.get_q()); /* * Blind the input message and compute x*r+m as (x*r*b + m*b)/b */ m_b = m_group.square_mod_q(m_b); m_b_inv = m_group.square_mod_q(m_b_inv); m = m_group.multiply_mod_q(m_b, m); const BigInt xr = m_group.multiply_mod_q(m_b, m_x, r); const BigInt s = m_group.multiply_mod_q(m_b_inv, k_inv, m_group.mod_q(xr+m)); // With overwhelming probability, a bug rather than actual zero r/s if(r.is_zero() || s.is_zero()) throw Internal_Error("Computed zero r/s during DSA signature"); return BigInt::encode_fixed_length_int_pair(r, s, q.bytes()); } /** * Object that can verify a DSA signature */ class DSA_Verification_Operation final : public PK_Ops::Verification_with_EMSA { public: DSA_Verification_Operation(const DSA_PublicKey& dsa, const std::string& emsa) : PK_Ops::Verification_with_EMSA(emsa), m_group(dsa.get_group()), m_y(dsa.get_y()) { } size_t max_input_bits() const override { return m_group.q_bits(); } bool with_recovery() const override { return false; } bool verify(const uint8_t msg[], size_t msg_len, const uint8_t sig[], size_t sig_len) override; private: const DL_Group m_group; const BigInt& m_y; }; bool DSA_Verification_Operation::verify(const uint8_t msg[], size_t msg_len, const uint8_t sig[], size_t sig_len) { const BigInt& q = m_group.get_q(); const size_t q_bytes = q.bytes(); if(sig_len != 2*q_bytes || msg_len > q_bytes) return false; BigInt r(sig, q_bytes); BigInt s(sig + q_bytes, q_bytes); BigInt i = BigInt::from_bytes_with_max_bits(msg, msg_len, m_group.q_bits()); if(r <= 0 || r >= q || s <= 0 || s >= q) return false; s = inverse_mod(s, q); const BigInt sr = m_group.multiply_mod_q(s, r); const BigInt si = m_group.multiply_mod_q(s, i); s = m_group.multi_exponentiate(si, m_y, sr); // s is too big for Barrett, and verification doesn't need to be const-time return (s % m_group.get_q() == r); } } std::unique_ptr<PK_Ops::Verification> DSA_PublicKey::create_verification_op(const std::string& params, const std::string& provider) const { if(provider == "base" || provider.empty()) return std::make_unique<DSA_Verification_Operation>(*this, params); throw Provider_Not_Found(algo_name(), provider); } std::unique_ptr<PK_Ops::Signature> DSA_PrivateKey::create_signature_op(RandomNumberGenerator& rng, const std::string& params, const std::string& provider) const { if(provider == "base" || provider.empty()) return std::make_unique<DSA_Signature_Operation>(*this, params, rng); throw Provider_Not_Found(algo_name(), provider); } } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // alSoundMgr.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "alSoundMgr.h" #include "Core/Log.h" #include "Core/Assert.h" #include "Core/String/StringBuilder.h" namespace Oryol { namespace Synth { using namespace Core; //------------------------------------------------------------------------------ alSoundMgr::alSoundMgr() : alcDevice(nullptr), alcContext(nullptr) { // empty } //------------------------------------------------------------------------------ alSoundMgr::~alSoundMgr() { o_assert_dbg(nullptr == this->alcDevice); o_assert_dbg(nullptr == this->alcContext); } //------------------------------------------------------------------------------ void alSoundMgr::Setup(const SynthSetup& setupAttrs) { o_assert_dbg(!this->isValid); o_assert_dbg(nullptr == this->alcDevice); o_assert_dbg(nullptr == this->alcContext); soundMgrBase::Setup(setupAttrs); // setup an OpenAL context and make it current this->alcDevice = alcOpenDevice(NULL); if (NULL == this->alcDevice) { Log::Warn("alcOpenDevice() failed!\n"); return; } this->alcContext = alcCreateContext(this->alcDevice, NULL); if (NULL == this->alcDevice) { Log::Warn("alcCreateContext() failed!\n"); return; } if (!alcMakeContextCurrent(this->alcContext)) { Log::Warn("alcMakeContextCurrent() failed!\n"); return; } // output some information about this OpenAL implementation const ALCchar* str = alcGetString(this->alcDevice, ALC_DEVICE_SPECIFIER); if (str) { Log::Info("ALC_DEVICE_SPECIFIER: %s\n", str); } str = alcGetString(this->alcDevice, ALC_EXTENSIONS); if (str) { StringBuilder strBuilder(str); strBuilder.SubstituteAll(" ", "\n"); Log::Info("ALC_EXTENSIONS:\n%s\n", strBuilder.AsCStr()); } } //------------------------------------------------------------------------------ void alSoundMgr::Discard() { o_assert_dbg(this->isValid); if (nullptr != this->alcContext) { alcDestroyContext(this->alcContext); this->alcContext = nullptr; } if (nullptr != this->alcDevice) { alcCloseDevice(this->alcDevice); this->alcDevice = nullptr; } soundMgrBase::Discard(); } } // namespace Synth } // namespace Oryol<commit_msg>Fixed small bug in OpenGL init<commit_after>//------------------------------------------------------------------------------ // alSoundMgr.cc //------------------------------------------------------------------------------ #include "Pre.h" #include "alSoundMgr.h" #include "Core/Log.h" #include "Core/Assert.h" #include "Core/String/StringBuilder.h" namespace Oryol { namespace Synth { using namespace Core; //------------------------------------------------------------------------------ alSoundMgr::alSoundMgr() : alcDevice(nullptr), alcContext(nullptr) { // empty } //------------------------------------------------------------------------------ alSoundMgr::~alSoundMgr() { o_assert_dbg(nullptr == this->alcDevice); o_assert_dbg(nullptr == this->alcContext); } //------------------------------------------------------------------------------ void alSoundMgr::Setup(const SynthSetup& setupAttrs) { o_assert_dbg(!this->isValid); o_assert_dbg(nullptr == this->alcDevice); o_assert_dbg(nullptr == this->alcContext); soundMgrBase::Setup(setupAttrs); // setup an OpenAL context and make it current this->alcDevice = alcOpenDevice(NULL); if (NULL == this->alcDevice) { Log::Warn("alcOpenDevice() failed!\n"); return; } this->alcContext = alcCreateContext(this->alcDevice, NULL); if (NULL == this->alcContext) { Log::Warn("alcCreateContext() failed!\n"); return; } if (!alcMakeContextCurrent(this->alcContext)) { Log::Warn("alcMakeContextCurrent() failed!\n"); return; } // output some information about this OpenAL implementation const ALCchar* str = alcGetString(this->alcDevice, ALC_DEVICE_SPECIFIER); if (str) { Log::Info("ALC_DEVICE_SPECIFIER: %s\n", str); } str = alcGetString(this->alcDevice, ALC_EXTENSIONS); if (str) { StringBuilder strBuilder(str); strBuilder.SubstituteAll(" ", "\n"); Log::Info("ALC_EXTENSIONS:\n%s\n", strBuilder.AsCStr()); } } //------------------------------------------------------------------------------ void alSoundMgr::Discard() { o_assert_dbg(this->isValid); if (nullptr != this->alcContext) { alcDestroyContext(this->alcContext); this->alcContext = nullptr; } if (nullptr != this->alcDevice) { alcCloseDevice(this->alcDevice); this->alcDevice = nullptr; } soundMgrBase::Discard(); } } // namespace Synth } // namespace Oryol<|endoftext|>
<commit_before>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2016 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : hugh/render/software/pipeline/fixed.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // include i/f header #include "hugh/render/software/pipeline/fixed.hpp" // includes, system #include <sstream> // std::ostringstream #include <stdexcept> // std::logic_error // includes, project //#include <> #define HUGH_USE_TRACE #undef HUGH_USE_TRACE #include <hugh/support/trace.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) // variables, internal // functions, internal } // namespace { namespace hugh { namespace render { namespace software { namespace pipeline { // variables, exported // functions, exported /* explicit */ fixed::fixed() : base() { TRACE("hugh::render::software::pipeline::fixed::fixed"); } /* virtual */ fixed::~fixed() { TRACE("hugh::render::software::pipeline::fixed::~fixed"); } /* virtual */ void fixed::process(primitive::base const& p) { TRACE("hugh::render::software::pipeline::fixed::process(" + std::to_string(unsigned(p.topology)) + ")"); using topology = primitive::topology; statistics lstats; vertex_list_type vertices; vertices.reserve(p.vertices.size()); for (auto const& v : p.vertices) { vertices.push_back(transform(v)); } lstats.vertices.processed += vertices.size(); fragment_list_type fragments; switch (p.topology) { case topology::point_list: fragments = raster<topology::point_list> (p.indices, vertices); break; case topology::line_list: fragments = raster<topology::line_list> (p.indices, vertices); break; case topology::line_strip: fragments = raster<topology::line_strip> (p.indices, vertices); break; case topology::triangle_list: fragments = raster<topology::triangle_list> (p.indices, vertices); break; case topology::triangle_strip: fragments = raster<topology::triangle_strip>(p.indices, vertices); break; default: { std::ostringstream ostr; ostr << "<hugh::render::software::pipeline::fixed::process>: " << "unrecognized primitive topology (" << unsigned(p.topology) << ")"; throw std::logic_error(ostr.str()); } break; } lstats.fragments.created += fragments.size(); for (auto const& f : fragments) { if (!(*depthbuffer)->zcull(f)) { fragment const fs(shade(f)); ++lstats.fragments.shaded; if ((*depthbuffer)->ztest(fs)) { (*colorbuffer)->update(fs); ++lstats.fragments.updated; } } } const_cast<statistics&>(*stats) += lstats; #if 1 { std::cout << support::trace::prefix() // << "hugh::render::software::pipeline::fixed::process: " << (p.indices.empty() ? "!" : " ") << "idx " << p.topology << " \t" << lstats << '\t' << *stats << '\n'; } #endif } vertex fixed::transform(vertex const& v) const { TRACE("hugh::render::software::pipeline::fixed::transform"); glm::vec4 const vh(v.position, 1); return vertex(clip_to_ndc(eye_to_clip(world_to_eye(object_to_world(vh)))), v.attributes); } fragment fixed::shade(fragment const& f) const { TRACE("hugh::render::software::pipeline::fixed::shade"); attribute::list attr (f.attributes); auto found(attr.find(attribute::type::color)); if (attr.end() == found) { attr[attribute::type::color] = glm::vec4(1, 1, 1, 0); } return fragment(f.position, f.depth, attr); } } // namespace pipeline { } // namespace software { } // namespace render { } // namespace hugh { <commit_msg>added: rudimentary phong-shading evaluation<commit_after>// -*- Mode:C++ -*- /**************************************************************************************************/ /* */ /* Copyright (C) 2016 University of Hull */ /* */ /**************************************************************************************************/ /* */ /* module : hugh/render/software/pipeline/fixed.cpp */ /* project : */ /* description: */ /* */ /**************************************************************************************************/ // include i/f header #include "hugh/render/software/pipeline/fixed.hpp" // includes, system #include <sstream> // std::ostringstream #include <stdexcept> // std::logic_error // includes, project //#include <> #define HUGH_USE_TRACE #undef HUGH_USE_TRACE #include <hugh/support/trace.hpp> // internal unnamed namespace namespace { // types, internal (class, enum, struct, union, typedef) // variables, internal // functions, internal } // namespace { namespace hugh { namespace render { namespace software { namespace pipeline { // variables, exported // functions, exported /* explicit */ fixed::fixed() : base() { TRACE("hugh::render::software::pipeline::fixed::fixed"); } /* virtual */ fixed::~fixed() { TRACE("hugh::render::software::pipeline::fixed::~fixed"); } /* virtual */ void fixed::process(primitive::base const& p) { TRACE("hugh::render::software::pipeline::fixed::process(" + std::to_string(unsigned(p.topology)) + ")"); using topology = primitive::topology; statistics lstats; vertex_list_type vertices; vertices.reserve(p.vertices.size()); for (auto const& v : p.vertices) { vertices.push_back(transform(v)); } lstats.vertices.processed += vertices.size(); fragment_list_type fragments; switch (p.topology) { case topology::point_list: fragments = raster<topology::point_list> (p.indices, vertices); break; case topology::line_list: fragments = raster<topology::line_list> (p.indices, vertices); break; case topology::line_strip: fragments = raster<topology::line_strip> (p.indices, vertices); break; case topology::triangle_list: fragments = raster<topology::triangle_list> (p.indices, vertices); break; case topology::triangle_strip: fragments = raster<topology::triangle_strip>(p.indices, vertices); break; default: { std::ostringstream ostr; ostr << "<hugh::render::software::pipeline::fixed::process>: " << "unrecognized primitive topology (" << unsigned(p.topology) << ")"; throw std::logic_error(ostr.str()); } break; } lstats.fragments.created += fragments.size(); for (auto const& f : fragments) { if (!(*depthbuffer)->zcull(f)) { fragment const fs(shade(f)); ++lstats.fragments.shaded; if ((*depthbuffer)->ztest(fs)) { (*colorbuffer)->update(fs); ++lstats.fragments.updated; } } } const_cast<statistics&>(*stats) += lstats; #if 1 { std::cout << support::trace::prefix() // << "hugh::render::software::pipeline::fixed::process: " << (p.indices.empty() ? "!" : " ") << "idx " << p.topology << " \t" << lstats << '\t' << *stats << '\n'; } #endif } vertex fixed::transform(vertex const& v) const { TRACE("hugh::render::software::pipeline::fixed::transform"); glm::vec4 const vh(v.position, 1); return vertex(clip_to_ndc(eye_to_clip(world_to_eye(object_to_world(vh)))), v.attributes); } fragment fixed::shade(fragment const& f) const { TRACE("hugh::render::software::pipeline::fixed::shade"); attribute::list attr(f.attributes); if (nullptr != *material) { glm::vec3 const P; glm::vec3 const N; glm::mat4 const C; glm::vec3 laccum_ambient (0,0,0); glm::vec3 laccum_diffuse (0,0,0); glm::vec3 laccum_specular(0,0,0); for (auto const& l : *lights) { if (l.active) { glm::vec3 L; float att(1.0); L = glm::normalize(L); float const NdotL(std::max(glm::dot(N, L), 0.0f)); if (0.0 < NdotL) { float const exp (glm::clamp((*material)->shininess, 0.0f, 128.0f)); glm::vec3 const V (C[3].xyz() - P); glm::vec3 const H (L + V); float const NdotV(std::max(glm::dot(N, V), 0.0f)); float const NdotH(std::max(glm::dot(N, H), 0.0f)); // glm::vec4 const lresult(lit(NdotL, NdotH, exp)); // laccum_diffuse += (att * l.diffuse * lresult.y); // laccum_specular += (att * l.specular * lresult.z); } laccum_ambient += att * l.ambient; } } glm::vec4 result((*material)->emission, (*material)->alpha); result.rgb() += laccum_ambient * (*material)->ambient; result.rgb() += laccum_diffuse * (*material)->diffuse; result.rgb() += laccum_specular * (*material)->specular; attr[attribute::type::color] = result; } else { auto found(attr.find(attribute::type::color)); if (attr.end() == found) { attr[attribute::type::color] = glm::vec4(1, 1, 1, 0); } } return fragment(f.position, f.depth, attr); } } // namespace pipeline { } // namespace software { } // namespace render { } // namespace hugh { <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/l10n_util.h" #include "base/command_line.h" #include "base/string16.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" namespace { class OptionsUITest : public UITest { public: OptionsUITest() { dom_automation_enabled_ = true; // TODO(csilv): Remove when dom-ui options is enabled by default. launch_arguments_.AppendSwitch(switches::kEnableTabbedOptions); } void AssertIsOptionsPage(TabProxy* tab) { std::wstring title; ASSERT_TRUE(tab->GetTabTitle(&title)); string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE); ASSERT_EQ(expected_title, WideToUTF16Hack(title)); } }; TEST_F(OptionsUITest, LoadOptionsByURL) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); // Go to the options tab via URL. NavigateToURL(GURL(chrome::kChromeUISettingsURL)); AssertIsOptionsPage(tab); } TEST_F(OptionsUITest, CommandOpensOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); } // TODO(csilv): Investigate why this fails and fix. http://crbug.com/48521 TEST_F(OptionsUITest, FLAKY_CommandAgainGoesBackToOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); // Switch to first tab and run command again. ASSERT_TRUE(browser->ActivateTab(0)); ASSERT_TRUE(browser->WaitForTabToBecomeActive(0, action_max_timeout_ms())); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); // Ensure the options ui tab is active. ASSERT_TRUE(browser->WaitForTabToBecomeActive(1, action_max_timeout_ms())); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } // TODO(csilv): Investigate why this fails (sometimes) on 10.5 and fix. // http://crbug.com/48521 TEST_F(OptionsUITest, FLAKY_TwoCommandsOneTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } } // namespace <commit_msg>Marking two OptionsUITests (TwoCommandsOneTab & CommandAgainGoesBackToOptionsTab) as DISALBED because of linux/views crashes<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/l10n_util.h" #include "base/command_line.h" #include "base/string16.h" #include "base/utf_string_conversions.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/url_constants.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" namespace { class OptionsUITest : public UITest { public: OptionsUITest() { dom_automation_enabled_ = true; // TODO(csilv): Remove when dom-ui options is enabled by default. launch_arguments_.AppendSwitch(switches::kEnableTabbedOptions); } void AssertIsOptionsPage(TabProxy* tab) { std::wstring title; ASSERT_TRUE(tab->GetTabTitle(&title)); string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE); ASSERT_EQ(expected_title, WideToUTF16Hack(title)); } }; TEST_F(OptionsUITest, LoadOptionsByURL) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); // Go to the options tab via URL. NavigateToURL(GURL(chrome::kChromeUISettingsURL)); AssertIsOptionsPage(tab); } TEST_F(OptionsUITest, CommandOpensOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); } // TODO(csilv): Investigate why this fails and fix. http://crbug.com/48521 // Also, crashing on linux/views. #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) #define MAYBE_CommandAgainGoesBackToOptionsTab \ DISABLED_CommandAgainGoesBackToOptionsTab #else #define MAYBE_CommandAgainGoesBackToOptionsTab \ FLAKY_CommandAgainGoesBackToOptionsTab #endif TEST_F(OptionsUITest, MAYBE_CommandAgainGoesBackToOptionsTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Bring up the options tab via command. ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); scoped_refptr<TabProxy> tab = browser->GetActiveTab(); ASSERT_TRUE(tab.get()); AssertIsOptionsPage(tab); // Switch to first tab and run command again. ASSERT_TRUE(browser->ActivateTab(0)); ASSERT_TRUE(browser->WaitForTabToBecomeActive(0, action_max_timeout_ms())); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); // Ensure the options ui tab is active. ASSERT_TRUE(browser->WaitForTabToBecomeActive(1, action_max_timeout_ms())); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } // TODO(csilv): Investigate why this fails (sometimes) on 10.5 and fix. // http://crbug.com/48521. Also, crashing on linux/views. #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) #define MAYBE_TwoCommandsOneTab DISABLED_TwoCommandsOneTab #else #define MAYBE_TwoComamndsOneTab FLAKY_TwoCommandsOneTab #endif TEST_F(OptionsUITest, MAYBE_TwoCommandsOneTab) { scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); ASSERT_TRUE(browser.get()); int tab_count = -1; ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->RunCommand(IDC_OPTIONS)); ASSERT_TRUE(browser->GetTabCount(&tab_count)); ASSERT_EQ(2, tab_count); } } // namespace <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Pavel Vainerman. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, version 2.1. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // -------------------------------------------------------------------------- /*! \file * \author Pavel Vainerman */ // -------------------------------------------------------------------------- #include <sstream> #include <cstdio> #include "UniSetTypes.h" #include "SQLiteInterface.h" // -------------------------------------------------------------------------- using namespace std; using namespace uniset; // -------------------------------------------------------------------------- SQLiteInterface::SQLiteInterface(): db(0), lastQ(""), lastE(""), queryok(false), connected(false), opTimeout(300), opCheckPause(50) { } SQLiteInterface::~SQLiteInterface() { try { close(); } catch( ... ) // пропускаем все необработанные исключения, если требуется обработать нужно вызывать close() до деструктора { std::exception_ptr p = std::current_exception(); cerr << "(SQLiteInterface::~SQLiteInterface): " << (p ? p.__cxa_exception_type()->name() : "an error occured while closing connection!") << std::endl; } } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::ping() const { return db && ( sqlite3_db_status(db, 0, NULL, NULL, 0) == SQLITE_OK ); } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::connect( const std::string& param ) { std::string dbfile; std::string::size_type pos = param.find_first_of(":"); dbfile = param.substr(0, pos); if( pos != std::string::npos ) { std::string create_str = param.substr(pos + 1, std::string::npos); if( create_str == "true" ) return connect( dbfile, true ); } return connect( dbfile, false ); } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::connect( const string& dbfile, bool create, int extra_sqlite_flags ) { // т.к. sqlite3 по умолчанию, создаёт файл при открытии, то проверим "сами" // if( !create && !uniset::file_exist(dbfile) ) // return false; if( db && ping() ) return true; int flags = create ? 0 : SQLITE_OPEN_READWRITE; if( extra_sqlite_flags ) flags |= extra_sqlite_flags; int rc = sqlite3_open_v2(dbfile.c_str(), &db, flags, NULL); if( rc != SQLITE_OK ) { // cerr << "SQLiteInterface::connect): rc=" << rc << " error: " << sqlite3_errmsg(db) << endl; lastE = "open '" + dbfile + "' error: " + string(sqlite3_errmsg(db)); sqlite3_close(db); db = 0; connected = false; return false; } setOperationTimeout(opTimeout); connected = true; return true; } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::close() { if( db ) { sqlite3_close(db); db = 0; } return true; } // ----------------------------------------------------------------------------------------- void SQLiteInterface::setOperationTimeout( timeout_t msec ) { opTimeout = msec; if( db ) sqlite3_busy_timeout(db, opTimeout); } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::insert( const string& q ) { if( !db ) return false; // char* errmsg; sqlite3_stmt* pStmt; // Компилируем SQL запрос if( sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL) != SQLITE_OK ) { queryok = false; return false; } int rc = sqlite3_step(pStmt); if( !checkResult(rc) && !wait(pStmt, SQLITE_DONE) ) { sqlite3_finalize(pStmt); queryok = false; return false; } sqlite3_finalize(pStmt); queryok = true; return true; } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::checkResult( int rc ) { if( rc == SQLITE_BUSY || rc == SQLITE_LOCKED || rc == SQLITE_INTERRUPT || rc == SQLITE_IOERR ) return false; return true; } // ----------------------------------------------------------------------------------------- DBResult SQLiteInterface::query( const string& q ) { if( !db ) return DBResult(); // char* errmsg = 0; sqlite3_stmt* pStmt; // Компилируем SQL запрос sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL); int rc = sqlite3_step(pStmt); if( !checkResult(rc) && !wait(pStmt, SQLITE_ROW) ) { sqlite3_finalize(pStmt); queryok = false; return DBResult(); } lastQ = q; queryok = true; return makeResult(pStmt, true); } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::wait( sqlite3_stmt* stmt, int result ) { PassiveTimer ptTimeout(opTimeout); while( !ptTimeout.checkTime() ) { sqlite3_reset(stmt); int rc = sqlite3_step(stmt); if( rc == result || rc == SQLITE_DONE ) return true; msleep(opCheckPause); } return false; } // ----------------------------------------------------------------------------------------- const string SQLiteInterface::error() { if( db ) { int errcode = sqlite3_errcode(db); lastE = ( errcode == SQLITE_OK ) ? "" : sqlite3_errmsg(db); } return lastE; } // ----------------------------------------------------------------------------------------- const string SQLiteInterface::lastQuery() { return lastQ; } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::lastQueryOK() const { return queryok; } // ----------------------------------------------------------------------------------------- double SQLiteInterface::insert_id() { if( !db ) return 0; return sqlite3_last_insert_rowid(db); } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::isConnection() const { return connected; } // ----------------------------------------------------------------------------------------- DBResult SQLiteInterface::makeResult( sqlite3_stmt* s, bool finalize ) { DBResult result; if( !s ) { if( finalize ) sqlite3_finalize(s); return result; } do { int n = sqlite3_data_count(s); if( n <= 0 ) { if( finalize ) sqlite3_finalize(s); return result; } DBResult::COL c; for( int i = 0; i < n; i++ ) { const char* p = (const char*)sqlite3_column_text(s, i); if( p ) { const char* cname = (const char*)sqlite3_column_name(s, i); if( cname ) result.setColName(i, cname); c.emplace_back(p); } else c.emplace_back(""); } result.row().emplace_back(c); } while( sqlite3_step(s) == SQLITE_ROW ); if( finalize ) sqlite3_finalize(s); return result; } // ----------------------------------------------------------------------------------------- extern "C" std::shared_ptr<DBInterface> create_sqliteinterface() { return std::shared_ptr<DBInterface>(new SQLiteInterface(), DBInterfaceDeleter()); } // ----------------------------------------------------------------------------------------- <commit_msg>(sqlite): minor fix<commit_after>/* * Copyright (c) 2015 Pavel Vainerman. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, version 2.1. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // -------------------------------------------------------------------------- /*! \file * \author Pavel Vainerman */ // -------------------------------------------------------------------------- #include <sstream> #include <cstdio> #include "UniSetTypes.h" #include "SQLiteInterface.h" // -------------------------------------------------------------------------- using namespace std; using namespace uniset; // -------------------------------------------------------------------------- SQLiteInterface::SQLiteInterface(): db(0), lastQ(""), lastE(""), queryok(false), connected(false), opTimeout(300), opCheckPause(50) { } SQLiteInterface::~SQLiteInterface() { try { close(); } catch( ... ) // пропускаем все необработанные исключения, если требуется обработать нужно вызывать close() до деструктора { std::exception_ptr p = std::current_exception(); cerr << "(SQLiteInterface::~SQLiteInterface): " << (p ? p.__cxa_exception_type()->name() : "an error occured while closing connection!") << std::endl; } } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::ping() const { return db && ( sqlite3_db_status(db, 0, NULL, NULL, 0) == SQLITE_OK ); } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::connect( const std::string& param ) { std::string dbfile; std::string::size_type pos = param.find_first_of(":"); dbfile = param.substr(0, pos); if( pos != std::string::npos ) { std::string create_str = param.substr(pos + 1, std::string::npos); if( create_str == "true" ) return connect( dbfile, true ); } return connect( dbfile, false ); } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::connect( const string& dbfile, bool create, int extra_sqlite_flags ) { // т.к. sqlite3 по умолчанию, создаёт файл при открытии, то проверим "сами" // if( !create && !uniset::file_exist(dbfile) ) // return false; if( db && ping() ) return true; if( db ) close(); int flags = create ? 0 : SQLITE_OPEN_READWRITE; if( extra_sqlite_flags ) flags |= extra_sqlite_flags; int rc = sqlite3_open_v2(dbfile.c_str(), &db, flags, NULL); if( rc != SQLITE_OK ) { // cerr << "SQLiteInterface::connect): rc=" << rc << " error: " << sqlite3_errmsg(db) << endl; lastE = "open '" + dbfile + "' error: " + string(sqlite3_errmsg(db)); sqlite3_close(db); db = 0; connected = false; return false; } setOperationTimeout(opTimeout); connected = true; return true; } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::close() { if( db ) { sqlite3_close(db); db = 0; } return true; } // ----------------------------------------------------------------------------------------- void SQLiteInterface::setOperationTimeout( timeout_t msec ) { opTimeout = msec; if( db ) sqlite3_busy_timeout(db, opTimeout); } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::insert( const string& q ) { if( !db ) return false; // char* errmsg; sqlite3_stmt* pStmt; // Компилируем SQL запрос if( sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL) != SQLITE_OK ) { queryok = false; return false; } int rc = sqlite3_step(pStmt); if( !checkResult(rc) && !wait(pStmt, SQLITE_DONE) ) { sqlite3_finalize(pStmt); queryok = false; return false; } sqlite3_finalize(pStmt); queryok = true; return true; } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::checkResult( int rc ) { if( rc == SQLITE_BUSY || rc == SQLITE_LOCKED || rc == SQLITE_INTERRUPT || rc == SQLITE_IOERR ) return false; return true; } // ----------------------------------------------------------------------------------------- DBResult SQLiteInterface::query( const string& q ) { if( !db ) return DBResult(); // char* errmsg = 0; sqlite3_stmt* pStmt; // Компилируем SQL запрос sqlite3_prepare(db, q.c_str(), -1, &pStmt, NULL); int rc = sqlite3_step(pStmt); if( !checkResult(rc) && !wait(pStmt, SQLITE_ROW) ) { sqlite3_finalize(pStmt); queryok = false; return DBResult(); } lastQ = q; queryok = true; return makeResult(pStmt, true); } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::wait( sqlite3_stmt* stmt, int result ) { PassiveTimer ptTimeout(opTimeout); while( !ptTimeout.checkTime() ) { sqlite3_reset(stmt); int rc = sqlite3_step(stmt); if( rc == result || rc == SQLITE_DONE ) return true; msleep(opCheckPause); } return false; } // ----------------------------------------------------------------------------------------- const string SQLiteInterface::error() { if( db ) { int errcode = sqlite3_errcode(db); lastE = ( errcode == SQLITE_OK ) ? "" : sqlite3_errmsg(db); } return lastE; } // ----------------------------------------------------------------------------------------- const string SQLiteInterface::lastQuery() { return lastQ; } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::lastQueryOK() const { return queryok; } // ----------------------------------------------------------------------------------------- double SQLiteInterface::insert_id() { if( !db ) return 0; return sqlite3_last_insert_rowid(db); } // ----------------------------------------------------------------------------------------- bool SQLiteInterface::isConnection() const { return connected; } // ----------------------------------------------------------------------------------------- DBResult SQLiteInterface::makeResult( sqlite3_stmt* s, bool finalize ) { DBResult result; if( !s ) { if( finalize ) sqlite3_finalize(s); return result; } do { int n = sqlite3_data_count(s); if( n <= 0 ) { if( finalize ) sqlite3_finalize(s); return result; } DBResult::COL c; for( int i = 0; i < n; i++ ) { const char* p = (const char*)sqlite3_column_text(s, i); if( p ) { const char* cname = (const char*)sqlite3_column_name(s, i); if( cname ) result.setColName(i, cname); c.emplace_back(p); } else c.emplace_back(""); } result.row().emplace_back(c); } while( sqlite3_step(s) == SQLITE_ROW ); if( finalize ) sqlite3_finalize(s); return result; } // ----------------------------------------------------------------------------------------- extern "C" std::shared_ptr<DBInterface> create_sqliteinterface() { return std::shared_ptr<DBInterface>(new SQLiteInterface(), DBInterfaceDeleter()); } // ----------------------------------------------------------------------------------------- <|endoftext|>
<commit_before>/* * RBWindControl.cpp * golf * * Created by Robert Rose on 10/30/08. * Copyright 2008 Bork 3D LLC. All rights reserved. * */ #include "RBWindControl.h" #include "RudeGL.h" #include "RudeDebug.h" RBWindControl::RBWindControl() : m_windSpeed(0.0f) , m_windVec(0,0,0) , m_animTimer(0.0f) , m_indicatorYaw(0.0f) , m_indicatorYawTwitch(0.0f) { m_windObject.LoadMesh("wind_indicator"); } void RBWindControl::SetWind(float windDir, float windSpeed) { m_indicatorYaw = windDir * 180.0f / 3.1415926f; m_windSpeed = windSpeed; } void RBWindControl::NextFrame(float delta) { m_animTimer += delta; const float kTwitchMax = 8.0f; if(m_twitchUp) { m_indicatorYawTwitch += delta * m_windSpeed; if(m_indicatorYawTwitch > kTwitchMax) { m_indicatorYawTwitch = kTwitchMax; m_twitchUp = false; } } else { m_indicatorYawTwitch -= delta * m_windSpeed; if(m_indicatorYawTwitch < -kTwitchMax) { m_indicatorYawTwitch = -kTwitchMax; m_twitchUp = true; } } } void RBWindControl::Render() { RGL.SetViewport(m_rect.m_top, m_rect.m_left, m_rect.m_bottom, m_rect.m_right); btVector3 eyevec = RGL.GetForward(); eyevec.setY(0.0f); eyevec.normalize(); eyevec.setY(1.0f); eyevec *= 5.0f; RGL.Frustum(0.0f, 0.0f, 0.2f, 0.2f, 1.0f, 10.0f); RGL.LookAt(eyevec.x(), eyevec.y(), eyevec.z(), 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); RGL.LoadIdentity(); m_indicatorYawTwitch = 0; RGL.Rotate(m_indicatorYaw + m_indicatorYawTwitch, 0.0f, 1.0f, 0.0f); m_windObject.Render(); } <commit_msg>fixed wind indicator bug.. yikes we shipped with this!<commit_after>/* * RBWindControl.cpp * golf * * Created by Robert Rose on 10/30/08. * Copyright 2008 Bork 3D LLC. All rights reserved. * */ #include "RBWindControl.h" #include "RudeGL.h" #include "RudeDebug.h" RBWindControl::RBWindControl() : m_windSpeed(0.0f) , m_windVec(0,0,0) , m_animTimer(0.0f) , m_indicatorYaw(0.0f) , m_indicatorYawTwitch(0.0f) { m_windObject.LoadMesh("wind_indicator"); } void RBWindControl::SetWind(float windDir, float windSpeed) { m_indicatorYaw = windDir * 180.0f / 3.1415926f; m_windSpeed = windSpeed; } void RBWindControl::NextFrame(float delta) { m_animTimer += delta; const float kTwitchMax = 8.0f; if(m_twitchUp) { m_indicatorYawTwitch += delta * m_windSpeed; if(m_indicatorYawTwitch > kTwitchMax) { m_indicatorYawTwitch = kTwitchMax; m_twitchUp = false; } } else { m_indicatorYawTwitch -= delta * m_windSpeed; if(m_indicatorYawTwitch < -kTwitchMax) { m_indicatorYawTwitch = -kTwitchMax; m_twitchUp = true; } } } void RBWindControl::Render() { RGL.SetViewport(m_rect.m_top, m_rect.m_left, m_rect.m_bottom, m_rect.m_right); btVector3 eyevec = RGL.GetForward(); eyevec.setY(0.0f); eyevec.normalize(); eyevec.setY(1.0f); eyevec *= 5.0f; RGL.Frustum(0.0f, 0.0f, 0.2f, 0.2f, 1.0f, 10.0f); RGL.LookAt(eyevec.x(), eyevec.y(), eyevec.z(), 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); RGL.LoadIdentity(); RGL.Rotate(m_indicatorYaw + m_indicatorYawTwitch, 0.0f, 1.0f, 0.0f); m_windObject.Render(); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/notifications/desktop_notification_service.h" #include "chrome/browser/notifications/desktop_notification_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, NotificationsNoPermission) { #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) // Notifications not supported on linux/views yet. #else ASSERT_TRUE(RunExtensionTest("notifications/has_not_permission")) << message_; #endif } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, NotificationsHasPermissionManifest) { #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) // Notifications not supported on linux/views yet. #else ASSERT_TRUE(RunExtensionTest("notifications/has_permission_manifest")) << message_; #endif } // http://crbug.com/98061 #if defined(OS_MACOSX) || defined(OS_LINUX) #define MAYBE_NotificationsHasPermission DISABLED_NotificationsHasPermission #else #define MAYBE_NotificationsHasPermission NotificationsHasPermission #endif IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_NotificationsHasPermission) { #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) // Notifications not supported on linux/views yet. #else DesktopNotificationServiceFactory::GetForProfile(browser()->profile()) ->GrantPermission(GURL( "chrome-extension://peoadpeiejnhkmpaakpnompolbglelel")); ASSERT_TRUE(RunExtensionTest("notifications/has_permission_prefs")) << message_; #endif } <commit_msg>Mark notifications api tests as DISABLED<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/notifications/desktop_notification_service.h" #include "chrome/browser/notifications/desktop_notification_service_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_NotificationsNoPermission) { #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) // Notifications not supported on linux/views yet. #else ASSERT_TRUE(RunExtensionTest("notifications/has_not_permission")) << message_; #endif } IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_NotificationsHasPermissionManifest) { #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) // Notifications not supported on linux/views yet. #else ASSERT_TRUE(RunExtensionTest("notifications/has_permission_manifest")) << message_; #endif } // http://crbug.com/98061 IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_NotificationsHasPermission) { #if defined(OS_LINUX) && defined(TOOLKIT_VIEWS) // Notifications not supported on linux/views yet. #else DesktopNotificationServiceFactory::GetForProfile(browser()->profile()) ->GrantPermission(GURL( "chrome-extension://peoadpeiejnhkmpaakpnompolbglelel")); ASSERT_TRUE(RunExtensionTest("notifications/has_permission_prefs")) << message_; #endif } <|endoftext|>
<commit_before>#ifndef MANIFOLDS_POLYNOMIAL_HH #define MANIFOLDS_POLYNOMIAL_HH #include "full_function_defs.hh" #include "function.hh" #include <ratio> #include <array> #include <type_traits> #include <ostream> #include <iostream> namespace manifolds { //Somewhat confusingly, //order here refers to the number of coefficients template <class CoeffType, class Order> struct PolynomialImpl : Function { static const int num_coeffs = Order::value; static const bool stateless = false; template <class Type, std::size_t N> PolynomialImpl(std::array<Type, N> t): coeffs(t){} template <class T> auto operator()(T t) const { typename std::common_type< T,CoeffType>::type result = 0, t2 = t; for(auto i = coeffs.rbegin(); i != coeffs.rend(); i++) { result = result * t2 + *i; } return result; } const auto & GetCoeffs() const { return coeffs; } void Print(std::ostream & s) const { s << "Polynomial("; for(int i = 0; i < Order::value; i++) { s << coeffs[i]; if(i != Order::value-1) s << ' '; } s << ")"; } private: std::array<CoeffType,Order::value> coeffs; }; DEF_FF_TEMPLATE(Polynomial) template <class CType, int N> std::ostream & operator<<(std::ostream & s, Polynomial<CType,int_<N>> p) { p.Print(s); return s; } inline Polynomial<long double,int_<1>> operator""_c(long double x) { std::array<long double, 1> a{{x}}; return {a}; } inline Polynomial<long long unsigned,int_<1>> operator""_c(long long unsigned x) { std::array<long long unsigned, 1> a{{x}}; return {a}; } template <class ... InputTypes> auto GetPolynomial(InputTypes ... coeffs) { typedef typename std::common_type< double,InputTypes...>::type coeff_type; std::array<coeff_type, sizeof...(InputTypes)> coeff_arr{{coeff_type(coeffs)...}}; return Polynomial< coeff_type, int_< sizeof...(InputTypes)>>(coeff_arr); } } #include "simplify.hh" #include "addition.hh" #include "multiplication.hh" #include "zero.hh" #include "unary_minus.hh" namespace manifolds { template <int order1, int order2, class CoeffType1, class CoeffType2> struct Simplification<Addition< Polynomial<CoeffType1, int_<order1>>, Polynomial<CoeffType2, int_<order2>>>> { static const int new_order = order1 > order2 ? order1 : order2; typedef typename std::common_type< CoeffType1, CoeffType2>::type coeff_type; typedef Polynomial< coeff_type, int_< new_order>> type; template <class T1, class T2> static auto Init(const T1 & t1, const T2&, std::true_type) { return t1.GetCoeffs(); } template <class T1, class T2> static auto Init(const T1& , const T2& t2, std::false_type) { return t2.GetCoeffs(); } static type Combine(Addition<Polynomial< CoeffType1, int_<order1>>, Polynomial< CoeffType2, int_<order2>>> p) { auto p1 = std::get<0>(p.GetFunctions()); auto p2 = std::get<1>(p.GetFunctions()); typedef std::integral_constant< bool, (order1>order2)> yes_no; if(order1 > order2) { std::array<coeff_type,new_order> r = Init(p1,p2,yes_no()); for(unsigned i = 0; i < order2; i++) r[i] += p2.GetCoeffs()[i]; return {r}; } else { std::array<coeff_type,new_order> r = Init(p1,p2,yes_no()); for(unsigned i = 0; i < order1; i++) r[i] += p1.GetCoeffs()[i]; return {r}; } } }; template <int order1, int order2, class CoeffType1, class CoeffType2> struct Simplification<Multiplication< Polynomial<CoeffType1, int_<order1>>, Polynomial<CoeffType2, int_<order2>>>> { static const int new_order = order1 + order2 - 1; typedef typename std::common_type< CoeffType1, CoeffType2>::type coeff_type; typedef Polynomial< coeff_type, int_< new_order>> type; static type Combine(Multiplication<Polynomial< CoeffType1, int_<order1>>, Polynomial< CoeffType2, int_<order2>>> p) { auto p1 = std::get<0>(p.GetFunctions()); auto p2 = std::get<1>(p.GetFunctions()); std::array<coeff_type,new_order> r; std::fill(r.begin(), r.end(), 0); for(unsigned j = 0; j < order1; j++) for(unsigned i = 0; i < order2; i++) r[i+j] += p1.GetCoeffs()[j] * p2.GetCoeffs()[i]; return {r}; } }; template <int order1, int order2, class CoeffType1, class CoeffType2> struct Simplification< Composition< Polynomial<CoeffType1,int_<order1>>, Polynomial<CoeffType2,int_<order2>>>> { static const int new_order = (order1-1) * (order2-1) + 1; typedef typename std::common_type< CoeffType1, CoeffType2>::type coeff_type; typedef Polynomial< coeff_type, int_< new_order>> type; template <class T, class U> static auto Multiply(const T & t, const U & u) { return Simplification<Multiplication<T,U>>:: Combine(Multiplication<T,U>(t,u)); } template <class T, class U> static auto Add(const T & t, const U & u) { return Simplification<Addition<T,U>>:: Combine(Addition<T,U>(t,u)); } template <class T, class U> static auto Accumulate(const T & t, const U & u, int_<-1>) { return zero; } template <int index, class T, class U> static auto Accumulate(const T & t, const U & u, int_<index> i) { auto t_coeffs = t.GetCoeffs(); static const int last_coeff = std::tuple_size<decltype(t_coeffs)>::value-1; auto m1 = GetPolynomial(std::get<last_coeff-index>(t_coeffs)); auto m2 = u; auto m3 = Accumulate(t, u, int_<index-1>()); auto m4 = Multiply(m2,m3); return Add(m1,m4); } static auto Combine(Composition<Polynomial< CoeffType1, int_<order1>>, Polynomial< CoeffType2, int_<order2>>> p) { auto p1 = std::get<0>(p.GetFunctions()); auto p2 = std::get<1>(p.GetFunctions()); return Accumulate(p1, p2, int_<order1-1>()); } }; template <class Order, class CoeffType> struct Simplification< UnaryMinus<Polynomial<CoeffType, Order>>> { typedef typename std::conditional< std::is_signed<CoeffType>::value, CoeffType, typename std::make_signed< CoeffType>::type >::type CoeffType2; typedef Polynomial<CoeffType2, Order> type; static type Combine(UnaryMinus<Polynomial< CoeffType, Order>> u) { std::array<CoeffType2, Order::value> a; for(int i = 0; i < Order::value; i++) a[i] = -CoeffType2(u.GetFunction().GetCoeffs()[i]); return {a}; } }; } #include "polynomial_composition_simplifications.hh" #endif <commit_msg>Adding new simplification specialization<commit_after>#ifndef MANIFOLDS_POLYNOMIAL_HH #define MANIFOLDS_POLYNOMIAL_HH #include "full_function_defs.hh" #include "function.hh" #include <ratio> #include <array> #include <type_traits> #include <ostream> #include <iostream> #include <algorithm> namespace manifolds { //Somewhat confusingly, //order here refers to the number of coefficients template <class CoeffType, class Order> struct PolynomialImpl : Function { static const int num_coeffs = Order::value; static const bool stateless = false; template <class Type, std::size_t N> PolynomialImpl(std::array<Type, N> t): coeffs(t){} template <class T> auto operator()(T t) const { typename std::common_type< T,CoeffType>::type result = 0, t2 = t; for(auto i = coeffs.rbegin(); i != coeffs.rend(); i++) { result = result * t2 + *i; } return result; } const auto & GetCoeffs() const { return coeffs; } void Print(std::ostream & s) const { s << "Polynomial("; for(int i = 0; i < Order::value; i++) { s << coeffs[i]; if(i != Order::value-1) s << ' '; } s << ")"; } private: std::array<CoeffType,Order::value> coeffs; }; DEF_FF_TEMPLATE(Polynomial) template <class CType, int N> std::ostream & operator<<(std::ostream & s, Polynomial<CType,int_<N>> p) { p.Print(s); return s; } inline Polynomial<long double,int_<1>> operator""_c(long double x) { std::array<long double, 1> a{{x}}; return {a}; } inline Polynomial<long long unsigned,int_<1>> operator""_c(long long unsigned x) { std::array<long long unsigned, 1> a{{x}}; return {a}; } template <class ... InputTypes> auto GetPolynomial(InputTypes ... coeffs) { typedef typename std::common_type< double,InputTypes...>::type coeff_type; std::array<coeff_type, sizeof...(InputTypes)> coeff_arr{{coeff_type(coeffs)...}}; return Polynomial< coeff_type, int_< sizeof...(InputTypes)>>(coeff_arr); } } #include "simplify.hh" #include "addition.hh" #include "multiplication.hh" #include "zero.hh" #include "unary_minus.hh" namespace manifolds { template <int order1, int order2, class CoeffType1, class CoeffType2> struct Simplification<Addition< Polynomial<CoeffType1, int_<order1>>, Polynomial<CoeffType2, int_<order2>>>> { static const int new_order = order1 > order2 ? order1 : order2; typedef typename std::common_type< CoeffType1, CoeffType2>::type coeff_type; typedef Polynomial< coeff_type, int_< new_order>> type; template <class T1, class T2> static auto Init(const T1 & t1, const T2&, std::true_type) { return t1.GetCoeffs(); } template <class T1, class T2> static auto Init(const T1& , const T2& t2, std::false_type) { return t2.GetCoeffs(); } static type Combine(Addition<Polynomial< CoeffType1, int_<order1>>, Polynomial< CoeffType2, int_<order2>>> p) { auto p1 = std::get<0>(p.GetFunctions()); auto p2 = std::get<1>(p.GetFunctions()); typedef std::integral_constant< bool, (order1>order2)> yes_no; if(order1 > order2) { std::array<coeff_type,new_order> r = Init(p1,p2,yes_no()); for(unsigned i = 0; i < order2; i++) r[i] += p2.GetCoeffs()[i]; return {r}; } else { std::array<coeff_type,new_order> r = Init(p1,p2,yes_no()); for(unsigned i = 0; i < order1; i++) r[i] += p1.GetCoeffs()[i]; return {r}; } } }; template <int order1, int order2, class CoeffType1, class CoeffType2> struct Simplification<Multiplication< Polynomial<CoeffType1, int_<order1>>, Polynomial<CoeffType2, int_<order2>>>> { static const int new_order = order1 + order2 - 1; typedef typename std::common_type< CoeffType1, CoeffType2>::type coeff_type; typedef Polynomial< coeff_type, int_< new_order>> type; static type Combine(Multiplication<Polynomial< CoeffType1, int_<order1>>, Polynomial< CoeffType2, int_<order2>>> p) { auto p1 = std::get<0>(p.GetFunctions()); auto p2 = std::get<1>(p.GetFunctions()); std::array<coeff_type,new_order> r; std::fill(r.begin(), r.end(), 0); for(unsigned j = 0; j < order1; j++) for(unsigned i = 0; i < order2; i++) r[i+j] += p1.GetCoeffs()[j] * p2.GetCoeffs()[i]; return {r}; } }; template <int order1, int order2, class CoeffType1, class CoeffType2> struct Simplification< Composition< Polynomial<CoeffType1,int_<order1>>, Polynomial<CoeffType2,int_<order2>>>> { static const int new_order = (order1-1) * (order2-1) + 1; typedef typename std::common_type< CoeffType1, CoeffType2>::type coeff_type; typedef Polynomial< coeff_type, int_< new_order>> type; template <class T, class U> static auto Multiply(const T & t, const U & u) { return Simplification<Multiplication<T,U>>:: Combine(Multiplication<T,U>(t,u)); } template <class T, class U> static auto Add(const T & t, const U & u) { return Simplification<Addition<T,U>>:: Combine(Addition<T,U>(t,u)); } template <class T, class U> static auto Accumulate(const T & t, const U & u, int_<-1>) { return zero; } template <int index, class T, class U> static auto Accumulate(const T & t, const U & u, int_<index> i) { auto t_coeffs = t.GetCoeffs(); static const int last_coeff = std::tuple_size<decltype(t_coeffs)>::value-1; auto m1 = GetPolynomial(std::get<last_coeff-index>(t_coeffs)); auto m2 = u; auto m3 = Accumulate(t, u, int_<index-1>()); auto m4 = Multiply(m2,m3); return Add(m1,m4); } static auto Combine(Composition<Polynomial< CoeffType1, int_<order1>>, Polynomial< CoeffType2, int_<order2>>> p) { auto p1 = std::get<0>(p.GetFunctions()); auto p2 = std::get<1>(p.GetFunctions()); return Accumulate(p1, p2, int_<order1-1>()); } }; template <class Order, class CoeffType> struct Simplification< UnaryMinus<Polynomial<CoeffType, Order>>> { typedef typename std::conditional< std::is_signed<CoeffType>::value, CoeffType, typename std::make_signed< CoeffType>::type >::type CoeffType2; typedef Polynomial<CoeffType2, Order> type; static type Combine(UnaryMinus<Polynomial< CoeffType, Order>> u) { std::array<CoeffType2, Order::value> a; for(int i = 0; i < Order::value; i++) a[i] = -CoeffType2(u.GetFunction().GetCoeffs()[i]); return {a}; } }; template <class Order, class CoeffType1, class CoeffType2, class ... Funcs> struct Simplification< Multiplication<Composition<Polynomial<CoeffType1, Order>, Funcs...>, Polynomial<CoeffType2, int_<1>>>> { typedef typename std::common_type< CoeffType1, CoeffType2>::type CoeffType; typedef Composition<Polynomial<CoeffType, Order>, Funcs...> type; static type Combine(Multiplication< Composition<Polynomial<CoeffType1, Order>, Funcs...>, Polynomial<CoeffType2, int_<1>>> m) { std::array<CoeffType, Order::value> cs; auto p = std::get<0>(std::get<0>(m.GetFunctions()). GetFunctions()).GetCoeffs(); CoeffType2 c = std::get<1>(m.GetFunctions()).GetCoeffs()[0]; std::transform(p.begin(), p.end(), cs.begin(), [&c](auto x){return x * c;}); return {insert_element<0> (remove_element<0> (std::get<0>(m.GetFunctions()).GetFunctions()), Polynomial<CoeffType, Order>(cs))}; } }; } #include "polynomial_composition_simplifications.hh" #endif <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, Youssef Kashef // Copyright (c) 2015, ELM Library Project // 3-clause BSD License // //M*/ #include "elm/layers/weightedsum.h" #include "gtest/gtest.h" #include <memory> #include "elm/core/exception.h" #include "elm/core/layerconfig.h" #include "elm/core/signal.h" #include "elm/ts/layer_assertions.h" #include "elm/ts/mat_assertions.h" using namespace std; using namespace cv; using namespace elm; namespace { ELM_INSTANTIATE_LAYER_TYPED_TEST_CASE_P(WeightedSum); class WeightedSumTest : public ::testing::Test { public: static const string NAME_STIMULUS; static const string NAME_RESPONSE; protected: virtual void SetUp() { to_.reset(new WeightedSum()); config_ = LayerConfig(); // params PTree params; params.add(WeightedSum::PARAM_A, -1.f); params.add(WeightedSum::PARAM_B, 2.f); config_.Params(params); // IO config_.Input(WeightedSum::KEY_INPUT_STIMULUS, NAME_STIMULUS); config_.Output(WeightedSum::KEY_OUTPUT_RESPONSE, NAME_RESPONSE); to_.reset(new WeightedSum); to_->Reset(config_); to_->IONames(config_); } unique_ptr<base_Layer> to_; ///< test object LayerConfig config_; ///< default config for tests }; const string WeightedSumTest::NAME_STIMULUS = "in"; const string WeightedSumTest::NAME_RESPONSE = "out"; TEST_F(WeightedSumTest, Reset_EmptyConfig) { EXPECT_THROW(to_->Reset(LayerConfig()), boost::property_tree::ptree_bad_path); } TEST_F(WeightedSumTest, Activate) { Signal signal; // feed input into signal object EXPECT_FALSE(signal.Exists(NAME_STIMULUS)); signal.Append(NAME_STIMULUS, Mat1f::ones(3, 2)); EXPECT_TRUE(signal.Exists(NAME_STIMULUS)); // compute response EXPECT_FALSE(signal.Exists(NAME_RESPONSE)); to_->Activate(signal); to_->Response(signal); EXPECT_TRUE(signal.Exists(NAME_RESPONSE)) << "Resonse missing"; // Check response dimensions Mat1f response = signal[NAME_RESPONSE][0]; EXPECT_MAT_DIMS_EQ(response, Size(1, 3)); // Check response values float a = config_.Params().get<float>(WeightedSum::PARAM_A); float b = config_.Params().get<float>(WeightedSum::PARAM_B); for(int r=0; r<response.rows; r++) { EXPECT_EQ(a+b, response(r)); } } } // annonymous namespace for test cases and fixtures <commit_msg>test calling of IONames<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2015, Youssef Kashef // Copyright (c) 2015, ELM Library Project // 3-clause BSD License // //M*/ #include "elm/layers/weightedsum.h" #include "gtest/gtest.h" #include <memory> #include "elm/core/exception.h" #include "elm/core/layerconfig.h" #include "elm/core/signal.h" #include "elm/ts/layer_assertions.h" #include "elm/ts/mat_assertions.h" using namespace std; using namespace cv; using namespace elm; namespace { ELM_INSTANTIATE_LAYER_TYPED_TEST_CASE_P(WeightedSum); class WeightedSumTest : public ::testing::Test { public: static const string NAME_STIMULUS; static const string NAME_RESPONSE; protected: virtual void SetUp() { to_.reset(new WeightedSum()); config_ = LayerConfig(); // params PTree params; params.add(WeightedSum::PARAM_A, -1.f); params.add(WeightedSum::PARAM_B, 2.f); config_.Params(params); // IO config_.Input(WeightedSum::KEY_INPUT_STIMULUS, NAME_STIMULUS); config_.Output(WeightedSum::KEY_OUTPUT_RESPONSE, NAME_RESPONSE); to_.reset(new WeightedSum); to_->Reset(config_); to_->IONames(config_); } unique_ptr<base_Layer> to_; ///< test object LayerConfig config_; ///< default config for tests }; const string WeightedSumTest::NAME_STIMULUS = "in"; const string WeightedSumTest::NAME_RESPONSE = "out"; TEST_F(WeightedSumTest, Reset_EmptyConfig) { EXPECT_THROW(to_->Reset(LayerConfig()), boost::property_tree::ptree_bad_path); } TEST_F(WeightedSumTest, IONames) { to_.reset(new WeightedSum); to_->Reset(config_); Signal signal; // feed input into signal object ASSERT_FALSE(signal.Exists(NAME_STIMULUS)); signal.Append(NAME_STIMULUS, Mat1f::ones(3, 2)); EXPECT_TRUE(signal.Exists(NAME_STIMULUS)); // activate before setting io names ASSERT_FALSE(signal.Exists(NAME_RESPONSE)); EXPECT_THROW(to_->Activate(signal), ExceptionKeyError); to_->IONames(config_); // re-attempt activation with I/O names properly set // activate before setting io names EXPECT_FALSE(signal.Exists(NAME_RESPONSE)); EXPECT_NO_THROW(to_->Activate(signal));\ to_->Response(signal); EXPECT_TRUE(signal.Exists(NAME_RESPONSE)) << "Response missing"; } TEST_F(WeightedSumTest, Activate) { Signal signal; // feed input into signal object EXPECT_FALSE(signal.Exists(NAME_STIMULUS)); signal.Append(NAME_STIMULUS, Mat1f::ones(3, 2)); EXPECT_TRUE(signal.Exists(NAME_STIMULUS)); // compute response EXPECT_FALSE(signal.Exists(NAME_RESPONSE)); to_->Activate(signal); to_->Response(signal); EXPECT_TRUE(signal.Exists(NAME_RESPONSE)) << "Response missing"; // Check response dimensions Mat1f response = signal[NAME_RESPONSE][0]; EXPECT_MAT_DIMS_EQ(response, Size(1, 3)); // Check response values float a = config_.Params().get<float>(WeightedSum::PARAM_A); float b = config_.Params().get<float>(WeightedSum::PARAM_B); for(int r=0; r<response.rows; r++) { EXPECT_EQ(a+b, response(r)); } } } // annonymous namespace for test cases and fixtures <|endoftext|>
<commit_before>/************************************************************************* * * 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: handlerhelper.hxx,v $ * $Revision: 1.6 $ * * 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 EXTENSIONS_SOURCE_PROPCTRLR_HANDLERHELPER_HXX #define EXTENSIONS_SOURCE_PROPCTRLR_HANDLERHELPER_HXX /** === begin UNO includes === **/ #include <com/sun/star/beans/Property.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/script/XTypeConverter.hpp> #include <com/sun/star/beans/XPropertyChangeListener.hpp> #include <com/sun/star/inspection/XPropertyControlFactory.hpp> #include <com/sun/star/beans/PropertyAttribute.hpp> #include <com/sun/star/beans/Optional.hpp> /** === end UNO includes === **/ #include <vector> class Window; namespace com { namespace sun { namespace star { namespace inspection { struct LineDescriptor; } } } } //........................................................................ namespace pcr { //........................................................................ class ComponentContext; //==================================================================== //= PropertyHandlerHelper //==================================================================== class PropertyHandlerHelper { public: /** helper for implementing XPropertyHandler::describePropertyLine in a generic way */ static void describePropertyLine( const ::com::sun::star::beans::Property& _rProperty, ::com::sun::star::inspection::LineDescriptor& /* [out] */ _out_rDescriptor, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory ); /** helper for implementing XPropertyHandler::convertToPropertyValue */ static ::com::sun::star::uno::Any convertToPropertyValue( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext, const ::com::sun::star::uno::Reference< ::com::sun::star::script::XTypeConverter >& _rxTypeConverter, const ::com::sun::star::beans::Property& _rProperty, const ::com::sun::star::uno::Any& _rControlValue ); /// helper for implementing XPropertyHandler::convertToControlValue static ::com::sun::star::uno::Any convertToControlValue( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext, const ::com::sun::star::uno::Reference< ::com::sun::star::script::XTypeConverter >& _rxTypeConverter, const ::com::sun::star::uno::Any& _rPropertyValue, const ::com::sun::star::uno::Type& _rControlValueType ); /** creates an <member scope="com::sun::star::inspection">PropertyControlType::ListBox</member>-type control and fills it with initial values @param _rxControlFactory A control factory. Must not be <NULL/>. @param _rInitialListEntries the initial values of the control @param _bReadOnlyControl determines whether the control should be read-only @param _bSorted determines whether the list entries should be sorted @return the newly created control */ static ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl > createListBoxControl( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rInitialListEntries, sal_Bool _bReadOnlyControl, sal_Bool _bSorted ); static ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl > createListBoxControl( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory, const ::std::vector< ::rtl::OUString >& _rInitialListEntries, sal_Bool _bReadOnlyControl, sal_Bool _bSorted ); /** creates an <member scope="com::sun::star::inspection">PropertyControlType::ComboBox</member>-type control and fills it with initial values @param _rxControlFactory A control factory. Must not be <NULL/>. @param _rInitialListEntries the initial values of the control @param _bReadOnlyControl determines whether the control should be read-only @param _bSorted determines whether the list entries should be sorted @return the newly created control */ static ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl > createComboBoxControl( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rInitialListEntries, sal_Bool _bReadOnlyControl, sal_Bool _bSorted ); static ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl > createComboBoxControl( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory, const ::std::vector< ::rtl::OUString >& _rInitialListEntries, sal_Bool _bReadOnlyControl, sal_Bool _bSorted ); /** creates an <member scope="com::sun::star::inspection">PropertyControlType::NumericField</member>-type control and initializes it @param _rxControlFactory A control factory. Must not be <NULL/>. @param _nDigits number of decimal digits for the control (<member scope="com::sun::star::inspection">XNumericControl::DecimalDigits</member>) @param _rMinValue minimum value which can be entered in the control (<member scope="com::sun::star::inspection">XNumericControl::MinValue</member>) @param _rMaxValue maximum value which can be entered in the control (<member scope="com::sun::star::inspection">XNumericControl::MaxValue</member>) @param _bReadOnlyControl determines whether the control should be read-only @return the newly created control */ static ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl > createNumericControl( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory, sal_Int16 _nDigits, const ::com::sun::star::beans::Optional< double >& _rMinValue, const ::com::sun::star::beans::Optional< double >& _rMaxValue, sal_Bool _bReadOnlyControl ); /** marks the document passed in our UNO context as modified The method looks up a value called "ContextDocument" in the given UNO component context, queries it for the ->com::sun::star::util::XModifiable interface, and calls its setModified method. If either of those steps fails, this is asserted in a non-product version, and silently ignore otherwise. @param _rContext the component context which was used to create the component calling this method */ static void setContextDocumentModified( const ComponentContext& _rContext ); /** gets the window of the ObjectInspector in which an property handler lives The method looks up a value called "DialogParentWindow" in the given UNO copmonent context, queries it for XWindow, and returns the respective Window*. If either of those steps fails, this is asserted in a non-product version, and silently ignore otherwise. @param _rContext the component context which was used to create the component calling this method */ static Window* getDialogParentWindow( const ComponentContext& _rContext ); /** determines whether given PropertyAttributes require a to-be-created <type scope="com::sun::star::inspection">XPropertyControl</type> to be read-only @param _nPropertyAttributes the attributes of the property which should be reflected by a to-be-created <type scope="com::sun::star::inspection">XPropertyControl</type> */ inline static sal_Bool requiresReadOnlyControl( sal_Int16 _nPropertyAttributes ) { return ( _nPropertyAttributes & ::com::sun::star::beans::PropertyAttribute::READONLY ) != 0; } private: PropertyHandlerHelper(); // never implemented PropertyHandlerHelper( const PropertyHandlerHelper& ); // never implemented PropertyHandlerHelper& operator=( const PropertyHandlerHelper& ); // never implemented }; //........................................................................ } // namespace pcr //........................................................................ #endif // EXTENSIONS_SOURCE_PROPCTRLR_HANDLERHELPER_HXX <commit_msg>INTEGRATION: CWS mba30patches01 (1.5.124); FILE MERGED 2008/04/23 10:49:39 mba 1.5.124.2: RESYNC: (1.5-1.6); FILE MERGED 2008/03/18 15:40:59 mba 1.5.124.1: #i86365#: remove unused code<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: handlerhelper.hxx,v $ * $Revision: 1.7 $ * * 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 EXTENSIONS_SOURCE_PROPCTRLR_HANDLERHELPER_HXX #define EXTENSIONS_SOURCE_PROPCTRLR_HANDLERHELPER_HXX /** === begin UNO includes === **/ #include <com/sun/star/beans/Property.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <com/sun/star/script/XTypeConverter.hpp> #include <com/sun/star/beans/XPropertyChangeListener.hpp> #include <com/sun/star/inspection/XPropertyControlFactory.hpp> #include <com/sun/star/beans/PropertyAttribute.hpp> #include <com/sun/star/beans/Optional.hpp> /** === end UNO includes === **/ #include <vector> class Window; namespace com { namespace sun { namespace star { namespace inspection { struct LineDescriptor; } } } } //........................................................................ namespace pcr { //........................................................................ class ComponentContext; //==================================================================== //= PropertyHandlerHelper //==================================================================== class PropertyHandlerHelper { public: /** helper for implementing XPropertyHandler::describePropertyLine in a generic way */ static void describePropertyLine( const ::com::sun::star::beans::Property& _rProperty, ::com::sun::star::inspection::LineDescriptor& /* [out] */ _out_rDescriptor, const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory ); /** helper for implementing XPropertyHandler::convertToPropertyValue */ static ::com::sun::star::uno::Any convertToPropertyValue( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext, const ::com::sun::star::uno::Reference< ::com::sun::star::script::XTypeConverter >& _rxTypeConverter, const ::com::sun::star::beans::Property& _rProperty, const ::com::sun::star::uno::Any& _rControlValue ); /// helper for implementing XPropertyHandler::convertToControlValue static ::com::sun::star::uno::Any convertToControlValue( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& _rxContext, const ::com::sun::star::uno::Reference< ::com::sun::star::script::XTypeConverter >& _rxTypeConverter, const ::com::sun::star::uno::Any& _rPropertyValue, const ::com::sun::star::uno::Type& _rControlValueType ); /** creates an <member scope="com::sun::star::inspection">PropertyControlType::ListBox</member>-type control and fills it with initial values @param _rxControlFactory A control factory. Must not be <NULL/>. @param _rInitialListEntries the initial values of the control @param _bReadOnlyControl determines whether the control should be read-only @param _bSorted determines whether the list entries should be sorted @return the newly created control */ static ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl > createListBoxControl( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory, const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rInitialListEntries, sal_Bool _bReadOnlyControl, sal_Bool _bSorted ); static ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl > createListBoxControl( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory, const ::std::vector< ::rtl::OUString >& _rInitialListEntries, sal_Bool _bReadOnlyControl, sal_Bool _bSorted ); /** creates an <member scope="com::sun::star::inspection">PropertyControlType::ComboBox</member>-type control and fills it with initial values @param _rxControlFactory A control factory. Must not be <NULL/>. @param _rInitialListEntries the initial values of the control @param _bReadOnlyControl determines whether the control should be read-only @param _bSorted determines whether the list entries should be sorted @return the newly created control */ static ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl > createComboBoxControl( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory, const ::std::vector< ::rtl::OUString >& _rInitialListEntries, sal_Bool _bReadOnlyControl, sal_Bool _bSorted ); /** creates an <member scope="com::sun::star::inspection">PropertyControlType::NumericField</member>-type control and initializes it @param _rxControlFactory A control factory. Must not be <NULL/>. @param _nDigits number of decimal digits for the control (<member scope="com::sun::star::inspection">XNumericControl::DecimalDigits</member>) @param _rMinValue minimum value which can be entered in the control (<member scope="com::sun::star::inspection">XNumericControl::MinValue</member>) @param _rMaxValue maximum value which can be entered in the control (<member scope="com::sun::star::inspection">XNumericControl::MaxValue</member>) @param _bReadOnlyControl determines whether the control should be read-only @return the newly created control */ static ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControl > createNumericControl( const ::com::sun::star::uno::Reference< ::com::sun::star::inspection::XPropertyControlFactory >& _rxControlFactory, sal_Int16 _nDigits, const ::com::sun::star::beans::Optional< double >& _rMinValue, const ::com::sun::star::beans::Optional< double >& _rMaxValue, sal_Bool _bReadOnlyControl ); /** marks the document passed in our UNO context as modified The method looks up a value called "ContextDocument" in the given UNO component context, queries it for the ->com::sun::star::util::XModifiable interface, and calls its setModified method. If either of those steps fails, this is asserted in a non-product version, and silently ignore otherwise. @param _rContext the component context which was used to create the component calling this method */ static void setContextDocumentModified( const ComponentContext& _rContext ); /** gets the window of the ObjectInspector in which an property handler lives The method looks up a value called "DialogParentWindow" in the given UNO copmonent context, queries it for XWindow, and returns the respective Window*. If either of those steps fails, this is asserted in a non-product version, and silently ignore otherwise. @param _rContext the component context which was used to create the component calling this method */ static Window* getDialogParentWindow( const ComponentContext& _rContext ); /** determines whether given PropertyAttributes require a to-be-created <type scope="com::sun::star::inspection">XPropertyControl</type> to be read-only @param _nPropertyAttributes the attributes of the property which should be reflected by a to-be-created <type scope="com::sun::star::inspection">XPropertyControl</type> */ inline static sal_Bool requiresReadOnlyControl( sal_Int16 _nPropertyAttributes ) { return ( _nPropertyAttributes & ::com::sun::star::beans::PropertyAttribute::READONLY ) != 0; } private: PropertyHandlerHelper(); // never implemented PropertyHandlerHelper( const PropertyHandlerHelper& ); // never implemented PropertyHandlerHelper& operator=( const PropertyHandlerHelper& ); // never implemented }; //........................................................................ } // namespace pcr //........................................................................ #endif // EXTENSIONS_SOURCE_PROPCTRLR_HANDLERHELPER_HXX <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/balloon_collection_impl.h" #include "base/logging.h" #include "base/stl_util-inl.h" #include "chrome/browser/notifications/balloon.h" #include "chrome/browser/notifications/balloon_host.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/window_sizer.h" #include "gfx/rect.h" #include "gfx/size.h" namespace { // Portion of the screen allotted for notifications. When notification balloons // extend over this, no new notifications are shown until some are closed. const double kPercentBalloonFillFactor = 0.7; // Allow at least this number of balloons on the screen. const int kMinAllowedBalloonCount = 2; // Delay from the mouse leaving the balloon collection before // there is a relayout, in milliseconds. const int kRepositionDelay = 300; } // namespace // static // Note that on MacOS, since the coordinate system is inverted vertically from // the others, this actually produces notifications coming from the TOP right, // which is what is desired. BalloonCollectionImpl::Layout::Placement BalloonCollectionImpl::Layout::placement_ = Layout::VERTICALLY_FROM_BOTTOM_RIGHT; BalloonCollectionImpl::BalloonCollectionImpl() #if USE_OFFSETS : ALLOW_THIS_IN_INITIALIZER_LIST(reposition_factory_(this)), added_as_message_loop_observer_(false) #endif { } BalloonCollectionImpl::~BalloonCollectionImpl() { STLDeleteElements(&balloons_); } void BalloonCollectionImpl::Add(const Notification& notification, Profile* profile) { Balloon* new_balloon = MakeBalloon(notification, profile); // The +1 on width is necessary because width is fixed on notifications, // so since we always have the max size, we would always hit the scrollbar // condition. We are only interested in comparing height to maximum. new_balloon->set_min_scrollbar_size(gfx::Size(1 + layout_.max_balloon_width(), layout_.max_balloon_height())); new_balloon->SetPosition(layout_.OffScreenLocation(), false); new_balloon->Show(); #if USE_OFFSETS if (balloons_.size() > 0) new_balloon->set_offset(balloons_[balloons_.size() - 1]->offset()); #endif balloons_.push_back(new_balloon); PositionBalloons(false); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); } bool BalloonCollectionImpl::Remove(const Notification& notification) { Balloons::iterator iter; for (iter = balloons_.begin(); iter != balloons_.end(); ++iter) { if (notification.IsSame((*iter)->notification())) { // Balloon.CloseByScript() will cause OnBalloonClosed() to be called on // this object, which will remove it from the collection and free it. (*iter)->CloseByScript(); return true; } } return false; } bool BalloonCollectionImpl::HasSpace() const { if (count() < kMinAllowedBalloonCount) return true; int max_balloon_size = 0; int total_size = 0; layout_.GetMaxLinearSize(&max_balloon_size, &total_size); int current_max_size = max_balloon_size * count(); int max_allowed_size = static_cast<int>(total_size * kPercentBalloonFillFactor); return current_max_size < max_allowed_size - max_balloon_size; } void BalloonCollectionImpl::ResizeBalloon(Balloon* balloon, const gfx::Size& size) { balloon->set_content_size(Layout::ConstrainToSizeLimits(size)); PositionBalloons(true); } void BalloonCollectionImpl::DisplayChanged() { layout_.RefreshSystemMetrics(); PositionBalloons(true); } void BalloonCollectionImpl::OnBalloonClosed(Balloon* source) { // We want to free the balloon when finished. scoped_ptr<Balloon> closed(source); Balloons::iterator it = balloons_.begin(); #if USE_OFFSETS gfx::Point offset; bool apply_offset = false; while (it != balloons_.end()) { if (*it == source) { it = balloons_.erase(it); if (it != balloons_.end()) { apply_offset = true; offset.set_y((source)->offset().y() - (*it)->offset().y() + (*it)->content_size().height() - source->content_size().height()); } } else { if (apply_offset) (*it)->add_offset(offset); ++it; } } // Start listening for UI events so we cancel the offset when the mouse // leaves the balloon area. if (apply_offset) AddMessageLoopObserver(); #else for (; it != balloons_.end(); ++it) { if (*it == source) { balloons_.erase(it); break; } } #endif PositionBalloons(true); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); } void BalloonCollectionImpl::PositionBalloons(bool reposition) { gfx::Point origin = layout_.GetLayoutOrigin(); for (Balloons::iterator it = balloons_.begin(); it != balloons_.end(); ++it) { gfx::Point upper_left = layout_.NextPosition((*it)->GetViewSize(), &origin); (*it)->SetPosition(upper_left, reposition); } } #if USE_OFFSETS void BalloonCollectionImpl::AddMessageLoopObserver() { if (!added_as_message_loop_observer_) { MessageLoopForUI::current()->AddObserver(this); added_as_message_loop_observer_ = true; } } void BalloonCollectionImpl::RemoveMessageLoopObserver() { if (added_as_message_loop_observer_) { MessageLoopForUI::current()->RemoveObserver(this); added_as_message_loop_observer_ = false; } } void BalloonCollectionImpl::CancelOffsets() { reposition_factory_.RevokeAll(); // Unhook from listening to all UI events. RemoveMessageLoopObserver(); for (Balloons::iterator it = balloons_.begin(); it != balloons_.end(); ++it) (*it)->set_offset(gfx::Point(0, 0)); PositionBalloons(true); } void BalloonCollectionImpl::HandleMouseMoveEvent() { if (!IsCursorInBalloonCollection()) { // Mouse has left the region. Schedule a reposition after // a short delay. if (reposition_factory_.empty()) { MessageLoop::current()->PostDelayedTask( FROM_HERE, reposition_factory_.NewRunnableMethod( &BalloonCollectionImpl::CancelOffsets), kRepositionDelay); } } else { // Mouse moved back into the region. Cancel the reposition. reposition_factory_.RevokeAll(); } } #endif BalloonCollectionImpl::Layout::Layout() { RefreshSystemMetrics(); } void BalloonCollectionImpl::Layout::GetMaxLinearSize(int* max_balloon_size, int* total_size) const { DCHECK(max_balloon_size && total_size); switch (placement_) { case VERTICALLY_FROM_TOP_RIGHT: case VERTICALLY_FROM_BOTTOM_RIGHT: *total_size = work_area_.height(); *max_balloon_size = max_balloon_height(); break; default: NOTREACHED(); break; } } gfx::Point BalloonCollectionImpl::Layout::GetLayoutOrigin() const { int x = 0; int y = 0; switch (placement_) { case VERTICALLY_FROM_TOP_RIGHT: x = work_area_.right() - HorizontalEdgeMargin(); y = work_area_.y() + VerticalEdgeMargin(); break; case VERTICALLY_FROM_BOTTOM_RIGHT: x = work_area_.right() - HorizontalEdgeMargin(); y = work_area_.bottom() - VerticalEdgeMargin(); break; default: NOTREACHED(); break; } return gfx::Point(x, y); } gfx::Point BalloonCollectionImpl::Layout::NextPosition( const gfx::Size& balloon_size, gfx::Point* position_iterator) const { DCHECK(position_iterator); int x = 0; int y = 0; switch (placement_) { case VERTICALLY_FROM_TOP_RIGHT: x = position_iterator->x() - balloon_size.width(); y = position_iterator->y(); position_iterator->set_y(position_iterator->y() + balloon_size.height() + InterBalloonMargin()); break; case VERTICALLY_FROM_BOTTOM_RIGHT: position_iterator->set_y(position_iterator->y() - balloon_size.height() - InterBalloonMargin()); x = position_iterator->x() - balloon_size.width(); y = position_iterator->y(); break; default: NOTREACHED(); break; } return gfx::Point(x, y); } gfx::Point BalloonCollectionImpl::Layout::OffScreenLocation() const { int x = 0; int y = 0; switch (placement_) { case VERTICALLY_FROM_TOP_RIGHT: x = work_area_.right() - kBalloonMaxWidth - HorizontalEdgeMargin(); y = work_area_.y() + kBalloonMaxHeight + VerticalEdgeMargin(); break; case VERTICALLY_FROM_BOTTOM_RIGHT: x = work_area_.right() - kBalloonMaxWidth - HorizontalEdgeMargin(); y = work_area_.bottom() + kBalloonMaxHeight + VerticalEdgeMargin(); break; default: NOTREACHED(); break; } return gfx::Point(x, y); } // static gfx::Size BalloonCollectionImpl::Layout::ConstrainToSizeLimits( const gfx::Size& size) { // restrict to the min & max sizes return gfx::Size( std::max(min_balloon_width(), std::min(max_balloon_width(), size.width())), std::max(min_balloon_height(), std::min(max_balloon_height(), size.height()))); } bool BalloonCollectionImpl::Layout::RefreshSystemMetrics() { bool changed = false; #if defined(OS_MACOSX) gfx::Rect new_work_area = GetMacWorkArea(); #else scoped_ptr<WindowSizer::MonitorInfoProvider> info_provider( WindowSizer::CreateDefaultMonitorInfoProvider()); gfx::Rect new_work_area = info_provider->GetPrimaryMonitorWorkArea(); #endif if (!work_area_.Equals(new_work_area)) { work_area_.SetRect(new_work_area.x(), new_work_area.y(), new_work_area.width(), new_work_area.height()); changed = true; } return changed; } <commit_msg>Always refresh the desktop size before showing notifications. This should prevent all the corner cases of misplacement being reported.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/notifications/balloon_collection_impl.h" #include "base/logging.h" #include "base/stl_util-inl.h" #include "chrome/browser/notifications/balloon.h" #include "chrome/browser/notifications/balloon_host.h" #include "chrome/browser/notifications/notification.h" #include "chrome/browser/window_sizer.h" #include "gfx/rect.h" #include "gfx/size.h" namespace { // Portion of the screen allotted for notifications. When notification balloons // extend over this, no new notifications are shown until some are closed. const double kPercentBalloonFillFactor = 0.7; // Allow at least this number of balloons on the screen. const int kMinAllowedBalloonCount = 2; // Delay from the mouse leaving the balloon collection before // there is a relayout, in milliseconds. const int kRepositionDelay = 300; } // namespace // static // Note that on MacOS, since the coordinate system is inverted vertically from // the others, this actually produces notifications coming from the TOP right, // which is what is desired. BalloonCollectionImpl::Layout::Placement BalloonCollectionImpl::Layout::placement_ = Layout::VERTICALLY_FROM_BOTTOM_RIGHT; BalloonCollectionImpl::BalloonCollectionImpl() #if USE_OFFSETS : ALLOW_THIS_IN_INITIALIZER_LIST(reposition_factory_(this)), added_as_message_loop_observer_(false) #endif { } BalloonCollectionImpl::~BalloonCollectionImpl() { STLDeleteElements(&balloons_); } void BalloonCollectionImpl::Add(const Notification& notification, Profile* profile) { Balloon* new_balloon = MakeBalloon(notification, profile); // The +1 on width is necessary because width is fixed on notifications, // so since we always have the max size, we would always hit the scrollbar // condition. We are only interested in comparing height to maximum. new_balloon->set_min_scrollbar_size(gfx::Size(1 + layout_.max_balloon_width(), layout_.max_balloon_height())); new_balloon->SetPosition(layout_.OffScreenLocation(), false); new_balloon->Show(); #if USE_OFFSETS if (balloons_.size() > 0) new_balloon->set_offset(balloons_[balloons_.size() - 1]->offset()); #endif balloons_.push_back(new_balloon); PositionBalloons(false); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); } bool BalloonCollectionImpl::Remove(const Notification& notification) { Balloons::iterator iter; for (iter = balloons_.begin(); iter != balloons_.end(); ++iter) { if (notification.IsSame((*iter)->notification())) { // Balloon.CloseByScript() will cause OnBalloonClosed() to be called on // this object, which will remove it from the collection and free it. (*iter)->CloseByScript(); return true; } } return false; } bool BalloonCollectionImpl::HasSpace() const { if (count() < kMinAllowedBalloonCount) return true; int max_balloon_size = 0; int total_size = 0; layout_.GetMaxLinearSize(&max_balloon_size, &total_size); int current_max_size = max_balloon_size * count(); int max_allowed_size = static_cast<int>(total_size * kPercentBalloonFillFactor); return current_max_size < max_allowed_size - max_balloon_size; } void BalloonCollectionImpl::ResizeBalloon(Balloon* balloon, const gfx::Size& size) { balloon->set_content_size(Layout::ConstrainToSizeLimits(size)); PositionBalloons(true); } void BalloonCollectionImpl::DisplayChanged() { layout_.RefreshSystemMetrics(); PositionBalloons(true); } void BalloonCollectionImpl::OnBalloonClosed(Balloon* source) { // We want to free the balloon when finished. scoped_ptr<Balloon> closed(source); Balloons::iterator it = balloons_.begin(); #if USE_OFFSETS gfx::Point offset; bool apply_offset = false; while (it != balloons_.end()) { if (*it == source) { it = balloons_.erase(it); if (it != balloons_.end()) { apply_offset = true; offset.set_y((source)->offset().y() - (*it)->offset().y() + (*it)->content_size().height() - source->content_size().height()); } } else { if (apply_offset) (*it)->add_offset(offset); ++it; } } // Start listening for UI events so we cancel the offset when the mouse // leaves the balloon area. if (apply_offset) AddMessageLoopObserver(); #else for (; it != balloons_.end(); ++it) { if (*it == source) { balloons_.erase(it); break; } } #endif PositionBalloons(true); // There may be no listener in a unit test. if (space_change_listener_) space_change_listener_->OnBalloonSpaceChanged(); } void BalloonCollectionImpl::PositionBalloons(bool reposition) { layout_.RefreshSystemMetrics(); gfx::Point origin = layout_.GetLayoutOrigin(); for (Balloons::iterator it = balloons_.begin(); it != balloons_.end(); ++it) { gfx::Point upper_left = layout_.NextPosition((*it)->GetViewSize(), &origin); (*it)->SetPosition(upper_left, reposition); } } #if USE_OFFSETS void BalloonCollectionImpl::AddMessageLoopObserver() { if (!added_as_message_loop_observer_) { MessageLoopForUI::current()->AddObserver(this); added_as_message_loop_observer_ = true; } } void BalloonCollectionImpl::RemoveMessageLoopObserver() { if (added_as_message_loop_observer_) { MessageLoopForUI::current()->RemoveObserver(this); added_as_message_loop_observer_ = false; } } void BalloonCollectionImpl::CancelOffsets() { reposition_factory_.RevokeAll(); // Unhook from listening to all UI events. RemoveMessageLoopObserver(); for (Balloons::iterator it = balloons_.begin(); it != balloons_.end(); ++it) (*it)->set_offset(gfx::Point(0, 0)); PositionBalloons(true); } void BalloonCollectionImpl::HandleMouseMoveEvent() { if (!IsCursorInBalloonCollection()) { // Mouse has left the region. Schedule a reposition after // a short delay. if (reposition_factory_.empty()) { MessageLoop::current()->PostDelayedTask( FROM_HERE, reposition_factory_.NewRunnableMethod( &BalloonCollectionImpl::CancelOffsets), kRepositionDelay); } } else { // Mouse moved back into the region. Cancel the reposition. reposition_factory_.RevokeAll(); } } #endif BalloonCollectionImpl::Layout::Layout() { RefreshSystemMetrics(); } void BalloonCollectionImpl::Layout::GetMaxLinearSize(int* max_balloon_size, int* total_size) const { DCHECK(max_balloon_size && total_size); switch (placement_) { case VERTICALLY_FROM_TOP_RIGHT: case VERTICALLY_FROM_BOTTOM_RIGHT: *total_size = work_area_.height(); *max_balloon_size = max_balloon_height(); break; default: NOTREACHED(); break; } } gfx::Point BalloonCollectionImpl::Layout::GetLayoutOrigin() const { int x = 0; int y = 0; switch (placement_) { case VERTICALLY_FROM_TOP_RIGHT: x = work_area_.right() - HorizontalEdgeMargin(); y = work_area_.y() + VerticalEdgeMargin(); break; case VERTICALLY_FROM_BOTTOM_RIGHT: x = work_area_.right() - HorizontalEdgeMargin(); y = work_area_.bottom() - VerticalEdgeMargin(); break; default: NOTREACHED(); break; } return gfx::Point(x, y); } gfx::Point BalloonCollectionImpl::Layout::NextPosition( const gfx::Size& balloon_size, gfx::Point* position_iterator) const { DCHECK(position_iterator); int x = 0; int y = 0; switch (placement_) { case VERTICALLY_FROM_TOP_RIGHT: x = position_iterator->x() - balloon_size.width(); y = position_iterator->y(); position_iterator->set_y(position_iterator->y() + balloon_size.height() + InterBalloonMargin()); break; case VERTICALLY_FROM_BOTTOM_RIGHT: position_iterator->set_y(position_iterator->y() - balloon_size.height() - InterBalloonMargin()); x = position_iterator->x() - balloon_size.width(); y = position_iterator->y(); break; default: NOTREACHED(); break; } return gfx::Point(x, y); } gfx::Point BalloonCollectionImpl::Layout::OffScreenLocation() const { int x = 0; int y = 0; switch (placement_) { case VERTICALLY_FROM_TOP_RIGHT: x = work_area_.right() - kBalloonMaxWidth - HorizontalEdgeMargin(); y = work_area_.y() + kBalloonMaxHeight + VerticalEdgeMargin(); break; case VERTICALLY_FROM_BOTTOM_RIGHT: x = work_area_.right() - kBalloonMaxWidth - HorizontalEdgeMargin(); y = work_area_.bottom() + kBalloonMaxHeight + VerticalEdgeMargin(); break; default: NOTREACHED(); break; } return gfx::Point(x, y); } // static gfx::Size BalloonCollectionImpl::Layout::ConstrainToSizeLimits( const gfx::Size& size) { // restrict to the min & max sizes return gfx::Size( std::max(min_balloon_width(), std::min(max_balloon_width(), size.width())), std::max(min_balloon_height(), std::min(max_balloon_height(), size.height()))); } bool BalloonCollectionImpl::Layout::RefreshSystemMetrics() { bool changed = false; #if defined(OS_MACOSX) gfx::Rect new_work_area = GetMacWorkArea(); #else scoped_ptr<WindowSizer::MonitorInfoProvider> info_provider( WindowSizer::CreateDefaultMonitorInfoProvider()); gfx::Rect new_work_area = info_provider->GetPrimaryMonitorWorkArea(); #endif if (!work_area_.Equals(new_work_area)) { work_area_.SetRect(new_work_area.x(), new_work_area.y(), new_work_area.width(), new_work_area.height()); changed = true; } return changed; } <|endoftext|>
<commit_before>#include "plat_libraries.h" #if defined(COFFEE_LINUX) #include <dlfcn.h> #elif defined(COFFEE_WIN32) #include <Windows.h> #include <WinUser.h> #endif namespace Coffee{ namespace CLibraryLoader{ constexpr cstring lib_load_error_format = "Native library loading error: %s"; constexpr cstring lib_symb_error_format = "Native library symbol resolution error: %s"; #if defined(COFFEE_LINUX) struct CNativeObject { void* handle; void* funptr; }; CNativeObject* _coffee_get_library(cstring file, cstring loaderFunction) { CNativeObject *e = new CNativeObject; e->handle = dlopen(file,RTLD_NOW); if(!e->handle) { cWarning(lib_load_error_format,dlerror()); _coffee_close_library(e); return nullptr; } byte* error = nullptr; e->funptr = dlsym(e->handle,loaderFunction); if((error = dlerror()) != NULL) { cWarning(lib_symb_error_format,error); _coffee_close_library(e); return nullptr; } return e; } void _coffee_close_library(CNativeObject* object) { if(object->handle) dlclose(object->handle); delete object; } void* _coffee_get_funptr(CNativeObject* object) { return object->funptr; } #endif #if defined(COFFEE_WINDOWS) struct CNativeObject { HINSTANCE hinstLib; void* procedure; }; CNativeObject* _coffee_get_library(cstring file, cstring loaderFunction) { CNativeObject* e = new CNativeObject; e->hinstLib = LoadLibrary(file); if(!e->hinstLib) { cWarning(lib_load_error_format,file); _coffee_close_library(e); return nullptr; } e->procedure = GetProcAddress(e->hinstLib,loaderFunction); if(!e->procedure) { cWarning(lib_symb_error_format,file); _coffee_close_library(e); return nullptr; } return e; } void _coffee_close_library(CNativeObject* library) { if(library->hinstLib) FreeLibrary(library->hinstLib); delete library; } void* _coffee_get_funptr(CNativeObject *object) { return object->procedure; } #endif } } <commit_msg> - Add more includes<commit_after>#include "plat_libraries.h" #if defined(COFFEE_LINUX) #include <dlfcn.h> #elif defined(COFFEE_WIN32) #include <Windows.h> #include <WinUser.h> #include <WinDef.h> #endif namespace Coffee{ namespace CLibraryLoader{ constexpr cstring lib_load_error_format = "Native library loading error: %s"; constexpr cstring lib_symb_error_format = "Native library symbol resolution error: %s"; #if defined(COFFEE_LINUX) struct CNativeObject { void* handle; void* funptr; }; CNativeObject* _coffee_get_library(cstring file, cstring loaderFunction) { CNativeObject *e = new CNativeObject; e->handle = dlopen(file,RTLD_NOW); if(!e->handle) { cWarning(lib_load_error_format,dlerror()); _coffee_close_library(e); return nullptr; } byte* error = nullptr; e->funptr = dlsym(e->handle,loaderFunction); if((error = dlerror()) != NULL) { cWarning(lib_symb_error_format,error); _coffee_close_library(e); return nullptr; } return e; } void _coffee_close_library(CNativeObject* object) { if(object->handle) dlclose(object->handle); delete object; } void* _coffee_get_funptr(CNativeObject* object) { return object->funptr; } #endif #if defined(COFFEE_WINDOWS) struct CNativeObject { HINSTANCE hinstLib; void* procedure; }; CNativeObject* _coffee_get_library(cstring file, cstring loaderFunction) { CNativeObject* e = new CNativeObject; e->hinstLib = LoadLibrary(file); if(!e->hinstLib) { cWarning(lib_load_error_format,file); _coffee_close_library(e); return nullptr; } e->procedure = GetProcAddress(e->hinstLib,loaderFunction); if(!e->procedure) { cWarning(lib_symb_error_format,file); _coffee_close_library(e); return nullptr; } return e; } void _coffee_close_library(CNativeObject* library) { if(library->hinstLib) FreeLibrary(library->hinstLib); delete library; } void* _coffee_get_funptr(CNativeObject *object) { return object->procedure; } #endif } } <|endoftext|>
<commit_before>/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef HAVE_NO_CONFIG #include <votca_config.h> #endif #include <iostream> #include "gmxtopologyreader.h" #if GMX == 50 #include <gromacs/legacyheaders/statutil.h> #include <gromacs/legacyheaders/typedefs.h> #include <gromacs/legacyheaders/smalloc.h> #include <gromacs/legacyheaders/vec.h> #include <gromacs/legacyheaders/copyrite.h> #include <gromacs/legacyheaders/statutil.h> #include <gromacs/fileio/tpxio.h> #elif GMX == 45 #include <gromacs/statutil.h> #include <gromacs/typedefs.h> #include <gromacs/smalloc.h> #include <gromacs/vec.h> #include <gromacs/copyrite.h> #include <gromacs/statutil.h> #include <gromacs/tpxio.h> #elif GMX == 40 extern "C" { #include <statutil.h> #include <typedefs.h> #include <smalloc.h> #include <vec.h> #include <copyrite.h> #include <statutil.h> #include <tpxio.h> } #else #error Unsupported GMX version #endif // this one is needed because of bool is defined in one of the headers included by gmx #undef bool namespace votca { namespace csg { bool GMXTopologyReader::ReadTopology(string file, Topology &top) { gmx_mtop_t mtop; int natoms; // cleanup topology to store new data top.Cleanup(); #if GMX == 50 t_inputrec ir; ::matrix gbox; (void)read_tpx((char *)file.c_str(),&ir,gbox,&natoms,NULL,NULL,NULL,&mtop); #elif GMX == 45 set_program_name("VOTCA"); t_inputrec ir; ::matrix gbox; (void)read_tpx((char *)file.c_str(),&ir,gbox,&natoms,NULL,NULL,NULL,&mtop); #elif GMX == 40 set_program_name("VOTCA"); int sss; // wtf is this ::real ttt,lll; // wtf is this (void)read_tpx((char *)file.c_str(),&sss,&ttt,&lll,NULL,NULL,&natoms,NULL,NULL,NULL,&mtop); #else #error Unsupported GMX version #endif int count=0; for(int iblock=0; iblock<mtop.nmolblock; ++iblock) count+=mtop.molblock[iblock].nmol; if(count != mtop.mols.nr ) { throw runtime_error("gromacs topology contains inconsistency in molecule definitons\n\n" "A possible reason is an outdated .tpr file. Please rerun grompp to generate a new tpr file.\n" "If the problem remains or " "you're missing the files to rerun grompp,\n contact the votca mailing list for a solution."); } for(int iblock=0; iblock<mtop.nmolblock; ++iblock) { gmx_moltype_t *mol = &(mtop.moltype[mtop.molblock[iblock].type]); string molname = *(mol->name); int res_offset = top.ResidueCount(); t_atoms *atoms=&(mol->atoms); for(int i=0; i < atoms->nres; i++) { #if GMX == 50 top.CreateResidue(*(atoms->resinfo[i].name)); #elif GMX == 45 top.CreateResidue(*(atoms->resinfo[i].name)); #elif GMX == 40 top.CreateResidue(*(atoms->resname[i])); #else #error Unsupported GMX version #endif } int ifirstatom = 0; for(int imol=0; imol<mtop.molblock[iblock].nmol; ++imol) { Molecule *mi = top.CreateMolecule(molname); // read the atoms for(int iatom=0; iatom<mtop.molblock[iblock].natoms_mol; iatom++) { t_atom *a = &(atoms->atom[iatom]); // read exclusions t_blocka * excl = &(mol->excls); // insert exclusions list<int> excl_list; for(int k=excl->index[iatom]; k<excl->index[iatom+1]; k++) { excl_list.push_back(excl->a[k]+ifirstatom); } top.InsertExclusion(iatom+ifirstatom, excl_list); BeadType *type = top.GetOrCreateBeadType(*(atoms->atomtype[iatom])); #if GMX == 50 Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resind, a->m, a->q); #elif GMX == 45 Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resind, a->m, a->q); #elif GMX == 40 Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resnr, a->m, a->q); #else #error Unsupported GMX version #endif stringstream nm; nm << bead->getResnr() + 1 << ":" << top.getResidue(res_offset + bead->getResnr())->getName() << ":" << bead->getName(); mi->AddBead(bead, nm.str()); } ifirstatom+=mtop.molblock[iblock].natoms_mol; } } return true; } }} <commit_msg>gmxtopologyreader: changes for gromacs 5.0-beta2<commit_after>/* * Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef HAVE_NO_CONFIG #include <votca_config.h> #endif #include <iostream> #include "gmxtopologyreader.h" #if GMX == 50 #include <gromacs/fileio/tpxio.h> #elif GMX == 45 #include <gromacs/statutil.h> #include <gromacs/typedefs.h> #include <gromacs/smalloc.h> #include <gromacs/vec.h> #include <gromacs/copyrite.h> #include <gromacs/statutil.h> #include <gromacs/tpxio.h> #elif GMX == 40 extern "C" { #include <statutil.h> #include <typedefs.h> #include <smalloc.h> #include <vec.h> #include <copyrite.h> #include <statutil.h> #include <tpxio.h> } #else #error Unsupported GMX version #endif // this one is needed because of bool is defined in one of the headers included by gmx #undef bool namespace votca { namespace csg { bool GMXTopologyReader::ReadTopology(string file, Topology &top) { gmx_mtop_t mtop; int natoms; // cleanup topology to store new data top.Cleanup(); #if GMX == 50 t_inputrec ir; ::matrix gbox; (void)read_tpx((char *)file.c_str(),&ir,gbox,&natoms,NULL,NULL,NULL,&mtop); #elif GMX == 45 set_program_name("VOTCA"); t_inputrec ir; ::matrix gbox; (void)read_tpx((char *)file.c_str(),&ir,gbox,&natoms,NULL,NULL,NULL,&mtop); #elif GMX == 40 set_program_name("VOTCA"); int sss; // wtf is this ::real ttt,lll; // wtf is this (void)read_tpx((char *)file.c_str(),&sss,&ttt,&lll,NULL,NULL,&natoms,NULL,NULL,NULL,&mtop); #else #error Unsupported GMX version #endif int count=0; for(int iblock=0; iblock<mtop.nmolblock; ++iblock) count+=mtop.molblock[iblock].nmol; if(count != mtop.mols.nr ) { throw runtime_error("gromacs topology contains inconsistency in molecule definitons\n\n" "A possible reason is an outdated .tpr file. Please rerun grompp to generate a new tpr file.\n" "If the problem remains or " "you're missing the files to rerun grompp,\n contact the votca mailing list for a solution."); } for(int iblock=0; iblock<mtop.nmolblock; ++iblock) { gmx_moltype_t *mol = &(mtop.moltype[mtop.molblock[iblock].type]); string molname = *(mol->name); int res_offset = top.ResidueCount(); t_atoms *atoms=&(mol->atoms); for(int i=0; i < atoms->nres; i++) { #if GMX == 50 top.CreateResidue(*(atoms->resinfo[i].name)); #elif GMX == 45 top.CreateResidue(*(atoms->resinfo[i].name)); #elif GMX == 40 top.CreateResidue(*(atoms->resname[i])); #else #error Unsupported GMX version #endif } int ifirstatom = 0; for(int imol=0; imol<mtop.molblock[iblock].nmol; ++imol) { Molecule *mi = top.CreateMolecule(molname); // read the atoms for(int iatom=0; iatom<mtop.molblock[iblock].natoms_mol; iatom++) { t_atom *a = &(atoms->atom[iatom]); // read exclusions t_blocka * excl = &(mol->excls); // insert exclusions list<int> excl_list; for(int k=excl->index[iatom]; k<excl->index[iatom+1]; k++) { excl_list.push_back(excl->a[k]+ifirstatom); } top.InsertExclusion(iatom+ifirstatom, excl_list); BeadType *type = top.GetOrCreateBeadType(*(atoms->atomtype[iatom])); #if GMX == 50 Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resind, a->m, a->q); #elif GMX == 45 Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resind, a->m, a->q); #elif GMX == 40 Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resnr, a->m, a->q); #else #error Unsupported GMX version #endif stringstream nm; nm << bead->getResnr() + 1 << ":" << top.getResidue(res_offset + bead->getResnr())->getName() << ":" << bead->getName(); mi->AddBead(bead, nm.str()); } ifirstatom+=mtop.molblock[iblock].natoms_mol; } } return true; } }} <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/glue/theme_change_processor.h" #include "base/logging.h" #include "chrome/browser/browser_theme_provider.h" #include "chrome/browser/profile.h" #include "chrome/browser/sync/engine/syncapi.h" #include "chrome/browser/sync/glue/theme_util.h" #include "chrome/browser/sync/protocol/theme_specifics.pb.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/notification_details.h" #include "chrome/common/notification_source.h" namespace browser_sync { namespace { std::string GetThemeId(Extension* current_theme) { if (current_theme) { DCHECK(current_theme->IsTheme()); } return current_theme ? current_theme->id() : "default/system"; } } // namespace ThemeChangeProcessor::ThemeChangeProcessor( UnrecoverableErrorHandler* error_handler) : ChangeProcessor(error_handler), profile_(NULL) { DCHECK(error_handler); } ThemeChangeProcessor::~ThemeChangeProcessor() {} void ThemeChangeProcessor::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(running()); DCHECK(profile_); Extension* extension = Details<Extension>(details).ptr(); switch (type.value) { case NotificationType::BROWSER_THEME_CHANGED: // We pay attention to this notification only when it signifies // that the user has set the current theme to the system theme or // default theme. If the user set the current theme to a custom // theme, the theme isn't actually loaded until after this // notification. LOG(INFO) << "Got BROWSER_THEME_CHANGED notification for theme " << GetThemeId(extension); DCHECK_EQ(Source<BrowserThemeProvider>(source).ptr(), profile_->GetThemeProvider()); if (extension != NULL) { DCHECK(extension->IsTheme()); DCHECK_EQ(extension->id(), profile_->GetThemeProvider()->GetThemeID()); return; } break; case NotificationType::EXTENSION_LOADED: // We pay attention to this notification only when it signifies // that a theme extension has been loaded because that means that // the user set the current theme to a custom theme and it has // successfully installed. DCHECK_EQ(Source<Profile>(source).ptr(), profile_); CHECK(extension); if (!extension->IsTheme()) { return; } LOG(INFO) << "Got EXTENSION_LOADED notification for theme " << extension->id(); DCHECK_EQ(extension->id(), profile_->GetThemeProvider()->GetThemeID()); DCHECK_EQ(extension, profile_->GetTheme()); break; case NotificationType::EXTENSION_UNLOADED: // We pay attention to this notification only when it signifies // that a theme extension has been unloaded because that means // that the user set the current theme to a custom theme and then // changed his mind and undid it (reverting to the previous // theme). DCHECK_EQ(Source<Profile>(source).ptr(), profile_); CHECK(extension); if (!extension->IsTheme()) { return; } LOG(INFO) << "Got EXTENSION_UNLOADED notification for theme " << extension->id(); extension = profile_->GetTheme(); break; default: LOG(DFATAL) << "Unexpected notification received: " << type.value; break; } DCHECK_EQ(extension, profile_->GetTheme()); if (extension) { DCHECK(extension->IsTheme()); } LOG(INFO) << "Theme changed to " << GetThemeId(extension); // Here, we know that a theme is being set; the theme is a custom // theme iff extension is non-NULL. sync_api::WriteTransaction trans(share_handle()); sync_api::WriteNode node(&trans); if (!node.InitByClientTagLookup(syncable::THEMES, kCurrentThemeClientTag)) { LOG(ERROR) << "Could not create node with client tag: " << kCurrentThemeClientTag; error_handler()->OnUnrecoverableError(); return; } sync_pb::ThemeSpecifics old_theme_specifics = node.GetThemeSpecifics(); // Make sure to base new_theme_specifics on old_theme_specifics so // we preserve the state of use_system_theme_by_default. sync_pb::ThemeSpecifics new_theme_specifics = old_theme_specifics; GetThemeSpecificsFromCurrentTheme(profile_, &new_theme_specifics); // Do a write only if something actually changed so as to guard // against cycles. if (!AreThemeSpecificsEqual(old_theme_specifics, new_theme_specifics)) { node.SetThemeSpecifics(new_theme_specifics); } return; } void ThemeChangeProcessor::ApplyChangesFromSyncModel( const sync_api::BaseTransaction* trans, const sync_api::SyncManager::ChangeRecord* changes, int change_count) { if (!running()) { return; } StopObserving(); ApplyChangesFromSyncModelHelper(trans, changes, change_count); StartObserving(); } void ThemeChangeProcessor::StartImpl(Profile* profile) { DCHECK(profile); profile_ = profile; StartObserving(); } void ThemeChangeProcessor::StopImpl() { StopObserving(); profile_ = NULL; } void ThemeChangeProcessor::ApplyChangesFromSyncModelHelper( const sync_api::BaseTransaction* trans, const sync_api::SyncManager::ChangeRecord* changes, int change_count) { if (change_count != 1) { LOG(ERROR) << "Unexpected number of theme changes"; error_handler()->OnUnrecoverableError(); return; } const sync_api::SyncManager::ChangeRecord& change = changes[0]; if (change.action != sync_api::SyncManager::ChangeRecord::ACTION_UPDATE) { LOG(ERROR) << "Unexpected change.action " << change.action; error_handler()->OnUnrecoverableError(); return; } sync_api::ReadNode node(trans); if (!node.InitByIdLookup(change.id)) { LOG(ERROR) << "Theme node lookup failed"; error_handler()->OnUnrecoverableError(); return; } DCHECK_EQ(node.GetModelType(), syncable::THEMES); DCHECK(profile_); SetCurrentThemeFromThemeSpecificsIfNecessary( node.GetThemeSpecifics(), profile_); } void ThemeChangeProcessor::StartObserving() { DCHECK(profile_); LOG(INFO) << "Observing BROWSER_THEME_CHANGED, EXTENSION_LOADED, " << "and EXTENSION_UNLOADED"; notification_registrar_.Add( this, NotificationType::BROWSER_THEME_CHANGED, Source<BrowserThemeProvider>(profile_->GetThemeProvider())); notification_registrar_.Add( this, NotificationType::EXTENSION_LOADED, Source<Profile>(profile_)); notification_registrar_.Add( this, NotificationType::EXTENSION_UNLOADED, Source<Profile>(profile_)); } void ThemeChangeProcessor::StopObserving() { DCHECK(profile_); LOG(INFO) << "Unobserving all notifications"; notification_registrar_.RemoveAll(); } } // namespace browser_sync <commit_msg>Fixed a bug where themes wouldn't sync properly if it had been installed before.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/glue/theme_change_processor.h" #include "base/logging.h" #include "chrome/browser/browser_theme_provider.h" #include "chrome/browser/profile.h" #include "chrome/browser/sync/engine/syncapi.h" #include "chrome/browser/sync/glue/theme_util.h" #include "chrome/browser/sync/protocol/theme_specifics.pb.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/notification_details.h" #include "chrome/common/notification_source.h" namespace browser_sync { namespace { std::string GetThemeId(Extension* current_theme) { if (current_theme) { DCHECK(current_theme->IsTheme()); } return current_theme ? current_theme->id() : "default/system"; } } // namespace ThemeChangeProcessor::ThemeChangeProcessor( UnrecoverableErrorHandler* error_handler) : ChangeProcessor(error_handler), profile_(NULL) { DCHECK(error_handler); } ThemeChangeProcessor::~ThemeChangeProcessor() {} void ThemeChangeProcessor::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(running()); DCHECK(profile_); Extension* extension = Details<Extension>(details).ptr(); std::string current_or_future_theme_id = profile_->GetThemeProvider()->GetThemeID(); Extension* current_theme = profile_->GetTheme(); switch (type.value) { case NotificationType::BROWSER_THEME_CHANGED: // We pay attention to this notification only when it signifies // that a user changed the theme to the default/system theme, or // when it signifies that a user changed the theme to a custom // one that was already installed. Otherwise, current_theme // still points to the previous theme until it gets installed // and loaded (and we get an EXTENSION_LOADED notification). LOG(INFO) << "Got BROWSER_THEME_CHANGED notification for theme " << GetThemeId(extension); DCHECK_EQ(Source<BrowserThemeProvider>(source).ptr(), profile_->GetThemeProvider()); if (extension != NULL) { DCHECK(extension->IsTheme()); DCHECK_EQ(extension->id(), current_or_future_theme_id); if (!current_theme || (current_theme->id() != extension->id())) { return; } } break; case NotificationType::EXTENSION_LOADED: // We pay attention to this notification only when it signifies // that a theme extension has been loaded because that means // that the user set the current theme to a custom theme that // needed to be downloaded and installed and that it was // installed successfully. DCHECK_EQ(Source<Profile>(source).ptr(), profile_); CHECK(extension); if (!extension->IsTheme()) { return; } LOG(INFO) << "Got EXTENSION_LOADED notification for theme " << extension->id(); DCHECK_EQ(extension->id(), current_or_future_theme_id); DCHECK_EQ(extension, current_theme); break; case NotificationType::EXTENSION_UNLOADED: // We pay attention to this notification only when it signifies // that a theme extension has been unloaded because that means // that the user set the current theme to a custom theme and then // changed his mind and undid it (reverting to the previous // theme). DCHECK_EQ(Source<Profile>(source).ptr(), profile_); CHECK(extension); if (!extension->IsTheme()) { return; } LOG(INFO) << "Got EXTENSION_UNLOADED notification for theme " << extension->id(); extension = current_theme; break; default: LOG(DFATAL) << "Unexpected notification received: " << type.value; break; } DCHECK_EQ(extension, current_theme); if (extension) { DCHECK(extension->IsTheme()); } LOG(INFO) << "Theme changed to " << GetThemeId(extension); // Here, we know that a theme is being set; the theme is a custom // theme iff extension is non-NULL. sync_api::WriteTransaction trans(share_handle()); sync_api::WriteNode node(&trans); if (!node.InitByClientTagLookup(syncable::THEMES, kCurrentThemeClientTag)) { LOG(ERROR) << "Could not create node with client tag: " << kCurrentThemeClientTag; error_handler()->OnUnrecoverableError(); return; } sync_pb::ThemeSpecifics old_theme_specifics = node.GetThemeSpecifics(); // Make sure to base new_theme_specifics on old_theme_specifics so // we preserve the state of use_system_theme_by_default. sync_pb::ThemeSpecifics new_theme_specifics = old_theme_specifics; GetThemeSpecificsFromCurrentTheme(profile_, &new_theme_specifics); // Do a write only if something actually changed so as to guard // against cycles. if (!AreThemeSpecificsEqual(old_theme_specifics, new_theme_specifics)) { node.SetThemeSpecifics(new_theme_specifics); } return; } void ThemeChangeProcessor::ApplyChangesFromSyncModel( const sync_api::BaseTransaction* trans, const sync_api::SyncManager::ChangeRecord* changes, int change_count) { if (!running()) { return; } StopObserving(); ApplyChangesFromSyncModelHelper(trans, changes, change_count); StartObserving(); } void ThemeChangeProcessor::StartImpl(Profile* profile) { DCHECK(profile); profile_ = profile; StartObserving(); } void ThemeChangeProcessor::StopImpl() { StopObserving(); profile_ = NULL; } void ThemeChangeProcessor::ApplyChangesFromSyncModelHelper( const sync_api::BaseTransaction* trans, const sync_api::SyncManager::ChangeRecord* changes, int change_count) { if (change_count != 1) { LOG(ERROR) << "Unexpected number of theme changes"; error_handler()->OnUnrecoverableError(); return; } const sync_api::SyncManager::ChangeRecord& change = changes[0]; if (change.action != sync_api::SyncManager::ChangeRecord::ACTION_UPDATE) { LOG(ERROR) << "Unexpected change.action " << change.action; error_handler()->OnUnrecoverableError(); return; } sync_api::ReadNode node(trans); if (!node.InitByIdLookup(change.id)) { LOG(ERROR) << "Theme node lookup failed"; error_handler()->OnUnrecoverableError(); return; } DCHECK_EQ(node.GetModelType(), syncable::THEMES); DCHECK(profile_); SetCurrentThemeFromThemeSpecificsIfNecessary( node.GetThemeSpecifics(), profile_); } void ThemeChangeProcessor::StartObserving() { DCHECK(profile_); LOG(INFO) << "Observing BROWSER_THEME_CHANGED, EXTENSION_LOADED, " << "and EXTENSION_UNLOADED"; notification_registrar_.Add( this, NotificationType::BROWSER_THEME_CHANGED, Source<BrowserThemeProvider>(profile_->GetThemeProvider())); notification_registrar_.Add( this, NotificationType::EXTENSION_LOADED, Source<Profile>(profile_)); notification_registrar_.Add( this, NotificationType::EXTENSION_UNLOADED, Source<Profile>(profile_)); } void ThemeChangeProcessor::StopObserving() { DCHECK(profile_); LOG(INFO) << "Unobserving all notifications"; notification_registrar_.RemoveAll(); } } // namespace browser_sync <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_check_master_stop15.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_sbe_check_master_stop15.H /// @brief Check if the targeted core (master) is fully in STOP15 /// // *HWP HWP Owner : Greg Still <stillgsg@us.ibm.com> // *HWP FW Owner : Bilicon Patil <bilpatil@in.ibm.com> // *HWP Team : PM // *HWP Level : 2 // *HWP Consumed by : SBE /// /// High-level procedure flow: /// @verbatim /// - Read the STOP History Register from the target core /// - Return SUCCESS if:: /// - STOP_GATED is set (indicating it is stopped) /// - STOP_TRANSITION is clear (indicating it is stable) /// - ACT_STOP_LEVEL is at the appropriate value (either 11 (0xB) or 15 (0x15) /// - Return PENDING if /// - STOP_TRANSITION is set (indicating transtion is progress) /// - Return ERROR if /// - STOP_GATED is set, STOP_TRANSITION is clear and ACT_STOP_LEVEL is not /// appropriate /// - STOP_TRANSITION is clear but STOP_GATED is clear /// - Hardware access errors /// @endverbatim // ----------------------------------------------------------------------------- // Includes // ----------------------------------------------------------------------------- #include <p9_sbe_check_master_stop15.H> #include <p9_pm_stop_history.H> #include <p9_quad_scom_addresses.H> // ----------------------------------------------------------------------------- // Function definitions // ----------------------------------------------------------------------------- // See .H for documentation fapi2::ReturnCode p9_sbe_check_master_stop15( const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target) { FAPI_IMP("> p9_sbe_check_master_stop15"); fapi2::buffer<uint64_t> l_data64; uint32_t l_stop_gated = 0; uint32_t l_stop_transition = p9ssh::SSH_UNDEFINED; uint32_t l_stop_requested_level = 0; // Running Level uint32_t l_stop_actual_level = 0; // Running Level // Read the "Other" STOP History Register FAPI_TRY(fapi2::getScom(i_target, C_PPM_SSHOTR, l_data64)); // Extract the field values l_data64.extractToRight<p9ssh::STOP_GATED_START, p9ssh::STOP_GATED_LEN>(l_stop_gated); l_data64.extractToRight<p9ssh::STOP_TRANSITION_START, p9ssh::STOP_TRANSITION_LEN>(l_stop_transition); // Testing showed the above operation was sign extending into // the l_stop_transition variable. l_stop_transition &= 0x3; l_data64.extractToRight<p9ssh::STOP_REQUESTED_LEVEL_START, p9ssh::STOP_REQUESTED_LEVEL_LEN>(l_stop_requested_level); l_data64.extractToRight<p9ssh::STOP_ACTUAL_LEVEL_START, p9ssh::STOP_ACTUAL_LEVEL_LEN>(l_stop_actual_level); #ifndef __PPE__ FAPI_DBG("GATED = %d; TRANSITION = %d (0x%X); REQUESTED_LEVEL = %d; ACTUAL_LEVEL = %d", l_stop_gated, l_stop_transition, l_stop_transition, l_stop_requested_level, l_stop_actual_level); #endif // Check for valide reguest level FAPI_ASSERT((l_stop_requested_level == 11 || l_stop_requested_level == 15), fapi2::CHECK_MASTER_STOP15_INVALID_REQUEST_LEVEL() .set_REQUESTED_LEVEL(l_stop_requested_level), "Invalid requested STOP Level"); // Check for valid pending condition FAPI_ASSERT(!(l_stop_transition == p9ssh::SSH_CORE_COMPLETE || l_stop_transition == p9ssh::SSH_ENTERING ), fapi2::CHECK_MASTER_STOP15_PENDING(), "STOP 15 is still pending"); // Assert completion and the core gated condition. If not, something is off. FAPI_ASSERT((l_stop_transition == p9ssh::SSH_COMPLETE && l_stop_gated == p9ssh::SSH_GATED ), fapi2::CHECK_MASTER_STOP15_INVALID_STATE() .set_STOP_HISTORY(l_data64), "STOP 15 error"); // Check for valid actual level FAPI_ASSERT((l_stop_actual_level == 11 || l_stop_actual_level == 15), fapi2::CHECK_MASTER_STOP15_INVALID_ACTUAL_LEVEL() .set_ACTUAL_LEVEL(l_stop_actual_level), "Invalid actual STOP Level"); FAPI_INF("SUCCESS!! Valid STOP entry state has been achieved.") fapi_try_exit: FAPI_INF("< p9_sbe_check_master_stop15"); return fapi2::current_err; } // END p9_sbe_check_master_stop15 <commit_msg>p9_sbe_check_master_stop15 fix for running<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_check_master_stop15.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_sbe_check_master_stop15.H /// @brief Check if the targeted core (master) is fully in STOP15 /// // *HWP HWP Owner : Greg Still <stillgsg@us.ibm.com> // *HWP FW Owner : Bilicon Patil <bilpatil@in.ibm.com> // *HWP Team : PM // *HWP Level : 2 // *HWP Consumed by : SBE /// /// High-level procedure flow: /// @verbatim /// - Read the STOP History Register from the target core /// - Return SUCCESS if:: /// - STOP_GATED is set (indicating it is not running) /// - STOP_TRANSITION is COMPLETE (indicating it is stable) /// - ACT_STOP_LEVEL is at the appropriate value (either 11 (0xB) or /// 15 (0xF) /// - Return PENDING if /// - STOP_GATED is RUNNING /// or /// - STOP_GATED is GATED (indicating it is not running) /// - STOP_TRANSITION is not COMPLETE (indicating transtion is progress) /// - Return ERROR if /// - STOP_GATED is set, STOP_TRANSITION is COMPLETE and ACT_STOP_LEVEL /// is not appropriate /// - Hardware access errors /// @endverbatim // ----------------------------------------------------------------------------- // Includes // ----------------------------------------------------------------------------- #include <p9_sbe_check_master_stop15.H> #include <p9_pm_stop_history.H> #include <p9_quad_scom_addresses.H> // ----------------------------------------------------------------------------- // Function definitions // ----------------------------------------------------------------------------- // See .H for documentation fapi2::ReturnCode p9_sbe_check_master_stop15( const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target) { FAPI_IMP("> p9_sbe_check_master_stop15"); fapi2::buffer<uint64_t> l_data64; uint32_t l_stop_gated = 0; uint32_t l_stop_transition = p9ssh::SSH_UNDEFINED; uint32_t l_stop_requested_level = 0; // Running Level uint32_t l_stop_actual_level = 0; // Running Level // Read the "Other" STOP History Register FAPI_TRY(fapi2::getScom(i_target, C_PPM_SSHOTR, l_data64)); // Extract the field values l_data64.extractToRight<p9ssh::STOP_GATED_START, p9ssh::STOP_GATED_LEN>(l_stop_gated); l_data64.extractToRight<p9ssh::STOP_TRANSITION_START, p9ssh::STOP_TRANSITION_LEN>(l_stop_transition); // Testing showed the above operation was sign extending into // the l_stop_transition variable. l_stop_transition &= 0x3; l_data64.extractToRight<p9ssh::STOP_REQUESTED_LEVEL_START, p9ssh::STOP_REQUESTED_LEVEL_LEN>(l_stop_requested_level); l_data64.extractToRight<p9ssh::STOP_ACTUAL_LEVEL_START, p9ssh::STOP_ACTUAL_LEVEL_LEN>(l_stop_actual_level); #ifndef __PPE__ FAPI_DBG("GATED = %d; TRANSITION = %d (0x%X); REQUESTED_LEVEL = %d; ACTUAL_LEVEL = %d", l_stop_gated, l_stop_transition, l_stop_transition, l_stop_requested_level, l_stop_actual_level); FAPI_DBG("SSH_RUNNING = %d; SSH_GATED = %d; SSH_COMPLETE = %d", p9ssh::SSH_RUNNING, p9ssh::SSH_GATED, p9ssh::SSH_COMPLETE); #endif if (l_stop_gated == p9ssh::SSH_RUNNING || (l_stop_gated == p9ssh::SSH_GATED && l_stop_transition != p9ssh::SSH_COMPLETE)) { FAPI_ASSERT(false, fapi2::CHECK_MASTER_STOP15_PENDING(), "STOP 15 is still pending") } if (l_stop_gated == p9ssh::SSH_GATED && l_stop_transition == p9ssh::SSH_COMPLETE && (l_stop_actual_level == 11 || l_stop_actual_level == 15)) { FAPI_INF("SUCCESS!! Valid STOP entry state has been achieved."); } else { FAPI_ASSERT(false, fapi2::CHECK_MASTER_STOP15_INVALID_STATE() .set_STOP_HISTORY(l_data64), "STOP 15 error"); } // @todo RTC 162331 These should work but don't..... follow-up later // // Check for valid pending condition (which includes running) // FAPI_ASSERT((l_stop_gated == p9ssh::SSH_RUNNING || // (l_stop_gated == p9ssh::SSH_GATED && // l_stop_transition != p9ssh::SSH_COMPLETE)), // fapi2::CHECK_MASTER_STOP15_PENDING(), // "STOP 15 is still pending"); // // Assert gated, completion and the proper STOP actual level. If not, something is off. // FAPI_ASSERT((l_stop_gated == p9ssh::SSH_GATED && // l_stop_transition == p9ssh::SSH_COMPLETE && // (l_stop_actual_level == 11 || l_stop_actual_level == 15)), // fapi2::CHECK_MASTER_STOP15_INVALID_STATE() // .set_STOP_HISTORY(l_data64), // } "STOP 15 error"); fapi_try_exit: FAPI_INF("< p9_sbe_check_master_stop15"); return fapi2::current_err; } // END p9_sbe_check_master_stop15 <|endoftext|>
<commit_before>/* * OS and machine specific utility functions * (C) 2015,2016,2017 Jack Lloyd * (C) 2016 Daniel Neus * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/os_utils.h> #include <botan/cpuid.h> #include <botan/exceptn.h> #include <botan/mem_ops.h> #include <chrono> #include <cstdlib> #if defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO) #include <string.h> #endif #if defined(BOTAN_TARGET_OS_HAS_POSIX1) #include <sys/types.h> #include <sys/resource.h> #include <sys/mman.h> #include <signal.h> #include <setjmp.h> #include <unistd.h> #include <errno.h> #elif defined(BOTAN_TARGET_OS_HAS_WIN32) #define NOMINMAX 1 #include <windows.h> #endif namespace Botan { // Not defined in OS namespace for historical reasons void secure_scrub_memory(void* ptr, size_t n) { #if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY) ::RtlSecureZeroMemory(ptr, n); #elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO) ::explicit_bzero(ptr, n); #elif defined(BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO) && (BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO == 1) /* Call memset through a static volatile pointer, which the compiler should not elide. This construct should be safe in conforming compilers, but who knows. I did confirm that on x86-64 GCC 6.1 and Clang 3.8 both create code that saves the memset address in the data segment and uncondtionally loads and jumps to that address. */ static void* (*const volatile memset_ptr)(void*, int, size_t) = std::memset; (memset_ptr)(ptr, 0, n); #else volatile uint8_t* p = reinterpret_cast<volatile uint8_t*>(ptr); for(size_t i = 0; i != n; ++i) p[i] = 0; #endif } uint32_t OS::get_process_id() { #if defined(BOTAN_TARGET_OS_HAS_POSIX1) return ::getpid(); #elif defined(BOTAN_TARGET_OS_HAS_WIN32) return ::GetCurrentProcessId(); #elif defined(BOTAN_TARGET_OS_IS_INCLUDEOS) || defined(BOTAN_TARGET_OS_IS_LLVM) return 0; // truly no meaningful value #else #error "Missing get_process_id" #endif } uint64_t OS::get_processor_timestamp() { uint64_t rtc = 0; #if defined(BOTAN_TARGET_OS_HAS_WIN32) LARGE_INTEGER tv; ::QueryPerformanceCounter(&tv); rtc = tv.QuadPart; #elif defined(BOTAN_USE_GCC_INLINE_ASM) #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY) if(CPUID::has_rdtsc()) { uint32_t rtc_low = 0, rtc_high = 0; asm volatile("rdtsc" : "=d" (rtc_high), "=a" (rtc_low)); rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low; } #elif defined(BOTAN_TARGET_ARCH_IS_PPC64) uint32_t rtc_low = 0, rtc_high = 0; asm volatile("mftbu %0; mftb %1" : "=r" (rtc_high), "=r" (rtc_low)); /* qemu-ppc seems to not support mftb instr, it always returns zero. If both time bases are 0, assume broken and return another clock. */ if(rtc_high > 0 || rtc_low > 0) { rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low; } #elif defined(BOTAN_TARGET_ARCH_IS_ALPHA) asm volatile("rpcc %0" : "=r" (rtc)); // OpenBSD does not trap access to the %tick register #elif defined(BOTAN_TARGET_ARCH_IS_SPARC64) && !defined(BOTAN_TARGET_OS_IS_OPENBSD) asm volatile("rd %%tick, %0" : "=r" (rtc)); #elif defined(BOTAN_TARGET_ARCH_IS_IA64) asm volatile("mov %0=ar.itc" : "=r" (rtc)); #elif defined(BOTAN_TARGET_ARCH_IS_S390X) asm volatile("stck 0(%0)" : : "a" (&rtc) : "memory", "cc"); #elif defined(BOTAN_TARGET_ARCH_IS_HPPA) asm volatile("mfctl 16,%0" : "=r" (rtc)); // 64-bit only? #else //#warning "OS::get_processor_timestamp not implemented" #endif #endif return rtc; } uint64_t OS::get_high_resolution_clock() { if(uint64_t cpu_clock = OS::get_processor_timestamp()) return cpu_clock; /* If we got here either we either don't have an asm instruction above, or (for x86) RDTSC is not available at runtime. Try some clock_gettimes and return the first one that works, or otherwise fall back to std::chrono. */ #if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME) // The ordering here is somewhat arbitrary... const clockid_t clock_types[] = { #if defined(CLOCK_MONOTONIC_HR) CLOCK_MONOTONIC_HR, #endif #if defined(CLOCK_MONOTONIC_RAW) CLOCK_MONOTONIC_RAW, #endif #if defined(CLOCK_MONOTONIC) CLOCK_MONOTONIC, #endif #if defined(CLOCK_PROCESS_CPUTIME_ID) CLOCK_PROCESS_CPUTIME_ID, #endif #if defined(CLOCK_THREAD_CPUTIME_ID) CLOCK_THREAD_CPUTIME_ID, #endif }; for(clockid_t clock : clock_types) { struct timespec ts; if(::clock_gettime(clock, &ts) == 0) { return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec); } } #endif // Plain C++11 fallback auto now = std::chrono::high_resolution_clock::now().time_since_epoch(); return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count(); } uint64_t OS::get_system_timestamp_ns() { #if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME) struct timespec ts; if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) { return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec); } #endif auto now = std::chrono::system_clock::now().time_since_epoch(); return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count(); } size_t OS::get_memory_locking_limit() { #if defined(BOTAN_TARGET_OS_HAS_POSIX1) /* * Linux defaults to only 64 KiB of mlockable memory per process * (too small) but BSDs offer a small fraction of total RAM (more * than we need). Bound the total mlock size to 512 KiB which is * enough to run the entire test suite without spilling to non-mlock * memory (and thus presumably also enough for many useful * programs), but small enough that we should not cause problems * even if many processes are mlocking on the same machine. */ size_t mlock_requested = BOTAN_MLOCK_ALLOCATOR_MAX_LOCKED_KB; /* * Allow override via env variable */ if(const char* env = std::getenv("BOTAN_MLOCK_POOL_SIZE")) { try { const size_t user_req = std::stoul(env, nullptr); mlock_requested = std::min(user_req, mlock_requested); } catch(std::exception&) { /* ignore it */ } } #if defined(RLIMIT_MEMLOCK) if(mlock_requested > 0) { struct ::rlimit limits; ::getrlimit(RLIMIT_MEMLOCK, &limits); if(limits.rlim_cur < limits.rlim_max) { limits.rlim_cur = limits.rlim_max; ::setrlimit(RLIMIT_MEMLOCK, &limits); ::getrlimit(RLIMIT_MEMLOCK, &limits); } return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024); } #else /* * If RLIMIT_MEMLOCK is not defined, likely the OS does not support * unprivileged mlock calls. */ return 0; #endif #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK) SIZE_T working_min = 0, working_max = 0; if(!::GetProcessWorkingSetSize(::GetCurrentProcess(), &working_min, &working_max)) { return 0; } SYSTEM_INFO sSysInfo; ::GetSystemInfo(&sSysInfo); // According to Microsoft MSDN: // The maximum number of pages that a process can lock is equal to the number of pages in its minimum working set minus a small overhead // In the book "Windows Internals Part 2": the maximum lockable pages are minimum working set size - 8 pages // But the information in the book seems to be inaccurate/outdated // I've tested this on Windows 8.1 x64, Windows 10 x64 and Windows 7 x86 // On all three OS the value is 11 instead of 8 size_t overhead = sSysInfo.dwPageSize * 11ULL; if(working_min > overhead) { size_t lockable_bytes = working_min - overhead; if(lockable_bytes < (BOTAN_MLOCK_ALLOCATOR_MAX_LOCKED_KB * 1024ULL)) { return lockable_bytes; } else { return BOTAN_MLOCK_ALLOCATOR_MAX_LOCKED_KB * 1024ULL; } } #endif return 0; } void* OS::allocate_locked_pages(size_t length) { #if defined(BOTAN_TARGET_OS_HAS_POSIX1) #if !defined(MAP_NOCORE) #define MAP_NOCORE 0 #endif #if !defined(MAP_ANONYMOUS) #define MAP_ANONYMOUS MAP_ANON #endif void* ptr = ::mmap(nullptr, length, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED | MAP_NOCORE, /*fd*/-1, /*offset*/0); if(ptr == MAP_FAILED) { return nullptr; } #if defined(MADV_DONTDUMP) ::madvise(ptr, length, MADV_DONTDUMP); #endif if(::mlock(ptr, length) != 0) { ::munmap(ptr, length); return nullptr; // failed to lock } ::memset(ptr, 0, length); return ptr; #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK) LPVOID ptr = ::VirtualAlloc(nullptr, length, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if(!ptr) { return nullptr; } if(::VirtualLock(ptr, length) == 0) { ::VirtualFree(ptr, 0, MEM_RELEASE); return nullptr; // failed to lock } return ptr; #else BOTAN_UNUSED(length); return nullptr; /* not implemented */ #endif } void OS::free_locked_pages(void* ptr, size_t length) { if(ptr == nullptr || length == 0) return; #if defined(BOTAN_TARGET_OS_HAS_POSIX1) secure_scrub_memory(ptr, length); ::munlock(ptr, length); ::munmap(ptr, length); #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK) secure_scrub_memory(ptr, length); ::VirtualUnlock(ptr, length); ::VirtualFree(ptr, 0, MEM_RELEASE); #else // Invalid argument because no way this pointer was allocated by us throw Invalid_Argument("Invalid ptr to free_locked_pages"); #endif } #if defined(BOTAN_TARGET_OS_HAS_POSIX1) namespace { static ::sigjmp_buf g_sigill_jmp_buf; void botan_sigill_handler(int) { siglongjmp(g_sigill_jmp_buf, /*non-zero return value*/1); } } #endif int OS::run_cpu_instruction_probe(std::function<int ()> probe_fn) { volatile int probe_result = -3; #if defined(BOTAN_TARGET_OS_HAS_POSIX1) struct sigaction old_sigaction; struct sigaction sigaction; sigaction.sa_handler = botan_sigill_handler; sigemptyset(&sigaction.sa_mask); sigaction.sa_flags = 0; int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction); if(rc != 0) throw Exception("run_cpu_instruction_probe sigaction failed"); rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/1); if(rc == 0) { // first call to sigsetjmp probe_result = probe_fn(); } else if(rc == 1) { // non-local return from siglongjmp in signal handler: return error probe_result = -1; } // Restore old SIGILL handler, if any rc = ::sigaction(SIGILL, &old_sigaction, nullptr); if(rc != 0) throw Exception("run_cpu_instruction_probe sigaction restore failed"); #elif defined(BOTAN_TARGET_OS_IS_WINDOWS) && defined(BOTAN_TARGET_COMPILER_IS_MSVC) // Windows SEH __try { probe_result = probe_fn(); } __except(::GetExceptionCode() == EXCEPTION_ILLEGAL_INSTRUCTION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { probe_result = -1; } #endif return probe_result; } } <commit_msg>Correctly read the POWER cycle counter<commit_after>/* * OS and machine specific utility functions * (C) 2015,2016,2017 Jack Lloyd * (C) 2016 Daniel Neus * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/os_utils.h> #include <botan/cpuid.h> #include <botan/exceptn.h> #include <botan/mem_ops.h> #include <chrono> #include <cstdlib> #if defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO) #include <string.h> #endif #if defined(BOTAN_TARGET_OS_HAS_POSIX1) #include <sys/types.h> #include <sys/resource.h> #include <sys/mman.h> #include <signal.h> #include <setjmp.h> #include <unistd.h> #include <errno.h> #elif defined(BOTAN_TARGET_OS_HAS_WIN32) #define NOMINMAX 1 #include <windows.h> #endif namespace Botan { // Not defined in OS namespace for historical reasons void secure_scrub_memory(void* ptr, size_t n) { #if defined(BOTAN_TARGET_OS_HAS_RTLSECUREZEROMEMORY) ::RtlSecureZeroMemory(ptr, n); #elif defined(BOTAN_TARGET_OS_HAS_EXPLICIT_BZERO) ::explicit_bzero(ptr, n); #elif defined(BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO) && (BOTAN_USE_VOLATILE_MEMSET_FOR_ZERO == 1) /* Call memset through a static volatile pointer, which the compiler should not elide. This construct should be safe in conforming compilers, but who knows. I did confirm that on x86-64 GCC 6.1 and Clang 3.8 both create code that saves the memset address in the data segment and uncondtionally loads and jumps to that address. */ static void* (*const volatile memset_ptr)(void*, int, size_t) = std::memset; (memset_ptr)(ptr, 0, n); #else volatile uint8_t* p = reinterpret_cast<volatile uint8_t*>(ptr); for(size_t i = 0; i != n; ++i) p[i] = 0; #endif } uint32_t OS::get_process_id() { #if defined(BOTAN_TARGET_OS_HAS_POSIX1) return ::getpid(); #elif defined(BOTAN_TARGET_OS_HAS_WIN32) return ::GetCurrentProcessId(); #elif defined(BOTAN_TARGET_OS_IS_INCLUDEOS) || defined(BOTAN_TARGET_OS_IS_LLVM) return 0; // truly no meaningful value #else #error "Missing get_process_id" #endif } uint64_t OS::get_processor_timestamp() { uint64_t rtc = 0; #if defined(BOTAN_TARGET_OS_HAS_WIN32) LARGE_INTEGER tv; ::QueryPerformanceCounter(&tv); rtc = tv.QuadPart; #elif defined(BOTAN_USE_GCC_INLINE_ASM) #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY) if(CPUID::has_rdtsc()) { uint32_t rtc_low = 0, rtc_high = 0; asm volatile("rdtsc" : "=d" (rtc_high), "=a" (rtc_low)); rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low; } #elif defined(BOTAN_TARGET_ARCH_IS_PPC64) for(;;) { uint32_t rtc_low = 0, rtc_high = 0, rtc_high2 = 0; asm volatile("mftbu %0" : "=r" (rtc_high)); asm volatile("mftb %0" : "=r" (rtc_low)); asm volatile("mftbu %0" : "=r" (rtc_high2)); if(rtc_high == rtc_high2) { rtc = (static_cast<uint64_t>(rtc_high) << 32) | rtc_low; break; } } #elif defined(BOTAN_TARGET_ARCH_IS_ALPHA) asm volatile("rpcc %0" : "=r" (rtc)); // OpenBSD does not trap access to the %tick register #elif defined(BOTAN_TARGET_ARCH_IS_SPARC64) && !defined(BOTAN_TARGET_OS_IS_OPENBSD) asm volatile("rd %%tick, %0" : "=r" (rtc)); #elif defined(BOTAN_TARGET_ARCH_IS_IA64) asm volatile("mov %0=ar.itc" : "=r" (rtc)); #elif defined(BOTAN_TARGET_ARCH_IS_S390X) asm volatile("stck 0(%0)" : : "a" (&rtc) : "memory", "cc"); #elif defined(BOTAN_TARGET_ARCH_IS_HPPA) asm volatile("mfctl 16,%0" : "=r" (rtc)); // 64-bit only? #else //#warning "OS::get_processor_timestamp not implemented" #endif #endif return rtc; } uint64_t OS::get_high_resolution_clock() { if(uint64_t cpu_clock = OS::get_processor_timestamp()) return cpu_clock; /* If we got here either we either don't have an asm instruction above, or (for x86) RDTSC is not available at runtime. Try some clock_gettimes and return the first one that works, or otherwise fall back to std::chrono. */ #if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME) // The ordering here is somewhat arbitrary... const clockid_t clock_types[] = { #if defined(CLOCK_MONOTONIC_HR) CLOCK_MONOTONIC_HR, #endif #if defined(CLOCK_MONOTONIC_RAW) CLOCK_MONOTONIC_RAW, #endif #if defined(CLOCK_MONOTONIC) CLOCK_MONOTONIC, #endif #if defined(CLOCK_PROCESS_CPUTIME_ID) CLOCK_PROCESS_CPUTIME_ID, #endif #if defined(CLOCK_THREAD_CPUTIME_ID) CLOCK_THREAD_CPUTIME_ID, #endif }; for(clockid_t clock : clock_types) { struct timespec ts; if(::clock_gettime(clock, &ts) == 0) { return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec); } } #endif // Plain C++11 fallback auto now = std::chrono::high_resolution_clock::now().time_since_epoch(); return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count(); } uint64_t OS::get_system_timestamp_ns() { #if defined(BOTAN_TARGET_OS_HAS_CLOCK_GETTIME) struct timespec ts; if(::clock_gettime(CLOCK_REALTIME, &ts) == 0) { return (static_cast<uint64_t>(ts.tv_sec) * 1000000000) + static_cast<uint64_t>(ts.tv_nsec); } #endif auto now = std::chrono::system_clock::now().time_since_epoch(); return std::chrono::duration_cast<std::chrono::nanoseconds>(now).count(); } size_t OS::get_memory_locking_limit() { #if defined(BOTAN_TARGET_OS_HAS_POSIX1) /* * Linux defaults to only 64 KiB of mlockable memory per process * (too small) but BSDs offer a small fraction of total RAM (more * than we need). Bound the total mlock size to 512 KiB which is * enough to run the entire test suite without spilling to non-mlock * memory (and thus presumably also enough for many useful * programs), but small enough that we should not cause problems * even if many processes are mlocking on the same machine. */ size_t mlock_requested = BOTAN_MLOCK_ALLOCATOR_MAX_LOCKED_KB; /* * Allow override via env variable */ if(const char* env = std::getenv("BOTAN_MLOCK_POOL_SIZE")) { try { const size_t user_req = std::stoul(env, nullptr); mlock_requested = std::min(user_req, mlock_requested); } catch(std::exception&) { /* ignore it */ } } #if defined(RLIMIT_MEMLOCK) if(mlock_requested > 0) { struct ::rlimit limits; ::getrlimit(RLIMIT_MEMLOCK, &limits); if(limits.rlim_cur < limits.rlim_max) { limits.rlim_cur = limits.rlim_max; ::setrlimit(RLIMIT_MEMLOCK, &limits); ::getrlimit(RLIMIT_MEMLOCK, &limits); } return std::min<size_t>(limits.rlim_cur, mlock_requested * 1024); } #else /* * If RLIMIT_MEMLOCK is not defined, likely the OS does not support * unprivileged mlock calls. */ return 0; #endif #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK) SIZE_T working_min = 0, working_max = 0; if(!::GetProcessWorkingSetSize(::GetCurrentProcess(), &working_min, &working_max)) { return 0; } SYSTEM_INFO sSysInfo; ::GetSystemInfo(&sSysInfo); // According to Microsoft MSDN: // The maximum number of pages that a process can lock is equal to the number of pages in its minimum working set minus a small overhead // In the book "Windows Internals Part 2": the maximum lockable pages are minimum working set size - 8 pages // But the information in the book seems to be inaccurate/outdated // I've tested this on Windows 8.1 x64, Windows 10 x64 and Windows 7 x86 // On all three OS the value is 11 instead of 8 size_t overhead = sSysInfo.dwPageSize * 11ULL; if(working_min > overhead) { size_t lockable_bytes = working_min - overhead; if(lockable_bytes < (BOTAN_MLOCK_ALLOCATOR_MAX_LOCKED_KB * 1024ULL)) { return lockable_bytes; } else { return BOTAN_MLOCK_ALLOCATOR_MAX_LOCKED_KB * 1024ULL; } } #endif return 0; } void* OS::allocate_locked_pages(size_t length) { #if defined(BOTAN_TARGET_OS_HAS_POSIX1) #if !defined(MAP_NOCORE) #define MAP_NOCORE 0 #endif #if !defined(MAP_ANONYMOUS) #define MAP_ANONYMOUS MAP_ANON #endif void* ptr = ::mmap(nullptr, length, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED | MAP_NOCORE, /*fd*/-1, /*offset*/0); if(ptr == MAP_FAILED) { return nullptr; } #if defined(MADV_DONTDUMP) ::madvise(ptr, length, MADV_DONTDUMP); #endif if(::mlock(ptr, length) != 0) { ::munmap(ptr, length); return nullptr; // failed to lock } ::memset(ptr, 0, length); return ptr; #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK) LPVOID ptr = ::VirtualAlloc(nullptr, length, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if(!ptr) { return nullptr; } if(::VirtualLock(ptr, length) == 0) { ::VirtualFree(ptr, 0, MEM_RELEASE); return nullptr; // failed to lock } return ptr; #else BOTAN_UNUSED(length); return nullptr; /* not implemented */ #endif } void OS::free_locked_pages(void* ptr, size_t length) { if(ptr == nullptr || length == 0) return; #if defined(BOTAN_TARGET_OS_HAS_POSIX1) secure_scrub_memory(ptr, length); ::munlock(ptr, length); ::munmap(ptr, length); #elif defined(BOTAN_TARGET_OS_HAS_VIRTUAL_LOCK) secure_scrub_memory(ptr, length); ::VirtualUnlock(ptr, length); ::VirtualFree(ptr, 0, MEM_RELEASE); #else // Invalid argument because no way this pointer was allocated by us throw Invalid_Argument("Invalid ptr to free_locked_pages"); #endif } #if defined(BOTAN_TARGET_OS_HAS_POSIX1) namespace { static ::sigjmp_buf g_sigill_jmp_buf; void botan_sigill_handler(int) { siglongjmp(g_sigill_jmp_buf, /*non-zero return value*/1); } } #endif int OS::run_cpu_instruction_probe(std::function<int ()> probe_fn) { volatile int probe_result = -3; #if defined(BOTAN_TARGET_OS_HAS_POSIX1) struct sigaction old_sigaction; struct sigaction sigaction; sigaction.sa_handler = botan_sigill_handler; sigemptyset(&sigaction.sa_mask); sigaction.sa_flags = 0; int rc = ::sigaction(SIGILL, &sigaction, &old_sigaction); if(rc != 0) throw Exception("run_cpu_instruction_probe sigaction failed"); rc = sigsetjmp(g_sigill_jmp_buf, /*save sigs*/1); if(rc == 0) { // first call to sigsetjmp probe_result = probe_fn(); } else if(rc == 1) { // non-local return from siglongjmp in signal handler: return error probe_result = -1; } // Restore old SIGILL handler, if any rc = ::sigaction(SIGILL, &old_sigaction, nullptr); if(rc != 0) throw Exception("run_cpu_instruction_probe sigaction restore failed"); #elif defined(BOTAN_TARGET_OS_IS_WINDOWS) && defined(BOTAN_TARGET_COMPILER_IS_MSVC) // Windows SEH __try { probe_result = probe_fn(); } __except(::GetExceptionCode() == EXCEPTION_ILLEGAL_INSTRUCTION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { probe_result = -1; } #endif return probe_result; } } <|endoftext|>
<commit_before>#include "HalideRuntime.h" extern "C" { typedef long dispatch_once_t; extern void dispatch_once_f(dispatch_once_t *, void *context, void (*initializer)(void *)); typedef struct dispatch_queue_s *dispatch_queue_t; typedef long dispatch_queue_priority_t; extern dispatch_queue_t dispatch_get_global_queue( dispatch_queue_priority_t priority, unsigned long flags); extern void dispatch_apply_f(size_t iterations, dispatch_queue_t queue, void *context, void (*work)(void *, size_t)); extern void dispatch_async_f(dispatch_queue_t queue, void *context, void (*work)(void *)); typedef struct dispatch_semaphore_s *dispatch_semaphore_t; typedef uint64_t dispatch_time_t; #define DISPATCH_TIME_FOREVER (~0ull) extern dispatch_semaphore_t dispatch_semaphore_create(long value); extern long dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout); extern long dispatch_semaphore_signal(dispatch_semaphore_t dsema); extern void dispatch_release(void *object); WEAK int halide_do_task(void *user_context, halide_task_t f, int idx, uint8_t *closure); } namespace Halide { namespace Runtime { namespace Internal { struct spawned_thread { void (*f)(void *); void *closure; dispatch_semaphore_t join_semaphore; }; WEAK void spawn_thread_helper(void *arg) { spawned_thread *t = (spawned_thread *)arg; t->f(t->closure); dispatch_semaphore_signal(t->join_semaphore); } }}} // namespace Halide::Runtime::Internal WEAK halide_thread *halide_spawn_thread(void (*f)(void *), void *closure) { spawned_thread *thread = (spawned_thread *)malloc(sizeof(spawned_thread)); thread->f = f; thread->closure = closure; thread->join_semaphore = dispatch_semaphore_create(0); dispatch_async_f(dispatch_get_global_queue(0, 0), thread, spawn_thread_helper); return (halide_thread *)thread; } WEAK void halide_join_thread(halide_thread *thread_arg) { spawned_thread *thread = (spawned_thread *)thread_arg; dispatch_semaphore_wait(thread->join_semaphore, DISPATCH_TIME_FOREVER); free(thread); } // Join thread and condition variables intentionally unimplemented for // now on OS X. Use of them will result in linker errors. Currently // only the common thread pool uses them. namespace Halide { namespace Runtime { namespace Internal { WEAK int custom_num_threads = 0; struct gcd_mutex { dispatch_once_t once; dispatch_semaphore_t semaphore; }; WEAK void init_mutex(void *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; mutex->semaphore = dispatch_semaphore_create(1); } WEAK int default_do_task(void *user_context, int (*f)(void *, int, uint8_t *), int idx, uint8_t *closure) { return f(user_context, idx, closure); } struct halide_gcd_job { int (*f)(void *, int, uint8_t *); void *user_context; uint8_t *closure; int min; int exit_status; }; // Take a call from grand-central-dispatch's parallel for loop, and // make a call to Halide's do task WEAK void halide_do_gcd_task(void *job, size_t idx) { halide_gcd_job *j = (halide_gcd_job *)job; j->exit_status = halide_do_task(j->user_context, j->f, j->min + (int)idx, j->closure); } WEAK int default_do_par_for(void *user_context, halide_task_t f, int min, int size, uint8_t *closure) { if (custom_num_threads == 1) { // GCD doesn't really allow us to limit the threads, // so ensure that there's no parallelism by executing serially. for (int x = min; x < min + size; x++) { int result = halide_do_task(user_context, f, x, closure); if (result) { return result; } } return 0; } halide_gcd_job job; job.f = f; job.user_context = user_context; job.closure = closure; job.min = min; job.exit_status = 0; dispatch_apply_f(size, dispatch_get_global_queue(0, 0), &job, &halide_do_gcd_task); return job.exit_status; } WEAK halide_do_task_t custom_do_task = default_do_task; WEAK halide_do_par_for_t custom_do_par_for = default_do_par_for; }}} // namespace Halide::Runtime::Internal extern "C" { WEAK void halide_mutex_destroy(halide_mutex *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; if (mutex->once != 0) { dispatch_release(mutex->semaphore); memset(mutex_arg, 0, sizeof(halide_mutex)); } } WEAK void halide_mutex_lock(halide_mutex *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; dispatch_once_f(&mutex->once, mutex, init_mutex); dispatch_semaphore_wait(mutex->semaphore, DISPATCH_TIME_FOREVER); } WEAK void halide_mutex_unlock(halide_mutex *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; dispatch_semaphore_signal(mutex->semaphore); } WEAK void halide_shutdown_thread_pool() { } WEAK int halide_set_num_threads(int n) { if (n < 0) { halide_error(NULL, "halide_set_num_threads: must be >= 0."); } int old_custom_num_threads = custom_num_threads; custom_num_threads = n; return old_custom_num_threads; } WEAK halide_do_task_t halide_set_custom_do_task(halide_do_task_t f) { halide_do_task_t result = custom_do_task; custom_do_task = f; return result; } WEAK halide_do_par_for_t halide_set_custom_do_par_for(halide_do_par_for_t f) { halide_do_par_for_t result = custom_do_par_for; custom_do_par_for = f; return result; } WEAK int halide_do_task(void *user_context, halide_task_t f, int idx, uint8_t *closure) { return (*custom_do_task)(user_context, f, idx, closure); } WEAK int halide_do_par_for(void *user_context, halide_task_t f, int min, int size, uint8_t *closure) { return (*custom_do_par_for)(user_context, f, min, size, closure); } } <commit_msg>add size == 1 check to GCD<commit_after>#include "HalideRuntime.h" extern "C" { typedef long dispatch_once_t; extern void dispatch_once_f(dispatch_once_t *, void *context, void (*initializer)(void *)); typedef struct dispatch_queue_s *dispatch_queue_t; typedef long dispatch_queue_priority_t; extern dispatch_queue_t dispatch_get_global_queue( dispatch_queue_priority_t priority, unsigned long flags); extern void dispatch_apply_f(size_t iterations, dispatch_queue_t queue, void *context, void (*work)(void *, size_t)); extern void dispatch_async_f(dispatch_queue_t queue, void *context, void (*work)(void *)); typedef struct dispatch_semaphore_s *dispatch_semaphore_t; typedef uint64_t dispatch_time_t; #define DISPATCH_TIME_FOREVER (~0ull) extern dispatch_semaphore_t dispatch_semaphore_create(long value); extern long dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout); extern long dispatch_semaphore_signal(dispatch_semaphore_t dsema); extern void dispatch_release(void *object); WEAK int halide_do_task(void *user_context, halide_task_t f, int idx, uint8_t *closure); } namespace Halide { namespace Runtime { namespace Internal { struct spawned_thread { void (*f)(void *); void *closure; dispatch_semaphore_t join_semaphore; }; WEAK void spawn_thread_helper(void *arg) { spawned_thread *t = (spawned_thread *)arg; t->f(t->closure); dispatch_semaphore_signal(t->join_semaphore); } }}} // namespace Halide::Runtime::Internal WEAK halide_thread *halide_spawn_thread(void (*f)(void *), void *closure) { spawned_thread *thread = (spawned_thread *)malloc(sizeof(spawned_thread)); thread->f = f; thread->closure = closure; thread->join_semaphore = dispatch_semaphore_create(0); dispatch_async_f(dispatch_get_global_queue(0, 0), thread, spawn_thread_helper); return (halide_thread *)thread; } WEAK void halide_join_thread(halide_thread *thread_arg) { spawned_thread *thread = (spawned_thread *)thread_arg; dispatch_semaphore_wait(thread->join_semaphore, DISPATCH_TIME_FOREVER); free(thread); } // Join thread and condition variables intentionally unimplemented for // now on OS X. Use of them will result in linker errors. Currently // only the common thread pool uses them. namespace Halide { namespace Runtime { namespace Internal { WEAK int custom_num_threads = 0; struct gcd_mutex { dispatch_once_t once; dispatch_semaphore_t semaphore; }; WEAK void init_mutex(void *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; mutex->semaphore = dispatch_semaphore_create(1); } WEAK int default_do_task(void *user_context, int (*f)(void *, int, uint8_t *), int idx, uint8_t *closure) { return f(user_context, idx, closure); } struct halide_gcd_job { int (*f)(void *, int, uint8_t *); void *user_context; uint8_t *closure; int min; int exit_status; }; // Take a call from grand-central-dispatch's parallel for loop, and // make a call to Halide's do task WEAK void halide_do_gcd_task(void *job, size_t idx) { halide_gcd_job *j = (halide_gcd_job *)job; j->exit_status = halide_do_task(j->user_context, j->f, j->min + (int)idx, j->closure); } WEAK int default_do_par_for(void *user_context, halide_task_t f, int min, int size, uint8_t *closure) { if (custom_num_threads == 1 || size == 1) { // GCD doesn't really allow us to limit the threads, // so ensure that there's no parallelism by executing serially. for (int x = min; x < min + size; x++) { int result = halide_do_task(user_context, f, x, closure); if (result) { return result; } } return 0; } halide_gcd_job job; job.f = f; job.user_context = user_context; job.closure = closure; job.min = min; job.exit_status = 0; dispatch_apply_f(size, dispatch_get_global_queue(0, 0), &job, &halide_do_gcd_task); return job.exit_status; } WEAK halide_do_task_t custom_do_task = default_do_task; WEAK halide_do_par_for_t custom_do_par_for = default_do_par_for; }}} // namespace Halide::Runtime::Internal extern "C" { WEAK void halide_mutex_destroy(halide_mutex *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; if (mutex->once != 0) { dispatch_release(mutex->semaphore); memset(mutex_arg, 0, sizeof(halide_mutex)); } } WEAK void halide_mutex_lock(halide_mutex *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; dispatch_once_f(&mutex->once, mutex, init_mutex); dispatch_semaphore_wait(mutex->semaphore, DISPATCH_TIME_FOREVER); } WEAK void halide_mutex_unlock(halide_mutex *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; dispatch_semaphore_signal(mutex->semaphore); } WEAK void halide_shutdown_thread_pool() { } WEAK int halide_set_num_threads(int n) { if (n < 0) { halide_error(NULL, "halide_set_num_threads: must be >= 0."); } int old_custom_num_threads = custom_num_threads; custom_num_threads = n; return old_custom_num_threads; } WEAK halide_do_task_t halide_set_custom_do_task(halide_do_task_t f) { halide_do_task_t result = custom_do_task; custom_do_task = f; return result; } WEAK halide_do_par_for_t halide_set_custom_do_par_for(halide_do_par_for_t f) { halide_do_par_for_t result = custom_do_par_for; custom_do_par_for = f; return result; } WEAK int halide_do_task(void *user_context, halide_task_t f, int idx, uint8_t *closure) { return (*custom_do_task)(user_context, f, idx, closure); } WEAK int halide_do_par_for(void *user_context, halide_task_t f, int min, int size, uint8_t *closure) { return (*custom_do_par_for)(user_context, f, min, size, closure); } } <|endoftext|>
<commit_before>#include <allegro5/allegro.h> #include <cstdio> #include <fstream> #include "inputcatcher.h" #include "datastructures.h" #include "renderer.h" #include "ingameelements/character.h" #include "global_constants.h" #define LEFT_MOUSE_BUTTON 1 #define RIGHT_MOUSE_BUTTON 2 InputCatcher::InputCatcher(ALLEGRO_DISPLAY *display) { // Create an event queue, and error if it fails event_queue = al_create_event_queue(); if (!event_queue) { fprintf(stderr, "Fatal Error: Could not create event queue!"); throw -1; } // Connect the window, keyboard and mouse events to this event queue al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_keyboard_event_source()); // al_register_event_source(event_queue, al_get_mouse_event_source(display)); std::ifstream configfile("config.json"); config << configfile; configfile.close(); } InputCatcher::~InputCatcher() { al_destroy_event_queue(event_queue); } void InputCatcher::run(ALLEGRO_DISPLAY *display, InputContainer *held_keys, double *mouse_x, double *mouse_y) { // pressed_keys->reset(); held_keys->reset(); ALLEGRO_EVENT event; // Catch all events that have stacked up this frame. al_get_next_event() returns false when event_queue is empty, and contents of event are undefined while (al_get_next_event(event_queue, &event)) { switch (event.type) { case ALLEGRO_EVENT_DISPLAY_CLOSE: // Deliberate closing, not an error throw 0; case ALLEGRO_EVENT_DISPLAY_RESIZE: al_acknowledge_resize(display); break; // case ALLEGRO_EVENT_KEY_DOWN: // //Debug: print the keycode number and name of the key we press //// printf("\n%i\t%s", event.keyboard.keycode, al_keycode_to_name(event.keyboard.keycode)); // // if (event.keyboard.keycode == config["jump"] or event.keyboard.keycode == config["jump_alt1"] or event.keyboard.keycode == config["jump_alt2"]) // { // pressed_keys->JUMP = true; // } // if (event.keyboard.keycode == config["crouch"] or event.keyboard.keycode == config["crouch_alt1"] or event.keyboard.keycode == config["crouch_alt2"]) // { // pressed_keys->CROUCH = true; // } // if (event.keyboard.keycode == config["left"] or event.keyboard.keycode == config["left_alt1"] or event.keyboard.keycode == config["left_alt2"]) // { // pressed_keys->LEFT = true; // } // if (event.keyboard.keycode == config["right"] or event.keyboard.keycode == config["right_alt1"] or event.keyboard.keycode == config["right_alt2"]) // { // pressed_keys->RIGHT = true; // } // if (event.keyboard.keycode == config["right"] or event.keyboard.keycode == config["right_alt1"] or event.keyboard.keycode == config["right_alt2"]) // { // pressed_keys->RIGHT = true; // } // if (event.keyboard.keycode == config["ability1"] or event.keyboard.keycode == config["ability1_alt1"] or event.keyboard.keycode == config["ability1_alt2"]) // { // pressed_keys->ABILITY_1 = true; // } // if (event.keyboard.keycode == config["ability2"] or event.keyboard.keycode == config["ability2_alt1"] or event.keyboard.keycode == config["ability2_alt2"]) // { // pressed_keys->ABILITY_2 = true; // } // if (event.keyboard.keycode == config["ultimate"] or event.keyboard.keycode == config["ultimate_alt1"] or event.keyboard.keycode == config["ultimate_alt2"]) // { // pressed_keys->ULTIMATE = true; // } // if (event.keyboard.keycode == config["reload"] or event.keyboard.keycode == config["reload_alt1"] or event.keyboard.keycode == config["reload_alt2"]) // { // pressed_keys->RELOAD = true; // } // // switch (event.keyboard.keycode) // { // case ALLEGRO_KEY_ESCAPE: // // Exit game // throw 0; // } // // case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN: // switch (event.mouse.button) // { // case LEFT_MOUSE_BUTTON: // pressed_keys->PRIMARY_FIRE = true; // break; // case RIGHT_MOUSE_BUTTON: // pressed_keys->SECONDARY_FIRE = true; // break; // } } } ALLEGRO_KEYBOARD_STATE keystate; al_get_keyboard_state(&keystate); if (al_key_down(&keystate, config["jump"]) or al_key_down(&keystate, config["jump_alt1"]) or al_key_down(&keystate, config["jump_alt2"])) { held_keys->JUMP = true; } if (al_key_down(&keystate, config["crouch"]) or al_key_down(&keystate, config["crouch_alt1"]) or al_key_down(&keystate, config["crouch_alt2"])) { held_keys->CROUCH = true; } if (al_key_down(&keystate, config["left"]) or al_key_down(&keystate, config["left_alt1"]) or al_key_down(&keystate, config["left_alt2"])) { held_keys->LEFT = true; } if (al_key_down(&keystate, config["right"]) or al_key_down(&keystate, config["right_alt1"]) or al_key_down(&keystate, config["right_alt2"])) { held_keys->RIGHT = true; } if (al_key_down(&keystate, config["ability1"]) or al_key_down(&keystate, config["ability1_alt1"]) or al_key_down(&keystate, config["ability1_alt2"])) { held_keys->ABILITY_1 = true; } if (al_key_down(&keystate, config["ability2"]) or al_key_down(&keystate, config["ability2_alt1"]) or al_key_down(&keystate, config["ability2_alt2"])) { held_keys->ABILITY_2 = true; } if (al_key_down(&keystate, config["ultimate"]) or al_key_down(&keystate, config["ultimate_alt1"]) or al_key_down(&keystate, config["ultimate_alt2"])) { held_keys->ULTIMATE = true; } if (al_key_down(&keystate, config["reload"]) or al_key_down(&keystate, config["reload_alt1"]) or al_key_down(&keystate, config["reload_alt2"])) { held_keys->RELOAD = true; } ALLEGRO_MOUSE_STATE mousestate; al_get_mouse_state(&mousestate); // FIXME: I have no idea if these constants are correct, allegro docs don't mention the specifics, just that it starts with 1. if (mousestate.buttons & LEFT_MOUSE_BUTTON) { held_keys->PRIMARY_FIRE = true; } if (mousestate.buttons & RIGHT_MOUSE_BUTTON) { held_keys->SECONDARY_FIRE = true; } *mouse_x = mousestate.x; *mouse_y = mousestate.y; } <commit_msg>Fixed missing esc quit.<commit_after>#include <allegro5/allegro.h> #include <cstdio> #include <fstream> #include "inputcatcher.h" #include "datastructures.h" #include "renderer.h" #include "ingameelements/character.h" #include "global_constants.h" #define LEFT_MOUSE_BUTTON 1 #define RIGHT_MOUSE_BUTTON 2 InputCatcher::InputCatcher(ALLEGRO_DISPLAY *display) { // Create an event queue, and error if it fails event_queue = al_create_event_queue(); if (!event_queue) { fprintf(stderr, "Fatal Error: Could not create event queue!"); throw -1; } // Connect the window, keyboard and mouse events to this event queue al_register_event_source(event_queue, al_get_display_event_source(display)); al_register_event_source(event_queue, al_get_keyboard_event_source()); // al_register_event_source(event_queue, al_get_mouse_event_source(display)); std::ifstream configfile("config.json"); config << configfile; configfile.close(); } InputCatcher::~InputCatcher() { al_destroy_event_queue(event_queue); } void InputCatcher::run(ALLEGRO_DISPLAY *display, InputContainer *held_keys, double *mouse_x, double *mouse_y) { // pressed_keys->reset(); held_keys->reset(); ALLEGRO_EVENT event; // Catch all events that have stacked up this frame. al_get_next_event() returns false when event_queue is empty, and contents of event are undefined while (al_get_next_event(event_queue, &event)) { switch (event.type) { case ALLEGRO_EVENT_DISPLAY_CLOSE: // Deliberate closing, not an error throw 0; case ALLEGRO_EVENT_DISPLAY_RESIZE: al_acknowledge_resize(display); break; case ALLEGRO_EVENT_KEY_DOWN: // //Debug: print the keycode number and name of the key we press //// printf("\n%i\t%s", event.keyboard.keycode, al_keycode_to_name(event.keyboard.keycode)); // // if (event.keyboard.keycode == config["jump"] or event.keyboard.keycode == config["jump_alt1"] or event.keyboard.keycode == config["jump_alt2"]) // { // pressed_keys->JUMP = true; // } // if (event.keyboard.keycode == config["crouch"] or event.keyboard.keycode == config["crouch_alt1"] or event.keyboard.keycode == config["crouch_alt2"]) // { // pressed_keys->CROUCH = true; // } // if (event.keyboard.keycode == config["left"] or event.keyboard.keycode == config["left_alt1"] or event.keyboard.keycode == config["left_alt2"]) // { // pressed_keys->LEFT = true; // } // if (event.keyboard.keycode == config["right"] or event.keyboard.keycode == config["right_alt1"] or event.keyboard.keycode == config["right_alt2"]) // { // pressed_keys->RIGHT = true; // } // if (event.keyboard.keycode == config["right"] or event.keyboard.keycode == config["right_alt1"] or event.keyboard.keycode == config["right_alt2"]) // { // pressed_keys->RIGHT = true; // } // if (event.keyboard.keycode == config["ability1"] or event.keyboard.keycode == config["ability1_alt1"] or event.keyboard.keycode == config["ability1_alt2"]) // { // pressed_keys->ABILITY_1 = true; // } // if (event.keyboard.keycode == config["ability2"] or event.keyboard.keycode == config["ability2_alt1"] or event.keyboard.keycode == config["ability2_alt2"]) // { // pressed_keys->ABILITY_2 = true; // } // if (event.keyboard.keycode == config["ultimate"] or event.keyboard.keycode == config["ultimate_alt1"] or event.keyboard.keycode == config["ultimate_alt2"]) // { // pressed_keys->ULTIMATE = true; // } // if (event.keyboard.keycode == config["reload"] or event.keyboard.keycode == config["reload_alt1"] or event.keyboard.keycode == config["reload_alt2"]) // { // pressed_keys->RELOAD = true; // } // switch (event.keyboard.keycode) { case ALLEGRO_KEY_ESCAPE: // Exit game throw 0; } // // case ALLEGRO_EVENT_MOUSE_BUTTON_DOWN: // switch (event.mouse.button) // { // case LEFT_MOUSE_BUTTON: // pressed_keys->PRIMARY_FIRE = true; // break; // case RIGHT_MOUSE_BUTTON: // pressed_keys->SECONDARY_FIRE = true; // break; // } } } ALLEGRO_KEYBOARD_STATE keystate; al_get_keyboard_state(&keystate); if (al_key_down(&keystate, config["jump"]) or al_key_down(&keystate, config["jump_alt1"]) or al_key_down(&keystate, config["jump_alt2"])) { held_keys->JUMP = true; } if (al_key_down(&keystate, config["crouch"]) or al_key_down(&keystate, config["crouch_alt1"]) or al_key_down(&keystate, config["crouch_alt2"])) { held_keys->CROUCH = true; } if (al_key_down(&keystate, config["left"]) or al_key_down(&keystate, config["left_alt1"]) or al_key_down(&keystate, config["left_alt2"])) { held_keys->LEFT = true; } if (al_key_down(&keystate, config["right"]) or al_key_down(&keystate, config["right_alt1"]) or al_key_down(&keystate, config["right_alt2"])) { held_keys->RIGHT = true; } if (al_key_down(&keystate, config["ability1"]) or al_key_down(&keystate, config["ability1_alt1"]) or al_key_down(&keystate, config["ability1_alt2"])) { held_keys->ABILITY_1 = true; } if (al_key_down(&keystate, config["ability2"]) or al_key_down(&keystate, config["ability2_alt1"]) or al_key_down(&keystate, config["ability2_alt2"])) { held_keys->ABILITY_2 = true; } if (al_key_down(&keystate, config["ultimate"]) or al_key_down(&keystate, config["ultimate_alt1"]) or al_key_down(&keystate, config["ultimate_alt2"])) { held_keys->ULTIMATE = true; } if (al_key_down(&keystate, config["reload"]) or al_key_down(&keystate, config["reload_alt1"]) or al_key_down(&keystate, config["reload_alt2"])) { held_keys->RELOAD = true; } ALLEGRO_MOUSE_STATE mousestate; al_get_mouse_state(&mousestate); // FIXME: I have no idea if these constants are correct, allegro docs don't mention the specifics, just that it starts with 1. if (mousestate.buttons & LEFT_MOUSE_BUTTON) { held_keys->PRIMARY_FIRE = true; } if (mousestate.buttons & RIGHT_MOUSE_BUTTON) { held_keys->SECONDARY_FIRE = true; } *mouse_x = mousestate.x; *mouse_y = mousestate.y; } <|endoftext|>
<commit_before>/** * An application which is responsible for handling the client inputs. * * @date Jul 17, 2014 * @author Joeri HERMANS * @version 0.1 * * Copyright 2013 Joeri HERMANS * * 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. */ // BEGIN Includes. /////////////////////////////////////////////////// // System dependencies. #include <cassert> #include <cstring> #include <cstdlib> #include <iostream> #include <unistd.h> #include <termios.h> #include <sys/types.h> #include <sstream> #include <netinet/in.h> #include <limits> #include <openssl/ssl.h> #include <openssl/err.h> // Application dependencies. #include <ias/application/client_application.h> #include <ias/application/constants.h> #include <ias/network/posix/posix_tcp_socket.h> #include <ias/network/posix/ssl/posix_ssl_socket.h> #include <ias/util/util.h> // END Includes. ///////////////////////////////////////////////////// inline void ClientApplication::initialize( void ) { writeMessage("Initializing client."); mSocket = nullptr; mLoggedIn = false; mSslContext = nullptr; } void ClientApplication::initializeSslContext( void ) { mSslContext = SSL_CTX_new(SSLv23_client_method()); } void ClientApplication::analyzeArguments( const int argc, const char ** argv ) { std::string address; std::size_t port; // Checking the precondition. assert( argc > 0 && argv != nullptr ); address = fetchAddress(argc,argv); port = fetchPort(argc,argv); if( sslRequested(argc,argv) ) { initializeSslContext(); mSocket = new PosixSslSocket(mSslContext); } else { mSocket = new PosixTcpSocket(); } if( mSocket != nullptr ) { writeMessage("Connecting..."); if( mSocket->createConnection(address,port) ) { writeMessage("Connected."); } else { delete mSocket; mSocket = nullptr; writeMessage("Connection failed."); } } else { writeMessage("Couldn't allocate socket."); } } std::string ClientApplication::fetchAddress( const int argc, const char ** argv ) const { std::string address; // Checking the precondition. assert( argc > 0 && argv != nullptr ); for( int i = 0 ; i < argc ; ++i ) { if( strcmp(argv[i],kFlagAddress) == 0 && ( i + 1 ) < argc ) { address = argv[i + 1]; break; } } if( address.empty() ) address = kDefaultServerAddress; return ( address ); } std::size_t ClientApplication::fetchPort( const int argc, const char ** argv ) const { std::size_t port; // Checking the precondition. assert( argc > 0 && argv != nullptr ); port = 0; for( int i = 0 ; i < argc ; ++i ) { if( strcmp(argv[i],kFlagPort) == 0 && ( i + 1 ) < argc ) { port = static_cast<std::size_t>(atol(argv[i + 1])); break; } } if( port == 0 ) { if( sslRequested(argc,argv) ) port = kDefaultUserServerPortSsl; else port = kDefaultUserServerPort; } return ( port ); } bool ClientApplication::sslRequested( const int argc , const char ** argv ) const { bool sslRequested; // Checking the precondition. assert( argc > 0 && argv != nullptr ); sslRequested = false; for( int i = 0 ; i < argc ; ++i ) { if( strcmp(argv[i],kFlagSsl) == 0 ) { sslRequested = true; break; } } return ( sslRequested ); } void ClientApplication::login( void ) { struct termios tty; std::string username; std::string password; Reader * reader; Writer * writer; std::uint8_t type; std::uint8_t byte; reader = mSocket->getReader(); writer = mSocket->getWriter(); writeMessage("Client initialized."); std::cout << kVersion << std::endl; std::cout << "Username: "; std::cin >> username; tcgetattr(STDIN_FILENO,&tty); tty.c_lflag &= ~ECHO; tcsetattr(STDIN_FILENO,TCSANOW,&tty); std::cout << "Password: "; std::cin >> password; tty.c_lflag |= ECHO; tcsetattr(STDIN_FILENO,TCSANOW,&tty); std::cout << std::endl; if( mSocket->isConnected() ) { writeMessage("Authenticating..."); type = 0x00; byte = static_cast<std::uint8_t>(username.length()); writer->writeBytes(reinterpret_cast<char *>(&type),1); writer->writeBytes(reinterpret_cast<char *>(&byte),1); writer->writeBytes(username.c_str(),byte); byte = static_cast<std::uint8_t>(password.length()); writer->writeByte(byte); writer->writeBytes(password.c_str(),byte); byte = 0xff; if( reader->readByte(reinterpret_cast<char *>(&byte)) == 1 && byte == 0x00 && reader->readByte(reinterpret_cast<char *>(&byte)) == 1 && byte == 0x01 ) { mLoggedIn = true; mUsername = username; writeMessage("Authenticated."); } else { writeMessage("Authentication failed."); } } } void ClientApplication::writeMessage( const std::string & message ) const { std::cout << "> " << message << std::endl; } void ClientApplication::readResponse( void ) { std::size_t nBytes; std::size_t bytesRead; Reader * reader; std::uint16_t messageSize; std::uint8_t type; reader = mSocket->getReader(); type = 0x00; messageSize = 0; if( mSocket->isConnected() && reader->readBytes(reinterpret_cast<char *>(&type),1) == 1 && type == 0x01 && reader->readBytes(reinterpret_cast<char *>(&type), sizeof(messageSize)) == sizeof(messageSize) ) { messageSize = ntohs(messageSize); bytesRead = 0; char buffer[messageSize + 1]; while( mSocket->isConnected() && bytesRead < messageSize ) { nBytes = reader->readBytes(buffer+bytesRead,messageSize-bytesRead); if( nBytes == 0 ) break; bytesRead += nBytes; } buffer[messageSize] = 0; puts(buffer); } } void ClientApplication::processCommands( void ) { std::string prefix; std::string command; std::string identifier; Reader * reader; Writer * writer; std::uint8_t b; std::uint8_t bytesWritten; std::size_t n; reader = mSocket->getReader(); writer = mSocket->getWriter(); prefix = "[" + mUsername + "@ias]$ "; std::cin.clear(); std::cin.ignore(); while( mSocket->isConnected() ) { std::cout << prefix; std::getline(std::cin,command); trim(command); if( command.length() > 0 ) { if( command == std::string("quit") ) { mSocket->closeConnection(); continue; } b = 0x01; writer->writeBytes(reinterpret_cast<char *>(&b),1); if( command.length() > 0xff ) { b = 0xff; writeMessage("Command exceeded max size, writing 255 bytes."); } else { b = static_cast<std::uint8_t>(command.length()); } writer->writeBytes(reinterpret_cast<char *>(&b),1); bytesWritten = 0; while( mSocket->isConnected() && bytesWritten < b ) { n = writer->writeBytes(command.c_str() + bytesWritten, b - bytesWritten); if( n == 0 ) break; bytesWritten += n; } std::stringstream ss; readResponse(); ss << command; ss >> identifier; trim(identifier); if( identifier == "stop" ) { mSocket->closeConnection(); } } } writeMessage("Disconnected."); } ClientApplication::ClientApplication( const int argc , const char ** argv ) { initialize(); analyzeArguments(argc,argv); } ClientApplication::~ClientApplication( void ) { delete mSocket; mSocket = nullptr; if( mSslContext != nullptr ) { SSL_CTX_free(mSslContext); mSslContext = nullptr; } } void ClientApplication::run( void ) { if( mSocket != nullptr && mSocket->isConnected() ) { login(); if( mLoggedIn ) processCommands(); } } void ClientApplication::stop( void ) { if( mSocket != nullptr ) mSocket->closeConnection(); } <commit_msg>Fix bug in client application.<commit_after>/** * An application which is responsible for handling the client inputs. * * @date Jul 17, 2014 * @author Joeri HERMANS * @version 0.1 * * Copyright 2013 Joeri HERMANS * * 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. */ // BEGIN Includes. /////////////////////////////////////////////////// // System dependencies. #include <cassert> #include <cstring> #include <cstdlib> #include <iostream> #include <unistd.h> #include <termios.h> #include <sys/types.h> #include <sstream> #include <netinet/in.h> #include <limits> #include <openssl/ssl.h> #include <openssl/err.h> // Application dependencies. #include <ias/application/client_application.h> #include <ias/application/constants.h> #include <ias/network/posix/posix_tcp_socket.h> #include <ias/network/posix/ssl/posix_ssl_socket.h> #include <ias/util/util.h> // END Includes. ///////////////////////////////////////////////////// inline void ClientApplication::initialize( void ) { writeMessage("Initializing client."); mSocket = nullptr; mLoggedIn = false; mSslContext = nullptr; } void ClientApplication::initializeSslContext( void ) { mSslContext = SSL_CTX_new(SSLv23_client_method()); } void ClientApplication::analyzeArguments( const int argc, const char ** argv ) { std::string address; std::size_t port; // Checking the precondition. assert( argc > 0 && argv != nullptr ); address = fetchAddress(argc,argv); port = fetchPort(argc,argv); if( sslRequested(argc,argv) ) { initializeSslContext(); mSocket = new PosixSslSocket(mSslContext); } else { mSocket = new PosixTcpSocket(); } if( mSocket != nullptr ) { writeMessage("Connecting..."); if( mSocket->createConnection(address,port) ) { writeMessage("Connected."); } else { delete mSocket; mSocket = nullptr; writeMessage("Connection failed."); } } else { writeMessage("Couldn't allocate socket."); } } std::string ClientApplication::fetchAddress( const int argc, const char ** argv ) const { std::string address; // Checking the precondition. assert( argc > 0 && argv != nullptr ); for( int i = 0 ; i < argc ; ++i ) { if( strcmp(argv[i],kFlagAddress) == 0 && ( i + 1 ) < argc ) { address = argv[i + 1]; break; } } if( address.empty() ) address = kDefaultServerAddress; return ( address ); } std::size_t ClientApplication::fetchPort( const int argc, const char ** argv ) const { std::size_t port; // Checking the precondition. assert( argc > 0 && argv != nullptr ); port = 0; for( int i = 0 ; i < argc ; ++i ) { if( strcmp(argv[i],kFlagPort) == 0 && ( i + 1 ) < argc ) { port = static_cast<std::size_t>(atol(argv[i + 1])); break; } } if( port == 0 ) { if( sslRequested(argc,argv) ) port = kDefaultUserServerPortSsl; else port = kDefaultUserServerPort; } return ( port ); } bool ClientApplication::sslRequested( const int argc , const char ** argv ) const { bool sslRequested; // Checking the precondition. assert( argc > 0 && argv != nullptr ); sslRequested = false; for( int i = 0 ; i < argc ; ++i ) { if( strcmp(argv[i],kFlagSsl) == 0 ) { sslRequested = true; break; } } return ( sslRequested ); } void ClientApplication::login( void ) { struct termios tty; std::string username; std::string password; Reader * reader; Writer * writer; std::uint8_t type; std::uint8_t byte; reader = mSocket->getReader(); writer = mSocket->getWriter(); writeMessage("Client initialized."); std::cout << kVersion << std::endl; std::cout << "Username: "; std::cin >> username; tcgetattr(STDIN_FILENO,&tty); tty.c_lflag &= ~ECHO; tcsetattr(STDIN_FILENO,TCSANOW,&tty); std::cout << "Password: "; std::cin >> password; tty.c_lflag |= ECHO; tcsetattr(STDIN_FILENO,TCSANOW,&tty); if( mSocket->isConnected() ) { writeMessage("Authenticating..."); type = 0x00; byte = static_cast<std::uint8_t>(username.length()); writer->writeBytes(reinterpret_cast<char *>(&type),1); writer->writeBytes(reinterpret_cast<char *>(&byte),1); writer->writeBytes(username.c_str(),byte); byte = static_cast<std::uint8_t>(password.length()); writer->writeByte(byte); writer->writeBytes(password.c_str(),byte); byte = 0xff; if( reader->readByte(reinterpret_cast<char *>(&byte)) == 1 && byte == 0x00 && reader->readByte(reinterpret_cast<char *>(&byte)) == 1 && byte == 0x01 ) { mLoggedIn = true; mUsername = username; writeMessage("Authenticated."); } else { writeMessage("Authentication failed."); } } } void ClientApplication::writeMessage( const std::string & message ) const { std::cout << "> " << message << std::endl; } void ClientApplication::readResponse( void ) { std::size_t nBytes; std::size_t bytesRead; Reader * reader; std::uint16_t messageSize; std::uint8_t type; reader = mSocket->getReader(); type = 0x00; messageSize = 0; if( mSocket->isConnected() && reader->readBytes(reinterpret_cast<char *>(&type),1) == 1 && type == 0x01 && reader->readBytes(reinterpret_cast<char *>(&messageSize),2) == 2 ) { messageSize = ntohs(messageSize); bytesRead = 0; char buffer[messageSize + 1]; while( mSocket->isConnected() && bytesRead < messageSize ) { nBytes = reader->readBytes(buffer+bytesRead,messageSize-bytesRead); if( nBytes == 0 ) break; bytesRead += nBytes; } buffer[messageSize] = 0; puts(buffer); } } void ClientApplication::processCommands( void ) { std::string prefix; std::string command; std::string identifier; Reader * reader; Writer * writer; std::uint8_t b; std::uint8_t bytesWritten; std::size_t n; reader = mSocket->getReader(); writer = mSocket->getWriter(); prefix = "[" + mUsername + "@ias]$ "; std::cin.clear(); std::cin.ignore(); while( mSocket->isConnected() ) { std::cout << prefix; std::getline(std::cin,command); trim(command); if( command.length() > 0 ) { if( command == std::string("quit") ) { mSocket->closeConnection(); continue; } b = 0x01; writer->writeBytes(reinterpret_cast<char *>(&b),1); if( command.length() > 0xff ) { b = 0xff; writeMessage("Command exceeded max size, writing 255 bytes."); } else { b = static_cast<std::uint8_t>(command.length()); } writer->writeBytes(reinterpret_cast<char *>(&b),1); bytesWritten = 0; while( mSocket->isConnected() && bytesWritten < b ) { n = writer->writeBytes(command.c_str() + bytesWritten, b - bytesWritten); if( n == 0 ) break; bytesWritten += n; } std::stringstream ss; readResponse(); ss << command; ss >> identifier; trim(identifier); if( identifier == "stop" ) { mSocket->closeConnection(); } } } writeMessage("Disconnected."); } ClientApplication::ClientApplication( const int argc , const char ** argv ) { initialize(); analyzeArguments(argc,argv); } ClientApplication::~ClientApplication( void ) { delete mSocket; mSocket = nullptr; if( mSslContext != nullptr ) { SSL_CTX_free(mSslContext); mSslContext = nullptr; } } void ClientApplication::run( void ) { if( mSocket != nullptr && mSocket->isConnected() ) { login(); if( mLoggedIn ) processCommands(); } } void ClientApplication::stop( void ) { if( mSocket != nullptr ) mSocket->closeConnection(); } <|endoftext|>
<commit_before>#include "neutralmoblistmodel.h" #include <QDebug> #include <sstream> #include <QStringList> // Initialize the counter long NeutralMob::id_counter = 0; NeutralMob::NeutralMob(const QString &type, const float &posX, const float &posY, const float &posZ, const float &rotation, const QList<float> &unknown_floats, const QBitArray &options, QObject * parent) : ListItem(parent), m_id(id_counter), m_type(type), m_posX(posX), m_posY(posY), m_posZ(posZ), m_rotation(rotation), m_unknown(unknown_floats), m_options(options) { id_counter++; } NeutralMob * NeutralMob::build(QStringList & unitData) { if (unitData.size() == 13) { // Load in the unknown floats QList<float> unknown_floats; for (int i=0; i<4; i++) { unknown_floats.append(unitData[i+5].toFloat()); } // Load in the options QBitArray options(3, false); for (int i=0; i<3; i++) { options.setBit(i, (unitData[i+9].compare("True"))?true:false); } return (new NeutralMob( unitData[0], unitData[1].toFloat(), unitData[2].toFloat(), unitData[3].toFloat(), unitData[4].toFloat(), unknown_floats, options )); } return Q_NULLPTR; } void NeutralMob::setType(QString type) { m_type = type; } QHash<int, QByteArray> NeutralMob::roleNames() const { QHash<int, QByteArray> names; names[IdRole] = "id"; names[FilterStringRole] = "filterString"; names[TypeRole] = "type"; names[PosXRole] = "posX"; names[PosYRole] = "posY"; names[PosZRole] = "posZ"; names[RotationRole] = "rotation"; return names; } QVariant NeutralMob::data(int role) const { switch(role) { case IdRole: return (unsigned int)id(); case FilterStringRole: return filterString(); case TypeRole: return type(); case PosXRole: return posX(); case PosYRole: return posY(); case PosZRole: return posZ(); case RotationRole: return rotation(); default: return QVariant(); } } QString NeutralMob::filterString() const { std::stringstream completeString; completeString << type().toStdString(); return (QString(completeString.str().c_str())); } void NeutralMob::print() { qDebug() << type() << "x" << posX() << "y" << posY() << "z" << posZ() << "rotation" << rotation(); } NeutralMobListModel::NeutralMobListModel(ListItem * prototype, QObject * parent ) : ListModel(prototype, parent) { } void NeutralMobListModel::setData(const long id, const QVariant &value, int role) { switch (role) { case NeutralMob::TypeRole: { NeutralMob * item = (NeutralMob *)find( id ); item->setType(value.toString()); break; } default: qWarning() << "NeutralMobListModel::setData does not understand what role" << role << "is."; break; } } void NeutralMobListModel::remove(const long id) { // Find the id of the item you want to delete, // get the index of that item, and remove it. removeRow(indexFromItem(find( id )).row()); } // This function only exists because we can't parse the map file. // TODO: change how units are placed. float NeutralMobListModel::getFirstPosition(const char label) { if (getList().size() != 0) { if (label==0) { return ((NeutralMob*)getList().first())->posX(); } else if (label==1) { return ((NeutralMob*)getList().first())->posY(); } else if (label==2) { return ((NeutralMob*)getList().first())->posZ(); } } return 0.0; } void NeutralMobListModel::add(const QString type, float x, float y, float z) { QList<float> unknown_floats; unknown_floats.append(0.4f); unknown_floats.append(0.0f); unknown_floats.append(0.0f); unknown_floats.append(0.0f); QBitArray options(2, false); appendRow(new NeutralMob( type, x, y, z, // position 0.0, // rotation unknown_floats, options) ); qDebug() << "Added a mob of type" << type; } <commit_msg>Fixed animal loading<commit_after>#include "neutralmoblistmodel.h" #include <QDebug> #include <sstream> #include <QStringList> // Initialize the counter long NeutralMob::id_counter = 0; NeutralMob::NeutralMob(const QString &type, const float &posX, const float &posY, const float &posZ, const float &rotation, const QList<float> &unknown_floats, const QBitArray &options, QObject * parent) : ListItem(parent), m_id(id_counter), m_type(type), m_posX(posX), m_posY(posY), m_posZ(posZ), m_rotation(rotation), m_unknown(unknown_floats), m_options(options) { id_counter++; } NeutralMob * NeutralMob::build(QStringList & unitData) { if (unitData.size() == 13) { // Load in the unknown floats QList<float> unknown_floats; for (int i=0; i<4; i++) { unknown_floats.append(unitData[i+5].toFloat()); } // Load in the options QBitArray options(3, false); for (int i=0; i<3; i++) { options.setBit(i, unitData[i+9].compare("True") ? false : true); } return (new NeutralMob( unitData[0], unitData[1].toFloat(), unitData[2].toFloat(), unitData[3].toFloat(), unitData[4].toFloat(), unknown_floats, options )); } return Q_NULLPTR; } void NeutralMob::setType(QString type) { m_type = type; } QHash<int, QByteArray> NeutralMob::roleNames() const { QHash<int, QByteArray> names; names[IdRole] = "id"; names[FilterStringRole] = "filterString"; names[TypeRole] = "type"; names[PosXRole] = "posX"; names[PosYRole] = "posY"; names[PosZRole] = "posZ"; names[RotationRole] = "rotation"; return names; } QVariant NeutralMob::data(int role) const { switch(role) { case IdRole: return (unsigned int)id(); case FilterStringRole: return filterString(); case TypeRole: return type(); case PosXRole: return posX(); case PosYRole: return posY(); case PosZRole: return posZ(); case RotationRole: return rotation(); default: return QVariant(); } } QString NeutralMob::filterString() const { std::stringstream completeString; completeString << type().toStdString(); return (QString(completeString.str().c_str())); } void NeutralMob::print() { qDebug() << type() << "x" << posX() << "y" << posY() << "z" << posZ() << "rotation" << rotation(); } NeutralMobListModel::NeutralMobListModel(ListItem * prototype, QObject * parent ) : ListModel(prototype, parent) { } void NeutralMobListModel::setData(const long id, const QVariant &value, int role) { switch (role) { case NeutralMob::TypeRole: { NeutralMob * item = (NeutralMob *)find( id ); item->setType(value.toString()); break; } default: qWarning() << "NeutralMobListModel::setData does not understand what role" << role << "is."; break; } } void NeutralMobListModel::remove(const long id) { // Find the id of the item you want to delete, // get the index of that item, and remove it. removeRow(indexFromItem(find( id )).row()); } // This function only exists because we can't parse the map file. // TODO: change how units are placed. float NeutralMobListModel::getFirstPosition(const char label) { if (getList().size() != 0) { if (label==0) { return ((NeutralMob*)getList().first())->posX(); } else if (label==1) { return ((NeutralMob*)getList().first())->posY(); } else if (label==2) { return ((NeutralMob*)getList().first())->posZ(); } } return 0.0; } void NeutralMobListModel::add(const QString type, float x, float y, float z) { QList<float> unknown_floats; unknown_floats.append(0.4f); unknown_floats.append(0.0f); unknown_floats.append(0.0f); unknown_floats.append(0.0f); QBitArray options(3, false); appendRow(new NeutralMob( type, x, y, z, // position 0.0, // rotation unknown_floats, options) ); qDebug() << "Added a mob of type" << type; } <|endoftext|>
<commit_before>/** * This file defines facilities to perform concept-based overloading. */ #ifndef DUCK_REQUIRES_HPP #define DUCK_REQUIRES_HPP #include <duck/detail/mpl_extensions.hpp> #include <duck/models.hpp> #include <boost/config.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/apply.hpp> #include <boost/mpl/back.hpp> #include <boost/mpl/bool.hpp> #include <boost/mpl/contains.hpp> #include <boost/mpl/copy_if.hpp> #include <boost/mpl/deref.hpp> #include <boost/mpl/find_if.hpp> #include <boost/mpl/not.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/pop_back.hpp> #include <boost/mpl/push_front.hpp> #include <boost/mpl/quote.hpp> #include <boost/mpl/vector.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/utility/enable_if.hpp> namespace duck { // Note to self: Storing the visited concepts in a list ordered by concept // specificity could make things much more efficient. /** * Tag to signal the failure of a concept-based overload resolution. * * @note It is important that this stays an incomplete type. */ struct concept_based_overload_resolution_failed #if defined(BOOST_NO_CXX11_DECLTYPE_N3276) { // On GCC, incomplete types can't appear inside decltype. // Instead of failing on valid decltypes, we will trigger a link time // error when `concept_based_overload_resolution_failed` is used. ~concept_based_overload_resolution_failed(); } #endif ; /** * Trait that must be specialized by new concepts to specify a partial order * between concepts. * * @note `is_more_specific_than<A, B>` is conceptually equivalent to `A < B` * where the `<` operator is a partial order meaning `A` is less * specific than `B`. */ template <typename A, typename B> struct is_more_specific_than; /** * Specialization of the `is_more_specific_than` trait for the trivial case * where both concepts are the same, i.e. `is_more_specific_than<A, A>`. In * this trivial case, the trait is obviously false. */ template <typename Concept> struct is_more_specific_than<Concept, Concept> : boost::mpl::false_ { }; /** * Metafunction class returning the result of calling the function overloaded * by `Family` at the current stage of the overload resolution. * * @note This metafunction class may be specialized by each family of * overload, or the family may define a * `perform_overload<OverloadResolution>` nested metafunction class * accepting arguments to perform the overload. */ template <typename Family, typename OverloadResolution> struct perform_overload { template <typename ...Args> struct apply : boost::mpl::apply< typename Family::template perform_overload<OverloadResolution>, Args... > { }; }; namespace requires_detail { //! Compile-time data structure storing state during an overload resolution. template <typename Family, typename VisitedConcepts = boost::mpl::vector<> > struct overload_resolution { typedef VisitedConcepts visited_concepts; typedef Family family; typedef overload_resolution type; // to make it a metafunction }; /** * Add a `Concept` to the list of concepts visited during the current * overload resolution. */ template <typename Concept, typename OverloadResolution> struct mark_as_visited : overload_resolution< typename OverloadResolution::family, typename boost::mpl::push_front< typename OverloadResolution::visited_concepts, Concept >::type > { }; /** * Metafunction returning whether a `Concept` has already been visited during * the current overload resolution. */ template <typename Concept, typename OverloadResolution> struct has_visited : boost::mpl::contains< typename OverloadResolution::visited_concepts, Concept > { }; /** * Metafunction returning whether a `Concept` is the most specific that was * visited so far during an overload resolution. */ template <typename Concept, typename OverloadResolution> struct is_most_specific_so_far : boost::mpl::none_of< typename OverloadResolution::visited_concepts, is_more_specific_than<Concept, boost::mpl::_1> > { }; /** * Metafunction returning whether a `Concept` is the best match for a `Type` * so far during an overload resolution. */ template <typename Type, typename Concept, typename OverloadResolution> struct is_best_match_so_far : boost::mpl::and_< boost::mpl::not_<has_visited<Concept, OverloadResolution> >, is_most_specific_so_far<Concept, OverloadResolution>, models<Concept, Type> > { }; /** * Metafunction class returning whether a `Concept` is the most specific * concept modeled by a `Type` for which an overload exists according to * the family present in `OverloadResolution`. */ template <typename Type, typename Concept, typename OverloadResolution> class clause_passes { template <typename ...Args> struct result_of_calling_the_function_with : boost::mpl::apply< perform_overload< typename OverloadResolution::family, typename mark_as_visited<Concept, OverloadResolution>::type >, Args... > { }; template <typename ...Args> struct there_are_no_better_overloads : boost::is_same< typename result_of_calling_the_function_with<Args...>::type, concept_based_overload_resolution_failed > { }; public: template <typename ...Args> struct apply : boost::mpl::and_< is_best_match_so_far<Type, Concept, OverloadResolution>, there_are_no_better_overloads<Args...> > { }; }; //! Requires a `Type` to be a model of a `Concept` in a `require` clause. template <typename Concept, typename Type> struct model_of { typedef Concept concept; typedef Type model; }; template <typename T> struct is_model_of_clause : boost::mpl::false_ { }; template <typename Concept, typename Type> struct is_model_of_clause<model_of<Concept, Type> > : boost::mpl::true_ { }; //! Provides the current `OverloadResolution` state to a `require` clause. template <typename Family> struct overload_resolution_state { typedef overload_resolution<Family> type; }; template <typename ...Args> struct overload_resolution_state<overload_resolution<Args...> > { typedef overload_resolution<Args...> type; }; template <typename T> struct is_overload_resolution_state : boost::mpl::false_ { }; template <typename OverloadResolution> struct is_overload_resolution_state< overload_resolution_state<OverloadResolution> > : boost::mpl::true_ { }; /** * Provides the template parameters to pass to the next function that will be * tried in the same overload family. * * @note The overload information is handled by the library and must not be * passed here. */ template <typename ...Params> struct template_parameters; template <typename T> struct is_template_parameters : boost::mpl::false_ { }; template <typename ...Params> struct is_template_parameters<template_parameters<Params...> > : boost::mpl::true_ { }; template <typename ...Blob> struct requires_impl { template <typename F, typename Pack> struct apply_pack; template <typename F, template <typename ...> class Pack, typename ...Args> struct apply_pack<F, Pack<Args...> > : boost::mpl::apply<F, Args...> { }; typedef typename boost::mpl::back< boost::mpl::vector<Blob...> >::type return_type; typedef typename boost::mpl::pop_back< boost::mpl::vector<Blob...> >::type arguments; // Gather all the model_of clauses typedef typename boost::mpl::copy_if< arguments, boost::mpl::quote1<is_model_of_clause> >::type clauses; // Gather the template parameters to be passed to subsequent overloads typedef typename boost::mpl::deref<typename boost::mpl::find_if< arguments, boost::mpl::quote1<is_template_parameters> >::type>::type template_parameters; // Fetch the current overload resolution state typedef typename boost::mpl::deref<typename boost::mpl::find_if< arguments, boost::mpl::quote1<is_overload_resolution_state> >::type>::type::type current_state; struct clause_is_respected { template <typename Clause> struct apply : apply_pack< clause_passes< typename Clause::model, typename Clause::concept, current_state >, template_parameters > { }; }; typedef typename boost::mpl::all_of< clauses, clause_is_respected >::type type; static bool const value = type::value; }; } // end namespace requires_detail // Named parameters for `requires` using requires_detail::model_of; using requires_detail::overload_resolution_state; using requires_detail::template_parameters; /** * Metafunction to perform concept-based overloading. * * Examples of usage: * * typename requires< * model_of<SomeConcept, SomeType>, * model_of<SomeOtherConcept, SomeOtherType>, * * overload_resolution_state<State>, * template_parameters<SomeType, SomeOtherType>, * return_type * >::type */ template <typename ...Args> struct requires : boost::enable_if< requires_detail::requires_impl<Args...>, typename requires_detail::requires_impl<Args...>::return_type > { }; /** * Macro to enable concept overloading on a family of overloads. * * @param FUNCTION The name of the function that is overloaded using concepts. * @param CALL An expression calling the function. This expression can use * the templates parameters provided in `__VA_ARGS__`. * @param ... A list of `typename T` template parameters that will be usable * within the `CALL` expression. The `State` parameter is always * available within the `CALL` expression and it represents the * current state of the overload resolution. * * Once instantiated, this macro will create a type named `FUNCTION` inside a * `tag` namespace. This type should be used as the default overload * resolution state for overloads within this family. */ #define DUCK_ENABLE_CONCEPT_OVERLOADING(FUNCTION, CALL, .../*typenames*/) \ ::duck::concept_based_overload_resolution_failed FUNCTION(...); \ namespace tag { \ /* We can't call the structure FUNCTION because it would clash */ \ /* with the CALL expansion. */ \ struct BOOST_PP_CAT(FUNCTION, _tag) { \ template <typename State> \ struct perform_overload { \ template <__VA_ARGS__> \ struct apply { \ typedef decltype(CALL) type; \ }; \ }; \ }; \ /* Now we can make the alias */ \ typedef BOOST_PP_CAT(FUNCTION, _tag) FUNCTION; \ } \ /**/ } // end namespace duck #endif // !DUCK_REQUIRES_HPP <commit_msg>Make it redundant to specialize is_more_specific_than twice.<commit_after>/** * This file defines facilities to perform concept-based overloading. */ #ifndef DUCK_REQUIRES_HPP #define DUCK_REQUIRES_HPP #include <duck/detail/mpl_extensions.hpp> #include <duck/models.hpp> #include <boost/config.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/apply.hpp> #include <boost/mpl/back.hpp> #include <boost/mpl/bool.hpp> #include <boost/mpl/contains.hpp> #include <boost/mpl/copy_if.hpp> #include <boost/mpl/deref.hpp> #include <boost/mpl/find_if.hpp> #include <boost/mpl/not.hpp> #include <boost/mpl/placeholders.hpp> #include <boost/mpl/pop_back.hpp> #include <boost/mpl/push_front.hpp> #include <boost/mpl/quote.hpp> #include <boost/mpl/vector.hpp> #include <boost/preprocessor/cat.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/utility/enable_if.hpp> namespace duck { // Note to self: Storing the visited concepts in a list ordered by concept // specificity could make things much more efficient. /** * Tag to signal the failure of a concept-based overload resolution. * * @note It is important that this stays an incomplete type. */ struct concept_based_overload_resolution_failed #if defined(BOOST_NO_CXX11_DECLTYPE_N3276) { // On GCC, incomplete types can't appear inside decltype. // Instead of failing on valid decltypes, we will trigger a link time // error when `concept_based_overload_resolution_failed` is used. ~concept_based_overload_resolution_failed(); } #endif ; /** * Trait that must be specialized by new concepts to specify a partial order * between concepts. * * @note It is only needed to specialize one side of the trait, i.e. * `is_more_specific_than<A, B> : true` does not require the definition * of `is_more_specific_than<B, A> : false` too. * * @note `is_more_specific_than<A, B>` is conceptually equivalent to `A < B` * where the `<` operator is a partial order meaning `A` is less * specific than `B`. */ template <typename A, typename B> struct is_more_specific_than : boost::mpl::not_<is_more_specific_than<B, A> > { }; /** * Specialization of the `is_more_specific_than` trait for the trivial case * where both concepts are the same, i.e. `is_more_specific_than<A, A>`. In * this trivial case, the trait is obviously false. */ template <typename Concept> struct is_more_specific_than<Concept, Concept> : boost::mpl::false_ { }; /** * Metafunction class returning the result of calling the function overloaded * by `Family` at the current stage of the overload resolution. * * @note This metafunction class may be specialized by each family of * overload, or the family may define a * `perform_overload<OverloadResolution>` nested metafunction class * accepting arguments to perform the overload. */ template <typename Family, typename OverloadResolution> struct perform_overload { template <typename ...Args> struct apply : boost::mpl::apply< typename Family::template perform_overload<OverloadResolution>, Args... > { }; }; namespace requires_detail { //! Compile-time data structure storing state during an overload resolution. template <typename Family, typename VisitedConcepts = boost::mpl::vector<> > struct overload_resolution { typedef VisitedConcepts visited_concepts; typedef Family family; typedef overload_resolution type; // to make it a metafunction }; /** * Add a `Concept` to the list of concepts visited during the current * overload resolution. */ template <typename Concept, typename OverloadResolution> struct mark_as_visited : overload_resolution< typename OverloadResolution::family, typename boost::mpl::push_front< typename OverloadResolution::visited_concepts, Concept >::type > { }; /** * Metafunction returning whether a `Concept` has already been visited during * the current overload resolution. */ template <typename Concept, typename OverloadResolution> struct has_visited : boost::mpl::contains< typename OverloadResolution::visited_concepts, Concept > { }; /** * Metafunction returning whether a `Concept` is the most specific that was * visited so far during an overload resolution. */ template <typename Concept, typename OverloadResolution> struct is_most_specific_so_far : boost::mpl::none_of< typename OverloadResolution::visited_concepts, is_more_specific_than<Concept, boost::mpl::_1> > { }; /** * Metafunction returning whether a `Concept` is the best match for a `Type` * so far during an overload resolution. */ template <typename Type, typename Concept, typename OverloadResolution> struct is_best_match_so_far : boost::mpl::and_< boost::mpl::not_<has_visited<Concept, OverloadResolution> >, is_most_specific_so_far<Concept, OverloadResolution>, models<Concept, Type> > { }; /** * Metafunction class returning whether a `Concept` is the most specific * concept modeled by a `Type` for which an overload exists according to * the family present in `OverloadResolution`. */ template <typename Type, typename Concept, typename OverloadResolution> class clause_passes { template <typename ...Args> struct result_of_calling_the_function_with : boost::mpl::apply< perform_overload< typename OverloadResolution::family, typename mark_as_visited<Concept, OverloadResolution>::type >, Args... > { }; template <typename ...Args> struct there_are_no_better_overloads : boost::is_same< typename result_of_calling_the_function_with<Args...>::type, concept_based_overload_resolution_failed > { }; public: template <typename ...Args> struct apply : boost::mpl::and_< is_best_match_so_far<Type, Concept, OverloadResolution>, there_are_no_better_overloads<Args...> > { }; }; //! Requires a `Type` to be a model of a `Concept` in a `require` clause. template <typename Concept, typename Type> struct model_of { typedef Concept concept; typedef Type model; }; template <typename T> struct is_model_of_clause : boost::mpl::false_ { }; template <typename Concept, typename Type> struct is_model_of_clause<model_of<Concept, Type> > : boost::mpl::true_ { }; //! Provides the current `OverloadResolution` state to a `require` clause. template <typename Family> struct overload_resolution_state { typedef overload_resolution<Family> type; }; template <typename ...Args> struct overload_resolution_state<overload_resolution<Args...> > { typedef overload_resolution<Args...> type; }; template <typename T> struct is_overload_resolution_state : boost::mpl::false_ { }; template <typename OverloadResolution> struct is_overload_resolution_state< overload_resolution_state<OverloadResolution> > : boost::mpl::true_ { }; /** * Provides the template parameters to pass to the next function that will be * tried in the same overload family. * * @note The overload information is handled by the library and must not be * passed here. */ template <typename ...Params> struct template_parameters; template <typename T> struct is_template_parameters : boost::mpl::false_ { }; template <typename ...Params> struct is_template_parameters<template_parameters<Params...> > : boost::mpl::true_ { }; template <typename ...Blob> struct requires_impl { template <typename F, typename Pack> struct apply_pack; template <typename F, template <typename ...> class Pack, typename ...Args> struct apply_pack<F, Pack<Args...> > : boost::mpl::apply<F, Args...> { }; typedef typename boost::mpl::back< boost::mpl::vector<Blob...> >::type return_type; typedef typename boost::mpl::pop_back< boost::mpl::vector<Blob...> >::type arguments; // Gather all the model_of clauses typedef typename boost::mpl::copy_if< arguments, boost::mpl::quote1<is_model_of_clause> >::type clauses; // Gather the template parameters to be passed to subsequent overloads typedef typename boost::mpl::deref<typename boost::mpl::find_if< arguments, boost::mpl::quote1<is_template_parameters> >::type>::type template_parameters; // Fetch the current overload resolution state typedef typename boost::mpl::deref<typename boost::mpl::find_if< arguments, boost::mpl::quote1<is_overload_resolution_state> >::type>::type::type current_state; struct clause_is_respected { template <typename Clause> struct apply : apply_pack< clause_passes< typename Clause::model, typename Clause::concept, current_state >, template_parameters > { }; }; typedef typename boost::mpl::all_of< clauses, clause_is_respected >::type type; static bool const value = type::value; }; } // end namespace requires_detail // Named parameters for `requires` using requires_detail::model_of; using requires_detail::overload_resolution_state; using requires_detail::template_parameters; /** * Metafunction to perform concept-based overloading. * * Examples of usage: * * typename requires< * model_of<SomeConcept, SomeType>, * model_of<SomeOtherConcept, SomeOtherType>, * * overload_resolution_state<State>, * template_parameters<SomeType, SomeOtherType>, * return_type * >::type */ template <typename ...Args> struct requires : boost::enable_if< requires_detail::requires_impl<Args...>, typename requires_detail::requires_impl<Args...>::return_type > { }; /** * Macro to enable concept overloading on a family of overloads. * * @param FUNCTION The name of the function that is overloaded using concepts. * @param CALL An expression calling the function. This expression can use * the templates parameters provided in `__VA_ARGS__`. * @param ... A list of `typename T` template parameters that will be usable * within the `CALL` expression. The `State` parameter is always * available within the `CALL` expression and it represents the * current state of the overload resolution. * * Once instantiated, this macro will create a type named `FUNCTION` inside a * `tag` namespace. This type should be used as the default overload * resolution state for overloads within this family. */ #define DUCK_ENABLE_CONCEPT_OVERLOADING(FUNCTION, CALL, .../*typenames*/) \ ::duck::concept_based_overload_resolution_failed FUNCTION(...); \ namespace tag { \ /* We can't call the structure FUNCTION because it would clash */ \ /* with the CALL expansion. */ \ struct BOOST_PP_CAT(FUNCTION, _tag) { \ template <typename State> \ struct perform_overload { \ template <__VA_ARGS__> \ struct apply { \ typedef decltype(CALL) type; \ }; \ }; \ }; \ /* Now we can make the alias */ \ typedef BOOST_PP_CAT(FUNCTION, _tag) FUNCTION; \ } \ /**/ } // end namespace duck #endif // !DUCK_REQUIRES_HPP <|endoftext|>
<commit_before>//===- AArch64MacroFusion.cpp - AArch64 Macro Fusion ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // \file This file contains the AArch64 implementation of the DAG scheduling mutation // to pair instructions back to back. // //===----------------------------------------------------------------------===// #include "AArch64MacroFusion.h" #include "AArch64Subtarget.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetInstrInfo.h" #define DEBUG_TYPE "misched" STATISTIC(NumFused, "Number of instr pairs fused"); using namespace llvm; static cl::opt<bool> EnableMacroFusion("aarch64-misched-fusion", cl::Hidden, cl::desc("Enable scheduling for macro fusion."), cl::init(true)); namespace { /// \brief Verify that the instruction pair, First and Second, /// should be scheduled back to back. Given an anchor instruction, if the other /// instruction is unspecified, then verify that the anchor instruction may be /// part of a pair at all. static bool shouldScheduleAdjacent(const AArch64InstrInfo &TII, const AArch64Subtarget &ST, const MachineInstr *First, const MachineInstr *Second) { assert((First || Second) && "At least one instr must be specified"); unsigned FirstOpcode = First ? First->getOpcode() : static_cast<unsigned>(AArch64::INSTRUCTION_LIST_END); unsigned SecondOpcode = Second ? Second->getOpcode() : static_cast<unsigned>(AArch64::INSTRUCTION_LIST_END); if (ST.hasArithmeticBccFusion()) // Fuse CMN, CMP, TST followed by Bcc. if (SecondOpcode == AArch64::Bcc) switch (FirstOpcode) { default: return false; case AArch64::ADDSWri: case AArch64::ADDSWrr: case AArch64::ADDSXri: case AArch64::ADDSXrr: case AArch64::ANDSWri: case AArch64::ANDSWrr: case AArch64::ANDSXri: case AArch64::ANDSXrr: case AArch64::SUBSWri: case AArch64::SUBSWrr: case AArch64::SUBSXri: case AArch64::SUBSXrr: case AArch64::BICSWrr: case AArch64::BICSXrr: return true; case AArch64::ADDSWrs: case AArch64::ADDSXrs: case AArch64::ANDSWrs: case AArch64::ANDSXrs: case AArch64::SUBSWrs: case AArch64::SUBSXrs: case AArch64::BICSWrs: case AArch64::BICSXrs: // Shift value can be 0 making these behave like the "rr" variant... return !TII.hasShiftedReg(*First); case AArch64::INSTRUCTION_LIST_END: return true; } if (ST.hasArithmeticCbzFusion()) // Fuse ALU operations followed by CBZ/CBNZ. if (SecondOpcode == AArch64::CBNZW || SecondOpcode == AArch64::CBNZX || SecondOpcode == AArch64::CBZW || SecondOpcode == AArch64::CBZX) switch (FirstOpcode) { default: return false; case AArch64::ADDWri: case AArch64::ADDWrr: case AArch64::ADDXri: case AArch64::ADDXrr: case AArch64::ANDWri: case AArch64::ANDWrr: case AArch64::ANDXri: case AArch64::ANDXrr: case AArch64::EORWri: case AArch64::EORWrr: case AArch64::EORXri: case AArch64::EORXrr: case AArch64::ORRWri: case AArch64::ORRWrr: case AArch64::ORRXri: case AArch64::ORRXrr: case AArch64::SUBWri: case AArch64::SUBWrr: case AArch64::SUBXri: case AArch64::SUBXrr: return true; case AArch64::ADDWrs: case AArch64::ADDXrs: case AArch64::ANDWrs: case AArch64::ANDXrs: case AArch64::SUBWrs: case AArch64::SUBXrs: case AArch64::BICWrs: case AArch64::BICXrs: // Shift value can be 0 making these behave like the "rr" variant... return !TII.hasShiftedReg(*First); case AArch64::INSTRUCTION_LIST_END: return true; } if (ST.hasFuseAES()) // Fuse AES crypto operations. switch(FirstOpcode) { // AES encode. case AArch64::AESErr: return SecondOpcode == AArch64::AESMCrr || SecondOpcode == AArch64::INSTRUCTION_LIST_END; // AES decode. case AArch64::AESDrr: return SecondOpcode == AArch64::AESIMCrr || SecondOpcode == AArch64::INSTRUCTION_LIST_END; } if (ST.hasFuseLiterals()) // Fuse literal generation operations. switch (FirstOpcode) { // PC relative address. case AArch64::ADRP: return SecondOpcode == AArch64::ADDXri || SecondOpcode == AArch64::INSTRUCTION_LIST_END; // 32 bit immediate. case AArch64::MOVZWi: return (SecondOpcode == AArch64::MOVKWi && Second->getOperand(3).getImm() == 16) || SecondOpcode == AArch64::INSTRUCTION_LIST_END; // Lower half of 64 bit immediate. case AArch64::MOVZXi: return (SecondOpcode == AArch64::MOVKXi && Second->getOperand(3).getImm() == 16) || SecondOpcode == AArch64::INSTRUCTION_LIST_END; // Upper half of 64 bit immediate. case AArch64::MOVKXi: return First->getOperand(3).getImm() == 32 && ((SecondOpcode == AArch64::MOVKXi && Second->getOperand(3).getImm() == 48) || SecondOpcode == AArch64::INSTRUCTION_LIST_END); } return false; } /// \brief Implement the fusion of instruction pairs in the scheduling /// DAG, anchored at the instruction in ASU. Preds /// indicates if its dependencies in \param APreds are predecessors instead of /// successors. static bool scheduleAdjacentImpl(ScheduleDAGMI *DAG, SUnit *ASU, SmallVectorImpl<SDep> &APreds, bool Preds) { const AArch64InstrInfo *TII = static_cast<const AArch64InstrInfo *>(DAG->TII); const AArch64Subtarget &ST = DAG->MF.getSubtarget<AArch64Subtarget>(); const MachineInstr *AMI = ASU->getInstr(); if (!AMI || AMI->isPseudo() || AMI->isTransient() || (Preds && !shouldScheduleAdjacent(*TII, ST, nullptr, AMI)) || (!Preds && !shouldScheduleAdjacent(*TII, ST, AMI, nullptr))) return false; for (SDep &BDep : APreds) { if (BDep.isWeak()) continue; SUnit *BSU = BDep.getSUnit(); const MachineInstr *BMI = BSU->getInstr(); if (!BMI || BMI->isPseudo() || BMI->isTransient() || (Preds && !shouldScheduleAdjacent(*TII, ST, BMI, AMI)) || (!Preds && !shouldScheduleAdjacent(*TII, ST, AMI, BMI))) continue; // Create a single weak edge between the adjacent instrs. The only // effect is to cause bottom-up scheduling to heavily prioritize the // clustered instrs. if (Preds) DAG->addEdge(ASU, SDep(BSU, SDep::Cluster)); else DAG->addEdge(BSU, SDep(ASU, SDep::Cluster)); // Adjust the latency between the 1st instr and its predecessors/successors. for (SDep &Dep : APreds) if (Dep.getSUnit() == BSU) Dep.setLatency(0); // Adjust the latency between the 2nd instr and its successors/predecessors. auto &BSuccs = Preds ? BSU->Succs : BSU->Preds; for (SDep &Dep : BSuccs) if (Dep.getSUnit() == ASU) Dep.setLatency(0); ++NumFused; DEBUG({ SUnit *LSU = Preds ? BSU : ASU; SUnit *RSU = Preds ? ASU : BSU; const MachineInstr *LMI = Preds ? BMI : AMI; const MachineInstr *RMI = Preds ? AMI : BMI; dbgs() << DAG->MF.getName() << "(): Macro fuse "; LSU->print(dbgs(), DAG); dbgs() << " - "; RSU->print(dbgs(), DAG); dbgs() << " / " << TII->getName(LMI->getOpcode()) << " - " << TII->getName(RMI->getOpcode()) << '\n'; }); return true; } return false; } /// \brief Post-process the DAG to create cluster edges between instructions /// that may be fused by the processor into a single operation. class AArch64MacroFusion : public ScheduleDAGMutation { public: AArch64MacroFusion() {} void apply(ScheduleDAGInstrs *DAGInstrs) override; }; void AArch64MacroFusion::apply(ScheduleDAGInstrs *DAGInstrs) { ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs); // For each of the SUnits in the scheduling block, try to fuse the instruction // in it with one in its successors. for (SUnit &ASU : DAG->SUnits) scheduleAdjacentImpl(DAG, &ASU, ASU.Succs, false); // Try to fuse the instruction in the ExitSU with one in its predecessors. scheduleAdjacentImpl(DAG, &DAG->ExitSU, DAG->ExitSU.Preds, true); } } // end namespace namespace llvm { std::unique_ptr<ScheduleDAGMutation> createAArch64MacroFusionDAGMutation () { return EnableMacroFusion ? make_unique<AArch64MacroFusion>() : nullptr; } } // end namespace llvm <commit_msg>[AArch64] Simplify MacroFusion<commit_after>//===- AArch64MacroFusion.cpp - AArch64 Macro Fusion ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // \file This file contains the AArch64 implementation of the DAG scheduling mutation // to pair instructions back to back. // //===----------------------------------------------------------------------===// #include "AArch64MacroFusion.h" #include "AArch64Subtarget.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetInstrInfo.h" #define DEBUG_TYPE "misched" STATISTIC(NumFused, "Number of instr pairs fused"); using namespace llvm; static cl::opt<bool> EnableMacroFusion("aarch64-misched-fusion", cl::Hidden, cl::desc("Enable scheduling for macro fusion."), cl::init(true)); namespace { /// \brief Verify that the instr pair, FirstMI and SecondMI, should be fused /// together. Given an anchor instr, when the other instr is unspecified, then /// check if the anchor instr may be part of a fused pair at all. static bool shouldScheduleAdjacent(const TargetInstrInfo &TII, const TargetSubtargetInfo &TSI, const MachineInstr *FirstMI, const MachineInstr *SecondMI) { assert((FirstMI || SecondMI) && "At least one instr must be specified"); const AArch64InstrInfo &II = static_cast<const AArch64InstrInfo&>(TII); const AArch64Subtarget &ST = static_cast<const AArch64Subtarget&>(TSI); // Assume wildcards for unspecified instrs. unsigned FirstOpcode = FirstMI ? FirstMI->getOpcode() : static_cast<unsigned>(AArch64::INSTRUCTION_LIST_END); unsigned SecondOpcode = SecondMI ? SecondMI->getOpcode() : static_cast<unsigned>(AArch64::INSTRUCTION_LIST_END); if (ST.hasArithmeticBccFusion()) // Fuse CMN, CMP, TST followed by Bcc. if (SecondOpcode == AArch64::Bcc) switch (FirstOpcode) { default: return false; case AArch64::ADDSWri: case AArch64::ADDSWrr: case AArch64::ADDSXri: case AArch64::ADDSXrr: case AArch64::ANDSWri: case AArch64::ANDSWrr: case AArch64::ANDSXri: case AArch64::ANDSXrr: case AArch64::SUBSWri: case AArch64::SUBSWrr: case AArch64::SUBSXri: case AArch64::SUBSXrr: case AArch64::BICSWrr: case AArch64::BICSXrr: return true; case AArch64::ADDSWrs: case AArch64::ADDSXrs: case AArch64::ANDSWrs: case AArch64::ANDSXrs: case AArch64::SUBSWrs: case AArch64::SUBSXrs: case AArch64::BICSWrs: case AArch64::BICSXrs: // Shift value can be 0 making these behave like the "rr" variant... return !II.hasShiftedReg(*FirstMI); case AArch64::INSTRUCTION_LIST_END: return true; } if (ST.hasArithmeticCbzFusion()) // Fuse ALU operations followed by CBZ/CBNZ. if (SecondOpcode == AArch64::CBNZW || SecondOpcode == AArch64::CBNZX || SecondOpcode == AArch64::CBZW || SecondOpcode == AArch64::CBZX) switch (FirstOpcode) { default: return false; case AArch64::ADDWri: case AArch64::ADDWrr: case AArch64::ADDXri: case AArch64::ADDXrr: case AArch64::ANDWri: case AArch64::ANDWrr: case AArch64::ANDXri: case AArch64::ANDXrr: case AArch64::EORWri: case AArch64::EORWrr: case AArch64::EORXri: case AArch64::EORXrr: case AArch64::ORRWri: case AArch64::ORRWrr: case AArch64::ORRXri: case AArch64::ORRXrr: case AArch64::SUBWri: case AArch64::SUBWrr: case AArch64::SUBXri: case AArch64::SUBXrr: return true; case AArch64::ADDWrs: case AArch64::ADDXrs: case AArch64::ANDWrs: case AArch64::ANDXrs: case AArch64::SUBWrs: case AArch64::SUBXrs: case AArch64::BICWrs: case AArch64::BICXrs: // Shift value can be 0 making these behave like the "rr" variant... return !II.hasShiftedReg(*FirstMI); case AArch64::INSTRUCTION_LIST_END: return true; } if (ST.hasFuseAES()) // Fuse AES crypto operations. switch(FirstOpcode) { // AES encode. case AArch64::AESErr: return SecondOpcode == AArch64::AESMCrr || SecondOpcode == AArch64::INSTRUCTION_LIST_END; // AES decode. case AArch64::AESDrr: return SecondOpcode == AArch64::AESIMCrr || SecondOpcode == AArch64::INSTRUCTION_LIST_END; } if (ST.hasFuseLiterals()) // Fuse literal generation operations. switch (FirstOpcode) { // PC relative address. case AArch64::ADRP: return SecondOpcode == AArch64::ADDXri || SecondOpcode == AArch64::INSTRUCTION_LIST_END; // 32 bit immediate. case AArch64::MOVZWi: return (SecondOpcode == AArch64::MOVKWi && SecondMI->getOperand(3).getImm() == 16) || SecondOpcode == AArch64::INSTRUCTION_LIST_END; // Lower half of 64 bit immediate. case AArch64::MOVZXi: return (SecondOpcode == AArch64::MOVKXi && SecondMI->getOperand(3).getImm() == 16) || SecondOpcode == AArch64::INSTRUCTION_LIST_END; // Upper half of 64 bit immediate. case AArch64::MOVKXi: return FirstMI->getOperand(3).getImm() == 32 && ((SecondOpcode == AArch64::MOVKXi && SecondMI->getOperand(3).getImm() == 48) || SecondOpcode == AArch64::INSTRUCTION_LIST_END); } return false; } /// \brief Implement the fusion of instr pairs in the scheduling DAG, /// anchored at the instr in AnchorSU.. static bool scheduleAdjacentImpl(ScheduleDAGMI *DAG, SUnit &AnchorSU) { const MachineInstr *AnchorMI = AnchorSU.getInstr(); if (!AnchorMI || AnchorMI->isPseudo() || AnchorMI->isTransient()) return false; // If the anchor instr is the ExitSU, then consider its predecessors; // otherwise, its successors. bool Preds = (&AnchorSU == &DAG->ExitSU); SmallVectorImpl<SDep> &AnchorDeps = Preds ? AnchorSU.Preds : AnchorSU.Succs; const MachineInstr *FirstMI = Preds ? nullptr : AnchorMI; const MachineInstr *SecondMI = Preds ? AnchorMI : nullptr; // Check if the anchor instr may be fused. if (!shouldScheduleAdjacent(*DAG->TII, DAG->MF.getSubtarget(), FirstMI, SecondMI)) return false; // Explorer for fusion candidates among the dependencies of the anchor instr. for (SDep &Dep : AnchorDeps) { // Ignore dependencies that don't enforce ordering. if (Dep.isWeak()) continue; SUnit &DepSU = *Dep.getSUnit(); // Ignore the ExitSU if the dependents are successors. if (!Preds && &DepSU == &DAG->ExitSU) continue; const MachineInstr *DepMI = DepSU.getInstr(); if (!DepMI || DepMI->isPseudo() || DepMI->isTransient()) continue; FirstMI = Preds ? DepMI : AnchorMI; SecondMI = Preds ? AnchorMI : DepMI; if (!shouldScheduleAdjacent(*DAG->TII, DAG->MF.getSubtarget(), FirstMI, SecondMI)) continue; // Create a single weak edge between the adjacent instrs. The only effect is // to cause bottom-up scheduling to heavily prioritize the clustered instrs. SUnit &FirstSU = Preds ? DepSU : AnchorSU; SUnit &SecondSU = Preds ? AnchorSU : DepSU; DAG->addEdge(&SecondSU, SDep(&FirstSU, SDep::Cluster)); // Adjust the latency between the anchor instr and its // predecessors/successors. for (SDep &IDep : AnchorDeps) if (IDep.getSUnit() == &DepSU) IDep.setLatency(0); // Adjust the latency between the dependent instr and its // successors/predecessors. for (SDep &IDep : Preds ? DepSU.Succs : DepSU.Preds) if (IDep.getSUnit() == &AnchorSU) IDep.setLatency(0); DEBUG(dbgs() << DAG->MF.getName() << "(): Macro fuse "; FirstSU.print(dbgs(), DAG); dbgs() << " - "; SecondSU.print(dbgs(), DAG); dbgs() << " / "; dbgs() << DAG->TII->getName(FirstMI->getOpcode()) << " - " << DAG->TII->getName(SecondMI->getOpcode()) << '\n'; ); ++NumFused; return true; } return false; } /// \brief Post-process the DAG to create cluster edges between instrs that may /// be fused by the processor into a single operation. class AArch64MacroFusion : public ScheduleDAGMutation { public: AArch64MacroFusion() {} void apply(ScheduleDAGInstrs *DAGInstrs) override; }; void AArch64MacroFusion::apply(ScheduleDAGInstrs *DAGInstrs) { ScheduleDAGMI *DAG = static_cast<ScheduleDAGMI*>(DAGInstrs); // For each of the SUnits in the scheduling block, try to fuse the instr in it // with one in its successors. for (SUnit &ISU : DAG->SUnits) scheduleAdjacentImpl(DAG, ISU); // Try to fuse the instr in the ExitSU with one in its predecessors. scheduleAdjacentImpl(DAG, DAG->ExitSU); } } // end namespace namespace llvm { std::unique_ptr<ScheduleDAGMutation> createAArch64MacroFusionDAGMutation () { return EnableMacroFusion ? make_unique<AArch64MacroFusion>() : nullptr; } } // end namespace llvm <|endoftext|>
<commit_before>//===- AMDGPUAliasAnalysis ------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This is the AMGPU address space based alias analysis pass. //===----------------------------------------------------------------------===// #include "AMDGPUAliasAnalysis.h" #include "AMDGPU.h" #include "llvm/ADT/Triple.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/MemoryLocation.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/Argument.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/CallingConv.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Type.h" #include "llvm/IR/Value.h" #include "llvm/Pass.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ErrorHandling.h" #include <cassert> using namespace llvm; #define DEBUG_TYPE "amdgpu-aa" // Register this pass... char AMDGPUAAWrapperPass::ID = 0; INITIALIZE_PASS(AMDGPUAAWrapperPass, "amdgpu-aa", "AMDGPU Address space based Alias Analysis", false, true) ImmutablePass *llvm::createAMDGPUAAWrapperPass() { return new AMDGPUAAWrapperPass(); } void AMDGPUAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } // Must match the table in getAliasResult. AMDGPUAAResult::ASAliasRulesTy::ASAliasRulesTy(AMDGPUAS AS_, Triple::ArchType Arch_) : Arch(Arch_), AS(AS_) { // These arrarys are indexed by address space value // enum elements 0 ... to 5 static const AliasResult ASAliasRulesPrivIsZero[6][6] = { /* Private Global Constant Group Flat Region*/ /* Private */ {MayAlias, NoAlias , NoAlias , NoAlias , MayAlias, NoAlias}, /* Global */ {NoAlias , MayAlias, NoAlias , NoAlias , MayAlias, NoAlias}, /* Constant */ {NoAlias , NoAlias , MayAlias, NoAlias , MayAlias, NoAlias}, /* Group */ {NoAlias , NoAlias , NoAlias , MayAlias, MayAlias, NoAlias}, /* Flat */ {MayAlias, MayAlias, MayAlias, MayAlias, MayAlias, MayAlias}, /* Region */ {NoAlias , NoAlias , NoAlias , NoAlias , MayAlias, MayAlias} }; static const AliasResult ASAliasRulesGenIsZero[6][6] = { /* Flat Global Region Group Constant Private */ /* Flat */ {MayAlias, MayAlias, MayAlias, MayAlias, MayAlias, MayAlias}, /* Global */ {MayAlias, MayAlias, NoAlias , NoAlias , NoAlias , NoAlias}, /* Constant */ {MayAlias, NoAlias , MayAlias, NoAlias , NoAlias, NoAlias}, /* Group */ {MayAlias, NoAlias , NoAlias , MayAlias, NoAlias , NoAlias}, /* Region */ {MayAlias, NoAlias , NoAlias , NoAlias, MayAlias, NoAlias}, /* Private */ {MayAlias, NoAlias , NoAlias , NoAlias , NoAlias , MayAlias} }; static_assert(AS.MAX_COMMON_ADDRESS <= 6, "Addr space out of range"); if (AS.FLAT_ADDRESS == 0) { assert(AS.GLOBAL_ADDRESS == 1 && AS.REGION_ADDRESS == 2 && AS.LOCAL_ADDRESS == 3 && AS.CONSTANT_ADDRESS == 4 && AS.PRIVATE_ADDRESS == 5); ASAliasRules = &ASAliasRulesGenIsZero; } else { assert(AS.PRIVATE_ADDRESS == 0 && AS.GLOBAL_ADDRESS == 1 && AS.CONSTANT_ADDRESS == 2 && AS.LOCAL_ADDRESS == 3 && AS.FLAT_ADDRESS == 4 && AS.REGION_ADDRESS == 5); ASAliasRules = &ASAliasRulesPrivIsZero; } } AliasResult AMDGPUAAResult::ASAliasRulesTy::getAliasResult(unsigned AS1, unsigned AS2) const { if (AS1 > AS.MAX_COMMON_ADDRESS || AS2 > AS.MAX_COMMON_ADDRESS) { if (Arch == Triple::amdgcn) report_fatal_error("Pointer address space out of range"); return AS1 == AS2 ? MayAlias : NoAlias; } return (*ASAliasRules)[AS1][AS2]; } AliasResult AMDGPUAAResult::alias(const MemoryLocation &LocA, const MemoryLocation &LocB) { unsigned asA = LocA.Ptr->getType()->getPointerAddressSpace(); unsigned asB = LocB.Ptr->getType()->getPointerAddressSpace(); AliasResult Result = ASAliasRules.getAliasResult(asA, asB); if (Result == NoAlias) return Result; // Forward the query to the next alias analysis. return AAResultBase::alias(LocA, LocB); } bool AMDGPUAAResult::pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) { const Value *Base = GetUnderlyingObject(Loc.Ptr, DL); if (Base->getType()->getPointerAddressSpace() == AS.CONSTANT_ADDRESS || Base->getType()->getPointerAddressSpace() == AS.CONSTANT_ADDRESS_32BIT) { return true; } if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) { if (GV->isConstant()) return true; } else if (const Argument *Arg = dyn_cast<Argument>(Base)) { const Function *F = Arg->getParent(); // Only assume constant memory for arguments on kernels. switch (F->getCallingConv()) { default: return AAResultBase::pointsToConstantMemory(Loc, OrLocal); case CallingConv::AMDGPU_LS: case CallingConv::AMDGPU_HS: case CallingConv::AMDGPU_ES: case CallingConv::AMDGPU_GS: case CallingConv::AMDGPU_VS: case CallingConv::AMDGPU_PS: case CallingConv::AMDGPU_CS: case CallingConv::AMDGPU_KERNEL: case CallingConv::SPIR_KERNEL: break; } unsigned ArgNo = Arg->getArgNo(); /* On an argument, ReadOnly attribute indicates that the function does not write through this pointer argument, even though it may write to the memory that the pointer points to. On an argument, ReadNone attribute indicates that the function does not dereference that pointer argument, even though it may read or write the memory that the pointer points to if accessed through other pointers. */ if (F->hasParamAttribute(ArgNo, Attribute::NoAlias) && (F->hasParamAttribute(ArgNo, Attribute::ReadNone) || F->hasParamAttribute(ArgNo, Attribute::ReadOnly))) { return true; } } return AAResultBase::pointsToConstantMemory(Loc, OrLocal); } <commit_msg>AMDGPU: fix compilation errors since r340171<commit_after>//===- AMDGPUAliasAnalysis ------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This is the AMGPU address space based alias analysis pass. //===----------------------------------------------------------------------===// #include "AMDGPUAliasAnalysis.h" #include "AMDGPU.h" #include "llvm/ADT/Triple.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/MemoryLocation.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/IR/Argument.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/CallingConv.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Type.h" #include "llvm/IR/Value.h" #include "llvm/Pass.h" #include "llvm/Support/Casting.h" #include "llvm/Support/ErrorHandling.h" #include <cassert> using namespace llvm; #define DEBUG_TYPE "amdgpu-aa" // Register this pass... char AMDGPUAAWrapperPass::ID = 0; INITIALIZE_PASS(AMDGPUAAWrapperPass, "amdgpu-aa", "AMDGPU Address space based Alias Analysis", false, true) ImmutablePass *llvm::createAMDGPUAAWrapperPass() { return new AMDGPUAAWrapperPass(); } void AMDGPUAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } // Must match the table in getAliasResult. AMDGPUAAResult::ASAliasRulesTy::ASAliasRulesTy(AMDGPUAS AS_, Triple::ArchType Arch_) : Arch(Arch_), AS(AS_) { // These arrarys are indexed by address space value // enum elements 0 ... to 5 static const AliasResult ASAliasRulesPrivIsZero[6][6] = { /* Private Global Constant Group Flat Region*/ /* Private */ {MayAlias, NoAlias , NoAlias , NoAlias , MayAlias, NoAlias}, /* Global */ {NoAlias , MayAlias, NoAlias , NoAlias , MayAlias, NoAlias}, /* Constant */ {NoAlias , NoAlias , MayAlias, NoAlias , MayAlias, NoAlias}, /* Group */ {NoAlias , NoAlias , NoAlias , MayAlias, MayAlias, NoAlias}, /* Flat */ {MayAlias, MayAlias, MayAlias, MayAlias, MayAlias, MayAlias}, /* Region */ {NoAlias , NoAlias , NoAlias , NoAlias , MayAlias, MayAlias} }; static const AliasResult ASAliasRulesGenIsZero[6][6] = { /* Flat Global Region Group Constant Private */ /* Flat */ {MayAlias, MayAlias, MayAlias, MayAlias, MayAlias, MayAlias}, /* Global */ {MayAlias, MayAlias, NoAlias , NoAlias , NoAlias , NoAlias}, /* Constant */ {MayAlias, NoAlias , MayAlias, NoAlias , NoAlias, NoAlias}, /* Group */ {MayAlias, NoAlias , NoAlias , MayAlias, NoAlias , NoAlias}, /* Region */ {MayAlias, NoAlias , NoAlias , NoAlias, MayAlias, NoAlias}, /* Private */ {MayAlias, NoAlias , NoAlias , NoAlias , NoAlias , MayAlias} }; static_assert(AMDGPUAS::MAX_COMMON_ADDRESS <= 6, "Addr space out of range"); if (AS.FLAT_ADDRESS == 0) { assert(AS.GLOBAL_ADDRESS == 1 && AS.REGION_ADDRESS == 2 && AS.LOCAL_ADDRESS == 3 && AS.CONSTANT_ADDRESS == 4 && AS.PRIVATE_ADDRESS == 5); ASAliasRules = &ASAliasRulesGenIsZero; } else { assert(AS.PRIVATE_ADDRESS == 0 && AS.GLOBAL_ADDRESS == 1 && AS.CONSTANT_ADDRESS == 2 && AS.LOCAL_ADDRESS == 3 && AS.FLAT_ADDRESS == 4 && AS.REGION_ADDRESS == 5); ASAliasRules = &ASAliasRulesPrivIsZero; } } AliasResult AMDGPUAAResult::ASAliasRulesTy::getAliasResult(unsigned AS1, unsigned AS2) const { if (AS1 > AS.MAX_COMMON_ADDRESS || AS2 > AS.MAX_COMMON_ADDRESS) { if (Arch == Triple::amdgcn) report_fatal_error("Pointer address space out of range"); return AS1 == AS2 ? MayAlias : NoAlias; } return (*ASAliasRules)[AS1][AS2]; } AliasResult AMDGPUAAResult::alias(const MemoryLocation &LocA, const MemoryLocation &LocB) { unsigned asA = LocA.Ptr->getType()->getPointerAddressSpace(); unsigned asB = LocB.Ptr->getType()->getPointerAddressSpace(); AliasResult Result = ASAliasRules.getAliasResult(asA, asB); if (Result == NoAlias) return Result; // Forward the query to the next alias analysis. return AAResultBase::alias(LocA, LocB); } bool AMDGPUAAResult::pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) { const Value *Base = GetUnderlyingObject(Loc.Ptr, DL); if (Base->getType()->getPointerAddressSpace() == AS.CONSTANT_ADDRESS || Base->getType()->getPointerAddressSpace() == AS.CONSTANT_ADDRESS_32BIT) { return true; } if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) { if (GV->isConstant()) return true; } else if (const Argument *Arg = dyn_cast<Argument>(Base)) { const Function *F = Arg->getParent(); // Only assume constant memory for arguments on kernels. switch (F->getCallingConv()) { default: return AAResultBase::pointsToConstantMemory(Loc, OrLocal); case CallingConv::AMDGPU_LS: case CallingConv::AMDGPU_HS: case CallingConv::AMDGPU_ES: case CallingConv::AMDGPU_GS: case CallingConv::AMDGPU_VS: case CallingConv::AMDGPU_PS: case CallingConv::AMDGPU_CS: case CallingConv::AMDGPU_KERNEL: case CallingConv::SPIR_KERNEL: break; } unsigned ArgNo = Arg->getArgNo(); /* On an argument, ReadOnly attribute indicates that the function does not write through this pointer argument, even though it may write to the memory that the pointer points to. On an argument, ReadNone attribute indicates that the function does not dereference that pointer argument, even though it may read or write the memory that the pointer points to if accessed through other pointers. */ if (F->hasParamAttribute(ArgNo, Attribute::NoAlias) && (F->hasParamAttribute(ArgNo, Attribute::ReadNone) || F->hasParamAttribute(ArgNo, Attribute::ReadOnly))) { return true; } } return AAResultBase::pointsToConstantMemory(Loc, OrLocal); } <|endoftext|>
<commit_before>//===- AMDGPUAliasAnalysis ---------------------------------------*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This is the AMGPU address space based alias analysis pass. //===----------------------------------------------------------------------===// #include "AMDGPU.h" #include "AMDGPUAliasAnalysis.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/Analysis/Passes.h" #include "llvm/Support/raw_ostream.h" #include "llvm/IR/Function.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" using namespace llvm; #define DEBUG_TYPE "amdgpu-aa" // Register this pass... char AMDGPUAAWrapperPass::ID = 0; INITIALIZE_PASS(AMDGPUAAWrapperPass, "amdgpu-aa", "AMDGPU Address space based Alias Analysis", false, true) ImmutablePass *llvm::createAMDGPUAAWrapperPass() { return new AMDGPUAAWrapperPass(); } void AMDGPUAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } // Must match the table in getAliasResult. AMDGPUAAResult::ASAliasRulesTy::ASAliasRulesTy(AMDGPUAS AS_, Triple::ArchType Arch_) : Arch(Arch_), AS(AS_) { // These arrarys are indexed by address space value // enum elements 0 ... to 5 static const AliasResult ASAliasRulesPrivIsZero[6][6] = { /* Private Global Constant Group Flat Region*/ /* Private */ {MayAlias, NoAlias , NoAlias , NoAlias , MayAlias, NoAlias}, /* Global */ {NoAlias , MayAlias, NoAlias , NoAlias , MayAlias, NoAlias}, /* Constant */ {NoAlias , NoAlias , MayAlias, NoAlias , MayAlias, NoAlias}, /* Group */ {NoAlias , NoAlias , NoAlias , MayAlias, MayAlias, NoAlias}, /* Flat */ {MayAlias, MayAlias, MayAlias, MayAlias, MayAlias, MayAlias}, /* Region */ {NoAlias , NoAlias , NoAlias , NoAlias , MayAlias, MayAlias} }; static const AliasResult ASAliasRulesGenIsZero[6][6] = { /* Flat Global Region Group Constant Private */ /* Flat */ {MayAlias, MayAlias, MayAlias, MayAlias, MayAlias, MayAlias}, /* Global */ {MayAlias, MayAlias, NoAlias , NoAlias , NoAlias , NoAlias}, /* Region */ {NoAlias , NoAlias , MayAlias, NoAlias, NoAlias , MayAlias}, /* Group */ {MayAlias, NoAlias , NoAlias , MayAlias, NoAlias , NoAlias}, /* Constant */ {MayAlias, NoAlias , NoAlias , NoAlias , MayAlias, NoAlias}, /* Private */ {MayAlias, NoAlias , NoAlias , NoAlias , NoAlias , MayAlias} }; assert(AS.MAX_COMMON_ADDRESS <= 5); if (AS.FLAT_ADDRESS == 0) { assert(AS.GLOBAL_ADDRESS == 1 && AS.REGION_ADDRESS == 2 && AS.LOCAL_ADDRESS == 3 && AS.CONSTANT_ADDRESS == 4 && AS.PRIVATE_ADDRESS == 5); ASAliasRules = &ASAliasRulesGenIsZero; } else { assert(AS.PRIVATE_ADDRESS == 0 && AS.GLOBAL_ADDRESS == 1 && AS.CONSTANT_ADDRESS == 2 && AS.LOCAL_ADDRESS == 3 && AS.FLAT_ADDRESS == 4 && AS.REGION_ADDRESS == 5); ASAliasRules = &ASAliasRulesPrivIsZero; } } AliasResult AMDGPUAAResult::ASAliasRulesTy::getAliasResult(unsigned AS1, unsigned AS2) const { if (AS1 > AS.MAX_COMMON_ADDRESS || AS2 > AS.MAX_COMMON_ADDRESS) { if (Arch == Triple::amdgcn) report_fatal_error("Pointer address space out of range"); return AS1 == AS2 ? MayAlias : NoAlias; } return (*ASAliasRules)[AS1][AS2]; } AliasResult AMDGPUAAResult::alias(const MemoryLocation &LocA, const MemoryLocation &LocB) { unsigned asA = LocA.Ptr->getType()->getPointerAddressSpace(); unsigned asB = LocB.Ptr->getType()->getPointerAddressSpace(); AliasResult Result = ASAliasRules.getAliasResult(asA, asB); if (Result == NoAlias) return Result; if (isa<Argument>(LocA.Ptr) && isa<Argument>(LocB.Ptr)) { Type *T1 = cast<PointerType>(LocA.Ptr->getType())->getElementType(); Type *T2 = cast<PointerType>(LocB.Ptr->getType())->getElementType(); if ((T1->isVectorTy() && !T2->isVectorTy()) || (T2->isVectorTy() && !T1->isVectorTy())) return NoAlias; } // Forward the query to the next alias analysis. return AAResultBase::alias(LocA, LocB); } bool AMDGPUAAResult::pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) { const Value *Base = GetUnderlyingObject(Loc.Ptr, DL); if (Base->getType()->getPointerAddressSpace() == AS.CONSTANT_ADDRESS) { return true; } if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) { if (GV->isConstant()) return true; } else if (const Argument *Arg = dyn_cast<Argument>(Base)) { const Function *F = Arg->getParent(); // Only assume constant memory for arguments on kernels. switch (F->getCallingConv()) { default: return AAResultBase::pointsToConstantMemory(Loc, OrLocal); case CallingConv::AMDGPU_VS: case CallingConv::AMDGPU_GS: case CallingConv::AMDGPU_PS: case CallingConv::AMDGPU_CS: case CallingConv::AMDGPU_KERNEL: case CallingConv::SPIR_KERNEL: break; } unsigned ArgNo = Arg->getArgNo(); /* On an argument, ReadOnly attribute indicates that the function does not write through this pointer argument, even though it may write to the memory that the pointer points to. On an argument, ReadNone attribute indicates that the function does not dereference that pointer argument, even though it may read or write the memory that the pointer points to if accessed through other pointers. */ if (F->getAttributes().hasAttribute(ArgNo + 1, Attribute::NoAlias) && (F->getAttributes().hasAttribute(ArgNo + 1, Attribute::ReadNone) || F->getAttributes().hasAttribute(ArgNo + 1, Attribute::ReadOnly))) { return true; } } return AAResultBase::pointsToConstantMemory(Loc, OrLocal); } <commit_msg>[AMDGPU] Remove assumption that vector and scalar types do not alias<commit_after>//===- AMDGPUAliasAnalysis ---------------------------------------*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// \file /// This is the AMGPU address space based alias analysis pass. //===----------------------------------------------------------------------===// #include "AMDGPU.h" #include "AMDGPUAliasAnalysis.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/ValueTracking.h" #include "llvm/Analysis/Passes.h" #include "llvm/Support/raw_ostream.h" #include "llvm/IR/Function.h" #include "llvm/IR/Module.h" #include "llvm/Pass.h" using namespace llvm; #define DEBUG_TYPE "amdgpu-aa" // Register this pass... char AMDGPUAAWrapperPass::ID = 0; INITIALIZE_PASS(AMDGPUAAWrapperPass, "amdgpu-aa", "AMDGPU Address space based Alias Analysis", false, true) ImmutablePass *llvm::createAMDGPUAAWrapperPass() { return new AMDGPUAAWrapperPass(); } void AMDGPUAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } // Must match the table in getAliasResult. AMDGPUAAResult::ASAliasRulesTy::ASAliasRulesTy(AMDGPUAS AS_, Triple::ArchType Arch_) : Arch(Arch_), AS(AS_) { // These arrarys are indexed by address space value // enum elements 0 ... to 5 static const AliasResult ASAliasRulesPrivIsZero[6][6] = { /* Private Global Constant Group Flat Region*/ /* Private */ {MayAlias, NoAlias , NoAlias , NoAlias , MayAlias, NoAlias}, /* Global */ {NoAlias , MayAlias, NoAlias , NoAlias , MayAlias, NoAlias}, /* Constant */ {NoAlias , NoAlias , MayAlias, NoAlias , MayAlias, NoAlias}, /* Group */ {NoAlias , NoAlias , NoAlias , MayAlias, MayAlias, NoAlias}, /* Flat */ {MayAlias, MayAlias, MayAlias, MayAlias, MayAlias, MayAlias}, /* Region */ {NoAlias , NoAlias , NoAlias , NoAlias , MayAlias, MayAlias} }; static const AliasResult ASAliasRulesGenIsZero[6][6] = { /* Flat Global Region Group Constant Private */ /* Flat */ {MayAlias, MayAlias, MayAlias, MayAlias, MayAlias, MayAlias}, /* Global */ {MayAlias, MayAlias, NoAlias , NoAlias , NoAlias , NoAlias}, /* Region */ {NoAlias , NoAlias , MayAlias, NoAlias, NoAlias , MayAlias}, /* Group */ {MayAlias, NoAlias , NoAlias , MayAlias, NoAlias , NoAlias}, /* Constant */ {MayAlias, NoAlias , NoAlias , NoAlias , MayAlias, NoAlias}, /* Private */ {MayAlias, NoAlias , NoAlias , NoAlias , NoAlias , MayAlias} }; assert(AS.MAX_COMMON_ADDRESS <= 5); if (AS.FLAT_ADDRESS == 0) { assert(AS.GLOBAL_ADDRESS == 1 && AS.REGION_ADDRESS == 2 && AS.LOCAL_ADDRESS == 3 && AS.CONSTANT_ADDRESS == 4 && AS.PRIVATE_ADDRESS == 5); ASAliasRules = &ASAliasRulesGenIsZero; } else { assert(AS.PRIVATE_ADDRESS == 0 && AS.GLOBAL_ADDRESS == 1 && AS.CONSTANT_ADDRESS == 2 && AS.LOCAL_ADDRESS == 3 && AS.FLAT_ADDRESS == 4 && AS.REGION_ADDRESS == 5); ASAliasRules = &ASAliasRulesPrivIsZero; } } AliasResult AMDGPUAAResult::ASAliasRulesTy::getAliasResult(unsigned AS1, unsigned AS2) const { if (AS1 > AS.MAX_COMMON_ADDRESS || AS2 > AS.MAX_COMMON_ADDRESS) { if (Arch == Triple::amdgcn) report_fatal_error("Pointer address space out of range"); return AS1 == AS2 ? MayAlias : NoAlias; } return (*ASAliasRules)[AS1][AS2]; } AliasResult AMDGPUAAResult::alias(const MemoryLocation &LocA, const MemoryLocation &LocB) { unsigned asA = LocA.Ptr->getType()->getPointerAddressSpace(); unsigned asB = LocB.Ptr->getType()->getPointerAddressSpace(); AliasResult Result = ASAliasRules.getAliasResult(asA, asB); if (Result == NoAlias) return Result; // Forward the query to the next alias analysis. return AAResultBase::alias(LocA, LocB); } bool AMDGPUAAResult::pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal) { const Value *Base = GetUnderlyingObject(Loc.Ptr, DL); if (Base->getType()->getPointerAddressSpace() == AS.CONSTANT_ADDRESS) { return true; } if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(Base)) { if (GV->isConstant()) return true; } else if (const Argument *Arg = dyn_cast<Argument>(Base)) { const Function *F = Arg->getParent(); // Only assume constant memory for arguments on kernels. switch (F->getCallingConv()) { default: return AAResultBase::pointsToConstantMemory(Loc, OrLocal); case CallingConv::AMDGPU_VS: case CallingConv::AMDGPU_GS: case CallingConv::AMDGPU_PS: case CallingConv::AMDGPU_CS: case CallingConv::AMDGPU_KERNEL: case CallingConv::SPIR_KERNEL: break; } unsigned ArgNo = Arg->getArgNo(); /* On an argument, ReadOnly attribute indicates that the function does not write through this pointer argument, even though it may write to the memory that the pointer points to. On an argument, ReadNone attribute indicates that the function does not dereference that pointer argument, even though it may read or write the memory that the pointer points to if accessed through other pointers. */ if (F->getAttributes().hasAttribute(ArgNo + 1, Attribute::NoAlias) && (F->getAttributes().hasAttribute(ArgNo + 1, Attribute::ReadNone) || F->getAttributes().hasAttribute(ArgNo + 1, Attribute::ReadOnly))) { return true; } } return AAResultBase::pointsToConstantMemory(Loc, OrLocal); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "executorjob.h" #include "artifact.h" #include "command.h" #include "jscommandexecutor.h" #include "processcommandexecutor.h" #include "transformer.h" #include <language/language.h> #include <tools/error.h> #include <tools/qbsassert.h> #include <QThread> namespace qbs { namespace Internal { ExecutorJob::ExecutorJob(const Logger &logger, QObject *parent) : QObject(parent) , m_processCommandExecutor(new ProcessCommandExecutor(logger, this)) , m_jsCommandExecutor(new JsCommandExecutor(logger, this)) { connect(m_processCommandExecutor, SIGNAL(reportCommandDescription(QString,QString)), this, SIGNAL(reportCommandDescription(QString,QString))); connect(m_processCommandExecutor, SIGNAL(reportProcessResult(qbs::ProcessResult)), this, SIGNAL(reportProcessResult(qbs::ProcessResult))); connect(m_processCommandExecutor, SIGNAL(finished(qbs::ErrorInfo)), this, SLOT(onCommandFinished(qbs::ErrorInfo))); connect(m_jsCommandExecutor, SIGNAL(reportCommandDescription(QString,QString)), this, SIGNAL(reportCommandDescription(QString,QString))); connect(m_jsCommandExecutor, SIGNAL(finished(qbs::ErrorInfo)), this, SLOT(onCommandFinished(qbs::ErrorInfo))); reset(); } ExecutorJob::~ExecutorJob() { } void ExecutorJob::setMainThreadScriptEngine(ScriptEngine *engine) { m_processCommandExecutor->setMainThreadScriptEngine(engine); m_jsCommandExecutor->setMainThreadScriptEngine(engine); } void ExecutorJob::setDryRun(bool enabled) { m_processCommandExecutor->setDryRunEnabled(enabled); m_jsCommandExecutor->setDryRunEnabled(enabled); } void ExecutorJob::run(Transformer *t) { QBS_ASSERT(m_currentCommandIdx == -1, return); if (t->commands.isEmpty()) { setFinished(); return; } t->propertiesRequestedInCommands.clear(); QBS_CHECK(!t->outputs.isEmpty()); m_processCommandExecutor->setProcessEnvironment( (*t->outputs.begin())->product->buildEnvironment); m_transformer = t; runNextCommand(); } void ExecutorJob::cancel() { QBS_ASSERT(m_currentCommandExecutor, return); m_error = ErrorInfo(tr("Transformer execution canceled.")); m_currentCommandExecutor->cancel(); } void ExecutorJob::runNextCommand() { QBS_ASSERT(m_currentCommandIdx <= m_transformer->commands.count(), return); ++m_currentCommandIdx; if (m_currentCommandIdx >= m_transformer->commands.count()) { setFinished(); return; } const AbstractCommandPtr &command = m_transformer->commands.at(m_currentCommandIdx); switch (command->type()) { case AbstractCommand::ProcessCommandType: m_currentCommandExecutor = m_processCommandExecutor; break; case AbstractCommand::JavaScriptCommandType: m_currentCommandExecutor = m_jsCommandExecutor; break; default: qFatal("Missing implementation for command type %d", command->type()); } m_currentCommandExecutor->start(m_transformer, command.data()); } void ExecutorJob::onCommandFinished(const ErrorInfo &err) { QBS_ASSERT(m_transformer, return); if (m_error.hasError()) { // Canceled? setFinished(); } else if (err.hasError()) { m_error = err; setFinished(); } else { runNextCommand(); } } void ExecutorJob::setFinished() { const ErrorInfo err = m_error; reset(); emit finished(err); } void ExecutorJob::reset() { m_transformer = 0; m_currentCommandExecutor = 0; m_currentCommandIdx = -1; m_error.clear(); } } // namespace Internal } // namespace qbs <commit_msg>Remove invalid assertion.<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the Qt Build Suite. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "executorjob.h" #include "artifact.h" #include "command.h" #include "jscommandexecutor.h" #include "processcommandexecutor.h" #include "transformer.h" #include <language/language.h> #include <tools/error.h> #include <tools/qbsassert.h> #include <QThread> namespace qbs { namespace Internal { ExecutorJob::ExecutorJob(const Logger &logger, QObject *parent) : QObject(parent) , m_processCommandExecutor(new ProcessCommandExecutor(logger, this)) , m_jsCommandExecutor(new JsCommandExecutor(logger, this)) { connect(m_processCommandExecutor, SIGNAL(reportCommandDescription(QString,QString)), this, SIGNAL(reportCommandDescription(QString,QString))); connect(m_processCommandExecutor, SIGNAL(reportProcessResult(qbs::ProcessResult)), this, SIGNAL(reportProcessResult(qbs::ProcessResult))); connect(m_processCommandExecutor, SIGNAL(finished(qbs::ErrorInfo)), this, SLOT(onCommandFinished(qbs::ErrorInfo))); connect(m_jsCommandExecutor, SIGNAL(reportCommandDescription(QString,QString)), this, SIGNAL(reportCommandDescription(QString,QString))); connect(m_jsCommandExecutor, SIGNAL(finished(qbs::ErrorInfo)), this, SLOT(onCommandFinished(qbs::ErrorInfo))); reset(); } ExecutorJob::~ExecutorJob() { } void ExecutorJob::setMainThreadScriptEngine(ScriptEngine *engine) { m_processCommandExecutor->setMainThreadScriptEngine(engine); m_jsCommandExecutor->setMainThreadScriptEngine(engine); } void ExecutorJob::setDryRun(bool enabled) { m_processCommandExecutor->setDryRunEnabled(enabled); m_jsCommandExecutor->setDryRunEnabled(enabled); } void ExecutorJob::run(Transformer *t) { QBS_ASSERT(m_currentCommandIdx == -1, return); if (t->commands.isEmpty()) { setFinished(); return; } t->propertiesRequestedInCommands.clear(); QBS_CHECK(!t->outputs.isEmpty()); m_processCommandExecutor->setProcessEnvironment( (*t->outputs.begin())->product->buildEnvironment); m_transformer = t; runNextCommand(); } void ExecutorJob::cancel() { if (!m_currentCommandExecutor) return; m_error = ErrorInfo(tr("Transformer execution canceled.")); m_currentCommandExecutor->cancel(); } void ExecutorJob::runNextCommand() { QBS_ASSERT(m_currentCommandIdx <= m_transformer->commands.count(), return); ++m_currentCommandIdx; if (m_currentCommandIdx >= m_transformer->commands.count()) { setFinished(); return; } const AbstractCommandPtr &command = m_transformer->commands.at(m_currentCommandIdx); switch (command->type()) { case AbstractCommand::ProcessCommandType: m_currentCommandExecutor = m_processCommandExecutor; break; case AbstractCommand::JavaScriptCommandType: m_currentCommandExecutor = m_jsCommandExecutor; break; default: qFatal("Missing implementation for command type %d", command->type()); } m_currentCommandExecutor->start(m_transformer, command.data()); } void ExecutorJob::onCommandFinished(const ErrorInfo &err) { QBS_ASSERT(m_transformer, return); if (m_error.hasError()) { // Canceled? setFinished(); } else if (err.hasError()) { m_error = err; setFinished(); } else { runNextCommand(); } } void ExecutorJob::setFinished() { const ErrorInfo err = m_error; reset(); emit finished(err); } void ExecutorJob::reset() { m_transformer = 0; m_currentCommandExecutor = 0; m_currentCommandIdx = -1; m_error.clear(); } } // namespace Internal } // namespace qbs <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/remote_bitrate_estimator/test/bwe_test.h" #include "webrtc/base/common.h" #include "webrtc/base/scoped_ptr.h" #include "webrtc/modules/interface/module_common_types.h" #include "webrtc/modules/remote_bitrate_estimator/test/bwe_test_framework.h" #include "webrtc/modules/remote_bitrate_estimator/test/packet_receiver.h" #include "webrtc/modules/remote_bitrate_estimator/test/packet_sender.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/test/testsupport/perf_test.h" using std::string; using std::vector; namespace webrtc { namespace testing { namespace bwe { PacketProcessorRunner::PacketProcessorRunner(PacketProcessor* processor) : processor_(processor) { } PacketProcessorRunner::~PacketProcessorRunner() { for (Packet* packet : queue_) delete packet; } bool PacketProcessorRunner::RunsProcessor( const PacketProcessor* processor) const { return processor == processor_; } void PacketProcessorRunner::RunFor(int64_t time_ms, int64_t time_now_ms, Packets* in_out) { Packets to_process; FindPacketsToProcess(processor_->flow_ids(), in_out, &to_process); processor_->RunFor(time_ms, &to_process); QueuePackets(&to_process, time_now_ms * 1000); if (!to_process.empty()) { processor_->Plot((to_process.back()->send_time_us() + 500) / 1000); } in_out->merge(to_process, DereferencingComparator<Packet>); } void PacketProcessorRunner::FindPacketsToProcess(const FlowIds& flow_ids, Packets* in, Packets* out) { assert(out->empty()); for (Packets::iterator it = in->begin(); it != in->end();) { // TODO(holmer): Further optimize this by looking for consecutive flow ids // in the packet list and only doing the binary search + splice once for a // sequence. if (flow_ids.find((*it)->flow_id()) != flow_ids.end()) { Packets::iterator next = it; ++next; out->splice(out->end(), *in, it); it = next; } else { ++it; } } } void PacketProcessorRunner::QueuePackets(Packets* batch, int64_t end_of_batch_time_us) { queue_.merge(*batch, DereferencingComparator<Packet>); if (queue_.empty()) { return; } Packets::iterator it = queue_.begin(); for (; it != queue_.end(); ++it) { if ((*it)->send_time_us() > end_of_batch_time_us) { break; } } Packets to_transfer; to_transfer.splice(to_transfer.begin(), queue_, queue_.begin(), it); batch->merge(to_transfer, DereferencingComparator<Packet>); } BweTest::BweTest() : run_time_ms_(0), time_now_ms_(-1), simulation_interval_ms_(-1) { links_.push_back(&uplink_); links_.push_back(&downlink_); } BweTest::~BweTest() { for (Packet* packet : packets_) delete packet; } void BweTest::SetUp() { const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); string test_name = string(test_info->test_case_name()) + "_" + string(test_info->name()); BWE_TEST_LOGGING_GLOBAL_CONTEXT(test_name); BWE_TEST_LOGGING_GLOBAL_ENABLE(false); } void Link::AddPacketProcessor(PacketProcessor* processor, ProcessorType processor_type) { assert(processor); switch (processor_type) { case kSender: senders_.push_back(static_cast<PacketSender*>(processor)); break; case kReceiver: receivers_.push_back(static_cast<PacketReceiver*>(processor)); break; case kRegular: break; } processors_.push_back(PacketProcessorRunner(processor)); } void Link::RemovePacketProcessor(PacketProcessor* processor) { for (vector<PacketProcessorRunner>::iterator it = processors_.begin(); it != processors_.end(); ++it) { if (it->RunsProcessor(processor)) { processors_.erase(it); return; } } assert(false); } // Ownership of the created packets is handed over to the caller. void Link::Run(int64_t run_for_ms, int64_t now_ms, Packets* packets) { for (auto& processor : processors_) { processor.RunFor(run_for_ms, now_ms, packets); } } void BweTest::VerboseLogging(bool enable) { BWE_TEST_LOGGING_GLOBAL_ENABLE(enable); } void BweTest::RunFor(int64_t time_ms) { // Set simulation interval from first packet sender. // TODO(holmer): Support different feedback intervals for different flows. if (!uplink_.senders().empty()) { simulation_interval_ms_ = uplink_.senders()[0]->GetFeedbackIntervalMs(); } else if (!downlink_.senders().empty()) { simulation_interval_ms_ = downlink_.senders()[0]->GetFeedbackIntervalMs(); } assert(simulation_interval_ms_ > 0); if (time_now_ms_ == -1) { time_now_ms_ = simulation_interval_ms_; } for (run_time_ms_ += time_ms; time_now_ms_ <= run_time_ms_ - simulation_interval_ms_; time_now_ms_ += simulation_interval_ms_) { // Packets are first generated on the first link, passed through all the // PacketProcessors and PacketReceivers. The PacketReceivers produces // FeedbackPackets which are then processed by the next link, where they // at some point will be consumed by a PacketSender. for (Link* link : links_) link->Run(simulation_interval_ms_, time_now_ms_, &packets_); } } string BweTest::GetTestName() const { const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); return string(test_info->name()); } void BweTest::PrintResults( double max_throughput_kbps, Stats<double> throughput_kbps, Stats<double> delay_ms, std::vector<Stats<double>> flow_throughput_kbps) { double utilization = throughput_kbps.GetMean() / max_throughput_kbps; webrtc::test::PrintResult("BwePerformance", GetTestName(), "Utilization", utilization * 100.0, "%", false); std::stringstream ss; ss << throughput_kbps.GetStdDev() / throughput_kbps.GetMean(); webrtc::test::PrintResult("BwePerformance", GetTestName(), "Utilization var coeff", ss.str(), "", false); webrtc::test::PrintResult("BwePerformance", GetTestName(), "Average delay", delay_ms.AsString(), "ms", false); double fairness_index = 0.0; double squared_bitrate_sum = 0.0; for (Stats<double> flow : flow_throughput_kbps) { squared_bitrate_sum += flow.GetMean() * flow.GetMean(); fairness_index += flow.GetMean(); } fairness_index *= fairness_index; fairness_index /= flow_throughput_kbps.size() * squared_bitrate_sum; webrtc::test::PrintResult("BwePerformance", GetTestName(), "Fairness", fairness_index * 100, "%", false); } void BweTest::RunFairnessTest(BandwidthEstimatorType bwe_type, size_t num_media_flows, size_t num_tcp_flows, int capacity_kbps) { std::set<int> all_flow_ids; std::set<int> media_flow_ids; std::set<int> tcp_flow_ids; int next_flow_id = 0; for (size_t i = 0; i < num_media_flows; ++i) { media_flow_ids.insert(next_flow_id); all_flow_ids.insert(next_flow_id); ++next_flow_id; } for (size_t i = 0; i < num_tcp_flows; ++i) { tcp_flow_ids.insert(next_flow_id); all_flow_ids.insert(next_flow_id); ++next_flow_id; } std::vector<VideoSource*> sources; std::vector<PacketSender*> senders; size_t i = 0; for (int media_flow : media_flow_ids) { // Streams started 20 seconds apart to give them different advantage when // competing for the bandwidth. sources.push_back(new AdaptiveVideoSource(media_flow, 30, 300, 0, i++ * (rand() % 40000))); senders.push_back(new PacedVideoSender(&uplink_, sources.back(), bwe_type)); } for (int tcp_flow : tcp_flow_ids) senders.push_back(new TcpSender(&uplink_, tcp_flow)); ChokeFilter choke(&uplink_, all_flow_ids); choke.SetCapacity(capacity_kbps); choke.SetMaxDelay(1000); std::vector<RateCounterFilter*> rate_counters; for (int flow : all_flow_ids) { rate_counters.push_back( new RateCounterFilter(&uplink_, flow, "receiver_input")); } RateCounterFilter total_utilization(&uplink_, all_flow_ids, "total_utilization"); std::vector<PacketReceiver*> receivers; i = 0; for (int media_flow : media_flow_ids) { receivers.push_back( new PacketReceiver(&uplink_, media_flow, bwe_type, i++ == 0, false)); } for (int tcp_flow : tcp_flow_ids) { receivers.push_back( new PacketReceiver(&uplink_, tcp_flow, kTcpEstimator, false, false)); } RunFor(15 * 60 * 1000); std::vector<Stats<double>> flow_throughput_kbps; for (i = 0; i < all_flow_ids.size(); ++i) flow_throughput_kbps.push_back(rate_counters[i]->GetBitrateStats()); PrintResults(capacity_kbps, total_utilization.GetBitrateStats(), choke.GetDelayStats(), flow_throughput_kbps); for (VideoSource* source : sources) delete source; for (PacketSender* sender : senders) delete sender; for (RateCounterFilter* rate_counter : rate_counters) delete rate_counter; for (PacketReceiver* receiver : receivers) delete receiver; } } // namespace bwe } // namespace testing } // namespace webrtc <commit_msg>Fix broken perf prints.<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/remote_bitrate_estimator/test/bwe_test.h" #include "webrtc/base/common.h" #include "webrtc/base/scoped_ptr.h" #include "webrtc/modules/interface/module_common_types.h" #include "webrtc/modules/remote_bitrate_estimator/test/bwe_test_framework.h" #include "webrtc/modules/remote_bitrate_estimator/test/packet_receiver.h" #include "webrtc/modules/remote_bitrate_estimator/test/packet_sender.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/test/testsupport/perf_test.h" using std::string; using std::vector; namespace webrtc { namespace testing { namespace bwe { PacketProcessorRunner::PacketProcessorRunner(PacketProcessor* processor) : processor_(processor) { } PacketProcessorRunner::~PacketProcessorRunner() { for (Packet* packet : queue_) delete packet; } bool PacketProcessorRunner::RunsProcessor( const PacketProcessor* processor) const { return processor == processor_; } void PacketProcessorRunner::RunFor(int64_t time_ms, int64_t time_now_ms, Packets* in_out) { Packets to_process; FindPacketsToProcess(processor_->flow_ids(), in_out, &to_process); processor_->RunFor(time_ms, &to_process); QueuePackets(&to_process, time_now_ms * 1000); if (!to_process.empty()) { processor_->Plot((to_process.back()->send_time_us() + 500) / 1000); } in_out->merge(to_process, DereferencingComparator<Packet>); } void PacketProcessorRunner::FindPacketsToProcess(const FlowIds& flow_ids, Packets* in, Packets* out) { assert(out->empty()); for (Packets::iterator it = in->begin(); it != in->end();) { // TODO(holmer): Further optimize this by looking for consecutive flow ids // in the packet list and only doing the binary search + splice once for a // sequence. if (flow_ids.find((*it)->flow_id()) != flow_ids.end()) { Packets::iterator next = it; ++next; out->splice(out->end(), *in, it); it = next; } else { ++it; } } } void PacketProcessorRunner::QueuePackets(Packets* batch, int64_t end_of_batch_time_us) { queue_.merge(*batch, DereferencingComparator<Packet>); if (queue_.empty()) { return; } Packets::iterator it = queue_.begin(); for (; it != queue_.end(); ++it) { if ((*it)->send_time_us() > end_of_batch_time_us) { break; } } Packets to_transfer; to_transfer.splice(to_transfer.begin(), queue_, queue_.begin(), it); batch->merge(to_transfer, DereferencingComparator<Packet>); } BweTest::BweTest() : run_time_ms_(0), time_now_ms_(-1), simulation_interval_ms_(-1) { links_.push_back(&uplink_); links_.push_back(&downlink_); } BweTest::~BweTest() { for (Packet* packet : packets_) delete packet; } void BweTest::SetUp() { const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); string test_name = string(test_info->test_case_name()) + "_" + string(test_info->name()); BWE_TEST_LOGGING_GLOBAL_CONTEXT(test_name); BWE_TEST_LOGGING_GLOBAL_ENABLE(false); } void Link::AddPacketProcessor(PacketProcessor* processor, ProcessorType processor_type) { assert(processor); switch (processor_type) { case kSender: senders_.push_back(static_cast<PacketSender*>(processor)); break; case kReceiver: receivers_.push_back(static_cast<PacketReceiver*>(processor)); break; case kRegular: break; } processors_.push_back(PacketProcessorRunner(processor)); } void Link::RemovePacketProcessor(PacketProcessor* processor) { for (vector<PacketProcessorRunner>::iterator it = processors_.begin(); it != processors_.end(); ++it) { if (it->RunsProcessor(processor)) { processors_.erase(it); return; } } assert(false); } // Ownership of the created packets is handed over to the caller. void Link::Run(int64_t run_for_ms, int64_t now_ms, Packets* packets) { for (auto& processor : processors_) { processor.RunFor(run_for_ms, now_ms, packets); } } void BweTest::VerboseLogging(bool enable) { BWE_TEST_LOGGING_GLOBAL_ENABLE(enable); } void BweTest::RunFor(int64_t time_ms) { // Set simulation interval from first packet sender. // TODO(holmer): Support different feedback intervals for different flows. if (!uplink_.senders().empty()) { simulation_interval_ms_ = uplink_.senders()[0]->GetFeedbackIntervalMs(); } else if (!downlink_.senders().empty()) { simulation_interval_ms_ = downlink_.senders()[0]->GetFeedbackIntervalMs(); } assert(simulation_interval_ms_ > 0); if (time_now_ms_ == -1) { time_now_ms_ = simulation_interval_ms_; } for (run_time_ms_ += time_ms; time_now_ms_ <= run_time_ms_ - simulation_interval_ms_; time_now_ms_ += simulation_interval_ms_) { // Packets are first generated on the first link, passed through all the // PacketProcessors and PacketReceivers. The PacketReceivers produces // FeedbackPackets which are then processed by the next link, where they // at some point will be consumed by a PacketSender. for (Link* link : links_) link->Run(simulation_interval_ms_, time_now_ms_, &packets_); } } string BweTest::GetTestName() const { const ::testing::TestInfo* const test_info = ::testing::UnitTest::GetInstance()->current_test_info(); return string(test_info->name()); } void BweTest::PrintResults( double max_throughput_kbps, Stats<double> throughput_kbps, Stats<double> delay_ms, std::vector<Stats<double>> flow_throughput_kbps) { double utilization = throughput_kbps.GetMean() / max_throughput_kbps; webrtc::test::PrintResult("BwePerformance", GetTestName(), "Utilization", utilization * 100.0, "%", false); std::stringstream ss; ss << throughput_kbps.GetStdDev() / throughput_kbps.GetMean(); webrtc::test::PrintResult("BwePerformance", GetTestName(), "Utilization var coeff", ss.str(), "", false); webrtc::test::PrintResultMeanAndError("BwePerformance", GetTestName(), "Average delay", delay_ms.AsString(), "ms", false); double fairness_index = 0.0; double squared_bitrate_sum = 0.0; for (Stats<double> flow : flow_throughput_kbps) { squared_bitrate_sum += flow.GetMean() * flow.GetMean(); fairness_index += flow.GetMean(); } fairness_index *= fairness_index; fairness_index /= flow_throughput_kbps.size() * squared_bitrate_sum; webrtc::test::PrintResult("BwePerformance", GetTestName(), "Fairness", fairness_index * 100, "%", false); } void BweTest::RunFairnessTest(BandwidthEstimatorType bwe_type, size_t num_media_flows, size_t num_tcp_flows, int capacity_kbps) { std::set<int> all_flow_ids; std::set<int> media_flow_ids; std::set<int> tcp_flow_ids; int next_flow_id = 0; for (size_t i = 0; i < num_media_flows; ++i) { media_flow_ids.insert(next_flow_id); all_flow_ids.insert(next_flow_id); ++next_flow_id; } for (size_t i = 0; i < num_tcp_flows; ++i) { tcp_flow_ids.insert(next_flow_id); all_flow_ids.insert(next_flow_id); ++next_flow_id; } std::vector<VideoSource*> sources; std::vector<PacketSender*> senders; size_t i = 0; for (int media_flow : media_flow_ids) { // Streams started 20 seconds apart to give them different advantage when // competing for the bandwidth. sources.push_back(new AdaptiveVideoSource(media_flow, 30, 300, 0, i++ * (rand() % 40000))); senders.push_back(new PacedVideoSender(&uplink_, sources.back(), bwe_type)); } for (int tcp_flow : tcp_flow_ids) senders.push_back(new TcpSender(&uplink_, tcp_flow)); ChokeFilter choke(&uplink_, all_flow_ids); choke.SetCapacity(capacity_kbps); choke.SetMaxDelay(1000); std::vector<RateCounterFilter*> rate_counters; for (int flow : all_flow_ids) { rate_counters.push_back( new RateCounterFilter(&uplink_, flow, "receiver_input")); } RateCounterFilter total_utilization(&uplink_, all_flow_ids, "total_utilization"); std::vector<PacketReceiver*> receivers; i = 0; for (int media_flow : media_flow_ids) { receivers.push_back( new PacketReceiver(&uplink_, media_flow, bwe_type, i++ == 0, false)); } for (int tcp_flow : tcp_flow_ids) { receivers.push_back( new PacketReceiver(&uplink_, tcp_flow, kTcpEstimator, false, false)); } RunFor(15 * 60 * 1000); std::vector<Stats<double>> flow_throughput_kbps; for (i = 0; i < all_flow_ids.size(); ++i) flow_throughput_kbps.push_back(rate_counters[i]->GetBitrateStats()); PrintResults(capacity_kbps, total_utilization.GetBitrateStats(), choke.GetDelayStats(), flow_throughput_kbps); for (VideoSource* source : sources) delete source; for (PacketSender* sender : senders) delete sender; for (RateCounterFilter* rate_counter : rate_counters) delete rate_counter; for (PacketReceiver* receiver : receivers) delete receiver; } } // namespace bwe } // namespace testing } // namespace webrtc <|endoftext|>
<commit_before>#pragma once #include <experimental/optional> #include <functional> #include <memory> #include "base/not_null.hpp" #include "geometry/affine_map.hpp" #include "geometry/named_quantities.hpp" #include "geometry/orthogonal_map.hpp" #include "geometry/rotation.hpp" #include "ksp_plugin/celestial.hpp" #include "ksp_plugin/frames.hpp" #include "ksp_plugin/vessel.hpp" #include "physics/discrete_trajectory.hpp" #include "physics/dynamic_frame.hpp" #include "physics/ephemeris.hpp" #include "physics/rigid_motion.hpp" #include "quantities/quantities.hpp" namespace principia { namespace ksp_plugin { namespace internal_renderer { using base::not_null; using geometry::AffineMap; using geometry::Instant; using geometry::OrthogonalMap; using geometry::Position; using geometry::RigidTransformation; using geometry::Rotation; using physics::DiscreteTrajectory; using physics::Ephemeris; using physics::Frenet; using physics::RigidMotion; using quantities::Length; class Renderer { public: Renderer(not_null<Celestial const*> sun, not_null<std::unique_ptr<NavigationFrame>> plotting_frame); virtual ~Renderer() = default; // Changes the plotting frame of the renderer. virtual void SetPlottingFrame( not_null<std::unique_ptr<NavigationFrame>> plotting_frame); // Returns the current plotting frame. This may not be the last set by // |SetPlottingFrame| if it is overridden by a target vessel. virtual not_null<NavigationFrame const*> GetPlottingFrame() const; // Overrides the current plotting frame with one that is centred on the given // |vessel|. virtual void SetTargetVessel( not_null<Vessel*> vessel, not_null<Celestial const*> celestial, not_null<Ephemeris<Barycentric> const*> ephemeris); // Reverts to frame last set by |SetPlottingFrame|. The second version only // has an effect if the given |vessel| is the current target vessel. virtual void ClearTargetVessel(); virtual void ClearTargetVesselIf(not_null<Vessel*> vessel); // Determines if there is a target vessel and returns it. virtual bool HasTargetVessel() const; virtual Vessel& GetTargetVessel(); virtual Vessel const& GetTargetVessel() const; // If there is a target vessel, returns its prediction after extending it up // to |time|. virtual DiscreteTrajectory<Barycentric> const& GetTargetVesselPrediction( Instant const& time) const; // Returns a trajectory in |World| corresponding to the trajectory defined by // |begin| and |end|, as seen in the current plotting frame. In this function // and others in this class, |sun_world_position| is the current position of // the sun in |World| space as returned by |Planetarium.fetch.Sun.position|; // it is used to define the relation between |WorldSun| and |World|. virtual not_null<std::unique_ptr<DiscreteTrajectory<World>>> RenderBarycentricTrajectoryInWorld( Instant const& time, DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end, Position<World> const& sun_world_position, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; // Returns a trajectory in the current plotting frame corresponding to the // trajectory defined by |begin| and |end|. If there is a target vessel, its // prediction must not be empty. virtual not_null<std::unique_ptr<DiscreteTrajectory<Navigation>>> RenderBarycentricTrajectoryInPlotting( DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end) const; // Returns a trajectory in |World| corresponding to the trajectory defined by // |begin| and |end| in the current plotting frame. virtual not_null<std::unique_ptr<DiscreteTrajectory<World>>> RenderPlottingTrajectoryInWorld( Instant const& time, DiscreteTrajectory<Navigation>::Iterator const& begin, DiscreteTrajectory<Navigation>::Iterator const& end, Position<World> const& sun_world_position, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; // Coordinate transforms. virtual RigidMotion<Barycentric, Navigation> BarycentricToPlotting( Instant const& time) const; virtual RigidTransformation<Barycentric, World> BarycentricToWorld( Instant const& time, Position<World> const& sun_world_position, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual OrthogonalMap<Barycentric, World> BarycentricToWorld( Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual OrthogonalMap<Barycentric, WorldSun> BarycentricToWorldSun( Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; // Converts from the Frenet frame of the manœuvre's initial time in the // plotted frame to the |World| coordinates. virtual OrthogonalMap<Frenet<Navigation>, World> FrenetToWorld( Instant const& time, NavigationManœuvre const& manœuvre, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; // Converts from the Frenet frame of the vessel's free-falling trajectory in // the plotted frame to the |World| coordinates. virtual OrthogonalMap<Frenet<Navigation>, World> FrenetToWorld( Vessel const& vessel, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; // Converts from the Frenet frame of the vessel's free-falling trajectory in // the given |navigation_frame| to the |World| coordinates. virtual OrthogonalMap<Frenet<Navigation>, World> FrenetToWorld( Vessel const& vessel, NavigationFrame const& navigation_frame, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual OrthogonalMap<Navigation, Barycentric> PlottingToBarycentric( Instant const& time) const; virtual RigidTransformation<Navigation, World> PlottingToWorld( Instant const& time, Position<World> const& sun_world_position, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual OrthogonalMap<Navigation, World> PlottingToWorld( Instant const& time, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual RigidTransformation<World, Barycentric> WorldToBarycentric( Instant const& time, Position<World> const& sun_world_position, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual OrthogonalMap<World, Barycentric> WorldToBarycentric( Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual RigidTransformation<World, Navigation> WorldToPlotting( Instant const& time, Position<World> const& sun_world_position, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual void WriteToMessage(not_null<serialization::Renderer*> message) const; static not_null<std::unique_ptr<Renderer>> ReadFromMessage( serialization::Renderer const& message, not_null<Celestial const*> sun, not_null<Ephemeris<Barycentric> const*> ephemeris); private: struct Target { Target(not_null<Vessel*> vessel, not_null<Celestial const*> celestial, not_null<Ephemeris<Barycentric> const*> ephemeris); not_null<Vessel*> const vessel; not_null<Celestial const*> const celestial; not_null<std::unique_ptr<NavigationFrame>> const target_frame; }; // Returns a plotting frame suitable for evaluation at |time|, possibly by // extending the prediction if there is a target vessel. not_null<NavigationFrame const*> GetPlottingFrame(Instant const& time) const; not_null<Celestial const*> const sun_; not_null<std::unique_ptr<NavigationFrame>> plotting_frame_; std::experimental::optional<Target> target_; }; } // namespace internal_renderer using internal_renderer::Renderer; } // namespace ksp_plugin } // namespace principia <commit_msg>Remove blank at end of line.<commit_after>#pragma once #include <experimental/optional> #include <functional> #include <memory> #include "base/not_null.hpp" #include "geometry/affine_map.hpp" #include "geometry/named_quantities.hpp" #include "geometry/orthogonal_map.hpp" #include "geometry/rotation.hpp" #include "ksp_plugin/celestial.hpp" #include "ksp_plugin/frames.hpp" #include "ksp_plugin/vessel.hpp" #include "physics/discrete_trajectory.hpp" #include "physics/dynamic_frame.hpp" #include "physics/ephemeris.hpp" #include "physics/rigid_motion.hpp" #include "quantities/quantities.hpp" namespace principia { namespace ksp_plugin { namespace internal_renderer { using base::not_null; using geometry::AffineMap; using geometry::Instant; using geometry::OrthogonalMap; using geometry::Position; using geometry::RigidTransformation; using geometry::Rotation; using physics::DiscreteTrajectory; using physics::Ephemeris; using physics::Frenet; using physics::RigidMotion; using quantities::Length; class Renderer { public: Renderer(not_null<Celestial const*> sun, not_null<std::unique_ptr<NavigationFrame>> plotting_frame); virtual ~Renderer() = default; // Changes the plotting frame of the renderer. virtual void SetPlottingFrame( not_null<std::unique_ptr<NavigationFrame>> plotting_frame); // Returns the current plotting frame. This may not be the last set by // |SetPlottingFrame| if it is overridden by a target vessel. virtual not_null<NavigationFrame const*> GetPlottingFrame() const; // Overrides the current plotting frame with one that is centred on the given // |vessel|. virtual void SetTargetVessel( not_null<Vessel*> vessel, not_null<Celestial const*> celestial, not_null<Ephemeris<Barycentric> const*> ephemeris); // Reverts to frame last set by |SetPlottingFrame|. The second version only // has an effect if the given |vessel| is the current target vessel. virtual void ClearTargetVessel(); virtual void ClearTargetVesselIf(not_null<Vessel*> vessel); // Determines if there is a target vessel and returns it. virtual bool HasTargetVessel() const; virtual Vessel& GetTargetVessel(); virtual Vessel const& GetTargetVessel() const; // If there is a target vessel, returns its prediction after extending it up // to |time|. virtual DiscreteTrajectory<Barycentric> const& GetTargetVesselPrediction( Instant const& time) const; // Returns a trajectory in |World| corresponding to the trajectory defined by // |begin| and |end|, as seen in the current plotting frame. In this function // and others in this class, |sun_world_position| is the current position of // the sun in |World| space as returned by |Planetarium.fetch.Sun.position|; // it is used to define the relation between |WorldSun| and |World|. virtual not_null<std::unique_ptr<DiscreteTrajectory<World>>> RenderBarycentricTrajectoryInWorld( Instant const& time, DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end, Position<World> const& sun_world_position, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; // Returns a trajectory in the current plotting frame corresponding to the // trajectory defined by |begin| and |end|. If there is a target vessel, its // prediction must not be empty. virtual not_null<std::unique_ptr<DiscreteTrajectory<Navigation>>> RenderBarycentricTrajectoryInPlotting( DiscreteTrajectory<Barycentric>::Iterator const& begin, DiscreteTrajectory<Barycentric>::Iterator const& end) const; // Returns a trajectory in |World| corresponding to the trajectory defined by // |begin| and |end| in the current plotting frame. virtual not_null<std::unique_ptr<DiscreteTrajectory<World>>> RenderPlottingTrajectoryInWorld( Instant const& time, DiscreteTrajectory<Navigation>::Iterator const& begin, DiscreteTrajectory<Navigation>::Iterator const& end, Position<World> const& sun_world_position, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; // Coordinate transforms. virtual RigidMotion<Barycentric, Navigation> BarycentricToPlotting( Instant const& time) const; virtual RigidTransformation<Barycentric, World> BarycentricToWorld( Instant const& time, Position<World> const& sun_world_position, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual OrthogonalMap<Barycentric, World> BarycentricToWorld( Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual OrthogonalMap<Barycentric, WorldSun> BarycentricToWorldSun( Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; // Converts from the Frenet frame of the manœuvre's initial time in the // plotted frame to the |World| coordinates. virtual OrthogonalMap<Frenet<Navigation>, World> FrenetToWorld( Instant const& time, NavigationManœuvre const& manœuvre, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; // Converts from the Frenet frame of the vessel's free-falling trajectory in // the plotted frame to the |World| coordinates. virtual OrthogonalMap<Frenet<Navigation>, World> FrenetToWorld( Vessel const& vessel, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; // Converts from the Frenet frame of the vessel's free-falling trajectory in // the given |navigation_frame| to the |World| coordinates. virtual OrthogonalMap<Frenet<Navigation>, World> FrenetToWorld( Vessel const& vessel, NavigationFrame const& navigation_frame, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual OrthogonalMap<Navigation, Barycentric> PlottingToBarycentric( Instant const& time) const; virtual RigidTransformation<Navigation, World> PlottingToWorld( Instant const& time, Position<World> const& sun_world_position, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual OrthogonalMap<Navigation, World> PlottingToWorld( Instant const& time, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual RigidTransformation<World, Barycentric> WorldToBarycentric( Instant const& time, Position<World> const& sun_world_position, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual OrthogonalMap<World, Barycentric> WorldToBarycentric( Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual RigidTransformation<World, Navigation> WorldToPlotting( Instant const& time, Position<World> const& sun_world_position, Rotation<Barycentric, AliceSun> const& planetarium_rotation) const; virtual void WriteToMessage(not_null<serialization::Renderer*> message) const; static not_null<std::unique_ptr<Renderer>> ReadFromMessage( serialization::Renderer const& message, not_null<Celestial const*> sun, not_null<Ephemeris<Barycentric> const*> ephemeris); private: struct Target { Target(not_null<Vessel*> vessel, not_null<Celestial const*> celestial, not_null<Ephemeris<Barycentric> const*> ephemeris); not_null<Vessel*> const vessel; not_null<Celestial const*> const celestial; not_null<std::unique_ptr<NavigationFrame>> const target_frame; }; // Returns a plotting frame suitable for evaluation at |time|, possibly by // extending the prediction if there is a target vessel. not_null<NavigationFrame const*> GetPlottingFrame(Instant const& time) const; not_null<Celestial const*> const sun_; not_null<std::unique_ptr<NavigationFrame>> plotting_frame_; std::experimental::optional<Target> target_; }; } // namespace internal_renderer using internal_renderer::Renderer; } // namespace ksp_plugin } // namespace principia <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "FVMatAdvectionOutflowBC.h" registerADMooseObject("MooseApp", FVMatAdvectionOutflowBC); InputParameters FVMatAdvectionOutflowBC::validParams() { InputParameters params = FVFluxBC::validParams(); params.addRequiredParam<MaterialPropertyName>("vel", "advection velocity"); params.addParam<MaterialPropertyName>( "advected_quantity", "An optional parameter for specifying an advected quantity from a material property. If this " "is not specified, then the advected quantity will simply be the variable that this object " "is acting on"); params.addClassDescription( "Outflow boundary condition taking the advected quantity from a material property"); MooseEnum advected_interp_method("average upwind", "upwind"); params.addParam<MooseEnum>("advected_interp_method", advected_interp_method, "The interpolation to use for the advected quantity. Options are " "'upwind' and 'average', with the default being 'upwind'."); return params; } FVMatAdvectionOutflowBC::FVMatAdvectionOutflowBC(const InputParameters & params) : FVFluxBC(params), _vel_elem(getADMaterialProperty<RealVectorValue>("vel")), _vel_neighbor(getNeighborADMaterialProperty<RealVectorValue>("vel")), _adv_quant_elem(isParamValid("advected_quantity") ? getADMaterialProperty<Real>("advected_quantity").get() : _u), _adv_quant_neighbor(isParamValid("advected_quantity") ? getNeighborADMaterialProperty<Real>("advected_quantity").get() : _u_neighbor) { using namespace Moose::FV; const auto & advected_interp_method = getParam<MooseEnum>("advected_interp_method"); if (advected_interp_method == "average") _advected_interp_method = InterpMethod::Average; else if (advected_interp_method == "upwind") _advected_interp_method = InterpMethod::Upwind; else mooseError("Unrecognized interpolation type ", static_cast<std::string>(advected_interp_method)); } ADReal FVMatAdvectionOutflowBC::computeQpResidual() { ADRealVectorValue v; ADReal adv_quant_boundary; using namespace Moose::FV; // Currently only Average is supported for the velocity interpolate(InterpMethod::Average, v, _vel_elem[_qp], _vel_neighbor[_qp], *_face_info, true); interpolate(_advected_interp_method, adv_quant_boundary, _adv_quant_elem[_qp], _adv_quant_neighbor[_qp], v, *_face_info, true); mooseAssert(_normal * v >= 0, "This boundary condition is for outflow but the flow is in the opposite direction of " "the boundary normal"); return _normal * v * adv_quant_boundary; } <commit_msg>Remove outflow assertion in FVMatAdvectionOutflowBC<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "FVMatAdvectionOutflowBC.h" registerADMooseObject("MooseApp", FVMatAdvectionOutflowBC); InputParameters FVMatAdvectionOutflowBC::validParams() { InputParameters params = FVFluxBC::validParams(); params.addRequiredParam<MaterialPropertyName>("vel", "advection velocity"); params.addParam<MaterialPropertyName>( "advected_quantity", "An optional parameter for specifying an advected quantity from a material property. If this " "is not specified, then the advected quantity will simply be the variable that this object " "is acting on"); params.addClassDescription( "Outflow boundary condition taking the advected quantity from a material property"); MooseEnum advected_interp_method("average upwind", "upwind"); params.addParam<MooseEnum>("advected_interp_method", advected_interp_method, "The interpolation to use for the advected quantity. Options are " "'upwind' and 'average', with the default being 'upwind'."); return params; } FVMatAdvectionOutflowBC::FVMatAdvectionOutflowBC(const InputParameters & params) : FVFluxBC(params), _vel_elem(getADMaterialProperty<RealVectorValue>("vel")), _vel_neighbor(getNeighborADMaterialProperty<RealVectorValue>("vel")), _adv_quant_elem(isParamValid("advected_quantity") ? getADMaterialProperty<Real>("advected_quantity").get() : _u), _adv_quant_neighbor(isParamValid("advected_quantity") ? getNeighborADMaterialProperty<Real>("advected_quantity").get() : _u_neighbor) { using namespace Moose::FV; const auto & advected_interp_method = getParam<MooseEnum>("advected_interp_method"); if (advected_interp_method == "average") _advected_interp_method = InterpMethod::Average; else if (advected_interp_method == "upwind") _advected_interp_method = InterpMethod::Upwind; else mooseError("Unrecognized interpolation type ", static_cast<std::string>(advected_interp_method)); } ADReal FVMatAdvectionOutflowBC::computeQpResidual() { ADRealVectorValue v; ADReal adv_quant_boundary; using namespace Moose::FV; // Currently only Average is supported for the velocity interpolate(InterpMethod::Average, v, _vel_elem[_qp], _vel_neighbor[_qp], *_face_info, true); interpolate(_advected_interp_method, adv_quant_boundary, _adv_quant_elem[_qp], _adv_quant_neighbor[_qp], v, *_face_info, true); return _normal * v * adv_quant_boundary; } <|endoftext|>
<commit_before>#include "compression.hh" #include "tarfile.hh" #include "util.hh" #include "finally.hh" #include "logging.hh" #include <archive.h> #include <archive_entry.h> #include <cstdio> #include <cstring> #include <brotli/decode.h> #include <brotli/encode.h> #include <zlib.h> #include <iostream> namespace nix { // Don't feed brotli too much at once. struct ChunkedCompressionSink : CompressionSink { uint8_t outbuf[32 * 1024]; void write(std::string_view data) override { const size_t CHUNK_SIZE = sizeof(outbuf) << 2; while (!data.empty()) { size_t n = std::min(CHUNK_SIZE, data.size()); writeInternal(data); data.remove_prefix(n); } } virtual void writeInternal(std::string_view data) = 0; }; struct ArchiveDecompressionSource : Source { std::unique_ptr<TarArchive> archive = 0; Source & src; ArchiveDecompressionSource(Source & src) : src(src) {} ~ArchiveDecompressionSource() override {} size_t read(char * data, size_t len) override { struct archive_entry * ae; if (!archive) { archive = std::make_unique<TarArchive>(src, true); this->archive->check(archive_read_next_header(this->archive->archive, &ae), "failed to read header (%s)"); if (archive_filter_count(this->archive->archive) < 2) { throw CompressionError("input compression not recognized"); } } ssize_t result = archive_read_data(this->archive->archive, data, len); if (result > 0) return result; if (result == 0) { throw EndOfFile("reached end of compressed file"); } this->archive->check(result, "failed to read compressed data (%s)"); return result; } }; struct ArchiveCompressionSink : CompressionSink { Sink & nextSink; struct archive * archive; ArchiveCompressionSink(Sink & nextSink, std::string format, bool parallel) : nextSink(nextSink) { archive = archive_write_new(); if (!archive) throw Error("failed to initialize libarchive"); check(archive_write_add_filter_by_name(archive, format.c_str()), "couldn't initialize compression (%s)"); check(archive_write_set_format_raw(archive)); if (format == "xz" && parallel) { check(archive_write_set_filter_option(archive, format.c_str(), "threads", "0")); } // disable internal buffering check(archive_write_set_bytes_per_block(archive, 0)); // disable output padding check(archive_write_set_bytes_in_last_block(archive, 1)); open(); } ~ArchiveCompressionSink() override { if (archive) archive_write_free(archive); } void finish() override { flush(); check(archive_write_close(archive)); } void check(int err, const std::string & reason = "failed to compress (%s)") { if (err == ARCHIVE_EOF) throw EndOfFile("reached end of archive"); else if (err != ARCHIVE_OK) throw Error(reason, archive_error_string(this->archive)); } void write(std::string_view data) override { ssize_t result = archive_write_data(archive, data.data(), data.length()); if (result <= 0) check(result); } private: void open() { check(archive_write_open(archive, this, nullptr, ArchiveCompressionSink::callback_write, nullptr)); auto ae = archive_entry_new(); archive_entry_set_filetype(ae, AE_IFREG); check(archive_write_header(archive, ae)); archive_entry_free(ae); } static ssize_t callback_write(struct archive * archive, void * _self, const void * buffer, size_t length) { auto self = (ArchiveCompressionSink *) _self; self->nextSink({(const char *) buffer, length}); return length; } }; struct NoneSink : CompressionSink { Sink & nextSink; NoneSink(Sink & nextSink) : nextSink(nextSink) { } void finish() override { flush(); } void write(std::string_view data) override { nextSink(data); } }; struct BrotliDecompressionSink : ChunkedCompressionSink { Sink & nextSink; BrotliDecoderState * state; bool finished = false; BrotliDecompressionSink(Sink & nextSink) : nextSink(nextSink) { state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr); if (!state) throw CompressionError("unable to initialize brotli decoder"); } ~BrotliDecompressionSink() { BrotliDecoderDestroyInstance(state); } void finish() override { flush(); writeInternal({}); } void writeInternal(std::string_view data) override { auto next_in = (const uint8_t *) data.data(); size_t avail_in = data.size(); uint8_t * next_out = outbuf; size_t avail_out = sizeof(outbuf); while (!finished && (!data.data() || avail_in)) { checkInterrupt(); if (!BrotliDecoderDecompressStream(state, &avail_in, &next_in, &avail_out, &next_out, nullptr)) throw CompressionError("error while decompressing brotli file"); if (avail_out < sizeof(outbuf) || avail_in == 0) { nextSink({(char *) outbuf, sizeof(outbuf) - avail_out}); next_out = outbuf; avail_out = sizeof(outbuf); } finished = BrotliDecoderIsFinished(state); } } }; ref<std::string> decompress(const std::string & method, const std::string & in) { if (method == "br") { StringSink ssink; auto sink = makeDecompressionSink(method, ssink); (*sink)(in); sink->finish(); return ssink.s; } else { StringSource ssrc(in); auto src = makeDecompressionSource(ssrc); return make_ref<std::string>(src->drain()); } } std::unique_ptr<FinishSink> makeDecompressionSink(const std::string & method, Sink & nextSink) { if (method == "none" || method == "") return std::make_unique<NoneSink>(nextSink); else if (method == "br") return std::make_unique<BrotliDecompressionSink>(nextSink); else return sourceToSink([&](Source & source) { auto decompressionSource = makeDecompressionSource(source); decompressionSource->drainInto(nextSink); }); } struct BrotliCompressionSink : ChunkedCompressionSink { Sink & nextSink; uint8_t outbuf[BUFSIZ]; BrotliEncoderState * state; bool finished = false; BrotliCompressionSink(Sink & nextSink) : nextSink(nextSink) { state = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr); if (!state) throw CompressionError("unable to initialise brotli encoder"); } ~BrotliCompressionSink() { BrotliEncoderDestroyInstance(state); } void finish() override { flush(); writeInternal({}); } void writeInternal(std::string_view data) override { auto next_in = (const uint8_t *) data.data(); size_t avail_in = data.size(); uint8_t * next_out = outbuf; size_t avail_out = sizeof(outbuf); while (!finished && (!data.data() || avail_in)) { checkInterrupt(); if (!BrotliEncoderCompressStream(state, data.data() ? BROTLI_OPERATION_PROCESS : BROTLI_OPERATION_FINISH, &avail_in, &next_in, &avail_out, &next_out, nullptr)) throw CompressionError("error while compressing brotli compression"); if (avail_out < sizeof(outbuf) || avail_in == 0) { nextSink({(const char *) outbuf, sizeof(outbuf) - avail_out}); next_out = outbuf; avail_out = sizeof(outbuf); } finished = BrotliEncoderIsFinished(state); } } }; std::unique_ptr<Source> makeDecompressionSource(Source & prev) { return std::unique_ptr<Source>(new ArchiveDecompressionSource(prev)); } ref<CompressionSink> makeCompressionSink(const std::string & method, Sink & nextSink, const bool parallel) { std::vector<std::string> la_supports = { "bzip2", "compress", "grzip", "gzip", "lrzip", "lz4", "lzip", "lzma", "lzop", "xz", "zstd" }; if (std::find(la_supports.begin(), la_supports.end(), method) != la_supports.end()) { return make_ref<ArchiveCompressionSink>(nextSink, method, parallel); } if (method == "none") return make_ref<NoneSink>(nextSink); else if (method == "br") return make_ref<BrotliCompressionSink>(nextSink); else throw UnknownCompressionMethod("unknown compression method '%s'", method); } ref<std::string> compress(const std::string & method, const std::string & in, const bool parallel) { StringSink ssink; auto sink = makeCompressionSink(method, ssink, parallel); (*sink)(in); sink->finish(); return ssink.s; } } <commit_msg>Fix brotli compression of files > 128 KiB<commit_after>#include "compression.hh" #include "tarfile.hh" #include "util.hh" #include "finally.hh" #include "logging.hh" #include <archive.h> #include <archive_entry.h> #include <cstdio> #include <cstring> #include <brotli/decode.h> #include <brotli/encode.h> #include <zlib.h> #include <iostream> namespace nix { // Don't feed brotli too much at once. struct ChunkedCompressionSink : CompressionSink { uint8_t outbuf[32 * 1024]; void write(std::string_view data) override { const size_t CHUNK_SIZE = sizeof(outbuf) << 2; while (!data.empty()) { size_t n = std::min(CHUNK_SIZE, data.size()); writeInternal(data.substr(0, n)); data.remove_prefix(n); } } virtual void writeInternal(std::string_view data) = 0; }; struct ArchiveDecompressionSource : Source { std::unique_ptr<TarArchive> archive = 0; Source & src; ArchiveDecompressionSource(Source & src) : src(src) {} ~ArchiveDecompressionSource() override {} size_t read(char * data, size_t len) override { struct archive_entry * ae; if (!archive) { archive = std::make_unique<TarArchive>(src, true); this->archive->check(archive_read_next_header(this->archive->archive, &ae), "failed to read header (%s)"); if (archive_filter_count(this->archive->archive) < 2) { throw CompressionError("input compression not recognized"); } } ssize_t result = archive_read_data(this->archive->archive, data, len); if (result > 0) return result; if (result == 0) { throw EndOfFile("reached end of compressed file"); } this->archive->check(result, "failed to read compressed data (%s)"); return result; } }; struct ArchiveCompressionSink : CompressionSink { Sink & nextSink; struct archive * archive; ArchiveCompressionSink(Sink & nextSink, std::string format, bool parallel) : nextSink(nextSink) { archive = archive_write_new(); if (!archive) throw Error("failed to initialize libarchive"); check(archive_write_add_filter_by_name(archive, format.c_str()), "couldn't initialize compression (%s)"); check(archive_write_set_format_raw(archive)); if (format == "xz" && parallel) { check(archive_write_set_filter_option(archive, format.c_str(), "threads", "0")); } // disable internal buffering check(archive_write_set_bytes_per_block(archive, 0)); // disable output padding check(archive_write_set_bytes_in_last_block(archive, 1)); open(); } ~ArchiveCompressionSink() override { if (archive) archive_write_free(archive); } void finish() override { flush(); check(archive_write_close(archive)); } void check(int err, const std::string & reason = "failed to compress (%s)") { if (err == ARCHIVE_EOF) throw EndOfFile("reached end of archive"); else if (err != ARCHIVE_OK) throw Error(reason, archive_error_string(this->archive)); } void write(std::string_view data) override { ssize_t result = archive_write_data(archive, data.data(), data.length()); if (result <= 0) check(result); } private: void open() { check(archive_write_open(archive, this, nullptr, ArchiveCompressionSink::callback_write, nullptr)); auto ae = archive_entry_new(); archive_entry_set_filetype(ae, AE_IFREG); check(archive_write_header(archive, ae)); archive_entry_free(ae); } static ssize_t callback_write(struct archive * archive, void * _self, const void * buffer, size_t length) { auto self = (ArchiveCompressionSink *) _self; self->nextSink({(const char *) buffer, length}); return length; } }; struct NoneSink : CompressionSink { Sink & nextSink; NoneSink(Sink & nextSink) : nextSink(nextSink) { } void finish() override { flush(); } void write(std::string_view data) override { nextSink(data); } }; struct BrotliDecompressionSink : ChunkedCompressionSink { Sink & nextSink; BrotliDecoderState * state; bool finished = false; BrotliDecompressionSink(Sink & nextSink) : nextSink(nextSink) { state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr); if (!state) throw CompressionError("unable to initialize brotli decoder"); } ~BrotliDecompressionSink() { BrotliDecoderDestroyInstance(state); } void finish() override { flush(); writeInternal({}); } void writeInternal(std::string_view data) override { auto next_in = (const uint8_t *) data.data(); size_t avail_in = data.size(); uint8_t * next_out = outbuf; size_t avail_out = sizeof(outbuf); while (!finished && (!data.data() || avail_in)) { checkInterrupt(); if (!BrotliDecoderDecompressStream(state, &avail_in, &next_in, &avail_out, &next_out, nullptr)) throw CompressionError("error while decompressing brotli file"); if (avail_out < sizeof(outbuf) || avail_in == 0) { nextSink({(char *) outbuf, sizeof(outbuf) - avail_out}); next_out = outbuf; avail_out = sizeof(outbuf); } finished = BrotliDecoderIsFinished(state); } } }; ref<std::string> decompress(const std::string & method, const std::string & in) { if (method == "br") { StringSink ssink; auto sink = makeDecompressionSink(method, ssink); (*sink)(in); sink->finish(); return ssink.s; } else { StringSource ssrc(in); auto src = makeDecompressionSource(ssrc); return make_ref<std::string>(src->drain()); } } std::unique_ptr<FinishSink> makeDecompressionSink(const std::string & method, Sink & nextSink) { if (method == "none" || method == "") return std::make_unique<NoneSink>(nextSink); else if (method == "br") return std::make_unique<BrotliDecompressionSink>(nextSink); else return sourceToSink([&](Source & source) { auto decompressionSource = makeDecompressionSource(source); decompressionSource->drainInto(nextSink); }); } struct BrotliCompressionSink : ChunkedCompressionSink { Sink & nextSink; uint8_t outbuf[BUFSIZ]; BrotliEncoderState * state; bool finished = false; BrotliCompressionSink(Sink & nextSink) : nextSink(nextSink) { state = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr); if (!state) throw CompressionError("unable to initialise brotli encoder"); } ~BrotliCompressionSink() { BrotliEncoderDestroyInstance(state); } void finish() override { flush(); writeInternal({}); } void writeInternal(std::string_view data) override { auto next_in = (const uint8_t *) data.data(); size_t avail_in = data.size(); uint8_t * next_out = outbuf; size_t avail_out = sizeof(outbuf); while (!finished && (!data.data() || avail_in)) { checkInterrupt(); if (!BrotliEncoderCompressStream(state, data.data() ? BROTLI_OPERATION_PROCESS : BROTLI_OPERATION_FINISH, &avail_in, &next_in, &avail_out, &next_out, nullptr)) throw CompressionError("error while compressing brotli compression"); if (avail_out < sizeof(outbuf) || avail_in == 0) { nextSink({(const char *) outbuf, sizeof(outbuf) - avail_out}); next_out = outbuf; avail_out = sizeof(outbuf); } finished = BrotliEncoderIsFinished(state); } } }; std::unique_ptr<Source> makeDecompressionSource(Source & prev) { return std::unique_ptr<Source>(new ArchiveDecompressionSource(prev)); } ref<CompressionSink> makeCompressionSink(const std::string & method, Sink & nextSink, const bool parallel) { std::vector<std::string> la_supports = { "bzip2", "compress", "grzip", "gzip", "lrzip", "lz4", "lzip", "lzma", "lzop", "xz", "zstd" }; if (std::find(la_supports.begin(), la_supports.end(), method) != la_supports.end()) { return make_ref<ArchiveCompressionSink>(nextSink, method, parallel); } if (method == "none") return make_ref<NoneSink>(nextSink); else if (method == "br") return make_ref<BrotliCompressionSink>(nextSink); else throw UnknownCompressionMethod("unknown compression method '%s'", method); } ref<std::string> compress(const std::string & method, const std::string & in, const bool parallel) { StringSink ssink; auto sink = makeCompressionSink(method, ssink, parallel); (*sink)(in); sink->finish(); return ssink.s; } } <|endoftext|>
<commit_before>/* * Copyright 2014-2020 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <exception> #include <functional> #include <string> #include <gtest/gtest.h> #include "aeron_client_test_utils.h" extern "C" { #include "aeron_image.h" #include "concurrent/aeron_term_appender.h" } #define FILE_PAGE_SIZE (4 * 1024) #define SUB_URI "aeron:udp?endpoint=localhost:24567" #define STREAM_ID (101) #define SESSION_ID (110) #define REGISTRATION_ID (27) #define INITIAL_TERM_ID (1234) using namespace aeron::test; class ImageTest : public testing::Test { public: ImageTest() { } ~ImageTest() override { if (!m_filename.empty()) { aeron_log_buffer_delete(m_image->log_buffer); aeron_image_delete(m_image); ::unlink(m_filename.c_str()); } } int64_t createImage() { aeron_image_t *image = nullptr; aeron_log_buffer_t *log_buffer = nullptr; std::string filename = tempFileName(); createLogFile(filename); if (aeron_log_buffer_create(&log_buffer, filename.c_str(), m_correlationId, false) < 0) { throw std::runtime_error("could not create log_buffer: " + std::string(aeron_errmsg())); } if (aeron_image_create( &image, nullptr, log_buffer, &m_subscriber_position, m_correlationId, (int32_t)m_correlationId) < 0) { throw std::runtime_error("could not create image: " + std::string(aeron_errmsg())); } aeron_logbuffer_metadata_t *metadata = (aeron_logbuffer_metadata_t *)log_buffer->mapped_raw_log.log_meta_data.addr; m_image = image; m_filename = filename; m_term_length = metadata->term_length; m_initial_term_id = metadata->initial_term_id; m_position_bits_to_shift = (size_t)aeron_number_of_trailing_zeroes(metadata->term_length); return m_correlationId++; } void appendMessage(int64_t position, size_t length) { aeron_logbuffer_metadata_t *metadata = (aeron_logbuffer_metadata_t *)m_image->log_buffer->mapped_raw_log.log_meta_data.addr; const size_t index = aeron_logbuffer_index_by_position(position, m_position_bits_to_shift); uint8_t buffer[1024]; aeron_term_appender_append_unfragmented_message( &m_image->log_buffer->mapped_raw_log.term_buffers[index], &metadata->term_tail_counters[index], buffer, length, nullptr, nullptr, aeron_logbuffer_compute_term_id_from_position(position, m_position_bits_to_shift, m_initial_term_id), SESSION_ID, STREAM_ID); } static void fragment_handler( void *clientd, const uint8_t *buffer, size_t offset, size_t length, aeron_header_t *header) { auto image = reinterpret_cast<ImageTest *>(clientd); if (image->m_handler) { image->m_handler(buffer, offset, length, header); } } protected: int64_t m_correlationId = 0; int64_t m_subscriber_position = 0; int32_t m_term_length; int32_t m_initial_term_id; size_t m_position_bits_to_shift; std::function<void(const uint8_t *, size_t, size_t, aeron_header_t *)> m_handler = nullptr; aeron_image_t *m_image; std::string m_filename; }; TEST_F(ImageTest, shouldReadFirstMessage) { createImage(); appendMessage(0, 120); EXPECT_EQ(aeron_image_poll(m_image, fragment_handler, this, 1), 1); } <commit_msg>[C]: add some image_poll basic tests akin to TermRead Java test.<commit_after>/* * Copyright 2014-2020 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <exception> #include <functional> #include <string> #include <gtest/gtest.h> #include "aeron_client_test_utils.h" extern "C" { #include "aeron_image.h" #include "concurrent/aeron_term_appender.h" } #define FILE_PAGE_SIZE (4 * 1024) #define SUB_URI "aeron:udp?endpoint=localhost:24567" #define STREAM_ID (101) #define SESSION_ID (110) #define REGISTRATION_ID (27) #define INITIAL_TERM_ID (1234) using namespace aeron::test; class ImageTest : public testing::Test { public: ImageTest() { } ~ImageTest() override { if (!m_filename.empty()) { aeron_log_buffer_delete(m_image->log_buffer); aeron_image_delete(m_image); ::unlink(m_filename.c_str()); } } int64_t createImage() { aeron_image_t *image = nullptr; aeron_log_buffer_t *log_buffer = nullptr; std::string filename = tempFileName(); createLogFile(filename); if (aeron_log_buffer_create(&log_buffer, filename.c_str(), m_correlationId, false) < 0) { throw std::runtime_error("could not create log_buffer: " + std::string(aeron_errmsg())); } if (aeron_image_create( &image, nullptr, log_buffer, &m_subscriber_position, m_correlationId, (int32_t)m_correlationId) < 0) { throw std::runtime_error("could not create image: " + std::string(aeron_errmsg())); } aeron_logbuffer_metadata_t *metadata = (aeron_logbuffer_metadata_t *)log_buffer->mapped_raw_log.log_meta_data.addr; m_image = image; m_filename = filename; m_term_length = metadata->term_length; m_initial_term_id = metadata->initial_term_id; m_position_bits_to_shift = (size_t)aeron_number_of_trailing_zeroes(metadata->term_length); return m_correlationId++; } void appendMessage(int64_t position, size_t length) { aeron_logbuffer_metadata_t *metadata = (aeron_logbuffer_metadata_t *)m_image->log_buffer->mapped_raw_log.log_meta_data.addr; const size_t index = aeron_logbuffer_index_by_position(position, m_position_bits_to_shift); uint8_t buffer[1024]; int32_t term_id = aeron_logbuffer_compute_term_id_from_position( position, m_position_bits_to_shift, m_initial_term_id); int32_t tail_offset = (int32_t)position; metadata->term_tail_counters[index] = static_cast<int64_t>(term_id) << 32 | tail_offset; aeron_term_appender_append_unfragmented_message( &m_image->log_buffer->mapped_raw_log.term_buffers[index], &metadata->term_tail_counters[index], buffer, length, nullptr, nullptr, aeron_logbuffer_compute_term_id_from_position(position, m_position_bits_to_shift, m_initial_term_id), SESSION_ID, STREAM_ID); } static void fragment_handler( void *clientd, const uint8_t *buffer, size_t offset, size_t length, aeron_header_t *header) { auto image = reinterpret_cast<ImageTest *>(clientd); if (image->m_handler) { image->m_handler(buffer, offset, length, header); } } template <typename F> int imagePoll(F&& handler, size_t fragment_limit) { m_handler = handler; return aeron_image_poll(m_image, fragment_handler, this, fragment_limit); } protected: int64_t m_correlationId = 0; int64_t m_subscriber_position = 0; int32_t m_term_length; int32_t m_initial_term_id; size_t m_position_bits_to_shift; std::function<void(const uint8_t *, size_t, size_t, aeron_header_t *)> m_handler = nullptr; aeron_image_t *m_image; std::string m_filename; }; TEST_F(ImageTest, shouldReadFirstMessage) { const size_t messageLength = 120; createImage(); appendMessage(m_subscriber_position, messageLength); auto handler = [&](const uint8_t *, size_t offset, size_t length, aeron_header_t *header) { EXPECT_EQ(offset, m_subscriber_position + AERON_DATA_HEADER_LENGTH); EXPECT_EQ(length, messageLength); EXPECT_EQ(header->frame->frame_header.type, AERON_HDR_TYPE_DATA); }; EXPECT_EQ(imagePoll(handler, SIZE_T_MAX), 1); EXPECT_EQ( static_cast<size_t>(m_subscriber_position), AERON_ALIGN(messageLength + AERON_DATA_HEADER_LENGTH, AERON_LOGBUFFER_FRAME_ALIGNMENT)); } TEST_F(ImageTest, shouldNotReadPastTail) { createImage(); auto handler = [&](const uint8_t *, size_t offset, size_t length, aeron_header_t *header) { FAIL() << "should not be called"; }; EXPECT_EQ(imagePoll(handler, SIZE_T_MAX), 0); EXPECT_EQ(static_cast<size_t>(m_subscriber_position), 0u); } TEST_F(ImageTest, shouldReadOneLimitedMessage) { const size_t messageLength = 120; const int64_t alignedMessageLength = AERON_ALIGN(messageLength + AERON_DATA_HEADER_LENGTH, AERON_LOGBUFFER_FRAME_ALIGNMENT); createImage(); appendMessage(m_subscriber_position, messageLength); appendMessage(m_subscriber_position + alignedMessageLength, messageLength); auto null_handler = [&](const uint8_t *, size_t offset, size_t length, aeron_header_t *header) { }; EXPECT_EQ(imagePoll(null_handler, 1), 1); } TEST_F(ImageTest, shouldReadMultipleMessages) { const size_t messageLength = 120; const int64_t alignedMessageLength = AERON_ALIGN(messageLength + AERON_DATA_HEADER_LENGTH, AERON_LOGBUFFER_FRAME_ALIGNMENT); createImage(); appendMessage(m_subscriber_position, messageLength); appendMessage(m_subscriber_position + alignedMessageLength, messageLength); size_t handlerCallCount = 0; auto handler = [&](const uint8_t *, size_t offset, size_t length, aeron_header_t *header) { handlerCallCount++; }; EXPECT_EQ(imagePoll(handler, SIZE_T_MAX),2); EXPECT_EQ(handlerCallCount, 2u); EXPECT_EQ(m_subscriber_position, alignedMessageLength * 2); } TEST_F(ImageTest, shouldReadLastMessage) { const size_t messageLength = 120; const int64_t alignedMessageLength = AERON_ALIGN(messageLength + AERON_DATA_HEADER_LENGTH, AERON_LOGBUFFER_FRAME_ALIGNMENT); createImage(); m_subscriber_position = m_term_length - alignedMessageLength; appendMessage(m_subscriber_position, messageLength); auto handler = [&](const uint8_t *, size_t offset, size_t length, aeron_header_t *header) { EXPECT_EQ(offset, m_subscriber_position + AERON_DATA_HEADER_LENGTH); EXPECT_EQ(length, messageLength); }; EXPECT_EQ(imagePoll(handler, SIZE_T_MAX), 1); EXPECT_EQ(m_subscriber_position, m_term_length); } TEST_F(ImageTest, shouldNotReadLastMessageWhenPadding) { const size_t messageLength = 120; const int64_t alignedMessageLength = AERON_ALIGN(messageLength + AERON_DATA_HEADER_LENGTH, AERON_LOGBUFFER_FRAME_ALIGNMENT); createImage(); m_subscriber_position = m_term_length - alignedMessageLength; // this will append padding instead of the message as it will trip over the end. appendMessage(m_subscriber_position, messageLength + AERON_DATA_HEADER_LENGTH); auto handler = [&](const uint8_t *, size_t offset, size_t length, aeron_header_t *header) { FAIL() << "should not be called"; }; EXPECT_EQ(imagePoll(handler, SIZE_T_MAX), 0); EXPECT_EQ(m_subscriber_position, m_term_length); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ImageRegistration13.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // This example illustrates how to do registration with a 2D Rigid Transform // and with MutualInformation metric. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkImageRegistrationMethod.h" #include "itkCenteredRigid2DTransform.h" #include "itkCenteredTransformInitializer.h" #include "itkMattesMutualInformationImageToImageMetric.h" #include "itkLinearInterpolateImageFunction.h" #include "itkRegularStepGradientDescentOptimizer.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" // The following section of code implements a Command observer // used to monitor the evolution of the registration process. // #include "itkCommand.h" class CommandIterationUpdate : public itk::Command { public: typedef CommandIterationUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer<Self> Pointer; itkNewMacro( Self ); protected: CommandIterationUpdate() {}; public: typedef itk::RegularStepGradientDescentOptimizer OptimizerType; typedef const OptimizerType * OptimizerPointer; void Execute(itk::Object *caller, const itk::EventObject & event) { Execute( (const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) { OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object ); if( typeid( event ) != typeid( itk::IterationEvent ) ) { return; } std::cout << optimizer->GetCurrentIteration() << " "; std::cout << optimizer->GetValue() << " "; std::cout << optimizer->GetCurrentPosition() << std::endl; } }; int main( int argc, char *argv[] ) { if( argc < 3 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " fixedImageFile movingImageFile "; std::cerr << "outputImagefile [differenceImage]" << std::endl; return 1; } const unsigned int Dimension = 2; typedef unsigned char PixelType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; typedef itk::CenteredRigid2DTransform< double > TransformType; typedef itk::RegularStepGradientDescentOptimizer OptimizerType; typedef itk::LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; typedef itk::ImageRegistrationMethod< FixedImageType, MovingImageType > RegistrationType; typedef itk::MattesMutualInformationImageToImageMetric< FixedImageType, MovingImageType > MetricType; TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); RegistrationType::Pointer registration = RegistrationType::New(); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetInterpolator( interpolator ); MetricType::Pointer metric = MetricType::New(); registration->SetMetric( metric ); metric->SetNumberOfHistogramBins( 20 ); metric->SetNumberOfSpatialSamples( 10000 ); typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType; typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType; FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); fixedImageReader->SetFileName( argv[1] ); movingImageReader->SetFileName( argv[2] ); registration->SetFixedImage( fixedImageReader->GetOutput() ); registration->SetMovingImage( movingImageReader->GetOutput() ); fixedImageReader->Update(); registration->SetFixedImageRegion( fixedImageReader->GetOutput()->GetBufferedRegion() ); typedef itk::CenteredTransformInitializer< TransformType, FixedImageType, MovingImageType > TransformInitializerType; TransformInitializerType::Pointer initializer = TransformInitializerType::New(); initializer->SetTransform( transform ); initializer->SetFixedImage( fixedImageReader->GetOutput() ); initializer->SetMovingImage( movingImageReader->GetOutput() ); initializer->GeometryOn(); initializer->InitializeTransform(); transform->SetAngle( 0.0 ); registration->SetInitialTransformParameters( transform->GetParameters() ); typedef OptimizerType::ScalesType OptimizerScalesType; OptimizerScalesType optimizerScales( transform->GetNumberOfParameters() ); const double translationScale = 1.0 / 1000.0; const double centerScale = 1000.0; // prevents it from moving // during the optimization optimizerScales[0] = 1.0; optimizerScales[1] = centerScale; optimizerScales[2] = centerScale; optimizerScales[3] = translationScale; optimizerScales[4] = translationScale; optimizer->SetScales( optimizerScales ); optimizer->SetMaximumStepLength( 0.5 ); optimizer->SetMinimumStepLength( 0.0001 ); optimizer->SetNumberOfIterations( 400 ); // Create the Command observer and register it with the optimizer. // CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); optimizer->AddObserver( itk::IterationEvent(), observer ); try { registration->StartRegistration(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } typedef RegistrationType::ParametersType ParametersType; ParametersType finalParameters = registration->GetLastTransformParameters(); const double finalAngle = finalParameters[0]; const double finalRotationCenterX = finalParameters[1]; const double finalRotationCenterY = finalParameters[2]; const double finalTranslationX = finalParameters[3]; const double finalTranslationY = finalParameters[4]; unsigned int numberOfIterations = optimizer->GetCurrentIteration(); double bestValue = optimizer->GetValue(); // Print out results // const double finalAngleInDegrees = finalAngle * 45.0 / atan(1.0); std::cout << "Result = " << std::endl; std::cout << " Angle (radians) " << finalAngle << std::endl; std::cout << " Angle (degrees) " << finalAngleInDegrees << std::endl; std::cout << " Center X = " << finalRotationCenterX << std::endl; std::cout << " Center Y = " << finalRotationCenterY << std::endl; std::cout << " Translation X = " << finalTranslationX << std::endl; std::cout << " Translation Y = " << finalTranslationY << std::endl; std::cout << " Iterations = " << numberOfIterations << std::endl; std::cout << " Metric value = " << bestValue << std::endl; typedef itk::ResampleImageFilter< MovingImageType, FixedImageType > ResampleFilterType; TransformType::Pointer finalTransform = TransformType::New(); finalTransform->SetParameters( finalParameters ); ResampleFilterType::Pointer resample = ResampleFilterType::New(); resample->SetTransform( finalTransform ); resample->SetInput( movingImageReader->GetOutput() ); FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resample->SetOutputOrigin( fixedImage->GetOrigin() ); resample->SetOutputSpacing( fixedImage->GetSpacing() ); resample->SetDefaultPixelValue( 100 ); typedef itk::Image< PixelType, Dimension > OutputImageType; typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[3] ); writer->SetInput( resample->GetOutput() ); writer->Update(); // Software Guide : EndCodeSnippet return 0; } <commit_msg>STYLE: Software Guide tags added<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ImageRegistration13.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Software Guide : BeginLatex // // This example illustrates how to do registration with a 2D Rigid Transform // and with MutualInformation metric. // // Software Guide : EndLatex #include "itkImageRegistrationMethod.h" #include "itkCenteredRigid2DTransform.h" #include "itkCenteredTransformInitializer.h" // Software Guide : BeginCodeSnippet #include "itkMattesMutualInformationImageToImageMetric.h" // Software Guide : EndCodeSnippet #include "itkLinearInterpolateImageFunction.h" #include "itkRegularStepGradientDescentOptimizer.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" // The following section of code implements a Command observer // used to monitor the evolution of the registration process. // #include "itkCommand.h" class CommandIterationUpdate : public itk::Command { public: typedef CommandIterationUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer<Self> Pointer; itkNewMacro( Self ); protected: CommandIterationUpdate() {}; public: typedef itk::RegularStepGradientDescentOptimizer OptimizerType; typedef const OptimizerType * OptimizerPointer; void Execute(itk::Object *caller, const itk::EventObject & event) { Execute( (const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) { OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object ); if( typeid( event ) != typeid( itk::IterationEvent ) ) { return; } std::cout << optimizer->GetCurrentIteration() << " "; std::cout << optimizer->GetValue() << " "; std::cout << optimizer->GetCurrentPosition() << std::endl; } }; int main( int argc, char *argv[] ) { if( argc < 3 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " fixedImageFile movingImageFile "; std::cerr << "outputImagefile " << std::endl; return 1; } const unsigned int Dimension = 2; typedef unsigned char PixelType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; // Software Guide : BeginLatex // The CenteredRigid2DTransform applies a rigid transform in 2D space. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::CenteredRigid2DTransform< double > TransformType; typedef itk::RegularStepGradientDescentOptimizer OptimizerType; // Software Guide : EndCodeSnippet typedef itk::LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; typedef itk::ImageRegistrationMethod< FixedImageType, MovingImageType > RegistrationType; // Software Guide : BeginCodeSnippet typedef itk::MattesMutualInformationImageToImageMetric< FixedImageType, MovingImageType > MetricType; // Software Guide : EndCodeSnippet // Software Guide : BeginCodeSnippet TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); // Software Guide : EndCodeSnippet InterpolatorType::Pointer interpolator = InterpolatorType::New(); RegistrationType::Pointer registration = RegistrationType::New(); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetInterpolator( interpolator ); MetricType::Pointer metric = MetricType::New(); registration->SetMetric( metric ); metric->SetNumberOfHistogramBins( 20 ); metric->SetNumberOfSpatialSamples( 10000 ); typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType; typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType; FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); fixedImageReader->SetFileName( argv[1] ); movingImageReader->SetFileName( argv[2] ); registration->SetFixedImage( fixedImageReader->GetOutput() ); registration->SetMovingImage( movingImageReader->GetOutput() ); fixedImageReader->Update(); registration->SetFixedImageRegion( fixedImageReader->GetOutput()->GetBufferedRegion() ); // Software Guide : BeginLatex // The \doxygen{CenteredRigid2DTransform} is initialized by 5 parameters, // indicating the angle of rotation, the centre co-ordinates and the // translation to be applied after rotation. The initialization is done // by the \doxygen{CenteredTransformInitializer}. // The transform can operate in two modes, one assumes that the // anatomical objects to be registered are centered in their respective // images. Hence the best initial guess for the registration is the one // that superimposes those two centers. // This second approach assumes that the moments of the anatomical // objects are similar for both images and hence the best initial guess // for registration is to superimpose both mass centers. The center of // mass is computed from the moments obtained from the gray level values. // Here we adopt the first approach. The \code{GeometryOn()} method // toggles between the approaches. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef itk::CenteredTransformInitializer< TransformType, FixedImageType, MovingImageType > TransformInitializerType; TransformInitializerType::Pointer initializer = TransformInitializerType::New(); initializer->SetTransform( transform ); initializer->SetFixedImage( fixedImageReader->GetOutput() ); initializer->SetMovingImage( movingImageReader->GetOutput() ); initializer->GeometryOn(); initializer->InitializeTransform(); // Software Guide : EndCodeSnippet transform->SetAngle( 0.0 ); registration->SetInitialTransformParameters( transform->GetParameters() ); // Software Guide : BeginLatex // The optimzer scales the metrics (the gradient in this case) by the // scales during each iteration. Hence a large value of the center scale // will prevent movement along the center during optimization. Here we // assume that the fixed and moving images are likely to be related by // a translation. // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef OptimizerType::ScalesType OptimizerScalesType; OptimizerScalesType optimizerScales( transform->GetNumberOfParameters() ); const double translationScale = 1.0 / 1000.0; const double centerScale = 1000.0; // prevents it from moving // during the optimization optimizerScales[0] = 1.0; optimizerScales[1] = centerScale; optimizerScales[2] = centerScale; optimizerScales[3] = translationScale; optimizerScales[4] = translationScale; optimizer->SetScales( optimizerScales ); optimizer->SetMaximumStepLength( 0.5 ); optimizer->SetMinimumStepLength( 0.0001 ); optimizer->SetNumberOfIterations( 400 ); // Software Guide : EndCodeSnippet // Create the Command observer and register it with the optimizer. // CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); optimizer->AddObserver( itk::IterationEvent(), observer ); try { registration->StartRegistration(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } typedef RegistrationType::ParametersType ParametersType; ParametersType finalParameters = registration->GetLastTransformParameters(); const double finalAngle = finalParameters[0]; const double finalRotationCenterX = finalParameters[1]; const double finalRotationCenterY = finalParameters[2]; const double finalTranslationX = finalParameters[3]; const double finalTranslationY = finalParameters[4]; unsigned int numberOfIterations = optimizer->GetCurrentIteration(); double bestValue = optimizer->GetValue(); // Print out results // const double finalAngleInDegrees = finalAngle * 45.0 / atan(1.0); std::cout << "Result = " << std::endl; std::cout << " Angle (radians) " << finalAngle << std::endl; std::cout << " Angle (degrees) " << finalAngleInDegrees << std::endl; std::cout << " Center X = " << finalRotationCenterX << std::endl; std::cout << " Center Y = " << finalRotationCenterY << std::endl; std::cout << " Translation X = " << finalTranslationX << std::endl; std::cout << " Translation Y = " << finalTranslationY << std::endl; std::cout << " Iterations = " << numberOfIterations << std::endl; std::cout << " Metric value = " << bestValue << std::endl; typedef itk::ResampleImageFilter< MovingImageType, FixedImageType > ResampleFilterType; TransformType::Pointer finalTransform = TransformType::New(); finalTransform->SetParameters( finalParameters ); ResampleFilterType::Pointer resample = ResampleFilterType::New(); resample->SetTransform( finalTransform ); resample->SetInput( movingImageReader->GetOutput() ); FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput(); resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resample->SetOutputOrigin( fixedImage->GetOrigin() ); resample->SetOutputSpacing( fixedImage->GetSpacing() ); resample->SetDefaultPixelValue( 100 ); typedef itk::Image< PixelType, Dimension > OutputImageType; typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[3] ); writer->SetInput( resample->GetOutput() ); writer->Update(); return 0; } // Software Guide : BeginLatex // // Let's execute this example over some of the images provided in // \code{Examples/Data}, for example: // // \begin{itemize} // \item \code{BrainProtonDensitySlice.png} // \item \code{BrainProtonDensitySliceBorder20.png} // \end{itemize} // // The second image is the result of intentionally shiftng the first // image by $20mm$ in $X$ and $20mm$ in // $Y$. Both images have unit-spacing and are shown in Figure // \ref{fig:FixedMovingImageRegistration1}. The example // yielded the following results. // // \begin{verbatim} // Translation X = 20 // Translation Y = 20 // \end{verbatim} // These values match the true misaligment introduced in the moving image. // Software Guide : EndLatex <|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. * **************************************************************************/ #include <TH1.h> #include <TObjArray.h> #include <TMath.h> #include "AliITSMapA2.h" #include "AliITSsegmentation.h" #include "AliITSresponse.h" #include "AliITSdigit.h" //////////////////////////////////////////////////////////////////////// // Map Class for ITS. Implementation A2. In this implementation, the // // 2 dimensional (iz,ix) map is filled with Double precision floating // // point values. Since this class is derived for AliITSMapA1 it also // // has all of the functionality of that class as well. For each // // cell a corresponding TObject, a hit, can also be stored. // // The detector geometry is accessed via the that detectors // // segmentation class and stored here for conveniance. // //////////////////////////////////////////////////////////////////////// ClassImp(AliITSMapA2) //______________________________________________________________________ AliITSMapA2::AliITSMapA2(){ // default constructor fSegmentation = 0; fNpz = 0; fNpx = 0; fMaxIndex = 0; fHitMapD = 0; fObjects = 0; fNobjects = 0; fMapThresholdD =0.; } //______________________________________________________________________ AliITSMapA2::AliITSMapA2(AliITSsegmentation *seg){ //constructor fScaleSizeZ = 1; fScaleSizeX = 1; fSegmentation = seg; fNpz = fSegmentation->Npz(); fNpx = fSegmentation->Npx(); fMaxIndex = fNpz*fNpx+fNpx; // 2 halves of detector fHitMapD = new Double_t[fMaxIndex]; fMapThresholdD = 0.; fObjects = 0; fNobjects = 0; ClearMap(); } //______________________________________________________________________ AliITSMapA2::AliITSMapA2(AliITSsegmentation *seg, Int_t scalesizeX, Int_t scalesizeZ){ //constructor fSegmentation = seg; fScaleSizeX = scalesizeX; fScaleSizeZ = scalesizeZ; fNpz = fScaleSizeZ*fSegmentation->Npz(); fNpx = fScaleSizeX*fSegmentation->Npx(); fMaxIndex = fNpz*fNpx+fNpx; // 2 halves of detector fHitMapD = new Double_t[fMaxIndex]; fMapThresholdD = 0.; fObjects = 0; fNobjects = 0; ClearMap(); } //______________________________________________________________________ AliITSMapA2::AliITSMapA2(AliITSsegmentation *seg, TObjArray *obj, Double_t thresh){ //constructor fNobjects = 0; fScaleSizeZ = 1; fScaleSizeX = 1; fSegmentation = seg; fNpz = fSegmentation->Npz(); fNpx = fSegmentation->Npx(); fMaxIndex = fNpz*fNpx+fNpx; // 2 halves of detector fHitMapD = new Double_t[fMaxIndex]; fObjects = obj; if (fObjects) fNobjects = fObjects->GetEntriesFast(); fMapThresholdD = thresh; ClearMap(); } //______________________________________________________________________ AliITSMapA2::~AliITSMapA2(){ //destructor if (fHitMapD) delete[] fHitMapD; } //______________________________________________________________________ AliITSMapA2::AliITSMapA2(const AliITSMapA2 &source){ // Copy Constructor if(&source == this) return; this->fMapThresholdD = source.fMapThresholdD; this->fScaleSizeX = source.fScaleSizeX; this->fScaleSizeZ = source.fScaleSizeZ; this->fHitMapD = source.fHitMapD; return; } //______________________________________________________________________ AliITSMapA2& AliITSMapA2::operator=(const AliITSMapA2 &source) { // Assignment operator if(&source == this) return *this; this->fMapThresholdD = source.fMapThresholdD; this->fScaleSizeX = source.fScaleSizeX; this->fScaleSizeZ = source.fScaleSizeZ; this->fHitMapD = source.fHitMapD; return *this; } //______________________________________________________________________ void AliITSMapA2::ClearMap(){ //clear array memset(fHitMapD,0,sizeof(Double_t)*fMaxIndex); } //______________________________________________________________________ void AliITSMapA2::FillMap(){ // fills signal map from digits - apply a threshold for signal if (!fObjects) return; Int_t ndigits = fObjects->GetEntriesFast(); if (!ndigits) return; AliITSdigit *dig; for (Int_t ndig=0; ndig<ndigits; ndig++) { dig = (AliITSdigit*)fObjects->UncheckedAt(ndig); Double_t signal = (Double_t)(dig->fSignal); if (signal > fMapThresholdD) SetHit(dig->fCoord1,dig->fCoord2,signal); } // end for ndig } //______________________________________________________________________ void AliITSMapA2::FlagHit(Int_t iz, Int_t ix){ //flag an entry fHitMapD[CheckedIndex(iz, ix)]= -1000.*TMath::Abs((Int_t)(fHitMapD[CheckedIndex(iz, ix)])+1.); } //______________________________________________________________________ TObject* AliITSMapA2::GetHit(Int_t i, Int_t dummy){ //return a pointer to the 1D histogram if (fObjects) { return fObjects->UncheckedAt(i); } else return NULL; } //______________________________________________________________________ Double_t AliITSMapA2::GetSignal(Int_t index){ //get signal in a cell if (index<fMaxIndex) return (index <0) ? 0. : fHitMapD[index]; else return 0.; } //______________________________________________________________________ FlagType AliITSMapA2::TestHit(Int_t iz, Int_t ix){ // check if the entry has already been flagged if (CheckedIndex(iz, ix) < 0) return kEmpty; Int_t inf=(Int_t)fHitMapD[CheckedIndex(iz, ix)]; if (inf <= -1000) { return kUsed; } else if (inf == 0) { return kEmpty; } else { return kUnused; } // end if inf... } //______________________________________________________________________ void AliITSMapA2::FillMapFromHist(){ // fills map from 1D histograms if (!fObjects) return; // an example for( Int_t i=0; i<fNobjects; i++) { TH1F *hist =(TH1F *)fObjects->UncheckedAt(i); Int_t nsamples = hist->GetNbinsX(); for( Int_t j=0; j<nsamples; j++) { Double_t signal = (Double_t)(hist->GetBinContent(j+1)); if (signal > fMapThresholdD) SetHit(i,j,signal); } // end for j } // end for i } //______________________________________________________________________ void AliITSMapA2::FillHist(){ // fill 1D histograms from map if (!fObjects || fScaleSizeX != 1) return; // an example for( Int_t i=0; i<fNobjects; i++) { TH1F *hist =(TH1F *)fObjects->UncheckedAt(i); for( Int_t j=0; j<fNpx; j++) { Double_t signal=GetSignal(i,j); if (signal > fMapThresholdD) hist->Fill((Float_t)j,signal); } // end for j } // end for i } //______________________________________________________________________ void AliITSMapA2::ResetHist(){ // Reset histograms if (!fObjects) return; for( Int_t i=0; i<fNobjects; i++) { if ((*fObjects)[i]) ((TH1F*)(*fObjects)[i])->Reset(); } // end for i } //______________________________________________________________________ void AliITSMapA2::AddSignal(Int_t iz,Int_t ix,Double_t sig){ // Addes sig to cell iz. equivalent to the very common // sig = fMapA2->GetSignal(iz,ix) + sig; fMapA2->SetHit(iz,ix,sig); Int_t index=GetHitIndex(iz,ix); if(index<0) return; fHitMapD[CheckedIndex(iz, ix)] += sig; } <commit_msg>Bad vector indexing corrected (from F. Carminati)<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. * **************************************************************************/ #include <TH1.h> #include <TObjArray.h> #include <TMath.h> #include "AliITSMapA2.h" #include "AliITSsegmentation.h" #include "AliITSresponse.h" #include "AliITSdigit.h" //////////////////////////////////////////////////////////////////////// // Map Class for ITS. Implementation A2. In this implementation, the // // 2 dimensional (iz,ix) map is filled with Double precision floating // // point values. Since this class is derived for AliITSMapA1 it also // // has all of the functionality of that class as well. For each // // cell a corresponding TObject, a hit, can also be stored. // // The detector geometry is accessed via the that detectors // // segmentation class and stored here for conveniance. // //////////////////////////////////////////////////////////////////////// ClassImp(AliITSMapA2) //______________________________________________________________________ AliITSMapA2::AliITSMapA2(){ // default constructor fSegmentation = 0; fNpz = 0; fNpx = 0; fMaxIndex = 0; fHitMapD = 0; fObjects = 0; fNobjects = 0; fMapThresholdD =0.; } //______________________________________________________________________ AliITSMapA2::AliITSMapA2(AliITSsegmentation *seg){ //constructor fScaleSizeZ = 1; fScaleSizeX = 1; fSegmentation = seg; fNpz = fSegmentation->Npz(); fNpx = fSegmentation->Npx(); fMaxIndex = fNpz*fNpx+fNpx; // 2 halves of detector fHitMapD = new Double_t[fMaxIndex+1]; fMapThresholdD = 0.; fObjects = 0; fNobjects = 0; ClearMap(); } //______________________________________________________________________ AliITSMapA2::AliITSMapA2(AliITSsegmentation *seg, Int_t scalesizeX, Int_t scalesizeZ){ //constructor fSegmentation = seg; fScaleSizeX = scalesizeX; fScaleSizeZ = scalesizeZ; fNpz = fScaleSizeZ*fSegmentation->Npz(); fNpx = fScaleSizeX*fSegmentation->Npx(); fMaxIndex = fNpz*fNpx+fNpx; // 2 halves of detector fHitMapD = new Double_t[fMaxIndex]; fMapThresholdD = 0.; fObjects = 0; fNobjects = 0; ClearMap(); } //______________________________________________________________________ AliITSMapA2::AliITSMapA2(AliITSsegmentation *seg, TObjArray *obj, Double_t thresh){ //constructor fNobjects = 0; fScaleSizeZ = 1; fScaleSizeX = 1; fSegmentation = seg; fNpz = fSegmentation->Npz(); fNpx = fSegmentation->Npx(); fMaxIndex = fNpz*fNpx+fNpx; // 2 halves of detector fHitMapD = new Double_t[fMaxIndex]; fObjects = obj; if (fObjects) fNobjects = fObjects->GetEntriesFast(); fMapThresholdD = thresh; ClearMap(); } //______________________________________________________________________ AliITSMapA2::~AliITSMapA2(){ //destructor if (fHitMapD) delete[] fHitMapD; } //______________________________________________________________________ AliITSMapA2::AliITSMapA2(const AliITSMapA2 &source){ // Copy Constructor if(&source == this) return; this->fMapThresholdD = source.fMapThresholdD; this->fScaleSizeX = source.fScaleSizeX; this->fScaleSizeZ = source.fScaleSizeZ; this->fHitMapD = source.fHitMapD; return; } //______________________________________________________________________ AliITSMapA2& AliITSMapA2::operator=(const AliITSMapA2 &source) { // Assignment operator if(&source == this) return *this; this->fMapThresholdD = source.fMapThresholdD; this->fScaleSizeX = source.fScaleSizeX; this->fScaleSizeZ = source.fScaleSizeZ; this->fHitMapD = source.fHitMapD; return *this; } //______________________________________________________________________ void AliITSMapA2::ClearMap(){ //clear array memset(fHitMapD,0,sizeof(Double_t)*fMaxIndex); } //______________________________________________________________________ void AliITSMapA2::FillMap(){ // fills signal map from digits - apply a threshold for signal if (!fObjects) return; Int_t ndigits = fObjects->GetEntriesFast(); if (!ndigits) return; AliITSdigit *dig; for (Int_t ndig=0; ndig<ndigits; ndig++) { dig = (AliITSdigit*)fObjects->UncheckedAt(ndig); Double_t signal = (Double_t)(dig->fSignal); if (signal > fMapThresholdD) SetHit(dig->fCoord1,dig->fCoord2,signal); } // end for ndig } //______________________________________________________________________ void AliITSMapA2::FlagHit(Int_t iz, Int_t ix){ //flag an entry fHitMapD[CheckedIndex(iz, ix)]= -1000.*TMath::Abs((Int_t)(fHitMapD[CheckedIndex(iz, ix)])+1.); } //______________________________________________________________________ TObject* AliITSMapA2::GetHit(Int_t i, Int_t dummy){ //return a pointer to the 1D histogram if (fObjects) { return fObjects->UncheckedAt(i); } else return NULL; } //______________________________________________________________________ Double_t AliITSMapA2::GetSignal(Int_t index){ //get signal in a cell if (index<fMaxIndex) return (index <0) ? 0. : fHitMapD[index]; else return 0.; } //______________________________________________________________________ FlagType AliITSMapA2::TestHit(Int_t iz, Int_t ix){ // check if the entry has already been flagged if (CheckedIndex(iz, ix) < 0) return kEmpty; Int_t inf=(Int_t)fHitMapD[CheckedIndex(iz, ix)]; if (inf <= -1000) { return kUsed; } else if (inf == 0) { return kEmpty; } else { return kUnused; } // end if inf... } //______________________________________________________________________ void AliITSMapA2::FillMapFromHist(){ // fills map from 1D histograms if (!fObjects) return; // an example for( Int_t i=0; i<fNobjects; i++) { TH1F *hist =(TH1F *)fObjects->UncheckedAt(i); Int_t nsamples = hist->GetNbinsX(); for( Int_t j=0; j<nsamples; j++) { Double_t signal = (Double_t)(hist->GetBinContent(j+1)); if (signal > fMapThresholdD) SetHit(i,j,signal); } // end for j } // end for i } //______________________________________________________________________ void AliITSMapA2::FillHist(){ // fill 1D histograms from map if (!fObjects || fScaleSizeX != 1) return; // an example for( Int_t i=0; i<fNobjects; i++) { TH1F *hist =(TH1F *)fObjects->UncheckedAt(i); for( Int_t j=0; j<fNpx; j++) { Double_t signal=GetSignal(i,j); if (signal > fMapThresholdD) hist->Fill((Float_t)j,signal); } // end for j } // end for i } //______________________________________________________________________ void AliITSMapA2::ResetHist(){ // Reset histograms if (!fObjects) return; for( Int_t i=0; i<fNobjects; i++) { if ((*fObjects)[i]) ((TH1F*)(*fObjects)[i])->Reset(); } // end for i } //______________________________________________________________________ void AliITSMapA2::AddSignal(Int_t iz,Int_t ix,Double_t sig){ // Addes sig to cell iz. equivalent to the very common // sig = fMapA2->GetSignal(iz,ix) + sig; fMapA2->SetHit(iz,ix,sig); Int_t index=GetHitIndex(iz,ix); if(index<0) return; fHitMapD[CheckedIndex(iz, ix)] += sig; } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/tools/quic_toy_server.h" #include <utility> #include <vector> #include "net/third_party/quiche/src/quic/core/quic_versions.h" #include "net/third_party/quiche/src/quic/platform/api/quic_default_proof_providers.h" #include "net/third_party/quiche/src/quic/platform/api/quic_flags.h" #include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h" #include "net/third_party/quiche/src/quic/tools/quic_memory_cache_backend.h" DEFINE_QUIC_COMMAND_LINE_FLAG(int32_t, port, 6121, "The port the quic server will listen on."); DEFINE_QUIC_COMMAND_LINE_FLAG( std::string, quic_response_cache_dir, "", "Specifies the directory used during QuicHttpResponseCache " "construction to seed the cache. Cache directory can be " "generated using `wget -p --save-headers <url>`"); DEFINE_QUIC_COMMAND_LINE_FLAG( bool, generate_dynamic_responses, false, "If true, then URLs which have a numeric path will send a dynamically " "generated response of that many bytes."); DEFINE_QUIC_COMMAND_LINE_FLAG(bool, quic_ietf_draft, false, "Only enable IETF draft versions. This also " "enables required internal QUIC flags."); DEFINE_QUIC_COMMAND_LINE_FLAG( std::string, quic_versions, "", "QUIC versions to enable, e.g. \"h3-25,h3-27\". If not set, then all " "available versions are enabled."); namespace quic { std::unique_ptr<quic::QuicSimpleServerBackend> QuicToyServer::MemoryCacheBackendFactory::CreateBackend() { auto memory_cache_backend = std::make_unique<QuicMemoryCacheBackend>(); if (GetQuicFlag(FLAGS_generate_dynamic_responses)) { memory_cache_backend->GenerateDynamicResponses(); } if (!GetQuicFlag(FLAGS_quic_response_cache_dir).empty()) { memory_cache_backend->InitializeBackend( GetQuicFlag(FLAGS_quic_response_cache_dir)); } return memory_cache_backend; } QuicToyServer::QuicToyServer(BackendFactory* backend_factory, ServerFactory* server_factory) : backend_factory_(backend_factory), server_factory_(server_factory) {} int QuicToyServer::Start() { ParsedQuicVersionVector supported_versions; if (GetQuicFlag(FLAGS_quic_ietf_draft)) { QuicVersionInitializeSupportForIetfDraft(); for (const ParsedQuicVersion& version : AllSupportedVersions()) { // Add all versions that supports IETF QUIC. if (version.HasIetfQuicFrames() && version.handshake_protocol == quic::PROTOCOL_TLS1_3) { supported_versions.push_back(version); break; } } } else { supported_versions = AllSupportedVersions(); } std::string versions_string = GetQuicFlag(FLAGS_quic_versions); if (!versions_string.empty()) { supported_versions = ParseQuicVersionVectorString(versions_string); } if (supported_versions.empty()) { return 1; } for (const auto& version : supported_versions) { QuicEnableVersion(version); } auto proof_source = quic::CreateDefaultProofSource(); auto backend = backend_factory_->CreateBackend(); auto server = server_factory_->CreateServer( backend.get(), std::move(proof_source), supported_versions); if (!server->CreateUDPSocketAndListen(quic::QuicSocketAddress( quic::QuicIpAddress::Any6(), GetQuicFlag(FLAGS_port)))) { return 1; } server->HandleEventsForever(); return 0; } } // namespace quic <commit_msg>Make QuicToyServer support all IETF drafts<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/third_party/quiche/src/quic/tools/quic_toy_server.h" #include <utility> #include <vector> #include "net/third_party/quiche/src/quic/core/quic_versions.h" #include "net/third_party/quiche/src/quic/platform/api/quic_default_proof_providers.h" #include "net/third_party/quiche/src/quic/platform/api/quic_flags.h" #include "net/third_party/quiche/src/quic/platform/api/quic_socket_address.h" #include "net/third_party/quiche/src/quic/tools/quic_memory_cache_backend.h" DEFINE_QUIC_COMMAND_LINE_FLAG(int32_t, port, 6121, "The port the quic server will listen on."); DEFINE_QUIC_COMMAND_LINE_FLAG( std::string, quic_response_cache_dir, "", "Specifies the directory used during QuicHttpResponseCache " "construction to seed the cache. Cache directory can be " "generated using `wget -p --save-headers <url>`"); DEFINE_QUIC_COMMAND_LINE_FLAG( bool, generate_dynamic_responses, false, "If true, then URLs which have a numeric path will send a dynamically " "generated response of that many bytes."); DEFINE_QUIC_COMMAND_LINE_FLAG(bool, quic_ietf_draft, false, "Only enable IETF draft versions. This also " "enables required internal QUIC flags."); DEFINE_QUIC_COMMAND_LINE_FLAG( std::string, quic_versions, "", "QUIC versions to enable, e.g. \"h3-25,h3-27\". If not set, then all " "available versions are enabled."); namespace quic { std::unique_ptr<quic::QuicSimpleServerBackend> QuicToyServer::MemoryCacheBackendFactory::CreateBackend() { auto memory_cache_backend = std::make_unique<QuicMemoryCacheBackend>(); if (GetQuicFlag(FLAGS_generate_dynamic_responses)) { memory_cache_backend->GenerateDynamicResponses(); } if (!GetQuicFlag(FLAGS_quic_response_cache_dir).empty()) { memory_cache_backend->InitializeBackend( GetQuicFlag(FLAGS_quic_response_cache_dir)); } return memory_cache_backend; } QuicToyServer::QuicToyServer(BackendFactory* backend_factory, ServerFactory* server_factory) : backend_factory_(backend_factory), server_factory_(server_factory) {} int QuicToyServer::Start() { ParsedQuicVersionVector supported_versions; if (GetQuicFlag(FLAGS_quic_ietf_draft)) { QuicVersionInitializeSupportForIetfDraft(); for (const ParsedQuicVersion& version : AllSupportedVersions()) { // Add all versions that supports IETF QUIC. if (version.HasIetfQuicFrames() && version.handshake_protocol == quic::PROTOCOL_TLS1_3) { supported_versions.push_back(version); } } } else { supported_versions = AllSupportedVersions(); } std::string versions_string = GetQuicFlag(FLAGS_quic_versions); if (!versions_string.empty()) { supported_versions = ParseQuicVersionVectorString(versions_string); } if (supported_versions.empty()) { return 1; } for (const auto& version : supported_versions) { QuicEnableVersion(version); } auto proof_source = quic::CreateDefaultProofSource(); auto backend = backend_factory_->CreateBackend(); auto server = server_factory_->CreateServer( backend.get(), std::move(proof_source), supported_versions); if (!server->CreateUDPSocketAndListen(quic::QuicSocketAddress( quic::QuicIpAddress::Any6(), GetQuicFlag(FLAGS_port)))) { return 1; } server->HandleEventsForever(); return 0; } } // namespace quic <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ImageRegistration15.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif // Software Guide : BeginLatex // // This example illustrates how to do registration with a 2D Translation Transform, // the Normalized Mutual Information metric and the One+One evolutionary optimizer. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkImageRegistrationMethod.h" #include "itkTranslationTransform.h" #include "itkNormalizedMutualInformationHistogramImageToImageMetric.h" #include "itkLinearInterpolateImageFunction.h" #include "itkOnePlusOneEvolutionaryOptimizer.h" #include "itkNormalVariateGenerator.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" // The following section of code implements a Command observer // used to monitor the evolution of the registration process. // #include "itkCommand.h" class CommandIterationUpdate : public itk::Command { public: typedef CommandIterationUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer<Self> Pointer; itkNewMacro( Self ); protected: CommandIterationUpdate() {m_LastMetricValue = 0;} public: typedef itk::OnePlusOneEvolutionaryOptimizer OptimizerType; typedef const OptimizerType * OptimizerPointer; void Execute(itk::Object *caller, const itk::EventObject & event) { Execute( (const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) { OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object ); if( typeid( event ) != typeid( itk::IterationEvent ) ) { return; } double currentValue = optimizer->GetValue(); // Only print out when the Metric value changes if( fabs( m_LastMetricValue - currentValue ) > 1e-7 ) { std::cout << optimizer->GetCurrentIteration() << " "; std::cout << currentValue << " "; std::cout << optimizer->GetCurrentPosition() << std::endl; m_LastMetricValue = currentValue; } } private: double m_LastMetricValue; }; int main( int argc, char *argv[] ) { if( argc < 4 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " fixedImageFile movingImageFile "; std::cerr << "outputImagefile [numberOfHistogramBins] "; std::cerr << "[initialRadius] [epsilon]" << std::endl; return 1; } const unsigned int Dimension = 2; typedef unsigned char PixelType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; typedef itk::TranslationTransform< double, Dimension > TransformType; typedef itk::OnePlusOneEvolutionaryOptimizer OptimizerType; typedef itk::LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; typedef itk::ImageRegistrationMethod< FixedImageType, MovingImageType > RegistrationType; typedef itk::NormalizedMutualInformationHistogramImageToImageMetric< FixedImageType, MovingImageType > MetricType; TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); RegistrationType::Pointer registration = RegistrationType::New(); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetInterpolator( interpolator ); MetricType::Pointer metric = MetricType::New(); registration->SetMetric( metric ); unsigned int numberOfHistogramBins = 32; if( argc > 4 ) { numberOfHistogramBins = atoi( argv[4] ); std::cout << "Using " << numberOfHistogramBins << " Histogram bins" << std::endl; } MetricType::HistogramType::SizeType histogramSize; histogramSize[0] = numberOfHistogramBins; histogramSize[1] = numberOfHistogramBins; metric->SetHistogramSize( histogramSize ); const unsigned int numberOfParameters = transform->GetNumberOfParameters(); typedef MetricType::ScalesType ScalesType; ScalesType scales( numberOfParameters ); scales.Fill( 1.0 ); metric->SetDerivativeStepLengthScales(scales); typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType; typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType; FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); fixedImageReader->SetFileName( argv[1] ); movingImageReader->SetFileName( argv[2] ); registration->SetFixedImage( fixedImageReader->GetOutput() ); registration->SetMovingImage( movingImageReader->GetOutput() ); fixedImageReader->Update(); movingImageReader->Update(); FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput(); registration->SetFixedImageRegion( fixedImage->GetBufferedRegion() ); transform->SetIdentity(); registration->SetInitialTransformParameters( transform->GetParameters() ); std::cout << "Initial transform parameters = "; std::cout << transform->GetParameters() << std::endl; typedef OptimizerType::ScalesType OptimizerScalesType; OptimizerScalesType optimizerScales( transform->GetNumberOfParameters() ); FixedImageType::RegionType region = fixedImage->GetLargestPossibleRegion(); FixedImageType::SizeType size = region.GetSize(); FixedImageType::SpacingType spacing = fixedImage->GetSpacing(); optimizerScales[0] = 1.0 / ( 10.0 * size[0] * spacing[0] ); optimizerScales[1] = 1.0 / ( 10.0 * size[1] * spacing[1] ); optimizer->SetScales( optimizerScales ); typedef itk::Statistics::NormalVariateGenerator GeneratorType; GeneratorType::Pointer generator = GeneratorType::New(); generator->Initialize(12345); optimizer->MaximizeOn(); optimizer->SetNormalVariateGenerator( generator ); double initialRadius = 0.01; if( argc > 5 ) { initialRadius = atof( argv[5] ); std::cout << "Using initial radius = " << initialRadius << std::endl; } optimizer->Initialize( initialRadius ); double epsilon = 0.001; if( argc > 6 ) { epsilon = atof( argv[6] ); std::cout << "Using epsilon = " << epsilon << std::endl; } optimizer->SetEpsilon( epsilon ); optimizer->SetMaximumIteration( 1000 ); // Create the Command observer and register it with the optimizer. // CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); optimizer->AddObserver( itk::IterationEvent(), observer ); try { registration->StartRegistration(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } typedef RegistrationType::ParametersType ParametersType; ParametersType finalParameters = registration->GetLastTransformParameters(); const double finalTranslationX = finalParameters[0]; const double finalTranslationY = finalParameters[1]; unsigned int numberOfIterations = optimizer->GetCurrentIteration(); double bestValue = optimizer->GetValue(); // Print out results // std::cout << "Result = " << std::endl; std::cout << " Translation X = " << finalTranslationX << std::endl; std::cout << " Translation Y = " << finalTranslationY << std::endl; std::cout << " Iterations = " << numberOfIterations << std::endl; std::cout << " Metric value = " << bestValue << std::endl; typedef itk::ResampleImageFilter< MovingImageType, FixedImageType > ResampleFilterType; TransformType::Pointer finalTransform = TransformType::New(); finalTransform->SetParameters( finalParameters ); ResampleFilterType::Pointer resample = ResampleFilterType::New(); resample->SetTransform( finalTransform ); resample->SetInput( movingImageReader->GetOutput() ); resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resample->SetOutputOrigin( fixedImage->GetOrigin() ); resample->SetOutputSpacing( fixedImage->GetSpacing() ); resample->SetDefaultPixelValue( 100 ); typedef itk::Image< PixelType, Dimension > OutputImageType; typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[3] ); writer->SetInput( resample->GetOutput() ); writer->Update(); // Software Guide : EndCodeSnippet return 0; } <commit_msg>ENH: Scales of parameters were adjusted according to expected values of translation.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: ImageRegistration15.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif // Software Guide : BeginLatex // // This example illustrates how to do registration with a 2D Translation Transform, // the Normalized Mutual Information metric and the One+One evolutionary optimizer. // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet #include "itkImageRegistrationMethod.h" #include "itkTranslationTransform.h" #include "itkNormalizedMutualInformationHistogramImageToImageMetric.h" #include "itkLinearInterpolateImageFunction.h" #include "itkOnePlusOneEvolutionaryOptimizer.h" #include "itkNormalVariateGenerator.h" #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkCastImageFilter.h" // The following section of code implements a Command observer // used to monitor the evolution of the registration process. // #include "itkCommand.h" class CommandIterationUpdate : public itk::Command { public: typedef CommandIterationUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer<Self> Pointer; itkNewMacro( Self ); protected: CommandIterationUpdate() {m_LastMetricValue = 0;} public: typedef itk::OnePlusOneEvolutionaryOptimizer OptimizerType; typedef const OptimizerType * OptimizerPointer; void Execute(itk::Object *caller, const itk::EventObject & event) { Execute( (const itk::Object *)caller, event); } void Execute(const itk::Object * object, const itk::EventObject & event) { OptimizerPointer optimizer = dynamic_cast< OptimizerPointer >( object ); if( typeid( event ) != typeid( itk::IterationEvent ) ) { return; } double currentValue = optimizer->GetValue(); // Only print out when the Metric value changes if( fabs( m_LastMetricValue - currentValue ) > 1e-7 ) { std::cout << optimizer->GetCurrentIteration() << " "; std::cout << currentValue << " "; std::cout << optimizer->GetCurrentPosition() << std::endl; m_LastMetricValue = currentValue; } } private: double m_LastMetricValue; }; int main( int argc, char *argv[] ) { if( argc < 4 ) { std::cerr << "Missing Parameters " << std::endl; std::cerr << "Usage: " << argv[0]; std::cerr << " fixedImageFile movingImageFile "; std::cerr << "outputImagefile [numberOfHistogramBins] "; std::cerr << "[initialRadius] [epsilon]" << std::endl; return 1; } const unsigned int Dimension = 2; typedef unsigned char PixelType; typedef itk::Image< PixelType, Dimension > FixedImageType; typedef itk::Image< PixelType, Dimension > MovingImageType; typedef itk::TranslationTransform< double, Dimension > TransformType; typedef itk::OnePlusOneEvolutionaryOptimizer OptimizerType; typedef itk::LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; typedef itk::ImageRegistrationMethod< FixedImageType, MovingImageType > RegistrationType; typedef itk::NormalizedMutualInformationHistogramImageToImageMetric< FixedImageType, MovingImageType > MetricType; TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); RegistrationType::Pointer registration = RegistrationType::New(); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetInterpolator( interpolator ); MetricType::Pointer metric = MetricType::New(); registration->SetMetric( metric ); unsigned int numberOfHistogramBins = 32; if( argc > 4 ) { numberOfHistogramBins = atoi( argv[4] ); std::cout << "Using " << numberOfHistogramBins << " Histogram bins" << std::endl; } MetricType::HistogramType::SizeType histogramSize; histogramSize[0] = numberOfHistogramBins; histogramSize[1] = numberOfHistogramBins; metric->SetHistogramSize( histogramSize ); const unsigned int numberOfParameters = transform->GetNumberOfParameters(); typedef MetricType::ScalesType ScalesType; ScalesType scales( numberOfParameters ); scales.Fill( 1.0 ); metric->SetDerivativeStepLengthScales(scales); typedef itk::ImageFileReader< FixedImageType > FixedImageReaderType; typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType; FixedImageReaderType::Pointer fixedImageReader = FixedImageReaderType::New(); MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New(); fixedImageReader->SetFileName( argv[1] ); movingImageReader->SetFileName( argv[2] ); registration->SetFixedImage( fixedImageReader->GetOutput() ); registration->SetMovingImage( movingImageReader->GetOutput() ); fixedImageReader->Update(); movingImageReader->Update(); FixedImageType::ConstPointer fixedImage = fixedImageReader->GetOutput(); registration->SetFixedImageRegion( fixedImage->GetBufferedRegion() ); transform->SetIdentity(); registration->SetInitialTransformParameters( transform->GetParameters() ); std::cout << "Initial transform parameters = "; std::cout << transform->GetParameters() << std::endl; typedef OptimizerType::ScalesType OptimizerScalesType; OptimizerScalesType optimizerScales( transform->GetNumberOfParameters() ); FixedImageType::RegionType region = fixedImage->GetLargestPossibleRegion(); FixedImageType::SizeType size = region.GetSize(); FixedImageType::SpacingType spacing = fixedImage->GetSpacing(); optimizerScales[0] = 1.0 / ( 0.1 * size[0] * spacing[0] ); optimizerScales[1] = 1.0 / ( 0.1 * size[1] * spacing[1] ); optimizer->SetScales( optimizerScales ); typedef itk::Statistics::NormalVariateGenerator GeneratorType; GeneratorType::Pointer generator = GeneratorType::New(); generator->Initialize(12345); optimizer->MaximizeOn(); optimizer->SetNormalVariateGenerator( generator ); double initialRadius = 0.01; if( argc > 5 ) { initialRadius = atof( argv[5] ); std::cout << "Using initial radius = " << initialRadius << std::endl; } optimizer->Initialize( initialRadius ); double epsilon = 0.001; if( argc > 6 ) { epsilon = atof( argv[6] ); std::cout << "Using epsilon = " << epsilon << std::endl; } optimizer->SetEpsilon( epsilon ); optimizer->SetMaximumIteration( 2000 ); // Create the Command observer and register it with the optimizer. // CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); optimizer->AddObserver( itk::IterationEvent(), observer ); try { registration->StartRegistration(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } typedef RegistrationType::ParametersType ParametersType; ParametersType finalParameters = registration->GetLastTransformParameters(); const double finalTranslationX = finalParameters[0]; const double finalTranslationY = finalParameters[1]; unsigned int numberOfIterations = optimizer->GetCurrentIteration(); double bestValue = optimizer->GetValue(); // Print out results // std::cout << "Result = " << std::endl; std::cout << " Translation X = " << finalTranslationX << std::endl; std::cout << " Translation Y = " << finalTranslationY << std::endl; std::cout << " Iterations = " << numberOfIterations << std::endl; std::cout << " Metric value = " << bestValue << std::endl; typedef itk::ResampleImageFilter< MovingImageType, FixedImageType > ResampleFilterType; TransformType::Pointer finalTransform = TransformType::New(); finalTransform->SetParameters( finalParameters ); ResampleFilterType::Pointer resample = ResampleFilterType::New(); resample->SetTransform( finalTransform ); resample->SetInput( movingImageReader->GetOutput() ); resample->SetSize( fixedImage->GetLargestPossibleRegion().GetSize() ); resample->SetOutputOrigin( fixedImage->GetOrigin() ); resample->SetOutputSpacing( fixedImage->GetSpacing() ); resample->SetDefaultPixelValue( 100 ); typedef itk::Image< PixelType, Dimension > OutputImageType; typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[3] ); writer->SetInput( resample->GetOutput() ); writer->Update(); // Software Guide : EndCodeSnippet return 0; } <|endoftext|>
<commit_before>//===-- LoopPredication.cpp - Guard based loop predication pass -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The LoopPredication pass tries to convert loop variant range checks to loop // invariant by widening checks across loop iterations. For example, it will // convert // // for (i = 0; i < n; i++) { // guard(i < len); // ... // } // // to // // for (i = 0; i < n; i++) { // guard(n - 1 < len); // ... // } // // After this transformation the condition of the guard is loop invariant, so // loop-unswitch can later unswitch the loop by this condition which basically // predicates the loop by the widened condition: // // if (n - 1 < len) // for (i = 0; i < n; i++) { // ... // } // else // deoptimize // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/LoopPredication.h" #include "llvm/Pass.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/Analysis/ScalarEvolutionExpander.h" #include "llvm/Analysis/ScalarEvolutionExpressions.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalValue.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Module.h" #include "llvm/IR/PatternMatch.h" #include "llvm/Support/Debug.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/LoopUtils.h" #define DEBUG_TYPE "loop-predication" using namespace llvm; namespace { class LoopPredication { ScalarEvolution *SE; Loop *L; const DataLayout *DL; BasicBlock *Preheader; Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander, IRBuilder<> &Builder); bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander); public: LoopPredication(ScalarEvolution *SE) : SE(SE){}; bool runOnLoop(Loop *L); }; class LoopPredicationLegacyPass : public LoopPass { public: static char ID; LoopPredicationLegacyPass() : LoopPass(ID) { initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const override { getLoopAnalysisUsage(AU); } bool runOnLoop(Loop *L, LPPassManager &LPM) override { if (skipLoop(L)) return false; auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); LoopPredication LP(SE); return LP.runOnLoop(L); } }; char LoopPredicationLegacyPass::ID = 0; } // end namespace llvm INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication", "Loop predication", false, false) INITIALIZE_PASS_DEPENDENCY(LoopPass) INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication", "Loop predication", false, false) Pass *llvm::createLoopPredicationPass() { return new LoopPredicationLegacyPass(); } PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U) { LoopPredication LP(&AR.SE); if (!LP.runOnLoop(&L)) return PreservedAnalyses::all(); return getLoopPassPreservedAnalyses(); } /// If ICI can be widened to a loop invariant condition emits the loop /// invariant condition in the loop preheader and return it, otherwise /// returns None. Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander, IRBuilder<> &Builder) { DEBUG(dbgs() << "Analyzing ICmpInst condition:\n"); DEBUG(ICI->dump()); ICmpInst::Predicate Pred = ICI->getPredicate(); Value *LHS = ICI->getOperand(0); Value *RHS = ICI->getOperand(1); const SCEV *LHSS = SE->getSCEV(LHS); if (isa<SCEVCouldNotCompute>(LHSS)) return None; const SCEV *RHSS = SE->getSCEV(RHS); if (isa<SCEVCouldNotCompute>(RHSS)) return None; // Canonicalize RHS to be loop invariant bound, LHS - a loop computable index if (SE->isLoopInvariant(LHSS, L)) { std::swap(LHS, RHS); std::swap(LHSS, RHSS); Pred = ICmpInst::getSwappedPredicate(Pred); } if (!SE->isLoopInvariant(RHSS, L)) return None; Value *Bound = RHS; const SCEVAddRecExpr *IndexAR = dyn_cast<SCEVAddRecExpr>(LHSS); if (!IndexAR || IndexAR->getLoop() != L) return None; DEBUG(dbgs() << "IndexAR: "); DEBUG(IndexAR->dump()); bool IsIncreasing = false; if (!SE->isMonotonicPredicate(IndexAR, Pred, IsIncreasing)) return None; // If the predicate is increasing the condition can change from false to true // as the loop progresses, in this case take the value on the first iteration // for the widened check. Otherwise the condition can change from true to // false as the loop progresses, so take the value on the last iteration. const SCEV *NewLHSS = IsIncreasing ? IndexAR->getStart() : SE->getSCEVAtScope(IndexAR, L->getParentLoop()); if (NewLHSS == IndexAR) { DEBUG(dbgs() << "Can't compute NewLHSS!"); return None; } DEBUG(dbgs() << "NewLHSS: "); DEBUG(NewLHSS->dump()); if (!SE->isLoopInvariant(NewLHSS, L) || !isSafeToExpand(NewLHSS, *SE)) return None; DEBUG(dbgs() << "NewLHSS is loop invariant and safe to expand. Expand!\n"); Value *NewLHS = Expander.expandCodeFor(NewLHSS, Bound->getType(), Preheader->getTerminator()); return Builder.CreateICmp(Pred, NewLHS, Bound); } bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard, SCEVExpander &Expander) { DEBUG(dbgs() << "Processing guard:\n"); DEBUG(Guard->dump()); IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator())); // The guard condition is expected to be in form of: // cond1 && cond2 && cond3 ... // Iterate over subconditions looking for for icmp conditions which can be // widened across loop iterations. Widening these conditions remember the // resulting list of subconditions in Checks vector. SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0)); SmallPtrSet<Value *, 4> Visited; SmallVector<Value *, 4> Checks; unsigned NumWidened = 0; do { Value *Condition = Worklist.pop_back_val(); if (!Visited.insert(Condition).second) continue; Value *LHS, *RHS; using namespace llvm::PatternMatch; if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) { Worklist.push_back(LHS); Worklist.push_back(RHS); continue; } if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) { if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) { Checks.push_back(NewRangeCheck.getValue()); NumWidened++; continue; } } // Save the condition as is if we can't widen it Checks.push_back(Condition); } while (Worklist.size() != 0); if (NumWidened == 0) return false; // Emit the new guard condition Builder.SetInsertPoint(Guard); Value *LastCheck = nullptr; for (auto *Check : Checks) if (!LastCheck) LastCheck = Check; else LastCheck = Builder.CreateAnd(LastCheck, Check); Guard->setOperand(0, LastCheck); DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); return true; } bool LoopPredication::runOnLoop(Loop *Loop) { L = Loop; DEBUG(dbgs() << "Analyzing "); DEBUG(L->dump()); Module *M = L->getHeader()->getModule(); // There is nothing to do if the module doesn't use guards auto *GuardDecl = M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard)); if (!GuardDecl || GuardDecl->use_empty()) return false; DL = &M->getDataLayout(); Preheader = L->getLoopPreheader(); if (!Preheader) return false; // Collect all the guards into a vector and process later, so as not // to invalidate the instruction iterator. SmallVector<IntrinsicInst *, 4> Guards; for (const auto BB : L->blocks()) for (auto &I : *BB) if (auto *II = dyn_cast<IntrinsicInst>(&I)) if (II->getIntrinsicID() == Intrinsic::experimental_guard) Guards.push_back(II); SCEVExpander Expander(*SE, *DL, "loop-predication"); bool Changed = false; for (auto *Guard : Guards) Changed |= widenGuardConditions(Guard, Expander); return Changed; } <commit_msg>[LoopPredication] Add a new line to debug output in LoopPredication pass<commit_after>//===-- LoopPredication.cpp - Guard based loop predication pass -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The LoopPredication pass tries to convert loop variant range checks to loop // invariant by widening checks across loop iterations. For example, it will // convert // // for (i = 0; i < n; i++) { // guard(i < len); // ... // } // // to // // for (i = 0; i < n; i++) { // guard(n - 1 < len); // ... // } // // After this transformation the condition of the guard is loop invariant, so // loop-unswitch can later unswitch the loop by this condition which basically // predicates the loop by the widened condition: // // if (n - 1 < len) // for (i = 0; i < n; i++) { // ... // } // else // deoptimize // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/LoopPredication.h" #include "llvm/Pass.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/Analysis/ScalarEvolutionExpander.h" #include "llvm/Analysis/ScalarEvolutionExpressions.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalValue.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Module.h" #include "llvm/IR/PatternMatch.h" #include "llvm/Support/Debug.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/LoopUtils.h" #define DEBUG_TYPE "loop-predication" using namespace llvm; namespace { class LoopPredication { ScalarEvolution *SE; Loop *L; const DataLayout *DL; BasicBlock *Preheader; Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander, IRBuilder<> &Builder); bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander); public: LoopPredication(ScalarEvolution *SE) : SE(SE){}; bool runOnLoop(Loop *L); }; class LoopPredicationLegacyPass : public LoopPass { public: static char ID; LoopPredicationLegacyPass() : LoopPass(ID) { initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const override { getLoopAnalysisUsage(AU); } bool runOnLoop(Loop *L, LPPassManager &LPM) override { if (skipLoop(L)) return false; auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); LoopPredication LP(SE); return LP.runOnLoop(L); } }; char LoopPredicationLegacyPass::ID = 0; } // end namespace llvm INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication", "Loop predication", false, false) INITIALIZE_PASS_DEPENDENCY(LoopPass) INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication", "Loop predication", false, false) Pass *llvm::createLoopPredicationPass() { return new LoopPredicationLegacyPass(); } PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U) { LoopPredication LP(&AR.SE); if (!LP.runOnLoop(&L)) return PreservedAnalyses::all(); return getLoopPassPreservedAnalyses(); } /// If ICI can be widened to a loop invariant condition emits the loop /// invariant condition in the loop preheader and return it, otherwise /// returns None. Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander, IRBuilder<> &Builder) { DEBUG(dbgs() << "Analyzing ICmpInst condition:\n"); DEBUG(ICI->dump()); ICmpInst::Predicate Pred = ICI->getPredicate(); Value *LHS = ICI->getOperand(0); Value *RHS = ICI->getOperand(1); const SCEV *LHSS = SE->getSCEV(LHS); if (isa<SCEVCouldNotCompute>(LHSS)) return None; const SCEV *RHSS = SE->getSCEV(RHS); if (isa<SCEVCouldNotCompute>(RHSS)) return None; // Canonicalize RHS to be loop invariant bound, LHS - a loop computable index if (SE->isLoopInvariant(LHSS, L)) { std::swap(LHS, RHS); std::swap(LHSS, RHSS); Pred = ICmpInst::getSwappedPredicate(Pred); } if (!SE->isLoopInvariant(RHSS, L)) return None; Value *Bound = RHS; const SCEVAddRecExpr *IndexAR = dyn_cast<SCEVAddRecExpr>(LHSS); if (!IndexAR || IndexAR->getLoop() != L) return None; DEBUG(dbgs() << "IndexAR: "); DEBUG(IndexAR->dump()); bool IsIncreasing = false; if (!SE->isMonotonicPredicate(IndexAR, Pred, IsIncreasing)) return None; // If the predicate is increasing the condition can change from false to true // as the loop progresses, in this case take the value on the first iteration // for the widened check. Otherwise the condition can change from true to // false as the loop progresses, so take the value on the last iteration. const SCEV *NewLHSS = IsIncreasing ? IndexAR->getStart() : SE->getSCEVAtScope(IndexAR, L->getParentLoop()); if (NewLHSS == IndexAR) { DEBUG(dbgs() << "Can't compute NewLHSS!\n"); return None; } DEBUG(dbgs() << "NewLHSS: "); DEBUG(NewLHSS->dump()); if (!SE->isLoopInvariant(NewLHSS, L) || !isSafeToExpand(NewLHSS, *SE)) return None; DEBUG(dbgs() << "NewLHSS is loop invariant and safe to expand. Expand!\n"); Value *NewLHS = Expander.expandCodeFor(NewLHSS, Bound->getType(), Preheader->getTerminator()); return Builder.CreateICmp(Pred, NewLHS, Bound); } bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard, SCEVExpander &Expander) { DEBUG(dbgs() << "Processing guard:\n"); DEBUG(Guard->dump()); IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator())); // The guard condition is expected to be in form of: // cond1 && cond2 && cond3 ... // Iterate over subconditions looking for for icmp conditions which can be // widened across loop iterations. Widening these conditions remember the // resulting list of subconditions in Checks vector. SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0)); SmallPtrSet<Value *, 4> Visited; SmallVector<Value *, 4> Checks; unsigned NumWidened = 0; do { Value *Condition = Worklist.pop_back_val(); if (!Visited.insert(Condition).second) continue; Value *LHS, *RHS; using namespace llvm::PatternMatch; if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) { Worklist.push_back(LHS); Worklist.push_back(RHS); continue; } if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) { if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) { Checks.push_back(NewRangeCheck.getValue()); NumWidened++; continue; } } // Save the condition as is if we can't widen it Checks.push_back(Condition); } while (Worklist.size() != 0); if (NumWidened == 0) return false; // Emit the new guard condition Builder.SetInsertPoint(Guard); Value *LastCheck = nullptr; for (auto *Check : Checks) if (!LastCheck) LastCheck = Check; else LastCheck = Builder.CreateAnd(LastCheck, Check); Guard->setOperand(0, LastCheck); DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); return true; } bool LoopPredication::runOnLoop(Loop *Loop) { L = Loop; DEBUG(dbgs() << "Analyzing "); DEBUG(L->dump()); Module *M = L->getHeader()->getModule(); // There is nothing to do if the module doesn't use guards auto *GuardDecl = M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard)); if (!GuardDecl || GuardDecl->use_empty()) return false; DL = &M->getDataLayout(); Preheader = L->getLoopPreheader(); if (!Preheader) return false; // Collect all the guards into a vector and process later, so as not // to invalidate the instruction iterator. SmallVector<IntrinsicInst *, 4> Guards; for (const auto BB : L->blocks()) for (auto &I : *BB) if (auto *II = dyn_cast<IntrinsicInst>(&I)) if (II->getIntrinsicID() == Intrinsic::experimental_guard) Guards.push_back(II); SCEVExpander Expander(*SE, *DL, "loop-predication"); bool Changed = false; for (auto *Guard : Guards) Changed |= widenGuardConditions(Guard, Expander); return Changed; } <|endoftext|>
<commit_before>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #pragma once #include "database.hh" #include "query-request.hh" #include "query-result.hh" #include "query-result-set.hh" #include "core/distributed.hh" #include "db/consistency_level.hh" namespace service { class abstract_write_response_handler; class abstract_read_executor; class storage_proxy /*implements StorageProxyMBean*/ { struct rh_entry { std::unique_ptr<abstract_write_response_handler> handler; timer<> expire_timer; rh_entry(std::unique_ptr<abstract_write_response_handler>&& h, std::function<void()>&& cb); }; public: using response_id_type = uint64_t; private: distributed<database>& _db; response_id_type _next_response_id = 0; std::unordered_map<response_id_type, rh_entry> _response_handlers; constexpr static size_t _max_hints_in_progress = 128; // origin multiplies by FBUtilities.getAvailableProcessors() but we already sharded size_t _total_hints_in_progress = 0; std::unordered_map<gms::inet_address, size_t> _hints_in_progress; private: void init_messaging_service(); future<foreign_ptr<lw_shared_ptr<query::result>>> query_singular(lw_shared_ptr<query::read_command> cmd, std::vector<query::partition_range>&& partition_ranges, db::consistency_level cl); response_id_type register_response_handler(std::unique_ptr<abstract_write_response_handler>&& h); void remove_response_handler(response_id_type id); void got_response(response_id_type id, gms::inet_address from); future<> response_wait(response_id_type id); abstract_write_response_handler& get_write_response_handler(storage_proxy::response_id_type id); response_id_type create_write_response_handler(keyspace& ks, db::consistency_level cl, frozen_mutation&& mutation, std::unordered_set<gms::inet_address> targets, std::vector<gms::inet_address>& pending_endpoints); future<> send_to_live_endpoints(response_id_type response_id, sstring local_data_center); template<typename Range> size_t hint_to_dead_endpoints(lw_shared_ptr<const frozen_mutation> m, const Range& targets); bool cannot_hint(gms::inet_address target); size_t get_hints_in_progress_for(gms::inet_address target); bool should_hint(gms::inet_address ep); bool submit_hint(lw_shared_ptr<const frozen_mutation> m, gms::inet_address target); std::vector<gms::inet_address> get_live_sorted_endpoints(keyspace& ks, const dht::token& token); ::shared_ptr<abstract_read_executor> get_read_executor(lw_shared_ptr<query::read_command> cmd, query::partition_range pr, db::consistency_level cl); future<foreign_ptr<lw_shared_ptr<query::result>>> query_singular_local(lw_shared_ptr<query::read_command> cmd, const query::partition_range& pr); future<query::result_digest> query_singular_local_digest(lw_shared_ptr<query::read_command> cmd, const query::partition_range& pr); public: storage_proxy(distributed<database>& db); ~storage_proxy(); distributed<database>& get_db() { return _db; } future<> mutate_locally(const mutation& m); future<> mutate_locally(const frozen_mutation& m); future<> mutate_locally(std::vector<mutation> mutations); /** * Use this method to have these Mutations applied * across all replicas. This method will take care * of the possibility of a replica being down and hint * the data across to some other replica. * * @param mutations the mutations to be applied across the replicas * @param consistency_level the consistency level for the operation */ future<> mutate(std::vector<mutation> mutations, db::consistency_level cl); future<> mutate_with_triggers(std::vector<mutation> mutations, db::consistency_level cl, bool should_mutate_atomically); /** * See mutate. Adds additional steps before and after writing a batch. * Before writing the batch (but after doing availability check against the FD for the row replicas): * write the entire batch to a batchlog elsewhere in the cluster. * After: remove the batchlog entry (after writing hints for the batch rows, if necessary). * * @param mutations the Mutations to be applied across the replicas * @param consistency_level the consistency level for the operation */ future<> mutate_atomically(std::vector<mutation> mutations, db::consistency_level cl); future<foreign_ptr<lw_shared_ptr<query::result>>> query(lw_shared_ptr<query::read_command> cmd, std::vector<query::partition_range>&& partition_ranges, db::consistency_level cl); future<foreign_ptr<lw_shared_ptr<query::result>>> query_local(lw_shared_ptr<query::read_command> cmd, std::vector<query::partition_range>&& partition_ranges); future<lw_shared_ptr<query::result_set>> query_local(const sstring& ks_name, const sstring& cf_name, const dht::decorated_key& key, const std::vector<query::clustering_range>& row_ranges = {query::clustering_range::make_open_ended_both_sides()}); future<> stop() { return make_ready_future<>(); } friend class abstract_read_executor; }; } <commit_msg>Storage proxy: Adding a stats object<commit_after>/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2015 Cloudius Systems * * Modified by Cloudius Systems */ #pragma once #include "database.hh" #include "query-request.hh" #include "query-result.hh" #include "query-result-set.hh" #include "core/distributed.hh" #include "db/consistency_level.hh" namespace service { class abstract_write_response_handler; class abstract_read_executor; class storage_proxy /*implements StorageProxyMBean*/ { struct rh_entry { std::unique_ptr<abstract_write_response_handler> handler; timer<> expire_timer; rh_entry(std::unique_ptr<abstract_write_response_handler>&& h, std::function<void()>&& cb); }; public: struct stats { uint64_t read_timeouts; uint64_t read_unavailables; uint64_t range_slice_timeouts; uint64_t range_slice_unavailables; uint64_t write_timeouts; uint64_t write_unavailables; }; using response_id_type = uint64_t; private: distributed<database>& _db; response_id_type _next_response_id = 0; std::unordered_map<response_id_type, rh_entry> _response_handlers; constexpr static size_t _max_hints_in_progress = 128; // origin multiplies by FBUtilities.getAvailableProcessors() but we already sharded size_t _total_hints_in_progress = 0; std::unordered_map<gms::inet_address, size_t> _hints_in_progress; stats _stats; private: void init_messaging_service(); future<foreign_ptr<lw_shared_ptr<query::result>>> query_singular(lw_shared_ptr<query::read_command> cmd, std::vector<query::partition_range>&& partition_ranges, db::consistency_level cl); response_id_type register_response_handler(std::unique_ptr<abstract_write_response_handler>&& h); void remove_response_handler(response_id_type id); void got_response(response_id_type id, gms::inet_address from); future<> response_wait(response_id_type id); abstract_write_response_handler& get_write_response_handler(storage_proxy::response_id_type id); response_id_type create_write_response_handler(keyspace& ks, db::consistency_level cl, frozen_mutation&& mutation, std::unordered_set<gms::inet_address> targets, std::vector<gms::inet_address>& pending_endpoints); future<> send_to_live_endpoints(response_id_type response_id, sstring local_data_center); template<typename Range> size_t hint_to_dead_endpoints(lw_shared_ptr<const frozen_mutation> m, const Range& targets); bool cannot_hint(gms::inet_address target); size_t get_hints_in_progress_for(gms::inet_address target); bool should_hint(gms::inet_address ep); bool submit_hint(lw_shared_ptr<const frozen_mutation> m, gms::inet_address target); std::vector<gms::inet_address> get_live_sorted_endpoints(keyspace& ks, const dht::token& token); ::shared_ptr<abstract_read_executor> get_read_executor(lw_shared_ptr<query::read_command> cmd, query::partition_range pr, db::consistency_level cl); future<foreign_ptr<lw_shared_ptr<query::result>>> query_singular_local(lw_shared_ptr<query::read_command> cmd, const query::partition_range& pr); future<query::result_digest> query_singular_local_digest(lw_shared_ptr<query::read_command> cmd, const query::partition_range& pr); public: storage_proxy(distributed<database>& db); ~storage_proxy(); distributed<database>& get_db() { return _db; } future<> mutate_locally(const mutation& m); future<> mutate_locally(const frozen_mutation& m); future<> mutate_locally(std::vector<mutation> mutations); /** * Use this method to have these Mutations applied * across all replicas. This method will take care * of the possibility of a replica being down and hint * the data across to some other replica. * * @param mutations the mutations to be applied across the replicas * @param consistency_level the consistency level for the operation */ future<> mutate(std::vector<mutation> mutations, db::consistency_level cl); future<> mutate_with_triggers(std::vector<mutation> mutations, db::consistency_level cl, bool should_mutate_atomically); /** * See mutate. Adds additional steps before and after writing a batch. * Before writing the batch (but after doing availability check against the FD for the row replicas): * write the entire batch to a batchlog elsewhere in the cluster. * After: remove the batchlog entry (after writing hints for the batch rows, if necessary). * * @param mutations the Mutations to be applied across the replicas * @param consistency_level the consistency level for the operation */ future<> mutate_atomically(std::vector<mutation> mutations, db::consistency_level cl); future<foreign_ptr<lw_shared_ptr<query::result>>> query(lw_shared_ptr<query::read_command> cmd, std::vector<query::partition_range>&& partition_ranges, db::consistency_level cl); future<foreign_ptr<lw_shared_ptr<query::result>>> query_local(lw_shared_ptr<query::read_command> cmd, std::vector<query::partition_range>&& partition_ranges); future<lw_shared_ptr<query::result_set>> query_local(const sstring& ks_name, const sstring& cf_name, const dht::decorated_key& key, const std::vector<query::clustering_range>& row_ranges = {query::clustering_range::make_open_ended_both_sides()}); future<> stop() { return make_ready_future<>(); } friend class abstract_read_executor; const stats& get_stats() const { return _stats; } }; } <|endoftext|>
<commit_before>#included "Header.h" //----------------------------------------------------// struct Statistics(){}; //----------------------------------------------------// <commit_msg>Delete Statistics.cpp<commit_after><|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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 <gtest/gtest.h> #include "zk.hpp" #include "../common/membership.hpp" using namespace std; using namespace pfi::lang; namespace jubatus { namespace common { TEST(zk, zk_trivial) { pfi::lang::shared_ptr<jubatus::common::lock_service> zk_; zk_ = pfi::lang::shared_ptr<jubatus::common::lock_service> (common::create_lock_service("zk", "localhost:2181", 1024, "test.log")); std::string engine_name, engine_root; std::string name_, path; std::string name1_, path1; engine_name = "test"; engine_root = ACTOR_BASE_PATH + "/" + engine_name; name_ = build_loc_str("localhost", 10000); build_actor_path(path, engine_name, name_); name1_ = build_loc_str("localhost", 10001); build_actor_path(path1, engine_name, name1_); zk_->create(JUBATUS_BASE_PATH, ""); zk_->create(ACTOR_BASE_PATH, ""); zk_->create(engine_root, ""); zk_->create(path, "hoge0", true); ASSERT_EQ(true, zk_->exists(path)); ASSERT_EQ(false, zk_->exists(path1)); zk_->create(path1, "hoge1", true); ASSERT_EQ(true, zk_->exists(path1)); std::string dat; zk_->read(path, dat); ASSERT_EQ("hoge0", dat); std::vector<std::string> pathlist; zk_->list(engine_root, pathlist); ASSERT_EQ((unsigned int)2, pathlist.size()); std::string name_e; zk_->hd_list(engine_root, name_e); ASSERT_EQ(name_e , name_); ASSERT_EQ("zk", zk_->type()); zk_->remove(path1); ASSERT_EQ(false, zk_->exists(path1)); zk_->remove(path); } } // common } // jubatus <commit_msg>Refactoring zk_test: refs #131<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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 <gtest/gtest.h> #include "lock_service.hpp" #include "../common/membership.hpp" using namespace std; using namespace pfi::lang; using jubatus::common::lock_service; using jubatus::common::ACTOR_BASE_PATH; using jubatus::common::JUBATUS_BASE_PATH; class zk_trivial : public testing::Test { protected: void SetUp() { zk_ = pfi::lang::shared_ptr<lock_service> (jubatus::common::create_lock_service("zk", "localhost:2181", 1024, "test.log")); root_path = "/jubatus_zk_test_root"; engine_name = "jubatus_zk_test"; engine_root = ACTOR_BASE_PATH + "/" + engine_name; } void TearDown() { if (!zk_) return; if (zk_->exists(root_path)) zk_->remove(root_path); if (zk_->exists(engine_root)) zk_->remove(engine_root); if (zk_->exists(ACTOR_BASE_PATH)) zk_->remove(ACTOR_BASE_PATH); if (zk_->exists(JUBATUS_BASE_PATH)) zk_->remove(JUBATUS_BASE_PATH); } string root_path; string engine_name; string engine_root; pfi::lang::shared_ptr<lock_service> zk_; }; TEST_F(zk_trivial, create_exists_remove) { const string dir = root_path + "/test1"; ASSERT_FALSE(zk_->exists(root_path)); ASSERT_FALSE(zk_->exists(dir)); zk_->create(root_path, ""); zk_->create(dir, ""); ASSERT_TRUE(zk_->exists(root_path)); ASSERT_TRUE(zk_->exists(dir)); vector<string> pathlist; zk_->list(root_path, pathlist); EXPECT_EQ(1u, pathlist.size()); zk_->remove(dir); zk_->remove(root_path); ASSERT_FALSE(zk_->exists(root_path)); ASSERT_FALSE(zk_->exists(dir)); } TEST_F(zk_trivial, non_exists) { ASSERT_FALSE(zk_->exists("/zktest_non_exists_path")); } TEST_F(zk_trivial, create_read) { zk_->create(root_path, "hoge0", true); string dat; zk_->read(root_path, dat); ASSERT_EQ("hoge0", dat); zk_->remove(root_path); } // TODO: test lock_service::hd_list() TEST_F(zk_trivial, create_seq) { string seqfile; zk_->create_seq(root_path, seqfile); EXPECT_LT(root_path.size(), seqfile.size()); if (!seqfile.empty()) zk_->remove(seqfile); } TEST_F(zk_trivial, create_id) { zk_->create(root_path, ""); ASSERT_TRUE(zk_->exists(root_path)); uint64_t id_initial = zk_->create_id(root_path, 1); EXPECT_EQ(0x100000000llu + 1, id_initial); uint64_t id_second = zk_->create_id(root_path, 1); EXPECT_EQ(0x100000000llu + 2, id_second); zk_->remove(root_path); } // TODO: test lock_service_mutex TEST_F(zk_trivial, trivial_with_membershp) { using namespace jubatus::common; string name_, path; string name1_, path1; vector<string> pathlist; zk_->list(engine_root, pathlist); const size_t engine_root_initial_size = pathlist.size(); EXPECT_EQ(0u, engine_root_initial_size); name_ = build_loc_str("localhost", 10000); build_actor_path(path, engine_name, name_); name1_ = build_loc_str("localhost", 10001); build_actor_path(path1, engine_name, name1_); zk_->create(JUBATUS_BASE_PATH, ""); zk_->create(ACTOR_BASE_PATH, ""); zk_->create(engine_root, ""); zk_->create(path, "hoge0", true); ASSERT_EQ(true, zk_->exists(path)); ASSERT_EQ(false, zk_->exists(path1)); zk_->create(path1, "hoge1", true); ASSERT_EQ(true, zk_->exists(path1)); string dat; zk_->read(path, dat); ASSERT_EQ("hoge0", dat); zk_->list(engine_root, pathlist); ASSERT_EQ(engine_root_initial_size + 2, pathlist.size()); string name_e; zk_->hd_list(engine_root, name_e); ASSERT_EQ(name_e , name_); ASSERT_EQ("zk", zk_->type()); zk_->remove(path1); ASSERT_EQ(false, zk_->exists(path1)); zk_->remove(path); } <|endoftext|>
<commit_before>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include <gtest/gtest.h> #include "lock_service.hpp" #include "../common/membership.hpp" using namespace std; using namespace pfi::lang; using jubatus::common::lock_service; using jubatus::common::ACTOR_BASE_PATH; using jubatus::common::JUBATUS_BASE_PATH; class zk_trivial : public testing::Test { protected: void SetUp() { zk_ = pfi::lang::shared_ptr<lock_service> (jubatus::common::create_lock_service("zk", "localhost:2181", 1024, "test.log")); root_path = "/jubatus_zk_test_root"; engine_name = "jubatus_zk_test"; engine_root = ACTOR_BASE_PATH + "/" + engine_name; } void TearDown() { if (!zk_) return; if (zk_->exists(root_path)) zk_->remove(root_path); if (zk_->exists(engine_root)) zk_->remove(engine_root); if (zk_->exists(ACTOR_BASE_PATH)) zk_->remove(ACTOR_BASE_PATH); if (zk_->exists(JUBATUS_BASE_PATH)) zk_->remove(JUBATUS_BASE_PATH); } string root_path; string engine_name; string engine_root; pfi::lang::shared_ptr<lock_service> zk_; }; TEST_F(zk_trivial, create_exists_remove) { const string dir = root_path + "/test1"; ASSERT_FALSE(zk_->exists(root_path)); ASSERT_FALSE(zk_->exists(dir)); zk_->create(root_path, ""); zk_->create(dir, ""); ASSERT_TRUE(zk_->exists(root_path)); ASSERT_TRUE(zk_->exists(dir)); vector<string> pathlist; zk_->list(root_path, pathlist); EXPECT_EQ(1u, pathlist.size()); zk_->remove(dir); zk_->remove(root_path); ASSERT_FALSE(zk_->exists(root_path)); ASSERT_FALSE(zk_->exists(dir)); } TEST_F(zk_trivial, non_exists) { ASSERT_FALSE(zk_->exists("/zktest_non_exists_path")); } TEST_F(zk_trivial, create_read) { zk_->create(root_path, "hoge0", true); string dat; zk_->read(root_path, dat); ASSERT_EQ("hoge0", dat); zk_->remove(root_path); } // TODO: test lock_service::hd_list() TEST_F(zk_trivial, create_seq) { string seqfile; zk_->create_seq(root_path, seqfile); EXPECT_LT(root_path.size(), seqfile.size()); if (!seqfile.empty()) zk_->remove(seqfile); } TEST_F(zk_trivial, create_id) { zk_->create(root_path, ""); ASSERT_TRUE(zk_->exists(root_path)); uint64_t id_initial = 0, id_second = 0; EXPECT_TRUE(zk_->create_id(root_path, 1, id_initial)); EXPECT_EQ(0x100000000llu + 1, id_initial); EXPECT_TRUE(zk_->create_id(root_path, 1, id_second)); EXPECT_EQ(0x100000000llu + 2, id_second); zk_->remove(root_path); } // TODO: test lock_service_mutex TEST_F(zk_trivial, trivial_with_membershp) { using namespace jubatus::common; string name_, path; string name1_, path1; vector<string> pathlist; zk_->list(engine_root, pathlist); const size_t engine_root_initial_size = pathlist.size(); EXPECT_EQ(0u, engine_root_initial_size); name_ = build_loc_str("localhost", 10000); build_actor_path(path, engine_name, name_); name1_ = build_loc_str("localhost", 10001); build_actor_path(path1, engine_name, name1_); zk_->create(JUBATUS_BASE_PATH, ""); zk_->create(ACTOR_BASE_PATH, ""); zk_->create(engine_root, ""); zk_->create(path, "hoge0", true); ASSERT_EQ(true, zk_->exists(path)); ASSERT_EQ(false, zk_->exists(path1)); zk_->create(path1, "hoge1", true); ASSERT_EQ(true, zk_->exists(path1)); string dat; zk_->read(path, dat); ASSERT_EQ("hoge0", dat); zk_->list(engine_root, pathlist); ASSERT_EQ(engine_root_initial_size + 2, pathlist.size()); string name_e; zk_->hd_list(engine_root, name_e); ASSERT_EQ(name_e , name_); ASSERT_EQ("zk", zk_->type()); zk_->remove(path1); ASSERT_EQ(false, zk_->exists(path1)); zk_->remove(path); } <commit_msg>add test<commit_after>// Jubatus: Online machine learning framework for distributed environment // Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation. // // 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #include <gtest/gtest.h> #include "lock_service.hpp" #include "../common/membership.hpp" using namespace std; using namespace pfi::lang; using jubatus::common::lock_service; using jubatus::common::ACTOR_BASE_PATH; using jubatus::common::JUBATUS_BASE_PATH; class zk_trivial : public testing::Test { protected: void SetUp() { zk_ = pfi::lang::shared_ptr<lock_service> (jubatus::common::create_lock_service("zk", "localhost:2181", 1024, "test.log")); root_path = "/jubatus_zk_test_root"; engine_name = "jubatus_zk_test"; engine_root = ACTOR_BASE_PATH + "/" + engine_name; } void TearDown() { if (!zk_) return; if (zk_->exists(root_path)) zk_->remove(root_path); if (zk_->exists(engine_root)) zk_->remove(engine_root); if (zk_->exists(ACTOR_BASE_PATH)) zk_->remove(ACTOR_BASE_PATH); if (zk_->exists(JUBATUS_BASE_PATH)) zk_->remove(JUBATUS_BASE_PATH); } string root_path; string engine_name; string engine_root; pfi::lang::shared_ptr<lock_service> zk_; }; TEST_F(zk_trivial, create_exists_remove) { const string dir = root_path + "/test1"; ASSERT_FALSE(zk_->exists(root_path)); ASSERT_FALSE(zk_->exists(dir)); zk_->create(root_path, ""); zk_->create(dir, ""); ASSERT_TRUE(zk_->exists(root_path)); ASSERT_TRUE(zk_->exists(dir)); vector<string> pathlist; zk_->list(root_path, pathlist); EXPECT_EQ(1u, pathlist.size()); zk_->remove(dir); zk_->remove(root_path); ASSERT_FALSE(zk_->exists(root_path)); ASSERT_FALSE(zk_->exists(dir)); } TEST_F(zk_trivial, non_exists) { ASSERT_FALSE(zk_->exists("/zktest_non_exists_path")); } TEST_F(zk_trivial, create_set_read) { zk_->create(root_path, "hoge0", true); string dat; zk_->read(root_path, dat); ASSERT_EQ("hoge0", dat); zk_->set(root_path, "hoge1"); string dat2; zk_->read(root_path, dat2); ASSERT_EQ("hoge1", dat2); zk_->remove(root_path); } // TODO: test lock_service::hd_list() TEST_F(zk_trivial, create_seq) { string seqfile; zk_->create_seq(root_path, seqfile); EXPECT_LT(root_path.size(), seqfile.size()); if (!seqfile.empty()) zk_->remove(seqfile); } TEST_F(zk_trivial, create_id) { zk_->create(root_path, ""); ASSERT_TRUE(zk_->exists(root_path)); uint64_t id_initial = 0, id_second = 0; EXPECT_TRUE(zk_->create_id(root_path, 1, id_initial)); EXPECT_EQ(0x100000000llu + 1, id_initial); EXPECT_TRUE(zk_->create_id(root_path, 1, id_second)); EXPECT_EQ(0x100000000llu + 2, id_second); zk_->remove(root_path); } // TODO: test lock_service_mutex TEST_F(zk_trivial, trivial_with_membershp) { using namespace jubatus::common; string name_, path; string name1_, path1; vector<string> pathlist; zk_->list(engine_root, pathlist); const size_t engine_root_initial_size = pathlist.size(); EXPECT_EQ(0u, engine_root_initial_size); name_ = build_loc_str("localhost", 10000); build_actor_path(path, engine_name, name_); name1_ = build_loc_str("localhost", 10001); build_actor_path(path1, engine_name, name1_); zk_->create(JUBATUS_BASE_PATH, ""); zk_->create(ACTOR_BASE_PATH, ""); zk_->create(engine_root, ""); zk_->create(path, "hoge0", true); ASSERT_EQ(true, zk_->exists(path)); ASSERT_EQ(false, zk_->exists(path1)); zk_->create(path1, "hoge1", true); ASSERT_EQ(true, zk_->exists(path1)); string dat; zk_->read(path, dat); ASSERT_EQ("hoge0", dat); zk_->list(engine_root, pathlist); ASSERT_EQ(engine_root_initial_size + 2, pathlist.size()); string name_e; zk_->hd_list(engine_root, name_e); ASSERT_EQ(name_e , name_); ASSERT_EQ("zk", zk_->type()); zk_->remove(path1); ASSERT_EQ(false, zk_->exists(path1)); zk_->remove(path); } <|endoftext|>
<commit_before>/* * labyrinth.cpp * * Created on: 15.01.2015 г. * Author: trifon */ #include <iostream> using namespace std; const int MAX = 100; char labyrinth[MAX][MAX]; int m, n; void readLabyrinth() { cin >> m >> n; cin.ignore(); for(int i = 0; i < m; i++) cin.getline(labyrinth[i], n + 2); } void printLabyrinth() { for(int i = 0; i < m; i++) cout << labyrinth[i] << endl; } void findStart(int& x, int& y) { for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) if (labyrinth[i][j] == 'o') { x = i; y = j; return; } } // findTreasure(x, y) == true <-> // можем от (x, y) да достигнем до съкровището bool findTreasure(int x, int y) { cout << "Пробваме да стъпим на (" << x << "," << y << ")" << endl; if (x < 0 || y < 0 || x >= m || y >= n || labyrinth[x][y] == '*' || labyrinth[x][y] == '"') // лесен лош случай return false; if (labyrinth[x][y] == '$') { // лесен хубав случай cout << "Намерихме съкровището на (" << x << "," << y << ")!\n"; cout << "Направихме " << move << " стъпки!\n"; return true; } labyrinth[x][y] = '"'; // стъпка надолу if (findTreasure(x + 1, y)) return true; // стъпка нагоре if (findTreasure(x - 1, y)) return true; // стъпка наляво if (findTreasure(x, y - 1)) return true; // стъпка надясно if (findTreasure(x, y + 1)) return true; labyrinth[x][y] = 'X'; return false; } int main() { readLabyrinth(); printLabyrinth(); int startx, starty; findStart(startx, starty); cout << "Започваме от " << "(" << startx << "," << starty << ")\n"; cout << findTreasure(startx, starty) << endl; printLabyrinth(); return 0; } <commit_msg>Проследяване на ходовете при обхождането на лабиринта.<commit_after>/* * labyrinth.cpp * * Created on: 15.01.2015 г. * Author: trifon */ #include <iostream> using namespace std; const int MAX = 100; char labyrinth[MAX][MAX]; int m, n; void readLabyrinth() { cin >> m >> n; cin.ignore(); for(int i = 0; i < m; i++) cin.getline(labyrinth[i], n + 2); } void printLabyrinth() { for(int i = 0; i < m; i++) cout << labyrinth[i] << endl; } void findStart(int& x, int& y) { for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) if (labyrinth[i][j] == 'o') { x = i; y = j; return; } } // findTreasure(x, y) == true <-> // можем от (x, y) да достигнем до съкровището bool findTreasure(int x, int y, int move) { cout << "Пробваме да стъпим на (" << x << "," << y << ")" << endl; if (x < 0 || y < 0 || x >= m || y >= n || labyrinth[x][y] == '*' || labyrinth[x][y] >= '0' && labyrinth[x][y] <= '9') // лесен лош случай return false; if (labyrinth[x][y] == '$') { // лесен хубав случай cout << "Намерихме съкровището на (" << x << "," << y << ")!\n"; cout << "Направихме " << move << " стъпки!\n"; return true; } //labyrinth[x][y] = '"'; labyrinth[x][y] = '0' + (move % 10); // стъпка надолу if (findTreasure(x + 1, y, move + 1)) return true; // стъпка нагоре if (findTreasure(x - 1, y, move + 1)) return true; // стъпка наляво if (findTreasure(x, y - 1, move + 1)) return true; // стъпка надясно if (findTreasure(x, y + 1, move + 1)) return true; labyrinth[x][y] = 'X'; return false; } int main() { readLabyrinth(); printLabyrinth(); int startx, starty; findStart(startx, starty); cout << "Започваме от " << "(" << startx << "," << starty << ")\n"; cout << findTreasure(startx, starty, 0) << endl; printLabyrinth(); return 0; } <|endoftext|>
<commit_before>/* * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands. * See the copyright notice in the ACK home directory, in the file "Copyright". * * Author: Ceriel J.H. Jacobs */ /* C A S E S T A T E M E N T C O D E G E N E R A T I O N */ /* $Header$ */ /* Generation of case statements is done by first creating a description structure for the statement, build a list of the case-labels, then generating a case description in the code, and generating either CSA or CSB, and then generating code for the cases themselves. */ #include "debug.h" #include <em_label.h> #include <em_arith.h> #include <em_code.h> #include <alloc.h> #include <assert.h> #include "Lpars.h" #include "type.h" #include "LLlex.h" #include "node.h" #include "desig.h" #include "walk.h" #include "chk_expr.h" #include "def.h" #include "density.h" struct switch_hdr { label sh_break; /* label of statement after this one */ label sh_default; /* label of ELSE part, or 0 */ int sh_nrofentries; /* number of cases */ t_type *sh_type; /* type of case expression */ arith sh_lowerbd; /* lowest case label */ arith sh_upperbd; /* highest case label */ struct case_entry *sh_entries; /* the cases with their generated labels */ }; /* STATICALLOCDEF "switch_hdr" 5 */ struct case_entry { struct case_entry *ce_next; /* next in list */ label ce_label; /* generated label */ arith ce_low, ce_up; /* lower and upper bound of range */ }; /* STATICALLOCDEF "case_entry" 20 */ /* The constant DENSITY determines when CSA and when CSB instructions are generated. Reasonable values are: 2, 3, 4. On machines that have lots of address space and memory, higher values might also be reasonable. On these machines the density of jump tables may be lower. */ compact(nr, low, up) arith low, up; { /* Careful! up - low might not fit in an arith. And then, the test "up-low < 0" might also not work to detect this situation! Or is this just a bug in the M68020/M68000? */ arith diff = up - low; return (nr != 0 && diff >= 0 && fit(diff, (int) word_size) && diff / nr <= (DENSITY - 1)); } #define nd_lab nd_symb int CaseCode(nd, exitlabel, end_reached) t_node *nd; label exitlabel; { /* Check the expression, stack a new case header and fill in the necessary fields. "exitlabel" is the exit-label of the closest enclosing LOOP-statement, or 0. */ register struct switch_hdr *sh = new_switch_hdr(); register t_node *pnode = nd; register struct case_entry *ce; register arith val; label CaseDescrLab; int rval; assert(pnode->nd_class == Stat && pnode->nd_symb == CASE); if (ChkExpression(&(pnode->nd_LEFT))) { MkCoercion(&(pnode->nd_LEFT),BaseType(pnode->nd_LEFT->nd_type)); CodePExpr(pnode->nd_LEFT); } sh->sh_type = pnode->nd_LEFT->nd_type; sh->sh_break = ++text_label; /* Now, create case label list */ while (pnode = pnode->nd_RIGHT) { if (pnode->nd_class == Link && pnode->nd_symb == '|') { if (pnode->nd_LEFT) { /* non-empty case */ pnode->nd_LEFT->nd_lab = ++text_label; AddCases(sh, /* to descriptor */ pnode->nd_LEFT->nd_LEFT, /* of case labels */ (label) pnode->nd_LEFT->nd_lab /* and code label */ ); } } else { /* Else part */ sh->sh_default = ++text_label; break; } } if (!sh->sh_nrofentries) { /* There were no cases, so we have to check the case-expression here */ if (! (sh->sh_type->tp_fund & T_DISCRETE)) { node_error(nd, "illegal type in CASE-expression"); } } /* Now generate code for the switch itself First the part that CSA and CSB descriptions have in common. */ CaseDescrLab = ++data_label; /* the rom must have a label */ C_df_dlb(CaseDescrLab); if (sh->sh_default) C_rom_ilb(sh->sh_default); else C_rom_ucon("0", pointer_size); if (compact(sh->sh_nrofentries, sh->sh_lowerbd, sh->sh_upperbd)) { /* CSA */ int gen = 1; ce = sh->sh_entries; while (! ce->ce_label) ce = ce->ce_next; C_rom_cst((arith) 0); C_rom_cst(sh->sh_upperbd - sh->sh_lowerbd); for (val = sh->sh_lowerbd; val <= sh->sh_upperbd; val++) { assert(ce); if (gen || val == ce->ce_low) { gen = 1; C_rom_ilb(ce->ce_label); if (val == ce->ce_up) { gen = 0; ce = ce->ce_next; while (! ce->ce_label) ce = ce->ce_next; } } else if (sh->sh_default) C_rom_ilb(sh->sh_default); else C_rom_ucon("0", pointer_size); } C_loc(sh->sh_lowerbd); C_sbu(word_size); c_lae_dlb(CaseDescrLab); /* perform the switch */ C_csa(word_size); } else { /* CSB */ C_rom_cst((arith)sh->sh_nrofentries); for (ce = sh->sh_entries; ce; ce = ce->ce_next) { /* generate the entries: value + prog.label */ if (! ce->ce_label) continue; val = ce->ce_low; do { C_rom_cst(val); C_rom_ilb(ce->ce_label); } while (val++ != ce->ce_up); } c_lae_dlb(CaseDescrLab); /* perform the switch */ C_csb(word_size); } /* Now generate code for the cases */ pnode = nd; rval = 0; while (pnode = pnode->nd_RIGHT) { if (pnode->nd_class == Link && pnode->nd_symb == '|') { if (pnode->nd_LEFT) { rval |= LblWalkNode((label) pnode->nd_LEFT->nd_lab, pnode->nd_LEFT->nd_RIGHT, exitlabel, end_reached); C_bra(sh->sh_break); } } else { /* Else part */ assert(sh->sh_default != 0); rval |= LblWalkNode(sh->sh_default, pnode, exitlabel, end_reached); break; } } def_ilb(sh->sh_break); FreeSh(sh); return rval; } FreeSh(sh) register struct switch_hdr *sh; { /* free the allocated switch structure */ register struct case_entry *ce; ce = sh->sh_entries; while (ce) { struct case_entry *tmp = ce->ce_next; free_case_entry(ce); ce = tmp; } free_switch_hdr(sh); } AddCases(sh, node, lbl) struct switch_hdr *sh; register t_node *node; label lbl; { /* Add case labels to the case label list */ if (node->nd_class == Link) { if (node->nd_symb == UPTO) { assert(node->nd_LEFT->nd_class == Value); assert(node->nd_RIGHT->nd_class == Value); AddOneCase(sh, node->nd_LEFT, node->nd_RIGHT, lbl); return; } assert(node->nd_symb == ','); AddCases(sh, node->nd_LEFT, lbl); AddCases(sh, node->nd_RIGHT, lbl); return; } assert(node->nd_class == Value); AddOneCase(sh, node, node, lbl); } AddOneCase(sh, lnode, rnode, lbl) register struct switch_hdr *sh; t_node *lnode, *rnode; label lbl; { register struct case_entry *ce = new_case_entry(); register struct case_entry *c1 = sh->sh_entries, *c2 = 0; int fund = sh->sh_type->tp_fund; arith diff; if (! ChkCompat(&lnode, sh->sh_type, "case") || ! ChkCompat(&rnode, sh->sh_type, "case")) { } ce->ce_label = lbl; ce->ce_low = lnode->nd_INT; ce->ce_up = rnode->nd_INT; diff = rnode->nd_INT - lnode->nd_INT; #define MAXRANGE 100 if (diff < 0 || diff > MAXRANGE) { /* This is a bit of a hack, but it prevents the compiler from crashing on things like CASE a OF 10 .. MAX(CARDINAL): .... If the range covers more than MAXRANGE cases, this case is dealt with separately. */ label cont = ++text_label; C_dup(int_size); C_loc(lnode->nd_INT); if (fund == T_INTEGER) { C_blt(cont); } else { C_cmu(int_size); C_zlt(cont); } C_dup(int_size); C_loc(rnode->nd_INT); if (fund == T_INTEGER) { C_bgt(cont); } else { C_cmu(int_size); C_zgt(cont); } C_asp(int_size); C_bra(lbl); C_df_ilb(cont); ce->ce_label = 0; } if (sh->sh_entries == 0) { /* first case entry */ sh->sh_entries = ce; if (ce->ce_label) { sh->sh_lowerbd = ce->ce_low; sh->sh_upperbd = ce->ce_up; } } else { /* second etc. case entry find the proper place to put ce into the list */ if (ce->ce_label) { if (! chk_bounds(sh->sh_lowerbd, ce->ce_low, fund)) { sh->sh_lowerbd = ce->ce_low; } if (! chk_bounds(ce->ce_up, sh->sh_upperbd, fund)) { sh->sh_upperbd = ce->ce_up; } } while (c1 && chk_bounds(c1->ce_low, ce->ce_low, fund)) { c2 = c1; c1 = c1->ce_next; } /* At this point three cases are possible: 1: c1 != 0 && c2 != 0: insert ce somewhere in the middle 2: c1 != 0 && c2 == 0: insert ce right after the head 3: c1 == 0 && c2 != 0: append ce to last element The case c1 == 0 && c2 == 0 cannot occur, since the list is guaranteed not to be empty. */ if (c2) { if ( chk_bounds(ce->ce_low, c2->ce_up, fund)) { node_error(rnode, "multiple case entry for value %ld", (long)(ce->ce_low)); free_case_entry(ce); return; } } if (c1) { if ( chk_bounds(c1->ce_low, ce->ce_up, fund)) { node_error(rnode, "multiple case entry for value %ld", (long)(ce->ce_up)); free_case_entry(ce); return; } if (c2) { ce->ce_next = c2->ce_next; c2->ce_next = ce; } else { ce->ce_next = sh->sh_entries; sh->sh_entries = ce; } } else { assert(c2); c2->ce_next = ce; } } if (ce->ce_label) sh->sh_nrofentries += ce->ce_up - ce->ce_low + 1; } <commit_msg>Yet another bug: null reference<commit_after>/* * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands. * See the copyright notice in the ACK home directory, in the file "Copyright". * * Author: Ceriel J.H. Jacobs */ /* C A S E S T A T E M E N T C O D E G E N E R A T I O N */ /* $Header$ */ /* Generation of case statements is done by first creating a description structure for the statement, build a list of the case-labels, then generating a case description in the code, and generating either CSA or CSB, and then generating code for the cases themselves. */ #include "debug.h" #include <em_label.h> #include <em_arith.h> #include <em_code.h> #include <alloc.h> #include <assert.h> #include "Lpars.h" #include "type.h" #include "LLlex.h" #include "node.h" #include "desig.h" #include "walk.h" #include "chk_expr.h" #include "def.h" #include "density.h" struct switch_hdr { label sh_break; /* label of statement after this one */ label sh_default; /* label of ELSE part, or 0 */ int sh_nrofentries; /* number of cases */ t_type *sh_type; /* type of case expression */ arith sh_lowerbd; /* lowest case label */ arith sh_upperbd; /* highest case label */ struct case_entry *sh_entries; /* the cases with their generated labels */ }; /* STATICALLOCDEF "switch_hdr" 5 */ struct case_entry { struct case_entry *ce_next; /* next in list */ label ce_label; /* generated label */ arith ce_low, ce_up; /* lower and upper bound of range */ }; /* STATICALLOCDEF "case_entry" 20 */ /* The constant DENSITY determines when CSA and when CSB instructions are generated. Reasonable values are: 2, 3, 4. On machines that have lots of address space and memory, higher values might also be reasonable. On these machines the density of jump tables may be lower. */ compact(nr, low, up) arith low, up; { /* Careful! up - low might not fit in an arith. And then, the test "up-low < 0" might also not work to detect this situation! Or is this just a bug in the M68020/M68000? */ arith diff = up - low; return (nr != 0 && diff >= 0 && fit(diff, (int) word_size) && diff / nr <= (DENSITY - 1)); } #define nd_lab nd_symb int CaseCode(nd, exitlabel, end_reached) t_node *nd; label exitlabel; { /* Check the expression, stack a new case header and fill in the necessary fields. "exitlabel" is the exit-label of the closest enclosing LOOP-statement, or 0. */ register struct switch_hdr *sh = new_switch_hdr(); register t_node *pnode = nd; register struct case_entry *ce; register arith val; label CaseDescrLab; int rval; assert(pnode->nd_class == Stat && pnode->nd_symb == CASE); if (ChkExpression(&(pnode->nd_LEFT))) { MkCoercion(&(pnode->nd_LEFT),BaseType(pnode->nd_LEFT->nd_type)); CodePExpr(pnode->nd_LEFT); } sh->sh_type = pnode->nd_LEFT->nd_type; sh->sh_break = ++text_label; /* Now, create case label list */ while (pnode = pnode->nd_RIGHT) { if (pnode->nd_class == Link && pnode->nd_symb == '|') { if (pnode->nd_LEFT) { /* non-empty case */ pnode->nd_LEFT->nd_lab = ++text_label; AddCases(sh, /* to descriptor */ pnode->nd_LEFT->nd_LEFT, /* of case labels */ (label) pnode->nd_LEFT->nd_lab /* and code label */ ); } } else { /* Else part */ sh->sh_default = ++text_label; break; } } if (!sh->sh_nrofentries) { /* There were no cases, so we have to check the case-expression here */ if (! (sh->sh_type->tp_fund & T_DISCRETE)) { node_error(nd, "illegal type in CASE-expression"); } } /* Now generate code for the switch itself First the part that CSA and CSB descriptions have in common. */ CaseDescrLab = ++data_label; /* the rom must have a label */ C_df_dlb(CaseDescrLab); if (sh->sh_default) C_rom_ilb(sh->sh_default); else C_rom_ucon("0", pointer_size); if (compact(sh->sh_nrofentries, sh->sh_lowerbd, sh->sh_upperbd)) { /* CSA */ int gen = 1; ce = sh->sh_entries; while (! ce->ce_label) ce = ce->ce_next; C_rom_cst((arith) 0); C_rom_cst(sh->sh_upperbd - sh->sh_lowerbd); for (val = sh->sh_lowerbd; val <= sh->sh_upperbd; val++) { assert(ce); if (gen || val == ce->ce_low) { gen = 1; C_rom_ilb(ce->ce_label); if (val == ce->ce_up) { gen = 0; ce = ce->ce_next; while (ce && ! ce->ce_label) ce = ce->ce_next; } } else if (sh->sh_default) C_rom_ilb(sh->sh_default); else C_rom_ucon("0", pointer_size); } C_loc(sh->sh_lowerbd); C_sbu(word_size); c_lae_dlb(CaseDescrLab); /* perform the switch */ C_csa(word_size); } else { /* CSB */ C_rom_cst((arith)sh->sh_nrofentries); for (ce = sh->sh_entries; ce; ce = ce->ce_next) { /* generate the entries: value + prog.label */ if (! ce->ce_label) continue; val = ce->ce_low; do { C_rom_cst(val); C_rom_ilb(ce->ce_label); } while (val++ != ce->ce_up); } c_lae_dlb(CaseDescrLab); /* perform the switch */ C_csb(word_size); } /* Now generate code for the cases */ pnode = nd; rval = 0; while (pnode = pnode->nd_RIGHT) { if (pnode->nd_class == Link && pnode->nd_symb == '|') { if (pnode->nd_LEFT) { rval |= LblWalkNode((label) pnode->nd_LEFT->nd_lab, pnode->nd_LEFT->nd_RIGHT, exitlabel, end_reached); C_bra(sh->sh_break); } } else { /* Else part */ assert(sh->sh_default != 0); rval |= LblWalkNode(sh->sh_default, pnode, exitlabel, end_reached); break; } } def_ilb(sh->sh_break); FreeSh(sh); return rval; } FreeSh(sh) register struct switch_hdr *sh; { /* free the allocated switch structure */ register struct case_entry *ce; ce = sh->sh_entries; while (ce) { struct case_entry *tmp = ce->ce_next; free_case_entry(ce); ce = tmp; } free_switch_hdr(sh); } AddCases(sh, node, lbl) struct switch_hdr *sh; register t_node *node; label lbl; { /* Add case labels to the case label list */ if (node->nd_class == Link) { if (node->nd_symb == UPTO) { assert(node->nd_LEFT->nd_class == Value); assert(node->nd_RIGHT->nd_class == Value); AddOneCase(sh, node->nd_LEFT, node->nd_RIGHT, lbl); return; } assert(node->nd_symb == ','); AddCases(sh, node->nd_LEFT, lbl); AddCases(sh, node->nd_RIGHT, lbl); return; } assert(node->nd_class == Value); AddOneCase(sh, node, node, lbl); } AddOneCase(sh, lnode, rnode, lbl) register struct switch_hdr *sh; t_node *lnode, *rnode; label lbl; { register struct case_entry *ce = new_case_entry(); register struct case_entry *c1 = sh->sh_entries, *c2 = 0; int fund = sh->sh_type->tp_fund; arith diff; if (! ChkCompat(&lnode, sh->sh_type, "case") || ! ChkCompat(&rnode, sh->sh_type, "case")) { } ce->ce_label = lbl; ce->ce_low = lnode->nd_INT; ce->ce_up = rnode->nd_INT; diff = rnode->nd_INT - lnode->nd_INT; #define MAXRANGE 100 if (diff < 0 || diff > MAXRANGE) { /* This is a bit of a hack, but it prevents the compiler from crashing on things like CASE a OF 10 .. MAX(CARDINAL): .... If the range covers more than MAXRANGE cases, this case is dealt with separately. */ label cont = ++text_label; C_dup(int_size); C_loc(lnode->nd_INT); if (fund == T_INTEGER) { C_blt(cont); } else { C_cmu(int_size); C_zlt(cont); } C_dup(int_size); C_loc(rnode->nd_INT); if (fund == T_INTEGER) { C_bgt(cont); } else { C_cmu(int_size); C_zgt(cont); } C_asp(int_size); C_bra(lbl); C_df_ilb(cont); ce->ce_label = 0; } if (sh->sh_entries == 0) { /* first case entry */ sh->sh_entries = ce; if (ce->ce_label) { sh->sh_lowerbd = ce->ce_low; sh->sh_upperbd = ce->ce_up; } } else { /* second etc. case entry find the proper place to put ce into the list */ while (c1 && chk_bounds(c1->ce_low, ce->ce_low, fund)) { c2 = c1; c1 = c1->ce_next; } /* At this point three cases are possible: 1: c1 != 0 && c2 != 0: insert ce somewhere in the middle 2: c1 != 0 && c2 == 0: insert ce right after the head 3: c1 == 0 && c2 != 0: append ce to last element The case c1 == 0 && c2 == 0 cannot occur, since the list is guaranteed not to be empty. */ if (c2) { if ( chk_bounds(ce->ce_low, c2->ce_up, fund)) { node_error(rnode, "multiple case entry for value %ld", (long)(ce->ce_low)); free_case_entry(ce); return; } } if (c1) { if ( chk_bounds(c1->ce_low, ce->ce_up, fund)) { node_error(rnode, "multiple case entry for value %ld", (long)(ce->ce_up)); free_case_entry(ce); return; } if (c2) { ce->ce_next = c2->ce_next; c2->ce_next = ce; } else { ce->ce_next = sh->sh_entries; sh->sh_entries = ce; } } else { assert(c2); c2->ce_next = ce; } if (ce->ce_label) { if (! chk_bounds(sh->sh_lowerbd, ce->ce_low, fund)) { sh->sh_lowerbd = ce->ce_low; } if (! chk_bounds(ce->ce_up, sh->sh_upperbd, fund)) { sh->sh_upperbd = ce->ce_up; } } } if (ce->ce_label) sh->sh_nrofentries += ce->ce_up - ce->ce_low + 1; } <|endoftext|>
<commit_before>/*! * \file File componentTimer.cpp * \brief Implementation of the class of game time * * The class implemented here provides to the game the time limit * * \sa componentTimer.hpp */ #include <> //#include <compLib.hpp> #include <gameObject.hpp> //#include <camera.hpp> //#include <inputManager.hpp> //! A constructor. /*! This is a constructor method of componentTimer class */ CompTimer::CompTimer(float limit):limit{limit}{} //! A destructor. /*! This is a destructor method of componentText class */ CompTimer::~CompTimer() {} /*! @fn CompTimer::update(float time) @brief Method that update the game time and check the time limit @param time @return The execution of this method returns no value @warning Method that requires review of comment */ void CompTimer::update(float time) { t.add_time(time); if (t.get_time()>limit) { GO(entity)->dead=true; } } /*! @fn void CompTimer::render() @brief Method that render the game time @return The execution of this method returns no value @warning Method that requires review of comment */ void CompTimer::render() {} /*! @fn void CompTimer::own(GameObject* go) @brief Method that monitor the game element @param GameObject* go @return The execution of this method returns no value @warning Method that requires review of comment */ void CompTimer::own(GameObject* go) { entity=go->uid; } /*! @fn void CompMovement::Update(float time) @brief Method that sets the game time @return The method return the current time @warning Method that requires review of comment */ Component::type CompTimer::get_type() const{ return Component::type::t_timer; } <commit_msg>Appling stylesheet in componentTimer.cpp<commit_after>/*! * @file File componentTimer.cpp * @brief Implementation of the class of game time * * The class implemented here provides to the game the time limit * * @sa componentTimer.hpp */ #include <> //#include <compLib.hpp> #include <gameObject.hpp> //#include <camera.hpp> //#include <inputManager.hpp> //! A constructor. /*! This is a constructor method of componentTimer class */ CompTimer::CompTimer(float limit):limit{limit}{} //! A destructor. /*! This is a destructor method of componentText class */ CompTimer::~CompTimer() {} /*! @fn CompTimer::update(float time) @brief Method that update the game time and check the time limit @param time @return The execution of this method returns no value @warning Method that requires review of comment */ void CompTimer::update(float time) { t.add_time(time); if (t.get_time()>limit) { GO(entity)->dead=true; } } /*! @fn void CompTimer::render() @brief Method that render the game time @return The execution of this method returns no value @warning Method that requires review of comment */ void CompTimer::render() {} /*! @fn void CompTimer::own(GameObject* go) @brief Method that monitor the game element @param GameObject* go @return The execution of this method returns no value @warning Method that requires review of comment */ void CompTimer::own(GameObject* go) { entity=go->uid; } /*! @fn void CompMovement::Update(float time) @brief Method that sets the game time @return The method return the current time @warning Method that requires review of comment */ Component::type CompTimer::get_type() const{ return Component::type::t_timer; } <|endoftext|>
<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <guido.tack@monash.edu> */ /* 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 __MINIZINC_UTILS_H__ #define __MINIZINC_UTILS_H__ #include <string> #include <sstream> #include <ctime> #include <limits> #include <iomanip> #include <minizinc/timer.hh> using namespace std; namespace MiniZinc { // #define __MZN_PRINTATONCE__ #ifdef __MZN_PRINTATONCE__ #define __MZN_PRINT_SRCLOC(e1, e2) \ std::cerr << '\n' << __FILE__ << ": " << __LINE__ << " (" << __func__ \ << "): not " << e1 << ": " << std::flush; \ std::cerr << e2 << std::endl #else #define __MZN_PRINT_SRCLOC(e1, e2) #endif #define MZN_ASSERT_HARD( c ) \ do { if ( !(c) ) { __MZN_PRINT_SRCLOC( #c, "" ); throw InternalError( #c ); } } while (0) #define MZN_ASSERT_HARD_MSG( c, e ) \ do { if ( !(c) ) { __MZN_PRINT_SRCLOC( #c, e ); \ ostringstream oss; oss << "not " << #c << ": " << e; \ throw InternalError( oss.str() ); } } while (0) inline std::string stoptime(Timer& timer) { std::ostringstream oss; oss << std::setprecision(0) << std::fixed << timer.ms() << " ms"; return oss.str(); } inline std::string stoptime(clock_t& start) { std::ostringstream oss; clock_t now = clock(); oss << std::setprecision(0) << std::fixed << ((static_cast<double>(now-start) / CLOCKS_PER_SEC) * 1000.0) << " ms"; start = now; return oss.str(); } inline std::string timeDiff(clock_t t2, clock_t t1) { std::ostringstream oss; oss << std::setprecision(2) << std::fixed << ((static_cast<double>(t2-t1) / CLOCKS_PER_SEC)) << " s"; return oss.str(); } inline bool beginswith(string s, string t) { return s.compare(0, t.length(), t)==0; } inline void checkIOStatus( bool fOk, string msg, bool fHard=1 ) { if ( !fOk ) { std::cerr << "\n " << msg << strerror(errno) << "." << std::endl; MZN_ASSERT_HARD_MSG ( !fHard, msg << strerror(errno) ); } } template <class T> inline bool assignStr(T*, const string ) { return false; } template<> inline bool assignStr(string* pS, const string s ) { *pS = s; return true; } /// A simple per-cmdline option parser class CLOParser { int& i; // current item const int argc=0; const char* const* argv=0; public: CLOParser( int& ii, const int ac, const char* const* av ) : i(ii), argc(ac), argv(av) { } template <class Value=int> inline bool getOption( const char* names, // space-separated option list Value* pResult=nullptr, // pointer to value storage bool fValueOptional=false // if pResult, for non-string values ) { assert(0 == strchr(names, ',')); assert(0 == strchr(names, ';')); if( i>=argc ) return false; assert( argv[i] ); string arg( argv[i] ); /// Separate keywords string keyword; istringstream iss( names ); while ( iss >> keyword ) { if ( ((2<keyword.size() || 0==pResult) && arg!=keyword) || // exact cmp (0!=arg.compare( 0, keyword.size(), keyword )) ) // truncated cmp continue; /// Process it if ( keyword.size() < arg.size() ) { if ( 0==pResult ) continue; arg.erase( 0, keyword.size() ); } else { if ( 0==pResult ) return true; i++; if( i>=argc ) return fValueOptional; arg = argv[i]; } assert( pResult ); if ( assignStr( pResult, arg ) ) return true; istringstream iss( arg ); Value tmp; if ( !( iss >> tmp ) ) { --i; if ( fValueOptional ) { return true; } // Not print because another agent can handle this option // cerr << "\nBad value for " << keyword << ": " << arg << endl; return false; } *pResult = tmp; return true; } return false; } }; // class CLOParser /// This class prints a value if non-0 and adds comma if not 1st time class HadOne { bool fHadOne=false; public: template <class N> string operator()(const N& val, const char* descr=0) { ostringstream oss; if ( val ) { if ( fHadOne ) oss << ", "; fHadOne=true; oss << val; if ( descr ) oss << descr; } return oss.str(); } void reset() { fHadOne=false; } operator bool() const { return fHadOne; } bool operator!() const { return !fHadOne; } }; } #endif // __MINIZINC_FLATTENER_H__ <commit_msg>utils.hh: string (vector) manipulations<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Guido Tack <guido.tack@monash.edu> */ /* 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 __MINIZINC_UTILS_H__ #define __MINIZINC_UTILS_H__ #include <string> #include <vector> #include <sstream> #include <ctime> #include <limits> #include <iomanip> #include <minizinc/timer.hh> #include <minizinc/exception.hh> using namespace std; namespace MiniZinc { // #define __MZN_PRINTATONCE__ #ifdef __MZN_PRINTATONCE__ #define __MZN_PRINT_SRCLOC(e1, e2) \ std::cerr << '\n' << __FILE__ << ": " << __LINE__ << " (" << __func__ \ << "): not " << e1 << ": " << std::flush; \ std::cerr << e2 << std::endl #else #define __MZN_PRINT_SRCLOC(e1, e2) #endif #define MZN_ASSERT_HARD( c ) \ do { if ( !(c) ) { __MZN_PRINT_SRCLOC( #c, "" ); throw InternalError( #c ); } } while (0) #define MZN_ASSERT_HARD_MSG( c, e ) \ do { if ( !(c) ) { __MZN_PRINT_SRCLOC( #c, e ); \ ostringstream oss; oss << "not " << #c << ": " << e; \ throw InternalError( oss.str() ); } } while (0) inline std::string stoptime(Timer& timer) { std::ostringstream oss; oss << std::setprecision(0) << std::fixed << timer.ms() << " ms"; return oss.str(); } inline std::string stoptime(clock_t& start) { std::ostringstream oss; clock_t now = clock(); oss << std::setprecision(0) << std::fixed << ((static_cast<double>(now-start) / CLOCKS_PER_SEC) * 1000.0) << " ms"; start = now; return oss.str(); } inline std::string timeDiff(clock_t t2, clock_t t1) { std::ostringstream oss; oss << std::setprecision(2) << std::fixed << ((static_cast<double>(t2-t1) / CLOCKS_PER_SEC)) << " s"; return oss.str(); } inline bool beginswith(string s, string t) { return s.compare(0, t.length(), t)==0; } inline void checkIOStatus( bool fOk, string msg, bool fHard=1 ) { if ( !fOk ) { std::cerr << "\n " << msg << strerror(errno) << "." << std::endl; MZN_ASSERT_HARD_MSG ( !fHard, msg << strerror(errno) ); } } template <class T> inline bool assignStr(T*, const string ) { return false; } template<> inline bool assignStr(string* pS, const string s ) { *pS = s; return true; } /// A simple per-cmdline option parser class CLOParser { int& i; // current item const int argc=0; const char* const* argv=0; public: CLOParser( int& ii, const int ac, const char* const* av ) : i(ii), argc(ac), argv(av) { } template <class Value=int> inline bool getOption( const char* names, // space-separated option list Value* pResult=nullptr, // pointer to value storage bool fValueOptional=false // if pResult, for non-string values ) { assert(0 == strchr(names, ',')); assert(0 == strchr(names, ';')); if( i>=argc ) return false; assert( argv[i] ); string arg( argv[i] ); /// Separate keywords string keyword; istringstream iss( names ); while ( iss >> keyword ) { if ( ((2<keyword.size() || 0==pResult) && arg!=keyword) || // exact cmp (0!=arg.compare( 0, keyword.size(), keyword )) ) // truncated cmp continue; /// Process it if ( keyword.size() < arg.size() ) { if ( 0==pResult ) continue; arg.erase( 0, keyword.size() ); } else { if ( 0==pResult ) return true; i++; if( i>=argc ) return fValueOptional; arg = argv[i]; } assert( pResult ); if ( assignStr( pResult, arg ) ) return true; istringstream iss( arg ); Value tmp; if ( !( iss >> tmp ) ) { --i; if ( fValueOptional ) { return true; } // Not print because another agent can handle this option // cerr << "\nBad value for " << keyword << ": " << arg << endl; return false; } *pResult = tmp; return true; } return false; } }; // class CLOParser /// This class prints a value if non-0 and adds comma if not 1st time class HadOne { bool fHadOne=false; public: template <class N> string operator()(const N& val, const char* descr=0) { ostringstream oss; if ( val ) { if ( fHadOne ) oss << ", "; fHadOne=true; oss << val; if ( descr ) oss << descr; } return oss.str(); } void reset() { fHadOne=false; } operator bool() const { return fHadOne; } bool operator!() const { return !fHadOne; } }; /// Split a string into words /// Add the words into the given vector inline void split(const string& str, std::vector<string>& words) { istringstream iss(str); string buf; while (iss) { iss >> buf; words.push_back(buf); } } /// Puts the strings' c_str()s into the 2nd argument. /// The latter is only valid as long as the former isn't changed. inline void vecString2vecPChar(const vector<string>& vS, vector<const char*>& vPC) { vPC.resize(vS.size()); for ( size_t i=0; i<vS.size(); ++i ) { vPC[i] = vS[i].c_str(); } } } #endif // __MINIZINC_FLATTENER_H__ <|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) //======================================================================= #ifndef MTAC_FUNCTION_H #define MTAC_FUNCTION_H #include <memory> #include <vector> #include <utility> #include <set> #include <ostream> #include "iterators.hpp" #include "mtac/forward.hpp" #include "mtac/basic_block.hpp" #include "mtac/basic_block_iterator.hpp" #include "mtac/Loop.hpp" #include "mtac/Quadruple.hpp" #include "ltac/Register.hpp" #include "ltac/FloatRegister.hpp" namespace eddic { class Function; class FunctionContext; namespace mtac { class Function : public std::enable_shared_from_this<Function> { public: Function(std::shared_ptr<FunctionContext> context, const std::string& name, eddic::Function& definition); //Function cannot be copied Function(const Function& rhs) = delete; Function& operator=(const Function& rhs) = delete; //Function can be moved Function(Function&& rhs); Function& operator=(Function&& rhs); std::string get_name() const; template< class... Args > void emplace_back( Args&&... args ){ statements.emplace_back(std::forward<Args>(args)...); } void push_back(mtac::Quadruple&& quadruple){ statements.push_back(std::forward<mtac::Quadruple>(quadruple)); } mtac::Quadruple& find(std::size_t uid); std::vector<mtac::Quadruple>& get_statements(); const std::vector<mtac::Quadruple>& get_statements() const; void release_statements(); void create_entry_bb(); void create_exit_bb(); basic_block_p current_bb(); basic_block_p append_bb(); basic_block_p new_bb(); basic_block_p entry_bb(); basic_block_p exit_bb(); basic_block_iterator begin(); basic_block_iterator end(); basic_block_const_iterator begin() const ; basic_block_const_iterator end() const ; basic_block_iterator at(basic_block_p bb); basic_block_iterator insert_before(basic_block_iterator it, basic_block_p block); basic_block_iterator insert_after(basic_block_iterator it, basic_block_p block); basic_block_iterator merge_basic_blocks(basic_block_iterator it, basic_block_p block); basic_block_iterator remove(basic_block_iterator it); basic_block_iterator remove(basic_block_p bb); std::pair<basic_block_iterator, basic_block_iterator> blocks(); std::vector<mtac::Loop>& loops(); std::size_t bb_count() const; std::size_t size() const; std::size_t pseudo_registers(); void set_pseudo_registers(std::size_t pseudo_registers); std::size_t pseudo_float_registers(); void set_pseudo_float_registers(std::size_t pseudo_registers); const std::set<ltac::Register>& use_registers() const; const std::set<ltac::FloatRegister>& use_float_registers() const; const std::set<ltac::Register>& variable_registers() const; const std::set<ltac::FloatRegister>& variable_float_registers() const; void use(ltac::Register reg); void use(ltac::FloatRegister reg); void variable_use(ltac::Register reg); void variable_use(ltac::FloatRegister reg); bool is_main() const; bool& pure(); bool pure() const; eddic::Function& definition(); std::shared_ptr<FunctionContext> context; private: eddic::Function* _definition; //Before being partitioned, the function has only statement std::vector<mtac::Quadruple> statements; bool _pure = false; //There is no basic blocks at the beginning std::size_t count = 0; std::size_t index = 0; basic_block_p entry = nullptr; basic_block_p exit = nullptr; std::set<ltac::Register> _use_registers; std::set<ltac::FloatRegister> _use_float_registers; std::set<ltac::Register> _variable_registers; std::set<ltac::FloatRegister> _variable_float_registers; std::size_t last_pseudo_registers = 0; std::size_t last_float_pseudo_registers = 0; std::vector<mtac::Loop> m_loops; std::string name; }; bool operator==(const mtac::Function& lhs, const mtac::Function& rhs); std::ostream& operator<<(std::ostream& stream, const mtac::Function& function); } //end of mtac template<> struct Iterators<mtac::Function> { mtac::Function& container; mtac::basic_block_iterator it; mtac::basic_block_iterator end; Iterators(mtac::Function& container) : container(container), it(container.begin()), end(container.end()) {} mtac::basic_block_p& operator*(){ return *it; } void operator++(){ ++it; } void operator--(){ --it; } void insert(mtac::basic_block_p bb){ it = container.insert_before(it, bb); end = container.end(); } void erase(){ it = container.remove(it); end = container.end(); } /*! * \brief Merge the current block into the specified one. * The current block will be removed. * \return an iterator to the merged block */ void merge_to(mtac::basic_block_p bb){ it = container.merge_basic_blocks(it, bb); end = container.end(); } /*! * \brief Merge the specified block into the current one. * The specified block will be removed. * \return an iterator to the merged block */ void merge_in(mtac::basic_block_p bb){ it = container.merge_basic_blocks(container.at(bb), *it); end = container.end(); } bool has_next(){ return it != end; } }; } //end of eddic #endif <commit_msg>Set good candidates as inline<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) //======================================================================= #ifndef MTAC_FUNCTION_H #define MTAC_FUNCTION_H #include <memory> #include <vector> #include <utility> #include <set> #include <ostream> #include "iterators.hpp" #include "mtac/forward.hpp" #include "mtac/basic_block.hpp" #include "mtac/basic_block_iterator.hpp" #include "mtac/Loop.hpp" #include "mtac/Quadruple.hpp" #include "ltac/Register.hpp" #include "ltac/FloatRegister.hpp" namespace eddic { class Function; class FunctionContext; namespace mtac { class Function : public std::enable_shared_from_this<Function> { public: Function(std::shared_ptr<FunctionContext> context, const std::string& name, eddic::Function& definition); //Function cannot be copied Function(const Function& rhs) = delete; Function& operator=(const Function& rhs) = delete; //Function can be moved Function(Function&& rhs); Function& operator=(Function&& rhs); std::string get_name() const; template< class... Args > inline void emplace_back( Args&&... args ){ statements.emplace_back(std::forward<Args>(args)...); } inline void push_back(mtac::Quadruple&& quadruple){ statements.push_back(std::forward<mtac::Quadruple>(quadruple)); } mtac::Quadruple& find(std::size_t uid); std::vector<mtac::Quadruple>& get_statements(); const std::vector<mtac::Quadruple>& get_statements() const; void release_statements(); void create_entry_bb(); void create_exit_bb(); basic_block_p current_bb(); basic_block_p append_bb(); basic_block_p new_bb(); basic_block_p entry_bb(); basic_block_p exit_bb(); basic_block_iterator begin(); basic_block_iterator end(); basic_block_const_iterator begin() const ; basic_block_const_iterator end() const ; basic_block_iterator at(basic_block_p bb); basic_block_iterator insert_before(basic_block_iterator it, basic_block_p block); basic_block_iterator insert_after(basic_block_iterator it, basic_block_p block); basic_block_iterator merge_basic_blocks(basic_block_iterator it, basic_block_p block); basic_block_iterator remove(basic_block_iterator it); basic_block_iterator remove(basic_block_p bb); std::pair<basic_block_iterator, basic_block_iterator> blocks(); std::vector<mtac::Loop>& loops(); std::size_t bb_count() const; std::size_t size() const; std::size_t pseudo_registers(); void set_pseudo_registers(std::size_t pseudo_registers); std::size_t pseudo_float_registers(); void set_pseudo_float_registers(std::size_t pseudo_registers); const std::set<ltac::Register>& use_registers() const; const std::set<ltac::FloatRegister>& use_float_registers() const; const std::set<ltac::Register>& variable_registers() const; const std::set<ltac::FloatRegister>& variable_float_registers() const; void use(ltac::Register reg); void use(ltac::FloatRegister reg); void variable_use(ltac::Register reg); void variable_use(ltac::FloatRegister reg); bool is_main() const; bool& pure(); bool pure() const; eddic::Function& definition(); std::shared_ptr<FunctionContext> context; private: eddic::Function* _definition; //Before being partitioned, the function has only statement std::vector<mtac::Quadruple> statements; bool _pure = false; //There is no basic blocks at the beginning std::size_t count = 0; std::size_t index = 0; basic_block_p entry = nullptr; basic_block_p exit = nullptr; std::set<ltac::Register> _use_registers; std::set<ltac::FloatRegister> _use_float_registers; std::set<ltac::Register> _variable_registers; std::set<ltac::FloatRegister> _variable_float_registers; std::size_t last_pseudo_registers = 0; std::size_t last_float_pseudo_registers = 0; std::vector<mtac::Loop> m_loops; std::string name; }; bool operator==(const mtac::Function& lhs, const mtac::Function& rhs); std::ostream& operator<<(std::ostream& stream, const mtac::Function& function); } //end of mtac template<> struct Iterators<mtac::Function> { mtac::Function& container; mtac::basic_block_iterator it; mtac::basic_block_iterator end; Iterators(mtac::Function& container) : container(container), it(container.begin()), end(container.end()) {} mtac::basic_block_p& operator*(){ return *it; } void operator++(){ ++it; } void operator--(){ --it; } void insert(mtac::basic_block_p bb){ it = container.insert_before(it, bb); end = container.end(); } void erase(){ it = container.remove(it); end = container.end(); } /*! * \brief Merge the current block into the specified one. * The current block will be removed. * \return an iterator to the merged block */ void merge_to(mtac::basic_block_p bb){ it = container.merge_basic_blocks(it, bb); end = container.end(); } /*! * \brief Merge the specified block into the current one. * The specified block will be removed. * \return an iterator to the merged block */ void merge_in(mtac::basic_block_p bb){ it = container.merge_basic_blocks(container.at(bb), *it); end = container.end(); } bool has_next(){ return it != end; } }; } //end of eddic #endif <|endoftext|>
<commit_before>/** * \file */ #pragma once #include <rleahylib/rleahylib.hpp> #include <client.hpp> #include <packet.hpp> #include <functional> namespace MCPP { /** * Encapsulates information about a packet * being received from a client. */ class PacketEvent { public: /** * The client from which the packet was * received. */ SmartPointer<Client> & From; /** * The packet which was received. */ Packet & Data; }; /** * Provides the facilities for routing * incoming packets to handlers. */ class PacketRouter { public: /** * The type of callback which may subscribe * to receive events. */ typedef std::function<void (PacketEvent)> Type; private: // Routes Type play_routes [PacketImpl::LargestID+1]; Type status_routes [PacketImpl::LargestID+1]; Type login_routes [PacketImpl::LargestID+1]; Type handshake_routes [PacketImpl::LargestID+1]; inline void destroy () noexcept; inline void init () noexcept; public: /** * Creates a new packet router with no * routes. */ PacketRouter () noexcept; /** * Cleans up a packet router. */ ~PacketRouter () noexcept; /** * Fetches a packet route. * * \param [in] id * The ID of the packet whole route * shall be retrieved. * \param [it] state * The state of the packet whose route * shall be retreived. * * \return * A reference to the requested route. */ Type & operator () (UInt32 id, ProtocolState state) noexcept; /** * Fetches a packet route. * * \param [in] id * The ID of the packet whole route * shall be retrieved. * \param [it] state * The state of the packet whose route * shall be retreived. * * \return * A reference to the requested route. */ const Type & operator () (UInt32 id, ProtocolState state) const noexcept; /** * Dispatches a packet to the appropriate * handler. * * \param [in] event * The event object which represents * this receive event. * \param [in] state * The state the protocol is in. */ void operator () (PacketEvent event, ProtocolState state) const; /** * Clears all handlers. */ void Clear () noexcept; }; } <commit_msg>PacketEvent Change<commit_after>/** * \file */ #pragma once #include <rleahylib/rleahylib.hpp> #include <client.hpp> #include <packet.hpp> #include <functional> namespace MCPP { /** * Encapsulates information about a packet * being received from a client. */ class PacketEvent { public: /** * The client from which the packet was * received. */ SmartPointer<Client> From; /** * The packet which was received. */ Packet & Data; }; /** * Provides the facilities for routing * incoming packets to handlers. */ class PacketRouter { public: /** * The type of callback which may subscribe * to receive events. */ typedef std::function<void (PacketEvent)> Type; private: // Routes Type play_routes [PacketImpl::LargestID+1]; Type status_routes [PacketImpl::LargestID+1]; Type login_routes [PacketImpl::LargestID+1]; Type handshake_routes [PacketImpl::LargestID+1]; inline void destroy () noexcept; inline void init () noexcept; public: /** * Creates a new packet router with no * routes. */ PacketRouter () noexcept; /** * Cleans up a packet router. */ ~PacketRouter () noexcept; /** * Fetches a packet route. * * \param [in] id * The ID of the packet whole route * shall be retrieved. * \param [it] state * The state of the packet whose route * shall be retreived. * * \return * A reference to the requested route. */ Type & operator () (UInt32 id, ProtocolState state) noexcept; /** * Fetches a packet route. * * \param [in] id * The ID of the packet whole route * shall be retrieved. * \param [it] state * The state of the packet whose route * shall be retreived. * * \return * A reference to the requested route. */ const Type & operator () (UInt32 id, ProtocolState state) const noexcept; /** * Dispatches a packet to the appropriate * handler. * * \param [in] event * The event object which represents * this receive event. * \param [in] state * The state the protocol is in. */ void operator () (PacketEvent event, ProtocolState state) const; /** * Clears all handlers. */ void Clear () noexcept; }; } <|endoftext|>
<commit_before>#include <iostream> int main() { std::cout << "HelloWorld" << std::endl; } <commit_msg>Update Helloworld.cpp<commit_after>#include <iostream> int main() { std::cout << "Fight On" << std::endl; } <|endoftext|>
<commit_before>// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // This MFC Samples source code demonstrates using MFC Microsoft Office Fluent User Interface // (the "Fluent UI") and is provided only as referential material to supplement the // Microsoft Foundation Classes Reference and related electronic documentation // included with the MFC C++ library software. // License terms to copy, use or distribute the Fluent UI are available separately. // To learn more about our Fluent UI licensing program, please visit // http://go.microsoft.com/fwlink/?LinkId=238214. // // Copyright (C) Microsoft Corporation // All rights reserved. // MGen.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "afxwinappex.h" #include "afxdialogex.h" #include "MGen.h" #include "MainFrm.h" #include "MGenDoc.h" #include "MGenView.h" #include "GLibrary/GLib.h" #include "git-version.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMGenApp BEGIN_MESSAGE_MAP(CMGenApp, CWinAppEx) ON_COMMAND(ID_APP_ABOUT, &CMGenApp::OnAppAbout) // Standard file based document commands ON_COMMAND(ID_FILE_NEW, &CWinAppEx::OnFileNew) //ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen) // Standard print setup command ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinAppEx::OnFilePrintSetup) ON_COMMAND(ID_FILE_OPEN, &CMGenApp::OnFileOpen) END_MESSAGE_MAP() // CMGenApp construction CMGenApp::CMGenApp() { m_bHiColorIcons = TRUE; // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS; #ifdef _MANAGED // If the application is built using Common Language Runtime support (/clr): // 1) This additional setting is needed for Restart Manager support to work properly. // 2) In your project, you must add a reference to System.Windows.Forms in order to build. System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException); #endif // Recommended format for string is CompanyName.ProductName.SubProduct.VersionInformation SetAppID(_T("MGen.MGen.2")); // Add construction code here, // Place all significant initialization in InitInstance } // The one and only CMGenApp object CMGenApp theApp; // CMGenApp initialization BOOL CMGenApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinAppEx::InitInstance(); // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); EnableTaskbarInteraction(FALSE); // AfxInitRichEdit2() is required to use RichEdit control // AfxInitRichEdit2(); // Initialize GDI+ Gdiplus::GdiplusStartupInput gdiplusStartupInput; Gdiplus::GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // Name of your company or organization SetRegistryKey(_T("MGen")); LoadStdProfileSettings(10); // Load standard INI file options (including MRU) InitContextMenuManager(); InitKeyboardManager(); InitTooltipManager(); CMFCToolTipInfo ttParams; ttParams.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CMGenDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CMGenView)); //if (!pDocTemplate) //return FALSE; AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; //ParseCommandLine(cmdInfo); // Enable DDE Execute open EnableShellOpen(); //RegisterShellFileTypes(TRUE); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it m_pMainWnd->ShowWindow(SW_SHOWMAXIMIZED); m_pMainWnd->UpdateWindow(); // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand // Enable drag/drop open m_pMainWnd->DragAcceptFiles(); return TRUE; } int CMGenApp::ExitInstance() { //Handle additional resources you may have added Gdiplus::GdiplusShutdown(m_gdiplusToken); AfxOleTerm(FALSE); CWinAppEx::ExitInstance(); // Log successful exit if (CGLib::m_testing) CGLib::AppendLineToFile("autotest\\exit.log", m_lpCmdLine); // Return error code for testing purposes return CGLib::exitcode; } // CMGenApp message handlers // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() public: CString m_ver; virtual BOOL OnInitDialog(); }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) , m_ver(_T("")) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_STATIC_VER, m_ver); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // App command to run the dialog void CMGenApp::OnAppAbout() { CAboutDlg aboutDlg; // APP_VERSION aboutDlg.m_ver.Format("Music Generator Laboratory, Version %s", GEN_VER_VERSION_STRING); aboutDlg.DoModal(); } // CMGenApp customization load/save methods void CMGenApp::PreLoadState() { BOOL bNameValid; CString strName; bNameValid = strName.LoadString(IDS_EDIT_MENU); ASSERT(bNameValid); GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT); } void CMGenApp::LoadCustomState() { } void CMGenApp::SaveCustomState() { } // CMGenApp message handlers void CMGenApp::OnFileOpen() { CMainFrame* mf = (CMainFrame *)AfxGetMainWnd(); if (mf->m_state_gen == 1) { AfxMessageBox("Please stop generation before opening files"); return; } TCHAR buffer[MAX_PATH]; GetCurrentDirectory(MAX_PATH, buffer); CString path_old = string(buffer).c_str(); // szFilters is a text string that includes two file name filters: // "*.my" for "MyType Files" and "*.*' for "All Files." TCHAR szFilters[] = _T("All supported formats (*.mgr;*.mid;*.midi)|*.mgr;*.mid;*.midi|MGen result files (*.mgr)|*.mgr|MIDI files (*.mid)|*.mid|MIDI files (*.midi)|*.midi||"); // Create an Open dialog; the default file name extension is ".my". CFileDialog fileDlg(TRUE, "", path_old, // path_old OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR, szFilters, mf, 0, false); fileDlg.m_ofn.lpstrInitialDir = path_old; // Display the file dialog. When user clicks OK, fileDlg.DoModal() // returns IDOK. if (fileDlg.DoModal() == IDOK) { mf->LoadFile(fileDlg.GetPathName()); AddToRecentFileList(fileDlg.GetPathName()); } } CString CMGenApp::getRecentFile(int index) { CString st = string((*m_pRecentFileList)[index]).c_str(); return st; } BOOL CAboutDlg::OnInitDialog() { CDialogEx::OnInitDialog(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } <commit_msg>Test commit<commit_after>// This is an independent project of an individual developer. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // This MFC Samples source code demonstrates using MFC Microsoft Office Fluent User Interface // (the "Fluent UI") and is provided only as referential material to supplement the // Microsoft Foundation Classes Reference and related electronic documentation // included with the MFC C++ library software. // License terms to copy, use or distribute the Fluent UI are available separately. // To learn more about our Fluent UI licensing program, please visit // http://go.microsoft.com/fwlink/?LinkId=238214. // // Copyright (C) Microsoft Corporation // All rights reserved. // MGen.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "afxwinappex.h" #include "afxdialogex.h" #include "MGen.h" #include "MainFrm.h" #include "MGenDoc.h" #include "MGenView.h" #include "GLibrary/GLib.h" #include "git-version.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMGenApp BEGIN_MESSAGE_MAP(CMGenApp, CWinAppEx) ON_COMMAND(ID_APP_ABOUT, &CMGenApp::OnAppAbout) // Standard file based document commands ON_COMMAND(ID_FILE_NEW, &CWinAppEx::OnFileNew) //ON_COMMAND(ID_FILE_OPEN, &CWinAppEx::OnFileOpen) // Standard print setup command ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinAppEx::OnFilePrintSetup) ON_COMMAND(ID_FILE_OPEN, &CMGenApp::OnFileOpen) END_MESSAGE_MAP() // CMGenApp construction CMGenApp::CMGenApp() { m_bHiColorIcons = TRUE; // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS; #ifdef _MANAGED // If the application is built using Common Language Runtime support (/clr): // 1) This additional setting is needed for Restart Manager support to work properly. // 2) In your project, you must add a reference to System.Windows.Forms in order to build. System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException); #endif // Recommended format for string is CompanyName.ProductName.SubProduct.VersionInformation SetAppID(_T("MGen.MGen.2")); // Add construction code here, // Place all significant initialization in InitInstance } // The one and only CMGenApp object CMGenApp theApp; // CMGenApp initialization BOOL CMGenApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinAppEx::InitInstance(); // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); EnableTaskbarInteraction(FALSE); // AfxInitRichEdit2() is required to use RichEdit control // AfxInitRichEdit2(); // Initialize GDI+ Gdiplus::GdiplusStartupInput gdiplusStartupInput; Gdiplus::GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // Name of your company or organization SetRegistryKey(_T("MGen")); LoadStdProfileSettings(10); // Load standard INI file options (including MRU) InitContextMenuManager(); InitKeyboardManager(); InitTooltipManager(); CMFCToolTipInfo ttParams; ttParams.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CMGenDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CMGenView)); //if (!pDocTemplate) //return FALSE; AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; //ParseCommandLine(cmdInfo); // Enable DDE Execute open EnableShellOpen(); //RegisterShellFileTypes(TRUE); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it m_pMainWnd->ShowWindow(SW_SHOWMAXIMIZED); m_pMainWnd->UpdateWindow(); // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand // Enable drag/drop open m_pMainWnd->DragAcceptFiles(); return TRUE; } int CMGenApp::ExitInstance() { //Handle additional resources you may have added Gdiplus::GdiplusShutdown(m_gdiplusToken); AfxOleTerm(FALSE); CWinAppEx::ExitInstance(); // Log successful exit if (CGLib::m_testing) CGLib::AppendLineToFile("autotest\\exit.log", m_lpCmdLine); // Return error code for testing purposes return CGLib::exitcode; } // CMGenApp message handlers // CAboutDlg dialog used for App About class CAboutDlg : public CDialogEx { public: CAboutDlg(); // Dialog Data #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() public: CString m_ver; virtual BOOL OnInitDialog(); }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) , m_ver(_T("")) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_STATIC_VER, m_ver); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // App command to run the dialog void CMGenApp::OnAppAbout() { CAboutDlg aboutDlg; // APP_VERSION aboutDlg.m_ver.Format("Music Generator Laboratory, Version %s", GEN_VER_VERSION_STRING); aboutDlg.DoModal(); } // CMGenApp customization load/save methods void CMGenApp::PreLoadState() { BOOL bNameValid; CString strName; bNameValid = strName.LoadString(IDS_EDIT_MENU); ASSERT(bNameValid); GetContextMenuManager()->AddMenu(strName, IDR_POPUP_EDIT); } void CMGenApp::LoadCustomState() { } void CMGenApp::SaveCustomState() { } // CMGenApp message handlers void CMGenApp::OnFileOpen() { CMainFrame* mf = (CMainFrame *)AfxGetMainWnd(); if (mf->m_state_gen == 1) { AfxMessageBox("Please stop generation before opening files"); return; } TCHAR buffer[MAX_PATH]; GetCurrentDirectory(MAX_PATH, buffer); CString path_old = string(buffer).c_str(); // szFilters is a text string that includes two file name filters: // "*.my" for "MyType Files" and "*.*' for "All Files." TCHAR szFilters[] = _T("All supported formats (*.mgr;*.mid;*.midi)|*.mgr;*.mid;*.midi|MGen result files (*.mgr)|*.mgr|MIDI files (*.mid)|*.mid|MIDI files (*.midi)|*.midi||"); // Create an Open dialog; the default file name extension is ".my". CFileDialog fileDlg(TRUE, "", path_old, // path_old OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR, szFilters, mf, 0, false); fileDlg.m_ofn.lpstrInitialDir = path_old; // Display the file dialog. When user clicks OK, fileDlg.DoModal() // returns IDOK. if (fileDlg.DoModal() == IDOK) { mf->LoadFile(fileDlg.GetPathName()); AddToRecentFileList(fileDlg.GetPathName()); } } CString CMGenApp::getRecentFile(int index) { CString st = string((*m_pRecentFileList)[index]).c_str(); return st; } BOOL CAboutDlg::OnInitDialog() { CDialogEx::OnInitDialog(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } <|endoftext|>
<commit_before>#include "hdr/types/list.hpp" #include "hdr/math.hpp" namespace Test { using namespace ::hdr::std; using namespace ::hdr::math; using namespace ::hdr::list; namespace ListLength { using empty = EmptyList; using oneel = Cons<empty, empty>; using twoel = Cons<oneel, oneel>; static_assert(Same<Apply<len, twoel>, Value<2>>::value); struct Element; using longlist = Cons<Element, Cons<Element, Cons<Element, empty>>>; static_assert(Same<Apply<len, longlist>, Value<3>>::value); using longerlist = Apply<concat, longlist, longlist>; static_assert(Same<Apply<len, longerlist>, Value<6>>::value); } namespace ListFolding { using ElementList = Cons<Value<1>, Cons<Value<2>, Cons<Value<3>, EmptyList>>>; using sum = Apply<fold, plus, Zero, ElementList>; static_assert(Same<sum, Value<6>>::value); } namespace ListMapping { using ElementList = Cons<Value<1>, Cons<Value<2>, Cons<Value<3>, EmptyList>>>; using AddedOne = Apply<map, Apply<plus, One>, ElementList>; using sum = Apply<fold, plus, Zero, AddedOne>; static_assert(Same<sum, Value<9>>::value); } namespace ListMonad { template<typename T> struct Double { using type = Cons<T, Cons<T, EmptyList>>; }; using double_elements = TypeFunction<Double>; using simple_list = Apply<return_, Value<1>>; static_assert(Same<simple_list, Cons<Value<1>, EmptyList>>::value); using bound_once = Apply<bind, simple_list, double_elements>; static_assert(Same<bound_once, Cons<Value<1>, Cons<Value<1>, EmptyList>>>::value); } } int main() {} <commit_msg>Test list kleisli operator<commit_after>#include "hdr/types/list.hpp" #include "hdr/math.hpp" namespace Test { using namespace ::hdr::std; using namespace ::hdr::math; using namespace ::hdr::list; namespace ListLength { using empty = EmptyList; using oneel = Cons<empty, empty>; using twoel = Cons<oneel, oneel>; static_assert(Same<Apply<len, twoel>, Value<2>>::value); struct Element; using longlist = Cons<Element, Cons<Element, Cons<Element, empty>>>; static_assert(Same<Apply<len, longlist>, Value<3>>::value); using longerlist = Apply<concat, longlist, longlist>; static_assert(Same<Apply<len, longerlist>, Value<6>>::value); } namespace ListFolding { using ElementList = Cons<Value<1>, Cons<Value<2>, Cons<Value<3>, EmptyList>>>; using sum = Apply<fold, plus, Zero, ElementList>; static_assert(Same<sum, Value<6>>::value); } namespace ListMapping { using ElementList = Cons<Value<1>, Cons<Value<2>, Cons<Value<3>, EmptyList>>>; using AddedOne = Apply<map, Apply<plus, One>, ElementList>; using sum = Apply<fold, plus, Zero, AddedOne>; static_assert(Same<sum, Value<9>>::value); } namespace ListMonad { template<typename T> struct Double { using type = Cons<T, Cons<T, EmptyList>>; }; using double_elements = TypeFunction<Double>; using simple_list = Apply<return_, Value<1>>; static_assert(Same<simple_list, Cons<Value<1>, EmptyList>>::value); using bound_once = Apply<bind, simple_list, double_elements>; static_assert(Same<bound_once, Cons<Value<1>, Cons<Value<1>, EmptyList>>>::value); using operator_list = Cons<double_elements, EmptyList>; using two_op_list = Apply<bind, operator_list, double_elements>; using four_op_list = Apply<bind, two_op_list, double_elements>; using eight_op_list = Apply<bind, four_op_list, double_elements>; using op_256x_elements = Apply<fold, kleisli, return_, eight_op_list>; using extensive_list = Apply<bind, simple_list, op_256x_elements>; static_assert(Same<Apply<len, extensive_list>, Value<256>>::value); } } int main() {} <|endoftext|>
<commit_before> #include "AbstractLcdView.h" #include "WiringPiLcdDisplay.h" #include "MiniLcdPCD8544.h" /** * Singleton accessor */ AbstractLcdView *AbstractLcdView::getLcdDisplayInstance(LcdDisplayType type) { AbstractLcdView *display = nullptr; switch(type) { case HD44780U: display = new WiringPiLcdDisplay(); break; case PCD8544: display = new MiniLcdPCD8544(); break; } return display; } void AbstractLcdView::displayBeacon(const Beacon &beacon) { char tmp[80]; int minorID = beacon.getMinor(); sprintf(tmp, "Beacon(%d):", minorID); displayText(tmp, 0, 0); sprintf(tmp, "rssi=%d", beacon.getRssi()); displayText(tmp, 2, 1); displayTime(beacon.getTime(), 2, 2); if(getBeaconMapper()) { string user = getBeaconMapper()->lookupUser(minorID); sprintf(tmp, "Hello %s", user.c_str()); } else { sprintf(tmp, "Hello Unknown"); } displayText(tmp, 2, 3); } void AbstractLcdView::displayHeartbeat(const Beacon &beacon) { char tmp[80]; sprintf(tmp, "Heartbeat(%d)*:", beacon.getMinor()); displayText(tmp, 0, 0); sprintf(tmp, "rssi=%d", beacon.getRssi()); displayText(tmp, 2, 1); displayTime(beacon.getTime(), 2, 2); sprintf(tmp, "No other in range"); displayText(tmp, 2, 3); } static inline void truncateName(string& name) { size_t length = name.length(); if(length > 8) { name.resize(8); name.replace(7, 1, 1, '.'); } } void AbstractLcdView::displayStatus(const StatusInformation& status){ char tmp[21]; string name(status.getScannerID()); truncateName(name); snprintf(tmp, sizeof(tmp), "%s:%.7d;%d", name.c_str(), status.getHeartbeatCount(), status.getHeartbeatRSSI()); displayText(tmp, 0, 0); shared_ptr<Properties> statusProps = status.getLastStatus(); #if 0 printf("StatusProps dump:\n"); for(Properties::const_iterator iter = statusProps->begin(); iter != statusProps->end(); iter ++) { printf("%s = %s\n", iter->first.c_str(), iter->second.c_str()); } printf("+++ End dump\n\n"); #endif string uptime = (*statusProps)["Uptime"]; int days=0, hrs=0, mins=0, secs=0; int count = sscanf (uptime.c_str(), "uptime: %*d, days:%d, hrs:%d, min:%d, sec:%d", &days, &hrs, &mins, &secs); snprintf(tmp, sizeof(tmp), "UP D:%d H:%d M:%d S:%d", days, hrs, mins, secs); displayText(tmp, 0, 1); const char *load = (*statusProps)["LoadAverage"].c_str(); displayText(load, 0, 2); snprintf(tmp, sizeof(tmp), "S:%.8d;M:%.7d", status.getRawEventCount(), status.getPublishEventCount()); displayText(tmp, 0, 3); } void AbstractLcdView::displayTime(int64_t timeInMS, int col, int row) { char timestr[256]; struct timeval tv; struct tm *tm; tv.tv_sec = timeInMS / 1000; tv.tv_usec = timeInMS * 1000 - tv.tv_sec * 1000000; tm = localtime(&tv.tv_sec); size_t length = strftime(timestr, 128, "%T", tm); snprintf(timestr+length, 128-length, ".%ld", tv.tv_usec/1000); displayText(timestr, col, row); } <commit_msg>clear the display at start of displayBeacon<commit_after> #include "AbstractLcdView.h" #include "WiringPiLcdDisplay.h" #include "MiniLcdPCD8544.h" /** * Singleton accessor */ AbstractLcdView *AbstractLcdView::getLcdDisplayInstance(LcdDisplayType type) { AbstractLcdView *display = nullptr; switch(type) { case HD44780U: display = new WiringPiLcdDisplay(); break; case PCD8544: display = new MiniLcdPCD8544(); break; } return display; } void AbstractLcdView::displayBeacon(const Beacon &beacon) { clear(); char tmp[80]; int minorID = beacon.getMinor(); sprintf(tmp, "Beacon(%d):", minorID); displayText(tmp, 0, 0); sprintf(tmp, "rssi=%d", beacon.getRssi()); displayText(tmp, 2, 1); displayTime(beacon.getTime(), 2, 2); if(getBeaconMapper()) { string user = getBeaconMapper()->lookupUser(minorID); sprintf(tmp, "Hello %s", user.c_str()); } else { sprintf(tmp, "Hello Unknown"); } displayText(tmp, 2, 3); } void AbstractLcdView::displayHeartbeat(const Beacon &beacon) { char tmp[80]; sprintf(tmp, "Heartbeat(%d)*:", beacon.getMinor()); displayText(tmp, 0, 0); sprintf(tmp, "rssi=%d", beacon.getRssi()); displayText(tmp, 2, 1); displayTime(beacon.getTime(), 2, 2); sprintf(tmp, "No other in range"); displayText(tmp, 2, 3); } static inline void truncateName(string& name) { size_t length = name.length(); if(length > 8) { name.resize(8); name.replace(7, 1, 1, '.'); } } void AbstractLcdView::displayStatus(const StatusInformation& status){ char tmp[21]; string name(status.getScannerID()); truncateName(name); snprintf(tmp, sizeof(tmp), "%s:%.7d;%d", name.c_str(), status.getHeartbeatCount(), status.getHeartbeatRSSI()); displayText(tmp, 0, 0); shared_ptr<Properties> statusProps = status.getLastStatus(); #if 0 printf("StatusProps dump:\n"); for(Properties::const_iterator iter = statusProps->begin(); iter != statusProps->end(); iter ++) { printf("%s = %s\n", iter->first.c_str(), iter->second.c_str()); } printf("+++ End dump\n\n"); #endif string uptime = (*statusProps)["Uptime"]; int days=0, hrs=0, mins=0, secs=0; int count = sscanf (uptime.c_str(), "uptime: %*d, days:%d, hrs:%d, min:%d, sec:%d", &days, &hrs, &mins, &secs); snprintf(tmp, sizeof(tmp), "UP D:%d H:%d M:%d S:%d", days, hrs, mins, secs); displayText(tmp, 0, 1); const char *load = (*statusProps)["LoadAverage"].c_str(); displayText(load, 0, 2); snprintf(tmp, sizeof(tmp), "S:%.8d;M:%.7d", status.getRawEventCount(), status.getPublishEventCount()); displayText(tmp, 0, 3); } void AbstractLcdView::displayTime(int64_t timeInMS, int col, int row) { char timestr[256]; struct timeval tv; struct tm *tm; tv.tv_sec = timeInMS / 1000; tv.tv_usec = timeInMS * 1000 - tv.tv_sec * 1000000; tm = localtime(&tv.tv_sec); size_t length = strftime(timestr, 128, "%T", tm); snprintf(timestr+length, 128-length, ".%ld", tv.tv_usec/1000); displayText(timestr, col, row); } <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2013 libwallet developers (see AUTHORS) * * This file is part of libwallet. * * libwallet 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/>. */ #ifndef LIBWALLET_WALLET_HPP #define LIBWALLET_WALLET_HPP // Convenience header that includes everything // Not to be used internally. For API users. #include <wallet/define.hpp> #include <wallet/deterministic_wallet.hpp> #include <wallet/mnemonic.hpp> #include <wallet/key_formats.hpp> #include <wallet/transaction.hpp> #include <wallet/uri.hpp> #endif <commit_msg>add hd_keys.hpp to wallet.hpp<commit_after>/* * Copyright (c) 2011-2013 libwallet developers (see AUTHORS) * * This file is part of libwallet. * * libwallet 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/>. */ #ifndef LIBWALLET_WALLET_HPP #define LIBWALLET_WALLET_HPP // Convenience header that includes everything // Not to be used internally. For API users. #include <wallet/deterministic_wallet.hpp> #include <wallet/mnemonic.hpp> #include <wallet/hd_keys.hpp> #include <wallet/key_formats.hpp> #include <wallet/transaction.hpp> #include <wallet/uri.hpp> #endif <|endoftext|>
<commit_before>// Copyright 2016 Open Source Robotics Foundation, 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 <experimental/filesystem> #include <cstring> #include <memory> #include <sstream> #include <string> #include <vector> #include "ament_index_cpp/get_resource.hpp" #include "class_loader/class_loader.h" #include "composition/srv/load_node.hpp" #include "rclcpp/rclcpp.hpp" #ifdef RMW_IMPLEMENTATION_SUFFIX #define STRINGIFY_(s) #s #define STRINGIFY(s) STRINGIFY_(s) #else #define STRINGIFY(s) "" #endif const char * executable_suffix = STRINGIFY(RMW_IMPLEMENTATION_SUFFIX); namespace fs = std::experimental::filesystem; std::vector<std::string> split( const std::string & s, char delim, bool skip_empty = false) { std::vector<std::string> result; std::stringstream ss; ss.str(s); std::string item; while (std::getline(ss, item, delim)) { if (skip_empty && item == "") { continue; } result.push_back(item); } return result; } int main(int argc, char * argv[]) { rclcpp::init(argc, argv); auto node = rclcpp::Node::make_shared("api_composition"); rclcpp::executors::SingleThreadedExecutor exec; exec.add_node(node); std::vector<class_loader::ClassLoader *> loaders; std::vector<std::shared_ptr<rclcpp::Node>> nodes; auto server = node->create_service<composition::srv::LoadNode>( "load_node", [&exec, &loaders, &nodes]( const std::shared_ptr<rmw_request_id_t>, const std::shared_ptr<composition::srv::LoadNode::Request> request, std::shared_ptr<composition::srv::LoadNode::Response> response) { // get node plugin resource from package std::string content; std::string base_path; if (!ament_index_cpp::get_resource("node_plugin", request->package_name, content, &base_path)) { fprintf(stderr, "Could not find requested resource in ament index\n"); response->success = false; return; } std::string plugin_name = request->plugin_name + executable_suffix; std::vector<std::string> lines = split(content, '\n', true); for (auto line : lines) { std::vector<std::string> parts = split(line, ';'); if (parts.size() != 2) { fprintf(stderr, "Invalid resource entry\n"); response->success = false; return; } // match plugin name with the same rmw suffix as this executable if (parts[0] != plugin_name) { continue; } // remove rmw suffix from plugin name to match registered class name std::string class_name = parts[0].substr( 0, parts[0].length() - strlen(executable_suffix)); // load node plugin std::string library_path = parts[1]; if (!fs::path(library_path).is_absolute()) { library_path = base_path + "/" + library_path; } printf("Load library %s\n", library_path.c_str()); class_loader::ClassLoader * loader; try { loader = new class_loader::ClassLoader(library_path); } catch (const std::exception & ex) { fprintf(stderr, "Failed to load library: %s\n", ex.what()); response->success = false; return; } catch (...) { fprintf(stderr, "Failed to load library\n"); response->success = false; return; } auto classes = loader->getAvailableClasses<rclcpp::Node>(); for (auto clazz : classes) { if (clazz == class_name) { printf("Instantiate class %s\n", clazz.c_str()); auto node = loader->createInstance<rclcpp::Node>(clazz); exec.add_node(node); nodes.push_back(node); loaders.push_back(loader); response->success = true; return; } } // no matching class found in loader delete loader; fprintf( stderr, "Failed to find class with the requested plugin name '%s' in " "the loaded library\n", plugin_name.c_str()); response->success = false; return; } fprintf( stderr, "Failed to find plugin name '%s' in prefix '%s'\n", plugin_name.c_str(), base_path.c_str()); response->success = false; }); exec.spin(); for (auto node : nodes) { exec.remove_node(node); } nodes.clear(); return 0; } <commit_msg>custom implementation for OS X until we can use libc++ 3.9<commit_after>// Copyright 2016 Open Source Robotics Foundation, 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. #ifdef __clang__ // TODO(dirk-thomas) custom implementation until we can use libc++ 3.9 #include <string> namespace fs { class path { public: explicit path(const std::string & p) : path_(p) {} bool is_absolute() { return path_[0] == '/'; } private: std::string path_; }; } // namespace fs #else # include <experimental/filesystem> namespace fs = std::experimental::filesystem; #endif #include <cstring> #include <memory> #include <sstream> #include <string> #include <vector> #include "ament_index_cpp/get_resource.hpp" #include "class_loader/class_loader.h" #include "composition/srv/load_node.hpp" #include "rclcpp/rclcpp.hpp" #ifdef RMW_IMPLEMENTATION_SUFFIX #define STRINGIFY_(s) #s #define STRINGIFY(s) STRINGIFY_(s) #else #define STRINGIFY(s) "" #endif const char * executable_suffix = STRINGIFY(RMW_IMPLEMENTATION_SUFFIX); std::vector<std::string> split( const std::string & s, char delim, bool skip_empty = false) { std::vector<std::string> result; std::stringstream ss; ss.str(s); std::string item; while (std::getline(ss, item, delim)) { if (skip_empty && item == "") { continue; } result.push_back(item); } return result; } int main(int argc, char * argv[]) { rclcpp::init(argc, argv); auto node = rclcpp::Node::make_shared("api_composition"); rclcpp::executors::SingleThreadedExecutor exec; exec.add_node(node); std::vector<class_loader::ClassLoader *> loaders; std::vector<std::shared_ptr<rclcpp::Node>> nodes; auto server = node->create_service<composition::srv::LoadNode>( "load_node", [&exec, &loaders, &nodes]( const std::shared_ptr<rmw_request_id_t>, const std::shared_ptr<composition::srv::LoadNode::Request> request, std::shared_ptr<composition::srv::LoadNode::Response> response) { // get node plugin resource from package std::string content; std::string base_path; if (!ament_index_cpp::get_resource("node_plugin", request->package_name, content, &base_path)) { fprintf(stderr, "Could not find requested resource in ament index\n"); response->success = false; return; } std::string plugin_name = request->plugin_name + executable_suffix; std::vector<std::string> lines = split(content, '\n', true); for (auto line : lines) { std::vector<std::string> parts = split(line, ';'); if (parts.size() != 2) { fprintf(stderr, "Invalid resource entry\n"); response->success = false; return; } // match plugin name with the same rmw suffix as this executable if (parts[0] != plugin_name) { continue; } // remove rmw suffix from plugin name to match registered class name std::string class_name = parts[0].substr( 0, parts[0].length() - strlen(executable_suffix)); // load node plugin std::string library_path = parts[1]; if (!fs::path(library_path).is_absolute()) { library_path = base_path + "/" + library_path; } printf("Load library %s\n", library_path.c_str()); class_loader::ClassLoader * loader; try { loader = new class_loader::ClassLoader(library_path); } catch (const std::exception & ex) { fprintf(stderr, "Failed to load library: %s\n", ex.what()); response->success = false; return; } catch (...) { fprintf(stderr, "Failed to load library\n"); response->success = false; return; } auto classes = loader->getAvailableClasses<rclcpp::Node>(); for (auto clazz : classes) { if (clazz == class_name) { printf("Instantiate class %s\n", clazz.c_str()); auto node = loader->createInstance<rclcpp::Node>(clazz); exec.add_node(node); nodes.push_back(node); loaders.push_back(loader); response->success = true; return; } } // no matching class found in loader delete loader; fprintf( stderr, "Failed to find class with the requested plugin name '%s' in " "the loaded library\n", plugin_name.c_str()); response->success = false; return; } fprintf( stderr, "Failed to find plugin name '%s' in prefix '%s'\n", plugin_name.c_str(), base_path.c_str()); response->success = false; }); exec.spin(); for (auto node : nodes) { exec.remove_node(node); } nodes.clear(); return 0; } <|endoftext|>
<commit_before>#ifndef XUTILS_HPP #define XUTILS_HPP #include <cstddef> #include <utility> #include <tuple> #include <type_traits> #include <initializer_list> namespace qs { template <class F, class... T> void for_each(F&& f, std::tuple<T...>& t); template <class F, class R, class... T> R accumulate(F&& f, R init, const std::tuple<T...>& t); template <class... T> struct or_; template <std::size_t I, class... Args> decltype(auto) argument(Args&&... args) noexcept; template<class R, class F, class... S> R apply(std::size_t index, F&& func, S&&... s); template <class U> struct initializer_dimension; /************************** * for_each implementation **************************/ namespace detail { template <std::size_t I, class F, class... T> inline typename std::enable_if<I == sizeof...(T), void>::type for_each_impl(F&& f, std::tuple<T...>& t) { } template <std::size_t I, class F, class... T> inline typename std::enable_if<I < sizeof...(T), void>::type for_each_impl(F&& f, std::tuple<T...>& t) { f(std::get<I>(t)); for_each_impl<I + 1, F, T...>(std::forward<F>(f), t); } } template <class F, class... T> inline void for_each(F&& f, std::tuple<T...>& t) { detail::for_each_impl<0, F, T...>(std::forward<F>(f), t); } /**************************** * accumulate implementation ****************************/ namespace detail { template <std::size_t I, class F, class R, class... T> inline std::enable_if_t<I == sizeof...(T), R> accumulate_impl(F&& f, R init, const std::tuple<T...>& t) { return init; } template <std::size_t I, class F, class R, class... T> inline std::enable_if_t<I < sizeof...(T), R> accumulate_impl(F&& f, R init, const std::tuple<T...>& t) { R res = f(init, std::get<I>(t)); return accumulate_impl<I + 1, F, R, T...>(std::forward<F>(f), res, t); } } template <class F, class R, class... T> inline R accumulate(F&& f, R init, const std::tuple<T...>& t) { return detail::accumulate_impl<0, F, R, T...>(f, init, t); } /********************** * or_ implementation **********************/ template <class T> struct or_<T> : std::integral_constant<bool, T::value> { }; template <class T, class... Ts> struct or_<T, Ts...> : std::integral_constant<bool, T::value || or_<Ts...>::value> { }; /************************** * argument implementation **************************/ namespace detail { template <std::size_t I> struct getter { template <class Arg, class... Args> static inline decltype(auto) get(Arg&& arg, Args&&... args) noexcept { return getter<I - 1>::get(std::forward<Args>(args)...); } }; template <> struct getter<0> { template <class Arg, class... Args> static inline Arg&& get(Arg&& arg, Args&&... args) noexcept { return std::forward<Arg>(arg); } }; } template <std::size_t I, class... Args> inline decltype(auto) argument(Args&&... args) noexcept { static_assert(I < sizeof...(Args), "I should be lesser than sizeof...(Args)"); return detail::getter<I>::get(std::forward<Args>(args)...); } /************************ * apply implementation ************************/ namespace detail { template<class R, class F, std::size_t I, class... S> R apply_one(F&& func, S&&... s) { return func(argument<I>(s...)); } template<class R, class F, std::size_t... I, class... S> R apply(std::size_t index, F&& func, std::index_sequence<I...>, S&&... s) { using FT = R(F, S&&...); static constexpr FT* arr[] = { &apply_one<R, F, I, S...>... }; return arr[index](std::forward<F>(func), std::forward<S>(s)...); } } template<class R, class F, class... S> R apply(std::size_t index, F&& func, S&&... s) { return detail::apply<R>(index, std::forward<F>(func), std::make_index_sequence<sizeof...(S)>(), std::forward<S>(s)...); } /*************************************** * initializer_dimension implementation ***************************************/ namespace detail { template <class U> struct initializer_depth_impl { static constexpr std::size_t value = 0; }; template <class T> struct initializer_depth_impl<std::initializer_list<T>> { static constexpr std::size_t value = 1 + initializer_depth_impl<T>::value; }; } template <class U> struct initializer_dimension { static constexpr std::size_t value = detail::initializer_depth_impl<U>::value; }; /*********************************** * initializer_shape implementation ***********************************/ namespace detail { template <std::size_t I> struct initializer_shape_impl { template <class T> static constexpr std::size_t value(T t) { return t.size() == 0 ? 0 : initializer_shape_impl<I - 1>::value(*t.begin()); } }; template <> struct initializer_shape_impl<0> { template <class T> static constexpr std::size_t value(T t) { return t.size(); } }; template <class R, class U, std::size_t... I> constexpr R initializer_shape(U t, std::index_sequence<I...>) { return { initializer_shape_impl<I>::value(t)... }; } } template <class R, class T> constexpr R initializer_shape(T t) { return detail::initializer_shape<R, decltype(t)>(t, std::make_index_sequence<initializer_dimension<decltype(t)>::value>()); } template <class R, class T> constexpr R initializer_shape(std::initializer_list<T> t) { return detail::initializer_shape<R, decltype(t)>(t, std::make_index_sequence<initializer_dimension<decltype(t)>::value>()); } template <class R, class T> constexpr R initializer_shape(std::initializer_list<std::initializer_list<T>> t) { return detail::initializer_shape<R, decltype(t)>(t, std::make_index_sequence<initializer_dimension<decltype(t)>::value>()); } /***************************** * nested_copy implementation *****************************/ template <class T, class S> inline void nested_copy(T&& iter, const S& s) { *iter++ = s; } template <class T, class S> inline void nested_copy(T&& iter, std::initializer_list<S> s) { for (auto it = s.begin(); it != s.end(); ++it) { nested_copy(std::forward<T>(iter), *it); } } template <class T, class S> inline void nested_copy(T&& iter, std::initializer_list<std::initializer_list<S>> s) { for (auto it = s.begin(); it != s.end(); ++it) { nested_copy(std::forward<T>(iter), *it); } } } #endif <commit_msg>indent<commit_after>#ifndef XUTILS_HPP #define XUTILS_HPP #include <cstddef> #include <utility> #include <tuple> #include <type_traits> #include <initializer_list> namespace qs { template <class F, class... T> void for_each(F&& f, std::tuple<T...>& t); template <class F, class R, class... T> R accumulate(F&& f, R init, const std::tuple<T...>& t); template <class... T> struct or_; template <std::size_t I, class... Args> decltype(auto) argument(Args&&... args) noexcept; template<class R, class F, class... S> R apply(std::size_t index, F&& func, S&&... s); template <class U> struct initializer_dimension; /************************** * for_each implementation **************************/ namespace detail { template <std::size_t I, class F, class... T> inline typename std::enable_if<I == sizeof...(T), void>::type for_each_impl(F&& f, std::tuple<T...>& t) { } template <std::size_t I, class F, class... T> inline typename std::enable_if<I < sizeof...(T), void>::type for_each_impl(F&& f, std::tuple<T...>& t) { f(std::get<I>(t)); for_each_impl<I + 1, F, T...>(std::forward<F>(f), t); } } template <class F, class... T> inline void for_each(F&& f, std::tuple<T...>& t) { detail::for_each_impl<0, F, T...>(std::forward<F>(f), t); } /**************************** * accumulate implementation ****************************/ namespace detail { template <std::size_t I, class F, class R, class... T> inline std::enable_if_t<I == sizeof...(T), R> accumulate_impl(F&& f, R init, const std::tuple<T...>& t) { return init; } template <std::size_t I, class F, class R, class... T> inline std::enable_if_t<I < sizeof...(T), R> accumulate_impl(F&& f, R init, const std::tuple<T...>& t) { R res = f(init, std::get<I>(t)); return accumulate_impl<I + 1, F, R, T...>(std::forward<F>(f), res, t); } } template <class F, class R, class... T> inline R accumulate(F&& f, R init, const std::tuple<T...>& t) { return detail::accumulate_impl<0, F, R, T...>(f, init, t); } /********************** * or_ implementation **********************/ template <class T> struct or_<T> : std::integral_constant<bool, T::value> { }; template <class T, class... Ts> struct or_<T, Ts...> : std::integral_constant<bool, T::value || or_<Ts...>::value> { }; /************************** * argument implementation **************************/ namespace detail { template <std::size_t I> struct getter { template <class Arg, class... Args> static inline decltype(auto) get(Arg&& arg, Args&&... args) noexcept { return getter<I - 1>::get(std::forward<Args>(args)...); } }; template <> struct getter<0> { template <class Arg, class... Args> static inline Arg&& get(Arg&& arg, Args&&... args) noexcept { return std::forward<Arg>(arg); } }; } template <std::size_t I, class... Args> inline decltype(auto) argument(Args&&... args) noexcept { static_assert(I < sizeof...(Args), "I should be lesser than sizeof...(Args)"); return detail::getter<I>::get(std::forward<Args>(args)...); } /************************ * apply implementation ************************/ namespace detail { template<class R, class F, std::size_t I, class... S> R apply_one(F&& func, S&&... s) { return func(argument<I>(s...)); } template<class R, class F, std::size_t... I, class... S> R apply(std::size_t index, F&& func, std::index_sequence<I...>, S&&... s) { using FT = R(F, S&&...); static constexpr FT* arr[] = { &apply_one<R, F, I, S...>... }; return arr[index](std::forward<F>(func), std::forward<S>(s)...); } } template<class R, class F, class... S> R apply(std::size_t index, F&& func, S&&... s) { return detail::apply<R>(index, std::forward<F>(func), std::make_index_sequence<sizeof...(S)>(), std::forward<S>(s)...); } /*************************************** * initializer_dimension implementation ***************************************/ namespace detail { template <class U> struct initializer_depth_impl { static constexpr std::size_t value = 0; }; template <class T> struct initializer_depth_impl<std::initializer_list<T>> { static constexpr std::size_t value = 1 + initializer_depth_impl<T>::value; }; } template <class U> struct initializer_dimension { static constexpr std::size_t value = detail::initializer_depth_impl<U>::value; }; /*********************************** * initializer_shape implementation ***********************************/ namespace detail { template <std::size_t I> struct initializer_shape_impl { template <class T> static constexpr std::size_t value(T t) { return t.size() == 0 ? 0 : initializer_shape_impl<I - 1>::value(*t.begin()); } }; template <> struct initializer_shape_impl<0> { template <class T> static constexpr std::size_t value(T t) { return t.size(); } }; template <class R, class U, std::size_t... I> constexpr R initializer_shape(U t, std::index_sequence<I...>) { return { initializer_shape_impl<I>::value(t)... }; } } template <class R, class T> constexpr R initializer_shape(T t) { return detail::initializer_shape<R, decltype(t)>(t, std::make_index_sequence<initializer_dimension<decltype(t)>::value>()); } template <class R, class T> constexpr R initializer_shape(std::initializer_list<T> t) { return detail::initializer_shape<R, decltype(t)>(t, std::make_index_sequence<initializer_dimension<decltype(t)>::value>()); } template <class R, class T> constexpr R initializer_shape(std::initializer_list<std::initializer_list<T>> t) { return detail::initializer_shape<R, decltype(t)>(t, std::make_index_sequence<initializer_dimension<decltype(t)>::value>()); } /***************************** * nested_copy implementation *****************************/ template <class T, class S> inline void nested_copy(T&& iter, const S& s) { *iter++ = s; } template <class T, class S> inline void nested_copy(T&& iter, std::initializer_list<S> s) { for (auto it = s.begin(); it != s.end(); ++it) { nested_copy(std::forward<T>(iter), *it); } } template <class T, class S> inline void nested_copy(T&& iter, std::initializer_list<std::initializer_list<S>> s) { for (auto it = s.begin(); it != s.end(); ++it) { nested_copy(std::forward<T>(iter), *it); } } } #endif <|endoftext|>
<commit_before>// $Id: AliHLTTPCClusterTransformation.cxx 41244 2010-05-14 08:13:35Z kkanaki $ //************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Kalliopi Kanaki <Kalliopi.Kanaki@ift.uib.no> * //* for The ALICE HLT Project. * //* * //* 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. * //************************************************************************** /** @file AliHLTTPCClusterTransformation.cxx @author Kalliopi Kanaki, Sergey Gorbubnov @date @brief */ #include "AliHLTTPCClusterTransformation.h" #include "AliHLTTPCTransform.h" #include "AliHLTTPCFastTransform.h" #include "AliCDBPath.h" #include "AliCDBManager.h" #include "AliCDBEntry.h" #include "AliGRPObject.h" #include "AliTPCcalibDB.h" #include "AliTPCTransform.h" #include "AliTPCParam.h" #include "AliTPCRecoParam.h" #include "AliGeomManager.h" #include "AliRunInfo.h" #include "AliEventInfo.h" #include "AliRawEventHeaderBase.h" #include <iostream> #include <iomanip> using namespace std; ClassImp(AliHLTTPCClusterTransformation) //ROOT macro for the implementation of ROOT specific class methods AliRecoParam AliHLTTPCClusterTransformation::fOfflineRecoParam; AliHLTTPCClusterTransformation::AliHLTTPCClusterTransformation() : fError(), fFastTransform() { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } AliHLTTPCClusterTransformation::~AliHLTTPCClusterTransformation() { // see header file for class documentation } int AliHLTTPCClusterTransformation::Init( double FieldBz, Long_t TimeStamp ) { // Initialisation if(!AliGeomManager::GetGeometry()){ AliGeomManager::LoadGeometry(); } if(!AliGeomManager::GetGeometry()) return Error(-1,"AliHLTTPCClusterTransformation::Init: Can not initialise geometry"); AliTPCcalibDB* pCalib=AliTPCcalibDB::Instance(); if(!pCalib ) return Error(-2,"AliHLTTPCClusterTransformation::Init: Calibration not found"); pCalib->SetExBField(FieldBz); if( !pCalib->GetTransform() ) return Error(-3,"AliHLTTPCClusterTransformation::Init: No TPC transformation found"); // -- Get AliRunInfo variables AliGRPObject tmpGRP, *pGRP=0; AliCDBEntry *entry = AliCDBManager::Instance()->Get("GRP/GRP/Data"); if(!entry) return Error(-4,"AliHLTTPCClusterTransformation::Init: No GRP object found in data base"); { TMap* m = dynamic_cast<TMap*>(entry->GetObject()); // old GRP entry if (m) { //cout<<"Found a TMap in GRP/GRP/Data, converting it into an AliGRPObject"<<endl; m->Print(); pGRP = &tmpGRP; pGRP->ReadValuesFromMap(m); } else { //cout<<"Found an AliGRPObject in GRP/GRP/Data, reading it"<<endl; pGRP = dynamic_cast<AliGRPObject*>(entry->GetObject()); // new GRP entry } } if( !pGRP ){ return Error(-5,"AliHLTTPCClusterTransformation::Init: Unknown format of the GRP object in data base"); } AliRunInfo runInfo(pGRP->GetLHCState(),pGRP->GetBeamType(),pGRP->GetBeamEnergy(),pGRP->GetRunType(),pGRP->GetDetectorMask()); AliEventInfo evInfo; evInfo.SetEventType(AliRawEventHeaderBase::kPhysicsEvent); entry=AliCDBManager::Instance()->Get("TPC/Calib/RecoParam"); if(!entry) return Error(-6,"AliHLTTPCClusterTransformation::Init: No TPC reco param entry found in data base"); TObject *recoParamObj = entry->GetObject(); if(!recoParamObj) return Error(-7,"AliHLTTPCClusterTransformation::Init: Empty TPC reco param entry in data base"); if (dynamic_cast<TObjArray*>(recoParamObj)) { //cout<<"\n\nSet reco param from AliHLTTPCClusterTransformation: TObjArray found \n"<<endl; fOfflineRecoParam.AddDetRecoParamArray(1,dynamic_cast<TObjArray*>(recoParamObj)); } else if (dynamic_cast<AliDetectorRecoParam*>(recoParamObj)) { //cout<<"\n\nSet reco param from AliHLTTPCClusterTransformation: AliDetectorRecoParam found \n"<<endl; fOfflineRecoParam.AddDetRecoParam(1,dynamic_cast<AliDetectorRecoParam*>(recoParamObj)); } else { return Error(-8,"AliHLTTPCClusterTransformation::Init: Unknown format of the TPC Reco Param entry in the data base"); } fOfflineRecoParam.SetEventSpecie(&runInfo, evInfo, 0); // AliTPCRecoParam* recParam = (AliTPCRecoParam*)fOfflineRecoParam.GetDetRecoParam(1); if( !recParam ) return Error(-9,"AliHLTTPCClusterTransformation::Init: No TPC Reco Param entry found for the given event specification"); pCalib->GetTransform()->SetCurrentRecoParam(recParam); // set current time stamp and initialize the fast transformation int err = fFastTransform.Init( pCalib->GetTransform(), TimeStamp ); if( err!=0 ){ return Error(-10,Form( "AliHLTTPCClusterTransformation::Init: Initialisation of Fast Transformation failed with error %d :%s",err,fFastTransform.GetLastError()) ); } return 0; } Bool_t AliHLTTPCClusterTransformation::IsInitialised() const { // Is the transformation initialised return fFastTransform.IsInitialised(); } void AliHLTTPCClusterTransformation::DeInit() { // Deinitialisation fFastTransform.DeInit(); } Int_t AliHLTTPCClusterTransformation::SetCurrentTimeStamp( Long_t TimeStamp ) { // Set the current time stamp AliTPCRecoParam* recParam = (AliTPCRecoParam*)fOfflineRecoParam.GetDetRecoParam(1); if( !recParam ) return Error(-1,"AliHLTTPCClusterTransformation::SetCurrentTimeStamp: No TPC Reco Param entry found"); AliTPCcalibDB* pCalib=AliTPCcalibDB::Instance(); if(!pCalib ) return Error(-2,"AliHLTTPCClusterTransformation::Init: Calibration not found"); if( !pCalib->GetTransform() ) return Error(-3,"AliHLTTPCClusterTransformation::SetCurrentTimeStamp: No TPC transformation found"); pCalib->GetTransform()->SetCurrentRecoParam(recParam); int err = fFastTransform.SetCurrentTimeStamp( TimeStamp ); if( err!=0 ){ return Error(-4,Form( "AliHLTTPCClusterTransformation::SetCurrentTimeStamp: SetCurrentTimeStamp to the Fast Transformation failed with error %d :%s",err,fFastTransform.GetLastError()) ); } return 0; } void AliHLTTPCClusterTransformation::Print(const char* /*option*/) const { // print info fFastTransform.Print(); } <commit_msg>Bug fix: savannah 99025 Put clones of OCDB objects to AliRecoParam to avoid double delete of these objects<commit_after>// $Id: AliHLTTPCClusterTransformation.cxx 41244 2010-05-14 08:13:35Z kkanaki $ //************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Kalliopi Kanaki <Kalliopi.Kanaki@ift.uib.no> * //* for The ALICE HLT Project. * //* * //* 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. * //************************************************************************** /** @file AliHLTTPCClusterTransformation.cxx @author Kalliopi Kanaki, Sergey Gorbubnov @date @brief */ #include "AliHLTTPCClusterTransformation.h" #include "AliHLTTPCTransform.h" #include "AliHLTTPCFastTransform.h" #include "AliCDBPath.h" #include "AliCDBManager.h" #include "AliCDBEntry.h" #include "AliGRPObject.h" #include "AliTPCcalibDB.h" #include "AliTPCTransform.h" #include "AliTPCParam.h" #include "AliTPCRecoParam.h" #include "AliGeomManager.h" #include "AliRunInfo.h" #include "AliEventInfo.h" #include "AliRawEventHeaderBase.h" #include <iostream> #include <iomanip> using namespace std; ClassImp(AliHLTTPCClusterTransformation) //ROOT macro for the implementation of ROOT specific class methods AliRecoParam AliHLTTPCClusterTransformation::fOfflineRecoParam; AliHLTTPCClusterTransformation::AliHLTTPCClusterTransformation() : fError(), fFastTransform() { // see header file for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt } AliHLTTPCClusterTransformation::~AliHLTTPCClusterTransformation() { // see header file for class documentation } int AliHLTTPCClusterTransformation::Init( double FieldBz, Long_t TimeStamp ) { // Initialisation if(!AliGeomManager::GetGeometry()){ AliGeomManager::LoadGeometry(); } if(!AliGeomManager::GetGeometry()) return Error(-1,"AliHLTTPCClusterTransformation::Init: Can not initialise geometry"); AliTPCcalibDB* pCalib=AliTPCcalibDB::Instance(); if(!pCalib ) return Error(-2,"AliHLTTPCClusterTransformation::Init: Calibration not found"); pCalib->SetExBField(FieldBz); if( !pCalib->GetTransform() ) return Error(-3,"AliHLTTPCClusterTransformation::Init: No TPC transformation found"); // -- Get AliRunInfo variables AliGRPObject tmpGRP, *pGRP=0; AliCDBEntry *entry = AliCDBManager::Instance()->Get("GRP/GRP/Data"); if(!entry) return Error(-4,"AliHLTTPCClusterTransformation::Init: No GRP object found in data base"); { TMap* m = dynamic_cast<TMap*>(entry->GetObject()); // old GRP entry if (m) { //cout<<"Found a TMap in GRP/GRP/Data, converting it into an AliGRPObject"<<endl; m->Print(); pGRP = &tmpGRP; pGRP->ReadValuesFromMap(m); } else { //cout<<"Found an AliGRPObject in GRP/GRP/Data, reading it"<<endl; pGRP = dynamic_cast<AliGRPObject*>(entry->GetObject()); // new GRP entry } } if( !pGRP ){ return Error(-5,"AliHLTTPCClusterTransformation::Init: Unknown format of the GRP object in data base"); } AliRunInfo runInfo(pGRP->GetLHCState(),pGRP->GetBeamType(),pGRP->GetBeamEnergy(),pGRP->GetRunType(),pGRP->GetDetectorMask()); AliEventInfo evInfo; evInfo.SetEventType(AliRawEventHeaderBase::kPhysicsEvent); entry=AliCDBManager::Instance()->Get("TPC/Calib/RecoParam"); if(!entry) return Error(-6,"AliHLTTPCClusterTransformation::Init: No TPC reco param entry found in data base"); TObject *recoParamObj = entry->GetObject(); if(!recoParamObj) return Error(-7,"AliHLTTPCClusterTransformation::Init: Empty TPC reco param entry in data base"); if (dynamic_cast<TObjArray*>(recoParamObj)) { //cout<<"\n\nSet reco param from AliHLTTPCClusterTransformation: TObjArray found \n"<<endl; TObjArray *copy = (TObjArray*)( static_cast<TObjArray*>(recoParamObj)->Clone() ); fOfflineRecoParam.AddDetRecoParamArray(1,copy); } else if (dynamic_cast<AliDetectorRecoParam*>(recoParamObj)) { //cout<<"\n\nSet reco param from AliHLTTPCClusterTransformation: AliDetectorRecoParam found \n"<<endl; AliDetectorRecoParam *copy = (AliDetectorRecoParam*)static_cast<AliDetectorRecoParam*>(recoParamObj)->Clone(); fOfflineRecoParam.AddDetRecoParam(1,copy); } else { return Error(-8,"AliHLTTPCClusterTransformation::Init: Unknown format of the TPC Reco Param entry in the data base"); } fOfflineRecoParam.SetEventSpecie(&runInfo, evInfo, 0); // AliTPCRecoParam* recParam = (AliTPCRecoParam*)fOfflineRecoParam.GetDetRecoParam(1); if( !recParam ) return Error(-9,"AliHLTTPCClusterTransformation::Init: No TPC Reco Param entry found for the given event specification"); pCalib->GetTransform()->SetCurrentRecoParam(recParam); // set current time stamp and initialize the fast transformation int err = fFastTransform.Init( pCalib->GetTransform(), TimeStamp ); if( err!=0 ){ return Error(-10,Form( "AliHLTTPCClusterTransformation::Init: Initialisation of Fast Transformation failed with error %d :%s",err,fFastTransform.GetLastError()) ); } return 0; } Bool_t AliHLTTPCClusterTransformation::IsInitialised() const { // Is the transformation initialised return fFastTransform.IsInitialised(); } void AliHLTTPCClusterTransformation::DeInit() { // Deinitialisation fFastTransform.DeInit(); } Int_t AliHLTTPCClusterTransformation::SetCurrentTimeStamp( Long_t TimeStamp ) { // Set the current time stamp AliTPCRecoParam* recParam = (AliTPCRecoParam*)fOfflineRecoParam.GetDetRecoParam(1); if( !recParam ) return Error(-1,"AliHLTTPCClusterTransformation::SetCurrentTimeStamp: No TPC Reco Param entry found"); AliTPCcalibDB* pCalib=AliTPCcalibDB::Instance(); if(!pCalib ) return Error(-2,"AliHLTTPCClusterTransformation::Init: Calibration not found"); if( !pCalib->GetTransform() ) return Error(-3,"AliHLTTPCClusterTransformation::SetCurrentTimeStamp: No TPC transformation found"); pCalib->GetTransform()->SetCurrentRecoParam(recParam); int err = fFastTransform.SetCurrentTimeStamp( TimeStamp ); if( err!=0 ){ return Error(-4,Form( "AliHLTTPCClusterTransformation::SetCurrentTimeStamp: SetCurrentTimeStamp to the Fast Transformation failed with error %d :%s",err,fFastTransform.GetLastError()) ); } return 0; } void AliHLTTPCClusterTransformation::Print(const char* /*option*/) const { // print info fFastTransform.Print(); } <|endoftext|>
<commit_before>//================================================================================================= // Copyright (c) 2016, Stefan Kohlbrecher, TU Darmstadt // 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 Simulation, Systems Optimization and Robotics // group, TU Darmstadt 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. //================================================================================================= #include <grid_map_planner_lib/grid_map_planner.h> #include <grid_map_cv/grid_map_cv.hpp> #include <grid_map_proc/grid_map_transforms.h> #include <grid_map_proc/grid_map_path_planning.h> #include <opencv2/core/eigen.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> using namespace grid_map_planner; GridMapPlanner::GridMapPlanner() { } GridMapPlanner::~GridMapPlanner() { } bool GridMapPlanner::setMap(const grid_map::GridMap& map) { if (!map.exists("occupancy")){ ROS_ERROR("Tried to set map for grid map planner, but has no occupancy layer!"); return false; } this->planning_map_ = map; return true; /* ros::WallTime start_time = ros::WallTime::now(); if (!grid_map_transforms::addDistanceTransformCv(this->planning_map_)){ ROS_WARN("Unable to generate distance transform!"); } ROS_INFO_STREAM("Distance transform took " << (ros::WallTime::now() - start_time).toSec() * 1000 << " ms\n"); std::vector<grid_map::Index> goals; goals.push_back(grid_map::Index(200, 310)); start_time = ros::WallTime::now(); if (!grid_map_transforms::addExplorationTransform(this->planning_map_, goals)){ ROS_WARN("Unable to generate distance transform!"); } ROS_INFO_STREAM ("Exploration transform took " << (ros::WallTime::now() - start_time).toSec() * 1000 << " ms\n"); //std::cout << "layers: " << this->planning_map_.getLayers().size() << "\n"; */ } bool GridMapPlanner::makeExplorationPlan(const geometry_msgs::Pose &start,std::vector<geometry_msgs::PoseStamped> &plan) { if (!this->planning_map_.exists("occupancy")){ ROS_ERROR("Tried to generate exploration plan, but map has no occupancy layer!"); return false; } grid_map::Index start_index; if (!this->planning_map_.getIndex(grid_map::Position(start.position.x, start.position.y), start_index)) { ROS_WARN("Goal coords outside map, unable to plan!"); return false; } if (!grid_map_transforms::addDistanceTransform(this->planning_map_, start_index, obstacle_cells_, frontier_cells_)) { ROS_WARN("Failed to compute distance transform!"); return false; } if (!grid_map_transforms::addExplorationTransform(this->planning_map_, frontier_cells_)){ ROS_WARN("Unable to generate exploration transform!"); return false; } if(!grid_map_path_planning::findPathExplorationTransform(this->planning_map_, start, plan)){ ROS_WARN("Find path on exploration transform failed!"); return false; } return true; } bool GridMapPlanner::makePlan(const geometry_msgs::Pose &start, const geometry_msgs::Pose &original_goal, std::vector<geometry_msgs::PoseStamped> &plan, float* plan_cost) { if (!this->planning_map_.exists("occupancy")){ ROS_ERROR("Tried to generate plan to goal, but map has no occupancy layer!"); return false; } grid_map::Index start_index; if (!this->planning_map_.getIndex(grid_map::Position(start.position.x, start.position.y), start_index)) { ROS_WARN("Start coords %f outside map, unable to plan!",start); return false; } if (!grid_map_transforms::addDistanceTransform(this->planning_map_, start_index, obstacle_cells_, frontier_cells_)) { ROS_WARN_STREAM("Failed computing reachable obstacle cells!" << start.position.x << start.position.y); return false; } std::vector<grid_map::Index> goals; grid_map::Index goal_index; if (!this->planning_map_.getIndex(grid_map::Position(original_goal.position.x, original_goal.position.y), goal_index)) { ROS_WARN("Original goal coords %f, %f outside map, unable to plan!",original_goal.position.x, original_goal.position.y); return false; } // Adjust goal pose and try to move it farther away from walls if possible grid_map::Index goal_index_adjusted; if (grid_map_path_planning::findValidClosePoseExplorationTransform(this->planning_map_, goal_index, goal_index_adjusted)) { ROS_INFO("Moved goal"); goal_index = goal_index_adjusted; } goals.push_back(goal_index); if (!grid_map_transforms::addExplorationTransform(this->planning_map_, goals)){ ROS_WARN("Unable to generate exploration transform!"); return false; } geometry_msgs::Pose adjusted_start; grid_map_path_planning::adjustStartPoseIfOccupied(this->planning_map_, start, adjusted_start); if(!grid_map_path_planning::findPathExplorationTransform(this->planning_map_, adjusted_start, plan, plan_cost)){ ROS_WARN("Find path on exploration transform failed!"); return false; } plan.back().pose.orientation = original_goal.orientation; return true; } bool GridMapPlanner::makePlan(const geometry_msgs::Pose &start, const std::vector<boost::shared_ptr<grid_map_planner_goal_types::MapGoalBase> >& map_goals, std::vector<geometry_msgs::PoseStamped> &plan, int& reached_goal_idx, float* plan_cost) { if (!this->planning_map_.exists("occupancy")){ ROS_ERROR("Tried to generate plan to multiple goal poses, but map has no occupancy layer!"); return false; } //return false; grid_map::Index start_index; if (!this->planning_map_.getIndex(grid_map::Position(start.position.x, start.position.y), start_index)) { ROS_WARN("Start coords outside map, unable to plan!"); return false; } if (!grid_map_transforms::addDistanceTransform(this->planning_map_, start_index, obstacle_cells_, frontier_cells_)) { ROS_WARN("Failed computing reachable obstacle cells!"); return false; } std::vector<grid_map::Index> goals; //grid_map::Index goal_index; for (size_t i = 0; i < map_goals.size(); ++i) { map_goals[i]->getGoalIndices(goals); } //std::cout << "map_goals size " << map_goals.size() << " goals size: " << goals.size() << "\n"; if (!grid_map_transforms::addExplorationTransform(this->planning_map_, goals)){ ROS_WARN("Unable to generate exploration transform!"); return false; } geometry_msgs::Pose adjusted_start; grid_map_path_planning::adjustStartPoseIfOccupied(this->planning_map_, start, adjusted_start); if(!grid_map_path_planning::findPathExplorationTransform(this->planning_map_, adjusted_start, plan, plan_cost)){ ROS_WARN("Find path on exploration transform failed!"); return false; } grid_map::Index found_goal_idx; this->planning_map_.getIndex(grid_map::Position(plan.back().pose.position.x, plan.back().pose.position.y), found_goal_idx); if (map_goals.size() == 1){ reached_goal_idx = 0; }else{ for (size_t i = 0; i < map_goals.size(); ++i) { if (map_goals[i]->isReached(found_goal_idx)) { reached_goal_idx = i; break; } } } plan.back().pose.orientation = map_goals[reached_goal_idx]->getOrientation(); return true; } <commit_msg>Add start pose adjustment for exploration<commit_after>//================================================================================================= // Copyright (c) 2016, Stefan Kohlbrecher, TU Darmstadt // 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 Simulation, Systems Optimization and Robotics // group, TU Darmstadt 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. //================================================================================================= #include <grid_map_planner_lib/grid_map_planner.h> #include <grid_map_cv/grid_map_cv.hpp> #include <grid_map_proc/grid_map_transforms.h> #include <grid_map_proc/grid_map_path_planning.h> #include <opencv2/core/eigen.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> using namespace grid_map_planner; GridMapPlanner::GridMapPlanner() { } GridMapPlanner::~GridMapPlanner() { } bool GridMapPlanner::setMap(const grid_map::GridMap& map) { if (!map.exists("occupancy")){ ROS_ERROR("Tried to set map for grid map planner, but has no occupancy layer!"); return false; } this->planning_map_ = map; return true; /* ros::WallTime start_time = ros::WallTime::now(); if (!grid_map_transforms::addDistanceTransformCv(this->planning_map_)){ ROS_WARN("Unable to generate distance transform!"); } ROS_INFO_STREAM("Distance transform took " << (ros::WallTime::now() - start_time).toSec() * 1000 << " ms\n"); std::vector<grid_map::Index> goals; goals.push_back(grid_map::Index(200, 310)); start_time = ros::WallTime::now(); if (!grid_map_transforms::addExplorationTransform(this->planning_map_, goals)){ ROS_WARN("Unable to generate distance transform!"); } ROS_INFO_STREAM ("Exploration transform took " << (ros::WallTime::now() - start_time).toSec() * 1000 << " ms\n"); //std::cout << "layers: " << this->planning_map_.getLayers().size() << "\n"; */ } bool GridMapPlanner::makeExplorationPlan(const geometry_msgs::Pose &start,std::vector<geometry_msgs::PoseStamped> &plan) { if (!this->planning_map_.exists("occupancy")){ ROS_ERROR("Tried to generate exploration plan, but map has no occupancy layer!"); return false; } grid_map::Index start_index; if (!this->planning_map_.getIndex(grid_map::Position(start.position.x, start.position.y), start_index)) { ROS_WARN("Goal coords outside map, unable to plan!"); return false; } if (!grid_map_transforms::addDistanceTransform(this->planning_map_, start_index, obstacle_cells_, frontier_cells_)) { ROS_WARN("Failed to compute distance transform!"); return false; } if (!grid_map_transforms::addExplorationTransform(this->planning_map_, frontier_cells_)){ ROS_WARN("Unable to generate exploration transform!"); return false; } geometry_msgs::Pose adjusted_start; grid_map_path_planning::adjustStartPoseIfOccupied(this->planning_map_, start, adjusted_start); if(!grid_map_path_planning::findPathExplorationTransform(this->planning_map_, adjusted_start, plan)){ ROS_WARN("Find path on exploration transform failed!"); return false; } return true; } bool GridMapPlanner::makePlan(const geometry_msgs::Pose &start, const geometry_msgs::Pose &original_goal, std::vector<geometry_msgs::PoseStamped> &plan, float* plan_cost) { if (!this->planning_map_.exists("occupancy")){ ROS_ERROR("Tried to generate plan to goal, but map has no occupancy layer!"); return false; } grid_map::Index start_index; if (!this->planning_map_.getIndex(grid_map::Position(start.position.x, start.position.y), start_index)) { ROS_WARN("Start coords %f outside map, unable to plan!",start); return false; } if (!grid_map_transforms::addDistanceTransform(this->planning_map_, start_index, obstacle_cells_, frontier_cells_)) { ROS_WARN_STREAM("Failed computing reachable obstacle cells!" << start.position.x << start.position.y); return false; } std::vector<grid_map::Index> goals; grid_map::Index goal_index; if (!this->planning_map_.getIndex(grid_map::Position(original_goal.position.x, original_goal.position.y), goal_index)) { ROS_WARN("Original goal coords %f, %f outside map, unable to plan!",original_goal.position.x, original_goal.position.y); return false; } // Adjust goal pose and try to move it farther away from walls if possible grid_map::Index goal_index_adjusted; if (grid_map_path_planning::findValidClosePoseExplorationTransform(this->planning_map_, goal_index, goal_index_adjusted)) { ROS_INFO("Moved goal"); goal_index = goal_index_adjusted; } goals.push_back(goal_index); if (!grid_map_transforms::addExplorationTransform(this->planning_map_, goals)){ ROS_WARN("Unable to generate exploration transform!"); return false; } geometry_msgs::Pose adjusted_start; grid_map_path_planning::adjustStartPoseIfOccupied(this->planning_map_, start, adjusted_start); if(!grid_map_path_planning::findPathExplorationTransform(this->planning_map_, adjusted_start, plan, plan_cost)){ ROS_WARN("Find path on exploration transform failed!"); return false; } plan.back().pose.orientation = original_goal.orientation; return true; } bool GridMapPlanner::makePlan(const geometry_msgs::Pose &start, const std::vector<boost::shared_ptr<grid_map_planner_goal_types::MapGoalBase> >& map_goals, std::vector<geometry_msgs::PoseStamped> &plan, int& reached_goal_idx, float* plan_cost) { if (!this->planning_map_.exists("occupancy")){ ROS_ERROR("Tried to generate plan to multiple goal poses, but map has no occupancy layer!"); return false; } //return false; grid_map::Index start_index; if (!this->planning_map_.getIndex(grid_map::Position(start.position.x, start.position.y), start_index)) { ROS_WARN("Start coords outside map, unable to plan!"); return false; } if (!grid_map_transforms::addDistanceTransform(this->planning_map_, start_index, obstacle_cells_, frontier_cells_)) { ROS_WARN("Failed computing reachable obstacle cells!"); return false; } std::vector<grid_map::Index> goals; //grid_map::Index goal_index; for (size_t i = 0; i < map_goals.size(); ++i) { map_goals[i]->getGoalIndices(goals); } //std::cout << "map_goals size " << map_goals.size() << " goals size: " << goals.size() << "\n"; if (!grid_map_transforms::addExplorationTransform(this->planning_map_, goals)){ ROS_WARN("Unable to generate exploration transform!"); return false; } geometry_msgs::Pose adjusted_start; grid_map_path_planning::adjustStartPoseIfOccupied(this->planning_map_, start, adjusted_start); if(!grid_map_path_planning::findPathExplorationTransform(this->planning_map_, adjusted_start, plan, plan_cost)){ ROS_WARN("Find path on exploration transform failed!"); return false; } grid_map::Index found_goal_idx; this->planning_map_.getIndex(grid_map::Position(plan.back().pose.position.x, plan.back().pose.position.y), found_goal_idx); if (map_goals.size() == 1){ reached_goal_idx = 0; }else{ for (size_t i = 0; i < map_goals.size(); ++i) { if (map_goals[i]->isReached(found_goal_idx)) { reached_goal_idx = i; break; } } } plan.back().pose.orientation = map_goals[reached_goal_idx]->getOrientation(); return true; } <|endoftext|>
<commit_before>/* ** Copyright 2011-2014 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <sstream> #include <QHostAddress> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/influxdb/influxdb9.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/influxdb/json_printer.hh" using namespace com::centreon::broker::influxdb; static const char* query_footer = "]}"; /** * Constructor. */ influxdb9::influxdb9( std::string const& user, std::string const& passwd, std::string const& addr, unsigned short port, std::string const& db) : _host(addr), _port(port) { logging::debug(logging::medium) << "influxdb: connecting using 0.9 version protocol"; _connect_socket(); _socket->close(); std::string base_url; base_url .append("/db/").append(db) .append("/series?u=").append(user) .append("&p=").append(passwd) .append("&time_precision=s"); _post_header.append("POST ").append(base_url).append(" HTTP/1.0\n"); json_printer p; p.open_object().add_string("database", db).open_array("points"); _db_header.append(p.get_data()); } /** * Copy constructor. * * @param[in] f Object to copy. */ influxdb9::influxdb9(influxdb9 const& f) { influxdb::operator=(f); } /** * Destructor. */ influxdb9::~influxdb9() {} /** * Assignment operator. * * @param[in] f Object to copy. * * @return This object. */ influxdb9& influxdb9::operator=(influxdb9 const& f) { if (this != &f) { _query = f._query; } return (*this); } /** * Clear the query. */ void influxdb9::clear() { _query.clear(); } /** * Write a metric to the query. * * @param[in] m The metric to write. */ void influxdb9::write(storage::metric const& m) { json_printer p; p.open_object() .add_string("name", m.name.toStdString()) .open_object("tags") .add_string("metric_id", m.metric_id) .close_object() .add_number("timestamp", m.ctime) .open_object("fields") .add_number("value", m.value) .close_object() .close_object(); _query.append(p.get_data()); } /** * Commit a query. */ void influxdb9::commit() { if (_query.empty()) return ; // Remove trailing coma. _query[_query.size() - 1] = ' '; std::stringstream content_length; size_t length = _query.size() + _db_header.size() + ::strlen(query_footer); content_length << "Content-Length: " << length << "\n"; std::string final_query; final_query.reserve(length + _post_header.size() + content_length.str().size() + 1); final_query .append(_post_header).append(content_length.str()).append("\n") .append(_db_header).append(_query).append(query_footer); _connect_socket(); if (_socket->write(final_query.c_str(), final_query.size()) != final_query.size()) throw exceptions::msg() << "influxdb: couldn't commit data to influxdb with address '" << _socket->peerAddress().toString() << "' and port '" << _socket->peerPort() << "': " << _socket->errorString(); _socket->waitForBytesWritten(); _query.clear(); } /** * Connect the socket to the endpoint. */ void influxdb9::_connect_socket() { _socket.reset(new QTcpSocket); _socket->connectToHost(QString::fromStdString(_host), _port); if (!_socket->waitForConnected()) throw exceptions::msg() << "influxdb: couldn't connect to influxdb with address '" << _host << "' and port '" << _port << "': " << _socket->errorString(); } <commit_msg>Influxdb: Use the good endpoint for if9.<commit_after>/* ** Copyright 2011-2014 Merethis ** ** This file is part of Centreon Broker. ** ** Centreon Broker is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Broker is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with Centreon Broker. If not, see ** <http://www.gnu.org/licenses/>. */ #include <sstream> #include <QHostAddress> #include "com/centreon/broker/exceptions/msg.hh" #include "com/centreon/broker/influxdb/influxdb9.hh" #include "com/centreon/broker/logging/logging.hh" #include "com/centreon/broker/influxdb/json_printer.hh" using namespace com::centreon::broker::influxdb; static const char* query_footer = "]}"; /** * Constructor. */ influxdb9::influxdb9( std::string const& user, std::string const& passwd, std::string const& addr, unsigned short port, std::string const& db) : _host(addr), _port(port) { logging::debug(logging::medium) << "influxdb: connecting using 0.9 version protocol"; _connect_socket(); _socket->close(); std::string base_url; base_url .append("/db/").append(db) .append("/write?u=").append(user) .append("&p=").append(passwd); _post_header.append("POST ").append(base_url).append(" HTTP/1.0\n"); json_printer p; p.open_object().add_string("database", db).open_array("points"); _db_header.append(p.get_data()); } /** * Copy constructor. * * @param[in] f Object to copy. */ influxdb9::influxdb9(influxdb9 const& f) { influxdb::operator=(f); } /** * Destructor. */ influxdb9::~influxdb9() {} /** * Assignment operator. * * @param[in] f Object to copy. * * @return This object. */ influxdb9& influxdb9::operator=(influxdb9 const& f) { if (this != &f) { _query = f._query; } return (*this); } /** * Clear the query. */ void influxdb9::clear() { _query.clear(); } /** * Write a metric to the query. * * @param[in] m The metric to write. */ void influxdb9::write(storage::metric const& m) { json_printer p; p.open_object() .add_string("name", m.name.toStdString()) .open_object("tags") .add_string("metric_id", m.metric_id) .close_object() .add_number("timestamp", m.ctime) .open_object("fields") .add_number("value", m.value) .close_object() .close_object(); _query.append(p.get_data()); } /** * Commit a query. */ void influxdb9::commit() { if (_query.empty()) return ; // Remove trailing coma. _query[_query.size() - 1] = ' '; std::stringstream content_length; size_t length = _query.size() + _db_header.size() + ::strlen(query_footer); content_length << "Content-Length: " << length << "\n"; std::string final_query; final_query.reserve(length + _post_header.size() + content_length.str().size() + 1); final_query .append(_post_header).append(content_length.str()).append("\n") .append(_db_header).append(_query).append(query_footer); _connect_socket(); if (_socket->write(final_query.c_str(), final_query.size()) != final_query.size()) throw exceptions::msg() << "influxdb: couldn't commit data to influxdb with address '" << _socket->peerAddress().toString() << "' and port '" << _socket->peerPort() << "': " << _socket->errorString(); _socket->waitForBytesWritten(); _query.clear(); } /** * Connect the socket to the endpoint. */ void influxdb9::_connect_socket() { _socket.reset(new QTcpSocket); _socket->connectToHost(QString::fromStdString(_host), _port); if (!_socket->waitForConnected()) throw exceptions::msg() << "influxdb: couldn't connect to influxdb with address '" << _host << "' and port '" << _port << "': " << _socket->errorString(); } <|endoftext|>
<commit_before>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdarg.h> #include <stdio.h> #include "tensorflow/c/c_api.h" #include "tensorflow/java/src/main/native/exception_jni.h" const char kIllegalArgumentException[] = "java/lang/IllegalArgumentException"; const char kIllegalStateException[] = "java/lang/IllegalStateException"; const char kNullPointerException[] = "java/lang/NullPointerException"; const char kIndexOutOfBoundsException[] = "java/lang/IndexOutOfBoundsException"; const char kUnsupportedOperationException[] = "java/lang/UnsupportedOperationException"; void throwException(JNIEnv* env, const char* clazz, const char* fmt, ...) { va_list args; va_start(args, fmt); char* message = nullptr; if (vasprintf(&message, fmt, args) >= 0) { env->ThrowNew(env->FindClass(clazz), message); } else { env->ThrowNew(env->FindClass(clazz), ""); } va_end(args); } namespace { // Map TF_Codes to unchecked exceptions. const char* exceptionClassName(TF_Code code) { switch (code) { case TF_OK: return nullptr; case TF_INVALID_ARGUMENT: return kIllegalArgumentException; case TF_UNAUTHENTICATED: case TF_PERMISSION_DENIED: return "java/lang/SecurityException"; case TF_RESOURCE_EXHAUSTED: case TF_FAILED_PRECONDITION: return kIllegalStateException; case TF_OUT_OF_RANGE: return kIndexOutOfBoundsException; case TF_UNIMPLEMENTED: return kUnsupportedOperationException; default: return "org/tensorflow/TensorFlowException"; } } } // namespace bool throwExceptionIfNotOK(JNIEnv* env, const TF_Status* status) { const char* clazz = exceptionClassName(TF_GetCode(status)); if (clazz == nullptr) return true; env->ThrowNew(env->FindClass(clazz), TF_Message(status)); return false; } <commit_msg>fix merge conflicts<commit_after>/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include "tensorflow/c/c_api.h" #include "tensorflow/java/src/main/native/exception_jni.h" const char kIllegalArgumentException[] = "java/lang/IllegalArgumentException"; const char kIllegalStateException[] = "java/lang/IllegalStateException"; const char kNullPointerException[] = "java/lang/NullPointerException"; const char kIndexOutOfBoundsException[] = "java/lang/IndexOutOfBoundsException"; const char kUnsupportedOperationException[] = "java/lang/UnsupportedOperationException"; void throwException(JNIEnv* env, const char* clazz, const char* fmt, ...) { va_list args; va_start(args, fmt); // Using vsnprintf() instead of vasprintf() because the latter doesn't seem to // be easily available on Windows. const size_t max_msg_len = 512; char* message = static_cast<char*>(malloc(max_msg_len)); if (vsnprintf(message, max_msg_len, fmt, args) >= 0) { env->ThrowNew(env->FindClass(clazz), message); } else { env->ThrowNew(env->FindClass(clazz), ""); } free(message); va_end(args); } namespace { // Map TF_Codes to unchecked exceptions. const char* exceptionClassName(TF_Code code) { switch (code) { case TF_OK: return nullptr; case TF_INVALID_ARGUMENT: return kIllegalArgumentException; case TF_UNAUTHENTICATED: case TF_PERMISSION_DENIED: return "java/lang/SecurityException"; case TF_RESOURCE_EXHAUSTED: case TF_FAILED_PRECONDITION: return kIllegalStateException; case TF_OUT_OF_RANGE: return kIndexOutOfBoundsException; case TF_UNIMPLEMENTED: return kUnsupportedOperationException; default: return "org/tensorflow/TensorFlowException"; } } } // namespace bool throwExceptionIfNotOK(JNIEnv* env, const TF_Status* status) { const char* clazz = exceptionClassName(TF_GetCode(status)); if (clazz == nullptr) return true; env->ThrowNew(env->FindClass(clazz), TF_Message(status)); return false; } <|endoftext|>
<commit_before>/* * Copyright (C) 2016, Isaac Woods. All rights reserved. */ #include <cstdio> #include <cstdlib> #include <cstdint> #include <common.hpp> struct elf_header { uint16_t fileType; uint64_t entryPoint; uint64_t programHeaderOffset; uint64_t sectionHeaderOffset; uint16_t numProgramHeaderEntries; uint16_t numSectionHeaderEntries; uint16_t sectionNameIndexInSectionHeader; }; static void GenerateHeader(FILE* f, elf_header& header) { // --- Generate ELF Header --- /*0x00*/fputc(0x7F , f); // Emit the 4 byte magic value fputc('E' , f); fputc('L' , f); fputc('F' , f); /*0x04*/fputc(2 , f); // Specify we are targetting a 64-bit system /*0x05*/fputc(1 , f); // Specify we are targetting a little-endian system /*0x06*/fputc(1 , f); // Specify that we are targetting the first version of ELF /*0x07*/fputc(0x00 , f); // Specify that we are targetting the System-V ABI /*0x08*/for (unsigned int i = 0x08; i < 0x10; i++) { fputc(0x00 , f); // Pad out EI_ABIVERSION and EI_PAD } /*0x10*/fwrite(&(header.fileType), sizeof(uint16_t), 1, f); /*0x12*/fputc(0x3E , f); // Specify we are targetting the x86_64 ISA fputc(0x00 , f); /*0x14*/fputc(0x01 , f); // Specify we are targetting the first version of ELF fputc(0x00 , f); fputc(0x00 , f); fputc(0x00 , f); /*0x18*/fwrite(&(header.entryPoint), sizeof(uint64_t), 1, f); /*0x20*/fwrite(&(header.programHeaderOffset), sizeof(uint64_t), 1, f); /*0x28*/fwrite(&(header.sectionHeaderOffset), sizeof(uint64_t), 1, f); /*0x30*/fputc(0x00 , f); // Specify some flags (undefined for x86_64) fputc(0x00 , f); fputc(0x00 , f); fputc(0x00 , f); /*0x34*/fputc(64u , f); // Specify the size of the header (64 bytes) fputc(0x00 , f); /*0x36*/fputc(0x10 , f); // Specify the size of an entry in the program header TODO fputc(0x00 , f); /*0x38*/fwrite(&(header.numProgramHeaderEntries), sizeof(uint16_t), 1, f); /*0x3A*/fputc(0x10 , f); // Specify the size of an entry in the section header TODO fputc(0x00 , f); /*0x3C*/fwrite(&(header.numSectionHeaderEntries), sizeof(uint16_t), 1, f); /*0x3E*/fwrite(&(header.sectionNameIndexInSectionHeader), sizeof(uint16_t), 1, f); // --- Generate Program Header --- // TODO // --- Generate Section Header // TODO } void Generate(const char* outputPath, codegen_target& target, parse_result& result) { FILE* file = fopen(outputPath, "wb"); elf_header header; header.fileType = 0x02; // NOTE(Isaac): executable file header.entryPoint = 0x63; // random header.programHeaderOffset = 0x40; // NOTE(Isaac): right after the header header.sectionHeaderOffset = 0x60; // random header.numProgramHeaderEntries = 0x0; // TODO header.numSectionHeaderEntries = 0x4; // TODO header.sectionNameIndexInSectionHeader = 0x0; // TODO GenerateHeader(file, header); fclose(file); } <commit_msg>Emit ELF program headers<commit_after>/* * Copyright (C) 2016, Isaac Woods. All rights reserved. */ #include <cstdio> #include <cstdlib> #include <cstdint> #include <common.hpp> struct elf_header { uint16_t fileType; uint64_t entryPoint; uint64_t programHeaderOffset; uint64_t sectionHeaderOffset; uint16_t numProgramHeaderEntries; uint16_t numSectionHeaderEntries; uint16_t sectionNameIndexInSectionHeader; }; #define SEGMENT_ATTRIB_X 0x1 // NOTE(Isaac): marks the segment as executable #define SEGMENT_ATTRIB_W 0x2 // NOTE(Isaac): marks the segment as writable #define SEGMENT_ATTRIB_R 0x4 // NOTE(Isaac): marks the segment as readable #define SEGMENT_ATTRIB_MASKOS 0x00FF0000 // NOTE(Isaac): environment-specific (nobody really knows :P) #define SEGMENT_ATTRIB_MASKPROC 0xFF000000 // NOTE(Isaac): processor-specific (even fewer people know) struct elf_segment { enum segment_type : uint32_t { PT_NULL = 0u, PT_LOAD = 1u, PT_DYNAMIC = 2u, PT_INTERP = 3u, PT_NOTE = 4u, PT_SHLIB = 5u, PT_PHDR = 6u, PT_TLS = 7u, PT_LOOS = 0x60000000, PT_HIOS = 0x6FFFFFFF, PT_LOPROC = 0x70000000, PT_HIPROC = 0x7FFFFFFF } type; uint32_t flags; uint64_t offset; // Offset of the first byte of the segment from the image uint64_t virtualAddress; uint64_t physicalAddress; uint64_t fileSize; // Number of bytes in the file image of the segment (may be zero) uint64_t memorySize; // Number of bytes in the memory image of the segment (may be zero) uint16_t alignment; // NOTE(Isaac): `virtualAddress` should equal `offset`, modulo this `alignment` }; static void GenerateHeader(FILE* f, elf_header& header) { const uint16_t programHeaderEntrySize = 32u; // TODO umm const uint16_t sectionHeaderEntrySize = 32u; // TODO umm /*0x00*/fputc(0x7F , f); // Emit the 4 byte magic value fputc('E' , f); fputc('L' , f); fputc('F' , f); /*0x04*/fputc(2 , f); // Specify we are targetting a 64-bit system /*0x05*/fputc(1 , f); // Specify we are targetting a little-endian system /*0x06*/fputc(1 , f); // Specify that we are targetting the first version of ELF /*0x07*/fputc(0x00 , f); // Specify that we are targetting the System-V ABI /*0x08*/for (unsigned int i = 0x08; i < 0x10; i++) { fputc(0x00 , f); // Pad out EI_ABIVERSION and EI_PAD } /*0x10*/fwrite(&(header.fileType), sizeof(uint16_t), 1, f); /*0x12*/fputc(0x3E , f); // Specify we are targetting the x86_64 ISA fputc(0x00 , f); /*0x14*/fputc(0x01 , f); // Specify we are targetting the first version of ELF fputc(0x00 , f); fputc(0x00 , f); fputc(0x00 , f); /*0x18*/fwrite(&(header.entryPoint), sizeof(uint64_t), 1, f); /*0x20*/fwrite(&(header.programHeaderOffset), sizeof(uint64_t), 1, f); /*0x28*/fwrite(&(header.sectionHeaderOffset), sizeof(uint64_t), 1, f); /*0x30*/fputc(0x00 , f); // Specify some flags (undefined for x86_64) fputc(0x00 , f); fputc(0x00 , f); fputc(0x00 , f); /*0x34*/fputc(64u , f); // Specify the size of the header (64 bytes) fputc(0x00 , f); /*0x36*/fwrite(&programHeaderEntrySize, sizeof(uint16_t), 1, f); /*0x38*/fwrite(&(header.numProgramHeaderEntries), sizeof(uint16_t), 1, f); /*0x3A*/fputc(0x10 , f); // Specify the size of an entry in the section header TODO fputc(0x00 , f); /*0x3A*/fwrite(&sectionHeaderEntrySize, sizeof(uint16_t), 1, f); /*0x3C*/fwrite(&(header.numSectionHeaderEntries), sizeof(uint16_t), 1, f); /*0x3E*/fwrite(&(header.sectionNameIndexInSectionHeader), sizeof(uint16_t), 1, f); } static void GenerateSegment(FILE* f, elf_segment& segment) { /*0x00*/fwrite(&(segment.type), sizeof(uint32_t), 1, f); /*0x04*/fwrite(&(segment.flags), sizeof(uint32_t), 1, f); /*0x08*/fwrite(&(segment.offset), sizeof(uint64_t), 1, f); /*0x10*/fwrite(&(segment.virtualAddress), sizeof(uint64_t), 1, f); /*0x18*/fwrite(&(segment.physicalAddress), sizeof(uint64_t), 1, f); /*0x20*/fwrite(&(segment.fileSize), sizeof(uint64_t), 1, f); /*0x28*/fwrite(&(segment.memorySize), sizeof(uint64_t), 1, f); /*0x30*/fwrite(&(segment.alignment), sizeof(uint16_t), 1, f); /*0x32*/ } void Generate(const char* outputPath, codegen_target& target, parse_result& result) { FILE* file = fopen(outputPath, "wb"); elf_header header; header.fileType = 0x02; // NOTE(Isaac): executable file header.entryPoint = 0x63; // random header.programHeaderOffset = 0x40; // NOTE(Isaac): right after the header header.sectionHeaderOffset = 0x60; // random header.numProgramHeaderEntries = 0x0; // TODO header.numSectionHeaderEntries = 0x4; // TODO header.sectionNameIndexInSectionHeader = 0x0; // TODO GenerateHeader(file, header); fclose(file); } <|endoftext|>
<commit_before>#include "command_manager.hh" #include "utils.hh" #include "assert.hh" #include "context.hh" #include <algorithm> #include <cstring> #include <sys/types.h> #include <sys/wait.h> namespace Kakoune { void CommandManager::register_command(const std::string& command_name, Command command, unsigned flags, const CommandCompleter& completer) { m_commands[command_name] = CommandDescriptor { command, flags, completer }; } void CommandManager::register_commands(const memoryview<std::string>& command_names, Command command, unsigned flags, const CommandCompleter& completer) { for (auto command_name : command_names) register_command(command_name, command, flags, completer); } static bool is_blank(char c) { return c == ' ' or c == '\t' or c == '\n'; } typedef std::vector<std::pair<size_t, size_t>> TokenList; static TokenList split(const std::string& line) { TokenList result; size_t pos = 0; while (pos < line.length()) { while(is_blank(line[pos]) and pos != line.length()) ++pos; size_t token_start = pos; if (line[pos] == '"' or line[pos] == '\'' or line[pos] == '`') { char delimiter = line[pos]; ++pos; token_start = delimiter == '`' ? pos - 1 : pos; while ((line[pos] != delimiter or line[pos-1] == '\\') and pos != line.length()) ++pos; if (delimiter == '`' and line[pos] == '`') ++pos; } else while (not is_blank(line[pos]) and pos != line.length() and (line[pos] != ';' or line[pos-1] == '\\')) ++pos; if (token_start != pos) result.push_back(std::make_pair(token_start, pos)); if (line[pos] == ';') result.push_back(std::make_pair(pos, pos+1)); ++pos; } return result; } struct command_not_found : runtime_error { command_not_found(const std::string& command) : runtime_error(command + " : no such command") {} }; void CommandManager::execute(const std::string& command_line, const Context& context) { TokenList tokens = split(command_line); if (tokens.empty()) return; std::vector<std::string> params; for (auto it = tokens.begin(); it != tokens.end(); ++it) { params.push_back(command_line.substr(it->first, it->second - it->first)); } execute(params, context); } static void shell_eval(std::vector<std::string>& params, const std::string& cmdline, const Context& context) { int write_pipe[2]; int read_pipe[2]; pipe(write_pipe); pipe(read_pipe); if (pid_t pid = fork()) { close(write_pipe[0]); close(read_pipe[1]); close(write_pipe[1]); std::string output; char buffer[1024]; while (size_t size = read(read_pipe[0], buffer, 1024)) output += std::string(buffer, buffer+size); close(read_pipe[0]); waitpid(pid, NULL, 0); TokenList tokens = split(output); for (auto it = tokens.begin(); it != tokens.end(); ++it) { params.push_back(output.substr(it->first, it->second - it->first)); } } else { close(write_pipe[1]); close(read_pipe[0]); dup2(read_pipe[1], 1); dup2(write_pipe[0], 0); setenv("kak_bufname", context.buffer().name().c_str(), 1); execlp("sh", "sh", "-c", cmdline.c_str(), NULL); } } void CommandManager::execute(const CommandParameters& params, const Context& context) { if (params.empty()) return; auto begin = params.begin(); auto end = begin; while (true) { while (end != params.end() and *end != ";") ++end; if (end != begin) { std::vector<std::string> expanded_params; auto command_it = m_commands.find(*begin); if (command_it == m_commands.end() and begin->front() == '`' and begin->back() == '`') { shell_eval(expanded_params, begin->substr(1, begin->length() - 2), context); if (not expanded_params.empty()) { command_it = m_commands.find(expanded_params[0]); expanded_params.erase(expanded_params.begin()); } } if (command_it == m_commands.end()) throw command_not_found(*begin); if (command_it->second.flags & IgnoreSemiColons) end = params.end(); if (command_it->second.flags & DeferredShellEval) command_it->second.command(CommandParameters(begin + 1, end), context); else { for (auto param = begin+1; param != end; ++param) { if (param->front() == '`' and param->back() == '`') shell_eval(expanded_params, param->substr(1, param->length() - 2), context); else expanded_params.push_back(*param); } command_it->second.command(expanded_params, context); } } if (end == params.end()) break; begin = end+1; end = begin; } } Completions CommandManager::complete(const std::string& command_line, size_t cursor_pos) { TokenList tokens = split(command_line); size_t token_to_complete = tokens.size(); for (size_t i = 0; i < tokens.size(); ++i) { if (tokens[i].first <= cursor_pos and tokens[i].second >= cursor_pos) { token_to_complete = i; break; } } if (token_to_complete == 0 or tokens.empty()) // command name completion { size_t cmd_start = tokens.empty() ? 0 : tokens[0].first; Completions result(cmd_start, cursor_pos); std::string prefix = command_line.substr(cmd_start, cursor_pos - cmd_start); for (auto& command : m_commands) { if (command.first.substr(0, prefix.length()) == prefix) result.candidates.push_back(command.first); } return result; } assert(not tokens.empty()); std::string command_name = command_line.substr(tokens[0].first, tokens[0].second - tokens[0].first); auto command_it = m_commands.find(command_name); if (command_it == m_commands.end() or not command_it->second.completer) return Completions(); std::vector<std::string> params; for (auto it = tokens.begin() + 1; it != tokens.end(); ++it) { params.push_back(command_line.substr(it->first, it->second - it->first)); } size_t start = token_to_complete < tokens.size() ? tokens[token_to_complete].first : cursor_pos; Completions result(start , cursor_pos); size_t cursor_pos_in_token = cursor_pos - start; result.candidates = command_it->second.completer(params, token_to_complete - 1, cursor_pos_in_token); return result; } CandidateList PerArgumentCommandCompleter::operator()(const CommandParameters& params, size_t token_to_complete, size_t pos_in_token) const { if (token_to_complete >= m_completers.size()) return CandidateList(); // it is possible to try to complete a new argument assert(token_to_complete <= params.size()); const std::string& argument = token_to_complete < params.size() ? params[token_to_complete] : std::string(); return m_completers[token_to_complete](argument, pos_in_token); } } <commit_msg>fix shell_eval when no buffer in context<commit_after>#include "command_manager.hh" #include "utils.hh" #include "assert.hh" #include "context.hh" #include <algorithm> #include <cstring> #include <sys/types.h> #include <sys/wait.h> namespace Kakoune { void CommandManager::register_command(const std::string& command_name, Command command, unsigned flags, const CommandCompleter& completer) { m_commands[command_name] = CommandDescriptor { command, flags, completer }; } void CommandManager::register_commands(const memoryview<std::string>& command_names, Command command, unsigned flags, const CommandCompleter& completer) { for (auto command_name : command_names) register_command(command_name, command, flags, completer); } static bool is_blank(char c) { return c == ' ' or c == '\t' or c == '\n'; } typedef std::vector<std::pair<size_t, size_t>> TokenList; static TokenList split(const std::string& line) { TokenList result; size_t pos = 0; while (pos < line.length()) { while(is_blank(line[pos]) and pos != line.length()) ++pos; size_t token_start = pos; if (line[pos] == '"' or line[pos] == '\'' or line[pos] == '`') { char delimiter = line[pos]; ++pos; token_start = delimiter == '`' ? pos - 1 : pos; while ((line[pos] != delimiter or line[pos-1] == '\\') and pos != line.length()) ++pos; if (delimiter == '`' and line[pos] == '`') ++pos; } else while (not is_blank(line[pos]) and pos != line.length() and (line[pos] != ';' or line[pos-1] == '\\')) ++pos; if (token_start != pos) result.push_back(std::make_pair(token_start, pos)); if (line[pos] == ';') result.push_back(std::make_pair(pos, pos+1)); ++pos; } return result; } struct command_not_found : runtime_error { command_not_found(const std::string& command) : runtime_error(command + " : no such command") {} }; void CommandManager::execute(const std::string& command_line, const Context& context) { TokenList tokens = split(command_line); if (tokens.empty()) return; std::vector<std::string> params; for (auto it = tokens.begin(); it != tokens.end(); ++it) { params.push_back(command_line.substr(it->first, it->second - it->first)); } execute(params, context); } static void shell_eval(std::vector<std::string>& params, const std::string& cmdline, const Context& context) { int write_pipe[2]; int read_pipe[2]; pipe(write_pipe); pipe(read_pipe); if (pid_t pid = fork()) { close(write_pipe[0]); close(read_pipe[1]); close(write_pipe[1]); std::string output; char buffer[1024]; while (size_t size = read(read_pipe[0], buffer, 1024)) output += std::string(buffer, buffer+size); close(read_pipe[0]); waitpid(pid, NULL, 0); TokenList tokens = split(output); for (auto it = tokens.begin(); it != tokens.end(); ++it) { params.push_back(output.substr(it->first, it->second - it->first)); } } else { close(write_pipe[1]); close(read_pipe[0]); dup2(read_pipe[1], 1); dup2(write_pipe[0], 0); if (context.has_buffer()) setenv("kak_bufname", context.buffer().name().c_str(), 1); execlp("sh", "sh", "-c", cmdline.c_str(), NULL); } } void CommandManager::execute(const CommandParameters& params, const Context& context) { if (params.empty()) return; auto begin = params.begin(); auto end = begin; while (true) { while (end != params.end() and *end != ";") ++end; if (end != begin) { std::vector<std::string> expanded_params; auto command_it = m_commands.find(*begin); if (command_it == m_commands.end() and begin->front() == '`' and begin->back() == '`') { shell_eval(expanded_params, begin->substr(1, begin->length() - 2), context); if (not expanded_params.empty()) { command_it = m_commands.find(expanded_params[0]); expanded_params.erase(expanded_params.begin()); } } if (command_it == m_commands.end()) throw command_not_found(*begin); if (command_it->second.flags & IgnoreSemiColons) end = params.end(); if (command_it->second.flags & DeferredShellEval) command_it->second.command(CommandParameters(begin + 1, end), context); else { for (auto param = begin+1; param != end; ++param) { if (param->front() == '`' and param->back() == '`') shell_eval(expanded_params, param->substr(1, param->length() - 2), context); else expanded_params.push_back(*param); } command_it->second.command(expanded_params, context); } } if (end == params.end()) break; begin = end+1; end = begin; } } Completions CommandManager::complete(const std::string& command_line, size_t cursor_pos) { TokenList tokens = split(command_line); size_t token_to_complete = tokens.size(); for (size_t i = 0; i < tokens.size(); ++i) { if (tokens[i].first <= cursor_pos and tokens[i].second >= cursor_pos) { token_to_complete = i; break; } } if (token_to_complete == 0 or tokens.empty()) // command name completion { size_t cmd_start = tokens.empty() ? 0 : tokens[0].first; Completions result(cmd_start, cursor_pos); std::string prefix = command_line.substr(cmd_start, cursor_pos - cmd_start); for (auto& command : m_commands) { if (command.first.substr(0, prefix.length()) == prefix) result.candidates.push_back(command.first); } return result; } assert(not tokens.empty()); std::string command_name = command_line.substr(tokens[0].first, tokens[0].second - tokens[0].first); auto command_it = m_commands.find(command_name); if (command_it == m_commands.end() or not command_it->second.completer) return Completions(); std::vector<std::string> params; for (auto it = tokens.begin() + 1; it != tokens.end(); ++it) { params.push_back(command_line.substr(it->first, it->second - it->first)); } size_t start = token_to_complete < tokens.size() ? tokens[token_to_complete].first : cursor_pos; Completions result(start , cursor_pos); size_t cursor_pos_in_token = cursor_pos - start; result.candidates = command_it->second.completer(params, token_to_complete - 1, cursor_pos_in_token); return result; } CandidateList PerArgumentCommandCompleter::operator()(const CommandParameters& params, size_t token_to_complete, size_t pos_in_token) const { if (token_to_complete >= m_completers.size()) return CandidateList(); // it is possible to try to complete a new argument assert(token_to_complete <= params.size()); const std::string& argument = token_to_complete < params.size() ? params[token_to_complete] : std::string(); return m_completers[token_to_complete](argument, pos_in_token); } } <|endoftext|>
<commit_before>// $Id$ // -*-C++-*- // * BeginRiceCopyright ***************************************************** // // Copyright ((c)) 2002, Rice University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * //*************************************************************************** // // File: // DCPIFilterExpr.C // // Purpose: // [The purpose of this file] // // Description: // [The set of functions, macros, etc. defined in the file] // //*************************************************************************** //************************* System Include Files **************************** #include <iostream> //*************************** User Include Files **************************** #include "PCProfileFilter.h" #include "DCPIProfileFilter.h" #include "DCPIProfileMetric.h" //*************************** Forward Declarations *************************** using std::endl; using std::hex; using std::dec; //**************************************************************************** // PredefinedDCPIMetricTable //**************************************************************************** #define TABLE_SZ \ sizeof(PredefinedDCPIMetricTable::table) / sizeof(PredefinedDCPIMetricTable::Entry) PredefinedDCPIMetricTable::Entry PredefinedDCPIMetricTable::table[] = { // ------------------------------------------------------- // Metrics available whenever ProfileMe is used (any PM mode) // ------------------------------------------------------- // FIXME: what should we do about unreliable data and early_kill? // NOTE: it seems we can cross check with the retire counter // for mode 0 or mode 2... {"retired_insn", "Retired Instructions (includes mispredicted branches)", PM0 | PM1 | PM2 | PM3, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_count | DCPI_PM_ATTR_retired_T), InsnClassExpr(INSN_CLASS_ALL) }, {"retired_fp_insn", "Retired FP Instructions (includes mispredicted branches)", PM0 | PM1 | PM2 | PM3, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_count | DCPI_PM_ATTR_retired_T), InsnClassExpr(INSN_CLASS_FLOP) }, {"mispredicted_branches", "Mispredicted branches", PM0 | PM1 | PM2 | PM3, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_count | DCPI_PM_ATTR_cbrmispredict_T), InsnClassExpr(INSN_CLASS_ALL) /* bit is only true for branches */ }, {"replay_ldst", "Replays caused by load/store ordering. [Untested]", PM0 | PM1 | PM2 | PM3, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_count | DCPI_PM_ATTR_ldstorder_T), InsnClassExpr(INSN_CLASS_ALL) }, {"trapped_insn", "Instructions causing traps", PM0 | PM1 | PM2 | PM3, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_count | DCPI_PM_TRAP_trap), InsnClassExpr(INSN_CLASS_ALL) }, #if 0 // "icache_miss_lb", "Lower bound on icache misses" // count + nyp , any insn #endif // ------------------------------------------------------- // Metrics available for a specific ProfileMe mode // ------------------------------------------------------- // m0: inflight, retires // m1: inflight, retdelay // m2: retires, bcmisses // m3: inflight, replays // FIXME: these are just the raw counters; how best to combine them? {"pm_inflight", "Inflight cycles (excludes fetch stage) for instructions that retired without trapping.", PM0 | PM1 | PM3, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_inflight), InsnClassExpr(INSN_CLASS_ALL) }, {"pm_retdelay", "Delays before retire (excludes all cycles prior to fetch).", PM1, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_retdelay), InsnClassExpr(INSN_CLASS_ALL) }, {"pm_retires", "Instruction retires.", PM0 | PM2, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_retires), InsnClassExpr(INSN_CLASS_ALL) }, {"pm_bcmisses", "B-cache (L2) cache misses.", PM2, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_bcmisses), InsnClassExpr(INSN_CLASS_ALL) }, {"pm_replays", "Memory system replay traps.", PM3, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_replays), InsnClassExpr(INSN_CLASS_ALL) }, #if 0 // "m0inflight" "Number of cycles instruction was Inflight // "m0retires" Instruction retires --> cross check retired instructions? // "m1inflight" Inflight cycles // "m1retdelay" Delays Retire delay (excludes all cycles prior to fetch)--> // "m2retires" Instruction retires --> cross check retired instructions? // "m2bcmisses" B-cache misses --> b-cache misses // "m3inflight" Inflight cycles // "m3replays" Pipeline replay traps #endif // ------------------------------------------------------- // Non ProfileMe metrics, possibly available at any time // ------------------------------------------------------- { "cntr_cycles", "Processor cycles", RM, DCPIMetricExpr(DCPI_MTYPE_RM | DCPI_RM_cycles), InsnClassExpr(INSN_CLASS_ALL) }, { "cntr_retires", "Retired instructions", RM, DCPIMetricExpr(DCPI_MTYPE_RM | DCPI_RM_retires), InsnClassExpr(INSN_CLASS_ALL) }, { "cntr_replaytrap", "Mbox replay traps", RM, DCPIMetricExpr(DCPI_MTYPE_RM | DCPI_RM_replaytrap), InsnClassExpr(INSN_CLASS_ALL) }, { "cntr_bmiss", "Bcache misses or long-latency probes", RM, DCPIMetricExpr(DCPI_MTYPE_RM | DCPI_RM_bmiss), InsnClassExpr(INSN_CLASS_ALL) } }; suint PredefinedDCPIMetricTable::size = TABLE_SZ; bool PredefinedDCPIMetricTable::sorted = false; #undef TABLE_SZ //**************************************************************************** PredefinedDCPIMetricTable::Entry* PredefinedDCPIMetricTable::FindEntry(const char* metric) { // FIXME: we should search a quick-sorted table with binary search. // check 'sorted' Entry* found = NULL; for (suint i = 0; i < GetSize(); ++i) { if (strcmp(metric, table[i].name) == 0) { found = &table[i]; } } return found; } PredefinedDCPIMetricTable::Entry* PredefinedDCPIMetricTable::Index(suint i) { if (i >= GetSize()) { return NULL; } return &table[i]; } //**************************************************************************** // //**************************************************************************** PCProfileFilter* GetPredefinedDCPIFilter(const char* metric, LoadModule* lm) { PredefinedDCPIMetricTable::Entry* e = PredefinedDCPIMetricTable::FindEntry(metric); if (!e) { return NULL; } PCProfileFilter* f = new PCProfileFilter(new DCPIMetricFilter(e->mexpr), new InsnFilter(e->iexpr, lm)); f->SetName(e->name); f->SetDescription(e->description); return f; } //**************************************************************************** // DCPIMetricFilter //**************************************************************************** bool DCPIMetricFilter::operator()(const PCProfileMetric* m) { const DCPIProfileMetric* dm = dynamic_cast<const DCPIProfileMetric*>(m); BriefAssertion(dm && "Internal Error: invalid cast!"); const DCPIMetricDesc& mdesc = dm->GetDCPIDesc(); return expr.IsSatisfied(mdesc); } <commit_msg>Ensure that we do not include bad data in derived metrics (exclude early_kills).<commit_after>// $Id$ // -*-C++-*- // * BeginRiceCopyright ***************************************************** // // Copyright ((c)) 2002, Rice University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * //*************************************************************************** // // File: // DCPIFilterExpr.C // // Purpose: // [The purpose of this file] // // Description: // [The set of functions, macros, etc. defined in the file] // //*************************************************************************** //************************* System Include Files **************************** #include <iostream> //*************************** User Include Files **************************** #include "PCProfileFilter.h" #include "DCPIProfileFilter.h" #include "DCPIProfileMetric.h" //*************************** Forward Declarations *************************** using std::endl; using std::hex; using std::dec; //**************************************************************************** // PredefinedDCPIMetricTable //**************************************************************************** #define TABLE_SZ \ sizeof(PredefinedDCPIMetricTable::table) / sizeof(PredefinedDCPIMetricTable::Entry) PredefinedDCPIMetricTable::Entry PredefinedDCPIMetricTable::table[] = { // ------------------------------------------------------- // Metrics available whenever ProfileMe is used (any PM mode) // ------------------------------------------------------- // We generally avoid metrics with early_kill set: When a profiled // instruction is killed early in the pipeline (early_kill is set), // the PC reported by the hardware may be wrong and all counter // values and bits other than valid, early_kill, no_trap, and and // map_stall may be wrong. // FIXME: Can we cross check with the retire counter for mode 0, 2 {"retired_insn", "Retired Instructions (includes mispredicted branches)", PM0 | PM1 | PM2 | PM3, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_count | DCPI_PM_ATTR_retired_T | DCPI_PM_ATTR_early_kill_F), InsnClassExpr(INSN_CLASS_ALL) }, {"retired_fp_insn", "Retired FP Instructions (includes mispredicted branches)", PM0 | PM1 | PM2 | PM3, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_count | DCPI_PM_ATTR_retired_T | DCPI_PM_ATTR_early_kill_F), InsnClassExpr(INSN_CLASS_FLOP) }, {"mispredicted_branches", "Mispredicted branches", PM0 | PM1 | PM2 | PM3, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_count | DCPI_PM_ATTR_cbrmispredict_T | DCPI_PM_ATTR_early_kill_F), InsnClassExpr(INSN_CLASS_ALL) /* bit is only true for branches */ }, {"replay_ldst", "Replays caused by load/store ordering. [Untested]", PM0 | PM1 | PM2 | PM3, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_count | DCPI_PM_ATTR_ldstorder_T | DCPI_PM_ATTR_early_kill_F), InsnClassExpr(INSN_CLASS_ALL) }, {"trapped_insn", "Instructions causing traps", PM0 | PM1 | PM2 | PM3, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_count | DCPI_PM_ATTR_early_kill_F | DCPI_PM_TRAP_trap), InsnClassExpr(INSN_CLASS_ALL) }, #if 0 // "icache_miss_lb", "Lower bound on icache misses" // count + nyp , any insn #endif // ------------------------------------------------------- // Metrics available for a specific ProfileMe mode // ------------------------------------------------------- // m0: inflight, retires // m1: inflight, retdelay // m2: retires, bcmisses // m3: inflight, replays // FIXME: these are just the raw counters; how best to combine them? {"pm_inflight", "Inflight cycles (excludes fetch stage) for instructions that retired without trapping.", PM0 | PM1 | PM3, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_inflight | DCPI_PM_ATTR_early_kill_F), InsnClassExpr(INSN_CLASS_ALL) }, {"pm_retdelay", "Delays before retire (excludes all cycles prior to fetch).", PM1, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_retdelay | DCPI_PM_ATTR_early_kill_F), InsnClassExpr(INSN_CLASS_ALL) }, {"pm_retires", "Instruction retires.", PM0 | PM2, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_retires | DCPI_PM_ATTR_early_kill_F), InsnClassExpr(INSN_CLASS_ALL) }, {"pm_bcmisses", "B-cache (L2) cache misses.", PM2, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_bcmisses | DCPI_PM_ATTR_early_kill_F), InsnClassExpr(INSN_CLASS_ALL) }, {"pm_replays", "Memory system replay traps.", PM3, DCPIMetricExpr(DCPI_MTYPE_PM | DCPI_PM_CNTR_replays | DCPI_PM_ATTR_early_kill_F), InsnClassExpr(INSN_CLASS_ALL) }, #if 0 // "m0inflight" "Number of cycles instruction was Inflight // "m0retires" Instruction retires --> cross check retired instructions? // "m1inflight" Inflight cycles // "m1retdelay" Delays Retire delay (excludes all cycles prior to fetch)--> // "m2retires" Instruction retires --> cross check retired instructions? // "m2bcmisses" B-cache misses --> b-cache misses // "m3inflight" Inflight cycles // "m3replays" Pipeline replay traps #endif // ------------------------------------------------------- // Non ProfileMe metrics, possibly available at any time // ------------------------------------------------------- { "cntr_cycles", "Processor cycles", RM, DCPIMetricExpr(DCPI_MTYPE_RM | DCPI_RM_cycles), InsnClassExpr(INSN_CLASS_ALL) }, { "cntr_retires", "Retired instructions", RM, DCPIMetricExpr(DCPI_MTYPE_RM | DCPI_RM_retires), InsnClassExpr(INSN_CLASS_ALL) }, { "cntr_replaytrap", "Mbox replay traps", RM, DCPIMetricExpr(DCPI_MTYPE_RM | DCPI_RM_replaytrap), InsnClassExpr(INSN_CLASS_ALL) }, { "cntr_bmiss", "Bcache misses or long-latency probes", RM, DCPIMetricExpr(DCPI_MTYPE_RM | DCPI_RM_bmiss), InsnClassExpr(INSN_CLASS_ALL) } }; suint PredefinedDCPIMetricTable::size = TABLE_SZ; bool PredefinedDCPIMetricTable::sorted = false; #undef TABLE_SZ //**************************************************************************** PredefinedDCPIMetricTable::Entry* PredefinedDCPIMetricTable::FindEntry(const char* metric) { // FIXME: we should search a quick-sorted table with binary search. // check 'sorted' Entry* found = NULL; for (suint i = 0; i < GetSize(); ++i) { if (strcmp(metric, table[i].name) == 0) { found = &table[i]; } } return found; } PredefinedDCPIMetricTable::Entry* PredefinedDCPIMetricTable::Index(suint i) { if (i >= GetSize()) { return NULL; } return &table[i]; } //**************************************************************************** // //**************************************************************************** PCProfileFilter* GetPredefinedDCPIFilter(const char* metric, LoadModule* lm) { PredefinedDCPIMetricTable::Entry* e = PredefinedDCPIMetricTable::FindEntry(metric); if (!e) { return NULL; } PCProfileFilter* f = new PCProfileFilter(new DCPIMetricFilter(e->mexpr), new InsnFilter(e->iexpr, lm)); f->SetName(e->name); f->SetDescription(e->description); return f; } //**************************************************************************** // DCPIMetricFilter //**************************************************************************** bool DCPIMetricFilter::operator()(const PCProfileMetric* m) { const DCPIProfileMetric* dm = dynamic_cast<const DCPIProfileMetric*>(m); BriefAssertion(dm && "Internal Error: invalid cast!"); const DCPIMetricDesc& mdesc = dm->GetDCPIDesc(); return expr.IsSatisfied(mdesc); } <|endoftext|>
<commit_before>#include <Hadouken/Http/JsonRpc/TorrentGetFilesMethod.hpp> #include <Hadouken/BitTorrent/FileEntry.hpp> #include <Hadouken/BitTorrent/FileStorage.hpp> #include <Hadouken/BitTorrent/Session.hpp> #include <Hadouken/BitTorrent/TorrentInfo.hpp> #include <Hadouken/BitTorrent/TorrentHandle.hpp> #include <Hadouken/BitTorrent/TorrentSubsystem.hpp> #include <Poco/Util/Application.h> using namespace Hadouken::BitTorrent; using namespace Hadouken::Http::JsonRpc; using namespace Poco::JSON; using namespace Poco::Util; Poco::Dynamic::Var::Ptr TorrentGetFilesMethod::execute(const Array::Ptr& params) { Application& app = Application::instance(); Session& sess = app.getSubsystem<TorrentSubsystem>().getSession(); if (params->size() < 1) { return nullptr; } std::string hash = params->getElement<std::string>(0); TorrentHandle handle = sess.findTorrent(hash); if (!handle.isValid()) { return nullptr; } std::unique_ptr<TorrentInfo> info = handle.getTorrentFile(); Poco::Dynamic::Array result; if (!info) { return new Poco::Dynamic::Var(result); } FileStorage files = info->getFiles(); std::vector<int64_t> progress; handle.getFileProgress(progress); for (int i = 0; i < files.getNumFiles(); i++) { FileEntry entry = files.getEntryAt(i); Poco::DynamicStruct obj; obj["index"] = i; obj["path"] = entry.getPath(); obj["progress"] = progress[i]; obj["size"] = entry.getSize(); result.push_back(obj); } return new Poco::Dynamic::Var(result); } <commit_msg>Return null if no torrent info is found.<commit_after>#include <Hadouken/Http/JsonRpc/TorrentGetFilesMethod.hpp> #include <Hadouken/BitTorrent/FileEntry.hpp> #include <Hadouken/BitTorrent/FileStorage.hpp> #include <Hadouken/BitTorrent/Session.hpp> #include <Hadouken/BitTorrent/TorrentInfo.hpp> #include <Hadouken/BitTorrent/TorrentHandle.hpp> #include <Hadouken/BitTorrent/TorrentSubsystem.hpp> #include <Poco/Util/Application.h> using namespace Hadouken::BitTorrent; using namespace Hadouken::Http::JsonRpc; using namespace Poco::JSON; using namespace Poco::Util; Poco::Dynamic::Var::Ptr TorrentGetFilesMethod::execute(const Array::Ptr& params) { Application& app = Application::instance(); Session& sess = app.getSubsystem<TorrentSubsystem>().getSession(); if (params->size() < 1) { return nullptr; } std::string hash = params->getElement<std::string>(0); TorrentHandle handle = sess.findTorrent(hash); if (!handle.isValid()) { return nullptr; } std::unique_ptr<TorrentInfo> info = handle.getTorrentFile(); Poco::Dynamic::Array result; if (!info) { return nullptr; } FileStorage files = info->getFiles(); std::vector<int64_t> progress; handle.getFileProgress(progress); for (int i = 0; i < files.getNumFiles(); i++) { FileEntry entry = files.getEntryAt(i); Poco::DynamicStruct obj; obj["index"] = i; obj["path"] = entry.getPath(); obj["progress"] = progress[i]; obj["size"] = entry.getSize(); result.push_back(obj); } return new Poco::Dynamic::Var(result); } <|endoftext|>
<commit_before>#pragma once #include <QString> #include <QtGlobal> #define CHATTERINO_VERSION "2.1.6" #if defined(Q_OS_WIN) # define CHATTERINO_OS "win" #elif defined(Q_OS_MACOS) # define CHATTERINO_OS "macos" #elif defined(Q_OS_LINUX) # define CHATTERINO_OS "linux" #else # define CHATTERINO_OS "unknown" #endif namespace chatterino { class Version { public: static const Version &instance(); const QString &version() const; const QString &commitHash() const; const QString &dateOfBuild() const; const QString &fullVersion() const; private: Version(); QString version_; QString commitHash_; QString dateOfBuild_; QString fullVersion_; }; }; // namespace chatterino <commit_msg>2.1.7<commit_after>#pragma once #include <QString> #include <QtGlobal> #define CHATTERINO_VERSION "2.1.7" #if defined(Q_OS_WIN) # define CHATTERINO_OS "win" #elif defined(Q_OS_MACOS) # define CHATTERINO_OS "macos" #elif defined(Q_OS_LINUX) # define CHATTERINO_OS "linux" #else # define CHATTERINO_OS "unknown" #endif namespace chatterino { class Version { public: static const Version &instance(); const QString &version() const; const QString &commitHash() const; const QString &dateOfBuild() const; const QString &fullVersion() const; private: Version(); QString version_; QString commitHash_; QString dateOfBuild_; QString fullVersion_; }; }; // namespace chatterino <|endoftext|>
<commit_before>#include "vlcplugin_win.h" #include "../common/win32_fullscreen.h" static HMODULE hDllModule= 0; HMODULE DllGetModule() { return hDllModule; }; extern "C" BOOL WINAPI DllMain(HANDLE hModule, DWORD fdwReason, LPVOID lpReserved ) { switch( fdwReason ) { case DLL_PROCESS_ATTACH: hDllModule = (HMODULE)hModule; break; default: break; } return TRUE; }; static LRESULT CALLBACK Manage( HWND p_hwnd, UINT i_msg, WPARAM wpar, LPARAM lpar ) { VlcPluginWin *p_plugin = reinterpret_cast<VlcPluginWin *>(GetWindowLongPtr(p_hwnd, GWLP_USERDATA)); switch( i_msg ) { case WM_ERASEBKGND: return 1L; case WM_PAINT: { PAINTSTRUCT paintstruct; HDC hdc; RECT rect; hdc = BeginPaint( p_hwnd, &paintstruct ); GetClientRect( p_hwnd, &rect ); FillRect( hdc, &rect, (HBRUSH)GetStockObject(BLACK_BRUSH) ); SetTextColor(hdc, RGB(255, 255, 255)); SetBkColor(hdc, RGB(0, 0, 0)); if( p_plugin->psz_text ) DrawText( hdc, p_plugin->psz_text, strlen(p_plugin->psz_text), &rect, DT_CENTER|DT_VCENTER|DT_SINGLELINE); EndPaint( p_hwnd, &paintstruct ); return 0L; } case WM_SIZE:{ int new_client_width = LOWORD(lpar); int new_client_height = HIWORD(lpar); //first child will be resized to client area HWND hChildWnd = GetWindow(p_hwnd, GW_CHILD); if(hChildWnd){ MoveWindow(hChildWnd, 0, 0, new_client_width, new_client_height, FALSE); } return 0L; } case WM_LBUTTONDBLCLK:{ p_plugin->toggle_fullscreen(); return 0L; } default: /* delegate to default handler */ return CallWindowProc( p_plugin->getWindowProc(), p_hwnd, i_msg, wpar, lpar ); } } VlcPluginWin::VlcPluginWin(NPP instance, NPuint16_t mode) : VlcPluginBase(instance, mode), pf_wndproc(NULL), _WindowsManager(DllGetModule()) { } VlcPluginWin::~VlcPluginWin() { HWND win = (HWND)getWindow().window; WNDPROC winproc = getWindowProc(); if( winproc ) { /* reset WNDPROC */ SetWindowLongPtr( win, GWLP_WNDPROC, (LONG_PTR)winproc ); } _WindowsManager.DestroyWindows(); } void VlcPluginWin::set_player_window() { _WindowsManager.LibVlcAttach(libvlc_media_player); } void VlcPluginWin::toggle_fullscreen() { _WindowsManager.ToggleFullScreen(); } void VlcPluginWin::set_fullscreen(int yes) { if(yes){ _WindowsManager.StartFullScreen(); } else{ _WindowsManager.EndFullScreen(); } } int VlcPluginWin::get_fullscreen() { return _WindowsManager.IsFullScreen(); } void VlcPluginWin::show_toolbar() { /* TODO */ } void VlcPluginWin::hide_toolbar() { /* TODO */ } void VlcPluginWin::update_controls() { /* TODO */ } bool VlcPluginWin::create_windows() { HWND drawable = (HWND) (getWindow().window); /* attach our plugin object */ SetWindowLongPtr(drawable, GWLP_USERDATA, (LONG_PTR)this); /* install our WNDPROC */ setWindowProc( (WNDPROC)SetWindowLongPtr( drawable, GWLP_WNDPROC, (LONG_PTR)Manage ) ); /* change window style to our liking */ LONG style = GetWindowLong(drawable, GWL_STYLE); style |= WS_CLIPCHILDREN | WS_CLIPSIBLINGS; SetWindowLong(drawable, GWL_STYLE, style); _WindowsManager.CreateWindows(drawable); return true; } bool VlcPluginWin::resize_windows() { /* TODO */ HWND drawable = (HWND) (getWindow().window); /* Redraw window */ InvalidateRect( drawable, NULL, TRUE ); UpdateWindow( drawable ); return true; } bool VlcPluginWin::destroy_windows() { _WindowsManager.DestroyWindows(); /* reset WNDPROC */ HWND oldwin = (HWND)npwindow.window; SetWindowLongPtr( oldwin, GWLP_WNDPROC, (LONG_PTR)(getWindowProc()) ); setWindowProc(NULL); npwindow.window = NULL; return true; } <commit_msg>npapi win32: added prerequisites checks to VlcPluginWin::destroy_windows<commit_after>#include "vlcplugin_win.h" #include "../common/win32_fullscreen.h" static HMODULE hDllModule= 0; HMODULE DllGetModule() { return hDllModule; }; extern "C" BOOL WINAPI DllMain(HANDLE hModule, DWORD fdwReason, LPVOID lpReserved ) { switch( fdwReason ) { case DLL_PROCESS_ATTACH: hDllModule = (HMODULE)hModule; break; default: break; } return TRUE; }; static LRESULT CALLBACK Manage( HWND p_hwnd, UINT i_msg, WPARAM wpar, LPARAM lpar ) { VlcPluginWin *p_plugin = reinterpret_cast<VlcPluginWin *>(GetWindowLongPtr(p_hwnd, GWLP_USERDATA)); switch( i_msg ) { case WM_ERASEBKGND: return 1L; case WM_PAINT: { PAINTSTRUCT paintstruct; HDC hdc; RECT rect; hdc = BeginPaint( p_hwnd, &paintstruct ); GetClientRect( p_hwnd, &rect ); FillRect( hdc, &rect, (HBRUSH)GetStockObject(BLACK_BRUSH) ); SetTextColor(hdc, RGB(255, 255, 255)); SetBkColor(hdc, RGB(0, 0, 0)); if( p_plugin->psz_text ) DrawText( hdc, p_plugin->psz_text, strlen(p_plugin->psz_text), &rect, DT_CENTER|DT_VCENTER|DT_SINGLELINE); EndPaint( p_hwnd, &paintstruct ); return 0L; } case WM_SIZE:{ int new_client_width = LOWORD(lpar); int new_client_height = HIWORD(lpar); //first child will be resized to client area HWND hChildWnd = GetWindow(p_hwnd, GW_CHILD); if(hChildWnd){ MoveWindow(hChildWnd, 0, 0, new_client_width, new_client_height, FALSE); } return 0L; } case WM_LBUTTONDBLCLK:{ p_plugin->toggle_fullscreen(); return 0L; } default: /* delegate to default handler */ return CallWindowProc( p_plugin->getWindowProc(), p_hwnd, i_msg, wpar, lpar ); } } VlcPluginWin::VlcPluginWin(NPP instance, NPuint16_t mode) : VlcPluginBase(instance, mode), pf_wndproc(NULL), _WindowsManager(DllGetModule()) { } VlcPluginWin::~VlcPluginWin() { HWND win = (HWND)getWindow().window; WNDPROC winproc = getWindowProc(); if( winproc ) { /* reset WNDPROC */ SetWindowLongPtr( win, GWLP_WNDPROC, (LONG_PTR)winproc ); } _WindowsManager.DestroyWindows(); } void VlcPluginWin::set_player_window() { _WindowsManager.LibVlcAttach(libvlc_media_player); } void VlcPluginWin::toggle_fullscreen() { _WindowsManager.ToggleFullScreen(); } void VlcPluginWin::set_fullscreen(int yes) { if(yes){ _WindowsManager.StartFullScreen(); } else{ _WindowsManager.EndFullScreen(); } } int VlcPluginWin::get_fullscreen() { return _WindowsManager.IsFullScreen(); } void VlcPluginWin::show_toolbar() { /* TODO */ } void VlcPluginWin::hide_toolbar() { /* TODO */ } void VlcPluginWin::update_controls() { /* TODO */ } bool VlcPluginWin::create_windows() { HWND drawable = (HWND) (getWindow().window); /* attach our plugin object */ SetWindowLongPtr(drawable, GWLP_USERDATA, (LONG_PTR)this); /* install our WNDPROC */ setWindowProc( (WNDPROC)SetWindowLongPtr( drawable, GWLP_WNDPROC, (LONG_PTR)Manage ) ); /* change window style to our liking */ LONG style = GetWindowLong(drawable, GWL_STYLE); style |= WS_CLIPCHILDREN | WS_CLIPSIBLINGS; SetWindowLong(drawable, GWL_STYLE, style); _WindowsManager.CreateWindows(drawable); return true; } bool VlcPluginWin::resize_windows() { /* TODO */ HWND drawable = (HWND) (getWindow().window); /* Redraw window */ InvalidateRect( drawable, NULL, TRUE ); UpdateWindow( drawable ); return true; } bool VlcPluginWin::destroy_windows() { _WindowsManager.DestroyWindows(); HWND oldwin = (HWND)npwindow.window; if(oldwin){ WNDPROC winproc = getWindowProc(); if( winproc ) { /* reset WNDPROC */ SetWindowLongPtr( oldwin, GWLP_WNDPROC, (LONG_PTR)winproc ); setWindowProc(NULL); } npwindow.window = NULL; } return true; } <|endoftext|>
<commit_before>#ifndef SILICIUM_RUN_PROCESS_HPP #define SILICIUM_RUN_PROCESS_HPP #include <silicium/async_process.hpp> #include <silicium/write.hpp> #include <silicium/sink/multi_sink.hpp> #include <boost/range/algorithm/transform.hpp> namespace Si { template <class T> bool extract(T &destination, optional<T> &&source) { if (source) { destination = std::forward<T>(*source); return true; } return false; } } #define SILICIUM_HAS_RUN_PROCESS (SILICIUM_HAS_EXCEPTIONS && SILICIUM_HAS_EXPERIMENTAL_READ_FROM_ANONYMOUS_PIPE && SILICIUM_HAS_LAUNCH_PROCESS) #if SILICIUM_HAS_RUN_PROCESS #include <future> namespace Si { inline int run_process(process_parameters const &parameters) { async_process_parameters async_parameters; async_parameters.executable = parameters.executable; async_parameters.arguments = parameters.arguments; async_parameters.current_path = parameters.current_path; auto input = make_pipe().move_value(); auto std_output = make_pipe().move_value(); auto std_error = make_pipe().move_value(); async_process process = launch_process(async_parameters, input.read.handle, std_output.write.handle, std_error.write.handle, std::vector<std::pair<os_char const *, os_char const *>>(), environment_inheritance::inherit).move_value(); boost::asio::io_service io; auto std_output_consumer = make_multi_sink<char, success>([&parameters]() { return make_iterator_range(&parameters.out, &parameters.out + (parameters.out != nullptr)); }); experimental::read_from_anonymous_pipe(io, std_output_consumer, std::move(std_output.read)); auto std_error_consumer = make_multi_sink<char, success>([&parameters]() { return make_iterator_range(&parameters.err, &parameters.err + (parameters.err != nullptr)); }); experimental::read_from_anonymous_pipe(io, std_error_consumer, std::move(std_error.read)); input.read.close(); std_output.write.close(); std_error.write.close(); auto copy_input = std::async(std::launch::async, [&input, &parameters]() { if (!parameters.in) { return; } for (;;) { optional<char> const c = Si::get(*parameters.in); if (!c) { break; } error_or<size_t> written = write(input.write.handle, make_memory_range(&*c, 1)); if (written.is_error()) { //process must have exited break; } assert(written.get() == 1); } input.write.close(); }); #ifdef _WIN32 auto wait_for_exit_async = std::async(std::launch::async, [&process, &std_output, &std_error]() { int rc = process.wait_for_exit().get(); std_output.read.close(); std_error.read.close(); return rc; }); io.run(); copy_input.get(); return wait_for_exit_async.get(); #else io.run(); copy_input.get(); return process.wait_for_exit().get(); #endif } SILICIUM_USE_RESULT inline int run_process( boost::filesystem::path executable, std::vector<noexcept_string> arguments, boost::filesystem::path current_path, Sink<char, success>::interface &output) { process_parameters parameters; parameters.executable = absolute_path::create(std::move(executable)).or_throw([]{ throw std::invalid_argument("The executable must be an absolute path."); }); boost::range::transform(arguments, std::back_inserter(parameters.arguments), [&parameters](noexcept_string const &argument) { return to_os_string(argument); }); parameters.current_path = absolute_path::create(std::move(current_path)).or_throw([]{ throw std::invalid_argument("The current directory must be an absolute path."); }); parameters.out = &output; parameters.err = &output; return run_process(parameters); } SILICIUM_USE_RESULT inline error_or<int> run_process( absolute_path executable, std::vector<os_string> arguments, absolute_path current_directory, Sink<char, success>::interface &output ) { process_parameters parameters; parameters.executable = std::move(executable); parameters.arguments = std::move(arguments); parameters.current_path = std::move(current_directory); parameters.out = &output; parameters.err = &output; return run_process(parameters); } } #endif #endif <commit_msg>Revert "try to convince async_process to work on Win32 by using another thread"<commit_after>#ifndef SILICIUM_RUN_PROCESS_HPP #define SILICIUM_RUN_PROCESS_HPP #include <silicium/async_process.hpp> #include <silicium/write.hpp> #include <silicium/sink/multi_sink.hpp> #include <boost/range/algorithm/transform.hpp> namespace Si { template <class T> bool extract(T &destination, optional<T> &&source) { if (source) { destination = std::forward<T>(*source); return true; } return false; } } #define SILICIUM_HAS_RUN_PROCESS (SILICIUM_HAS_EXCEPTIONS && SILICIUM_HAS_EXPERIMENTAL_READ_FROM_ANONYMOUS_PIPE && SILICIUM_HAS_LAUNCH_PROCESS) #if SILICIUM_HAS_RUN_PROCESS #include <future> namespace Si { inline int run_process(process_parameters const &parameters) { async_process_parameters async_parameters; async_parameters.executable = parameters.executable; async_parameters.arguments = parameters.arguments; async_parameters.current_path = parameters.current_path; auto input = make_pipe().move_value(); auto std_output = make_pipe().move_value(); auto std_error = make_pipe().move_value(); async_process process = launch_process(async_parameters, input.read.handle, std_output.write.handle, std_error.write.handle, std::vector<std::pair<os_char const *, os_char const *>>(), environment_inheritance::inherit).move_value(); boost::asio::io_service io; auto std_output_consumer = make_multi_sink<char, success>([&parameters]() { return make_iterator_range(&parameters.out, &parameters.out + (parameters.out != nullptr)); }); experimental::read_from_anonymous_pipe(io, std_output_consumer, std::move(std_output.read)); auto std_error_consumer = make_multi_sink<char, success>([&parameters]() { return make_iterator_range(&parameters.err, &parameters.err + (parameters.err != nullptr)); }); experimental::read_from_anonymous_pipe(io, std_error_consumer, std::move(std_error.read)); input.read.close(); std_output.write.close(); std_error.write.close(); auto copy_input = std::async(std::launch::async, [&input, &parameters]() { if (!parameters.in) { return; } for (;;) { optional<char> const c = Si::get(*parameters.in); if (!c) { break; } error_or<size_t> written = write(input.write.handle, make_memory_range(&*c, 1)); if (written.is_error()) { //process must have exited break; } assert(written.get() == 1); } input.write.close(); }); io.run(); copy_input.get(); return process.wait_for_exit().get(); } SILICIUM_USE_RESULT inline int run_process( boost::filesystem::path executable, std::vector<noexcept_string> arguments, boost::filesystem::path current_path, Sink<char, success>::interface &output) { process_parameters parameters; parameters.executable = absolute_path::create(std::move(executable)).or_throw([]{ throw std::invalid_argument("The executable must be an absolute path."); }); boost::range::transform(arguments, std::back_inserter(parameters.arguments), [&parameters](noexcept_string const &argument) { return to_os_string(argument); }); parameters.current_path = absolute_path::create(std::move(current_path)).or_throw([]{ throw std::invalid_argument("The current directory must be an absolute path."); }); parameters.out = &output; parameters.err = &output; return run_process(parameters); } SILICIUM_USE_RESULT inline error_or<int> run_process( absolute_path executable, std::vector<os_string> arguments, absolute_path current_directory, Sink<char, success>::interface &output ) { process_parameters parameters; parameters.executable = std::move(executable); parameters.arguments = std::move(arguments); parameters.current_path = std::move(current_directory); parameters.out = &output; parameters.err = &output; return run_process(parameters); } } #endif #endif <|endoftext|>